on demand release 2.5beta+
[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 *
6fec1820 22 * @package cachestore_memcache
e3b77f9f
SH
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 */
2b274ad0 40class cachestore_memcache extends cache_store implements cache_is_configurable {
e3b77f9f
SH
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
65b3edc4
SH
72 /**
73 * Set to true once this store instance has been initialised.
74 * @var bool
75 */
76 protected $isinitialised = false;
77
e3b77f9f
SH
78 /**
79 * The cache definition this store was initialised for.
80 * @var cache_definition
81 */
82 protected $definition;
83
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 }
42f5d164
SH
99 if (!is_array($configuration['servers'])) {
100 $configuration['servers'] = array($configuration['servers']);
101 }
e3b77f9f
SH
102 foreach ($configuration['servers'] as $server) {
103 if (!is_array($server)) {
104 $server = explode(':', $server, 3);
105 }
106 if (!array_key_exists(1, $server)) {
107 $server[1] = 11211;
108 $server[2] = 100;
109 } else if (!array_key_exists(2, $server)) {
110 $server[2] = 100;
111 }
112 $this->servers[] = $server;
113 }
114
f4cec2ec
MS
115 $this->connection = new Memcache;
116 foreach ($this->servers as $server) {
117 $this->connection->addServer($server[0], $server[1], true, $server[2]);
118 // Test the connection to this server.
f4cec2ec 119 }
4af3d7e7 120 $this->isready = @$this->connection->set($this->parse_key('ping'), 'ping', MEMCACHE_COMPRESSED, 1);
e3b77f9f
SH
121 }
122
123 /**
124 * Initialises the cache.
125 *
126 * Once this has been done the cache is all set to be used.
127 *
128 * @param cache_definition $definition
129 */
130 public function initialise(cache_definition $definition) {
131 if ($this->is_initialised()) {
132 throw new coding_exception('This memcache instance has already been initialised.');
133 }
134 $this->definition = $definition;
65b3edc4 135 $this->isinitialised = true;
e3b77f9f
SH
136 }
137
138 /**
139 * Returns true once this instance has been initialised.
140 *
141 * @return bool
142 */
143 public function is_initialised() {
65b3edc4 144 return ($this->isinitialised);
e3b77f9f
SH
145 }
146
147 /**
148 * Returns true if this store instance is ready to be used.
149 * @return bool
150 */
151 public function is_ready() {
152 return $this->isready;
153 }
154
155 /**
156 * Returns true if the store requirements are met.
157 *
158 * @return bool
159 */
160 public static function are_requirements_met() {
161 return class_exists('Memcache');
162 }
163
164 /**
165 * Returns true if the given mode is supported by this store.
166 *
167 * @param int $mode One of cache_store::MODE_*
168 * @return bool
169 */
170 public static function is_supported_mode($mode) {
171 return ($mode === self::MODE_APPLICATION || $mode === self::MODE_SESSION);
172 }
173
174 /**
175 * Returns the supported features as a combined int.
176 *
177 * @param array $configuration
178 * @return int
179 */
180 public static function get_supported_features(array $configuration = array()) {
181 return self::SUPPORTS_NATIVE_TTL;
182 }
183
e3b77f9f
SH
184 /**
185 * Returns the supported modes as a combined int.
186 *
187 * @param array $configuration
188 * @return int
189 */
190 public static function get_supported_modes(array $configuration = array()) {
191 return self::MODE_APPLICATION + self::MODE_SESSION;
192 }
193
4af3d7e7
SH
194 /**
195 * Parses the given key to make it work for this memcache backend.
196 *
197 * @param string $key The raw key.
198 * @return string The resulting key.
199 */
200 protected function parse_key($key) {
201 if (strlen($key) > 245) {
202 $key = '_sha1_'.sha1($key);
203 }
204 $key = 'mdl_'.$key;
205 return $key;
206 }
207
e3b77f9f
SH
208 /**
209 * Retrieves an item from the cache store given its key.
210 *
211 * @param string $key The key to retrieve
212 * @return mixed The data that was associated with the key, or false if the key did not exist.
213 */
214 public function get($key) {
4af3d7e7 215 return $this->connection->get($this->parse_key($key));
e3b77f9f
SH
216 }
217
218 /**
219 * Retrieves several items from the cache store in a single transaction.
220 *
221 * 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.
222 *
223 * @param array $keys The array of keys to retrieve
224 * @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
225 * be set to false.
226 */
227 public function get_many($keys) {
4af3d7e7
SH
228 $mkeys = array();
229 foreach ($keys as $key) {
230 $mkeys[$key] = $this->parse_key($key);
231 }
232 $result = $this->connection->get($mkeys);
e3b77f9f
SH
233 if (!is_array($result)) {
234 $result = array();
235 }
4af3d7e7
SH
236 $return = array();
237 foreach ($mkeys as $key => $mkey) {
238 if (!array_key_exists($mkey, $result)) {
239 $return[$key] = false;
240 } else {
241 $return[$key] = $result[$mkey];
e3b77f9f
SH
242 }
243 }
4af3d7e7 244 return $return;
e3b77f9f
SH
245 }
246
247 /**
248 * Sets an item in the cache given its key and data value.
249 *
250 * @param string $key The key to use.
251 * @param mixed $data The data to set.
252 * @return bool True if the operation was a success false otherwise.
253 */
254 public function set($key, $data) {
4af3d7e7 255 return $this->connection->set($this->parse_key($key), $data, MEMCACHE_COMPRESSED, $this->definition->get_ttl());
e3b77f9f
SH
256 }
257
258 /**
259 * Sets many items in the cache in a single transaction.
260 *
261 * @param array $keyvaluearray An array of key value pairs. Each item in the array will be an associative array with two
262 * keys, 'key' and 'value'.
263 * @return int The number of items successfully set. It is up to the developer to check this matches the number of items
264 * sent ... if they care that is.
265 */
266 public function set_many(array $keyvaluearray) {
267 $count = 0;
268 foreach ($keyvaluearray as $pair) {
4af3d7e7 269 if ($this->connection->set($this->parse_key($pair['key']), $pair['value'], MEMCACHE_COMPRESSED, $this->definition->get_ttl())) {
e3b77f9f
SH
270 $count++;
271 }
272 }
273 return $count;
274 }
275
276 /**
277 * Deletes an item from the cache store.
278 *
279 * @param string $key The key to delete.
280 * @return bool Returns true if the operation was a success, false otherwise.
281 */
282 public function delete($key) {
4af3d7e7 283 return $this->connection->delete($this->parse_key($key));
e3b77f9f
SH
284 }
285
286 /**
287 * Deletes several keys from the cache in a single action.
288 *
289 * @param array $keys The keys to delete
290 * @return int The number of items successfully deleted.
291 */
292 public function delete_many(array $keys) {
293 $count = 0;
294 foreach ($keys as $key) {
295 if ($this->delete($key)) {
296 $count++;
297 }
298 }
299 return $count;
300 }
301
302 /**
303 * Purges the cache deleting all items within it.
304 *
305 * @return boolean True on success. False otherwise.
306 */
307 public function purge() {
f4cec2ec
MS
308 if ($this->isready) {
309 $this->connection->flush();
310 }
311
e3b77f9f
SH
312 return true;
313 }
314
315 /**
316 * Given the data from the add instance form this function creates a configuration array.
317 *
318 * @param stdClass $data
319 * @return array
320 */
321 public static function config_get_configuration_array($data) {
322 $lines = explode("\n", $data->servers);
323 $servers = array();
324 foreach ($lines as $line) {
325 $line = trim($line, ':');
326 $servers[] = explode(':', $line, 3);
327 }
328 return array(
329 'servers' => $servers,
330 );
331 }
332
81ede547
SH
333 /**
334 * Allows the cache store to set its data against the edit form before it is shown to the user.
335 *
336 * @param moodleform $editform
337 * @param array $config
338 */
339 public static function config_set_edit_form_data(moodleform $editform, array $config) {
340 $data = array();
341 if (!empty($config['servers'])) {
342 $servers = array();
343 foreach ($config['servers'] as $server) {
344 $servers[] = join(":", $server);
345 }
346 $data['servers'] = join("\n", $servers);
347 }
348 $editform->set_data($data);
349 }
350
e3b77f9f 351 /**
e3b77f9f
SH
352 * Performs any necessary clean up when the store instance is being deleted.
353 */
59ca73ff 354 public function instance_deleted() {
a037c943
SH
355 if ($this->connection) {
356 $connection = $this->connection;
357 } else {
358 $connection = new Memcache;
359 foreach ($this->servers as $server) {
360 $connection->addServer($server[0], $server[1], true, $server[2]);
361 }
362 }
bb4c3916 363 @$connection->flush();
a037c943
SH
364 unset($connection);
365 unset($this->connection);
59ca73ff
MS
366 }
367
e3b77f9f
SH
368 /**
369 * Generates an instance of the cache store that can be used for testing.
370 *
371 * @param cache_definition $definition
372 * @return false
373 */
374 public static function initialise_test_instance(cache_definition $definition) {
375 if (!self::are_requirements_met()) {
376 return false;
377 }
378
6fec1820 379 $config = get_config('cachestore_memcache');
e3b77f9f
SH
380 if (empty($config->testservers)) {
381 return false;
382 }
383
384 $configuration = array();
385 $configuration['servers'] = explode("\n", $config->testservers);
386
6fec1820 387 $store = new cachestore_memcache('Test memcache', $configuration);
e3b77f9f
SH
388 $store->initialise($definition);
389
390 return $store;
391 }
34c84c72
SH
392
393 /**
394 * Returns the name of this instance.
395 * @return string
396 */
397 public function my_name() {
398 return $this->name;
399 }
bb4c3916 400}