Record number of connections per dataabase from pg_stat_activity

This commit is contained in:
Peter J. Holzer 2023-04-17 13:21:34 +02:00
parent 1485debaae
commit 5047a56fe8
1 changed files with 60 additions and 0 deletions

60
clients/record_pg_stat_activity Executable file
View File

@ -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)