Merge "(Bug 27559) Preserve tab selection after submit in [[Special:Preferences]]"
[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 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 $id = sha1( serialize( $options ) );
102 if ( !isset( self::$instances[$id] ) ) {
103 self::$instances[$id] = new self( $options );
104 wfDebug( "Creating a new " . __CLASS__ . " instance with id $id." );
105 }
106 return self::$instances[$id];
107 }
108
109 /**
110 * Get a connection to a redis server. Based on code in RedisBagOStuff.php.
111 *
112 * @param $server string A hostname/port combination or the absolute path of a UNIX socket.
113 * If a hostname is specified but no port, port 6379 will be used.
114 * @return RedisConnRef|bool Returns false on failure
115 * @throws MWException
116 */
117 public function getConnection( $server ) {
118 // Check the listing "dead" servers which have had a connection errors.
119 // Servers are marked dead for a limited period of time, to
120 // avoid excessive overhead from repeated connection timeouts.
121 if ( isset( $this->downServers[$server] ) ) {
122 $now = time();
123 if ( $now > $this->downServers[$server] ) {
124 // Dead time expired
125 unset( $this->downServers[$server] );
126 } else {
127 // Server is dead
128 wfDebug( "server $server is marked down for another " .
129 ( $this->downServers[$server] - $now ) . " seconds, can't get connection" );
130 return false;
131 }
132 }
133
134 // Check if a connection is already free for use
135 if ( isset( $this->connections[$server] ) ) {
136 foreach ( $this->connections[$server] as &$connection ) {
137 if ( $connection['free'] ) {
138 $connection['free'] = false;
139 --$this->idlePoolSize;
140 return new RedisConnRef( $this, $server, $connection['conn'] );
141 }
142 }
143 }
144
145 if ( substr( $server, 0, 1 ) === '/' ) {
146 // UNIX domain socket
147 // These are required by the redis extension to start with a slash, but
148 // we still need to set the port to a special value to make it work.
149 $host = $server;
150 $port = 0;
151 } else {
152 // TCP connection
153 $hostPort = IP::splitHostAndPort( $server );
154 if ( !$hostPort ) {
155 throw new MWException( __CLASS__.": invalid configured server \"$server\"" );
156 }
157 list( $host, $port ) = $hostPort;
158 if ( $port === false ) {
159 $port = 6379;
160 }
161 }
162
163 $conn = new Redis();
164 try {
165 if ( $this->persistent ) {
166 $result = $conn->pconnect( $host, $port, $this->connectTimeout );
167 } else {
168 $result = $conn->connect( $host, $port, $this->connectTimeout );
169 }
170 if ( !$result ) {
171 wfDebugLog( 'redis', "Could not connect to server $server" );
172 // Mark server down for some time to avoid further timeouts
173 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
174 return false;
175 }
176 if ( $this->password !== null ) {
177 if ( !$conn->auth( $this->password ) ) {
178 wfDebugLog( 'redis', "Authentication error connecting to $server" );
179 }
180 }
181 } catch ( RedisException $e ) {
182 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
183 wfDebugLog( 'redis', "Redis exception: " . $e->getMessage() . "\n" );
184 return false;
185 }
186
187 if ( $conn ) {
188 $conn->setOption( Redis::OPT_SERIALIZER, $this->serializer );
189 $this->connections[$server][] = array( 'conn' => $conn, 'free' => false );
190 return new RedisConnRef( $this, $server, $conn );
191 } else {
192 return false;
193 }
194 }
195
196 /**
197 * Mark a connection to a server as free to return to the pool
198 *
199 * @param $server string
200 * @param $conn Redis
201 * @return boolean
202 */
203 public function freeConnection( $server, Redis $conn ) {
204 $found = false;
205
206 foreach ( $this->connections[$server] as &$connection ) {
207 if ( $connection['conn'] === $conn && !$connection['free'] ) {
208 $connection['free'] = true;
209 ++$this->idlePoolSize;
210 break;
211 }
212 }
213
214 $this->closeExcessIdleConections();
215
216 return $found;
217 }
218
219 /**
220 * Close any extra idle connections if there are more than the limit
221 *
222 * @return void
223 */
224 protected function closeExcessIdleConections() {
225 if ( $this->idlePoolSize <= $this->poolSize ) {
226 return; // nothing to do
227 }
228
229 foreach ( $this->connections as $server => &$serverConnections ) {
230 foreach ( $serverConnections as $key => &$connection ) {
231 if ( $connection['free'] ) {
232 unset( $serverConnections[$key] );
233 if ( --$this->idlePoolSize <= $this->poolSize ) {
234 return; // done
235 }
236 }
237 }
238 }
239 }
240
241 /**
242 * The redis extension throws an exception in response to various read, write
243 * and protocol errors. Sometimes it also closes the connection, sometimes
244 * not. The safest response for us is to explicitly destroy the connection
245 * object and let it be reopened during the next request.
246 *
247 * @param $server string
248 * @param $conn RedisConnRef
249 * @param $e RedisException
250 * @return void
251 */
252 public function handleException( $server, RedisConnRef $conn, RedisException $e ) {
253 wfDebugLog( 'redis',
254 "Redis exception on server $server: " . $e->getMessage() . "\n" );
255 foreach ( $this->connections[$server] as $key => $connection ) {
256 if ( $connection['conn'] === $conn ) {
257 $this->idlePoolSize -= $connection['free'] ? 1 : 0;
258 unset( $this->connections[$server][$key] );
259 break;
260 }
261 }
262 }
263 }
264
265 /**
266 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
267 *
268 * @ingroup Redis
269 * @since 1.21
270 */
271 class RedisConnRef {
272 /** @var RedisConnectionPool */
273 protected $pool;
274
275 protected $server; // string
276
277 /** @var Redis */
278 protected $conn;
279
280 /**
281 * @param $pool RedisConnectionPool
282 * @param $server string
283 * @param $conn Redis
284 */
285 public function __construct( RedisConnectionPool $pool, $server, Redis $conn ) {
286 $this->pool = $pool;
287 $this->server = $server;
288 $this->conn = $conn;
289 }
290
291 public function __call( $name, $arguments ) {
292 return call_user_func_array( array( $this->conn, $name ), $arguments );
293 }
294
295 function __destruct() {
296 $this->pool->freeConnection( $this->server, $this->conn );
297 }
298 }