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