MDL-36363 Override instance_deleted() for all cache stores performing just a cleanup...
[moodle.git] / cache / stores / memcached / lib.php
CommitLineData
47d89ccf
SH
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * The library file for the memcached cache store.
19 *
20 * This file is part of the memcached cache store, it contains the API for interacting with an instance of the store.
21 *
6fec1820 22 * @package cachestore_memcached
47d89ccf
SH
23 * @copyright 2012 Sam Hemelryk
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
27defined('MOODLE_INTERNAL') || die();
28
29/**
30 * The memcached store.
31 *
32 * (Not to be confused with the memcache store)
33 *
34 * Configuration options:
35 * servers: string: host:port:weight , ...
36 * compression: true, false
37 * serialiser: SERIALIZER_PHP, SERIALIZER_JSON, SERIALIZER_IGBINARY
38 * prefix: string: defaults to instance name
39 * hashmethod: HASH_DEFAULT, HASH_MD5, HASH_CRC, HASH_FNV1_64, HASH_FNV1A_64, HASH_FNV1_32,
40 * HASH_FNV1A_32, HASH_HSIEH, HASH_MURMUR
41 * bufferwrites: true, false
42 *
43 * @copyright 2012 Sam Hemelryk
44 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
45 */
2b274ad0 46class cachestore_memcached extends cache_store implements cache_is_configurable {
47d89ccf
SH
47 /**
48 * The name of the store
49 * @var store
50 */
51 protected $name;
52
53 /**
54 * The memcached connection
55 * @var Memcached
56 */
57 protected $connection;
58
59 /**
60 * An array of servers to use during connection
61 * @var array
62 */
63 protected $servers = array();
64
65 /**
66 * The options used when establishing the connection
67 * @var array
68 */
69 protected $options = array();
70
71 /**
72 * True when this instance is ready to be initialised.
73 * @var bool
74 */
75 protected $isready = false;
170f821b 76
47d89ccf
SH
77 /**
78 * The cache definition this store was initialised with.
79 * @var cache_definition
80 */
81 protected $definition;
82
83 /**
84 * Constructs the store instance.
85 *
86 * Noting that this function is not an initialisation. It is used to prepare the store for use.
87 * The store will be initialised when required and will be provided with a cache_definition at that time.
88 *
89 * @param string $name
90 * @param array $configuration
91 */
92 public function __construct($name, array $configuration = array()) {
93 $this->name = $name;
94 if (!array_key_exists('servers', $configuration) || empty($configuration['servers'])) {
95 // Nothing configured.
96 return;
97 }
42f5d164
SH
98 if (!is_array($configuration['servers'])) {
99 $configuration['servers'] = array($configuration['servers']);
100 }
47d89ccf
SH
101
102 $compression = array_key_exists('compression', $configuration) ? (bool)$configuration['compression'] : true;
170f821b
SH
103 if (array_key_exists('serialiser', $configuration)) {
104 $serialiser = (int)$configuration['serialiser'];
105 } else {
106 $serialiser = Memcached::SERIALIZER_PHP;
107 }
47d89ccf
SH
108 $prefix = (!empty($configuration['prefix'])) ? (string)$configuration['prefix'] : crc32($name);
109 $hashmethod = (array_key_exists('hash', $configuration)) ? (int)$configuration['hash'] : Memcached::HASH_DEFAULT;
110 $bufferwrites = array_key_exists('bufferwrites', $configuration) ? (bool)$configuration['bufferwrites'] : false;
111
112 foreach ($configuration['servers'] as $server) {
113 if (!is_array($server)) {
114 $server = explode(':', $server, 3);
115 }
116 if (!array_key_exists(1, $server)) {
117 $server[1] = 11211;
118 $server[2] = 100;
119 } else if (!array_key_exists(2, $server)) {
120 $server[2] = 100;
121 }
122 $this->servers[] = $server;
123 }
124 $this->options[Memcached::OPT_COMPRESSION] = $compression;
125 $this->options[Memcached::OPT_SERIALIZER] = $serialiser;
126 $this->options[Memcached::OPT_PREFIX_KEY] = $prefix;
127 $this->options[Memcached::OPT_HASH] = $hashmethod;
128 $this->options[Memcached::OPT_BUFFER_WRITES] = $bufferwrites;
129
130 $this->isready = true;
131 }
132
133 /**
134 * Initialises the cache.
135 *
136 * Once this has been done the cache is all set to be used.
137 *
138 * @param cache_definition $definition
139 */
140 public function initialise(cache_definition $definition) {
141 if ($this->is_initialised()) {
142 throw new coding_exception('This memcached instance has already been initialised.');
143 }
144 $this->definition = $definition;
145 $this->connection = new Memcached(crc32($this->name));
146 $servers = $this->connection->getServerList();
147 if (empty($servers)) {
148 foreach ($this->options as $key => $value) {
149 $this->connection->setOption($key, $value);
150 }
151 $this->connection->addServers($this->servers);
152 }
153 }
154
155 /**
156 * Returns true once this instance has been initialised.
157 *
158 * @return bool
159 */
160 public function is_initialised() {
161 return ($this->connection !== null);
162 }
163
164 /**
165 * Returns true if this store instance is ready to be used.
166 * @return bool
167 */
168 public function is_ready() {
169 return $this->isready;
170 }
171
172 /**
173 * Returns true if the store requirements are met.
174 *
175 * @return bool
176 */
177 public static function are_requirements_met() {
178 return class_exists('Memcached');
179 }
180
181 /**
182 * Returns true if the given mode is supported by this store.
183 *
184 * @param int $mode One of cache_store::MODE_*
185 * @return bool
186 */
187 public static function is_supported_mode($mode) {
188 return ($mode === self::MODE_APPLICATION || $mode === self::MODE_SESSION);
189 }
190
191 /**
192 * Returns the supported features as a combined int.
193 *
194 * @param array $configuration
195 * @return int
196 */
197 public static function get_supported_features(array $configuration = array()) {
198 return self::SUPPORTS_NATIVE_TTL;
199 }
200
47d89ccf
SH
201 /**
202 * Returns the supported modes as a combined int.
203 *
204 * @param array $configuration
205 * @return int
206 */
207 public static function get_supported_modes(array $configuration = array()) {
208 return self::MODE_APPLICATION + self::MODE_SESSION;
209 }
210
211 /**
212 * Retrieves an item from the cache store given its key.
213 *
214 * @param string $key The key to retrieve
215 * @return mixed The data that was associated with the key, or false if the key did not exist.
216 */
217 public function get($key) {
218 return $this->connection->get($key);
219 }
220
221 /**
222 * Retrieves several items from the cache store in a single transaction.
223 *
224 * If not all of the items are available in the cache then the data value for those that are missing will be set to false.
225 *
226 * @param array $keys The array of keys to retrieve
227 * @return array An array of items from the cache. There will be an item for each key, those that were not in the store will
228 * be set to false.
229 */
230 public function get_many($keys) {
231 $result = $this->connection->getMulti($keys);
232 if (!is_array($result)) {
233 $result = array();
234 }
235 foreach ($keys as $key) {
236 if (!array_key_exists($key, $result)) {
237 $result[$key] = false;
238 }
239 }
240 return $result;
241 }
242
243 /**
244 * Sets an item in the cache given its key and data value.
245 *
246 * @param string $key The key to use.
247 * @param mixed $data The data to set.
248 * @return bool True if the operation was a success false otherwise.
249 */
250 public function set($key, $data) {
251 return $this->connection->set($key, $data, $this->definition->get_ttl());
252 }
253
254 /**
255 * Sets many items in the cache in a single transaction.
256 *
257 * @param array $keyvaluearray An array of key value pairs. Each item in the array will be an associative array with two
258 * keys, 'key' and 'value'.
259 * @return int The number of items successfully set. It is up to the developer to check this matches the number of items
260 * sent ... if they care that is.
261 */
262 public function set_many(array $keyvaluearray) {
263 $pairs = array();
264 foreach ($keyvaluearray as $pair) {
265 $pairs[$pair['key']] = $pair['value'];
266 }
267 if ($this->connection->setMulti($pairs, $this->definition->get_ttl())) {
268 return count($keyvaluearray);
269 }
270 return 0;
271 }
272
273 /**
274 * Deletes an item from the cache store.
275 *
276 * @param string $key The key to delete.
277 * @return bool Returns true if the operation was a success, false otherwise.
278 */
279 public function delete($key) {
280 return $this->connection->delete($key);
281 }
282
283 /**
284 * Deletes several keys from the cache in a single action.
285 *
286 * @param array $keys The keys to delete
287 * @return int The number of items successfully deleted.
288 */
289 public function delete_many(array $keys) {
290 $count = 0;
291 foreach ($keys as $key) {
292 if ($this->connection->delete($key)) {
293 $count++;
294 }
295 }
296 return $count;
297 }
298
299 /**
300 * Purges the cache deleting all items within it.
301 *
302 * @return boolean True on success. False otherwise.
303 */
304 public function purge() {
305 $this->connection->flush();
306 return true;
307 }
308
309 /**
310 * Gets an array of options to use as the serialiser.
311 * @return array
312 */
313 public static function config_get_serialiser_options() {
314 $options = array(
6fec1820 315 Memcached::SERIALIZER_PHP => get_string('serialiser_php', 'cachestore_memcached')
47d89ccf
SH
316 );
317 if (Memcached::HAVE_JSON) {
6fec1820 318 $options[Memcached::SERIALIZER_JSON] = get_string('serialiser_json', 'cachestore_memcached');
47d89ccf
SH
319 }
320 if (Memcached::HAVE_IGBINARY) {
6fec1820 321 $options[Memcached::SERIALIZER_IGBINARY] = get_string('serialiser_php', 'cachestore_memcached');
47d89ccf
SH
322 }
323 return $options;
324 }
325
326 /**
327 * Gets an array of hash options available during configuration.
328 * @return array
329 */
330 public static function config_get_hash_options() {
331 $options = array(
6fec1820
SH
332 Memcached::HASH_DEFAULT => get_string('hash_default', 'cachestore_memcached'),
333 Memcached::HASH_MD5 => get_string('hash_md5', 'cachestore_memcached'),
334 Memcached::HASH_CRC => get_string('hash_crc', 'cachestore_memcached'),
335 Memcached::HASH_FNV1_64 => get_string('hash_fnv1_64', 'cachestore_memcached'),
336 Memcached::HASH_FNV1A_64 => get_string('hash_fnv1a_64', 'cachestore_memcached'),
337 Memcached::HASH_FNV1_32 => get_string('hash_fnv1_32', 'cachestore_memcached'),
338 Memcached::HASH_FNV1A_32 => get_string('hash_fnv1a_32', 'cachestore_memcached'),
339 Memcached::HASH_HSIEH => get_string('hash_hsieh', 'cachestore_memcached'),
340 Memcached::HASH_MURMUR => get_string('hash_murmur', 'cachestore_memcached'),
47d89ccf
SH
341 );
342 return $options;
343 }
344
345 /**
346 * Given the data from the add instance form this function creates a configuration array.
347 *
348 * @param stdClass $data
349 * @return array
350 */
351 public static function config_get_configuration_array($data) {
352 $lines = explode("\n", $data->servers);
353 $servers = array();
354 foreach ($lines as $line) {
355 $line = trim($line, ':');
356 $servers[] = explode(':', $line, 3);
357 }
358 return array(
359 'servers' => $servers,
360 'compression' => $data->compression,
361 'serialiser' => $data->serialiser,
362 'prefix' => $data->prefix,
363 'hash' => $data->hash,
364 'bufferwrites' => $data->bufferwrites,
365 );
366 }
367
81ede547
SH
368 /**
369 * Allows the cache store to set its data against the edit form before it is shown to the user.
370 *
371 * @param moodleform $editform
372 * @param array $config
373 */
374 public static function config_set_edit_form_data(moodleform $editform, array $config) {
375 $data = array();
376 if (!empty($config['servers'])) {
377 $servers = array();
378 foreach ($config['servers'] as $server) {
379 $servers[] = join(":", $server);
380 }
381 $data['servers'] = join("\n", $servers);
382 }
d837df0d
SH
383 if (isset($config['compression'])) {
384 $data['compression'] = (bool)$config['compression'];
81ede547
SH
385 }
386 if (!empty($config['serialiser'])) {
387 $data['serialiser'] = $config['serialiser'];
388 }
389 if (!empty($config['prefix'])) {
390 $data['prefix'] = $config['prefix'];
391 }
392 if (!empty($config['hash'])) {
393 $data['hash'] = $config['hash'];
394 }
d837df0d
SH
395 if (isset($config['bufferwrites'])) {
396 $data['bufferwrites'] = (bool)$config['bufferwrites'];
81ede547
SH
397 }
398 $editform->set_data($data);
399 }
400
47d89ccf
SH
401 /**
402 * Performs any necessary clean up when the store instance is being deleted.
403 */
404 public function cleanup() {
405 $this->purge();
406 }
407
59ca73ff
MS
408 /**
409 * Performs any necessary operation when the store instance is being deleted,
410 * regardless the store being initialised with a definition ({@link initialise()}).
411 *
412 * @link http://tracker.moodle.org/browse/MDL-36363
413 * @see cleanup()
414 */
415 public function instance_deleted() {
416 $this->cleanup();
417 }
418
47d89ccf
SH
419 /**
420 * Generates an instance of the cache store that can be used for testing.
421 *
422 * @param cache_definition $definition
423 * @return false
424 */
425 public static function initialise_test_instance(cache_definition $definition) {
426
427 if (!self::are_requirements_met()) {
428 return false;
429 }
430
6fec1820 431 $config = get_config('cachestore_memcached');
47d89ccf
SH
432 if (empty($config->testservers)) {
433 return false;
434 }
435
436 $configuration = array();
437 $configuration['servers'] = $config->testservers;
438 if (!empty($config->testcompression)) {
439 $configuration['compression'] = $config->testcompression;
440 }
441 if (!empty($config->testserialiser)) {
442 $configuration['serialiser'] = $config->testserialiser;
443 }
444 if (!empty($config->testprefix)) {
445 $configuration['prefix'] = $config->testprefix;
446 }
447 if (!empty($config->testhash)) {
448 $configuration['hash'] = $config->testhash;
449 }
450 if (!empty($config->testbufferwrites)) {
451 $configuration['bufferwrites'] = $config->testbufferwrites;
452 }
453
6fec1820 454 $store = new cachestore_memcached('Test memcached', $configuration);
47d89ccf
SH
455 $store->initialise($definition);
456
457 return $store;
458 }
34c84c72
SH
459
460 /**
461 * Returns the name of this instance.
462 * @return string
463 */
464 public function my_name() {
465 return $this->name;
466 }
47d89ccf 467}