summaryrefslogtreecommitdiff
path: root/includes/clientpool/RedisConnectionPool.php
blob: ef71b1826ae7d058d8899aa201ffa28146b06284 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
<?php
/**
 * Redis client connection pooling manager.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @defgroup Redis Redis
 * @author Aaron Schulz
 */

/**
 * Helper class to manage Redis connections.
 *
 * This can be used to get handle wrappers that free the handle when the wrapper
 * leaves scope. The maximum number of free handles (connections) is configurable.
 * This provides an easy way to cache connection handles that may also have state,
 * such as a handle does between multi() and exec(), and without hoarding connections.
 * The wrappers use PHP magic methods so that calling functions on them calls the
 * function of the actual Redis object handle.
 *
 * @ingroup Redis
 * @since 1.21
 */
class RedisConnectionPool {
	/**
	 * @name Pool settings.
	 * Settings there are shared for any connection made in this pool.
	 * See the singleton() method documentation for more details.
	 * @{
	 */
	/** @var string Connection timeout in seconds */
	protected $connectTimeout;
	/** @var string Plaintext auth password */
	protected $password;
	/** @var bool Whether connections persist */
	protected $persistent;
	/** @var integer Serializer to use (Redis::SERIALIZER_*) */
	protected $serializer;
	/** @} */

	/** @var integer Current idle pool size */
	protected $idlePoolSize = 0;

	/** @var Array (server name => ((connection info array),...) */
	protected $connections = array();
	/** @var Array (server name => UNIX timestamp) */
	protected $downServers = array();

	/** @var Array (pool ID => RedisConnectionPool) */
	protected static $instances = array();

	/** integer; seconds to cache servers as "down". */
	const SERVER_DOWN_TTL = 30;

	/**
	 * @param array $options
	 */
	protected function __construct( array $options ) {
		if ( !class_exists( 'Redis' ) ) {
			throw new MWException( __CLASS__ . ' requires a Redis client library. ' .
				'See https://www.mediawiki.org/wiki/Redis#Setup' );
		}
		$this->connectTimeout = $options['connectTimeout'];
		$this->persistent = $options['persistent'];
		$this->password = $options['password'];
		if ( !isset( $options['serializer'] ) || $options['serializer'] === 'php' ) {
			$this->serializer = Redis::SERIALIZER_PHP;
		} elseif ( $options['serializer'] === 'igbinary' ) {
			$this->serializer = Redis::SERIALIZER_IGBINARY;
		} elseif ( $options['serializer'] === 'none' ) {
			$this->serializer = Redis::SERIALIZER_NONE;
		} else {
			throw new MWException( "Invalid serializer specified." );
		}
	}

	/**
	 * @param $options Array
	 * @return Array
	 */
	protected static function applyDefaultConfig( array $options ) {
		if ( !isset( $options['connectTimeout'] ) ) {
			$options['connectTimeout'] = 1;
		}
		if ( !isset( $options['persistent'] ) ) {
			$options['persistent'] = false;
		}
		if ( !isset( $options['password'] ) ) {
			$options['password'] = null;
		}
		return $options;
	}

	/**
	 * @param $options Array
	 * $options include:
	 *   - connectTimeout : The timeout for new connections, in seconds.
	 *                      Optional, default is 1 second.
	 *   - persistent     : Set this to true to allow connections to persist across
	 *                      multiple web requests. False by default.
	 *   - password       : The authentication password, will be sent to Redis in clear text.
	 *                      Optional, if it is unspecified, no AUTH command will be sent.
	 *   - serializer     : Set to "php", "igbinary", or "none". Default is "php".
	 * @return RedisConnectionPool
	 */
	public static function singleton( array $options ) {
		$options = self::applyDefaultConfig( $options );
		// Map the options to a unique hash...
		ksort( $options ); // normalize to avoid pool fragmentation
		$id = sha1( serialize( $options ) );
		// Initialize the object at the hash as needed...
		if ( !isset( self::$instances[$id] ) ) {
			self::$instances[$id] = new self( $options );
			wfDebug( "Creating a new " . __CLASS__ . " instance with id $id." );
		}
		return self::$instances[$id];
	}

