Merge branch 'MDL-34904-master' of git://github.com/ankitagarwal/moodle
[moodle.git] / cache / stores / mongodb / lib.php
CommitLineData
2e638e3d
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 MongoDB store plugin.
19 *
20 * This file is part of the MongoDB store plugin, it contains the API for interacting with an instance of the store.
21 *
6fec1820 22 * @package cachestore_mongodb
2e638e3d
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 MongoDB Cache store.
31 *
32 * This cache store uses the MongoDB Native Driver.
33 * For installation instructions have a look at the following two links:
34 * - {@link http://www.php.net/manual/en/mongo.installation.php}
35 * - {@link http://www.mongodb.org/display/DOCS/PHP+Language+Center}
36 *
37 * @copyright 2012 Sam Hemelryk
38 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39 */
2b274ad0 40class cachestore_mongodb extends cache_store implements cache_is_configurable {
2e638e3d
SH
41
42 /**
43 * The name of the store
44 * @var string
45 */
46 protected $name;
47
48 /**
49 * The server connection string. Comma separated values.
50 * @var string
51 */
52 protected $server = 'mongodb://127.0.0.1:27017';
53
54 /**
55 * The database connection options
56 * @var array
57 */
58 protected $options = array();
59
60 /**
61 * The name of the database to use.
62 * @var string
63 */
64 protected $databasename = 'mcache';
65
66 /**
67 * The Connection object
68 * @var Mongo
69 */
a037c943 70 protected $connection = false;
2e638e3d
SH
71
72 /**
73 * The Database Object
74 * @var MongoDB
75 */
76 protected $database;
77
78 /**
79 * The Collection object
80 * @var MongoCollection
81 */
82 protected $collection;
83
84 /**
85 * Determines if and what safe setting is to be used.
86 * @var bool|int
87 */
88 protected $usesafe = false;
89
90 /**
91 * If set to true then multiple identifiers will be requested and used.
92 * @var bool
93 */
94 protected $extendedmode = false;
95
96 /**
97 * The definition has which is used in the construction of the collection.
98 * @var string
99 */
100 protected $definitionhash = null;
101
102 /**
5dfa3031
SH
103 * Set to true once this store is ready to be initialised and used.
104 * @var bool
105 */
106 protected $isready = false;
107
108 /**
109 * Constructs a new instance of the Mongo store.
110 *
111 * Noting that this function is not an initialisation. It is used to prepare the store for use.
112 * The store will be initialised when required and will be provided with a cache_definition at that time.
113 *
2e638e3d
SH
114 * @param string $name
115 * @param array $configuration
116 */
117 public function __construct($name, array $configuration = array()) {
118 $this->name = $name;
119
120 if (array_key_exists('server', $configuration)) {
121 $this->server = $configuration['server'];
122 }
123
124 if (array_key_exists('replicaset', $configuration)) {
125 $this->options['replicaSet'] = (string)$configuration['replicaset'];
126 }
127 if (array_key_exists('username', $configuration) && !empty($configuration['username'])) {
128 $this->options['username'] = (string)$configuration['username'];
129 }
130 if (array_key_exists('password', $configuration) && !empty($configuration['password'])) {
131 $this->options['password'] = (string)$configuration['password'];
132 }
133 if (array_key_exists('database', $configuration)) {
134 $this->databasename = (string)$configuration['database'];
135 }
136 if (array_key_exists('usesafe', $configuration)) {
137 $this->usesafe = $configuration['usesafe'];
138 }
139 if (array_key_exists('extendedmode', $configuration)) {
140 $this->extendedmode = $configuration['extendedmode'];
141 }
142
f4cec2ec
MS
143 try {
144 $this->connection = new Mongo($this->server, $this->options);
f4cec2ec 145 $this->isready = true;
65b3edc4
SH
146 } catch (MongoConnectionException $e) {
147 // We only want to catch MongoConnectionExceptions here.
f4cec2ec 148 }
2e638e3d
SH
149 }
150
151 /**
152 * Returns true if the requirements of this store have been met.
153 * @return bool
154 */
155 public static function are_requirements_met() {
156 return class_exists('Mongo');
157 }
158
2e638e3d
SH
159 /**
160 * Returns the supported features.
161 * @param array $configuration
162 * @return int
163 */
164 public static function get_supported_features(array $configuration = array()) {
165 $supports = self::SUPPORTS_DATA_GUARANTEE;
166 if (array_key_exists('extendedmode', $configuration) && $configuration['extendedmode']) {
167 $supports += self::SUPPORTS_MULTIPLE_IDENTIFIERS;
168 }
169 return $supports;
170 }
171
172 /**
173 * Returns an int describing the supported modes.
174 * @param array $configuration
175 * @return int
176 */
177 public static function get_supported_modes(array $configuration = array()) {
90a3a620 178 return self::MODE_APPLICATION;
2e638e3d
SH
179 }
180
181 /**
182 * Initialises the store instance for use.
183 *
5dfa3031 184 * Once this has been done the cache is all set to be used.
2e638e3d
SH
185 *
186 * @param cache_definition $definition
187 * @throws coding_exception
188 */
189 public function initialise(cache_definition $definition) {
190 if ($this->is_initialised()) {
191 throw new coding_exception('This mongodb instance has already been initialised.');
192 }
65b3edc4 193 $this->database = $this->connection->selectDB($this->databasename);
2e638e3d 194 $this->definitionhash = $definition->generate_definition_hash();
2e638e3d
SH
195 $this->collection = $this->database->selectCollection($this->definitionhash);
196 $this->collection->ensureIndex(array('key' => 1), array(
197 'safe' => $this->usesafe,
198 'name' => 'idx_key'
199 ));
200 }
201
202 /**
203 * Returns true if this store instance has been initialised.
204 * @return bool
205 */
206 public function is_initialised() {
207 return ($this->database instanceof MongoDB);
208 }
209
210 /**
211 * Returns true if this store instance is ready to use.
212 * @return bool
213 */
214 public function is_ready() {
215 return $this->isready;
216 }
217
218 /**
219 * Returns true if the given mode is supported by this store.
220 * @param int $mode
221 * @return bool
222 */
223 public static function is_supported_mode($mode) {
224 return ($mode == self::MODE_APPLICATION || $mode == self::MODE_SESSION);
225 }
226
2e638e3d
SH
227 /**
228 * Returns true if this store is making use of multiple identifiers.
229 * @return bool
230 */
758dbdf8 231 public function supports_multiple_identifiers() {
2e638e3d
SH
232 return $this->extendedmode;
233 }
234
2e638e3d
SH
235 /**
236 * Retrieves an item from the cache store given its key.
237 *
238 * @param string $key The key to retrieve
239 * @return mixed The data that was associated with the key, or false if the key did not exist.
240 */
241 public function get($key) {
242 if (!is_array($key)) {
243 $key = array('key' => $key);
244 }
170f821b 245
2e638e3d
SH
246 $result = $this->collection->findOne($key);
247 if ($result === null || !array_key_exists('data', $result)) {
248 return false;
249 }
250 $data = @unserialize($result['data']);
251 return $data;
252 }
253
254 /**
255 * Retrieves several items from the cache store in a single transaction.
256 *
257 * 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.
258 *
259 * @param array $keys The array of keys to retrieve
260 * @return array An array of items from the cache.
261 */
262 public function get_many($keys) {
263 if ($this->extendedmode) {
264 $query = $this->get_many_extendedmode_query($keys);
265 $keyarray = array();
266 foreach ($keys as $key) {
267 $keyarray[] = $key['key'];
268 }
269 $keys = $keyarray;
270 $query = array('key' => array('$in' => $keys));
271 } else {
272 $query = array('key' => array('$in' => $keys));
273 }
274 $cursor = $this->collection->find($query);
275 $results = array();
276 foreach ($cursor as $result) {
32c981e6 277 $id = (string)$result['key'];
2e638e3d
SH
278 $results[$id] = unserialize($result['data']);
279 }
280 foreach ($keys as $key) {
281 if (!array_key_exists($key, $results)) {
282 $results[$key] = false;
283 }
284 }
285 return $results;
286 }
287
288 /**
289 * Sets an item in the cache given its key and data value.
290 *
291 * @param string $key The key to use.
292 * @param mixed $data The data to set.
293 * @return bool True if the operation was a success false otherwise.
294 */
295 public function set($key, $data) {
296 if (!is_array($key)) {
297 $record = array(
298 'key' => $key
299 );
300 } else {
301 $record = $key;
302 }
303 $record['data'] = serialize($data);
304 $options = array(
305 'upsert' => true,
32c981e6
SH
306 'safe' => $this->usesafe,
307 'w' => $this->usesafe ? 1 : 0
2e638e3d
SH
308 );
309 $this->delete($key);
310 $result = $this->collection->insert($record, $options);
32c981e6
SH
311 if ($result === true) {
312 // Safe mode is off.
313 return true;
314 } else if (is_array($result)) {
315 if (empty($result['ok']) || isset($result['err'])) {
316 return false;
317 }
318 return true;
319 }
320 // Who knows?
321 return false;
2e638e3d
SH
322 }
323
324 /**
325 * Sets many items in the cache in a single transaction.
326 *
327 * @param array $keyvaluearray An array of key value pairs. Each item in the array will be an associative array with two
328 * keys, 'key' and 'value'.
329 * @return int The number of items successfully set. It is up to the developer to check this matches the number of items
330 * sent ... if they care that is.
331 */
332 public function set_many(array $keyvaluearray) {
333 $count = 0;
334 foreach ($keyvaluearray as $pair) {
335 $result = $this->set($pair['key'], $pair['value']);
32c981e6 336 if ($result === true) {
2e638e3d
SH
337 $count++;
338 }
339 }
32c981e6 340 return $count;
2e638e3d
SH
341 }
342
343 /**
344 * Deletes an item from the cache store.
345 *
346 * @param string $key The key to delete.
347 * @return bool Returns true if the operation was a success, false otherwise.
348 */
349 public function delete($key) {
350 if (!is_array($key)) {
351 $criteria = array(
352 'key' => $key
353 );
354 } else {
355 $criteria = $key;
356 }
357 $options = array(
358 'justOne' => false,
32c981e6
SH
359 'safe' => $this->usesafe,
360 'w' => $this->usesafe ? 1 : 0
2e638e3d
SH
361 );
362 $result = $this->collection->remove($criteria, $options);
32c981e6
SH
363
364 if ($result === true) {
365 // Safe mode.
366 return true;
367 } else if (is_array($result)) {
368 if (empty($result['ok']) || isset($result['err'])) {
369 return false;
370 } else if (empty($result['n'])) {
371 // Nothing was removed.
372 return false;
373 }
374 return true;
2e638e3d 375 }
32c981e6
SH
376 // Who knows?
377 return false;
2e638e3d
SH
378 }
379
380 /**
381 * Deletes several keys from the cache in a single action.
382 *
383 * @param array $keys The keys to delete
384 * @return int The number of items successfully deleted.
385 */
386 public function delete_many(array $keys) {
387 $count = 0;
388 foreach ($keys as $key) {
389 if ($this->delete($key)) {
390 $count++;
391 }
392 }
393 return $count;
394 }
395
396 /**
397 * Purges the cache deleting all items within it.
398 *
399 * @return boolean True on success. False otherwise.
400 */
401 public function purge() {
f4cec2ec
MS
402 if ($this->isready) {
403 $this->collection->drop();
404 $this->collection = $this->database->selectCollection($this->definitionhash);
405 }
406
407 return true;
2e638e3d
SH
408 }
409
410 /**
411 * Takes the object from the add instance store and creates a configuration array that can be used to initialise an instance.
412 *
413 * @param stdClass $data
414 * @return array
415 */
416 public static function config_get_configuration_array($data) {
417 $return = array(
418 'server' => $data->server,
419 'database' => $data->database,
420 'extendedmode' => (!empty($data->extendedmode))
421 );
422 if (!empty($data->username)) {
423 $return['username'] = $data->username;
424 }
425 if (!empty($data->password)) {
426 $return['password'] = $data->password;
427 }
428 if (!empty($data->replicaset)) {
429 $return['replicaset'] = $data->replicaset;
430 }
431 if (!empty($data->usesafe)) {
432 $return['usesafe'] = true;
433 if (!empty($data->usesafevalue)) {
434 $return['usesafe'] = (int)$data->usesafevalue;
d837df0d 435 $return['usesafevalue'] = $return['usesafe'];
2e638e3d
SH
436 }
437 }
438 return $return;
439 }
440
81ede547
SH
441 /**
442 * Allows the cache store to set its data against the edit form before it is shown to the user.
443 *
444 * @param moodleform $editform
445 * @param array $config
446 */
447 public static function config_set_edit_form_data(moodleform $editform, array $config) {
448 $data = array();
449 if (!empty($config['server'])) {
450 $data['server'] = $config['server'];
451 }
452 if (!empty($config['database'])) {
453 $data['database'] = $config['database'];
454 }
d837df0d
SH
455 if (isset($config['extendedmode'])) {
456 $data['extendedmode'] = (bool)$config['extendedmode'];
81ede547
SH
457 }
458 if (!empty($config['username'])) {
459 $data['username'] = $config['username'];
460 }
461 if (!empty($config['password'])) {
462 $data['password'] = $config['password'];
463 }
464 if (!empty($config['replicaset'])) {
465 $data['replicaset'] = $config['replicaset'];
466 }
d837df0d
SH
467 if (isset($config['usesafevalue'])) {
468 $data['usesafe'] = true;
469 $data['usesafevalue'] = (int)$data['usesafe'];
470 } else if (isset($config['usesafe'])) {
471 $data['usesafe'] = (bool)$config['usesafe'];
81ede547
SH
472 }
473 $editform->set_data($data);
474 }
475
2e638e3d
SH
476 /**
477 * Performs any necessary clean up when the store instance is being deleted.
478 */
59ca73ff 479 public function instance_deleted() {
a037c943
SH
480 // We can't use purge here that acts upon a collection.
481 // Instead we must drop the named database.
482 if ($this->connection) {
483 $connection = $this->connection;
484 } else {
bb4c3916
SH
485 try {
486 $connection = new Mongo($this->server, $this->options);
487 } catch (MongoConnectionException $e) {
488 // We only want to catch MongoConnectionExceptions here.
489 // If the server cannot be connected to we cannot clean it.
490 return;
491 }
a037c943
SH
492 }
493 $database = $connection->selectDB($this->databasename);
494 $database->drop();
495 $connection = null;
496 $database = null;
497 // Explicitly unset things to cause a close.
498 $this->collection = null;
499 $this->database = null;
500 $this->connection = null;
59ca73ff
MS
501 }
502
2e638e3d
SH
503 /**
504 * Generates an instance of the cache store that can be used for testing.
505 *
506 * @param cache_definition $definition
507 * @return false
508 */
509 public static function initialise_test_instance(cache_definition $definition) {
510 if (!self::are_requirements_met()) {
511 return false;
512 }
513
6fec1820 514 $config = get_config('cachestore_mongodb');
2e638e3d
SH
515 if (empty($config->testserver)) {
516 return false;
517 }
2e638e3d
SH
518 $configuration = array();
519 $configuration['server'] = $config->testserver;
520 if (!empty($config->testreplicaset)) {
521 $configuration['replicaset'] = $config->testreplicaset;
522 }
523 if (!empty($config->testusername)) {
524 $configuration['username'] = $config->testusername;
525 }
526 if (!empty($config->testpassword)) {
527 $configuration['password'] = $config->testpassword;
528 }
529 if (!empty($config->testdatabase)) {
530 $configuration['database'] = $config->testdatabase;
531 }
32c981e6 532 $configuration['usesafe'] = 1;
2e638e3d
SH
533 if (!empty($config->testextendedmode)) {
534 $configuration['extendedmode'] = (bool)$config->testextendedmode;
535 }
536
6fec1820 537 $store = new cachestore_mongodb('Test mongodb', $configuration);
2e638e3d
SH
538 $store->initialise($definition);
539
540 return $store;
541 }
34c84c72
SH
542
543 /**
544 * Returns the name of this instance.
545 * @return string
546 */
547 public function my_name() {
548 return $this->name;
549 }
a3f3ea26 550}