MDL-25290 cache_memcache: Added Memcache cache store
[moodle.git] / cache / stores / memcache / lib.php
CommitLineData
e3b77f9f
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 memcache cache store.
19 *
20 * This file is part of the memcache cache store, it contains the API for interacting with an instance of the store.
21 *
22 * @package cache_memcache
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 memcache store class.
31 *
32 * (Not to be confused with memcached store)
33 *
34 * Configuration options:
35 * servers: string: host:port:weight , ...
36 *
37 * @copyright 2012 Sam Hemelryk
38 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39 */
40class cache_store_memcache implements cache_store {
41
42 /**
43 * The name of the store
44 * @var store
45 */
46 protected $name;
47
48 /**
49 * The memcache connection once established.
50 * @var Memcache
51 */
52 protected $connection;
53
54 /**
55 * An array of servers to use in the connection args.
56 * @var array
57 */
58 protected $servers = array();
59
60 /**
61 * An array of options used when establishing the connection.
62 * @var array
63 */
64 protected $options = array();
65
66 /**
67 * Set to true when things are ready to be initialised.
68 * @var bool
69 */
70 protected $isready = false;
71
72 /**
73 * The cache definition this store was initialised for.
74 * @var cache_definition
75 */
76 protected $definition;
77
78 /**
79 * Constructs the store instance.
80 *
81 * Noting that this function is not an initialisation. It is used to prepare the store for use.
82 * The store will be initialised when required and will be provided with a cache_definition at that time.
83 *
84 * @param string $name
85 * @param array $configuration
86 */
87 public function __construct($name, array $configuration = array()) {
88 $this->name = $name;
89 if (!array_key_exists('servers', $configuration) || empty($configuration['servers'])) {
90 // Nothing configured.
91 return;
92 }
93 foreach ($configuration['servers'] as $server) {
94 if (!is_array($server)) {
95 $server = explode(':', $server, 3);
96 }
97 if (!array_key_exists(1, $server)) {
98 $server[1] = 11211;
99 $server[2] = 100;
100 } else if (!array_key_exists(2, $server)) {
101 $server[2] = 100;
102 }
103 $this->servers[] = $server;
104 }
105
106 $this->isready = true;
107 }
108
109 /**
110 * Initialises the cache.
111 *
112 * Once this has been done the cache is all set to be used.
113 *
114 * @param cache_definition $definition
115 */
116 public function initialise(cache_definition $definition) {
117 if ($this->is_initialised()) {
118 throw new coding_exception('This memcache instance has already been initialised.');
119 }
120 $this->definition = $definition;
121 $this->connection = new Memcache;
122 foreach ($this->servers as $server) {
123 $this->connection->addServer($server[0], $server[1], true, $server[2]);
124 }
125 }
126
127 /**
128 * Returns true once this instance has been initialised.
129 *
130 * @return bool
131 */
132 public function is_initialised() {
133 return ($this->connection !== null);
134 }
135
136 /**
137 * Returns true if this store instance is ready to be used.
138 * @return bool
139 */
140 public function is_ready() {
141 return $this->isready;
142 }
143
144 /**
145 * Returns true if the store requirements are met.
146 *
147 * @return bool
148 */
149 public static function are_requirements_met() {
150 return class_exists('Memcache');
151 }
152
153 /**
154 * Returns true if the given mode is supported by this store.
155 *
156 * @param int $mode One of cache_store::MODE_*
157 * @return bool
158 */
159 public static function is_supported_mode($mode) {
160 return ($mode === self::MODE_APPLICATION || $mode === self::MODE_SESSION);
161 }
162
163 /**
164 * Returns the supported features as a combined int.
165 *
166 * @param array $configuration
167 * @return int
168 */
169 public static function get_supported_features(array $configuration = array()) {
170 return self::SUPPORTS_NATIVE_TTL;
171 }
172
173 /**
174 * Returns true if the store instance supports multiple identifiers.
175 *
176 * @return bool
177 */
178 public function supports_multiple_indentifiers() {
179 return false;
180 }
181
182 /**
183 * Returns true if the store instance guarantees data.
184 *
185 * @return bool
186 */
187 public function supports_data_guarantee() {
188 return false;
189 }
190
191 /**
192 * Returns true if the store instance supports native ttl.
193 *
194 * @return bool
195 */
196 public function supports_native_ttl() {
197 return true;
198 }
199
200 /**
201 * Returns the supported modes as a combined int.
202 *
203 * @param array $configuration
204 * @return int
205 */
206 public static function get_supported_modes(array $configuration = array()) {
207 return self::MODE_APPLICATION + self::MODE_SESSION;
208 }
209
210 /**
211 * Retrieves an item from the cache store given its key.
212 *
213 * @param string $key The key to retrieve
214 * @return mixed The data that was associated with the key, or false if the key did not exist.
215 */
216 public function get($key) {
217 return $this->connection->get($key);
218 }
219
220 /**
221 * Retrieves several items from the cache store in a single transaction.
222 *
223 * 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.
224 *
225 * @param array $keys The array of keys to retrieve
226 * @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
227 * be set to false.
228 */
229 public function get_many($keys) {
230 $result = $this->connection->get($keys);
231 if (!is_array($result)) {
232 $result = array();
233 }
234 foreach ($keys as $key) {
235 if (!array_key_exists($key, $result)) {
236 $result[$key] = false;
237 }
238 }
239 return $result;
240 }
241
242 /**
243 * Sets an item in the cache given its key and data value.
244 *
245 * @param string $key The key to use.
246 * @param mixed $data The data to set.
247 * @return bool True if the operation was a success false otherwise.
248 */
249 public function set($key, $data) {
250 return $this->connection->set($key, $data, MEMCACHE_COMPRESSED, $this->definition->get_ttl());
251 }
252
253 /**
254 * Sets many items in the cache in a single transaction.
255 *
256 * @param array $keyvaluearray An array of key value pairs. Each item in the array will be an associative array with two
257 * keys, 'key' and 'value'.
258 * @return int The number of items successfully set. It is up to the developer to check this matches the number of items
259 * sent ... if they care that is.
260 */
261 public function set_many(array $keyvaluearray) {
262 $count = 0;
263 foreach ($keyvaluearray as $pair) {
264 if ($this->connection->set($pair['key'], $pair['value'], MEMCACHE_COMPRESSED, $this->definition->get_ttl())) {
265 $count++;
266 }
267 }
268 return $count;
269 }
270
271 /**
272 * Deletes an item from the cache store.
273 *
274 * @param string $key The key to delete.
275 * @return bool Returns true if the operation was a success, false otherwise.
276 */
277 public function delete($key) {
278 return $this->connection->delete($key);
279 }
280
281 /**
282 * Deletes several keys from the cache in a single action.
283 *
284 * @param array $keys The keys to delete
285 * @return int The number of items successfully deleted.
286 */
287 public function delete_many(array $keys) {
288 $count = 0;
289 foreach ($keys as $key) {
290 if ($this->delete($key)) {
291 $count++;
292 }
293 }
294 return $count;
295 }
296
297 /**
298 * Purges the cache deleting all items within it.
299 *
300 * @return boolean True on success. False otherwise.
301 */
302 public function purge() {
303 $this->connection->flush();
304 return true;
305 }
306
307 /**
308 * Given the data from the add instance form this function creates a configuration array.
309 *
310 * @param stdClass $data
311 * @return array
312 */
313 public static function config_get_configuration_array($data) {
314 $lines = explode("\n", $data->servers);
315 $servers = array();
316 foreach ($lines as $line) {
317 $line = trim($line, ':');
318 $servers[] = explode(':', $line, 3);
319 }
320 return array(
321 'servers' => $servers,
322 );
323 }
324
325 /**
326 * Returns true if the user can add an instance of the store plugin.
327 *
328 * @return bool
329 */
330 public static function can_add_instance() {
331 return true;
332 }
333
334 /**
335 * Performs any necessary clean up when the store instance is being deleted.
336 */
337 public function cleanup() {
338 $this->purge();
339 }
340
341 /**
342 * Generates an instance of the cache store that can be used for testing.
343 *
344 * @param cache_definition $definition
345 * @return false
346 */
347 public static function initialise_test_instance(cache_definition $definition) {
348 if (!self::are_requirements_met()) {
349 return false;
350 }
351
352 $config = get_config('cache_memcache');
353 if (empty($config->testservers)) {
354 return false;
355 }
356
357 $configuration = array();
358 $configuration['servers'] = explode("\n", $config->testservers);
359
360 $store = new cache_store_memcache('Test memcache', $configuration);
361 $store->initialise($definition);
362
363 return $store;
364 }
365}