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_base {
49 * The name of the store
55 * The memcached connection
58 protected $connection;
61 * An array of servers to use during connection
64 protected $servers = array();
67 * The options used when establishing the connection
70 protected $options = array();
73 * True when this instance is ready to be initialised.
76 protected $isready = false;
79 * The cache definition this store was initialised with.
80 * @var cache_definition
82 protected $definition;
85 * Constructs the store instance.
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.
91 * @param array $configuration
93 public function __construct($name, array $configuration = array()) {
95 if (!array_key_exists('servers', $configuration) || empty($configuration['servers'])) {
96 // Nothing configured.
99 if (!is_array($configuration['servers'])) {
100 $configuration['servers'] = array($configuration['servers']);
103 $compression = array_key_exists('compression', $configuration) ? (bool)$configuration['compression'] : true;
104 if (array_key_exists('serialiser', $configuration)) {
105 $serialiser = (int)$configuration['serialiser'];
107 $serialiser = Memcached::SERIALIZER_PHP;
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);
117 if (!array_key_exists(1, $server)) {
120 } else if (!array_key_exists(2, $server)) {
123 $this->servers[] = $server;
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;
135 * Initialises the cache.
137 * Once this has been done the cache is all set to be used.
139 * @param cache_definition $definition
141 public function initialise(cache_definition $definition) {
142 if ($this->is_initialised()) {
143 throw new coding_exception('This memcached instance has already been initialised.');
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);
152 $this->connection->addServers($this->servers);
157 * Returns true once this instance has been initialised.
161 public function is_initialised() {
162 return ($this->connection !== null);
166 * Returns true if this store instance is ready to be used.
169 public function is_ready() {
170 return $this->isready;
174 * Returns true if the store requirements are met.
178 public static function are_requirements_met() {
179 return class_exists('Memcached');
183 * Returns true if the given mode is supported by this store.
185 * @param int $mode One of cache_store::MODE_*
188 public static function is_supported_mode($mode) {
189 return ($mode === self::MODE_APPLICATION || $mode === self::MODE_SESSION);
193 * Returns the supported features as a combined int.
195 * @param array $configuration
198 public static function get_supported_features(array $configuration = array()) {
199 return self::SUPPORTS_NATIVE_TTL;
203 * Returns the supported modes as a combined int.
205 * @param array $configuration
208 public static function get_supported_modes(array $configuration = array()) {
209 return self::MODE_APPLICATION + self::MODE_SESSION;
213 * Retrieves an item from the cache store given its key.
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.
218 public function get($key) {
219 return $this->connection->get($key);
223 * Retrieves several items from the cache store in a single transaction.
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.
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
231 public function get_many($keys) {
232 $result = $this->connection->getMulti($keys);
233 if (!is_array($result)) {
236 foreach ($keys as $key) {
237 if (!array_key_exists($key, $result)) {
238 $result[$key] = false;
245 * Sets an item in the cache given its key and data value.
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.
251 public function set($key, $data) {
252 return $this->connection->set($key, $data, $this->definition->get_ttl());
256 * Sets many items in the cache in a single transaction.
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.
263 public function set_many(array $keyvaluearray) {
265 foreach ($keyvaluearray as $pair) {
266 $pairs[$pair['key']] = $pair['value'];
268 if ($this->connection->setMulti($pairs, $this->definition->get_ttl())) {
269 return count($keyvaluearray);
275 * Deletes an item from the cache store.
277 * @param string $key The key to delete.
278 * @return bool Returns true if the operation was a success, false otherwise.
280 public function delete($key) {
281 return $this->connection->delete($key);
285 * Deletes several keys from the cache in a single action.
287 * @param array $keys The keys to delete
288 * @return int The number of items successfully deleted.
290 public function delete_many(array $keys) {
292 foreach ($keys as $key) {
293 if ($this->connection->delete($key)) {
301 * Purges the cache deleting all items within it.
303 * @return boolean True on success. False otherwise.
305 public function purge() {
306 $this->connection->flush();
311 * Gets an array of options to use as the serialiser.
314 public static function config_get_serialiser_options() {
316 Memcached::SERIALIZER_PHP => get_string('serialiser_php', 'cachestore_memcached')
318 if (Memcached::HAVE_JSON) {
319 $options[Memcached::SERIALIZER_JSON] = get_string('serialiser_json', 'cachestore_memcached');
321 if (Memcached::HAVE_IGBINARY) {
322 $options[Memcached::SERIALIZER_IGBINARY] = get_string('serialiser_php', 'cachestore_memcached');
328 * Gets an array of hash options available during configuration.
331 public static function config_get_hash_options() {
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'),
347 * Given the data from the add instance form this function creates a configuration array.
349 * @param stdClass $data
352 public static function config_get_configuration_array($data) {
353 $lines = explode("\n", $data->servers);
355 foreach ($lines as $line) {
356 $line = trim($line, ':');
357 $servers[] = explode(':', $line, 3);
360 'servers' => $servers,
361 'compression' => $data->compression,
362 'serialiser' => $data->serialiser,
363 'prefix' => $data->prefix,
364 'hash' => $data->hash,
365 'bufferwrites' => $data->bufferwrites,
370 * Allows the cache store to set its data against the edit form before it is shown to the user.
372 * @param moodleform $editform
373 * @param array $config
375 public static function config_set_edit_form_data(moodleform $editform, array $config) {
377 if (!empty($config['servers'])) {
379 foreach ($config['servers'] as $server) {
380 $servers[] = join(":", $server);
382 $data['servers'] = join("\n", $servers);
384 if (isset($config['compression'])) {
385 $data['compression'] = (bool)$config['compression'];
387 if (!empty($config['serialiser'])) {
388 $data['serialiser'] = $config['serialiser'];
390 if (!empty($config['prefix'])) {
391 $data['prefix'] = $config['prefix'];
393 if (!empty($config['hash'])) {
394 $data['hash'] = $config['hash'];
396 if (isset($config['bufferwrites'])) {
397 $data['bufferwrites'] = (bool)$config['bufferwrites'];
399 $editform->set_data($data);
403 * Performs any necessary clean up when the store instance is being deleted.
405 public function cleanup() {
410 * Generates an instance of the cache store that can be used for testing.
412 * @param cache_definition $definition
415 public static function initialise_test_instance(cache_definition $definition) {
417 if (!self::are_requirements_met()) {
421 $config = get_config('cachestore_memcached');
422 if (empty($config->testservers)) {
426 $configuration = array();
427 $configuration['servers'] = $config->testservers;
428 if (!empty($config->testcompression)) {
429 $configuration['compression'] = $config->testcompression;
431 if (!empty($config->testserialiser)) {
432 $configuration['serialiser'] = $config->testserialiser;
434 if (!empty($config->testprefix)) {
435 $configuration['prefix'] = $config->testprefix;
437 if (!empty($config->testhash)) {
438 $configuration['hash'] = $config->testhash;
440 if (!empty($config->testbufferwrites)) {
441 $configuration['bufferwrites'] = $config->testbufferwrites;
444 $store = new cachestore_memcached('Test memcached', $configuration);
445 $store->initialise($definition);
451 * Returns the name of this instance.
454 public function my_name() {