MediaWiki  REL1_31
RedisBagOStuff.php
Go to the documentation of this file.
1 <?php
32 class RedisBagOStuff extends BagOStuff {
34  protected $redisPool;
36  protected $servers;
38  protected $serverTagMap;
40  protected $automaticFailover;
41 
70  function __construct( $params ) {
71  parent::__construct( $params );
72  $redisConf = [ 'serializer' => 'none' ]; // manage that in this class
73  foreach ( [ 'connectTimeout', 'persistent', 'password' ] as $opt ) {
74  if ( isset( $params[$opt] ) ) {
75  $redisConf[$opt] = $params[$opt];
76  }
77  }
78  $this->redisPool = RedisConnectionPool::singleton( $redisConf );
79 
80  $this->servers = $params['servers'];
81  foreach ( $this->servers as $key => $server ) {
82  $this->serverTagMap[is_int( $key ) ? $server : $key] = $server;
83  }
84 
85  if ( isset( $params['automaticFailover'] ) ) {
86  $this->automaticFailover = $params['automaticFailover'];
87  } else {
88  $this->automaticFailover = true;
89  }
90 
92  }
93 
94  protected function doGet( $key, $flags = 0 ) {
95  list( $server, $conn ) = $this->getConnection( $key );
96  if ( !$conn ) {
97  return false;
98  }
99  try {
100  $value = $conn->get( $key );
101  $result = $this->unserialize( $value );
102  } catch ( RedisException $e ) {
103  $result = false;
104  $this->handleException( $conn, $e );
105  }
106 
107  $this->logRequest( 'get', $key, $server, $result );
108  return $result;
109  }
110 
111  public function set( $key, $value, $expiry = 0, $flags = 0 ) {
112  list( $server, $conn ) = $this->getConnection( $key );
113  if ( !$conn ) {
114  return false;
115  }
116  $expiry = $this->convertToRelative( $expiry );
117  try {
118  if ( $expiry ) {
119  $result = $conn->setex( $key, $expiry, $this->serialize( $value ) );
120  } else {
121  // No expiry, that is very different from zero expiry in Redis
122  $result = $conn->set( $key, $this->serialize( $value ) );
123  }
124  } catch ( RedisException $e ) {
125  $result = false;
126  $this->handleException( $conn, $e );
127  }
128 
129  $this->logRequest( 'set', $key, $server, $result );
130  return $result;
131  }
132 
133  public function delete( $key ) {
134  list( $server, $conn ) = $this->getConnection( $key );
135  if ( !$conn ) {
136  return false;
137  }
138  try {
139  $conn->del( $key );
140  // Return true even if the key didn't exist
141  $result = true;
142  } catch ( RedisException $e ) {
143  $result = false;
144  $this->handleException( $conn, $e );
145  }
146 
147  $this->logRequest( 'delete', $key, $server, $result );
148  return $result;
149  }
150 
151  public function getMulti( array $keys, $flags = 0 ) {
152  $batches = [];
153  $conns = [];
154  foreach ( $keys as $key ) {
155  list( $server, $conn ) = $this->getConnection( $key );
156  if ( !$conn ) {
157  continue;
158  }
159  $conns[$server] = $conn;
160  $batches[$server][] = $key;
161  }
162  $result = [];
163  foreach ( $batches as $server => $batchKeys ) {
164  $conn = $conns[$server];
165  try {
166  $conn->multi( Redis::PIPELINE );
167  foreach ( $batchKeys as $key ) {
168  $conn->get( $key );
169  }
170  $batchResult = $conn->exec();
171  if ( $batchResult === false ) {
172  $this->debug( "multi request to $server failed" );
173  continue;
174  }
175  foreach ( $batchResult as $i => $value ) {
176  if ( $value !== false ) {
177  $result[$batchKeys[$i]] = $this->unserialize( $value );
178  }
179  }
180  } catch ( RedisException $e ) {
181  $this->handleException( $conn, $e );
182  }
183  }
184 
185  $this->debug( "getMulti for " . count( $keys ) . " keys " .
186  "returned " . count( $result ) . " results" );
187  return $result;
188  }
189 
195  public function setMulti( array $data, $expiry = 0 ) {
196  $batches = [];
197  $conns = [];
198  foreach ( $data as $key => $value ) {
199  list( $server, $conn ) = $this->getConnection( $key );
200  if ( !$conn ) {
201  continue;
202  }
203  $conns[$server] = $conn;
204  $batches[$server][] = $key;
205  }
206 
207  $expiry = $this->convertToRelative( $expiry );
208  $result = true;
209  foreach ( $batches as $server => $batchKeys ) {
210  $conn = $conns[$server];
211  try {
212  $conn->multi( Redis::PIPELINE );
213  foreach ( $batchKeys as $key ) {
214  if ( $expiry ) {
215  $conn->setex( $key, $expiry, $this->serialize( $data[$key] ) );
216  } else {
217  $conn->set( $key, $this->serialize( $data[$key] ) );
218  }
219  }
220  $batchResult = $conn->exec();
221  if ( $batchResult === false ) {
222  $this->debug( "setMulti request to $server failed" );
223  continue;
224  }
225  foreach ( $batchResult as $value ) {
226  if ( $value === false ) {
227  $result = false;
228  }
229  }
230  } catch ( RedisException $e ) {
231  $this->handleException( $server, $conn, $e );
232  $result = false;
233  }
234  }
235 
236  return $result;
237  }
238 
239  public function add( $key, $value, $expiry = 0 ) {
240  list( $server, $conn ) = $this->getConnection( $key );
241  if ( !$conn ) {
242  return false;
243  }
244  $expiry = $this->convertToRelative( $expiry );
245  try {
246  if ( $expiry ) {
247  $result = $conn->set(
248  $key,
249  $this->serialize( $value ),
250  [ 'nx', 'ex' => $expiry ]
251  );
252  } else {
253  $result = $conn->setnx( $key, $this->serialize( $value ) );
254  }
255  } catch ( RedisException $e ) {
256  $result = false;
257  $this->handleException( $conn, $e );
258  }
259 
260  $this->logRequest( 'add', $key, $server, $result );
261  return $result;
262  }
263 
276  public function incr( $key, $value = 1 ) {
277  list( $server, $conn ) = $this->getConnection( $key );
278  if ( !$conn ) {
279  return false;
280  }
281  try {
282  if ( !$conn->exists( $key ) ) {
283  return null;
284  }
285  // @FIXME: on races, the key may have a 0 TTL
286  $result = $conn->incrBy( $key, $value );
287  } catch ( RedisException $e ) {
288  $result = false;
289  $this->handleException( $conn, $e );
290  }
291 
292  $this->logRequest( 'incr', $key, $server, $result );
293  return $result;
294  }
295 
296  public function changeTTL( $key, $expiry = 0 ) {
297  list( $server, $conn ) = $this->getConnection( $key );
298  if ( !$conn ) {
299  return false;
300  }
301 
302  $expiry = $this->convertToRelative( $expiry );
303  try {
304  $result = $conn->expire( $key, $expiry );
305  } catch ( RedisException $e ) {
306  $result = false;
307  $this->handleException( $conn, $e );
308  }
309 
310  $this->logRequest( 'expire', $key, $server, $result );
311  return $result;
312  }
313 
314  public function modifySimpleRelayEvent( array $event ) {
315  if ( array_key_exists( 'val', $event ) ) {
316  $event['val'] = serialize( $event['val'] ); // this class uses PHP serialization
317  }
318 
319  return $event;
320  }
321 
326  protected function serialize( $data ) {
327  // Serialize anything but integers so INCR/DECR work
328  // Do not store integer-like strings as integers to avoid type confusion (T62563)
329  return is_int( $data ) ? $data : serialize( $data );
330  }
331 
336  protected function unserialize( $data ) {
337  $int = intval( $data );
338  return $data === (string)$int ? $int : unserialize( $data );
339  }
340 
346  protected function getConnection( $key ) {
347  $candidates = array_keys( $this->serverTagMap );
348 
349  if ( count( $this->servers ) > 1 ) {
350  ArrayUtils::consistentHashSort( $candidates, $key, '/' );
351  if ( !$this->automaticFailover ) {
352  $candidates = array_slice( $candidates, 0, 1 );
353  }
354  }
355 
356  while ( ( $tag = array_shift( $candidates ) ) !== null ) {
357  $server = $this->serverTagMap[$tag];
358  $conn = $this->redisPool->getConnection( $server, $this->logger );
359  if ( !$conn ) {
360  continue;
361  }
362 
363  // If automatic failover is enabled, check that the server's link
364  // to its master (if any) is up -- but only if there are other
365  // viable candidates left to consider. Also, getMasterLinkStatus()
366  // does not work with twemproxy, though $candidates will be empty
367  // by now in such cases.
368  if ( $this->automaticFailover && $candidates ) {
369  try {
370  if ( $this->getMasterLinkStatus( $conn ) === 'down' ) {
371  // If the master cannot be reached, fail-over to the next server.
372  // If masters are in data-center A, and replica DBs in data-center B,
373  // this helps avoid the case were fail-over happens in A but not
374  // to the corresponding server in B (e.g. read/write mismatch).
375  continue;
376  }
377  } catch ( RedisException $e ) {
378  // Server is not accepting commands
379  $this->handleException( $conn, $e );
380  continue;
381  }
382  }
383 
384  return [ $server, $conn ];
385  }
386 
388 
389  return [ false, false ];
390  }
391 
398  protected function getMasterLinkStatus( RedisConnRef $conn ) {
399  $info = $conn->info();
400  return isset( $info['master_link_status'] )
401  ? $info['master_link_status']
402  : null;
403  }
404 
409  protected function logError( $msg ) {
410  $this->logger->error( "Redis error: $msg" );
411  }
412 
421  protected function handleException( RedisConnRef $conn, $e ) {
423  $this->redisPool->handleError( $conn, $e );
424  }
425 
433  public function logRequest( $method, $key, $server, $result ) {
434  $this->debug( "$method $key on $server: " .
435  ( $result === false ? "failure" : "success" ) );
436  }
437 }
ArrayUtils\consistentHashSort
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
RedisBagOStuff
Redis-based caching module for redis server >= 2.6.12 and phpredis >= 2.2.4.
Definition: RedisBagOStuff.php:32
RedisConnectionPool\singleton
static singleton(array $options)
Definition: RedisConnectionPool.php:147
RedisBagOStuff\setMulti
setMulti(array $data, $expiry=0)
Definition: RedisBagOStuff.php:195
RedisBagOStuff\changeTTL
changeTTL( $key, $expiry=0)
Reset the TTL on a key if it exists.
Definition: RedisBagOStuff.php:296
servers
storage can be distributed across multiple servers
Definition: memcached.txt:33
RedisBagOStuff\incr
incr( $key, $value=1)
Non-atomic implementation of incr().
Definition: RedisBagOStuff.php:276
BagOStuff\ERR_UNREACHABLE
const ERR_UNREACHABLE
Definition: BagOStuff.php:82
array
the array() calling protocol came about after MediaWiki 1.4rc1.
$opt
$opt
Definition: postprocess-phan.php:119
string
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition: hooks.txt:181
RedisBagOStuff\getMulti
getMulti(array $keys, $flags=0)
Get an associative array containing the item for each of the keys that have items.
Definition: RedisBagOStuff.php:151
RedisBagOStuff\unserialize
unserialize( $data)
Definition: RedisBagOStuff.php:336
BagOStuff\debug
debug( $text)
Definition: BagOStuff.php:682
RedisBagOStuff\$redisPool
RedisConnectionPool $redisPool
Definition: RedisBagOStuff.php:34
$params
$params
Definition: styleTest.css.php:40
BagOStuff
interface is intended to be more or less compatible with the PHP memcached client.
Definition: BagOStuff.php:47
RedisBagOStuff\$automaticFailover
bool $automaticFailover
Definition: RedisBagOStuff.php:40
RedisBagOStuff\$servers
array $servers
List of server names.
Definition: RedisBagOStuff.php:36
$result
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. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. '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 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name '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:Array with elements of the form "language:title" in the order that they will be output. & $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':DEPRECATED! Use HtmlPageLinkRendererBegin instead. 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:1993
php
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:37
RedisBagOStuff\doGet
doGet( $key, $flags=0)
Definition: RedisBagOStuff.php:94
RedisBagOStuff\add
add( $key, $value, $expiry=0)
Definition: RedisBagOStuff.php:239
RedisBagOStuff\getConnection
getConnection( $key)
Get a Redis object with a connection suitable for fetching the specified key.
Definition: RedisBagOStuff.php:346
RedisBagOStuff\logError
logError( $msg)
Log a fatal error.
Definition: RedisBagOStuff.php:409
RedisBagOStuff\logRequest
logRequest( $method, $key, $server, $result)
Send information about a single request to the debug log.
Definition: RedisBagOStuff.php:433
RedisBagOStuff\serialize
serialize( $data)
Definition: RedisBagOStuff.php:326
list
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
RedisBagOStuff\handleException
handleException(RedisConnRef $conn, $e)
The redis extension throws an exception in response to various read, write and protocol errors.
Definition: RedisBagOStuff.php:421
RedisConnectionPool
Helper class to manage Redis connections.
Definition: RedisConnectionPool.php:40
$value
$value
Definition: styleTest.css.php:45
RedisBagOStuff\$serverTagMap
array $serverTagMap
Map of (tag => server name)
Definition: RedisBagOStuff.php:38
IExpiringStore\ATTR_SYNCWRITES
const ATTR_SYNCWRITES
Definition: IExpiringStore.php:52
RedisBagOStuff\getMasterLinkStatus
getMasterLinkStatus(RedisConnRef $conn)
Check the master link status of a Redis server that is configured as a replica DB.
Definition: RedisBagOStuff.php:398
RedisBagOStuff\__construct
__construct( $params)
Construct a RedisBagOStuff object.
Definition: RedisBagOStuff.php:70
as
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:22
RedisConnRef
Helper class to handle automatically marking connectons as reusable (via RAII pattern)
Definition: RedisConnRef.php:31
$keys
$keys
Definition: testCompression.php:67
IExpiringStore\QOS_SYNCWRITES_NONE
const QOS_SYNCWRITES_NONE
Definition: IExpiringStore.php:53
BagOStuff\setLastError
setLastError( $err)
Set the "last error" registry.
Definition: BagOStuff.php:633
BagOStuff\ERR_UNEXPECTED
const ERR_UNEXPECTED
Definition: BagOStuff.php:83
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
RedisBagOStuff\modifySimpleRelayEvent
modifySimpleRelayEvent(array $event)
Modify a cache update operation array for EventRelayer::notify()
Definition: RedisBagOStuff.php:314
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2171
BagOStuff\convertToRelative
convertToRelative( $exptime)
Convert an optionally absolute expiry time to a relative time.
Definition: BagOStuff.php:710