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