Export mw.Message's string formatter as mw.format
[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 $params = $this->applyDefaultParams( $params );
50
51 if ( $params['persistent'] ) {
52 // The pool ID must be unique to the server/option combination.
53 // The Memcached object is essentially shared for each pool ID.
54 // We can only reuse a pool ID if we keep the config consistent.
55 $this->client = new Memcached( md5( serialize( $params ) ) );
56 if ( count( $this->client->getServerList() ) ) {
57 wfDebug( __METHOD__ . ": persistent Memcached object already loaded.\n" );
58 return; // already initialized; don't add duplicate servers
59 }
60 } else {
61 $this->client = new Memcached;
62 }
63
64 if ( !isset( $params['serializer'] ) ) {
65 $params['serializer'] = 'php';
66 }
67
68 if ( isset( $params['retry_timeout'] ) ) {
69 $this->client->setOption( Memcached::OPT_RETRY_TIMEOUT, $params['retry_timeout'] );
70 }
71
72 if ( isset( $params['server_failure_limit'] ) ) {
73 $this->client->setOption( Memcached::OPT_SERVER_FAILURE_LIMIT, $params['server_failure_limit'] );
74 }
75
76 // The compression threshold is an undocumented php.ini option for some
77 // reason. There's probably not much harm in setting it globally, for
78 // compatibility with the settings for the PHP client.
79 ini_set( 'memcached.compression_threshold', $params['compress_threshold'] );
80
81 // Set timeouts
82 $this->client->setOption( Memcached::OPT_CONNECT_TIMEOUT, $params['connect_timeout'] * 1000 );
83 $this->client->setOption( Memcached::OPT_SEND_TIMEOUT, $params['timeout'] );
84 $this->client->setOption( Memcached::OPT_RECV_TIMEOUT, $params['timeout'] );
85 $this->client->setOption( Memcached::OPT_POLL_TIMEOUT, $params['timeout'] / 1000 );
86
87 // Set libketama mode since it's recommended by the documentation and
88 // is as good as any. There's no way to configure libmemcached to use
89 // hashes identical to the ones currently in use by the PHP client, and
90 // even implementing one of the libmemcached hashes in pure PHP for
91 // forwards compatibility would require MWMemcached::get_sock() to be
92 // rewritten.
93 $this->client->setOption( Memcached::OPT_LIBKETAMA_COMPATIBLE, true );
94
95 // Set the serializer
96 switch ( $params['serializer'] ) {
97 case 'php':
98 $this->client->setOption( Memcached::OPT_SERIALIZER, Memcached::SERIALIZER_PHP );
99 break;
100 case 'igbinary':
101 if ( !Memcached::HAVE_IGBINARY ) {
102 throw new MWException( __CLASS__ . ': the igbinary extension is not available ' .
103 'but igbinary serialization was requested.' );
104 }
105 $this->client->setOption( Memcached::OPT_SERIALIZER, Memcached::SERIALIZER_IGBINARY );
106 break;
107 default:
108 throw new MWException( __CLASS__ . ': invalid value for serializer parameter' );
109 }
110 $servers = array();
111 foreach ( $params['servers'] as $host ) {
112 $servers[] = IP::splitHostAndPort( $host ); // (ip, port)
113 }
114 $this->client->addServers( $servers );
115 }
116
117 /**
118 * @param string $key
119 * @param float $casToken [optional]
120 * @return mixed
121 */
122 public function get( $key, &$casToken = null ) {
123 wfProfileIn( __METHOD__ );
124 $this->debugLog( "get($key)" );
125 $result = $this->client->get( $this->encodeKey( $key ), null, $casToken );
126 $result = $this->checkResult( $key, $result );
127 wfProfileOut( __METHOD__ );
128 return $result;
129 }
130
131 /**
132 * @param string $key
133 * @param mixed $value
134 * @param int $exptime
135 * @return bool
136 */
137 public function set( $key, $value, $exptime = 0 ) {
138 $this->debugLog( "set($key)" );
139 return $this->checkResult( $key, parent::set( $key, $value, $exptime ) );
140 }
141
142 /**
143 * @param float $casToken
144 * @param string $key
145 * @param mixed $value
146 * @param int $exptime
147 * @return bool
148 */
149 public function cas( $casToken, $key, $value, $exptime = 0 ) {
150 $this->debugLog( "cas($key)" );
151 return $this->checkResult( $key, parent::cas( $casToken, $key, $value, $exptime ) );
152 }
153
154 /**
155 * @param string $key
156 * @param int $time
157 * @return bool
158 */
159 public function delete( $key, $time = 0 ) {
160 $this->debugLog( "delete($key)" );
161 $result = parent::delete( $key, $time );
162 if ( $result === false && $this->client->getResultCode() === Memcached::RES_NOTFOUND ) {
163 // "Not found" is counted as success in our interface
164 return true;
165 } else {
166 return $this->checkResult( $key, $result );
167 }
168 }
169
170 /**
171 * @param string $key
172 * @param int $value
173 * @param int $exptime
174 * @return mixed
175 */
176 public function add( $key, $value, $exptime = 0 ) {
177 $this->debugLog( "add($key)" );
178 return $this->checkResult( $key, parent::add( $key, $value, $exptime ) );
179 }
180
181 /**
182 * @param string $key
183 * @param int $value
184 * @return mixed
185 */
186 public function incr( $key, $value = 1 ) {
187 $this->debugLog( "incr($key)" );
188 $result = $this->client->increment( $key, $value );
189 return $this->checkResult( $key, $result );
190 }
191
192 /**
193 * @param string $key
194 * @param int $value
195 * @return mixed
196 */
197 public function decr( $key, $value = 1 ) {
198 $this->debugLog( "decr($key)" );
199 $result = $this->client->decrement( $key, $value );
200 return $this->checkResult( $key, $result );
201 }
202
203 /**
204 * Check the return value from a client method call and take any necessary
205 * action. Returns the value that the wrapper function should return. At
206 * present, the return value is always the same as the return value from
207 * the client, but some day we might find a case where it should be
208 * different.
209 *
210 * @param string $key The key used by the caller, or false if there wasn't one.
211 * @param mixed $result The return value
212 * @return mixed
213 */
214 protected function checkResult( $key, $result ) {
215 if ( $result !== false ) {
216 return $result;
217 }
218 switch ( $this->client->getResultCode() ) {
219 case Memcached::RES_SUCCESS:
220 break;
221 case Memcached::RES_DATA_EXISTS:
222 case Memcached::RES_NOTSTORED:
223 case Memcached::RES_NOTFOUND:
224 $this->debugLog( "result: " . $this->client->getResultMessage() );
225 break;
226 default:
227 $msg = $this->client->getResultMessage();
228 if ( $key !== false ) {
229 $server = $this->client->getServerByKey( $key );
230 $serverName = "{$server['host']}:{$server['port']}";
231 $msg = "Memcached error for key \"$key\" on server \"$serverName\": $msg";
232 } else {
233 $msg = "Memcached error: $msg";
234 }
235 wfDebugLog( 'memcached-serious', $msg );
236 $this->setLastError( BagOStuff::ERR_UNEXPECTED );
237 }
238 return $result;
239 }
240
241 /**
242 * @param array $keys
243 * @return array
244 */
245 public function getMulti( array $keys ) {
246 wfProfileIn( __METHOD__ );
247 $this->debugLog( 'getMulti(' . implode( ', ', $keys ) . ')' );
248 $callback = array( $this, 'encodeKey' );
249 $result = $this->client->getMulti( array_map( $callback, $keys ) );
250 wfProfileOut( __METHOD__ );
251 $result = $result ?: array(); // must be an array
252 return $this->checkResult( false, $result );
253 }
254
255 /**
256 * @param array $data
257 * @param int $exptime
258 * @return bool
259 */
260 public function setMulti( array $data, $exptime = 0 ) {
261 wfProfileIn( __METHOD__ );
262 foreach ( $data as $key => $value ) {
263 $encKey = $this->encodeKey( $key );
264 if ( $encKey !== $key ) {
265 $data[$encKey] = $value;
266 unset( $data[$key] );
267 }
268 }
269 $this->debugLog( 'setMulti(' . implode( ', ', array_keys( $data ) ) . ')' );
270 $result = $this->client->setMulti( $data, $this->fixExpiry( $exptime ) );
271 wfProfileOut( __METHOD__ );
272 return $this->checkResult( false, $result );
273 }
274 }