MediaWiki  1.27.2
RedisBagOStuff.php
Go to the documentation of this file.
1 <?php
28 class RedisBagOStuff extends BagOStuff {
30  protected $redisPool;
32  protected $servers;
34  protected $serverTagMap;
36  protected $automaticFailover;
37 
66  function __construct( $params ) {
67  parent::__construct( $params );
68  $redisConf = [ 'serializer' => 'none' ]; // manage that in this class
69  foreach ( [ 'connectTimeout', 'persistent', 'password' ] as $opt ) {
70  if ( isset( $params[$opt] ) ) {
71  $redisConf[$opt] = $params[$opt];
72  }
73  }
74  $this->redisPool = RedisConnectionPool::singleton( $redisConf );
75 
76  $this->servers = $params['servers'];
77  foreach ( $this->servers as $key => $server ) {
78  $this->serverTagMap[is_int( $key ) ? $server : $key] = $server;
79  }
80 
81  if ( isset( $params['automaticFailover'] ) ) {
82  $this->automaticFailover = $params['automaticFailover'];
83  } else {
84  $this->automaticFailover = true;
85  }
86  }
87 
88  protected function doGet( $key, $flags = 0 ) {
89  list( $server, $conn ) = $this->getConnection( $key );
90  if ( !$conn ) {
91  return false;
92  }
93  try {
94  $value = $conn->get( $key );
95  $result = $this->unserialize( $value );
96  } catch ( RedisException $e ) {
97  $result = false;
98  $this->handleException( $conn, $e );
99  }
100 
101  $this->logRequest( 'get', $key, $server, $result );
102  return $result;
103  }
104 
105  public function set( $key, $value, $expiry = 0, $flags = 0 ) {
106  list( $server, $conn ) = $this->getConnection( $key );
107  if ( !$conn ) {
108  return false;
109  }
110  $expiry = $this->convertToRelative( $expiry );
111  try {
112  if ( $expiry ) {
113  $result = $conn->setex( $key, $expiry, $this->serialize( $value ) );
114  } else {
115  // No expiry, that is very different from zero expiry in Redis
116  $result = $conn->set( $key, $this->serialize( $value ) );
117  }
118  } catch ( RedisException $e ) {
119  $result = false;
120  $this->handleException( $conn, $e );
121  }
122 
123  $this->logRequest( 'set', $key, $server, $result );
124  return $result;
125  }
126 
127  public function delete( $key ) {
128  list( $server, $conn ) = $this->getConnection( $key );
129  if ( !$conn ) {
130  return false;
131  }
132  try {
133  $conn->delete( $key );
134  // Return true even if the key didn't exist
135  $result = true;
136  } catch ( RedisException $e ) {
137  $result = false;
138  $this->handleException( $conn, $e );
139  }
140 
141  $this->logRequest( 'delete', $key, $server, $result );
142  return $result;
143  }
144 
145  public function getMulti( array $keys, $flags = 0 ) {
146  $batches = [];
147  $conns = [];
148  foreach ( $keys as $key ) {
149  list( $server, $conn ) = $this->getConnection( $key );
150  if ( !$conn ) {
151  continue;
152  }
153  $conns[$server] = $conn;
154  $batches[$server][] = $key;
155  }
156  $result = [];
157  foreach ( $batches as $server => $batchKeys ) {
158  $conn = $conns[$server];
159  try {
160  $conn->multi( Redis::PIPELINE );
161  foreach ( $batchKeys as $key ) {
162  $conn->get( $key );
163  }
164  $batchResult = $conn->exec();
165  if ( $batchResult === false ) {
166  $this->debug( "multi request to $server failed" );
167  continue;
168  }
169  foreach ( $batchResult as $i => $value ) {
170  if ( $value !== false ) {
171  $result[$batchKeys[$i]] = $this->unserialize( $value );
172  }
173  }
174  } catch ( RedisException $e ) {
175  $this->handleException( $conn, $e );
176  }
177  }
178 
179  $this->debug( "getMulti for " . count( $keys ) . " keys " .
180  "returned " . count( $result ) . " results" );
181  return $result;
182  }
183 
189  public function setMulti( array $data, $expiry = 0 ) {
190  $batches = [];
191  $conns = [];
192  foreach ( $data as $key => $value ) {
193  list( $server, $conn ) = $this->getConnection( $key );
194  if ( !$conn ) {
195  continue;
196  }
197  $conns[$server] = $conn;
198  $batches[$server][] = $key;
199  }
200 
201  $expiry = $this->convertToRelative( $expiry );
202  $result = true;
203  foreach ( $batches as $server => $batchKeys ) {
204  $conn = $conns[$server];
205  try {
206  $conn->multi( Redis::PIPELINE );
207  foreach ( $batchKeys as $key ) {
208  if ( $expiry ) {
209  $conn->setex( $key, $expiry, $this->serialize( $data[$key] ) );
210  } else {
211  $conn->set( $key, $this->serialize( $data[$key] ) );
212  }
213  }
214  $batchResult = $conn->exec();
215  if ( $batchResult === false ) {
216  $this->debug( "setMulti request to $server failed" );
217  continue;
218  }
219  foreach ( $batchResult as $value ) {
220  if ( $value === false ) {
221  $result = false;
222  }
223  }
224  } catch ( RedisException $e ) {
225  $this->handleException( $server, $conn, $e );
226  $result = false;
227  }
228  }
229 
230  return $result;
231  }
232 
233  public function add( $key, $value, $expiry = 0 ) {
234  list( $server, $conn ) = $this->getConnection( $key );
235  if ( !$conn ) {
236  return false;
237  }
238  $expiry = $this->convertToRelative( $expiry );
239  try {
240  if ( $expiry ) {
241  $result = $conn->set(
242  $key,
243  $this->serialize( $value ),
244  [ 'nx', 'ex' => $expiry ]
245  );
246  } else {
247  $result = $conn->setnx( $key, $this->serialize( $value ) );
248  }
249  } catch ( RedisException $e ) {
250  $result = false;
251  $this->handleException( $conn, $e );
252  }
253 
254  $this->logRequest( 'add', $key, $server, $result );
255  return $result;
256  }
257 
270  public function incr( $key, $value = 1 ) {
271  list( $server, $conn ) = $this->getConnection( $key );
272  if ( !$conn ) {
273  return false;
274  }
275  if ( !$conn->exists( $key ) ) {
276  return null;
277  }
278  try {
279  // @FIXME: on races, the key may have a 0 TTL
280  $result = $conn->incrBy( $key, $value );
281  } catch ( RedisException $e ) {
282  $result = false;
283  $this->handleException( $conn, $e );
284  }
285 
286  $this->logRequest( 'incr', $key, $server, $result );
287  return $result;
288  }
289 
290  public function modifySimpleRelayEvent( array $event ) {
291  if ( array_key_exists( 'val', $event ) ) {
292  $event['val'] = serialize( $event['val'] ); // this class uses PHP serialization
293  }
294 
295  return $event;
296  }
297 
302  protected function serialize( $data ) {
303  // Serialize anything but integers so INCR/DECR work
304  // Do not store integer-like strings as integers to avoid type confusion (bug 60563)
305  return is_int( $data ) ? $data : serialize( $data );
306  }
307 
312  protected function unserialize( $data ) {
313  return ctype_digit( $data ) ? intval( $data ) : unserialize( $data );
314  }
315 
321  protected function getConnection( $key ) {
322  $candidates = array_keys( $this->serverTagMap );
323 
324  if ( count( $this->servers ) > 1 ) {
325  ArrayUtils::consistentHashSort( $candidates, $key, '/' );
326  if ( !$this->automaticFailover ) {
327  $candidates = array_slice( $candidates, 0, 1 );
328  }
329  }
330 
331  while ( ( $tag = array_shift( $candidates ) ) !== null ) {
332  $server = $this->serverTagMap[$tag];
333  $conn = $this->redisPool->getConnection( $server );
334  if ( !$conn ) {
335  continue;
336  }
337 
338  // If automatic failover is enabled, check that the server's link
339  // to its master (if any) is up -- but only if there are other
340  // viable candidates left to consider. Also, getMasterLinkStatus()
341  // does not work with twemproxy, though $candidates will be empty
342  // by now in such cases.
343  if ( $this->automaticFailover && $candidates ) {
344  try {
345  if ( $this->getMasterLinkStatus( $conn ) === 'down' ) {
346  // If the master cannot be reached, fail-over to the next server.
347  // If masters are in data-center A, and slaves in data-center B,
348  // this helps avoid the case were fail-over happens in A but not
349  // to the corresponding server in B (e.g. read/write mismatch).
350  continue;
351  }
352  } catch ( RedisException $e ) {
353  // Server is not accepting commands
354  $this->handleException( $conn, $e );
355  continue;
356  }
357  }
358 
359  return [ $server, $conn ];
360  }
361 
363 
364  return [ false, false ];
365  }
366 
373  protected function getMasterLinkStatus( RedisConnRef $conn ) {
374  $info = $conn->info();
375  return isset( $info['master_link_status'] )
376  ? $info['master_link_status']
377  : null;
378  }
379 
384  protected function logError( $msg ) {
385  $this->logger->error( "Redis error: $msg" );
386  }
387 
396  protected function handleException( RedisConnRef $conn, $e ) {
398  $this->redisPool->handleError( $conn, $e );
399  }
400 
408  public function logRequest( $method, $key, $server, $result ) {
409  $this->debug( "$method $key on $server: " .
410  ( $result === false ? "failure" : "success" ) );
411  }
412 }
const ERR_UNEXPECTED
Definition: BagOStuff.php:77
static consistentHashSort(&$array, $key, $separator="\000")
Sort the given array in a pseudo-random order which depends only on the given key and each element va...
Definition: ArrayUtils.php:49
modifySimpleRelayEvent(array $event)
array $serverTagMap
Map of (tag => server name)
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
the array() calling protocol came about after MediaWiki 1.4rc1.
magic word the default is to use $key to get the and $key value or $key value text $key value html to format the value $key
Definition: hooks.txt:2321
getMulti(array $keys, $flags=0)
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1932
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
logError($msg)
Log a fatal error.
$value
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2548
const ERR_UNREACHABLE
Definition: BagOStuff.php:76
getConnection($key)
Get a Redis object with a connection suitable for fetching the specified key.
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message.Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item.Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page.Return false to stop further processing of the tag $reader:XMLReader object &$pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision.Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag.Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload.Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports.&$fullInterwikiPrefix:Interwiki prefix, may contain colons.&$pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable.Can be used to lazy-load the import sources list.&$importSources:The value of $wgImportSources.Modify as necessary.See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page.$context:IContextSource object &$pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect.&$title:Title object for the current page &$request:WebRequest &$ignoreRedirect:boolean to skip redirect check &$target:Title/string of redirect target &$article:Article object 'InternalParseBeforeLinks':during Parser's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InternalParseBeforeSanitize':during Parser's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings.Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not.Return true without providing an interwiki to continue interwiki search.$prefix:interwiki prefix we are looking for.&$iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user's email has been invalidated successfully.$user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification.Callee may modify $url and $query, URL will be constructed as $url.$query &$url:URL to index.php &$query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) &$article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() &$ip:IP being check &$result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from &$allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn't match your organization.$addr:The e-mail address entered by the user &$result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user &$result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we're looking for a messages file for &$file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED!Use $magicWords in a file listed in $wgExtensionMessagesFiles instead.Use this to define synonyms of magic words depending of the language &$magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces.Do not use this hook to add namespaces.Use CanonicalNamespaces for that.&$namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED!Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead.Use to define aliases of special pages names depending of the language &$specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names.&$names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page's language links.This is called in various places to allow extensions to define the effective language links for a page.$title:The page's Title.&$links:Associative array mapping language codes to prefixed links of the form"language:title".&$linkFlags:Associative array mapping prefixed links to arrays of flags.Currently unused, but planned to provide support for marking individual language links in the UI, e.g.for featured articles. 'LanguageSelector':Hook to change the language selector available on a page.$out:The output page.$cssClassName:CSS class name of the language selector. 'LinkBegin':Used when generating internal and interwiki links in Linker::link(), before processing starts.Return false to skip default processing and return $ret.See documentation for Linker::link() for details on the expected meanings of parameters.$skin:the Skin object $target:the Title that the link is pointing to &$html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1796
static singleton(array $options)
setMulti(array $data, $expiry=0)
array $servers
List of server names.
incr($key, $value=1)
Non-atomic implementation of incr().
$params
add($key, $value, $expiry=0)
RedisConnectionPool $redisPool
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books $tag
Definition: hooks.txt:965
Redis-based caching module for redis server >= 2.6.12.
handleException(RedisConnRef $conn, $e)
The redis extension throws an exception in response to various read, write and protocol errors...
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
getMasterLinkStatus(RedisConnRef $conn)
Check the master link status of a Redis server that is configured as a slave.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
__construct($params)
Construct a RedisBagOStuff object.
doGet($key, $flags=0)
convertToRelative($exptime)
Convert an optionally absolute expiry time to a relative time.
Definition: BagOStuff.php:671
logRequest($method, $key, $server, $result)
Send information about a single request to the debug log.
Helper class to handle automatically marking connectons as reusable (via RAII pattern) ...
storage can be distributed across multiple servers
Definition: memcached.txt:33
debug($text)
Definition: BagOStuff.php:643
setLastError($err)
Set the "last error" registry.
Definition: BagOStuff.php:618
set($key, $value, $expiry=0, $flags=0)