Merge "API: Fix parameter validation in setnotificationtimestamp"
[lhc/web/wiklou.git] / includes / clientpool / RedisConnectionPool.php
1 <?php
2 /**
3 * PhpRedis 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 using PhpRedis.
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 // Settings for all connections in this pool
40 protected $connectTimeout; // string; connection timeout
41 protected $persistent; // bool; whether connections persist
42 protected $password; // string; plaintext auth password
43 protected $serializer; // integer; the serializer to use (Redis::SERIALIZER_*)
44
45 protected $idlePoolSize = 0; // integer; current idle pool size
46
47 /** @var Array (server name => ((connection info array),...) */
48 protected $connections = array();
49 /** @var Array (server name => UNIX timestamp) */
50 protected $downServers = array();
51
52 /** @var Array */
53 protected static $instances = array(); // (pool ID => RedisConnectionPool)
54
55 const SERVER_DOWN_TTL = 30; // integer; seconds to cache servers as "down"
56
57 /**
58 * @param array $options
59 */
60 protected function __construct( array $options ) {
61 if ( !extension_loaded( 'redis' ) ) {
62 throw new MWException( __CLASS__. ' requires the phpredis extension: ' .
63 'https://github.com/nicolasff/phpredis' );
64 }
65 $this->connectTimeout = $options['connectTimeout'];
66 $this->persistent = $options['persistent'];
67 $this->password = $options['password'];
68 if ( !isset( $options['serializer'] ) || $options['serializer'] === 'php' ) {
69 $this->serializer = Redis::SERIALIZER_PHP;
70 } elseif ( $options['serializer'] === 'igbinary' ) {
71 $this->serializer = Redis::SERIALIZER_IGBINARY;
72 } elseif ( $options['serializer'] === 'none' ) {
73 $this->serializer = Redis::SERIALIZER_NONE;
74 } else {
75 throw new MWException( "Invalid serializer specified." );
76 }
77 }
78
79 /**
80 * @param $options Array
81 * @return Array
82 */
83 protected static function applyDefaultConfig( array $options ) {
84 if ( !isset( $options['connectTimeout'] ) ) {
85 $options['connectTimeout'] = 1;
86 }
87 if ( !isset( $options['persistent'] ) ) {
88 $options['persistent'] = false;
89 }
90 if ( !isset( $options['password'] ) ) {
91 $options['password'] = null;
92 }
93 return $options;
94 }
95
96 /**
97 * @param $options Array
98 * $options include:
99 * - connectTimeout : The timeout for new connections, in seconds.
100 * Optional, default is 1 second.
101 * - persistent : Set this to true to allow connections to persist across
102 * multiple web requests. False by default.
103 * - password : The authentication password, will be sent to Redis in clear text.
104 * Optional, if it is unspecified, no AUTH command will be sent.
105 * - serializer : Set to "php", "igbinary", or "none". Default is "php".
106 * @return RedisConnectionPool
107 */
108 public static function singleton( array $options ) {
109 $options = self::applyDefaultConfig( $options );
110 // Map the options to a unique hash...
111 ksort( $options ); // normalize to avoid pool fragmentation
112 $id = sha1( serialize( $options ) );
113 // Initialize the object at the hash as needed...
114 if ( !isset( self::$instances[$id] ) ) {
115 self::$instances[$id] = new self( $options );
116 wfDebug( "Creating a new " . __CLASS__ . " instance with id $id." );
117 }
118 return self::$instances[$id];
119 }
120
121 /**
122 * Get a connection to a redis server. Based on code in RedisBagOStuff.php.
123 *
124 * @param string $server A hostname/port combination or the absolute path of a UNIX socket.
125 * If a hostname is specified but no port, port 6379 will be used.
126 * @return RedisConnRef|bool Returns false on failure
127 * @throws MWException
128 */
129 public function getConnection( $server ) {
130 // Check the listing "dead" servers which have had a connection errors.
131 // Servers are marked dead for a limited period of time, to
132 // avoid excessive overhead from repeated connection timeouts.
133 if ( isset( $this->downServers[$server] ) ) {
134 $now = time();
135 if ( $now > $this->downServers[$server] ) {
136 // Dead time expired
137 unset( $this->downServers[$server] );
138 } else {
139 // Server is dead
140 wfDebug( "server $server is marked down for another " .
141 ( $this->downServers[$server] - $now ) . " seconds, can't get connection" );
142 return false;
143 }
144 }
145
146 // Check if a connection is already free for use
147 if ( isset( $this->connections[$server] ) ) {
148 foreach ( $this->connections[$server] as &$connection ) {
149 if ( $connection['free'] ) {
150 $connection['free'] = false;
151 --$this->idlePoolSize;
152 return new RedisConnRef( $this, $server, $connection['conn'] );
153 }
154 }
155 }
156
157 if ( substr( $server, 0, 1 ) === '/' ) {
158 // UNIX domain socket
159 // These are required by the redis extension to start with a slash, but
160 // we still need to set the port to a special value to make it work.
161 $host = $server;
162 $port = 0;
163 } else {
164 // TCP connection
165 $hostPort = IP::splitHostAndPort( $server );
166 if ( !$hostPort ) {
167 throw new MWException( __CLASS__.": invalid configured server \"$server\"" );
168 }
169 list( $host, $port ) = $hostPort;
170 if ( $port === false ) {
171 $port = 6379;
172 }
173 }
174
175 $conn = new Redis();
176 try {
177 if ( $this->persistent ) {
178 $result = $conn->pconnect( $host, $port, $this->connectTimeout );
179 } else {
180 $result = $conn->connect( $host, $port, $this->connectTimeout );
181 }
182 if ( !$result ) {
183 wfDebugLog( 'redis', "Could not connect to server $server" );
184 // Mark server down for some time to avoid further timeouts
185 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
186 return false;
187 }
188 if ( $this->password !== null ) {
189 if ( !$conn->auth( $this->password ) ) {
190 wfDebugLog( 'redis', "Authentication error connecting to $server" );
191 }
192 }
193 } catch ( RedisException $e ) {
194 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
195 wfDebugLog( 'redis', "Redis exception: " . $e->getMessage() . "\n" );
196 return false;
197 }
198
199 if ( $conn ) {
200 $conn->setOption( Redis::OPT_SERIALIZER, $this->serializer );
201 $this->connections[$server][] = array( 'conn' => $conn, 'free' => false );
202 return new RedisConnRef( $this, $server, $conn );
203 } else {
204 return false;
205 }
206 }
207
208 /**
209 * Mark a connection to a server as free to return to the pool
210 *
211 * @param $server string
212 * @param $conn Redis
213 * @return boolean
214 */
215 public function freeConnection( $server, Redis $conn ) {
216 $found = false;
217
218 foreach ( $this->connections[$server] as &$connection ) {
219 if ( $connection['conn'] === $conn && !$connection['free'] ) {
220 $connection['free'] = true;
221 ++$this->idlePoolSize;
222 break;
223 }
224 }
225
226 $this->closeExcessIdleConections();
227
228 return $found;
229 }
230
231 /**
232 * Close any extra idle connections if there are more than the limit
233 *
234 * @return void
235 */
236 protected function closeExcessIdleConections() {
237 if ( $this->idlePoolSize <= count( $this->connections ) ) {
238 return; // nothing to do (no more connections than servers)
239 }
240
241 foreach ( $this->connections as $server => &$serverConnections ) {
242 foreach ( $serverConnections as $key => &$connection ) {
243 if ( $connection['free'] ) {
244 unset( $serverConnections[$key] );
245 if ( --$this->idlePoolSize <= count( $this->connections ) ) {
246 return; // done (no more connections than servers)
247 }
248 }
249 }
250 }
251 }
252
253 /**
254 * The redis extension throws an exception in response to various read, write
255 * and protocol errors. Sometimes it also closes the connection, sometimes
256 * not. The safest response for us is to explicitly destroy the connection
257 * object and let it be reopened during the next request.
258 *
259 * @param $server string
260 * @param $cref RedisConnRef
261 * @param $e RedisException
262 * @return void
263 */
264 public function handleException( $server, RedisConnRef $cref, RedisException $e ) {
265 wfDebugLog( 'redis', "Redis exception on server $server: " . $e->getMessage() . "\n" );
266 foreach ( $this->connections[$server] as $key => $connection ) {
267 if ( $cref->isConnIdentical( $connection['conn'] ) ) {
268 $this->idlePoolSize -= $connection['free'] ? 1 : 0;
269 unset( $this->connections[$server][$key] );
270 break;
271 }
272 }
273 }
274 }
275
276 /**
277 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
278 *
279 * @ingroup Redis
280 * @since 1.21
281 */
282 class RedisConnRef {
283 /** @var RedisConnectionPool */
284 protected $pool;
285 /** @var Redis */
286 protected $conn;
287
288 protected $server; // string
289
290 /**
291 * @param $pool RedisConnectionPool
292 * @param $server string
293 * @param $conn Redis
294 */
295 public function __construct( RedisConnectionPool $pool, $server, Redis $conn ) {
296 $this->pool = $pool;
297 $this->server = $server;
298 $this->conn = $conn;
299 }
300
301 public function __call( $name, $arguments ) {
302 return call_user_func_array( array( $this->conn, $name ), $arguments );
303 }
304
305 public function isConnIdentical( Redis $conn ) {
306 return $this->conn === $conn;
307 }
308
309 function __destruct() {
310 $this->pool->freeConnection( $this->server, $this->conn );
311 }
312 }