Skip to content

Commit ec4794b

Browse files
author
Anze
committed
Fix: close DB connection in main process to avoid multithreading issues caused by creating DB connection pool before the workers were forked
1 parent 43d5763 commit ec4794b

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

dbutils.py

+10-1
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,16 @@ def db_connect():
7474
connect_timeout=connect_timeout)
7575
except:
7676
db_pool = None
77-
log.error("DB connection failed")
77+
log.exception("DB connection failed")
78+
79+
80+
def db_disconnect():
81+
global db_pool
82+
if not db_pool:
83+
return
84+
db_pool.closeall()
85+
db_pool = None
86+
log.info("DB connection is closed")
7887

7988

8089
###########################

snmpbot.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
import psycopg2
1515

1616
from grafoleancollector import Collector
17-
from dbutils import get_db_cursor, DB_PREFIX, migrate_if_needed
17+
from dbutils import get_db_cursor, DB_PREFIX, migrate_if_needed, db_disconnect
1818

1919

2020
logging.basicConfig(format='%(asctime)s | %(levelname)s | %(message)s',
@@ -410,7 +410,6 @@ def jobs(self):
410410
Each entity (device) is a single job, no matter how many sensors it has. The reason is
411411
that when the intervals align, we can then issue a single SNMP Bulk GET/WALK.
412412
"""
413-
migrate_if_needed()
414413
for entity_info in self.fetch_job_configs('snmp'):
415414
intervals = list(set([sensor_info["interval"] for sensor_info in entity_info["sensors"]]))
416415
job_info = { **entity_info, "backend_url": self.backend_url, "bot_token": self.bot_token }
@@ -444,6 +443,9 @@ def wait_for_grafolean(backend_url):
444443
if __name__ == "__main__":
445444
dotenv.load_dotenv()
446445

446+
migrate_if_needed()
447+
db_disconnect() # each worker should open their own connection pool
448+
447449
backend_url = os.environ.get('BACKEND_URL')
448450
jobs_refresh_interval = int(os.environ.get('JOBS_REFRESH_INTERVAL', 120))
449451

0 commit comments

Comments
 (0)