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 memcache cache store.
20 * This file is part of the memcache cache store, it contains the API for interacting with an instance of the store.
22 * @package cachestore_memcache
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 memcache store class.
32 * (Not to be confused with memcached store)
34 * Configuration options:
35 * servers: string: host:port:weight , ...
37 * @copyright 2012 Sam Hemelryk
38 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
40 class cachestore_memcache extends cache_store implements cache_is_configurable {
43 * The name of the store
49 * The memcache connection once established.
52 protected $connection;
55 * Key prefix for this memcache.
61 * An array of servers to use in the connection args.
64 protected $servers = array();
67 * An array of options used when establishing the connection.
70 protected $options = array();
73 * Set to true when things are ready to be initialised.
76 protected $isready = false;
79 * Set to true once this store instance has been initialised.
82 protected $isinitialised = false;
85 * The cache definition this store was initialised for.
86 * @var cache_definition
88 protected $definition;
91 * Default prefix for key names.
94 const DEFAULT_PREFIX = 'mdl_';
97 * Constructs the store instance.
99 * Noting that this function is not an initialisation. It is used to prepare the store for use.
100 * The store will be initialised when required and will be provided with a cache_definition at that time.
102 * @param string $name
103 * @param array $configuration
105 public function __construct($name, array $configuration = array()) {
107 if (!array_key_exists('servers', $configuration) || empty($configuration['servers'])) {
108 // Nothing configured.
111 if (!is_array($configuration['servers'])) {
112 $configuration['servers'] = array($configuration['servers']);
114 foreach ($configuration['servers'] as $server) {
115 if (!is_array($server)) {
116 $server = explode(':', $server, 3);
118 if (!array_key_exists(1, $server)) {
121 } else if (!array_key_exists(2, $server)) {
124 $this->servers[] = $server;
126 if (empty($configuration['prefix'])) {
127 $this->prefix = self::DEFAULT_PREFIX;
129 $this->prefix = $configuration['prefix'];
132 $this->connection = new Memcache;
133 foreach ($this->servers as $server) {
134 $this->connection->addServer($server[0], (int) $server[1], true, (int) $server[2]);
136 // Test the connection to the pool of servers.
137 $this->isready = @$this->connection->set($this->parse_key('ping'), 'ping', MEMCACHE_COMPRESSED, 1);
141 * Initialises the cache.
143 * Once this has been done the cache is all set to be used.
145 * @param cache_definition $definition
147 public function initialise(cache_definition $definition) {
148 if ($this->is_initialised()) {
149 throw new coding_exception('This memcache instance has already been initialised.');
151 $this->definition = $definition;
152 $this->isinitialised = true;
156 * Returns true once this instance has been initialised.
160 public function is_initialised() {
161 return ($this->isinitialised);
165 * Returns true if this store instance is ready to be used.
168 public function is_ready() {
169 return $this->isready;
173 * Returns true if the store requirements are met.
177 public static function are_requirements_met() {
178 return class_exists('Memcache');
182 * Returns true if the given mode is supported by this store.
184 * @param int $mode One of cache_store::MODE_*
187 public static function is_supported_mode($mode) {
188 return ($mode === self::MODE_APPLICATION || $mode === self::MODE_SESSION);
192 * Returns the supported features as a combined int.
194 * @param array $configuration
197 public static function get_supported_features(array $configuration = array()) {
198 return self::SUPPORTS_NATIVE_TTL;
202 * Returns false as this store does not support multiple identifiers.
203 * (This optional function is a performance optimisation; it must be
204 * consistent with the value from get_supported_features.)
208 public function supports_multiple_identifiers() {
213 * Returns the supported modes as a combined int.
215 * @param array $configuration
218 public static function get_supported_modes(array $configuration = array()) {
219 return self::MODE_APPLICATION;
223 * Parses the given key to make it work for this memcache backend.
225 * @param string $key The raw key.
226 * @return string The resulting key.
228 protected function parse_key($key) {
229 if (strlen($key) > 245) {
230 $key = '_sha1_'.sha1($key);
232 $key = $this->prefix . $key;
237 * Retrieves an item from the cache store given its key.
239 * @param string $key The key to retrieve
240 * @return mixed The data that was associated with the key, or false if the key did not exist.
242 public function get($key) {
243 return $this->connection->get($this->parse_key($key));
247 * Retrieves several items from the cache store in a single transaction.
249 * 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.
251 * @param array $keys The array of keys to retrieve
252 * @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
255 public function get_many($keys) {
257 foreach ($keys as $key) {
258 $mkeys[$key] = $this->parse_key($key);
260 $result = $this->connection->get($mkeys);
261 if (!is_array($result)) {
265 foreach ($mkeys as $key => $mkey) {
266 if (!array_key_exists($mkey, $result)) {
267 $return[$key] = false;
269 $return[$key] = $result[$mkey];
276 * Sets an item in the cache given its key and data value.
278 * @param string $key The key to use.
279 * @param mixed $data The data to set.
280 * @return bool True if the operation was a success false otherwise.
282 public function set($key, $data) {
283 return $this->connection->set($this->parse_key($key), $data, MEMCACHE_COMPRESSED, $this->definition->get_ttl());
287 * Sets many items in the cache in a single transaction.
289 * @param array $keyvaluearray An array of key value pairs. Each item in the array will be an associative array with two
290 * keys, 'key' and 'value'.
291 * @return int The number of items successfully set. It is up to the developer to check this matches the number of items
292 * sent ... if they care that is.
294 public function set_many(array $keyvaluearray) {
296 foreach ($keyvaluearray as $pair) {
297 if ($this->connection->set($this->parse_key($pair['key']), $pair['value'], MEMCACHE_COMPRESSED, $this->definition->get_ttl())) {
305 * Deletes an item from the cache store.
307 * @param string $key The key to delete.
308 * @return bool Returns true if the operation was a success, false otherwise.
310 public function delete($key) {
311 return $this->connection->delete($this->parse_key($key));
315 * Deletes several keys from the cache in a single action.
317 * @param array $keys The keys to delete
318 * @return int The number of items successfully deleted.
320 public function delete_many(array $keys) {
322 foreach ($keys as $key) {
323 if ($this->delete($key)) {
331 * Purges the cache deleting all items within it.
333 * @return boolean True on success. False otherwise.
335 public function purge() {
336 if ($this->isready) {
337 $this->connection->flush();
344 * Given the data from the add instance form this function creates a configuration array.
346 * @param stdClass $data
349 public static function config_get_configuration_array($data) {
350 $lines = explode("\n", $data->servers);
352 foreach ($lines as $line) {
353 // Trim surrounding colons and default whitespace.
354 $line = trim(trim($line), ":");
359 $servers[] = explode(':', $line, 3);
362 'servers' => $servers,
363 'prefix' => $data->prefix,
368 * Allows the cache store to set its data against the edit form before it is shown to the user.
370 * @param moodleform $editform
371 * @param array $config
373 public static function config_set_edit_form_data(moodleform $editform, array $config) {
375 if (!empty($config['servers'])) {
377 foreach ($config['servers'] as $server) {
378 $servers[] = join(":", $server);
380 $data['servers'] = join("\n", $servers);
382 if (!empty($config['prefix'])) {
383 $data['prefix'] = $config['prefix'];
385 $data['prefix'] = self::DEFAULT_PREFIX;
388 $editform->set_data($data);
392 * Performs any necessary clean up when the store instance is being deleted.
394 public function instance_deleted() {
395 if ($this->connection) {
396 $connection = $this->connection;
398 $connection = new Memcache;
399 foreach ($this->servers as $server) {
400 $connection->addServer($server[0], $server[1], true, $server[2]);
403 @$connection->flush();
405 unset($this->connection);
409 * Generates an instance of the cache store that can be used for testing.
411 * @param cache_definition $definition
412 * @return cachestore_memcache|false
414 public static function initialise_test_instance(cache_definition $definition) {
415 if (!self::are_requirements_met()) {
419 $config = get_config('cachestore_memcache');
420 if (empty($config->testservers)) {
424 $configuration = array();
425 $configuration['servers'] = explode("\n", $config->testservers);
427 $store = new cachestore_memcache('Test memcache', $configuration);
428 $store->initialise($definition);
434 * Creates a test instance for unit tests if possible.
435 * @param cache_definition $definition
436 * @return bool|cachestore_memcache
438 public static function initialise_unit_test_instance(cache_definition $definition) {
439 if (!self::are_requirements_met()) {
442 if (!defined('TEST_CACHESTORE_MEMCACHE_TESTSERVERS')) {
445 $configuration = array();
446 $configuration['servers'] = explode("\n", TEST_CACHESTORE_MEMCACHE_TESTSERVERS);
448 $store = new cachestore_memcache('Test memcache', $configuration);
449 $store->initialise($definition);
455 * Returns the name of this instance.
458 public function my_name() {