MediaWiki REL1_31
RedisBagOStuff.php
Go to the documentation of this file.
1<?php
34 protected $redisPool;
36 protected $servers;
38 protected $serverTagMap;
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}
serialize()
interface is intended to be more or less compatible with the PHP memcached client.
Definition BagOStuff.php:47
const ERR_UNEXPECTED
Definition BagOStuff.php:83
debug( $text)
convertToRelative( $exptime)
Convert an optionally absolute expiry time to a relative time.
setLastError( $err)
Set the "last error" registry.
const ERR_UNREACHABLE
Definition BagOStuff.php:82
Redis-based caching module for redis server >= 2.6.12 and phpredis >= 2.2.4.
RedisConnectionPool $redisPool
incr( $key, $value=1)
Non-atomic implementation of incr().
modifySimpleRelayEvent(array $event)
Modify a cache update operation array for EventRelayer::notify()
getMasterLinkStatus(RedisConnRef $conn)
Check the master link status of a Redis server that is configured as a replica DB.
array $servers
List of server names.
setMulti(array $data, $expiry=0)
logError( $msg)
Log a fatal error.
getConnection( $key)
Get a Redis object with a connection suitable for fetching the specified key.
__construct( $params)
Construct a RedisBagOStuff object.
doGet( $key, $flags=0)
changeTTL( $key, $expiry=0)
Reset the TTL on a key if it exists.
array $serverTagMap
Map of (tag => server name)
add( $key, $value, $expiry=0)
handleException(RedisConnRef $conn, $e)
The redis extension throws an exception in response to various read, write and protocol errors.
getMulti(array $keys, $flags=0)
Get an associative array containing the item for each of the keys that have items.
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)
Helper class to manage Redis connections.
static singleton(array $options)
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
namespace being checked & $result
Definition hooks.txt:2323
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
processing should stop and the error should be shown to the user * false
Definition hooks.txt:187
returning false will NOT prevent logging $e
Definition hooks.txt:2176
storage can be distributed across multiple servers
Definition memcached.txt:33
$params