Commit 11025e87 authored by Raphael Beer's avatar Raphael Beer

Add: wait for DB +

  Makes 7 attempts to connect to the database
parent 208a9d57
import copy import copy
import traceback import traceback
import sys import sys
from time import sleep
from pymongo import MongoClient, errors as MongoErrors, DESCENDING from pymongo import MongoClient, errors as MongoErrors, DESCENDING
class Database: class Database:
...@@ -9,7 +10,6 @@ class Database: ...@@ -9,7 +10,6 @@ class Database:
RESULTS_COLLECTION = 'results' RESULTS_COLLECTION = 'results'
RATELIMIT_COLLECTION = 'rate-limits' RATELIMIT_COLLECTION = 'rate-limits'
try:
print('[mongoDB] Connecting to ' + host + ':' + str(port)) print('[mongoDB] Connecting to ' + host + ':' + str(port))
print('[mongoDB] Using Database `' + db + '`') print('[mongoDB] Using Database `' + db + '`')
# client and DB # client and DB
...@@ -23,12 +23,6 @@ class Database: ...@@ -23,12 +23,6 @@ class Database:
# Test connection immediately, instead of # Test connection immediately, instead of
# when trying to write in a request, later. # when trying to write in a request, later.
self.client.admin.command('ismaster') self.client.admin.command('ismaster')
except MongoErrors.ServerSelectionTimeoutError:
print(traceback.format_exc())
sys.exit('MongoDB connection timed out.')
except:
print(traceback.format_exc())
sys.exit('MongoDB connection failed.')
def write_result(self, result): def write_result(self, result):
# copy.deepcopy; otherwise mongo ObjectId (_id) would be added, # copy.deepcopy; otherwise mongo ObjectId (_id) would be added,
...@@ -45,4 +39,20 @@ def connect(host=None, port=27017, db='tester', username=None, password=None): ...@@ -45,4 +39,20 @@ def connect(host=None, port=27017, db='tester', username=None, password=None):
if host is None: if host is None:
raise ValueError('[mongoDB] Database constructor needs a `host`name or ip!') raise ValueError('[mongoDB] Database constructor needs a `host`name or ip!')
return Database(host=host, port=port, db=db, username=username, password=password) attempt = 0
max_attempts = 7
mongo_client = None
while (mongo_client is None):
print('[mongoDB|connect] Connecting, ', attempt, '/', max_attempts)
try:
mongo_client = Database(host=host, port=port, db=db, username=username, password=password)
except Exception as e:
if attempt is max_attempts:
raise e
sleep(attempt)
attempt += 1
return mongo_client
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment