Fix MongoDB successful connection logging.
Since pymongo 3.0, client.connect() method is not blocking anymore and
always successfuly returns. Connection is established lazily when a
first query / command is issued.
This means we incorrectly always logged "Successfully connected to
database" when a connection was not established yet and when subsequent
queries failed.
@@ -25,6 +25,7 @@ import mongoengine
from mongoengine.queryset import visitor
from pymongo import uri_parser
from pymongo.errors import OperationFailure
+from pymongo.errors import ConnectionFailure
from st2common import log as logging
from st2common.util import isotime
@@ -113,6 +114,17 @@ def _db_connect(db_name, db_host, db_port, username=None, password=None,
username=username, password=password,
**ssl_kwargs)
+ # NOTE: In recent version of pymongo connect() method is lazy and not blocking (always
+ # returns success) so we need to issue a common / query to check if connection has been
+ # successfuly established
+ try:
+ # The ismaster command is cheap and does not require auth.
+ connection.admin.command('ismaster')
+ except ConnectionFailure as e:
+ LOG.error('Failed to connect to database "%s" @ "%s" as user "%s".' % (db_name,
+ host_string, str(username_string)))
+ raise e
+
LOG.info('Successfully connected to database "%s" @ "%s" as user "%s".' % (
db_name, host_string, str(username_string)))
