61 lines
2.6 KiB
Python
Executable File
61 lines
2.6 KiB
Python
Executable File
#!/usr/bin/env python3
|
||
"""Ежедневный аудит Tool Gateway из Postgres: объём, ошибки, p95, топ-инструменты."""
|
||
import os
|
||
import subprocess
|
||
import time
|
||
import urllib.request
|
||
import json
|
||
import sys
|
||
|
||
ROOM = "!puEdcZCc87kKoCm3mX5bbjrTS-Skv2XCZg7JJBKOMw0"
|
||
HS = "http://192.168.1.155:8008"
|
||
|
||
|
||
def pg(sql):
|
||
env = dict(os.environ, PGPASSWORD=open("/root/.pg-superuser-pass").read().strip())
|
||
r = subprocess.run(["psql", "-w", "-h", "192.168.1.151", "-U", "postgres", "-d", "hermes",
|
||
"-t", "-A", "-F", "|", "-c", sql], capture_output=True, text=True,
|
||
timeout=20, env=env)
|
||
return [ln.split("|") for ln in (r.stdout or "").strip().splitlines() if ln]
|
||
|
||
|
||
def matrix(text):
|
||
tok = open("/root/.matrix-admin-token").read().strip()
|
||
txn = "audit-%d" % int(time.time() * 1000)
|
||
body = json.dumps({"msgtype": "m.text", "body": text}).encode()
|
||
url = "%s/_matrix/client/v3/rooms/%s/send/m.room.message/%s?access_token=%s" % (HS, ROOM, txn, tok)
|
||
req = urllib.request.Request(url, data=body, headers={"Content-Type": "application/json"}, method="PUT")
|
||
with urllib.request.urlopen(req, timeout=20) as r:
|
||
return r.status
|
||
|
||
|
||
def main():
|
||
rows = pg("""select count(*), count(*) filter (where not ok),
|
||
coalesce(round(avg(ms)),0),
|
||
coalesce(round(percentile_cont(0.95) within group (order by ms)),0)
|
||
from tool_audit where ts > now() - interval '24 hours';""")
|
||
total, errors, avg, p95 = (rows[0] + ["0", "0", "0", "0"])[:4] if rows else ("0", "0", "0", "0")
|
||
top = pg("""select tool, count(*), count(*) filter (where not ok),
|
||
coalesce(round(avg(ms)),0) from tool_audit
|
||
where ts > now() - interval '24 hours'
|
||
group by tool order by count(*) desc limit 8;""")
|
||
lines = ["📊 **Аудит Tool Gateway за 24ч** — " + time.strftime("%d.%m.%Y"),
|
||
"• Вызовов: **%s**, ошибок: **%s**" % (total, errors),
|
||
"• Среднее: **%s мс**, p95: **%s мс**" % (avg, p95)]
|
||
if top:
|
||
lines.append("• Топ инструментов:")
|
||
for t in top:
|
||
lines.append(" – %s: %s (ошибок %s, avg %s мс)" % (t[0], t[1], t[2], t[3]))
|
||
text = "\n".join(lines)
|
||
try:
|
||
print("sent", matrix(text))
|
||
except Exception as e:
|
||
print("matrix failed:", e)
|
||
subprocess.run(["/opt/buryan-hub/scripts/notify.py", "--priority", "normal",
|
||
"--title", "Аудит Tool Gateway", text], timeout=30)
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|