MediaWiki  1.23.6
RedisBagOStuff.php
Go to the documentation of this file.
1 <?php
23 class RedisBagOStuff extends BagOStuff {
25  protected $redisPool;
27  protected $servers;
29  protected $automaticFailover;
30 
57  function __construct( $params ) {
58  $redisConf = array( 'serializer' => 'none' ); // manage that in this class
59  foreach ( array( 'connectTimeout', 'persistent', 'password' ) as $opt ) {
60  if ( isset( $params[$opt] ) ) {
61  $redisConf[$opt] = $params[$opt];
62  }
63  }
64  $this->redisPool = RedisConnectionPool::singleton( $redisConf );
65 
66  $this->servers = $params['servers'];
67  if ( isset( $params['automaticFailover'] ) ) {
68  $this->automaticFailover = $params['automaticFailover'];
69  } else {
70  $this->automaticFailover = true;
71  }
72  }
73 
74  public function get( $key, &$casToken = null ) {
75  $section = new ProfileSection( __METHOD__ );
76 
77  list( $server, $conn ) = $this->getConnection( $key );
78  if ( !$conn ) {
79  return false;
80  }
81  try {
82  $value = $conn->get( $key );
83  $casToken = $value;
84  $result = $this->unserialize( $value );
85  } catch ( RedisException $e ) {
86  $result = false;
87  $this->handleException( $conn, $e );
88  }
89 
90  $this->logRequest( 'get', $key, $server, $result );
91  return $result;
92  }
93 
94  public function set( $key, $value, $expiry = 0 ) {
95  $section = new ProfileSection( __METHOD__ );
96 
97  list( $server, $conn ) = $this->getConnection( $key );
98  if ( !$conn ) {
99  return false;
100  }
101  $expiry = $this->convertToRelative( $expiry );
102  try {
103  if ( $expiry ) {
104  $result = $conn->setex( $key, $expiry, $this->serialize( $value ) );
105  } else {
106  // No expiry, that is very different from zero expiry in Redis
107  $result = $conn->set( $key, $this->serialize( $value ) );
108  }
109  } catch ( RedisException $e ) {
110  $result = false;
111  $this->handleException( $conn, $e );
112  }
113 
114  $this->logRequest( 'set', $key, $server, $result );
115  return $result;
116  }
117 
118  public function cas( $casToken, $key, $value, $expiry = 0 ) {
119  $section = new ProfileSection( __METHOD__ );
120 
121  list( $server, $conn ) = $this->getConnection( $key );
122  if ( !$conn ) {
123  return false;
124  }
125  $expiry = $this->convertToRelative( $expiry );
126  try {
127  $conn->watch( $key );
128 
129  if ( $this->serialize( $this->get( $key ) ) !== $casToken ) {
130  $conn->unwatch();
131  return false;
132  }
133 
134  // multi()/exec() will fail atomically if the key changed since watch()
135  $conn->multi();
136  if ( $expiry ) {
137  $conn->setex( $key, $expiry, $this->serialize( $value ) );
138  } else {
139  // No expiry, that is very different from zero expiry in Redis
140  $conn->set( $key, $this->serialize( $value ) );
141  }
142  $result = ( $conn->exec() == array( true ) );
143  } catch ( RedisException $e ) {
144  $result = false;
145  $this->handleException( $conn, $e );
146  }
147 
148  $this->logRequest( 'cas', $key, $server, $result );
149  return $result;
150  }
151 
152  public function delete( $key, $time = 0 ) {
153  $section = new ProfileSection( __METHOD__ );
154 
155  list( $server, $conn ) = $this->getConnection( $key );
156  if ( !$conn ) {
157  return false;
158  }
159  try {
160  $conn->delete( $key );
161  // Return true even if the key didn't exist
162  $result = true;
163  } catch ( RedisException $e ) {
164  $result = false;
165  $this->handleException( $conn, $e );
166  }
167 
168  $this->logRequest( 'delete', $key, $server, $result );
169  return $result;
170  }
171 
172  public function getMulti( array $keys ) {
173  $section = new ProfileSection( __METHOD__ );
174 
175  $batches = array();
176  $conns = array();
177  foreach ( $keys as $key ) {
178  list( $server, $conn ) = $this->getConnection( $key );
179  if ( !$conn ) {
180  continue;
181  }
182  $conns[$server] = $conn;
183  $batches[$server][] = $key;
184  }
185  $result = array();
186  foreach ( $batches as $server => $batchKeys ) {
187  $conn = $conns[$server];
188  try {
189  $conn->multi( Redis::PIPELINE );
190  foreach ( $batchKeys as $key ) {
191  $conn->get( $key );
192  }
193  $batchResult = $conn->exec();
194  if ( $batchResult === false ) {
195  $this->debug( "multi request to $server failed" );
196  continue;
197  }
198  foreach ( $batchResult as $i => $value ) {
199  if ( $value !== false ) {
200  $result[$batchKeys[$i]] = $this->unserialize( $value );
201  }
202  }
203  } catch ( RedisException $e ) {
204  $this->handleException( $conn, $e );
205  }
206  }
207 
208  $this->debug( "getMulti for " . count( $keys ) . " keys " .
209  "returned " . count( $result ) . " results" );
210  return $result;
211  }
212 
213  public function add( $key, $value, $expiry = 0 ) {
214  $section = new ProfileSection( __METHOD__ );
215 
216  list( $server, $conn ) = $this->getConnection( $key );
217  if ( !$conn ) {
218  return false;
219  }
220  $expiry = $this->convertToRelative( $expiry );
221  try {
222  if ( $expiry ) {
223  $conn->multi();
224  $conn->setnx( $key, $this->serialize( $value ) );
225  $conn->expire( $key, $expiry );
226  $result = ( $conn->exec() == array( true, true ) );
227  } else {
228  $result = $conn->setnx( $key, $this->serialize( $value ) );
229  }
230  } catch ( RedisException $e ) {
231  $result = false;
232  $this->handleException( $conn, $e );
233  }
234 
235  $this->logRequest( 'add', $key, $server, $result );
236  return $result;
237  }
238 
248  public function incr( $key, $value = 1 ) {
249  $section = new ProfileSection( __METHOD__ );
250 
251  list( $server, $conn ) = $this->getConnection( $key );
252  if ( !$conn ) {
253  return false;
254  }
255  if ( !$conn->exists( $key ) ) {
256  return null;
257  }
258  try {
259  $result = $this->unserialize( $conn->incrBy( $key, $value ) );
260  } catch ( RedisException $e ) {
261  $result = false;
262  $this->handleException( $conn, $e );
263  }
264 
265  $this->logRequest( 'incr', $key, $server, $result );
266  return $result;
267  }
268 
273  protected function serialize( $data ) {
274  // Ignore digit strings and ints so INCR/DECR work
275  return ( is_int( $data ) || ctype_digit( $data ) ) ? $data : serialize( $data );
276  }
277 
282  protected function unserialize( $data ) {
283  // Ignore digit strings and ints so INCR/DECR work
284  return ( is_int( $data ) || ctype_digit( $data ) ) ? $data : unserialize( $data );
285  }
286 
291  protected function getConnection( $key ) {
292  if ( count( $this->servers ) === 1 ) {
293  $candidates = $this->servers;
294  } else {
295  $candidates = $this->servers;
296  ArrayUtils::consistentHashSort( $candidates, $key, '/' );
297  if ( !$this->automaticFailover ) {
298  $candidates = array_slice( $candidates, 0, 1 );
299  }
300  }
301 
302  foreach ( $candidates as $server ) {
303  $conn = $this->redisPool->getConnection( $server );
304  if ( $conn ) {
305  return array( $server, $conn );
306  }
307  }
309  return array( false, false );
310  }
311 
315  protected function logError( $msg ) {
316  wfDebugLog( 'redis', "Redis error: $msg" );
317  }
318 
325  protected function handleException( RedisConnRef $conn, $e ) {
327  $this->redisPool->handleError( $conn, $e );
328  }
329 
333  public function logRequest( $method, $key, $server, $result ) {
334  $this->debug( "$method $key on $server: " .
335  ( $result === false ? "failure" : "success" ) );
336  }
337 }
$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. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. $reader:XMLReader object $logInfo:Array of information Return false to stop further processing of the tag 'ImportHandlePageXMLTag':When parsing a XML tag in a page. $reader:XMLReader object $pageInfo:Array of information Return false to stop further processing of the tag 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information Return false to stop further processing of the tag 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. $reader:XMLReader object Return false to stop further processing of the tag 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. $reader:XMLReader object $revisionInfo:Array of information Return false to stop further processing of the tag '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 '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. '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 '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 '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 wfIsTrustedProxy() $ip:IP being check $result:Change this value to override the result of wfIsTrustedProxy() '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 User::isValidEmailAddr(), 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 '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) '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. '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:1528
$time
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1358
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
Definition: RedisBagOStuff.php:23
RedisConnectionPool\singleton
static singleton(array $options)
Definition: RedisConnectionPool.php:115
php
skin txt MediaWiki includes four core it has been set as the default in MediaWiki since the replacing Monobook it had been been the default skin since before being replaced by Vector largely rewritten in while keeping its appearance Several legacy skins were removed in the as the burden of supporting them became too heavy to bear Those in etc for skin dependent CSS etc for skin dependent JavaScript These can also be customised on a per user by etc This feature has led to a wide variety of user styles becoming that gallery is a good place to ending in php
Definition: skin.txt:62
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:245
BagOStuff\ERR_UNREACHABLE
const ERR_UNREACHABLE
Definition: BagOStuff.php:51
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all')
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:1040
RedisBagOStuff\unserialize
unserialize( $data)
Definition: RedisBagOStuff.php:279
BagOStuff\debug
debug( $text)
Definition: BagOStuff.php:339
RedisBagOStuff\$servers
Array $servers
List of server names *.
Definition: RedisBagOStuff.php:25
RedisBagOStuff\$redisPool
RedisConnectionPool $redisPool
Definition: RedisBagOStuff.php:24
$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:43
RedisBagOStuff\$automaticFailover
bool $automaticFailover
Definition: RedisBagOStuff.php:26
RedisBagOStuff\add
add( $key, $value, $expiry=0)
Definition: RedisBagOStuff.php:210
RedisBagOStuff\getConnection
getConnection( $key)
Get a Redis object with a connection suitable for fetching the specified key.
Definition: RedisBagOStuff.php:288
RedisBagOStuff\logError
logError( $msg)
Log a fatal error.
Definition: RedisBagOStuff.php:312
ProfileSection
Class for handling function-scope profiling.
Definition: Profiler.php:60
RedisBagOStuff\cas
cas( $casToken, $key, $value, $expiry=0)
Check and set an item.
Definition: RedisBagOStuff.php:115
array
the array() calling protocol came about after MediaWiki 1.4rc1.
List of Api Query prop modules.
RedisBagOStuff\logRequest
logRequest( $method, $key, $server, $result)
Send information about a single request to the debug log.
Definition: RedisBagOStuff.php:330
RedisBagOStuff\serialize
serialize( $data)
Definition: RedisBagOStuff.php:270
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:322
$section
$section
Definition: Utf8Test.php:88
RedisConnectionPool
Helper class to manage Redis connections.
Definition: RedisConnectionPool.php:38
$value
$value
Definition: styleTest.css.php:45
RedisBagOStuff\getMulti
getMulti(array $keys)
Get an associative array containing the item for each of the keys that have items.
Definition: RedisBagOStuff.php:169
RedisBagOStuff\__construct
__construct( $params)
Construct a RedisBagOStuff object.
Definition: RedisBagOStuff.php:54
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:9
RedisConnRef
Helper class to handle automatically marking connectons as reusable (via RAII pattern)
Definition: RedisConnectionPool.php:348
$keys
$keys
Definition: testCompression.php:63
$e
if( $useReadline) $e
Definition: eval.php:66
BagOStuff\setLastError
setLastError( $err)
Set the "last error" registry.
Definition: BagOStuff.php:332
BagOStuff\ERR_UNEXPECTED
const ERR_UNEXPECTED
Definition: BagOStuff.php:52
BagOStuff\convertToRelative
convertToRelative( $exptime)
Convert an optionally absolute expiry time to a relative time.
Definition: BagOStuff.php:366