Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / objectcache / MemcachedPeclBagOStuff.php
blobf2c49281ba537c8e595194c5048ed0e464efeabc
1 <?php
2 /**
3 * Object caching using memcached.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Cache
24 /**
25 * A wrapper class for the PECL memcached client
27 * @ingroup Cache
29 class MemcachedPeclBagOStuff extends MemcachedBagOStuff {
31 /**
32 * Constructor
34 * Available parameters are:
35 * - servers: The list of IP:port combinations holding the memcached servers.
36 * - persistent: Whether to use a persistent connection
37 * - compress_threshold: The minimum size an object must be before it is compressed
38 * - timeout: The read timeout in microseconds
39 * - connect_timeout: The connect timeout in seconds
40 * - retry_timeout: Time in seconds to wait before retrying a failed connect attempt
41 * - server_failure_limit: Limit for server connect failures before it is removed
42 * - serializer: May be either "php" or "igbinary". Igbinary produces more compact
43 * values, but serialization is much slower unless the php.ini option
44 * igbinary.compact_strings is off.
45 * @param array $params
46 * @throws MWException
48 function __construct( $params ) {
49 parent::__construct( $params );
50 $params = $this->applyDefaultParams( $params );
52 if ( $params['persistent'] ) {
53 // The pool ID must be unique to the server/option combination.
54 // The Memcached object is essentially shared for each pool ID.
55 // We can only reuse a pool ID if we keep the config consistent.
56 $this->client = new Memcached( md5( serialize( $params ) ) );
57 if ( count( $this->client->getServerList() ) ) {
58 $this->logger->debug( __METHOD__ . ": persistent Memcached object already loaded." );
59 return; // already initialized; don't add duplicate servers
61 } else {
62 $this->client = new Memcached;
65 if ( !isset( $params['serializer'] ) ) {
66 $params['serializer'] = 'php';
69 if ( isset( $params['retry_timeout'] ) ) {
70 $this->client->setOption( Memcached::OPT_RETRY_TIMEOUT, $params['retry_timeout'] );
73 if ( isset( $params['server_failure_limit'] ) ) {
74 $this->client->setOption( Memcached::OPT_SERVER_FAILURE_LIMIT, $params['server_failure_limit'] );
77 // The compression threshold is an undocumented php.ini option for some
78 // reason. There's probably not much harm in setting it globally, for
79 // compatibility with the settings for the PHP client.
80 ini_set( 'memcached.compression_threshold', $params['compress_threshold'] );
82 // Set timeouts
83 $this->client->setOption( Memcached::OPT_CONNECT_TIMEOUT, $params['connect_timeout'] * 1000 );
84 $this->client->setOption( Memcached::OPT_SEND_TIMEOUT, $params['timeout'] );
85 $this->client->setOption( Memcached::OPT_RECV_TIMEOUT, $params['timeout'] );
86 $this->client->setOption( Memcached::OPT_POLL_TIMEOUT, $params['timeout'] / 1000 );
88 // Set libketama mode since it's recommended by the documentation and
89 // is as good as any. There's no way to configure libmemcached to use
90 // hashes identical to the ones currently in use by the PHP client, and
91 // even implementing one of the libmemcached hashes in pure PHP for
92 // forwards compatibility would require MWMemcached::get_sock() to be
93 // rewritten.
94 $this->client->setOption( Memcached::OPT_LIBKETAMA_COMPATIBLE, true );
96 // Set the serializer
97 switch ( $params['serializer'] ) {
98 case 'php':
99 $this->client->setOption( Memcached::OPT_SERIALIZER, Memcached::SERIALIZER_PHP );
100 break;
101 case 'igbinary':
102 if ( !Memcached::HAVE_IGBINARY ) {
103 throw new MWException( __CLASS__ . ': the igbinary extension is not available ' .
104 'but igbinary serialization was requested.' );
106 $this->client->setOption( Memcached::OPT_SERIALIZER, Memcached::SERIALIZER_IGBINARY );
107 break;
108 default:
109 throw new MWException( __CLASS__ . ': invalid value for serializer parameter' );
111 $servers = array();
112 foreach ( $params['servers'] as $host ) {
113 $servers[] = IP::splitHostAndPort( $host ); // (ip, port)
115 $this->client->addServers( $servers );
119 * @param string $key
120 * @param float $casToken [optional]
121 * @return mixed
123 public function get( $key, &$casToken = null ) {
124 $this->debugLog( "get($key)" );
125 $result = $this->client->get( $this->encodeKey( $key ), null, $casToken );
126 $result = $this->checkResult( $key, $result );
127 return $result;
131 * @param string $key
132 * @param mixed $value
133 * @param int $exptime
134 * @return bool
136 public function set( $key, $value, $exptime = 0 ) {
137 $this->debugLog( "set($key)" );
138 return $this->checkResult( $key, parent::set( $key, $value, $exptime ) );
142 * @param float $casToken
143 * @param string $key
144 * @param mixed $value
145 * @param int $exptime
146 * @return bool
148 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
149 $this->debugLog( "cas($key)" );
150 return $this->checkResult( $key, parent::cas( $casToken, $key, $value, $exptime ) );
154 * @param string $key
155 * @return bool
157 public function delete( $key ) {
158 $this->debugLog( "delete($key)" );
159 $result = parent::delete( $key );
160 if ( $result === false && $this->client->getResultCode() === Memcached::RES_NOTFOUND ) {
161 // "Not found" is counted as success in our interface
162 return true;
163 } else {
164 return $this->checkResult( $key, $result );
169 * @param string $key
170 * @param int $value
171 * @param int $exptime
172 * @return mixed
174 public function add( $key, $value, $exptime = 0 ) {
175 $this->debugLog( "add($key)" );
176 return $this->checkResult( $key, parent::add( $key, $value, $exptime ) );
180 * @param string $key
181 * @param int $value
182 * @return mixed
184 public function incr( $key, $value = 1 ) {
185 $this->debugLog( "incr($key)" );
186 $result = $this->client->increment( $key, $value );
187 return $this->checkResult( $key, $result );
191 * @param string $key
192 * @param int $value
193 * @return mixed
195 public function decr( $key, $value = 1 ) {
196 $this->debugLog( "decr($key)" );
197 $result = $this->client->decrement( $key, $value );
198 return $this->checkResult( $key, $result );
202 * Check the return value from a client method call and take any necessary
203 * action. Returns the value that the wrapper function should return. At
204 * present, the return value is always the same as the return value from
205 * the client, but some day we might find a case where it should be
206 * different.
208 * @param string $key The key used by the caller, or false if there wasn't one.
209 * @param mixed $result The return value
210 * @return mixed
212 protected function checkResult( $key, $result ) {
213 if ( $result !== false ) {
214 return $result;
216 switch ( $this->client->getResultCode() ) {
217 case Memcached::RES_SUCCESS:
218 break;
219 case Memcached::RES_DATA_EXISTS:
220 case Memcached::RES_NOTSTORED:
221 case Memcached::RES_NOTFOUND:
222 $this->debugLog( "result: " . $this->client->getResultMessage() );
223 break;
224 default:
225 $msg = $this->client->getResultMessage();
226 $logCtx = array();
227 if ( $key !== false ) {
228 $server = $this->client->getServerByKey( $key );
229 $logCtx['memcached-server'] = "{$server['host']}:{$server['port']}";
230 $logCtx['memcached-key'] = $key;
231 $msg = "Memcached error for key \"{memcached-key}\" on server \"{memcached-server}\": $msg";
232 } else {
233 $msg = "Memcached error: $msg";
235 $this->logger->error( $msg, $logCtx );
236 $this->setLastError( BagOStuff::ERR_UNEXPECTED );
238 return $result;
242 * @param array $keys
243 * @return array
245 public function getMulti( array $keys ) {
246 $this->debugLog( 'getMulti(' . implode( ', ', $keys ) . ')' );
247 $callback = array( $this, 'encodeKey' );
248 $result = $this->client->getMulti( array_map( $callback, $keys ) );
249 $result = $result ?: array(); // must be an array
250 return $this->checkResult( false, $result );
254 * @param array $data
255 * @param int $exptime
256 * @return bool
258 public function setMulti( array $data, $exptime = 0 ) {
259 foreach ( $data as $key => $value ) {
260 $encKey = $this->encodeKey( $key );
261 if ( $encKey !== $key ) {
262 $data[$encKey] = $value;
263 unset( $data[$key] );
266 $this->debugLog( 'setMulti(' . implode( ', ', array_keys( $data ) ) . ')' );
267 $result = $this->client->setMulti( $data, $this->fixExpiry( $exptime ) );
268 return $this->checkResult( false, $result );