From 46cc53eb219116296c02ec4f02722f168eb8a507 Mon Sep 17 00:00:00 2001 From: Leo Q Date: Mon, 23 Aug 2021 19:30:20 +0800 Subject: [PATCH] fix mongo connction --- sql/engines/mongo.py | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/sql/engines/mongo.py b/sql/engines/mongo.py index 8e7143fd7e..49ca125b21 100644 --- a/sql/engines/mongo.py +++ b/sql/engines/mongo.py @@ -256,17 +256,19 @@ def exec_cmd(self, sql, db_name=None, slave_ok=''): """审核时执行的语句""" if self.user and self.password and self.port and self.host: + msg = "" + auth_db = self.instance.db_name or 'admin' try: - if not sql.startswith('var host='): # 在master节点执行的情况 - cmd = "{mongo} --quiet -u {uname} -p '{password}' {host}:{port}/admin <<\\EOF\ndb=db.getSiblingDB(\"{db_name}\");{slave_ok}printjson({sql})\nEOF".format( - mongo=mongo, uname=self.user, password=self.password, host=self.host, port=self.port, - db_name=db_name, sql=sql, slave_ok=slave_ok) + if not sql.startswith('var host='): #在master节点执行的情况 + cmd = "{mongo} --quiet -u {uname} -p '{password}' {host}:{port}/{auth_db} <<\\EOF\ndb=db.getSiblingDB(\"{db_name}\");{slave_ok}printjson({sql})\nEOF".format( + mongo=mongo, uname=self.user, password=self.password, host=self.host, port=self.port, db_name=db_name, sql=sql, auth_db=auth_db, slave_ok=slave_ok) else: - cmd = "{mongo} --quiet -u {user} -p '{password}' {host}:{port}/admin <<\\EOF\nrs.slaveOk();{sql}\nEOF".format( - mongo=mongo, user=self.user, password=self.password, host=self.host, port=self.port, - db_name=db_name, sql=sql) + cmd = "{mongo} --quiet -u {user} -p '{password}' {host}:{port}/{auth_db} <<\\EOF\nrs.slaveOk();{sql}\nEOF".format( + mongo=mongo, user=self.user, password=self.password, host=self.host, port=self.port, db_name=db_name, sql=sql, auth_db=auth_db) logger.debug(cmd) - p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + p = subprocess.Popen(cmd, shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, universal_newlines=True) re_msg = [] for line in iter(p.stdout.read, ''): @@ -501,8 +503,7 @@ def execute_check(self, db_name=None, sql=''): return check_result def get_connection(self, db_name=None): - self.db_name = db_name or 'admin' # =======这里要注意一下 - self.db_name = 'admin' + self.db_name = db_name or self.instance.db_name self.conn = pymongo.MongoClient(self.host, self.port, authSource=self.db_name, connect=True, connectTimeoutMS=10000) if self.user and self.password: