]> arthur.barton.de Git - netdata.git/blobdiff - python.d/postgres.chart.py
Merge pull request #1887 from ktsaou/clock-fixes
[netdata.git] / python.d / postgres.chart.py
index 919b6f8eebef60a57fa002f56fdaa2d626679158..eb3224bf0b3da471664c583e83052858ec7e1283 100644 (file)
@@ -8,6 +8,7 @@ from copy import deepcopy
 import psycopg2
 from psycopg2 import extensions
 from psycopg2.extras import DictCursor
+from psycopg2 import OperationalError
 
 from base import SimpleService
 
@@ -193,7 +194,7 @@ class Service(SimpleService):
         self.table_stats = configuration.pop('table_stats', True)
         self.index_stats = configuration.pop('index_stats', True)
         self.configuration = configuration
-        self.connection = None
+        self.connection = False
         self.is_superuser = False
         self.data = {}
         self.databases = set()
@@ -202,18 +203,24 @@ class Service(SimpleService):
         params = dict(user='postgres',
                       database=None,
                       password=None,
-                      host='localhost',
+                      host=None,
                       port=5432)
         params.update(self.configuration)
 
         if not self.connection:
-            self.connection = psycopg2.connect(**params)
-            self.connection.set_isolation_level(extensions.ISOLATION_LEVEL_AUTOCOMMIT)
-            self.connection.set_session(readonly=True)
+            try:
+                self.connection = psycopg2.connect(**params)
+                self.connection.set_isolation_level(extensions.ISOLATION_LEVEL_AUTOCOMMIT)
+                self.connection.set_session(readonly=True)
+            except OperationalError:
+                return False
+        return True
 
     def check(self):
         try:
-            self._connect()
+            if not self._connect():
+                self.error('Can\'t connect to %s' % str(self.configuration))
+                return False
             cursor = self.connection.cursor()
             self._discover_databases(cursor)
             self._check_if_superuser(cursor)
@@ -291,13 +298,19 @@ class Service(SimpleService):
                 self.definitions[chart_name]['lines'].append([lock_id, label, 'absolute'])
 
     def _get_data(self):
-        self._connect()
-
-        cursor = self.connection.cursor(cursor_factory=DictCursor)
-        self.add_stats(cursor)
-
-        cursor.close()
-        return self.data
+        if self._connect():
+            cursor = self.connection.cursor(cursor_factory=DictCursor)
+            try:
+                self.add_stats(cursor)
+            except OperationalError:
+                self.connection = False
+                cursor.close()
+                return None
+            else:
+                cursor.close()
+                return self.data
+        else:
+            return None
 
     def add_stats(self, cursor):
         self.add_database_stats(cursor)