Merge "Don't check namespace in SpecialWantedtemplates"
[lhc/web/wiklou.git] / includes / objectcache / MemcachedPeclBagOStuff.php
1 <?php
2 /**
3 * Object caching using memcached.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Cache
22 */
23
24 /**
25 * A wrapper class for the PECL memcached client
26 *
27 * @ingroup Cache
28 */
29 class MemcachedPeclBagOStuff extends MemcachedBagOStuff {
30
31 /**
32 * Constructor
33 *
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
47 */
48 function __construct( $params ) {
49 parent::__construct( $params );
50 $params = $this->applyDefaultParams( $params );
51
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
60 }
61 } else {
62 $this->client = new Memcached;
63 }
64
65 if ( !isset( $params['serializer'] ) ) {
66 $params['serializer'] = 'php';
67 }
68
69 if ( isset( $params['retry_timeout'] ) ) {
70 $this->client->setOption( Memcached::OPT_RETRY_TIMEOUT, $params['retry_timeout'] );
71 }
72
73 if ( isset( $params['server_failure_limit'] ) ) {
74 $this->client->setOption( Memcached::OPT_SERVER_FAILURE_LIMIT, $params['server_failure_limit'] );
75 }
76
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'] );
81
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 );
87
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 );
95
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.' );
105 }
106 $this->client->setOption( Memcached::OPT_SERIALIZER, Memcached::SERIALIZER_IGBINARY );
107 break;
108 default:
109 throw new MWException( __CLASS__ . ': invalid value for serializer parameter' );
110 }
111 $servers = array();
112 foreach ( $params['servers'] as $host ) {
113 $servers[] = IP::splitHostAndPort( $host ); // (ip, port)
114 }
115 $this->client->addServers( $servers );
116 }
117
118 public function get( $key, &$casToken = null, $flags = 0 ) {
119 $this->debugLog( "get($key)" );
120 $result = $this->client->get( $this->encodeKey( $key ), null, $casToken );
121 $result = $this->checkResult( $key, $result );
122 return $result;
123 }
124
125 /**
126 * @param string $key
127 * @param mixed $value
128 * @param int $exptime
129 * @return bool
130 */
131 public function set( $key, $value, $exptime = 0 ) {
132 $this->debugLog( "set($key)" );
133 return $this->checkResult( $key, parent::set( $key, $value, $exptime ) );
134 }
135
136 /**
137 * @param float $casToken
138 * @param string $key
139 * @param mixed $value
140 * @param int $exptime
141 * @return bool
142 */
143 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
144 $this->debugLog( "cas($key)" );
145 return $this->checkResult( $key, parent::cas( $casToken, $key, $value, $exptime ) );
146 }
147
148 /**
149 * @param string $key
150 * @return bool
151 */
152 public function delete( $key ) {
153 $this->debugLog( "delete($key)" );
154 $result = parent::delete( $key );
155 if ( $result === false && $this->client->getResultCode() === Memcached::RES_NOTFOUND ) {
156 // "Not found" is counted as success in our interface
157 return true;
158 } else {
159 return $this->checkResult( $key, $result );
160 }
161 }
162
163 /**
164 * @param string $key
165 * @param int $value
166 * @param int $exptime
167 * @return mixed
168 */
169 public function add( $key, $value, $exptime = 0 ) {
170 $this->debugLog( "add($key)" );
171 return $this->checkResult( $key, parent::add( $key, $value, $exptime ) );
172 }
173
174 /**
175 * @param string $key
176 * @param int $value
177 * @return mixed
178 */
179 public function incr( $key, $value = 1 ) {
180 $this->debugLog( "incr($key)" );
181 $result = $this->client->increment( $key, $value );
182 return $this->checkResult( $key, $result );
183 }
184
185 /**
186 * @param string $key
187 * @param int $value
188 * @return mixed
189 */
190 public function decr( $key, $value = 1 ) {
191 $this->debugLog( "decr($key)" );
192 $result = $this->client->decrement( $key, $value );
193 return $this->checkResult( $key, $result );
194 }
195
196 /**
197 * Check the return value from a client method call and take any necessary
198 * action. Returns the value that the wrapper function should return. At
199 * present, the return value is always the same as the return value from
200 * the client, but some day we might find a case where it should be
201 * different.
202 *
203 * @param string $key The key used by the caller, or false if there wasn't one.
204 * @param mixed $result The return value
205 * @return mixed
206 */
207 protected function checkResult( $key, $result ) {
208 if ( $result !== false ) {
209 return $result;
210 }
211 switch ( $this->client->getResultCode() ) {
212 case Memcached::RES_SUCCESS:
213 break;
214 case Memcached::RES_DATA_EXISTS:
215 case Memcached::RES_NOTSTORED:
216 case Memcached::RES_NOTFOUND:
217 $this->debugLog( "result: " . $this->client->getResultMessage() );
218 break;
219 default:
220 $msg = $this->client->getResultMessage();
221 $logCtx = array();
222 if ( $key !== false ) {
223 $server = $this->client->getServerByKey( $key );
224 $logCtx['memcached-server'] = "{$server['host']}:{$server['port']}";
225 $logCtx['memcached-key'] = $key;
226 $msg = "Memcached error for key \"{memcached-key}\" on server \"{memcached-server}\": $msg";
227 } else {
228 $msg = "Memcached error: $msg";
229 }
230 $this->logger->error( $msg, $logCtx );
231 $this->setLastError( BagOStuff::ERR_UNEXPECTED );
232 }
233 return $result;
234 }
235
236 public function getMulti( array $keys, $flags = 0 ) {
237 $this->debugLog( 'getMulti(' . implode( ', ', $keys ) . ')' );
238 $callback = array( $this, 'encodeKey' );
239 $encodedResult = $this->client->getMulti( array_map( $callback, $keys ) );
240 $encodedResult = $encodedResult ?: array(); // must be an array
241 $result = array();
242 foreach ( $encodedResult as $key => $value ) {
243 $key = $this->decodeKey( $key );
244 $result[$key] = $value;
245 }
246 return $this->checkResult( false, $result );
247 }
248
249 /**
250 * @param array $data
251 * @param int $exptime
252 * @return bool
253 */
254 public function setMulti( array $data, $exptime = 0 ) {
255 foreach ( $data as $key => $value ) {
256 $encKey = $this->encodeKey( $key );
257 if ( $encKey !== $key ) {
258 $data[$encKey] = $value;
259 unset( $data[$key] );
260 }
261 }
262 $this->debugLog( 'setMulti(' . implode( ', ', array_keys( $data ) ) . ')' );
263 $result = $this->client->setMulti( $data, $this->fixExpiry( $exptime ) );
264 return $this->checkResult( false, $result );
265 }
266 }