Files

106 lines
4.3 KiB
Python
Executable File

#!/usr/bin/env python3
"""Дополнение лёджера: диск по CT, возраст образов, использование по доменам.
Дописывает в ops/topology/ledger.md разделы, которых не хватало для
оценки «стоимости» сервиса (пункт 3 контура V1).
"""
import json
import os
import re
import subprocess
from datetime import datetime
ROOT = "/root/buryan-infra"
LEDGER = ROOT + "/ops/topology/ledger.md"
VPS = "193.233.210.184"
def sh(cmd, timeout=60):
try:
r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout)
return (r.stdout or "").strip()
except Exception:
return ""
def main():
sections = []
# 1) диск по контейнерам
rows = []
for line in sh("pct list").splitlines()[1:]:
p = line.split()
if len(p) < 2 or p[1] != "running":
continue
ct, name = p[0], (p[2] if len(p) > 2 else "")
out = sh("pct exec %s -- sh -c \"df -h / | tail -1\" " % ct, 30)
m = re.search(r"(\d+)%\s+/\s*$", out)
if m:
rows.append((int(m.group(1)), ct, name))
rows.sort(reverse=True)
sections.append(("Диск по контейнерам (топ по заполнению)", rows and
["| CT | Имя | Заполнено |", "|---|---|---|"] +
["| CT%s | %s | %d%% |" % (ct, name, pct) for pct, ct, name in rows[:12]] or
["нет данных"]))
# 2) возраст образов (сколько старше 180 дней)
old, total = 0, 0
for line in sh("pct list").splitlines()[1:]:
p = line.split()
if len(p) < 2 or p[1] != "running":
continue
ct = p[0]
out = sh("pct exec %s -- sh -c 'docker ps --format \"{{.Image}}\" 2>/dev/null'" % ct, 40)
for img in set(x for x in out.splitlines() if x.strip()):
total += 1
created = sh("pct exec %s -- sh -c 'docker inspect --format \"{{.Created}}\" %s 2>/dev/null'"
% (ct, img), 25)
m = re.match(r"(\d{4}-\d{2}-\d{2})", created)
if m:
try:
age = (datetime.now() - datetime.strptime(m.group(1), "%Y-%m-%d")).days
if age > 180:
old += 1
except Exception:
pass
sections.append(("Возраст образов", [
"| Метрика | Значение |", "|---|---|",
"| Образов (уникальных) | %d |" % total,
"| Старше 180 дней | %d |" % old,
"| Вывод | %s |" % ("есть кандидаты на обновление" if old else "всё свежее"),
]))
# 3) использование по доменам (nginx host + VPS, за текущий лог)
usage = {}
host_log = sh("awk '{print $1}' /var/log/nginx/access.log 2>/dev/null | wc -l", 30)
usage["хост"] = host_log or "0"
vps_log = sh("ssh -o ConnectTimeout=10 -o BatchMode=yes root@%s "
"'awk \"{print \\\\$1}\" /var/log/nginx/access.log 2>/dev/null | wc -l'" % VPS, 40)
usage["VPS"] = vps_log or "0"
sections.append(("Использование (запросов в текущем логе nginx)", [
"| Узел | Запросов |", "|---|---|",
"| хост | %s |" % usage["хост"],
"| VPS | %s |" % usage["VPS"],
]))
# запись
try:
text = open(LEDGER, encoding="utf-8").read()
except Exception:
text = "# Лёджер сервисов (V1, Фаза A)\n"
# удаляем предыдущие доп.разделы
text = text.split("\n## Дополнение:")[0].rstrip() + "\n"
text += "\n## Дополнение: стоимость и использование\n"
text += "\n_Обновлено: %s_\n" % datetime.now().isoformat(timespec="seconds")
for title, lines in sections:
text += "\n### %s\n\n" % title
text += "\n".join(lines) + "\n"
open(LEDGER, "w", encoding="utf-8").write(text)
print("лёджер дополнен:", LEDGER)
for title, lines in sections:
print(" ", title, "—", len(lines), "строк")
if __name__ == "__main__":
main()