From 5047a56fe8789520fd7ef77a3f6c445d87d50851 Mon Sep 17 00:00:00 2001 From: "Peter J. Holzer" Date: Mon, 17 Apr 2023 13:21:34 +0200 Subject: [PATCH] Record number of connections per dataabase from pg_stat_activity --- clients/record_pg_stat_activity | 60 +++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100755 clients/record_pg_stat_activity diff --git a/clients/record_pg_stat_activity b/clients/record_pg_stat_activity new file mode 100755 index 0000000..76e8c4d --- /dev/null +++ b/clients/record_pg_stat_activity @@ -0,0 +1,60 @@ +#!/usr/bin/python3 + +import time +import re + +import psycopg2 +import psycopg2.extras + +import ltsdb_record + +db = psycopg2.connect() # We only get useful results if we are postgres, but for testing we can be any user + +csr = db.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor) +csr.execute( + """ + select datname, count(*) + from pg_stat_activity + where backend_type = 'client backend' group by datname order by datname + """) + +total = 0 + +now = time.time() +report0 = [] +for r in csr: + report0.append( + { + "measure": "connections", + "database": r.datname, + "unit": "connections", + "value": r.count + } + ) + total += r.count +report0.append( + { + "measure": "connections", + "database": "ALL", + "unit": "connections", + "value": total + } + ) + +report = [ + { + "description": { + "hostname": ltsdb_record.node, + "measure": r["measure"], + "database": r["database"], + "unit": r["unit"] + }, + "data": [ + [now, r["value"]] + ] + } + for r in report0 +] + +success = ltsdb_record.record_observations(report) +exit(1 - success)