Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 219
0.00% covered (danger)
0.00%
0 / 17
CRAP
0.00% covered (danger)
0.00%
0 / 1
MemcachedPeclBagOStuff
0.00% covered (danger)
0.00%
0 / 218
0.00% covered (danger)
0.00%
0 / 17
4160
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
6
 initializeClient
0.00% covered (danger)
0.00%
0 / 42
0.00% covered (danger)
0.00%
0 / 1
156
 noReplyScope
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 doGet
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 doSet
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
 doCas
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 doDelete
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
 doAdd
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
2
 doIncrWithInitAsync
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 doIncrWithInitSync
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
42
 checkResult
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
72
 doGetMulti
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
30
 doSetMulti
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 doDeleteMulti
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
30
 doChangeTTL
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 serialize
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 unserialize
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6namespace Wikimedia\ObjectCache;
7
8use Memcached;
9use RuntimeException;
10use UnexpectedValueException;
11use Wikimedia\ScopedCallback;
12
13/**
14 * Store data on memcached server(s) via the php-memcached PECL extension.
15 *
16 * To use memcached out of the box without any PECL dependency, use the
17 * MemcachedPhpBagOStuff class instead.
18 *
19 * @ingroup Cache
20 */
21class MemcachedPeclBagOStuff extends MemcachedBagOStuff {
22    /** @var Memcached */
23    protected $client;
24
25    /**
26     * Available parameters are:
27     *   - servers:              List of IP:port combinations holding the memcached servers.
28     *   - persistent:           Whether to use a persistent connection
29     *   - compress_threshold:   The minimum size an object must be before it is compressed
30     *   - timeout:              The read timeout in microseconds
31     *   - connect_timeout:      The connect timeout in seconds
32     *   - retry_timeout:        Time in seconds to wait before retrying a failed connect attempt
33     *   - server_failure_limit: Limit for server connect failures before it is removed
34     *   - serializer:           Either "php" or "igbinary". Igbinary produces more compact
35     *                           values, but serialization is much slower unless the php.ini
36     *                           option igbinary.compact_strings is off.
37     *   - use_binary_protocol   Whether to enable the binary protocol (default is ASCII)
38     *   - allow_tcp_nagle_delay Whether to permit Nagle's algorithm for reducing packet count
39     *
40     * @param array $params
41     */
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
74    /**
75     * Initialize the client only if needed and reuse it otherwise.
76     * This avoids duplicate servers in the list and new connections.
77     *
78     * @param Memcached $client
79     * @param array $params
80     *
81     * @throws RuntimeException
82     */
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
149    /**
150     * If $flags is true or is an integer with the WRITE_BACKGROUND bit set,
151     * enable no-reply mode, and disable it when the scope object is destroyed.
152     * This makes writes much faster.
153     *
154     * @param bool|int $flags
155     *
156     * @return ScopedCallback|null
157     */
158    private function noReplyScope( $flags ) {
159        if ( $flags !== true && !( $flags & self::WRITE_BACKGROUND ) ) {
160            return null;
161        }
162        $client = $this->client;
163        $client->setOption( Memcached::OPT_NOREPLY, true );
164
165        return new ScopedCallback( static function () use ( $client ) {
166            $client->setOption( Memcached::OPT_NOREPLY, false );
167        } );
168    }
169
170    /** @inheritDoc */
171    protected function doGet( $key, $flags = 0, &$casToken = null ) {
172        $getToken = ( $casToken === self::PASS_BY_REF );
173        $casToken = null;
174
175        $this->debug( "get($key)" );
176
177        $routeKey = $this->validateKeyAndPrependRoute( $key );
178
179        // T257003: only require "gets" (instead of "get") when a CAS token is needed
180        if ( $getToken ) {
181            /** @noinspection PhpUndefinedClassConstantInspection */
182            $flags = Memcached::GET_EXTENDED;
183            $res = $this->client->get( $routeKey, null, $flags );
184            if ( is_array( $res ) ) {
185                $result = $res['value'];
186                $casToken = $res['cas'];
187            } else {
188                $result = false;
189            }
190        } else {
191            $result = $this->client->get( $routeKey );
192        }
193
194        return $this->checkResult( $key, $result );
195    }
196
197    /** @inheritDoc */
198    protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
199        $this->debug( "set($key)" );
200
201        $routeKey = $this->validateKeyAndPrependRoute( $key );
202
203        $noReplyScope = $this->noReplyScope( $flags );
204        $result = $this->client->set( $routeKey, $value, $this->fixExpiry( $exptime ) );
205        ScopedCallback::consume( $noReplyScope );
206
207        return ( !$result && $this->client->getResultCode() === Memcached::RES_NOTSTORED )
208            // "Not stored" is always used as the mcrouter response with AllAsyncRoute
209            ? true
210            : $this->checkResult( $key, $result );
211    }
212
213    /** @inheritDoc */
214    protected function doCas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
215        $this->debug( "cas($key)" );
216
217        $routeKey = $this->validateKeyAndPrependRoute( $key );
218        $result = $this->client->cas(
219            $casToken,
220            $routeKey,
221            $value, $this->fixExpiry( $exptime )
222        );
223
224        return $this->checkResult( $key, $result );
225    }
226
227    /** @inheritDoc */
228    protected function doDelete( $key, $flags = 0 ) {
229        $this->debug( "delete($key)" );
230
231        $routeKey = $this->validateKeyAndPrependRoute( $key );
232        $noReplyScope = $this->noReplyScope( $flags );
233        $result = $this->client->delete( $routeKey );
234        ScopedCallback::consume( $noReplyScope );
235
236        return ( !$result && $this->client->getResultCode() === Memcached::RES_NOTFOUND )
237            // "Not found" is counted as success in our interface
238            ? true
239            : $this->checkResult( $key, $result );
240    }
241
242    /** @inheritDoc */
243    protected function doAdd( $key, $value, $exptime = 0, $flags = 0 ) {
244        $this->debug( "add($key)" );
245
246        $routeKey = $this->validateKeyAndPrependRoute( $key );
247        $noReplyScope = $this->noReplyScope( $flags );
248        $result = $this->client->add(
249            $routeKey,
250            $value,
251            $this->fixExpiry( $exptime )
252        );
253        ScopedCallback::consume( $noReplyScope );
254
255        return $this->checkResult( $key, $result );
256    }
257
258    /** @inheritDoc */
259    protected function doIncrWithInitAsync( $key, $exptime, $step, $init ) {
260        $this->debug( "incrWithInit($key)" );
261        $routeKey = $this->validateKeyAndPrependRoute( $key );
262        $watchPoint = $this->watchErrors();
263        $scope = $this->noReplyScope( true );
264        $this->checkResult( $key, $this->client->add( $routeKey, $init - $step, $this->fixExpiry( $exptime ) ) );
265        $this->checkResult( $key, $this->client->increment( $routeKey, $step ) );
266        ScopedCallback::consume( $scope );
267        $lastError = $this->getLastError( $watchPoint );
268
269        return !$lastError;
270    }
271
272    /** @inheritDoc */
273    protected function doIncrWithInitSync( $key, $exptime, $step, $init ) {
274        $this->debug( "incrWithInit($key)" );
275        $routeKey = $this->validateKeyAndPrependRoute( $key );
276        $watchPoint = $this->watchErrors();
277        $result = $this->client->increment( $routeKey, $step );
278        $newValue = $this->checkResult( $key, $result );
279        if ( $newValue === false && !$this->getLastError( $watchPoint ) ) {
280            // No key set; initialize
281            $result = $this->client->add( $routeKey, $init, $this->fixExpiry( $exptime ) );
282            $newValue = $this->checkResult( $key, $result ) ? $init : false;
283            if ( $newValue === false && !$this->getLastError( $watchPoint ) ) {
284                // Raced out initializing; increment
285                $result = $this->client->increment( $routeKey, $step );
286                $newValue = $this->checkResult( $key, $result );
287            }
288        }
289
290        return $newValue;
291    }
292
293    /**
294     * Check the return value from a client method call and take any necessary
295     * action. Returns the value that the wrapper function should return. At
296     * present, the return value is always the same as the return value from
297     * the client, but some day we might find a case where it should be
298     * different.
299     *
300     * @param string|false $key The key used by the caller, or false if there wasn't one.
301     * @param mixed $result The return value
302     *
303     * @return mixed
304     */
305    protected function checkResult( $key, $result ) {
306        static $statusByCode = [
307            Memcached::RES_HOST_LOOKUP_FAILURE => self::ERR_UNREACHABLE,
308            Memcached::RES_SERVER_MARKED_DEAD => self::ERR_UNREACHABLE,
309            Memcached::RES_SERVER_TEMPORARILY_DISABLED => self::ERR_UNREACHABLE,
310            Memcached::RES_UNKNOWN_READ_FAILURE => self::ERR_NO_RESPONSE,
311            Memcached::RES_WRITE_FAILURE => self::ERR_NO_RESPONSE,
312            Memcached::RES_PARTIAL_READ => self::ERR_NO_RESPONSE,
313            // Hard-code values that only exist in recent versions of the PECL extension.
314            // https://github.com/JetBrains/phpstorm-stubs/blob/master/memcached/memcached.php
315            3 /* Memcached::RES_CONNECTION_FAILURE */ => self::ERR_UNREACHABLE,
316            27 /* Memcached::RES_FAIL_UNIX_SOCKET */ => self::ERR_UNREACHABLE,
317            6 /* Memcached::RES_READ_FAILURE */ => self::ERR_NO_RESPONSE
318        ];
319
320        if ( $result !== false ) {
321            return $result;
322        }
323
324        $client = $this->client;
325        $code = $client->getResultCode();
326        switch ( $code ) {
327            case Memcached::RES_SUCCESS:
328                break;
329            case Memcached::RES_DATA_EXISTS:
330            case Memcached::RES_NOTSTORED:
331            case Memcached::RES_NOTFOUND:
332                $this->debug( "result: " . $client->getResultMessage() );
333                break;
334            default:
335                $msg = $client->getResultMessage();
336                $logCtx = [];
337                if ( $key !== false ) {
338                    $server = $client->getServerByKey( $key );
339                    $logCtx['memcached-server'] = "{$server['host']}:{$server['port']}";
340                    $logCtx['memcached-key'] = $key;
341                    $msg = "Memcached error for key \"{memcached-key}\" " .
342                        "on server \"{memcached-server}\": $msg";
343                } else {
344                    $msg = "Memcached error: $msg";
345                }
346                $this->logger->error( $msg, $logCtx );
347                $this->setLastError( $statusByCode[$code] ?? self::ERR_UNEXPECTED );
348        }
349
350        return $result;
351    }
352
353    /** @inheritDoc */
354    protected function doGetMulti( array $keys, $flags = 0 ) {
355        $this->debug( 'getMulti(' . implode( ', ', $keys ) . ')' );
356
357        $routeKeys = [];
358        foreach ( $keys as $key ) {
359            $routeKeys[] = $this->validateKeyAndPrependRoute( $key );
360        }
361
362        // The PECL implementation uses multi-key "get"/"gets"; no need to pipeline.
363        // T257003: avoid Memcached::GET_EXTENDED; no tokens are needed and that requires "gets"
364        // https://github.com/libmemcached/libmemcached/blob/eda2becbec24363f56115fa5d16d38a2d1f54775/libmemcached/get.cc#L272
365        $resByRouteKey = $this->client->getMulti( $routeKeys );
366
367        if ( is_array( $resByRouteKey ) ) {
368            $res = [];
369            foreach ( $resByRouteKey as $routeKey => $value ) {
370                $res[$this->stripRouteFromKey( $routeKey )] = $value;
371            }
372        } else {
373            $res = false;
374        }
375
376        $res = $this->checkResult( false, $res );
377
378        return $res !== false ? $res : [];
379    }
380
381    /** @inheritDoc */
382    protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
383        $this->debug( 'setMulti(' . implode( ', ', array_keys( $data ) ) . ')' );
384
385        $exptime = $this->fixExpiry( $exptime );
386        $dataByRouteKey = [];
387        foreach ( $data as $key => $value ) {
388            $dataByRouteKey[$this->validateKeyAndPrependRoute( $key )] = $value;
389        }
390
391        $noReplyScope = $this->noReplyScope( $flags );
392
393        // Ignore "failed to set" warning from php-memcached 3.x (T251450)
394        // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
395        $result = @$this->client->setMulti( $dataByRouteKey, $exptime );
396        ScopedCallback::consume( $noReplyScope );
397
398        return $this->checkResult( false, $result );
399    }
400
401    /** @inheritDoc */
402    protected function doDeleteMulti( array $keys, $flags = 0 ) {
403        $this->debug( 'deleteMulti(' . implode( ', ', $keys ) . ')' );
404
405        $routeKeys = [];
406        foreach ( $keys as $key ) {
407            $routeKeys[] = $this->validateKeyAndPrependRoute( $key );
408        }
409
410        $noReplyScope = $this->noReplyScope( $flags );
411        $resultArray = $this->client->deleteMulti( $routeKeys ) ?: [];
412        ScopedCallback::consume( $noReplyScope );
413
414        $result = true;
415        foreach ( $resultArray as $code ) {
416            if ( !in_array( $code, [ true, Memcached::RES_NOTFOUND ], true ) ) {
417                // "Not found" is counted as success in our interface
418                $result = false;
419            }
420        }
421
422        return $this->checkResult( false, $result );
423    }
424
425    /** @inheritDoc */
426    protected function doChangeTTL( $key, $exptime, $flags ) {
427        $this->debug( "touch($key)" );
428
429        $routeKey = $this->validateKeyAndPrependRoute( $key );
430        // Avoid NO_REPLY due to libmemcached hang
431        // https://phabricator.wikimedia.org/T310662#8031692
432        $result = $this->client->touch( $routeKey, $this->fixExpiry( $exptime ) );
433
434        return $this->checkResult( $key, $result );
435    }
436
437    /** @inheritDoc */
438    protected function serialize( $value ) {
439        if ( is_int( $value ) ) {
440            return $value;
441        }
442
443        $serializer = $this->client->getOption( Memcached::OPT_SERIALIZER );
444        if ( $serializer === Memcached::SERIALIZER_PHP ) {
445            return serialize( $value );
446        } elseif ( $serializer === Memcached::SERIALIZER_IGBINARY ) {
447            return igbinary_serialize( $value );
448        }
449
450        throw new UnexpectedValueException( __METHOD__ . ": got serializer '$serializer'." );
451    }
452
453    /** @inheritDoc */
454    protected function unserialize( $value ) {
455        if ( $this->isInteger( $value ) ) {
456            return (int)$value;
457        }
458
459        $serializer = $this->client->getOption( Memcached::OPT_SERIALIZER );
460        if ( $serializer === Memcached::SERIALIZER_PHP ) {
461            return unserialize( $value );
462        } elseif ( $serializer === Memcached::SERIALIZER_IGBINARY ) {
463            return igbinary_unserialize( $value );
464        }
465
466        throw new UnexpectedValueException( __METHOD__ . ": got serializer '$serializer'." );
467    }
468}
469
470/** @deprecated class alias since 1.43 */
471class_alias( MemcachedPeclBagOStuff::class, 'MemcachedPeclBagOStuff' );