MediaWiki  master
RedisBagOStuff.php
Go to the documentation of this file.
1 <?php
31 class RedisBagOStuff extends BagOStuff {
33  protected $redisPool;
35  protected $servers;
37  protected $serverTagMap;
39  protected $automaticFailover;
40 
69  function __construct( $params ) {
70  parent::__construct( $params );
71  $redisConf = [ 'serializer' => 'none' ]; // manage that in this class
72  foreach ( [ 'connectTimeout', 'persistent', 'password' ] as $opt ) {
73  if ( isset( $params[$opt] ) ) {
74  $redisConf[$opt] = $params[$opt];
75  }
76  }
77  $this->redisPool = RedisConnectionPool::singleton( $redisConf );
78 
79  $this->servers = $params['servers'];
80  foreach ( $this->servers as $key => $server ) {
81  $this->serverTagMap[is_int( $key ) ? $server : $key] = $server;
82  }
83 
84  $this->automaticFailover = $params['automaticFailover'] ?? true;
85 
86  $this->attrMap[self::ATTR_SYNCWRITES] = self::QOS_SYNCWRITES_NONE;
87  }
88 
89  protected function doGet( $key, $flags = 0, &$casToken = null ) {
90  $casToken = null;
91 
92  list( $server, $conn ) = $this->getConnection( $key );
93  if ( !$conn ) {
94  return false;
95  }
96  try {
97  $value = $conn->get( $key );
98  $casToken = $value;
99  $result = $this->unserialize( $value );
100  } catch ( RedisException $e ) {
101  $result = false;
102  $this->handleException( $conn, $e );
103  }
104 
105  $this->logRequest( 'get', $key, $server, $result );
106  return $result;
107  }
108 
109  protected function doSet( $key, $value, $expiry = 0, $flags = 0 ) {
110  list( $server, $conn ) = $this->getConnection( $key );
111  if ( !$conn ) {
112  return false;
113  }
114  $expiry = $this->convertToRelative( $expiry );
115  try {
116  if ( $expiry ) {
117  $result = $conn->setex( $key, $expiry, $this->serialize( $value ) );
118  } else {
119  // No expiry, that is very different from zero expiry in Redis
120  $result = $conn->set( $key, $this->serialize( $value ) );
121  }
122  } catch ( RedisException $e ) {
123  $result = false;
124  $this->handleException( $conn, $e );
125  }
126 
127  $this->logRequest( 'set', $key, $server, $result );
128  return $result;
129  }
130 
131  protected function doDelete( $key, $flags = 0 ) {
132  list( $server, $conn ) = $this->getConnection( $key );
133  if ( !$conn ) {
134  return false;
135  }
136  try {
137  $conn->delete( $key );
138  // Return true even if the key didn't exist
139  $result = true;
140  } catch ( RedisException $e ) {
141  $result = false;
142  $this->handleException( $conn, $e );
143  }
144 
145  $this->logRequest( 'delete', $key, $server, $result );
146  return $result;
147  }
148 
149  public function doGetMulti( array $keys, $flags = 0 ) {
150  $batches = [];
151  $conns = [];
152  foreach ( $keys as $key ) {
153  list( $server, $conn ) = $this->getConnection( $key );
154  if ( !$conn ) {
155  continue;
156  }
157  $conns[$server] = $conn;
158  $batches[$server][] = $key;
159  }
160  $result = [];
161  foreach ( $batches as $server => $batchKeys ) {
162  $conn = $conns[$server];
163  try {
164  $conn->multi( Redis::PIPELINE );
165  foreach ( $batchKeys as $key ) {
166  $conn->get( $key );
167  }
168  $batchResult = $conn->exec();
169  if ( $batchResult === false ) {
170  $this->debug( "multi request to $server failed" );
171  continue;
172  }
173  foreach ( $batchResult as $i => $value ) {
174  if ( $value !== false ) {
175  $result[$batchKeys[$i]] = $this->unserialize( $value );
176  }
177  }
178  } catch ( RedisException $e ) {
179  $this->handleException( $conn, $e );
180  }
181  }
182 
183  $this->debug( "getMulti for " . count( $keys ) . " keys " .
184  "returned " . count( $result ) . " results" );
185  return $result;
186  }
187 
188  public function setMulti( array $data, $expiry = 0, $flags = 0 ) {
189  $batches = [];
190  $conns = [];
191  foreach ( $data as $key => $value ) {
192  list( $server, $conn ) = $this->getConnection( $key );
193  if ( !$conn ) {
194  continue;
195  }
196  $conns[$server] = $conn;
197  $batches[$server][] = $key;
198  }
199 
200  $expiry = $this->convertToRelative( $expiry );
201  $result = true;
202  foreach ( $batches as $server => $batchKeys ) {
203  $conn = $conns[$server];
204  try {
205  $conn->multi( Redis::PIPELINE );
206  foreach ( $batchKeys as $key ) {
207  if ( $expiry ) {
208  $conn->setex( $key, $expiry, $this->serialize( $data[$key] ) );
209  } else {
210  $conn->set( $key, $this->serialize( $data[$key] ) );
211  }
212  }
213  $batchResult = $conn->exec();
214  if ( $batchResult === false ) {
215  $this->debug( "setMulti request to $server failed" );
216  continue;
217  }
218  foreach ( $batchResult as $value ) {
219  if ( $value === false ) {
220  $result = false;
221  }
222  }
223  } catch ( RedisException $e ) {
224  $this->handleException( $conn, $e );
225  $result = false;
226  }
227  }
228 
229  return $result;
230  }
231 
232  public function deleteMulti( array $keys, $flags = 0 ) {
233  $batches = [];
234  $conns = [];
235  foreach ( $keys as $key ) {
236  list( $server, $conn ) = $this->getConnection( $key );
237  if ( !$conn ) {
238  continue;
239  }
240  $conns[$server] = $conn;
241  $batches[$server][] = $key;
242  }
243 
244  $result = true;
245  foreach ( $batches as $server => $batchKeys ) {
246  $conn = $conns[$server];
247  try {
248  $conn->multi( Redis::PIPELINE );
249  foreach ( $batchKeys as $key ) {
250  $conn->delete( $key );
251  }
252  $batchResult = $conn->exec();
253  if ( $batchResult === false ) {
254  $this->debug( "deleteMulti request to $server failed" );
255  continue;
256  }
257  foreach ( $batchResult as $value ) {
258  if ( $value === false ) {
259  $result = false;
260  }
261  }
262  } catch ( RedisException $e ) {
263  $this->handleException( $conn, $e );
264  $result = false;
265  }
266  }
267 
268  return $result;
269  }
270 
271  public function add( $key, $value, $expiry = 0, $flags = 0 ) {
272  list( $server, $conn ) = $this->getConnection( $key );
273  if ( !$conn ) {
274  return false;
275  }
276  $expiry = $this->convertToRelative( $expiry );
277  try {
278  if ( $expiry ) {
279  $result = $conn->set(
280  $key,
281  $this->serialize( $value ),
282  [ 'nx', 'ex' => $expiry ]
283  );
284  } else {
285  $result = $conn->setnx( $key, $this->serialize( $value ) );
286  }
287  } catch ( RedisException $e ) {
288  $result = false;
289  $this->handleException( $conn, $e );
290  }
291 
292  $this->logRequest( 'add', $key, $server, $result );
293  return $result;
294  }
295 
308  public function incr( $key, $value = 1 ) {
309  list( $server, $conn ) = $this->getConnection( $key );
310  if ( !$conn ) {
311  return false;
312  }
313  try {
314  if ( !$conn->exists( $key ) ) {
315  return false;
316  }
317  // @FIXME: on races, the key may have a 0 TTL
318  $result = $conn->incrBy( $key, $value );
319  } catch ( RedisException $e ) {
320  $result = false;
321  $this->handleException( $conn, $e );
322  }
323 
324  $this->logRequest( 'incr', $key, $server, $result );
325  return $result;
326  }
327 
328  public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
329  list( $server, $conn ) = $this->getConnection( $key );
330  if ( !$conn ) {
331  return false;
332  }
333 
334  $relative = $this->expiryIsRelative( $exptime );
335  try {
336  if ( $exptime == 0 ) {
337  $result = $conn->persist( $key );
338  $this->logRequest( 'persist', $key, $server, $result );
339  } elseif ( $relative ) {
340  $result = $conn->expire( $key, $this->convertToRelative( $exptime ) );
341  $this->logRequest( 'expire', $key, $server, $result );
342  } else {
343  $result = $conn->expireAt( $key, $this->convertToExpiry( $exptime ) );
344  $this->logRequest( 'expireAt', $key, $server, $result );
345  }
346  } catch ( RedisException $e ) {
347  $result = false;
348  $this->handleException( $conn, $e );
349  }
350 
351  return $result;
352  }
353 
359  protected function getConnection( $key ) {
360  $candidates = array_keys( $this->serverTagMap );
361 
362  if ( count( $this->servers ) > 1 ) {
363  ArrayUtils::consistentHashSort( $candidates, $key, '/' );
364  if ( !$this->automaticFailover ) {
365  $candidates = array_slice( $candidates, 0, 1 );
366  }
367  }
368 
369  while ( ( $tag = array_shift( $candidates ) ) !== null ) {
370  $server = $this->serverTagMap[$tag];
371  $conn = $this->redisPool->getConnection( $server, $this->logger );
372  if ( !$conn ) {
373  continue;
374  }
375 
376  // If automatic failover is enabled, check that the server's link
377  // to its master (if any) is up -- but only if there are other
378  // viable candidates left to consider. Also, getMasterLinkStatus()
379  // does not work with twemproxy, though $candidates will be empty
380  // by now in such cases.
381  if ( $this->automaticFailover && $candidates ) {
382  try {
383  if ( $this->getMasterLinkStatus( $conn ) === 'down' ) {
384  // If the master cannot be reached, fail-over to the next server.
385  // If masters are in data-center A, and replica DBs in data-center B,
386  // this helps avoid the case were fail-over happens in A but not
387  // to the corresponding server in B (e.g. read/write mismatch).
388  continue;
389  }
390  } catch ( RedisException $e ) {
391  // Server is not accepting commands
392  $this->handleException( $conn, $e );
393  continue;
394  }
395  }
396 
397  return [ $server, $conn ];
398  }
399 
401 
402  return [ false, false ];
403  }
404 
411  protected function getMasterLinkStatus( RedisConnRef $conn ) {
412  $info = $conn->info();
413  return $info['master_link_status'] ?? null;
414  }
415 
420  protected function logError( $msg ) {
421  $this->logger->error( "Redis error: $msg" );
422  }
423 
432  protected function handleException( RedisConnRef $conn, $e ) {
434  $this->redisPool->handleError( $conn, $e );
435  }
436 
444  public function logRequest( $method, $key, $server, $result ) {
445  $this->debug( "$method $key on $server: " .
446  ( $result === false ? "failure" : "success" ) );
447  }
448 }
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
doGet( $key, $flags=0, &$casToken=null)
incr( $key, $value=1)
Non-atomic implementation of incr().
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
debug( $text)
Definition: BagOStuff.php:875
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2159
changeTTL( $key, $exptime=0, $flags=0)
add( $key, $value, $expiry=0, $flags=0)
unserialize( $value)
Definition: BagOStuff.php:1059
$value
doSet( $key, $value, $expiry=0, $flags=0)
expiryIsRelative( $exptime)
Definition: BagOStuff.php:887
getConnection( $key)
Get a Redis object with a connection suitable for fetching the specified key.
setLastError( $err)
Set the "last error" registry.
Definition: BagOStuff.php:844
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 '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. '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 '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 since 1.28! 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:1980
static singleton(array $options)
convertToExpiry( $exptime)
Convert an optionally relative time to an absolute time.
Definition: BagOStuff.php:896
array $servers
List of server names.
logError( $msg)
Log a fatal error.
doDelete( $key, $flags=0)
doGetMulti(array $keys, $flags=0)
deleteMulti(array $keys, $flags=0)
$params
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
RedisConnectionPool $redisPool
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
convertToRelative( $exptime)
Convert an optionally absolute expiry time to a relative time.
Definition: BagOStuff.php:911
getMasterLinkStatus(RedisConnRef $conn)
Check the master link status of a Redis server that is configured as a replica DB.
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
setMulti(array $data, $expiry=0, $flags=0)
static consistentHashSort(&$array, $key, $separator="\0")
Sort the given array in a pseudo-random order which depends only on the given key and each element va...
Definition: ArrayUtils.php:49
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
serialize( $value)
Definition: BagOStuff.php:1050
__construct( $params)
Construct a RedisBagOStuff object.