Add missing line breaks to wfDebug() calls
[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 /**
26 * Helper class to manage Redis connections.
27 *
28 * This can be used to get handle wrappers that free the handle when the wrapper
29 * leaves scope. The maximum number of free handles (connections) is configurable.
30 * This provides an easy way to cache connection handles that may also have state,
31 * such as a handle does between multi() and exec(), and without hoarding connections.
32 * The wrappers use PHP magic methods so that calling functions on them calls the
33 * function of the actual Redis object handle.
34 *
35 * @ingroup Redis
36 * @since 1.21
37 */
38 class RedisConnectionPool {
39 /**
40 * @name Pool settings.
41 * Settings there are shared for any connection made in this pool.
42 * See the singleton() method documentation for more details.
43 * @{
44 */
45 /** @var string Connection timeout in seconds */
46 protected $connectTimeout;
47 /** @var string Plaintext auth password */
48 protected $password;
49 /** @var bool Whether connections persist */
50 protected $persistent;
51 /** @var integer Serializer to use (Redis::SERIALIZER_*) */
52 protected $serializer;
53 /** @} */
54
55 /** @var int Current idle pool size */
56 protected $idlePoolSize = 0;
57
58 /** @var array (server name => ((connection info array),...) */
59 protected $connections = array();
60 /** @var array (server name => UNIX timestamp) */
61 protected $downServers = array();
62
63 /** @var array (pool ID => RedisConnectionPool) */
64 protected static $instances = array();
65
66 /** integer; seconds to cache servers as "down". */
67 const SERVER_DOWN_TTL = 30;
68
69 /**
70 * @param array $options
71 * @throws MWException
72 */
73 protected function __construct( array $options ) {
74 if ( !class_exists( 'Redis' ) ) {
75 throw new MWException( __CLASS__ . ' requires a Redis client library. ' .
76 'See https://www.mediawiki.org/wiki/Redis#Setup' );
77 }
78 $this->connectTimeout = $options['connectTimeout'];
79 $this->persistent = $options['persistent'];
80 $this->password = $options['password'];
81 if ( !isset( $options['serializer'] ) || $options['serializer'] === 'php' ) {
82 $this->serializer = Redis::SERIALIZER_PHP;
83 } elseif ( $options['serializer'] === 'igbinary' ) {
84 $this->serializer = Redis::SERIALIZER_IGBINARY;
85 } elseif ( $options['serializer'] === 'none' ) {
86 $this->serializer = Redis::SERIALIZER_NONE;
87 } else {
88 throw new MWException( "Invalid serializer specified." );
89 }
90 }
91
92 /**
93 * @param array $options
94 * @return array
95 */
96 protected static function applyDefaultConfig( array $options ) {
97 if ( !isset( $options['connectTimeout'] ) ) {
98 $options['connectTimeout'] = 1;
99 }
100 if ( !isset( $options['persistent'] ) ) {
101 $options['persistent'] = false;
102 }
103 if ( !isset( $options['password'] ) ) {
104 $options['password'] = null;
105 }
106
107 return $options;
108 }
109
110 /**
111 * @param array $options
112 * $options include:
113 * - connectTimeout : The timeout for new connections, in seconds.
114 * Optional, default is 1 second.
115 * - persistent : Set this to true to allow connections to persist across
116 * multiple web requests. False by default.
117 * - password : The authentication password, will be sent to Redis in clear text.
118 * Optional, if it is unspecified, no AUTH command will be sent.
119 * - serializer : Set to "php", "igbinary", or "none". Default is "php".
120 * @return RedisConnectionPool
121 */
122 public static function singleton( array $options ) {
123 $options = self::applyDefaultConfig( $options );
124 // Map the options to a unique hash...
125 ksort( $options ); // normalize to avoid pool fragmentation
126 $id = sha1( serialize( $options ) );
127 // Initialize the object at the hash as needed...
128 if ( !isset( self::$instances[$id] ) ) {
129 self::$instances[$id] = new self( $options );
130 wfDebug( "Creating a new " . __CLASS__ . " instance with id $id.\n" );
131 }
132
133 return self::$instances[$id];
134 }
135
136 /**
137 * Get a connection to a redis server. Based on code in RedisBagOStuff.php.
138 *
139 * @param string $server A hostname/port combination or the absolute path of a UNIX socket.
140 * If a hostname is specified but no port, port 6379 will be used.
141 * @return RedisConnRef|bool Returns false on failure
142 * @throws MWException
143 */
144 public function getConnection( $server ) {
145 // Check the listing "dead" servers which have had a connection errors.
146 // Servers are marked dead for a limited period of time, to
147 // avoid excessive overhead from repeated connection timeouts.
148 if ( isset( $this->downServers[$server] ) ) {
149 $now = time();
150 if ( $now > $this->downServers[$server] ) {
151 // Dead time expired
152 unset( $this->downServers[$server] );
153 } else {
154 // Server is dead
155 wfDebug( "server $server is marked down for another " .
156 ( $this->downServers[$server] - $now ) . " seconds, can't get connection\n" );
157
158 return false;
159 }
160 }
161
162 // Check if a connection is already free for use
163 if ( isset( $this->connections[$server] ) ) {
164 foreach ( $this->connections[$server] as &$connection ) {
165 if ( $connection['free'] ) {
166 $connection['free'] = false;
167 --$this->idlePoolSize;
168
169 return new RedisConnRef( $this, $server, $connection['conn'] );
170 }
171 }
172 }
173
174 if ( substr( $server, 0, 1 ) === '/' ) {
175 // UNIX domain socket
176 // These are required by the redis extension to start with a slash, but
177 // we still need to set the port to a special value to make it work.
178 $host = $server;
179 $port = 0;
180 } else {
181 // TCP connection
182 $hostPort = IP::splitHostAndPort( $server );
183 if ( !$hostPort ) {
184 throw new MWException( __CLASS__ . ": invalid configured server \"$server\"" );
185 }
186 list( $host, $port ) = $hostPort;
187 if ( $port === false ) {
188 $port = 6379;
189 }
190 }
191
192 $conn = new Redis();
193 try {
194 if ( $this->persistent ) {
195 $result = $conn->pconnect( $host, $port, $this->connectTimeout );
196 } else {
197 $result = $conn->connect( $host, $port, $this->connectTimeout );
198 }
199 if ( !$result ) {
200 wfDebugLog( 'redis', "Could not connect to server $server" );
201 // Mark server down for some time to avoid further timeouts
202 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
203
204 return false;
205 }
206 if ( $this->password !== null ) {
207 if ( !$conn->auth( $this->password ) ) {
208 wfDebugLog( 'redis', "Authentication error connecting to $server" );
209 }
210 }
211 } catch ( RedisException $e ) {
212 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
213 wfDebugLog( 'redis', "Redis exception connecting to $server: " . $e->getMessage() );
214
215 return false;
216 }
217
218 if ( $conn ) {
219 $conn->setOption( Redis::OPT_SERIALIZER, $this->serializer );
220 $this->connections[$server][] = array( 'conn' => $conn, 'free' => false );
221
222 return new RedisConnRef( $this, $server, $conn );
223 } else {
224 return false;
225 }
226 }
227
228 /**
229 * Mark a connection to a server as free to return to the pool
230 *
231 * @param string $server
232 * @param Redis $conn
233 * @return bool
234 */
235 public function freeConnection( $server, Redis $conn ) {
236 $found = false;
237
238 foreach ( $this->connections[$server] as &$connection ) {
239 if ( $connection['conn'] === $conn && !$connection['free'] ) {
240 $connection['free'] = true;
241 ++$this->idlePoolSize;
242 break;
243 }
244 }
245
246 $this->closeExcessIdleConections();
247
248 return $found;
249 }
250
251 /**
252 * Close any extra idle connections if there are more than the limit
253 */
254 protected function closeExcessIdleConections() {
255 if ( $this->idlePoolSize <= count( $this->connections ) ) {
256 return; // nothing to do (no more connections than servers)
257 }
258
259 foreach ( $this->connections as &$serverConnections ) {
260 foreach ( $serverConnections as $key => &$connection ) {
261 if ( $connection['free'] ) {
262 unset( $serverConnections[$key] );
263 if ( --$this->idlePoolSize <= count( $this->connections ) ) {
264 return; // done (no more connections than servers)
265 }
266 }
267 }
268 }
269 }
270
271 /**
272 * The redis extension throws an exception in response to various read, write
273 * and protocol errors. Sometimes it also closes the connection, sometimes
274 * not. The safest response for us is to explicitly destroy the connection
275 * object and let it be reopened during the next request.
276 *
277 * @param string $server
278 * @param RedisConnRef $cref
279 * @param RedisException $e
280 * @deprecated 1.23
281 */
282 public function handleException( $server, RedisConnRef $cref, RedisException $e ) {
283 return $this->handleError( $cref, $e );
284 }
285
286 /**
287 * The redis extension throws an exception in response to various read, write
288 * and protocol errors. Sometimes it also closes the connection, sometimes
289 * not. The safest response for us is to explicitly destroy the connection
290 * object and let it be reopened during the next request.
291 *
292 * @param RedisConnRef $cref
293 * @param RedisException $e
294 */
295 public function handleError( RedisConnRef $cref, RedisException $e ) {
296 $server = $cref->getServer();
297 wfDebugLog( 'redis', "Redis exception on server $server: " . $e->getMessage() . "\n" );
298 foreach ( $this->connections[$server] as $key => $connection ) {
299 if ( $cref->isConnIdentical( $connection['conn'] ) ) {
300 $this->idlePoolSize -= $connection['free'] ? 1 : 0;
301 unset( $this->connections[$server][$key] );
302 break;
303 }
304 }
305 }
306
307 /**
308 * Re-send an AUTH request to the redis server (useful after disconnects).
309 *
310 * This works around an upstream bug in phpredis. phpredis hides disconnects by transparently
311 * reconnecting, but it neglects to re-authenticate the new connection. To the user of the
312 * phpredis client API this manifests as a seemingly random tendency of connections to lose
313 * their authentication status.
314 *
315 * This method is for internal use only.
316 *
317 * @see https://github.com/nicolasff/phpredis/issues/403
318 *
319 * @param string $server
320 * @param Redis $conn
321 * @return bool Success
322 */
323 public function reauthenticateConnection( $server, Redis $conn ) {
324 if ( $this->password !== null ) {
325 if ( !$conn->auth( $this->password ) ) {
326 wfDebugLog( 'redis', "Authentication error connecting to $server" );
327
328 return false;
329 }
330 }
331
332 return true;
333 }
334
335 /**
336 * Make sure connections are closed for sanity
337 */
338 function __destruct() {
339 foreach ( $this->connections as $server => &$serverConnections ) {
340 foreach ( $serverConnections as $key => &$connection ) {
341 $connection['conn']->close();
342 }
343 }
344 }
345 }
346
347 /**
348 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
349 *
350 * This class simply wraps the Redis class and can be used the same way
351 *
352 * @ingroup Redis
353 * @since 1.21
354 */
355 class RedisConnRef {
356 /** @var RedisConnectionPool */
357 protected $pool;
358 /** @var Redis */
359 protected $conn;
360
361 protected $server; // string
362 protected $lastError; // string
363
364 /**
365 * @param RedisConnectionPool $pool
366 * @param string $server
367 * @param Redis $conn
368 */
369 public function __construct( RedisConnectionPool $pool, $server, Redis $conn ) {
370 $this->pool = $pool;
371 $this->server = $server;
372 $this->conn = $conn;
373 }
374
375 /**
376 * @return string
377 * @since 1.23
378 */
379 public function getServer() {
380 return $this->server;
381 }
382
383 public function getLastError() {
384 return $this->lastError;
385 }
386
387 public function clearLastError() {
388 $this->lastError = null;
389 }
390
391 public function __call( $name, $arguments ) {
392 $conn = $this->conn; // convenience
393
394 $conn->clearLastError();
395 $res = call_user_func_array( array( $conn, $name ), $arguments );
396 if ( preg_match( '/^ERR operation not permitted\b/', $conn->getLastError() ) ) {
397 $this->pool->reauthenticateConnection( $this->server, $conn );
398 $conn->clearLastError();
399 $res = call_user_func_array( array( $conn, $name ), $arguments );
400 wfDebugLog( 'redis', "Used automatic re-authentication for method '$name'." );
401 }
402
403 $this->lastError = $conn->getLastError() ?: $this->lastError;
404
405 return $res;
406 }
407
408 /**
409 * @param string $script
410 * @param array $params
411 * @param integer $numKeys
412 * @return mixed
413 * @throws RedisException
414 */
415 public function luaEval( $script, array $params, $numKeys ) {
416 $sha1 = sha1( $script ); // 40 char hex
417 $conn = $this->conn; // convenience
418 $server = $this->server; // convenience
419
420 // Try to run the server-side cached copy of the script
421 $conn->clearLastError();
422 $res = $conn->evalSha( $sha1, $params, $numKeys );
423 // If we got a permission error reply that means that (a) we are not in
424 // multi()/pipeline() and (b) some connection problem likely occured. If
425 // the password the client gave was just wrong, an exception should have
426 // been thrown back in getConnection() previously.
427 if ( preg_match( '/^ERR operation not permitted\b/', $conn->getLastError() ) ) {
428 $this->pool->reauthenticateConnection( $server, $conn );
429 $conn->clearLastError();
430 $res = $conn->eval( $script, $params, $numKeys );
431 wfDebugLog( 'redis', "Used automatic re-authentication for Lua script $sha1." );
432 }
433 // If the script is not in cache, use eval() to retry and cache it
434 if ( preg_match( '/^NOSCRIPT/', $conn->getLastError() ) ) {
435 $conn->clearLastError();
436 $res = $conn->eval( $script, $params, $numKeys );
437 wfDebugLog( 'redis', "Used eval() for Lua script $sha1." );
438 }
439
440 if ( $conn->getLastError() ) { // script bug?
441 wfDebugLog( 'redis', "Lua script error on server $server: " . $conn->getLastError() );
442 }
443
444 $this->lastError = $conn->getLastError() ?: $this->lastError;
445
446 return $res;
447 }
448
449 /**
450 * @param Redis $conn
451 * @return bool
452 */
453 public function isConnIdentical( Redis $conn ) {
454 return $this->conn === $conn;
455 }
456
457 function __destruct() {
458 $this->pool->freeConnection( $this->server, $this->conn );
459 }
460 }