MDL-36768 cache: Implemented abstract cache store base class
[moodle.git] / cache / stores / memcached / lib.php
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/>.
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  *
22  * @package    cachestore_memcached
23  * @copyright  2012 Sam Hemelryk
24  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25  */
27 defined('MOODLE_INTERNAL') || die();
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  */
46 class cachestore_memcached extends cache_store_base {
48     /**
49      * The name of the store
50      * @var store
51      */
52     protected $name;
54     /**
55      * The memcached connection
56      * @var Memcached
57      */
58     protected $connection;
60     /**
61      * An array of servers to use during connection
62      * @var array
63      */
64     protected $servers = array();
66     /**
67      * The options used when establishing the connection
68      * @var array
69      */
70     protected $options = array();
72     /**
73      * True when this instance is ready to be initialised.
74      * @var bool
75      */
76     protected $isready = false;
78     /**
79      * The cache definition this store was initialised with.
80      * @var cache_definition
81      */
82     protected $definition;
84     /**
85      * Constructs the store instance.
86      *
87      * Noting that this function is not an initialisation. It is used to prepare the store for use.
88      * The store will be initialised when required and will be provided with a cache_definition at that time.
89      *
90      * @param string $name
91      * @param array $configuration
92      */
93     public function __construct($name, array $configuration = array()) {
94         $this->name = $name;
95         if (!array_key_exists('servers', $configuration) || empty($configuration['servers'])) {
96             // Nothing configured.
97             return;
98         }
99         if (!is_array($configuration['servers'])) {
100             $configuration['servers'] = array($configuration['servers']);
101         }
103         $compression = array_key_exists('compression', $configuration) ? (bool)$configuration['compression'] : true;
104         if (array_key_exists('serialiser', $configuration)) {
105             $serialiser = (int)$configuration['serialiser'];
106         } else {
107             $serialiser = Memcached::SERIALIZER_PHP;
108         }
109         $prefix = (!empty($configuration['prefix'])) ? (string)$configuration['prefix'] : crc32($name);
110         $hashmethod = (array_key_exists('hash', $configuration)) ? (int)$configuration['hash'] : Memcached::HASH_DEFAULT;
111         $bufferwrites = array_key_exists('bufferwrites', $configuration) ? (bool)$configuration['bufferwrites'] : false;
113         foreach ($configuration['servers'] as $server) {
114             if (!is_array($server)) {
115                 $server = explode(':', $server, 3);
116             }
117             if (!array_key_exists(1, $server)) {
118                 $server[1] = 11211;
119                 $server[2] = 100;
120             } else if (!array_key_exists(2, $server)) {
121                 $server[2] = 100;
122             }
123             $this->servers[] = $server;
124         }
125         $this->options[Memcached::OPT_COMPRESSION] = $compression;
126         $this->options[Memcached::OPT_SERIALIZER] = $serialiser;
127         $this->options[Memcached::OPT_PREFIX_KEY] = $prefix;
128         $this->options[Memcached::OPT_HASH] = $hashmethod;
129         $this->options[Memcached::OPT_BUFFER_WRITES] = $bufferwrites;
131         $this->isready = true;
132     }
134     /**
135      * Initialises the cache.
136      *
137      * Once this has been done the cache is all set to be used.
138      *
139      * @param cache_definition $definition
140      */
141     public function initialise(cache_definition $definition) {
142         if ($this->is_initialised()) {
143             throw new coding_exception('This memcached instance has already been initialised.');
144         }
145         $this->definition = $definition;
146         $this->connection = new Memcached(crc32($this->name));
147         $servers = $this->connection->getServerList();
148         if (empty($servers)) {
149             foreach ($this->options as $key => $value) {
150                 $this->connection->setOption($key, $value);
151             }
152             $this->connection->addServers($this->servers);
153         }
154     }
156     /**
157      * Returns true once this instance has been initialised.
158      *
159      * @return bool
160      */
161     public function is_initialised() {
162         return ($this->connection !== null);
163     }
165     /**
166      * Returns true if this store instance is ready to be used.
167      * @return bool
168      */
169     public function is_ready() {
170         return $this->isready;
171     }
173     /**
174      * Returns true if the store requirements are met.
175      *
176      * @return bool
177      */
178     public static function are_requirements_met() {
179         return class_exists('Memcached');
180     }
182     /**
183      * Returns true if the given mode is supported by this store.
184      *
185      * @param int $mode One of cache_store::MODE_*
186      * @return bool
187      */
188     public static function is_supported_mode($mode) {
189         return ($mode === self::MODE_APPLICATION || $mode === self::MODE_SESSION);
190     }
192     /**
193      * Returns the supported features as a combined int.
194      *
195      * @param array $configuration
196      * @return int
197      */
198     public static function get_supported_features(array $configuration = array()) {
199         return self::SUPPORTS_NATIVE_TTL;
200     }
202     /**
203      * Returns the supported modes as a combined int.
204      *
205      * @param array $configuration
206      * @return int
207      */
208     public static function get_supported_modes(array $configuration = array()) {
209         return self::MODE_APPLICATION + self::MODE_SESSION;
210     }
212     /**
213      * Retrieves an item from the cache store given its key.
214      *
215      * @param string $key The key to retrieve
216      * @return mixed The data that was associated with the key, or false if the key did not exist.
217      */
218     public function get($key) {
219         return $this->connection->get($key);
220     }
222     /**
223      * Retrieves several items from the cache store in a single transaction.
224      *
225      * 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.
226      *
227      * @param array $keys The array of keys to retrieve
228      * @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
229      *      be set to false.
230      */
231     public function get_many($keys) {
232         $result = $this->connection->getMulti($keys);
233         if (!is_array($result)) {
234             $result = array();
235         }
236         foreach ($keys as $key) {
237             if (!array_key_exists($key, $result)) {
238                 $result[$key] = false;
239             }
240         }
241         return $result;
242     }
244     /**
245      * Sets an item in the cache given its key and data value.
246      *
247      * @param string $key The key to use.
248      * @param mixed $data The data to set.
249      * @return bool True if the operation was a success false otherwise.
250      */
251     public function set($key, $data) {
252         return $this->connection->set($key, $data, $this->definition->get_ttl());
253     }
255     /**
256      * Sets many items in the cache in a single transaction.
257      *
258      * @param array $keyvaluearray An array of key value pairs. Each item in the array will be an associative array with two
259      *      keys, 'key' and 'value'.
260      * @return int The number of items successfully set. It is up to the developer to check this matches the number of items
261      *      sent ... if they care that is.
262      */
263     public function set_many(array $keyvaluearray) {
264         $pairs = array();
265         foreach ($keyvaluearray as $pair) {
266             $pairs[$pair['key']] = $pair['value'];
267         }
268         if ($this->connection->setMulti($pairs, $this->definition->get_ttl())) {
269             return count($keyvaluearray);
270         }
271         return 0;
272     }
274     /**
275      * Deletes an item from the cache store.
276      *
277      * @param string $key The key to delete.
278      * @return bool Returns true if the operation was a success, false otherwise.
279      */
280     public function delete($key) {
281         return $this->connection->delete($key);
282     }
284     /**
285      * Deletes several keys from the cache in a single action.
286      *
287      * @param array $keys The keys to delete
288      * @return int The number of items successfully deleted.
289      */
290     public function delete_many(array $keys) {
291         $count = 0;
292         foreach ($keys as $key) {
293             if ($this->connection->delete($key)) {
294                 $count++;
295             }
296         }
297         return $count;
298     }
300     /**
301      * Purges the cache deleting all items within it.
302      *
303      * @return boolean True on success. False otherwise.
304      */
305     public function purge() {
306         $this->connection->flush();
307         return true;
308     }
310     /**
311      * Gets an array of options to use as the serialiser.
312      * @return array
313      */
314     public static function config_get_serialiser_options() {
315         $options = array(
316             Memcached::SERIALIZER_PHP => get_string('serialiser_php', 'cachestore_memcached')
317         );
318         if (Memcached::HAVE_JSON) {
319             $options[Memcached::SERIALIZER_JSON] = get_string('serialiser_json', 'cachestore_memcached');
320         }
321         if (Memcached::HAVE_IGBINARY) {
322             $options[Memcached::SERIALIZER_IGBINARY] = get_string('serialiser_php', 'cachestore_memcached');
323         }
324         return $options;
325     }
327     /**
328      * Gets an array of hash options available during configuration.
329      * @return array
330      */
331     public static function config_get_hash_options() {
332         $options = array(
333             Memcached::HASH_DEFAULT => get_string('hash_default', 'cachestore_memcached'),
334             Memcached::HASH_MD5 => get_string('hash_md5', 'cachestore_memcached'),
335             Memcached::HASH_CRC => get_string('hash_crc', 'cachestore_memcached'),
336             Memcached::HASH_FNV1_64 => get_string('hash_fnv1_64', 'cachestore_memcached'),
337             Memcached::HASH_FNV1A_64 => get_string('hash_fnv1a_64', 'cachestore_memcached'),
338             Memcached::HASH_FNV1_32 => get_string('hash_fnv1_32', 'cachestore_memcached'),
339             Memcached::HASH_FNV1A_32 => get_string('hash_fnv1a_32', 'cachestore_memcached'),
340             Memcached::HASH_HSIEH => get_string('hash_hsieh', 'cachestore_memcached'),
341             Memcached::HASH_MURMUR => get_string('hash_murmur', 'cachestore_memcached'),
342         );
343         return $options;
344     }
346     /**
347      * Given the data from the add instance form this function creates a configuration array.
348      *
349      * @param stdClass $data
350      * @return array
351      */
352     public static function config_get_configuration_array($data) {
353         $lines = explode("\n", $data->servers);
354         $servers = array();
355         foreach ($lines as $line) {
356             $line = trim($line, ':');
357             $servers[] = explode(':', $line, 3);
358         }
359         return array(
360             'servers' => $servers,
361             'compression' => $data->compression,
362             'serialiser' => $data->serialiser,
363             'prefix' => $data->prefix,
364             'hash' => $data->hash,
365             'bufferwrites' => $data->bufferwrites,
366         );
367     }
369     /**
370      * Allows the cache store to set its data against the edit form before it is shown to the user.
371      *
372      * @param moodleform $editform
373      * @param array $config
374      */
375     public static function config_set_edit_form_data(moodleform $editform, array $config) {
376         $data = array();
377         if (!empty($config['servers'])) {
378             $servers = array();
379             foreach ($config['servers'] as $server) {
380                 $servers[] = join(":", $server);
381             }
382             $data['servers'] = join("\n", $servers);
383         }
384         if (isset($config['compression'])) {
385             $data['compression'] = (bool)$config['compression'];
386         }
387         if (!empty($config['serialiser'])) {
388             $data['serialiser'] = $config['serialiser'];
389         }
390         if (!empty($config['prefix'])) {
391             $data['prefix'] = $config['prefix'];
392         }
393         if (!empty($config['hash'])) {
394             $data['hash'] = $config['hash'];
395         }
396         if (isset($config['bufferwrites'])) {
397             $data['bufferwrites'] = (bool)$config['bufferwrites'];
398         }
399         $editform->set_data($data);
400     }
402     /**
403      * Performs any necessary clean up when the store instance is being deleted.
404      */
405     public function cleanup() {
406         $this->purge();
407     }
409     /**
410      * Generates an instance of the cache store that can be used for testing.
411      *
412      * @param cache_definition $definition
413      * @return false
414      */
415     public static function initialise_test_instance(cache_definition $definition) {
417         if (!self::are_requirements_met()) {
418             return false;
419         }
421         $config = get_config('cachestore_memcached');
422         if (empty($config->testservers)) {
423             return false;
424         }
426         $configuration = array();
427         $configuration['servers'] = $config->testservers;
428         if (!empty($config->testcompression)) {
429             $configuration['compression'] = $config->testcompression;
430         }
431         if (!empty($config->testserialiser)) {
432             $configuration['serialiser'] = $config->testserialiser;
433         }
434         if (!empty($config->testprefix)) {
435             $configuration['prefix'] = $config->testprefix;
436         }
437         if (!empty($config->testhash)) {
438             $configuration['hash'] = $config->testhash;
439         }
440         if (!empty($config->testbufferwrites)) {
441             $configuration['bufferwrites'] = $config->testbufferwrites;
442         }
444         $store = new cachestore_memcached('Test memcached', $configuration);
445         $store->initialise($definition);
447         return $store;
448     }
450     /**
451      * Returns the name of this instance.
452      * @return string
453      */
454     public function my_name() {
455         return $this->name;
456     }