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    #[\NoDiscard]
157    private function noReplyScope( $flags ): ?ScopedCallback {
158        if ( $flags !== true && !( $flags & self::WRITE_BACKGROUND ) ) {
159            return null;
160        }
161        $client = $this->client;
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
169    /** @inheritDoc */
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 ) {
180            /** @noinspection PhpUndefinedClassConstantInspection */
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
196    /** @inheritDoc */
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
212    /** @inheritDoc */
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
226    /** @inheritDoc */
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
241    /** @inheritDoc */
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
257    /** @inheritDoc */
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
271    /** @inheritDoc */
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
292    /**
293     * Check the return value from a client method call and take any necessary
294     * action. Returns the value that the wrapper function should return. At
295     * present, the return value is always the same as the return value from
296     * the client, but some day we might find a case where it should be
297     * different.
298     *
299     * @param string|false $key The key used by the caller, or false if there wasn't one.
300     * @param mixed $result The return value
301     *
302     * @return mixed
303     */
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
352    /** @inheritDoc */
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
380    /** @inheritDoc */
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
400    /** @inheritDoc */
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
424    /** @inheritDoc */
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
436    /** @inheritDoc */
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
452    /** @inheritDoc */
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
469/** @deprecated class alias since 1.43 */
470class_alias( MemcachedPeclBagOStuff::class, 'MemcachedPeclBagOStuff' );