2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * The library file for the memcached cache store.
20 * This file is part of the memcached cache store, it contains the API for interacting with an instance of the store.
22 * @package cachestore_memcached
23 * @copyright 2012 Sam Hemelryk
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
30 * The memcached store.
32 * (Not to be confused with the memcache store)
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
43 * @copyright 2012 Sam Hemelryk
44 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46 class cachestore_memcached extends cache_store implements cache_is_configurable {
48 * The name of the store
54 * The memcached connection
57 protected $connection;
60 * An array of servers to use during connection
63 protected $servers = array();
66 * The options used when establishing the connection
69 protected $options = array();
72 * True when this instance is ready to be initialised.
75 protected $isready = false;
78 * Set to true when this store instance has been initialised.
81 protected $isinitialised = false;
84 * The cache definition this store was initialised with.
85 * @var cache_definition
87 protected $definition;
90 * Constructs the store instance.
92 * Noting that this function is not an initialisation. It is used to prepare the store for use.
93 * The store will be initialised when required and will be provided with a cache_definition at that time.
96 * @param array $configuration
98 public function __construct($name, array $configuration = array()) {
100 if (!array_key_exists('servers', $configuration) || empty($configuration['servers'])) {
101 // Nothing configured.
104 if (!is_array($configuration['servers'])) {
105 $configuration['servers'] = array($configuration['servers']);
108 $compression = array_key_exists('compression', $configuration) ? (bool)$configuration['compression'] : true;
109 if (array_key_exists('serialiser', $configuration)) {
110 $serialiser = (int)$configuration['serialiser'];
112 $serialiser = Memcached::SERIALIZER_PHP;
114 $prefix = (!empty($configuration['prefix'])) ? (string)$configuration['prefix'] : crc32($name);
115 $hashmethod = (array_key_exists('hash', $configuration)) ? (int)$configuration['hash'] : Memcached::HASH_DEFAULT;
116 $bufferwrites = array_key_exists('bufferwrites', $configuration) ? (bool)$configuration['bufferwrites'] : false;
118 foreach ($configuration['servers'] as $server) {
119 if (!is_array($server)) {
120 $server = explode(':', $server, 3);
122 if (!array_key_exists(1, $server)) {
125 } else if (!array_key_exists(2, $server)) {
128 $this->servers[] = $server;
130 $this->options[Memcached::OPT_COMPRESSION] = $compression;
131 $this->options[Memcached::OPT_SERIALIZER] = $serialiser;
132 $this->options[Memcached::OPT_PREFIX_KEY] = $prefix;
133 $this->options[Memcached::OPT_HASH] = $hashmethod;
134 $this->options[Memcached::OPT_BUFFER_WRITES] = $bufferwrites;
136 $this->connection = new Memcached(crc32($this->name));
137 $servers = $this->connection->getServerList();
138 if (empty($servers)) {
139 foreach ($this->options as $key => $value) {
140 $this->connection->setOption($key, $value);
142 $this->connection->addServers($this->servers);
144 // Test the connection to the pool of servers.
145 $this->isready = @$this->connection->set("ping", 'ping', 1);
149 * Initialises the cache.
151 * Once this has been done the cache is all set to be used.
153 * @param cache_definition $definition
155 public function initialise(cache_definition $definition) {
156 if ($this->is_initialised()) {
157 throw new coding_exception('This memcached instance has already been initialised.');
159 $this->definition = $definition;
160 $this->isinitialised = true;
164 * Returns true once this instance has been initialised.
168 public function is_initialised() {
169 return ($this->isinitialised);
173 * Returns true if this store instance is ready to be used.
176 public function is_ready() {
177 return $this->isready;
181 * Returns true if the store requirements are met.
185 public static function are_requirements_met() {
186 return class_exists('Memcached');
190 * Returns true if the given mode is supported by this store.
192 * @param int $mode One of cache_store::MODE_*
195 public static function is_supported_mode($mode) {
196 return ($mode === self::MODE_APPLICATION || $mode === self::MODE_SESSION);
200 * Returns the supported features as a combined int.
202 * @param array $configuration
205 public static function get_supported_features(array $configuration = array()) {
206 return self::SUPPORTS_NATIVE_TTL;
210 * Returns false as this store does not support multiple identifiers.
211 * (This optional function is a performance optimisation; it must be
212 * consistent with the value from get_supported_features.)
216 public function supports_multiple_identifiers() {
221 * Returns the supported modes as a combined int.
223 * @param array $configuration
226 public static function get_supported_modes(array $configuration = array()) {
227 return self::MODE_APPLICATION;
231 * Retrieves an item from the cache store given its key.
233 * @param string $key The key to retrieve
234 * @return mixed The data that was associated with the key, or false if the key did not exist.
236 public function get($key) {
237 return $this->connection->get($key);
241 * Retrieves several items from the cache store in a single transaction.
243 * 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.
245 * @param array $keys The array of keys to retrieve
246 * @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
249 public function get_many($keys) {
250 $result = $this->connection->getMulti($keys);
251 if (!is_array($result)) {
254 foreach ($keys as $key) {
255 if (!array_key_exists($key, $result)) {
256 $result[$key] = false;
263 * Sets an item in the cache given its key and data value.
265 * @param string $key The key to use.
266 * @param mixed $data The data to set.
267 * @return bool True if the operation was a success false otherwise.
269 public function set($key, $data) {
270 return $this->connection->set($key, $data, $this->definition->get_ttl());
274 * Sets many items in the cache in a single transaction.
276 * @param array $keyvaluearray An array of key value pairs. Each item in the array will be an associative array with two
277 * keys, 'key' and 'value'.
278 * @return int The number of items successfully set. It is up to the developer to check this matches the number of items
279 * sent ... if they care that is.
281 public function set_many(array $keyvaluearray) {
283 foreach ($keyvaluearray as $pair) {
284 $pairs[$pair['key']] = $pair['value'];
286 if ($this->connection->setMulti($pairs, $this->definition->get_ttl())) {
287 return count($keyvaluearray);
293 * Deletes an item from the cache store.
295 * @param string $key The key to delete.
296 * @return bool Returns true if the operation was a success, false otherwise.
298 public function delete($key) {
299 return $this->connection->delete($key);
303 * Deletes several keys from the cache in a single action.
305 * @param array $keys The keys to delete
306 * @return int The number of items successfully deleted.
308 public function delete_many(array $keys) {
310 foreach ($keys as $key) {
311 if ($this->connection->delete($key)) {
319 * Purges the cache deleting all items within it.
321 * @return boolean True on success. False otherwise.
323 public function purge() {
324 if ($this->isready) {
325 $this->connection->flush();
332 * Gets an array of options to use as the serialiser.
335 public static function config_get_serialiser_options() {
337 Memcached::SERIALIZER_PHP => get_string('serialiser_php', 'cachestore_memcached')
339 if (Memcached::HAVE_JSON) {
340 $options[Memcached::SERIALIZER_JSON] = get_string('serialiser_json', 'cachestore_memcached');
342 if (Memcached::HAVE_IGBINARY) {
343 $options[Memcached::SERIALIZER_IGBINARY] = get_string('serialiser_igbinary', 'cachestore_memcached');
349 * Gets an array of hash options available during configuration.
352 public static function config_get_hash_options() {
354 Memcached::HASH_DEFAULT => get_string('hash_default', 'cachestore_memcached'),
355 Memcached::HASH_MD5 => get_string('hash_md5', 'cachestore_memcached'),
356 Memcached::HASH_CRC => get_string('hash_crc', 'cachestore_memcached'),
357 Memcached::HASH_FNV1_64 => get_string('hash_fnv1_64', 'cachestore_memcached'),
358 Memcached::HASH_FNV1A_64 => get_string('hash_fnv1a_64', 'cachestore_memcached'),
359 Memcached::HASH_FNV1_32 => get_string('hash_fnv1_32', 'cachestore_memcached'),
360 Memcached::HASH_FNV1A_32 => get_string('hash_fnv1a_32', 'cachestore_memcached'),
361 Memcached::HASH_HSIEH => get_string('hash_hsieh', 'cachestore_memcached'),
362 Memcached::HASH_MURMUR => get_string('hash_murmur', 'cachestore_memcached'),
368 * Given the data from the add instance form this function creates a configuration array.
370 * @param stdClass $data
373 public static function config_get_configuration_array($data) {
374 $lines = explode("\n", $data->servers);
376 foreach ($lines as $line) {
377 // Trim surrounding colons and default whitespace.
378 $line = trim(trim($line), ":");
383 $servers[] = explode(':', $line, 3);
386 'servers' => $servers,
387 'compression' => $data->compression,
388 'serialiser' => $data->serialiser,
389 'prefix' => $data->prefix,
390 'hash' => $data->hash,
391 'bufferwrites' => $data->bufferwrites,
396 * Allows the cache store to set its data against the edit form before it is shown to the user.
398 * @param moodleform $editform
399 * @param array $config
401 public static function config_set_edit_form_data(moodleform $editform, array $config) {
403 if (!empty($config['servers'])) {
405 foreach ($config['servers'] as $server) {
406 $servers[] = join(":", $server);
408 $data['servers'] = join("\n", $servers);
410 if (isset($config['compression'])) {
411 $data['compression'] = (bool)$config['compression'];
413 if (!empty($config['serialiser'])) {
414 $data['serialiser'] = $config['serialiser'];
416 if (!empty($config['prefix'])) {
417 $data['prefix'] = $config['prefix'];
419 if (!empty($config['hash'])) {
420 $data['hash'] = $config['hash'];
422 if (isset($config['bufferwrites'])) {
423 $data['bufferwrites'] = (bool)$config['bufferwrites'];
425 $editform->set_data($data);
429 * Performs any necessary clean up when the store instance is being deleted.
431 public function instance_deleted() {
432 if ($this->connection) {
433 $connection = $this->connection;
435 $connection = new Memcached(crc32($this->name));
436 $servers = $connection->getServerList();
437 if (empty($servers)) {
438 foreach ($this->options as $key => $value) {
439 $connection->setOption($key, $value);
441 $connection->addServers($this->servers);
444 @$connection->flush();
446 unset($this->connection);
450 * Generates an instance of the cache store that can be used for testing.
452 * @param cache_definition $definition
453 * @return cachestore_memcached|false
455 public static function initialise_test_instance(cache_definition $definition) {
457 if (!self::are_requirements_met()) {
461 $config = get_config('cachestore_memcached');
462 if (empty($config->testservers)) {
466 $configuration = array();
467 $configuration['servers'] = $config->testservers;
468 if (!empty($config->testcompression)) {
469 $configuration['compression'] = $config->testcompression;
471 if (!empty($config->testserialiser)) {
472 $configuration['serialiser'] = $config->testserialiser;
474 if (!empty($config->testprefix)) {
475 $configuration['prefix'] = $config->testprefix;
477 if (!empty($config->testhash)) {
478 $configuration['hash'] = $config->testhash;
480 if (!empty($config->testbufferwrites)) {
481 $configuration['bufferwrites'] = $config->testbufferwrites;
484 $store = new cachestore_memcached('Test memcached', $configuration);
485 $store->initialise($definition);
491 * Returns the name of this instance.
494 public function my_name() {