Merge "Drop zh-tw message "saveprefs""
[lhc/web/wiklou.git] / includes / clientpool / RedisConnectionPool.php
1 <?php
2 /**
3 * Redis client connection pooling manager.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @defgroup Redis Redis
22 * @author Aaron Schulz
23 */
24
25 use MediaWiki\Logger\LoggerFactory;
26 use Psr\Log\LoggerAwareInterface;
27 use Psr\Log\LoggerInterface;
28
29 /**
30 * Helper class to manage Redis connections.
31 *
32 * This can be used to get handle wrappers that free the handle when the wrapper
33 * leaves scope. The maximum number of free handles (connections) is configurable.
34 * This provides an easy way to cache connection handles that may also have state,
35 * such as a handle does between multi() and exec(), and without hoarding connections.
36 * The wrappers use PHP magic methods so that calling functions on them calls the
37 * function of the actual Redis object handle.
38 *
39 * @ingroup Redis
40 * @since 1.21
41 */
42 class RedisConnectionPool implements LoggerAwareInterface {
43 /**
44 * @name Pool settings.
45 * Settings there are shared for any connection made in this pool.
46 * See the singleton() method documentation for more details.
47 * @{
48 */
49 /** @var string Connection timeout in seconds */
50 protected $connectTimeout;
51 /** @var string Read timeout in seconds */
52 protected $readTimeout;
53 /** @var string Plaintext auth password */
54 protected $password;
55 /** @var bool Whether connections persist */
56 protected $persistent;
57 /** @var int Serializer to use (Redis::SERIALIZER_*) */
58 protected $serializer;
59 /** @} */
60
61 /** @var int Current idle pool size */
62 protected $idlePoolSize = 0;
63
64 /** @var array (server name => ((connection info array),...) */
65 protected $connections = array();
66 /** @var array (server name => UNIX timestamp) */
67 protected $downServers = array();
68
69 /** @var array (pool ID => RedisConnectionPool) */
70 protected static $instances = array();
71
72 /** integer; seconds to cache servers as "down". */
73 const SERVER_DOWN_TTL = 30;
74
75 /**
76 * @var LoggerInterface
77 */
78 protected $logger;
79
80 /**
81 * @param array $options
82 * @throws MWException
83 */
84 protected function __construct( array $options ) {
85 if ( !class_exists( 'Redis' ) ) {
86 throw new MWException( __CLASS__ . ' requires a Redis client library. ' .
87 'See https://www.mediawiki.org/wiki/Redis#Setup' );
88 }
89 if ( isset( $options['logger'] ) ) {
90 $this->setLogger( $options['logger'] );
91 } else {
92 $this->setLogger( LoggerFactory::getInstance( 'redis' ) );
93 }
94 $this->connectTimeout = $options['connectTimeout'];
95 $this->readTimeout = $options['readTimeout'];
96 $this->persistent = $options['persistent'];
97 $this->password = $options['password'];
98 if ( !isset( $options['serializer'] ) || $options['serializer'] === 'php' ) {
99 $this->serializer = Redis::SERIALIZER_PHP;
100 } elseif ( $options['serializer'] === 'igbinary' ) {
101 $this->serializer = Redis::SERIALIZER_IGBINARY;
102 } elseif ( $options['serializer'] === 'none' ) {
103 $this->serializer = Redis::SERIALIZER_NONE;
104 } else {
105 throw new MWException( "Invalid serializer specified." );
106 }
107 }
108
109 /**
110 * @param LoggerInterface $logger
111 * @return null
112 */
113 public function setLogger( LoggerInterface $logger ) {
114 $this->logger = $logger;
115 }
116
117 /**
118 * @param array $options
119 * @return array
120 */
121 protected static function applyDefaultConfig( array $options ) {
122 if ( !isset( $options['connectTimeout'] ) ) {
123 $options['connectTimeout'] = 1;
124 }
125 if ( !isset( $options['readTimeout'] ) ) {
126 $options['readTimeout'] = 1;
127 }
128 if ( !isset( $options['persistent'] ) ) {
129 $options['persistent'] = false;
130 }
131 if ( !isset( $options['password'] ) ) {
132 $options['password'] = null;
133 }
134
135 return $options;
136 }
137
138 /**
139 * @param array $options
140 * $options include:
141 * - connectTimeout : The timeout for new connections, in seconds.
142 * Optional, default is 1 second.
143 * - readTimeout : The timeout for operation reads, in seconds.
144 * Commands like BLPOP can fail if told to wait longer than this.
145 * Optional, default is 1 second.
146 * - persistent : Set this to true to allow connections to persist across
147 * multiple web requests. False by default.
148 * - password : The authentication password, will be sent to Redis in clear text.
149 * Optional, if it is unspecified, no AUTH command will be sent.
150 * - serializer : Set to "php", "igbinary", or "none". Default is "php".
151 * @return RedisConnectionPool
152 */
153 public static function singleton( array $options ) {
154 $options = self::applyDefaultConfig( $options );
155 // Map the options to a unique hash...
156 ksort( $options ); // normalize to avoid pool fragmentation
157 $id = sha1( serialize( $options ) );
158 // Initialize the object at the hash as needed...
159 if ( !isset( self::$instances[$id] ) ) {
160 self::$instances[$id] = new self( $options );
161 LoggerFactory::getInstance( 'redis' )->debug(
162 "Creating a new " . __CLASS__ . " instance with id $id."
163 );
164 }
165
166 return self::$instances[$id];
167 }
168
169 /**
170 * Get a connection to a redis server. Based on code in RedisBagOStuff.php.
171 *
172 * @param string $server A hostname/port combination or the absolute path of a UNIX socket.
173 * If a hostname is specified but no port, port 6379 will be used.
174 * @return RedisConnRef|bool Returns false on failure
175 * @throws MWException
176 */
177 public function getConnection( $server ) {
178 // Check the listing "dead" servers which have had a connection errors.
179 // Servers are marked dead for a limited period of time, to
180 // avoid excessive overhead from repeated connection timeouts.
181 if ( isset( $this->downServers[$server] ) ) {
182 $now = time();
183 if ( $now > $this->downServers[$server] ) {
184 // Dead time expired
185 unset( $this->downServers[$server] );
186 } else {
187 // Server is dead
188 $this->logger->debug(
189 'Server "{redis_server}" is marked down for another ' .
190 ( $this->downServers[$server] - $now ) . 'seconds',
191 array( 'redis_server' => $server )
192 );
193
194 return false;
195 }
196 }
197
198 // Check if a connection is already free for use
199 if ( isset( $this->connections[$server] ) ) {
200 foreach ( $this->connections[$server] as &$connection ) {
201 if ( $connection['free'] ) {
202 $connection['free'] = false;
203 --$this->idlePoolSize;
204
205 return new RedisConnRef(
206 $this, $server, $connection['conn'], $this->logger
207 );
208 }
209 }
210 }
211
212 if ( substr( $server, 0, 1 ) === '/' ) {
213 // UNIX domain socket
214 // These are required by the redis extension to start with a slash, but
215 // we still need to set the port to a special value to make it work.
216 $host = $server;
217 $port = 0;
218 } else {
219 // TCP connection
220 $hostPort = IP::splitHostAndPort( $server );
221 if ( !$server || !$hostPort ) {
222 throw new MWException( __CLASS__ . ": invalid configured server \"$server\"" );
223 }
224 list( $host, $port ) = $hostPort;
225 if ( $port === false ) {
226 $port = 6379;
227 }
228 }
229
230 $conn = new Redis();
231 try {
232 if ( $this->persistent ) {
233 $result = $conn->pconnect( $host, $port, $this->connectTimeout );
234 } else {
235 $result = $conn->connect( $host, $port, $this->connectTimeout );
236 }
237 if ( !$result ) {
238 $this->logger->error(
239 'Could not connect to server "{redis_server}"',
240 array( 'redis_server' => $server )
241 );
242 // Mark server down for some time to avoid further timeouts
243 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
244
245 return false;
246 }
247 if ( $this->password !== null ) {
248 if ( !$conn->auth( $this->password ) ) {
249 $this->logger->error(
250 'Authentication error connecting to "{redis_server}"',
251 array( 'redis_server' => $server )
252 );
253 }
254 }
255 } catch ( RedisException $e ) {
256 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
257 $this->logger->error(
258 'Redis exception connecting to "{redis_server}"',
259 array(
260 'redis_server' => $server,
261 'exception' => $e,
262 )
263 );
264
265 return false;
266 }
267
268 if ( $conn ) {
269 $conn->setOption( Redis::OPT_READ_TIMEOUT, $this->readTimeout );
270 $conn->setOption( Redis::OPT_SERIALIZER, $this->serializer );
271 $this->connections[$server][] = array( 'conn' => $conn, 'free' => false );
272
273 return new RedisConnRef( $this, $server, $conn, $this->logger );
274 } else {
275 return false;
276 }
277 }
278
279 /**
280 * Mark a connection to a server as free to return to the pool
281 *
282 * @param string $server
283 * @param Redis $conn
284 * @return bool
285 */
286 public function freeConnection( $server, Redis $conn ) {
287 $found = false;
288
289 foreach ( $this->connections[$server] as &$connection ) {
290 if ( $connection['conn'] === $conn && !$connection['free'] ) {
291 $connection['free'] = true;
292 ++$this->idlePoolSize;
293 break;
294 }
295 }
296
297 $this->closeExcessIdleConections();
298
299 return $found;
300 }
301
302 /**
303 * Close any extra idle connections if there are more than the limit
304 */
305 protected function closeExcessIdleConections() {
306 if ( $this->idlePoolSize <= count( $this->connections ) ) {
307 return; // nothing to do (no more connections than servers)
308 }
309
310 foreach ( $this->connections as &$serverConnections ) {
311 foreach ( $serverConnections as $key => &$connection ) {
312 if ( $connection['free'] ) {
313 unset( $serverConnections[$key] );
314 if ( --$this->idlePoolSize <= count( $this->connections ) ) {
315 return; // done (no more connections than servers)
316 }
317 }
318 }
319 }
320 }
321
322 /**
323 * The redis extension throws an exception in response to various read, write
324 * and protocol errors. Sometimes it also closes the connection, sometimes
325 * not. The safest response for us is to explicitly destroy the connection
326 * object and let it be reopened during the next request.
327 *
328 * @param string $server
329 * @param RedisConnRef $cref
330 * @param RedisException $e
331 * @deprecated since 1.23
332 */
333 public function handleException( $server, RedisConnRef $cref, RedisException $e ) {
334 $this->handleError( $cref, $e );
335 }
336
337 /**
338 * The redis extension throws an exception in response to various read, write
339 * and protocol errors. Sometimes it also closes the connection, sometimes
340 * not. The safest response for us is to explicitly destroy the connection
341 * object and let it be reopened during the next request.
342 *
343 * @param RedisConnRef $cref
344 * @param RedisException $e
345 */
346 public function handleError( RedisConnRef $cref, RedisException $e ) {
347 $server = $cref->getServer();
348 $this->logger->error(
349 'Redis exception on server "{redis_server}"',
350 array(
351 'redis_server' => $server,
352 'exception' => $e,
353 )
354 );
355 foreach ( $this->connections[$server] as $key => $connection ) {
356 if ( $cref->isConnIdentical( $connection['conn'] ) ) {
357 $this->idlePoolSize -= $connection['free'] ? 1 : 0;
358 unset( $this->connections[$server][$key] );
359 break;
360 }
361 }
362 }
363
364 /**
365 * Re-send an AUTH request to the redis server (useful after disconnects).
366 *
367 * This works around an upstream bug in phpredis. phpredis hides disconnects by transparently
368 * reconnecting, but it neglects to re-authenticate the new connection. To the user of the
369 * phpredis client API this manifests as a seemingly random tendency of connections to lose
370 * their authentication status.
371 *
372 * This method is for internal use only.
373 *
374 * @see https://github.com/nicolasff/phpredis/issues/403
375 *
376 * @param string $server
377 * @param Redis $conn
378 * @return bool Success
379 */
380 public function reauthenticateConnection( $server, Redis $conn ) {
381 if ( $this->password !== null ) {
382 if ( !$conn->auth( $this->password ) ) {
383 $this->logger->error(
384 'Authentication error connecting to "{redis_server}"',
385 array( 'redis_server' => $server )
386 );
387
388 return false;
389 }
390 }
391
392 return true;
393 }
394
395 /**
396 * Adjust or reset the connection handle read timeout value
397 *
398 * @param Redis $conn
399 * @param int $timeout Optional
400 */
401 public function resetTimeout( Redis $conn, $timeout = null ) {
402 $conn->setOption( Redis::OPT_READ_TIMEOUT, $timeout ?: $this->readTimeout );
403 }
404
405 /**
406 * Make sure connections are closed for sanity
407 */
408 function __destruct() {
409 foreach ( $this->connections as $server => &$serverConnections ) {
410 foreach ( $serverConnections as $key => &$connection ) {
411 $connection['conn']->close();
412 }
413 }
414 }
415 }
416
417 /**
418 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
419 *
420 * This class simply wraps the Redis class and can be used the same way
421 *
422 * @ingroup Redis
423 * @since 1.21
424 */
425 class RedisConnRef {
426 /** @var RedisConnectionPool */
427 protected $pool;
428 /** @var Redis */
429 protected $conn;
430
431 protected $server; // string
432 protected $lastError; // string
433
434 /**
435 * @var LoggerInterface
436 */
437 protected $logger;
438
439 /**
440 * @param RedisConnectionPool $pool
441 * @param string $server
442 * @param Redis $conn
443 * @param LoggerInterface $logger
444 */
445 public function __construct( RedisConnectionPool $pool, $server, Redis $conn, LoggerInterface $logger ) {
446 $this->pool = $pool;
447 $this->server = $server;
448 $this->conn = $conn;
449 $this->logger = $logger;
450 }
451
452 /**
453 * @return string
454 * @since 1.23
455 */
456 public function getServer() {
457 return $this->server;
458 }
459
460 public function getLastError() {
461 return $this->lastError;
462 }
463
464 public function clearLastError() {
465 $this->lastError = null;
466 }
467
468 public function __call( $name, $arguments ) {
469 $conn = $this->conn; // convenience
470
471 // Work around https://github.com/nicolasff/phpredis/issues/70
472 $lname = strtolower( $name );
473 if ( ( $lname === 'blpop' || $lname == 'brpop' )
474 && is_array( $arguments[0] ) && isset( $arguments[1] )
475 ) {
476 $this->pool->resetTimeout( $conn, $arguments[1] + 1 );
477 } elseif ( $lname === 'brpoplpush' && isset( $arguments[2] ) ) {
478 $this->pool->resetTimeout( $conn, $arguments[2] + 1 );
479 }
480
481 $conn->clearLastError();
482 try {
483 $res = call_user_func_array( array( $conn, $name ), $arguments );
484 if ( preg_match( '/^ERR operation not permitted\b/', $conn->getLastError() ) ) {
485 $this->pool->reauthenticateConnection( $this->server, $conn );
486 $conn->clearLastError();
487 $res = call_user_func_array( array( $conn, $name ), $arguments );
488 $this->logger->info(
489 "Used automatic re-authentication for method '$name'.",
490 array( 'redis_server' => $this->server )
491 );
492 }
493 } catch ( RedisException $e ) {
494 $this->pool->resetTimeout( $conn ); // restore
495 throw $e;
496 }
497
498 $this->lastError = $conn->getLastError() ?: $this->lastError;
499
500 $this->pool->resetTimeout( $conn ); // restore
501
502 return $res;
503 }
504
505 /**
506 * @param string $script
507 * @param array $params
508 * @param int $numKeys
509 * @return mixed
510 * @throws RedisException
511 */
512 public function luaEval( $script, array $params, $numKeys ) {
513 $sha1 = sha1( $script ); // 40 char hex
514 $conn = $this->conn; // convenience
515 $server = $this->server; // convenience
516
517 // Try to run the server-side cached copy of the script
518 $conn->clearLastError();
519 $res = $conn->evalSha( $sha1, $params, $numKeys );
520 // If we got a permission error reply that means that (a) we are not in
521 // multi()/pipeline() and (b) some connection problem likely occurred. If
522 // the password the client gave was just wrong, an exception should have
523 // been thrown back in getConnection() previously.
524 if ( preg_match( '/^ERR operation not permitted\b/', $conn->getLastError() ) ) {
525 $this->pool->reauthenticateConnection( $server, $conn );
526 $conn->clearLastError();
527 $res = $conn->eval( $script, $params, $numKeys );
528 $this->logger->info(
529 "Used automatic re-authentication for Lua script '$sha1'.",
530 array( 'redis_server' => $server )
531 );
532 }
533 // If the script is not in cache, use eval() to retry and cache it
534 if ( preg_match( '/^NOSCRIPT/', $conn->getLastError() ) ) {
535 $conn->clearLastError();
536 $res = $conn->eval( $script, $params, $numKeys );
537 $this->logger->info(
538 "Used eval() for Lua script '$sha1'.",
539 array( 'redis_server' => $server )
540 );
541 }
542
543 if ( $conn->getLastError() ) { // script bug?
544 $this->logger->error(
545 'Lua script error on server "{redis_server}": {lua_error}',
546 array(
547 'redis_server' => $server,
548 'lua_error' => $conn->getLastError()
549 )
550 );
551 }
552
553 $this->lastError = $conn->getLastError() ?: $this->lastError;
554
555 return $res;
556 }
557
558 /**
559 * @param Redis $conn
560 * @return bool
561 */
562 public function isConnIdentical( Redis $conn ) {
563 return $this->conn === $conn;
564 }
565
566 function __destruct() {
567 $this->pool->freeConnection( $this->server, $this->conn );
568 }
569 }