weekly release 2.5dev
[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 }
ff6f9d3a 120 $this->isready = @$this->connection->set("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
194 /**
195 * Retrieves an item from the cache store given its key.
196 *
197 * @param string $key The key to retrieve
198 * @return mixed The data that was associated with the key, or false if the key did not exist.
199 */
200 public function get($key) {
201 return $this->connection->get($key);
202 }
203
204 /**
205 * Retrieves several items from the cache store in a single transaction.
206 *
207 * 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.
208 *
209 * @param array $keys The array of keys to retrieve
210 * @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
211 * be set to false.
212 */
213 public function get_many($keys) {
214 $result = $this->connection->get($keys);
215 if (!is_array($result)) {
216 $result = array();
217 }
218 foreach ($keys as $key) {
219 if (!array_key_exists($key, $result)) {
220 $result[$key] = false;
221 }
222 }
223 return $result;
224 }
225
226 /**
227 * Sets an item in the cache given its key and data value.
228 *
229 * @param string $key The key to use.
230 * @param mixed $data The data to set.
231 * @return bool True if the operation was a success false otherwise.
232 */
233 public function set($key, $data) {
234 return $this->connection->set($key, $data, MEMCACHE_COMPRESSED, $this->definition->get_ttl());
235 }
236
237 /**
238 * Sets many items in the cache in a single transaction.
239 *
240 * @param array $keyvaluearray An array of key value pairs. Each item in the array will be an associative array with two
241 * keys, 'key' and 'value'.
242 * @return int The number of items successfully set. It is up to the developer to check this matches the number of items
243 * sent ... if they care that is.
244 */
245 public function set_many(array $keyvaluearray) {
246 $count = 0;
247 foreach ($keyvaluearray as $pair) {
248 if ($this->connection->set($pair['key'], $pair['value'], MEMCACHE_COMPRESSED, $this->definition->get_ttl())) {
249 $count++;
250 }
251 }
252 return $count;
253 }
254
255 /**
256 * Deletes an item from the cache store.
257 *
258 * @param string $key The key to delete.
259 * @return bool Returns true if the operation was a success, false otherwise.
260 */
261 public function delete($key) {
262 return $this->connection->delete($key);
263 }
264
265 /**
266 * Deletes several keys from the cache in a single action.
267 *
268 * @param array $keys The keys to delete
269 * @return int The number of items successfully deleted.
270 */
271 public function delete_many(array $keys) {
272 $count = 0;
273 foreach ($keys as $key) {
274 if ($this->delete($key)) {
275 $count++;
276 }
277 }
278 return $count;
279 }
280
281 /**
282 * Purges the cache deleting all items within it.
283 *
284 * @return boolean True on success. False otherwise.
285 */
286 public function purge() {
f4cec2ec
MS
287 if ($this->isready) {
288 $this->connection->flush();
289 }
290
e3b77f9f
SH
291 return true;
292 }
293
294 /**
295 * Given the data from the add instance form this function creates a configuration array.
296 *
297 * @param stdClass $data
298 * @return array
299 */
300 public static function config_get_configuration_array($data) {
301 $lines = explode("\n", $data->servers);
302 $servers = array();
303 foreach ($lines as $line) {
304 $line = trim($line, ':');
305 $servers[] = explode(':', $line, 3);
306 }
307 return array(
308 'servers' => $servers,
309 );
310 }
311
81ede547
SH
312 /**
313 * Allows the cache store to set its data against the edit form before it is shown to the user.
314 *
315 * @param moodleform $editform
316 * @param array $config
317 */
318 public static function config_set_edit_form_data(moodleform $editform, array $config) {
319 $data = array();
320 if (!empty($config['servers'])) {
321 $servers = array();
322 foreach ($config['servers'] as $server) {
323 $servers[] = join(":", $server);
324 }
325 $data['servers'] = join("\n", $servers);
326 }
327 $editform->set_data($data);
328 }
329
e3b77f9f 330 /**
e3b77f9f
SH
331 * Performs any necessary clean up when the store instance is being deleted.
332 */
59ca73ff 333 public function instance_deleted() {
a037c943
SH
334 if ($this->connection) {
335 $connection = $this->connection;
336 } else {
337 $connection = new Memcache;
338 foreach ($this->servers as $server) {
339 $connection->addServer($server[0], $server[1], true, $server[2]);
340 }
341 }
bb4c3916 342 @$connection->flush();
a037c943
SH
343 unset($connection);
344 unset($this->connection);
59ca73ff
MS
345 }
346
e3b77f9f
SH
347 /**
348 * Generates an instance of the cache store that can be used for testing.
349 *
350 * @param cache_definition $definition
351 * @return false
352 */
353 public static function initialise_test_instance(cache_definition $definition) {
354 if (!self::are_requirements_met()) {
355 return false;
356 }
357
6fec1820 358 $config = get_config('cachestore_memcache');
e3b77f9f
SH
359 if (empty($config->testservers)) {
360 return false;
361 }
362
363 $configuration = array();
364 $configuration['servers'] = explode("\n", $config->testservers);
365
6fec1820 366 $store = new cachestore_memcache('Test memcache', $configuration);
e3b77f9f
SH
367 $store->initialise($definition);
368
369 return $store;
370 }
34c84c72
SH
371
372 /**
373 * Returns the name of this instance.
374 * @return string
375 */
376 public function my_name() {
377 return $this->name;
378 }
bb4c3916 379}