Merge "Fix 'Tags' padding to keep it farther from the edge and document the source...
[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 * @var constant
49 */
50 const AUTH_NO_ERROR = 200;
51
52 /**
53 * Temporary authentication error; recovered by reauthenticating.
54 *
55 * @var constant
56 */
57 const AUTH_ERROR_TEMPORARY = 201;
58
59 /**
60 * Authentication error was permanent and could not be recovered.
61 *
62 * @var constant
63 */
64 const AUTH_ERROR_PERMANENT = 202;
65
66 /**
67 * @param RedisConnectionPool $pool
68 * @param string $server
69 * @param Redis $conn
70 * @param LoggerInterface $logger
71 */
72 public function __construct(
73 RedisConnectionPool $pool, $server, Redis $conn, LoggerInterface $logger
74 ) {
75 $this->pool = $pool;
76 $this->server = $server;
77 $this->conn = $conn;
78 $this->logger = $logger;
79 }
80
81 public function setLogger( LoggerInterface $logger ) {
82 $this->logger = $logger;
83 }
84
85 /**
86 * @return string
87 * @since 1.23
88 */
89 public function getServer() {
90 return $this->server;
91 }
92
93 public function getLastError() {
94 return $this->lastError;
95 }
96
97 public function clearLastError() {
98 $this->lastError = null;
99 }
100
101 /**
102 * Magic __call handler for most Redis functions.
103 *
104 * @param string $name
105 * @param array $arguments
106 * @return mixed $res
107 * @throws RedisException
108 */
109 public function __call( $name, $arguments ) {
110 // Work around https://github.com/nicolasff/phpredis/issues/70
111 $lname = strtolower( $name );
112 if (
113 ( $lname === 'blpop' || $lname === 'brpop' || $lname === 'brpoplpush' )
114 && count( $arguments ) > 1
115 ) {
116 // Get timeout off the end since it is always required and argument length can vary
117 $timeout = end( $arguments );
118 // Only give the additional one second buffer if not requesting an infinite timeout
119 $this->pool->resetTimeout( $this->conn, ( $timeout > 0 ? $timeout + 1 : $timeout ) );
120 }
121
122 return $this->tryCall( $name, $arguments );
123 }
124
125 /**
126 * Do the method call in the common try catch handler.
127 *
128 * @param string $method
129 * @param array $arguments
130 * @return mixed $res
131 * @throws RedisException
132 */
133 private function tryCall( $method, $arguments ) {
134 $this->conn->clearLastError();
135 try {
136 $res = $this->conn->$method( ...$arguments );
137 $authError = $this->checkAuthentication();
138 if ( $authError === self::AUTH_ERROR_TEMPORARY ) {
139 $res = $this->conn->$method( ...$arguments );
140 }
141 if ( $authError === self::AUTH_ERROR_PERMANENT ) {
142 throw new RedisException( "Failure reauthenticating to Redis." );
143 }
144 } finally {
145 $this->postCallCleanup();
146 }
147
148 return $res;
149 }
150
151 /**
152 * Key Scan
153 * Handle this explicity due to needing the iterator passed by reference.
154 * See: https://github.com/phpredis/phpredis#scan
155 *
156 * @param int &$iterator
157 * @param string $pattern
158 * @param int $count
159 * @return array $res
160 */
161 public function scan( &$iterator, $pattern = null, $count = null ) {
162 return $this->tryCall( 'scan', [ &$iterator, $pattern, $count ] );
163 }
164
165 /**
166 * Set Scan
167 * Handle this explicity due to needing the iterator passed by reference.
168 * See: https://github.com/phpredis/phpredis#sScan
169 *
170 * @param string $key
171 * @param int &$iterator
172 * @param string $pattern
173 * @param int $count
174 * @return array $res
175 */
176 public function sScan( $key, &$iterator, $pattern = null, $count = null ) {
177 return $this->tryCall( 'sScan', [ $key, &$iterator, $pattern, $count ] );
178 }
179
180 /**
181 * Hash Scan
182 * Handle this explicity due to needing the iterator passed by reference.
183 * See: https://github.com/phpredis/phpredis#hScan
184 *
185 * @param string $key
186 * @param int &$iterator
187 * @param string $pattern
188 * @param int $count
189 * @return array $res
190 */
191 public function hScan( $key, &$iterator, $pattern = null, $count = null ) {
192 return $this->tryCall( 'hScan', [ $key, &$iterator, $pattern, $count ] );
193 }
194
195 /**
196 * Sorted Set Scan
197 * Handle this explicity due to needing the iterator passed by reference.
198 * See: https://github.com/phpredis/phpredis#hScan
199 *
200 * @param string $key
201 * @param int &$iterator
202 * @param string $pattern
203 * @param int $count
204 * @return array $res
205 */
206 public function zScan( $key, &$iterator, $pattern = null, $count = null ) {
207 return $this->tryCall( 'zScan', [ $key, &$iterator, $pattern, $count ] );
208 }
209
210 /**
211 * Handle authentication errors and automatically reauthenticate.
212 *
213 * @return constant self::AUTH_NO_ERROR, self::AUTH_ERROR_TEMPORARY, or self::AUTH_ERROR_PERMANENT
214 */
215 private function checkAuthentication() {
216 if ( preg_match( '/^ERR operation not permitted\b/', $this->conn->getLastError() ) ) {
217 if ( !$this->pool->reauthenticateConnection( $this->server, $this->conn ) ) {
218 return self::AUTH_ERROR_PERMANENT;
219 }
220 $this->conn->clearLastError();
221 $this->logger->info(
222 "Used automatic re-authentication for Redis.",
223 [ 'redis_server' => $this->server ]
224 );
225 return self::AUTH_ERROR_TEMPORARY;
226 }
227 return self::AUTH_NO_ERROR;
228 }
229
230 /**
231 * Post Redis call cleanup.
232 *
233 * @return void
234 */
235 private function postCallCleanup() {
236 $this->lastError = $this->conn->getLastError() ?: $this->lastError;
237
238 // Restore original timeout in the case of blocking calls.
239 $this->pool->resetTimeout( $this->conn );
240 }
241
242 /**
243 * @param string $script
244 * @param array $params
245 * @param int $numKeys
246 * @return mixed
247 * @throws RedisException
248 */
249 public function luaEval( $script, array $params, $numKeys ) {
250 $sha1 = sha1( $script ); // 40 char hex
251 $conn = $this->conn; // convenience
252 $server = $this->server; // convenience
253
254 // Try to run the server-side cached copy of the script
255 $conn->clearLastError();
256 $res = $conn->evalSha( $sha1, $params, $numKeys );
257 // If we got a permission error reply that means that (a) we are not in
258 // multi()/pipeline() and (b) some connection problem likely occurred. If
259 // the password the client gave was just wrong, an exception should have
260 // been thrown back in getConnection() previously.
261 if ( preg_match( '/^ERR operation not permitted\b/', $conn->getLastError() ) ) {
262 $this->pool->reauthenticateConnection( $server, $conn );
263 $conn->clearLastError();
264 $res = $conn->eval( $script, $params, $numKeys );
265 $this->logger->info(
266 "Used automatic re-authentication for Lua script '$sha1'.",
267 [ 'redis_server' => $server ]
268 );
269 }
270 // If the script is not in cache, use eval() to retry and cache it
271 if ( preg_match( '/^NOSCRIPT/', $conn->getLastError() ) ) {
272 $conn->clearLastError();
273 $res = $conn->eval( $script, $params, $numKeys );
274 $this->logger->info(
275 "Used eval() for Lua script '$sha1'.",
276 [ 'redis_server' => $server ]
277 );
278 }
279
280 if ( $conn->getLastError() ) { // script bug?
281 $this->logger->error(
282 'Lua script error on server "{redis_server}": {lua_error}',
283 [
284 'redis_server' => $server,
285 'lua_error' => $conn->getLastError()
286 ]
287 );
288 }
289
290 $this->lastError = $conn->getLastError() ?: $this->lastError;
291
292 return $res;
293 }
294
295 /**
296 * @param Redis $conn
297 * @return bool
298 */
299 public function isConnIdentical( Redis $conn ) {
300 return $this->conn === $conn;
301 }
302
303 function __destruct() {
304 $this->pool->freeConnection( $this->server, $this->conn );
305 }
306 }