Merge "installer: Remove additional newline in LocalSettings.php"
[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 Exception
83 */
84 protected function __construct( array $options ) {
85 if ( !class_exists( 'Redis' ) ) {
86 throw new Exception( __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 InvalidArgumentException( "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 InvalidArgumentException(
223 __CLASS__ . ": invalid configured server \"$server\""
224 );
225 }
226 list( $host, $port ) = $hostPort;
227 if ( $port === false ) {
228 $port = 6379;
229 }
230 }
231
232 $conn = new Redis();
233 try {
234 if ( $this->persistent ) {
235 $result = $conn->pconnect( $host, $port, $this->connectTimeout );
236 } else {
237 $result = $conn->connect( $host, $port, $this->connectTimeout );
238 }
239 if ( !$result ) {
240 $this->logger->error(
241 'Could not connect to server "{redis_server}"',
242 array( 'redis_server' => $server )
243 );
244 // Mark server down for some time to avoid further timeouts
245 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
246
247 return false;
248 }
249 if ( $this->password !== null ) {
250 if ( !$conn->auth( $this->password ) ) {
251 $this->logger->error(
252 'Authentication error connecting to "{redis_server}"',
253 array( 'redis_server' => $server )
254 );
255 }
256 }
257 } catch ( RedisException $e ) {
258 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
259 $this->logger->error(
260 'Redis exception connecting to "{redis_server}"',
261 array(
262 'redis_server' => $server,
263 'exception' => $e,
264 )
265 );
266
267 return false;
268 }
269
270 if ( $conn ) {
271 $conn->setOption( Redis::OPT_READ_TIMEOUT, $this->readTimeout );
272 $conn->setOption( Redis::OPT_SERIALIZER, $this->serializer );
273 $this->connections[$server][] = array( 'conn' => $conn, 'free' => false );
274
275 return new RedisConnRef( $this, $server, $conn, $this->logger );
276 } else {
277 return false;
278 }
279 }
280
281 /**
282 * Mark a connection to a server as free to return to the pool
283 *
284 * @param string $server
285 * @param Redis $conn
286 * @return bool
287 */
288 public function freeConnection( $server, Redis $conn ) {
289 $found = false;
290
291 foreach ( $this->connections[$server] as &$connection ) {
292 if ( $connection['conn'] === $conn && !$connection['free'] ) {
293 $connection['free'] = true;
294 ++$this->idlePoolSize;
295 break;
296 }
297 }
298
299 $this->closeExcessIdleConections();
300
301 return $found;
302 }
303
304 /**
305 * Close any extra idle connections if there are more than the limit
306 */
307 protected function closeExcessIdleConections() {
308 if ( $this->idlePoolSize <= count( $this->connections ) ) {
309 return; // nothing to do (no more connections than servers)
310 }
311
312 foreach ( $this->connections as &$serverConnections ) {
313 foreach ( $serverConnections as $key => &$connection ) {
314 if ( $connection['free'] ) {
315 unset( $serverConnections[$key] );
316 if ( --$this->idlePoolSize <= count( $this->connections ) ) {
317 return; // done (no more connections than servers)
318 }
319 }
320 }
321 }
322 }
323
324 /**
325 * The redis extension throws an exception in response to various read, write
326 * and protocol errors. Sometimes it also closes the connection, sometimes
327 * not. The safest response for us is to explicitly destroy the connection
328 * object and let it be reopened during the next request.
329 *
330 * @param string $server
331 * @param RedisConnRef $cref
332 * @param RedisException $e
333 * @deprecated since 1.23
334 */
335 public function handleException( $server, RedisConnRef $cref, RedisException $e ) {
336 $this->handleError( $cref, $e );
337 }
338
339 /**
340 * The redis extension throws an exception in response to various read, write
341 * and protocol errors. Sometimes it also closes the connection, sometimes
342 * not. The safest response for us is to explicitly destroy the connection
343 * object and let it be reopened during the next request.
344 *
345 * @param RedisConnRef $cref
346 * @param RedisException $e
347 */
348 public function handleError( RedisConnRef $cref, RedisException $e ) {
349 $server = $cref->getServer();
350 $this->logger->error(
351 'Redis exception on server "{redis_server}"',
352 array(
353 'redis_server' => $server,
354 'exception' => $e,
355 )
356 );
357 foreach ( $this->connections[$server] as $key => $connection ) {
358 if ( $cref->isConnIdentical( $connection['conn'] ) ) {
359 $this->idlePoolSize -= $connection['free'] ? 1 : 0;
360 unset( $this->connections[$server][$key] );
361 break;
362 }
363 }
364 }
365
366 /**
367 * Re-send an AUTH request to the redis server (useful after disconnects).
368 *
369 * This works around an upstream bug in phpredis. phpredis hides disconnects by transparently
370 * reconnecting, but it neglects to re-authenticate the new connection. To the user of the
371 * phpredis client API this manifests as a seemingly random tendency of connections to lose
372 * their authentication status.
373 *
374 * This method is for internal use only.
375 *
376 * @see https://github.com/nicolasff/phpredis/issues/403
377 *
378 * @param string $server
379 * @param Redis $conn
380 * @return bool Success
381 */
382 public function reauthenticateConnection( $server, Redis $conn ) {
383 if ( $this->password !== null ) {
384 if ( !$conn->auth( $this->password ) ) {
385 $this->logger->error(
386 'Authentication error connecting to "{redis_server}"',
387 array( 'redis_server' => $server )
388 );
389
390 return false;
391 }
392 }
393
394 return true;
395 }
396
397 /**
398 * Adjust or reset the connection handle read timeout value
399 *
400 * @param Redis $conn
401 * @param int $timeout Optional
402 */
403 public function resetTimeout( Redis $conn, $timeout = null ) {
404 $conn->setOption( Redis::OPT_READ_TIMEOUT, $timeout ?: $this->readTimeout );
405 }
406
407 /**
408 * Make sure connections are closed for sanity
409 */
410 function __destruct() {
411 foreach ( $this->connections as $server => &$serverConnections ) {
412 foreach ( $serverConnections as $key => &$connection ) {
413 $connection['conn']->close();
414 }
415 }
416 }
417 }
418
419 /**
420 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
421 *
422 * This class simply wraps the Redis class and can be used the same way
423 *
424 * @ingroup Redis
425 * @since 1.21
426 */
427 class RedisConnRef {
428 /** @var RedisConnectionPool */
429 protected $pool;
430 /** @var Redis */
431 protected $conn;
432
433 protected $server; // string
434 protected $lastError; // string
435
436 /**
437 * @var LoggerInterface
438 */
439 protected $logger;
440
441 /**
442 * @param RedisConnectionPool $pool
443 * @param string $server
444 * @param Redis $conn
445 * @param LoggerInterface $logger
446 */
447 public function __construct(
448 RedisConnectionPool $pool, $server, Redis $conn, LoggerInterface $logger
449 ) {
450 $this->pool = $pool;
451 $this->server = $server;
452 $this->conn = $conn;
453 $this->logger = $logger;
454 }
455
456 /**
457 * @return string
458 * @since 1.23
459 */
460 public function getServer() {
461 return $this->server;
462 }
463
464 public function getLastError() {
465 return $this->lastError;
466 }
467
468 public function clearLastError() {
469 $this->lastError = null;
470 }
471
472 public function __call( $name, $arguments ) {
473 $conn = $this->conn; // convenience
474
475 // Work around https://github.com/nicolasff/phpredis/issues/70
476 $lname = strtolower( $name );
477 if ( ( $lname === 'blpop' || $lname == 'brpop' )
478 && is_array( $arguments[0] ) && isset( $arguments[1] )
479 ) {
480 $this->pool->resetTimeout( $conn, $arguments[1] + 1 );
481 } elseif ( $lname === 'brpoplpush' && isset( $arguments[2] ) ) {
482 $this->pool->resetTimeout( $conn, $arguments[2] + 1 );
483 }
484
485 $conn->clearLastError();
486 try {
487 $res = call_user_func_array( array( $conn, $name ), $arguments );
488 if ( preg_match( '/^ERR operation not permitted\b/', $conn->getLastError() ) ) {
489 $this->pool->reauthenticateConnection( $this->server, $conn );
490 $conn->clearLastError();
491 $res = call_user_func_array( array( $conn, $name ), $arguments );
492 $this->logger->info(
493 "Used automatic re-authentication for method '$name'.",
494 array( 'redis_server' => $this->server )
495 );
496 }
497 } catch ( RedisException $e ) {
498 $this->pool->resetTimeout( $conn ); // restore
499 throw $e;
500 }
501
502 $this->lastError = $conn->getLastError() ?: $this->lastError;
503
504 $this->pool->resetTimeout( $conn ); // restore
505
506 return $res;
507 }
508
509 /**
510 * @param string $script
511 * @param array $params
512 * @param int $numKeys
513 * @return mixed
514 * @throws RedisException
515 */
516 public function luaEval( $script, array $params, $numKeys ) {
517 $sha1 = sha1( $script ); // 40 char hex
518 $conn = $this->conn; // convenience
519 $server = $this->server; // convenience
520
521 // Try to run the server-side cached copy of the script
522 $conn->clearLastError();
523 $res = $conn->evalSha( $sha1, $params, $numKeys );
524 // If we got a permission error reply that means that (a) we are not in
525 // multi()/pipeline() and (b) some connection problem likely occurred. If
526 // the password the client gave was just wrong, an exception should have
527 // been thrown back in getConnection() previously.
528 if ( preg_match( '/^ERR operation not permitted\b/', $conn->getLastError() ) ) {
529 $this->pool->reauthenticateConnection( $server, $conn );
530 $conn->clearLastError();
531 $res = $conn->eval( $script, $params, $numKeys );
532 $this->logger->info(
533 "Used automatic re-authentication for Lua script '$sha1'.",
534 array( 'redis_server' => $server )
535 );
536 }
537 // If the script is not in cache, use eval() to retry and cache it
538 if ( preg_match( '/^NOSCRIPT/', $conn->getLastError() ) ) {
539 $conn->clearLastError();
540 $res = $conn->eval( $script, $params, $numKeys );
541 $this->logger->info(
542 "Used eval() for Lua script '$sha1'.",
543 array( 'redis_server' => $server )
544 );
545 }
546
547 if ( $conn->getLastError() ) { // script bug?
548 $this->logger->error(
549 'Lua script error on server "{redis_server}": {lua_error}',
550 array(
551 'redis_server' => $server,
552 'lua_error' => $conn->getLastError()
553 )
554 );
555 }
556
557 $this->lastError = $conn->getLastError() ?: $this->lastError;
558
559 return $res;
560 }
561
562 /**
563 * @param Redis $conn
564 * @return bool
565 */
566 public function isConnIdentical( Redis $conn ) {
567 return $this->conn === $conn;
568 }
569
570 function __destruct() {
571 $this->pool->freeConnection( $this->server, $this->conn );
572 }
573 }