Debian Codegraph @

includes/libs/objectcache/utils/RedisConnRef.php

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