Merge "Use username from last successful login in Special:PasswordReset"
[lhc/web/wiklou.git] / includes / libs / redis / RedisConnRef.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20 use Psr\Log\LoggerInterface;
21 use Psr\Log\LoggerAwareInterface;
22
23 /**
24 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
25 *
26 * This class simply wraps the Redis class and can be used the same way
27 *
28 * @ingroup Redis
29 * @since 1.21
30 */
31 class RedisConnRef implements LoggerAwareInterface {
32 /** @var RedisConnectionPool */
33 protected $pool;
34 /** @var Redis */
35 protected $conn;
36
37 protected $server; // string
38 protected $lastError; // string
39
40 /**
41 * @var LoggerInterface
42 */
43 protected $logger;
44
45 /**
46 * No authentication errors.
47 */
48 const AUTH_NO_ERROR = 200;
49
50 /**
51 * Temporary authentication error; recovered by reauthenticating.
52 */
53 const AUTH_ERROR_TEMPORARY = 201;
54
55 /**
56 * Authentication error was permanent and could not be recovered.
57 */
58 const AUTH_ERROR_PERMANENT = 202;
59
60 /**
61 * @param RedisConnectionPool $pool
62 * @param string $server
63 * @param Redis $conn
64 * @param LoggerInterface $logger
65 */
66 public function __construct(
67 RedisConnectionPool $pool, $server, Redis $conn, LoggerInterface $logger
68 ) {
69 $this->pool = $pool;
70 $this->server = $server;
71 $this->conn = $conn;
72 $this->logger = $logger;
73 }
74
75 public function setLogger( LoggerInterface $logger ) {
76 $this->logger = $logger;
77 }
78
79 /**
80 * @return string
81 * @since 1.23
82 */
83 public function getServer() {
84 return $this->server;
85 }
86
87 public function getLastError() {
88 return $this->lastError;
89 }
90
91 public function clearLastError() {
92 $this->lastError = null;
93 }
94
95 /**
96 * Magic __call handler for most Redis functions.
97 *
98 * @param string $name
99 * @param array $arguments
100 * @return mixed $res
101 * @throws RedisException
102 */
103 public function __call( $name, $arguments ) {
104 // Work around https://github.com/nicolasff/phpredis/issues/70
105 $lname = strtolower( $name );
106 if (
107 ( $lname === 'blpop' || $lname === 'brpop' || $lname === 'brpoplpush' )
108 && count( $arguments ) > 1
109 ) {
110 // Get timeout off the end since it is always required and argument length can vary
111 $timeout = end( $arguments );
112 // Only give the additional one second buffer if not requesting an infinite timeout
113 $this->pool->resetTimeout( $this->conn, ( $timeout > 0 ? $timeout + 1 : $timeout ) );
114 }
115
116 return $this->tryCall( $name, $arguments );
117 }
118
119 /**
120 * Do the method call in the common try catch handler.
121 *
122 * @param string $method
123 * @param array $arguments
124 * @return mixed $res
125 * @throws RedisException
126 */
127 private function tryCall( $method, $arguments ) {
128 $this->conn->clearLastError();
129 try {
130 $res = $this->conn->$method( ...$arguments );
131 $authError = $this->checkAuthentication();
132 if ( $authError === self::AUTH_ERROR_TEMPORARY ) {
133 $res = $this->conn->$method( ...$arguments );
134 }
135 if ( $authError === self::AUTH_ERROR_PERMANENT ) {
136 throw new RedisException( "Failure reauthenticating to Redis." );
137 }
138 } finally {
139 $this->postCallCleanup();
140 }
141
142 return $res;
143 }
144
145 /**
146 * Key Scan
147 * Handle this explicity due to needing the iterator passed by reference.
148 * See: https://github.com/phpredis/phpredis#scan
149 *
150 * @param int &$iterator
151 * @param string|null $pattern
152 * @param int|null $count
153 * @return array $res
154 */
155 public function scan( &$iterator, $pattern = null, $count = null ) {
156 return $this->tryCall( 'scan', [ &$iterator, $pattern, $count ] );
157 }
158
159 /**
160 * Set Scan
161 * Handle this explicity due to needing the iterator passed by reference.
162 * See: https://github.com/phpredis/phpredis#sScan
163 *
164 * @param string $key
165 * @param int &$iterator
166 * @param string|null $pattern
167 * @param int|null $count
168 * @return array $res
169 */
170 public function sScan( $key, &$iterator, $pattern = null, $count = null ) {
171 return $this->tryCall( 'sScan', [ $key, &$iterator, $pattern, $count ] );
172 }
173
174 /**
175 * Hash Scan
176 * Handle this explicity due to needing the iterator passed by reference.
177 * See: https://github.com/phpredis/phpredis#hScan
178 *
179 * @param string $key
180 * @param int &$iterator
181 * @param string|null $pattern
182 * @param int|null $count
183 * @return array $res
184 */
185 public function hScan( $key, &$iterator, $pattern = null, $count = null ) {
186 return $this->tryCall( 'hScan', [ $key, &$iterator, $pattern, $count ] );
187 }
188
189 /**
190 * Sorted Set Scan
191 * Handle this explicity due to needing the iterator passed by reference.
192 * See: https://github.com/phpredis/phpredis#hScan
193 *
194 * @param string $key
195 * @param int &$iterator
196 * @param string|null $pattern
197 * @param int|null $count
198 * @return array $res
199 */
200 public function zScan( $key, &$iterator, $pattern = null, $count = null ) {
201 return $this->tryCall( 'zScan', [ $key, &$iterator, $pattern, $count ] );
202 }
203
204 /**
205 * Handle authentication errors and automatically reauthenticate.
206 *
207 * @return int self::AUTH_NO_ERROR, self::AUTH_ERROR_TEMPORARY, or self::AUTH_ERROR_PERMANENT
208 */
209 private function checkAuthentication() {
210 if ( preg_match( '/^ERR operation not permitted\b/', $this->conn->getLastError() ) ) {
211 if ( !$this->pool->reauthenticateConnection( $this->server, $this->conn ) ) {
212 return self::AUTH_ERROR_PERMANENT;
213 }
214 $this->conn->clearLastError();
215 $this->logger->info(
216 "Used automatic re-authentication for Redis.",
217 [ 'redis_server' => $this->server ]
218 );
219 return self::AUTH_ERROR_TEMPORARY;
220 }
221 return self::AUTH_NO_ERROR;
222 }
223
224 /**
225 * Post Redis call cleanup.
226 *
227 * @return void
228 */
229 private function postCallCleanup() {
230 $this->lastError = $this->conn->getLastError() ?: $this->lastError;
231
232 // Restore original timeout in the case of blocking calls.
233 $this->pool->resetTimeout( $this->conn );
234 }
235
236 /**
237 * @param string $script
238 * @param array $params
239 * @param int $numKeys
240 * @return mixed
241 * @throws RedisException
242 */
243 public function luaEval( $script, array $params, $numKeys ) {
244 $sha1 = sha1( $script ); // 40 char hex
245 $conn = $this->conn; // convenience
246 $server = $this->server; // convenience
247
248 // Try to run the server-side cached copy of the script
249 $conn->clearLastError();
250 $res = $conn->evalSha( $sha1, $params, $numKeys );
251 // If we got a permission error reply that means that (a) we are not in
252 // multi()/pipeline() and (b) some connection problem likely occurred. If
253 // the password the client gave was just wrong, an exception should have
254 // been thrown back in getConnection() previously.
255 if ( preg_match( '/^ERR operation not permitted\b/', $conn->getLastError() ) ) {
256 $this->pool->reauthenticateConnection( $server, $conn );
257 $conn->clearLastError();
258 $res = $conn->eval( $script, $params, $numKeys );
259 $this->logger->info(
260 "Used automatic re-authentication for Lua script '$sha1'.",
261 [ 'redis_server' => $server ]
262 );
263 }
264 // If the script is not in cache, use eval() to retry and cache it
265 if ( preg_match( '/^NOSCRIPT/', $conn->getLastError() ) ) {
266 $conn->clearLastError();
267 $res = $conn->eval( $script, $params, $numKeys );
268 $this->logger->info(
269 "Used eval() for Lua script '$sha1'.",
270 [ 'redis_server' => $server ]
271 );
272 }
273
274 if ( $conn->getLastError() ) { // script bug?
275 $this->logger->error(
276 'Lua script error on server "{redis_server}": {lua_error}',
277 [
278 'redis_server' => $server,
279 'lua_error' => $conn->getLastError()
280 ]
281 );
282 }
283
284 $this->lastError = $conn->getLastError() ?: $this->lastError;
285
286 return $res;
287 }
288
289 /**
290 * @param Redis $conn
291 * @return bool
292 */
293 public function isConnIdentical( Redis $conn ) {
294 return $this->conn === $conn;
295 }
296
297 function __destruct() {
298 $this->pool->freeConnection( $this->server, $this->conn );
299 }
300 }