@cryptotaxi247 / netdata-1 / commits / 0f6457c9d

postgres plugin: reconnect to postgres after restart/stop etc

Ilya committed Jan 26, 2017 at 01:58 UTC 0f6457c9dfb50e3720bcec5d5a19b29ddbabbcfa
1 file changed +23 -11
python.d/postgres.chart.py
+23 -11
@@ -8,6 +8,7 @@ from copy import deepcopy
8 import psycopg2
9 from psycopg2 import extensions
10 from psycopg2.extras import DictCursor
11 +from psycopg2 import OperationalError
12
13 from base import SimpleService
14
@@ -193,7 +194,7 @@ class Service(SimpleService):
194 self.table_stats = configuration.pop('table_stats', True)
195 self.index_stats = configuration.pop('index_stats', True)
196 self.configuration = configuration
196 - self.connection = None
197 + self.connection = False
198 self.is_superuser = False
199 self.data = {}
200 self.databases = set()
@@ -207,9 +208,13 @@ class Service(SimpleService):
208 params.update(self.configuration)
209
210 if not self.connection:
210 - self.connection = psycopg2.connect(**params)
211 - self.connection.set_isolation_level(extensions.ISOLATION_LEVEL_AUTOCOMMIT)
212 - self.connection.set_session(readonly=True)
211 + try:
212 + self.connection = psycopg2.connect(**params)
213 + self.connection.set_isolation_level(extensions.ISOLATION_LEVEL_AUTOCOMMIT)
214 + self.connection.set_session(readonly=True)
215 + except OperationalError:
216 + return False
217 + return True
218
219 def check(self):
220 try:
@@ -291,13 +296,20 @@ class Service(SimpleService):
296 self.definitions[chart_name]['lines'].append([lock_id, label, 'absolute'])
297
298 def _get_data(self):
294 - self._connect()
295 -
296 - cursor = self.connection.cursor(cursor_factory=DictCursor)
297 - self.add_stats(cursor)
298 -
299 - cursor.close()
300 - return self.data
299 + if self._connect():
300 + cursor = self.connection.cursor(cursor_factory=DictCursor)
301 + try:
302 + self.add_stats(cursor)
303 + except OperationalError:
304 + if self.connection.closed == 2:
305 + self.connection = False
306 + cursor.close()
307 + return None
308 + else:
309 + cursor.close()
310 + return self.data
311 + else:
312 + return None
313
314 def add_stats(self, cursor):
315 self.add_database_stats(cursor)