From 02a5d26bd58ab885dcbc402cef1e31c5bdda2e8e Mon Sep 17 00:00:00 2001 From: Victor Deniz Falcon Date: Mon, 18 Mar 2019 11:11:01 +0000 Subject: [PATCH] MDL-54592 cachestore_mongodb: check MongoDB server connection The connection to the MongoDB server is checked on the creation and deletion of a cache store instance. If the connection fails during creation, the instance is set as not ready. Before deleting a instance, a new cachestore_mongodb object is created, and connection checked. There is no reason to check again the connection in the instance_deleted() method. --- cache/stores/mongodb/lib.php | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/cache/stores/mongodb/lib.php b/cache/stores/mongodb/lib.php index 302828fc587..2122b817a0a 100644 --- a/cache/stores/mongodb/lib.php +++ b/cache/stores/mongodb/lib.php @@ -144,6 +144,9 @@ class cachestore_mongodb extends cache_store implements cache_is_configurable { try { $this->connection = new MongoDB\Client($this->server, $this->options); + // Required because MongoDB\Client does not try to connect to the server + $rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY); + $this->connection->getManager()->selectServer($rp); $this->isready = true; } catch (MongoDB\Driver\Exception\RuntimeException $e) { // We only want to catch RuntimeException here. @@ -480,18 +483,10 @@ class cachestore_mongodb extends cache_store implements cache_is_configurable { public function instance_deleted() { // We can't use purge here that acts upon a collection. // Instead we must drop the named database. - if ($this->connection) { - $connection = $this->connection; - } else { - try { - $connection = new MongoDB\Client($this->server, $this->options); - } catch (MongoDB\Driver\Exception\RuntimeException $e) { - // We only want to catch RuntimeException here. - // If the server cannot be connected to we cannot clean it. - return; - } + if (!$this->is_ready()) { + return; } - $database = $connection->selectDatabase($this->databasename); + $database = $this->connection->selectDatabase($this->databasename); $database->drop(); $connection = null; $database = null;