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