	/**
	 * Get a connection to a redis server. Based on code in RedisBagOStuff.php.
	 *
	 * @param string $server A hostname/port combination or the absolute path of a UNIX socket.
	 *                       If a hostname is specified but no port, port 6379 will be used.
	 * @return RedisConnRef|bool Returns false on failure
	 * @throws MWException
	 */
	public function getConnection( $server ) {
		// Check the listing "dead" servers which have had a connection errors.
		// Servers are marked dead for a limited period of time, to
		// avoid excessive overhead from repeated connection timeouts.
		if ( isset( $this->downServers[$server] ) ) {
			$now = time();
			if ( $now > $this->downServers[$server] ) {
				// Dead time expired
				unset( $this->downServers[$server] );
			} else {
				// Server is dead
				wfDebug( "server $server is marked down for another " .
					( $this->downServers[$server] - $now ) . " seconds, can't get connection" );
				return false;
			}
		}

		// Check if a connection is already free for use
		if ( isset( $this->connections[$server] ) ) {
			foreach ( $this->connections[$server] as &$connection ) {
				if ( $connection['free'] ) {
					$connection['free'] = false;
					--$this->idlePoolSize;
					return new RedisConnRef( $this, $server, $connection['conn'] );
				}
			}
		}

		if ( substr( $server, 0, 1 ) === '/' ) {
			// UNIX domain socket
			// These are required by the redis extension to start with a slash, but
			// we still need to set the port to a special value to make it work.
			$host = $server;
			$port = 0;
		} else {
			// TCP connection
			$hostPort = IP::splitHostAndPort( $server );
			if ( !$hostPort ) {
				throw new MWException( __CLASS__ . ": invalid configured server \"$server\"" );
			}
			list( $host, $port ) = $hostPort;
			if ( $port === false ) {
				$port = 6379;
			}
		}

		$conn = new Redis();
		try {
			if ( $this->persistent ) {
				$result = $conn->pconnect( $host, $port, $this->connectTimeout );
			} else {
				$result = $conn->connect( $host, $port, $this->connectTimeout );
			}
			if ( !$result ) {
				wfDebugLog( 'redis', "Could not connect to server $server" );
				// Mark server down for some time to avoid further timeouts
				$this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
				return false;
			}
			if ( $this->password !== null ) {
				if ( !$conn->auth( $this->password ) ) {
					wfDebugLog( 'redis', "Authentication error connecting to $server" );
				}
			}
		} catch ( RedisException $e ) {
			$this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
			wfDebugLog( 'redis', "Redis exception: " . $e->getMessage() . "\n" );
			return false;
		}

		if ( $conn ) {
			$conn->setOption( Redis::OPT_SERIALIZER, $this->serializer );
			$this->connections[$server][] = array( 'conn' => $conn, 'free' => false );
			return new RedisConnRef( $this, $server, $conn );
		} else {
			return false;
		}
	}

	/**
	 * Mark a connection to a server as free to return to the pool
	 *
	 * @param $server string
	 * @param $conn Redis
	 * @return boolean
	 */
	public function freeConnection( $server, Redis $conn ) {
		$found = false;

		foreach ( $this->connections[$server] as &$connection ) {
			if ( $connection['conn'] === $conn && !$connection['free'] ) {
				$connection['free'] = true;
				++$this->idlePoolSize;
				break;
			}
		}

		$this->closeExcessIdleConections();

		return $found;
	}

	/**
	 * Close any extra idle connections if there are more than the limit
	 *
	 * @return void
	 */
	protected function closeExcessIdleConections() {
		if ( $this->idlePoolSize <= count( $this->connections ) ) {
			return; // nothing to do (no more connections than servers)
		}

		foreach ( $this->connections as $server => &$serverConnections ) {
			foreach ( $serverConnections as $key => &$connection ) {
				if ( $connection['free'] ) {
					unset( $serverConnections[$key] );
					if ( --$this->idlePoolSize <= count( $this->connections ) ) {
						return; // done (no more connections than servers)
					}
				}
			}
		}
	}

	/**
	 * The redis extension throws an exception in response to various read, write
	 * and protocol errors. Sometimes it also closes the connection, sometimes
	 * not. The safest response for us is to explicitly destroy the connection
	 * object and let it be reopened during the next request.
	 *
	 * @param $server string
	 * @param $cref RedisConnRef
	 * @param $e RedisException
	 * @return void
	 */
	public function handleException( $server, RedisConnRef $cref, RedisException $e ) {
		wfDebugLog( 'redis', "Redis exception on server $server: " . $e->getMessage() . "\n" );
		foreach ( $this->connections[$server] as $key => $connection ) {
			if ( $cref->isConnIdentical( $connection['conn'] ) ) {
				$this->idlePoolSize -= $connection['free'] ? 1 : 0;
				unset( $this->connections[$server][$key] );
				break;
			}
		}
	}
}

/**
 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
 *
 * @ingroup Redis
 * @since 1.21
 */
class RedisConnRef {
	/** @var RedisConnectionPool */
	protected $pool;
	/** @var Redis */
	protected $conn;

	protected $server; // string

	/**
	 * @param $pool RedisConnectionPool
	 * @param $server string
	 * @param $conn Redis
	 */
	public function __construct( RedisConnectionPool $pool, $server, Redis $conn ) {
		$this->pool = $pool;
		$this->server = $server;
		$this->conn = $conn;
	}

	public function __call( $name, $arguments ) {
		return call_user_func_array( array( $this->conn, $name ), $arguments );
	}

	/**
	 * @param string $script
	 * @param array $params
	 * @param integer $numKeys
	 * @return mixed
	 * @throws RedisException
	 */
	public function luaEval( $script, array $params, $numKeys ) {
		$sha1 = sha1( $script ); // 40 char hex
		$conn = $this->conn; // convenience

		// Try to run the server-side cached copy of the script
		$conn->clearLastError();
		$res = $conn->evalSha( $sha1, $params, $numKeys );
		// If the script is not in cache, use eval() to retry and cache it
		if ( preg_match( '/^NOSCRIPT/', $conn->getLastError() ) ) {
			$conn->clearLastError();
			$res = $conn->eval( $script, $params, $numKeys );
			wfDebugLog( 'redis', "Used eval() for Lua script $sha1." );
		}

		if ( $conn->getLastError() ) { // script bug?
			wfDebugLog( 'redis', "Lua script error: " . $conn->getLastError() );
		}

		return $res;
	}

	/**
	 * @param RedisConnRef $conn
	 * @return bool
	 */
	public function isConnIdentical( Redis $conn ) {
		return $this->conn === $conn;
	}

	function __destruct() {
		$this->pool->freeConnection( $this->server, $this->conn );
	}
}