MediaWiki master
MemcachedPeclBagOStuff.php
Go to the documentation of this file.
1<?php
7
8use Memcached;
9use RuntimeException;
10use UnexpectedValueException;
11use Wikimedia\ScopedCallback;
12
23 protected $client;
24
42 public function __construct( $params ) {
43 parent::__construct( $params );
44
45 // Default class-specific parameters
46 $params += [
47 'compress_threshold' => 1500,
48 'connect_timeout' => 0.5,
49 'timeout' => 500_000,
50 'serializer' => 'php',
51 'use_binary_protocol' => false,
52 'allow_tcp_nagle_delay' => true
53 ];
54
55 if ( $params['persistent'] ) {
56 // The pool ID must be unique to the server/option combination.
57 // The Memcached object is essentially shared for each pool ID.
58 // We can only reuse a pool ID if we keep the config consistent.
59 $connectionPoolId = md5( serialize( $params ) );
60 $client = new Memcached( $connectionPoolId );
61 } else {
62 $client = new Memcached();
63 }
64
65 $this->initializeClient( $client, $params );
66
67 $this->client = $client;
68 // The compression threshold is an undocumented php.ini option for some
69 // reason. There's probably not much harm in setting it globally, for
70 // compatibility with the settings for the PHP client.
71 ini_set( 'memcached.compression_threshold', $params['compress_threshold'] );
72 }
73
83 private function initializeClient( Memcached $client, array $params ) {
84 if ( $client->getServerList() ) {
85 $this->logger->debug( __METHOD__ . ": pre-initialized client instance." );
86
87 return; // preserve persistent handle
88 }
89
90 $this->logger->debug( __METHOD__ . ": initializing new client instance." );
91
92 $options = [
93 Memcached::OPT_NO_BLOCK => false,
94 Memcached::OPT_BUFFER_WRITES => false,
95 Memcached::OPT_NOREPLY => false,
96 // Network protocol (ASCII or binary)
97 Memcached::OPT_BINARY_PROTOCOL => $params['use_binary_protocol'],
98 // Set various network timeouts
99 Memcached::OPT_CONNECT_TIMEOUT => $params['connect_timeout'] * 1000,
100 Memcached::OPT_SEND_TIMEOUT => $params['timeout'],
101 Memcached::OPT_RECV_TIMEOUT => $params['timeout'],
102 Memcached::OPT_POLL_TIMEOUT => $params['timeout'] / 1000,
103 // Avoid pointless delay when sending/fetching large blobs
104 Memcached::OPT_TCP_NODELAY => !$params['allow_tcp_nagle_delay'],
105 // Set libketama mode since it's recommended by the documentation
106 Memcached::OPT_LIBKETAMA_COMPATIBLE => true
107 ];
108 if ( isset( $params['retry_timeout'] ) ) {
109 $options[Memcached::OPT_RETRY_TIMEOUT] = $params['retry_timeout'];
110 }
111 if ( isset( $params['server_failure_limit'] ) ) {
112 $options[Memcached::OPT_SERVER_FAILURE_LIMIT] = $params['server_failure_limit'];
113 }
114 if ( $params['serializer'] === 'php' ) {
115 $options[Memcached::OPT_SERIALIZER] = Memcached::SERIALIZER_PHP;
116 } elseif ( $params['serializer'] === 'igbinary' ) {
117 // @phan-suppress-next-line PhanImpossibleCondition
118 if ( !Memcached::HAVE_IGBINARY ) {
119 throw new RuntimeException(
120 __CLASS__ . ': the igbinary extension is not available ' .
121 'but igbinary serialization was requested.'
122 );
123 }
124 $options[Memcached::OPT_SERIALIZER] = Memcached::SERIALIZER_IGBINARY;
125 }
126
127 if ( !$client->setOptions( $options ) ) {
128 throw new RuntimeException(
129 "Invalid options: " . json_encode( $options, JSON_PRETTY_PRINT )
130 );
131 }
132
133 $servers = [];
134 foreach ( $params['servers'] as $host ) {
135 if ( preg_match( '/^\[(.+)\]:(\d+)$/', $host, $m ) ) {
136 $servers[] = [ $m[1], (int)$m[2] ]; // (ip, port)
137 } elseif ( preg_match( '/^([^:]+):(\d+)$/', $host, $m ) ) {
138 $servers[] = [ $m[1], (int)$m[2] ]; // (ip or path, port)
139 } else {
140 $servers[] = [ $host, false ]; // (ip or path, port)
141 }
142 }
143
144 if ( !$client->addServers( $servers ) ) {
145 throw new RuntimeException( "Failed to inject server address list" );
146 }
147 }
148
156 #[\NoDiscard]
157 private function noReplyScope( $flags ): ?ScopedCallback {
158 if ( $flags !== true && !( $flags & self::WRITE_BACKGROUND ) ) {
159 return null;
160 }
162 $client->setOption( Memcached::OPT_NOREPLY, true );
163
164 return new ScopedCallback( static function () use ( $client ) {
165 $client->setOption( Memcached::OPT_NOREPLY, false );
166 } );
167 }
168
170 protected function doGet( $key, $flags = 0, &$casToken = null ) {
171 $getToken = ( $casToken === self::PASS_BY_REF );
172 $casToken = null;
173
174 $this->debug( "get($key)" );
175
176 $routeKey = $this->validateKeyAndPrependRoute( $key );
177
178 // T257003: only require "gets" (instead of "get") when a CAS token is needed
179 if ( $getToken ) {
181 $flags = Memcached::GET_EXTENDED;
182 $res = $this->client->get( $routeKey, null, $flags );
183 if ( is_array( $res ) ) {
184 $result = $res['value'];
185 $casToken = $res['cas'];
186 } else {
187 $result = false;
188 }
189 } else {
190 $result = $this->client->get( $routeKey );
191 }
192
193 return $this->checkResult( $key, $result );
194 }
195
197 protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
198 $this->debug( "set($key)" );
199
200 $routeKey = $this->validateKeyAndPrependRoute( $key );
201
202 $noReplyScope = $this->noReplyScope( $flags );
203 $result = $this->client->set( $routeKey, $value, $this->fixExpiry( $exptime ) );
204 ScopedCallback::consume( $noReplyScope );
205
206 return ( !$result && $this->client->getResultCode() === Memcached::RES_NOTSTORED )
207 // "Not stored" is always used as the mcrouter response with AllAsyncRoute
208 ? true
209 : $this->checkResult( $key, $result );
210 }
211
213 protected function doCas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
214 $this->debug( "cas($key)" );
215
216 $routeKey = $this->validateKeyAndPrependRoute( $key );
217 $result = $this->client->cas(
218 $casToken,
219 $routeKey,
220 $value, $this->fixExpiry( $exptime )
221 );
222
223 return $this->checkResult( $key, $result );
224 }
225
227 protected function doDelete( $key, $flags = 0 ) {
228 $this->debug( "delete($key)" );
229
230 $routeKey = $this->validateKeyAndPrependRoute( $key );
231 $noReplyScope = $this->noReplyScope( $flags );
232 $result = $this->client->delete( $routeKey );
233 ScopedCallback::consume( $noReplyScope );
234
235 return ( !$result && $this->client->getResultCode() === Memcached::RES_NOTFOUND )
236 // "Not found" is counted as success in our interface
237 ? true
238 : $this->checkResult( $key, $result );
239 }
240
242 protected function doAdd( $key, $value, $exptime = 0, $flags = 0 ) {
243 $this->debug( "add($key)" );
244
245 $routeKey = $this->validateKeyAndPrependRoute( $key );
246 $noReplyScope = $this->noReplyScope( $flags );
247 $result = $this->client->add(
248 $routeKey,
249 $value,
250 $this->fixExpiry( $exptime )
251 );
252 ScopedCallback::consume( $noReplyScope );
253
254 return $this->checkResult( $key, $result );
255 }
256
258 protected function doIncrWithInitAsync( $key, $exptime, $step, $init ) {
259 $this->debug( "incrWithInit($key)" );
260 $routeKey = $this->validateKeyAndPrependRoute( $key );
261 $watchPoint = $this->watchErrors();
262 $scope = $this->noReplyScope( true );
263 $this->checkResult( $key, $this->client->add( $routeKey, $init - $step, $this->fixExpiry( $exptime ) ) );
264 $this->checkResult( $key, $this->client->increment( $routeKey, $step ) );
265 ScopedCallback::consume( $scope );
266 $lastError = $this->getLastError( $watchPoint );
267
268 return !$lastError;
269 }
270
272 protected function doIncrWithInitSync( $key, $exptime, $step, $init ) {
273 $this->debug( "incrWithInit($key)" );
274 $routeKey = $this->validateKeyAndPrependRoute( $key );
275 $watchPoint = $this->watchErrors();
276 $result = $this->client->increment( $routeKey, $step );
277 $newValue = $this->checkResult( $key, $result );
278 if ( $newValue === false && !$this->getLastError( $watchPoint ) ) {
279 // No key set; initialize
280 $result = $this->client->add( $routeKey, $init, $this->fixExpiry( $exptime ) );
281 $newValue = $this->checkResult( $key, $result ) ? $init : false;
282 if ( $newValue === false && !$this->getLastError( $watchPoint ) ) {
283 // Raced out initializing; increment
284 $result = $this->client->increment( $routeKey, $step );
285 $newValue = $this->checkResult( $key, $result );
286 }
287 }
288
289 return $newValue;
290 }
291
304 protected function checkResult( $key, $result ) {
305 static $statusByCode = [
306 Memcached::RES_HOST_LOOKUP_FAILURE => self::ERR_UNREACHABLE,
307 Memcached::RES_SERVER_MARKED_DEAD => self::ERR_UNREACHABLE,
308 Memcached::RES_SERVER_TEMPORARILY_DISABLED => self::ERR_UNREACHABLE,
309 Memcached::RES_UNKNOWN_READ_FAILURE => self::ERR_NO_RESPONSE,
310 Memcached::RES_WRITE_FAILURE => self::ERR_NO_RESPONSE,
311 Memcached::RES_PARTIAL_READ => self::ERR_NO_RESPONSE,
312 // Hard-code values that only exist in recent versions of the PECL extension.
313 // https://github.com/JetBrains/phpstorm-stubs/blob/master/memcached/memcached.php
314 3 /* Memcached::RES_CONNECTION_FAILURE */ => self::ERR_UNREACHABLE,
315 27 /* Memcached::RES_FAIL_UNIX_SOCKET */ => self::ERR_UNREACHABLE,
316 6 /* Memcached::RES_READ_FAILURE */ => self::ERR_NO_RESPONSE
317 ];
318
319 if ( $result !== false ) {
320 return $result;
321 }
322
323 $client = $this->client;
324 $code = $client->getResultCode();
325 switch ( $code ) {
326 case Memcached::RES_SUCCESS:
327 break;
328 case Memcached::RES_DATA_EXISTS:
329 case Memcached::RES_NOTSTORED:
330 case Memcached::RES_NOTFOUND:
331 $this->debug( "result: " . $client->getResultMessage() );
332 break;
333 default:
334 $msg = $client->getResultMessage();
335 $logCtx = [];
336 if ( $key !== false ) {
337 $server = $client->getServerByKey( $key );
338 $logCtx['memcached-server'] = "{$server['host']}:{$server['port']}";
339 $logCtx['memcached-key'] = $key;
340 $msg = "Memcached error for key \"{memcached-key}\" " .
341 "on server \"{memcached-server}\": $msg";
342 } else {
343 $msg = "Memcached error: $msg";
344 }
345 $this->logger->error( $msg, $logCtx );
346 $this->setLastError( $statusByCode[$code] ?? self::ERR_UNEXPECTED );
347 }
348
349 return $result;
350 }
351
353 protected function doGetMulti( array $keys, $flags = 0 ) {
354 $this->debug( 'getMulti(' . implode( ', ', $keys ) . ')' );
355
356 $routeKeys = [];
357 foreach ( $keys as $key ) {
358 $routeKeys[] = $this->validateKeyAndPrependRoute( $key );
359 }
360
361 // The PECL implementation uses multi-key "get"/"gets"; no need to pipeline.
362 // T257003: avoid Memcached::GET_EXTENDED; no tokens are needed and that requires "gets"
363 // https://github.com/libmemcached/libmemcached/blob/eda2becbec24363f56115fa5d16d38a2d1f54775/libmemcached/get.cc#L272
364 $resByRouteKey = $this->client->getMulti( $routeKeys );
365
366 if ( is_array( $resByRouteKey ) ) {
367 $res = [];
368 foreach ( $resByRouteKey as $routeKey => $value ) {
369 $res[$this->stripRouteFromKey( $routeKey )] = $value;
370 }
371 } else {
372 $res = false;
373 }
374
375 $res = $this->checkResult( false, $res );
376
377 return $res !== false ? $res : [];
378 }
379
381 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
382 $this->debug( 'setMulti(' . implode( ', ', array_keys( $data ) ) . ')' );
383
384 $exptime = $this->fixExpiry( $exptime );
385 $dataByRouteKey = [];
386 foreach ( $data as $key => $value ) {
387 $dataByRouteKey[$this->validateKeyAndPrependRoute( $key )] = $value;
388 }
389
390 $noReplyScope = $this->noReplyScope( $flags );
391
392 // Ignore "failed to set" warning from php-memcached 3.x (T251450)
393 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
394 $result = @$this->client->setMulti( $dataByRouteKey, $exptime );
395 ScopedCallback::consume( $noReplyScope );
396
397 return $this->checkResult( false, $result );
398 }
399
401 protected function doDeleteMulti( array $keys, $flags = 0 ) {
402 $this->debug( 'deleteMulti(' . implode( ', ', $keys ) . ')' );
403
404 $routeKeys = [];
405 foreach ( $keys as $key ) {
406 $routeKeys[] = $this->validateKeyAndPrependRoute( $key );
407 }
408
409 $noReplyScope = $this->noReplyScope( $flags );
410 $resultArray = $this->client->deleteMulti( $routeKeys ) ?: [];
411 ScopedCallback::consume( $noReplyScope );
412
413 $result = true;
414 foreach ( $resultArray as $code ) {
415 if ( !in_array( $code, [ true, Memcached::RES_NOTFOUND ], true ) ) {
416 // "Not found" is counted as success in our interface
417 $result = false;
418 }
419 }
420
421 return $this->checkResult( false, $result );
422 }
423
425 protected function doChangeTTL( $key, $exptime, $flags ) {
426 $this->debug( "touch($key)" );
427
428 $routeKey = $this->validateKeyAndPrependRoute( $key );
429 // Avoid NO_REPLY due to libmemcached hang
430 // https://phabricator.wikimedia.org/T310662#8031692
431 $result = $this->client->touch( $routeKey, $this->fixExpiry( $exptime ) );
432
433 return $this->checkResult( $key, $result );
434 }
435
437 protected function serialize( $value ) {
438 if ( is_int( $value ) ) {
439 return $value;
440 }
441
442 $serializer = $this->client->getOption( Memcached::OPT_SERIALIZER );
443 if ( $serializer === Memcached::SERIALIZER_PHP ) {
444 return serialize( $value );
445 } elseif ( $serializer === Memcached::SERIALIZER_IGBINARY ) {
446 return igbinary_serialize( $value );
447 }
448
449 throw new UnexpectedValueException( __METHOD__ . ": got serializer '$serializer'." );
450 }
451
453 protected function unserialize( $value ) {
454 if ( $this->isInteger( $value ) ) {
455 return (int)$value;
456 }
457
458 $serializer = $this->client->getOption( Memcached::OPT_SERIALIZER );
459 if ( $serializer === Memcached::SERIALIZER_PHP ) {
460 return unserialize( $value );
461 } elseif ( $serializer === Memcached::SERIALIZER_IGBINARY ) {
462 return igbinary_unserialize( $value );
463 }
464
465 throw new UnexpectedValueException( __METHOD__ . ": got serializer '$serializer'." );
466 }
467}
468
470class_alias( MemcachedPeclBagOStuff::class, 'MemcachedPeclBagOStuff' );
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:69
const WRITE_BACKGROUND
If supported, do not block on write operation completion; instead, treat writes as succesful based on...
Store data in a memcached server or memcached cluster.
Store data on memcached server(s) via the php-memcached PECL extension.
doSetMulti(array $data, $exptime=0, $flags=0)
bool Success
doIncrWithInitAsync( $key, $exptime, $step, $init)
bool True on success, false on failure
doAdd( $key, $value, $exptime=0, $flags=0)
Insert an item if it does not already exist.bool Success
doSet( $key, $value, $exptime=0, $flags=0)
Set an item.bool Success
unserialize( $value)
mixed Original value or false on error Special handling is usually needed for integers so incr()/decr...
doCas( $casToken, $key, $value, $exptime=0, $flags=0)
Set an item if the current CAS token matches the provided CAS token.bool Success
serialize( $value)
string|int|false String/integer representation Special handling is usually needed for integers so inc...
doDelete( $key, $flags=0)
Delete an item.bool True if the item was deleted or not found, false on failure
checkResult( $key, $result)
Check the return value from a client method call and take any necessary action.
__construct( $params)
Available parameters are:
doDeleteMulti(array $keys, $flags=0)
bool Success
doGetMulti(array $keys, $flags=0)
Get an associative array containing the item for each of the keys that have items....
doIncrWithInitSync( $key, $exptime, $step, $init)
int|bool New value or false on failure
doGet( $key, $flags=0, &$casToken=null)
Get an item.The CAS token should be null if the key does not exist or the value is corruptmixed Retur...