Merge branch 'MDL-44269_master' of git://github.com/lazydaisy/moodle
[moodle.git] / cache / stores / mongodb / lib.php
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/>.
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  *
22  * @package    cachestore_mongodb
23  * @copyright  2012 Sam Hemelryk
24  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25  */
27 defined('MOODLE_INTERNAL') || die();
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  */
40 class cachestore_mongodb extends cache_store implements cache_is_configurable {
42     /**
43      * The name of the store
44      * @var string
45      */
46     protected $name;
48     /**
49      * The server connection string. Comma separated values.
50      * @var string
51      */
52     protected $server = 'mongodb://127.0.0.1:27017';
54     /**
55      * The database connection options
56      * @var array
57      */
58     protected $options = array();
60     /**
61      * The name of the database to use.
62      * @var string
63      */
64     protected $databasename = 'mcache';
66     /**
67      * The Connection object
68      * @var Mongo
69      */
70     protected $connection = false;
72     /**
73      * The Database Object
74      * @var MongoDB
75      */
76     protected $database;
78     /**
79      * The Collection object
80      * @var MongoCollection
81      */
82     protected $collection;
84     /**
85      * Determines if and what safe setting is to be used.
86      * @var bool|int
87      */
88     protected $usesafe = false;
90     /**
91      * If set to true then multiple identifiers will be requested and used.
92      * @var bool
93      */
94     protected $extendedmode = false;
96     /**
97      * The definition has which is used in the construction of the collection.
98      * @var string
99      */
100     protected $definitionhash = null;
102     /**
103      * Set to true once this store is ready to be initialised and used.
104      * @var bool
105      */
106     protected $isready = false;
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      *
114      * @param string $name
115      * @param array $configuration
116      */
117     public function __construct($name, array $configuration = array()) {
118         $this->name = $name;
120         if (array_key_exists('server', $configuration)) {
121             $this->server = $configuration['server'];
122         }
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         }
143         try {
144             $this->connection = new Mongo($this->server, $this->options);
145             $this->isready = true;
146         } catch (MongoConnectionException $e) {
147             // We only want to catch MongoConnectionExceptions here.
148         }
149     }
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     }
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     }
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()) {
178         return self::MODE_APPLICATION + self::MODE_SESSION;
179     }
181     /**
182      * Initialises the store instance for use.
183      *
184      * Once this has been done the cache is all set to be used.
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         }
193         $this->database = $this->connection->selectDB($this->databasename);
194         $this->definitionhash = $definition->generate_definition_hash();
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     }
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     }
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     }
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     }
227     /**
228      * Returns true if this store is making use of multiple identifiers.
229      * @return bool
230      */
231     public function supports_multiple_identifiers() {
232         return $this->extendedmode;
233     }
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         }
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     }
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) {
277             $id = (string)$result['key'];
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     }
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,
306             'safe' => $this->usesafe,
307             'w' => $this->usesafe ? 1 : 0
308         );
309         $this->delete($key);
310         $result = $this->collection->insert($record, $options);
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;
322     }
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']);
336             if ($result === true) {
337                  $count++;
338             }
339         }
340         return $count;
341     }
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,
359             'safe' => $this->usesafe,
360             'w' => $this->usesafe ? 1 : 0
361         );
362         $result = $this->collection->remove($criteria, $options);
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;
375         }
376         // Who knows?
377         return false;
378     }
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     }
396     /**
397      * Purges the cache deleting all items within it.
398      *
399      * @return boolean True on success. False otherwise.
400      */
401     public function purge() {
402         if ($this->isready) {
403             $this->collection->drop();
404             $this->collection = $this->database->selectCollection($this->definitionhash);
405         }
407         return true;
408     }
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;
435                 $return['usesafevalue'] = $return['usesafe'];
436             }
437         }
438         return $return;
439     }
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         }
455         if (isset($config['extendedmode'])) {
456             $data['extendedmode'] = (bool)$config['extendedmode'];
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         }
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'];
472         }
473         $editform->set_data($data);
474     }
476     /**
477      * Performs any necessary clean up when the store instance is being deleted.
478      */
479     public function instance_deleted() {
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 {
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             }
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;
501     }
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         }
514         $config = get_config('cachestore_mongodb');
515         if (empty($config->testserver)) {
516             return false;
517         }
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         }
532         $configuration['usesafe'] = 1;
533         if (!empty($config->testextendedmode)) {
534             $configuration['extendedmode'] = (bool)$config->testextendedmode;
535         }
537         $store = new cachestore_mongodb('Test mongodb', $configuration);
538         $store->initialise($definition);
540         return $store;
541     }
543     /**
544      * Returns the name of this instance.
545      * @return string
546      */
547     public function my_name() {
548         return $this->name;
549     }