Merge "Check validity and availability of usernames during signup via AJAX"
[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 */
46 function __construct( $params ) {
47 $params = $this->applyDefaultParams( $params );
48
49 if ( $params['persistent'] ) {
50 // The pool ID must be unique to the server/option combination.
51 // The Memcached object is essentially shared for each pool ID.
52 // We can only reuse a pool ID if we keep the config consistent.
53 $this->client = new Memcached( md5( serialize( $params ) ) );
54 if ( count( $this->client->getServerList() ) ) {
55 wfDebug( __METHOD__ . ": persistent Memcached object already loaded.\n" );
56 return; // already initialized; don't add duplicate servers
57 }
58 } else {
59 $this->client = new Memcached;
60 }
61
62 if ( !isset( $params['serializer'] ) ) {
63 $params['serializer'] = 'php';
64 }
65
66 if ( isset( $params['retry_timeout'] ) ) {
67 $this->client->setOption( Memcached::OPT_RETRY_TIMEOUT, $params['retry_timeout'] );
68 }
69
70 if ( isset( $params['server_failure_limit'] ) ) {
71 $this->client->setOption( Memcached::OPT_SERVER_FAILURE_LIMIT, $params['server_failure_limit'] );
72 }
73
74 // The compression threshold is an undocumented php.ini option for some
75 // reason. There's probably not much harm in setting it globally, for
76 // compatibility with the settings for the PHP client.
77 ini_set( 'memcached.compression_threshold', $params['compress_threshold'] );
78
79 // Set timeouts
80 $this->client->setOption( Memcached::OPT_CONNECT_TIMEOUT, $params['connect_timeout'] * 1000 );
81 $this->client->setOption( Memcached::OPT_SEND_TIMEOUT, $params['timeout'] );
82 $this->client->setOption( Memcached::OPT_RECV_TIMEOUT, $params['timeout'] );
83 $this->client->setOption( Memcached::OPT_POLL_TIMEOUT, $params['timeout'] / 1000 );
84
85 // Set libketama mode since it's recommended by the documentation and
86 // is as good as any. There's no way to configure libmemcached to use
87 // hashes identical to the ones currently in use by the PHP client, and
88 // even implementing one of the libmemcached hashes in pure PHP for
89 // forwards compatibility would require MWMemcached::get_sock() to be
90 // rewritten.
91 $this->client->setOption( Memcached::OPT_LIBKETAMA_COMPATIBLE, true );
92
93 // Set the serializer
94 switch ( $params['serializer'] ) {
95 case 'php':
96 $this->client->setOption( Memcached::OPT_SERIALIZER, Memcached::SERIALIZER_PHP );
97 break;
98 case 'igbinary':
99 if ( !Memcached::HAVE_IGBINARY ) {
100 throw new MWException( __CLASS__ . ': the igbinary extension is not available ' .
101 'but igbinary serialization was requested.' );
102 }
103 $this->client->setOption( Memcached::OPT_SERIALIZER, Memcached::SERIALIZER_IGBINARY );
104 break;
105 default:
106 throw new MWException( __CLASS__ . ': invalid value for serializer parameter' );
107 }
108 $servers = array();
109 foreach ( $params['servers'] as $host ) {
110 $servers[] = IP::splitHostAndPort( $host ); // (ip, port)
111 }
112 $this->client->addServers( $servers );
113 }
114
115 /**
116 * @param $key string
117 * @param $casToken[optional] float
118 * @return Mixed
119 */
120 public function get( $key, &$casToken = null ) {
121 wfProfileIn( __METHOD__ );
122 $this->debugLog( "get($key)" );
123 $result = $this->client->get( $this->encodeKey( $key ), null, $casToken );
124 $result = $this->checkResult( $key, $result );
125 wfProfileOut( __METHOD__ );
126 return $result;
127 }
128
129 /**
130 * @param $key string
131 * @param $value
132 * @param $exptime int
133 * @return bool
134 */
135 public function set( $key, $value, $exptime = 0 ) {
136 $this->debugLog( "set($key)" );
137 return $this->checkResult( $key, parent::set( $key, $value, $exptime ) );
138 }
139
140 /**
141 * @param $casToken float
142 * @param $key string
143 * @param $value
144 * @param $exptime int
145 * @return bool
146 */
147 public function cas( $casToken, $key, $value, $exptime = 0 ) {
148 $this->debugLog( "cas($key)" );
149 return $this->checkResult( $key, parent::cas( $casToken, $key, $value, $exptime ) );
150 }
151
152 /**
153 * @param $key string
154 * @param $time int
155 * @return bool
156 */
157 public function delete( $key, $time = 0 ) {
158 $this->debugLog( "delete($key)" );
159 $result = parent::delete( $key, $time );
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 );
165 }
166 }
167
168 /**
169 * @param $key string
170 * @param $value int
171 * @param $exptime int
172 * @return Mixed
173 */
174 public function add( $key, $value, $exptime = 0 ) {
175 $this->debugLog( "add($key)" );
176 return $this->checkResult( $key, parent::add( $key, $value, $exptime ) );
177 }
178
179 /**
180 * @param $key string
181 * @param $value int
182 * @return Mixed
183 */
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 );
188 }
189
190 /**
191 * @param $key string
192 * @param $value int
193 * @return Mixed
194 */
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 );
199 }
200
201 /**
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.
207 *
208 * @param string $key The key used by the caller, or false if there wasn't one.
209 * @param $result Mixed The return value
210 * @return Mixed
211 */
212 protected function checkResult( $key, $result ) {
213 if ( $result !== false ) {
214 return $result;
215 }
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 if ( $key !== false ) {
227 $server = $this->client->getServerByKey( $key );
228 $serverName = "{$server['host']}:{$server['port']}";
229 $msg = "Memcached error for key \"$key\" on server \"$serverName\": $msg";
230 } else {
231 $msg = "Memcached error: $msg";
232 }
233 wfDebugLog( 'memcached-serious', $msg );
234 }
235 return $result;
236 }
237
238 /**
239 * @param $keys Array
240 * @return Array
241 */
242 public function getMulti( array $keys ) {
243 wfProfileIn( __METHOD__ );
244 $this->debugLog( 'getMulti(' . implode( ', ', $keys ) . ')' );
245 $callback = array( $this, 'encodeKey' );
246 $result = $this->client->getMulti( array_map( $callback, $keys ) );
247 wfProfileOut( __METHOD__ );
248 return $this->checkResult( false, $result );
249 }
250
251 /* NOTE: there is no cas() method here because it is currently not supported
252 * by the BagOStuff interface and other BagOStuff subclasses, such as
253 * SqlBagOStuff.
254 */
255 }