]> arthur.barton.de Git - netdata.git/blob - python.d/postgres.chart.py
919b6f8eebef60a57fa002f56fdaa2d626679158
[netdata.git] / python.d / postgres.chart.py
1 # -*- coding: utf-8 -*-
2 # Description: example netdata python.d module
3 # Authors: facetoe, dangtranhoang
4
5 import re
6 from copy import deepcopy
7
8 import psycopg2
9 from psycopg2 import extensions
10 from psycopg2.extras import DictCursor
11
12 from base import SimpleService
13
14 # default module values
15 update_every = 1
16 priority = 90000
17 retries = 60
18
19 ARCHIVE = """
20 SELECT
21     CAST(COUNT(*) AS INT) AS file_count,
22     CAST(COALESCE(SUM(CAST(archive_file ~ $r$\.ready$$r$ as INT)), 0) AS INT) AS ready_count,
23     CAST(COALESCE(SUM(CAST(archive_file ~ $r$\.done$$r$ AS INT)), 0) AS INT) AS done_count
24 FROM
25     pg_catalog.pg_ls_dir('pg_xlog/archive_status') AS archive_files (archive_file);
26 """
27
28 BACKENDS = """
29 SELECT
30     count(*) - (SELECT count(*) FROM pg_stat_activity WHERE state = 'idle') AS backends_active,
31     (SELECT count(*) FROM pg_stat_activity WHERE state = 'idle' ) AS backends_idle
32 FROM
33     pg_stat_activity;
34 """
35
36 TABLE_STATS = """
37 SELECT
38   ((sum(relpages) * 8) * 1024) AS size_relations,
39   count(1)                     AS relations
40 FROM pg_class
41 WHERE relkind IN ('r', 't');
42 """
43
44 INDEX_STATS = """
45 SELECT
46   ((sum(relpages) * 8) * 1024) AS size_indexes,
47   count(1)                     AS indexes
48 FROM pg_class
49 WHERE relkind = 'i';"""
50
51 DATABASE = """
52 SELECT
53   datname AS database_name,
54   sum(numbackends) AS connections,
55   sum(xact_commit) AS xact_commit,
56   sum(xact_rollback) AS xact_rollback,
57   sum(blks_read) AS blks_read,
58   sum(blks_hit) AS blks_hit,
59   sum(tup_returned) AS tup_returned,
60   sum(tup_fetched) AS tup_fetched,
61   sum(tup_inserted) AS tup_inserted,
62   sum(tup_updated) AS tup_updated,
63   sum(tup_deleted) AS tup_deleted,
64   sum(conflicts) AS conflicts
65 FROM pg_stat_database
66 WHERE NOT datname ~* '^template\d+'
67 GROUP BY database_name;
68 """
69
70 BGWRITER = 'SELECT * FROM pg_stat_bgwriter;'
71 DATABASE_LOCKS = """
72 SELECT
73   pg_database.datname as database_name,
74   mode,
75   count(mode) AS count
76 FROM pg_locks
77   INNER JOIN pg_database ON pg_database.oid = pg_locks.database
78 GROUP BY datname, mode
79 ORDER BY datname, mode;
80 """
81 REPLICATION = """
82 SELECT
83     client_hostname,
84     client_addr,
85     state,
86     sent_offset - (
87         replay_offset - (sent_xlog - replay_xlog) * 255 * 16 ^ 6 ) AS byte_lag
88 FROM (
89     SELECT
90         client_addr, client_hostname, state,
91         ('x' || lpad(split_part(sent_location::text,   '/', 1), 8, '0'))::bit(32)::bigint AS sent_xlog,
92         ('x' || lpad(split_part(replay_location::text, '/', 1), 8, '0'))::bit(32)::bigint AS replay_xlog,
93         ('x' || lpad(split_part(sent_location::text,   '/', 2), 8, '0'))::bit(32)::bigint AS sent_offset,
94         ('x' || lpad(split_part(replay_location::text, '/', 2), 8, '0'))::bit(32)::bigint AS replay_offset
95     FROM pg_stat_replication
96 ) AS s;
97 """
98
99 LOCK_TYPES = [
100     'ExclusiveLock',
101     'RowShareLock',
102     'SIReadLock',
103     'ShareUpdateExclusiveLock',
104     'AccessExclusiveLock',
105     'AccessShareLock',
106     'ShareRowExclusiveLock',
107     'ShareLock',
108     'RowExclusiveLock'
109 ]
110
111 ORDER = ['db_stat_transactions', 'db_stat_tuple_read', 'db_stat_tuple_returned', 'db_stat_tuple_write',
112          'backend_process', 'index_count', 'index_size', 'table_count', 'table_size', 'wal', 'background_writer']
113
114 CHARTS = {
115     'db_stat_transactions': {
116         'options': [None, 'Transactions on db', 'transactions/s', 'db statistics', 'postgres.db_stat_transactions', 'line'],
117         'lines': [
118             ['db_stat_xact_commit',   'committed',   'incremental'],
119             ['db_stat_xact_rollback', 'rolled back', 'incremental']
120         ]},
121     'db_stat_connections': {
122         'options': [None, 'Current connections to db', 'count', 'db statistics', 'postgres.db_stat_connections', 'line'],
123         'lines': [
124             ['db_stat_connections', 'connections', 'absolute']
125         ]},
126     'db_stat_tuple_read': {
127         'options': [None, 'Tuple reads from db', 'reads/s', 'db statistics', 'postgres.db_stat_tuple_read', 'line'],
128         'lines': [
129             ['db_stat_blks_read', 'disk',  'incremental'],
130             ['db_stat_blks_hit',  'cache', 'incremental']
131         ]},
132     'db_stat_tuple_returned': {
133         'options': [None, 'Tuples returned from db', 'tuples/s', 'db statistics', 'postgres.db_stat_tuple_returned', 'line'],
134         'lines': [
135             ['db_stat_tup_returned', 'sequential', 'incremental'],
136             ['db_stat_tup_fetched',  'bitmap',     'incremental']
137         ]},
138     'db_stat_tuple_write': {
139         'options': [None, 'Tuples written to db', 'writes/s', 'db statistics', 'postgres.db_stat_tuple_write', 'line'],
140         'lines': [
141             ['db_stat_tup_inserted', 'inserted',  'incremental'],
142             ['db_stat_tup_updated',  'updated',   'incremental'],
143             ['db_stat_tup_deleted',  'deleted',   'incremental'],
144             ['db_stat_conflicts',    'conflicts', 'incremental']
145         ]},
146     'backend_process': {
147         'options': [None, 'Current Backend Processes', 'processes', 'backend processes', 'postgres.backend_process', 'line'],
148         'lines': [
149             ['backend_process_active', 'active', 'absolute'],
150             ['backend_process_idle',   'idle',   'absolute']
151         ]},
152     'index_count': {
153         'options': [None, 'Total indexes', 'index', 'indexes', 'postgres.index_count', 'line'],
154         'lines': [
155             ['index_count', 'total', 'absolute']
156         ]},
157     'index_size': {
158         'options': [None, 'Indexes size', 'MB', 'indexes', 'postgres.index_size', 'line'],
159         'lines': [
160             ['index_size', 'size', 'absolute', 1, 1024 * 1024]
161         ]},
162     'table_count': {
163         'options': [None, 'Total Tables', 'tables', 'tables', 'postgres.table_count', 'line'],
164         'lines': [
165             ['table_count', 'total', 'absolute']
166         ]},
167     'table_size': {
168         'options': [None, 'Tables size', 'MB', 'tables', 'postgres.table_size', 'line'],
169         'lines': [
170             ['table_size', 'size', 'absolute', 1, 1024 * 1024]
171         ]},
172     'wal': {
173         'options': [None, 'Write-Ahead Logging Statistics', 'files/s', 'write ahead log', 'postgres.wal', 'line'],
174         'lines': [
175             ['wal_total', 'total', 'incremental'],
176             ['wal_ready', 'ready', 'incremental'],
177             ['wal_done',  'done',  'incremental']
178         ]},
179     'background_writer': {
180         'options': [None, 'Checkpoints', 'writes/s', 'background writer', 'postgres.background_writer', 'line'],
181         'lines': [
182             ['background_writer_scheduled', 'scheduled', 'incremental'],
183             ['background_writer_requested', 'requested', 'incremental']
184         ]}
185 }
186
187
188 class Service(SimpleService):
189     def __init__(self, configuration=None, name=None):
190         super(self.__class__, self).__init__(configuration=configuration, name=name)
191         self.order = ORDER
192         self.definitions = CHARTS
193         self.table_stats = configuration.pop('table_stats', True)
194         self.index_stats = configuration.pop('index_stats', True)
195         self.configuration = configuration
196         self.connection = None
197         self.is_superuser = False
198         self.data = {}
199         self.databases = set()
200
201     def _connect(self):
202         params = dict(user='postgres',
203                       database=None,
204                       password=None,
205                       host='localhost',
206                       port=5432)
207         params.update(self.configuration)
208
209         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)
213
214     def check(self):
215         try:
216             self._connect()
217             cursor = self.connection.cursor()
218             self._discover_databases(cursor)
219             self._check_if_superuser(cursor)
220             cursor.close()
221
222             self._create_definitions()
223             return True
224         except Exception as e:
225             self.error(str(e))
226             return False
227
228     def _discover_databases(self, cursor):
229         cursor.execute("""
230             SELECT datname
231             FROM pg_stat_database
232             WHERE NOT datname ~* '^template\d+'
233         """)
234         self.databases = set(r[0] for r in cursor)
235
236     def _check_if_superuser(self, cursor):
237         cursor.execute("""
238             SELECT current_setting('is_superuser') = 'on' AS is_superuser;
239         """)
240         self.is_superuser = cursor.fetchone()[0]
241
242     def _create_definitions(self):
243         for database_name in self.databases:
244             for chart_template_name in list(CHARTS):
245                 if chart_template_name.startswith('db_stat'):
246                     self._add_database_stat_chart(chart_template_name, database_name)
247             self._add_database_lock_chart(database_name)
248
249     def _add_database_stat_chart(self, chart_template_name, database_name):
250         chart_template = CHARTS[chart_template_name]
251         chart_name = "{0}_{1}".format(database_name, chart_template_name)
252         if chart_name not in self.order:
253             self.order.insert(0, chart_name)
254             name, title, units, family, context, chart_type = chart_template['options']
255             self.definitions[chart_name] = {
256                 'options': [
257                     name,
258                     title + ': ' + database_name,
259                     units,
260                     'db ' + database_name,
261                     context,
262                     chart_type
263                 ]
264             }
265
266             self.definitions[chart_name]['lines'] = []
267             for line in deepcopy(chart_template['lines']):
268                 line[0] = "{0}_{1}".format(database_name, line[0])
269                 self.definitions[chart_name]['lines'].append(line)
270
271     def _add_database_lock_chart(self, database_name):
272         chart_name = "{0}_locks".format(database_name)
273         if chart_name not in self.order:
274             self.order.insert(-1, chart_name)
275             self.definitions[chart_name] = dict(
276                 options=
277                 [
278                     None,
279                     'Locks on db: ' + database_name,
280                     'locks',
281                     'db ' + database_name,
282                     'postgres.db_locks',
283                     'line'
284                 ],
285                 lines=[]
286             )
287
288             for lock_type in LOCK_TYPES:
289                 lock_id = "{0}_{1}".format(database_name, lock_type)
290                 label = re.sub("([a-z])([A-Z])", "\g<1> \g<2>", lock_type)
291                 self.definitions[chart_name]['lines'].append([lock_id, label, 'absolute'])
292
293     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
301
302     def add_stats(self, cursor):
303         self.add_database_stats(cursor)
304         self.add_backend_stats(cursor)
305         if self.index_stats:
306             self.add_index_stats(cursor)
307         if self.table_stats:
308             self.add_table_stats(cursor)
309         self.add_lock_stats(cursor)
310         self.add_bgwriter_stats(cursor)
311
312         # self.add_replication_stats(cursor)
313
314         if self.is_superuser:
315             self.add_wal_stats(cursor)
316
317     def add_database_stats(self, cursor):
318         cursor.execute(DATABASE)
319         for row in cursor:
320             database_name = row.get('database_name')
321             self.data["{0}_{1}".format(database_name, 'db_stat_xact_commit')]   = int(row.get('xact_commit',   0))
322             self.data["{0}_{1}".format(database_name, 'db_stat_xact_rollback')] = int(row.get('xact_rollback', 0))
323             self.data["{0}_{1}".format(database_name, 'db_stat_blks_read')]     = int(row.get('blks_read',     0))
324             self.data["{0}_{1}".format(database_name, 'db_stat_blks_hit')]      = int(row.get('blks_hit',      0))
325             self.data["{0}_{1}".format(database_name, 'db_stat_tup_returned')]  = int(row.get('tup_returned',  0))
326             self.data["{0}_{1}".format(database_name, 'db_stat_tup_fetched')]   = int(row.get('tup_fetched',   0))
327             self.data["{0}_{1}".format(database_name, 'db_stat_tup_inserted')]  = int(row.get('tup_inserted',  0))
328             self.data["{0}_{1}".format(database_name, 'db_stat_tup_updated')]   = int(row.get('tup_updated',   0))
329             self.data["{0}_{1}".format(database_name, 'db_stat_tup_deleted')]   = int(row.get('tup_deleted',   0))
330             self.data["{0}_{1}".format(database_name, 'db_stat_conflicts')]     = int(row.get('conflicts',     0))
331             self.data["{0}_{1}".format(database_name, 'db_stat_connections')]   = int(row.get('connections',   0))
332
333     def add_backend_stats(self, cursor):
334         cursor.execute(BACKENDS)
335         temp = cursor.fetchone()
336
337         self.data['backend_process_active'] = int(temp.get('backends_active', 0))
338         self.data['backend_process_idle']   = int(temp.get('backends_idle',   0))
339
340     def add_index_stats(self, cursor):
341         cursor.execute(INDEX_STATS)
342         temp = cursor.fetchone()
343         self.data['index_count'] = int(temp.get('indexes',      0))
344         self.data['index_size']  = int(temp.get('size_indexes', 0))
345
346     def add_table_stats(self, cursor):
347         cursor.execute(TABLE_STATS)
348         temp = cursor.fetchone()
349         self.data['table_count'] = int(temp.get('relations',      0))
350         self.data['table_size']  = int(temp.get('size_relations', 0))
351
352     def add_lock_stats(self, cursor):
353         cursor.execute(DATABASE_LOCKS)
354
355         # zero out all current lock values
356         for database_name in self.databases:
357             for lock_type in LOCK_TYPES:
358                 self.data["{0}_{1}".format(database_name, lock_type)] = 0
359
360         # populate those that have current locks
361         for row in cursor:
362             database_name, lock_type, lock_count = row
363             self.data["{0}_{1}".format(database_name, lock_type)] = lock_count
364
365     def add_wal_stats(self, cursor):
366         cursor.execute(ARCHIVE)
367         temp = cursor.fetchone()
368         self.data['wal_total'] = int(temp.get('file_count',  0))
369         self.data['wal_ready'] = int(temp.get('ready_count', 0))
370         self.data['wal_done']  = int(temp.get('done_count',  0))
371
372     def add_bgwriter_stats(self, cursor):
373         cursor.execute(BGWRITER)
374         temp = cursor.fetchone()
375         self.data['background_writer_scheduled'] = temp.get('checkpoints_timed',    0)
376         self.data['background_writer_requested'] = temp.get('checkpoints_requests', 0)
377
378 '''
379     def add_replication_stats(self, cursor):
380         cursor.execute(REPLICATION)
381         temp = cursor.fetchall()
382         for row in temp:
383             self.add_gauge_value('Replication/%s' % row.get('client_addr', 'Unknown'),
384                                  'byte_lag',
385                                  int(row.get('byte_lag', 0)))
386 '''