[OPS] n8n-алерты убраны: метрика buryan_service_up{name=n8n} убрана через update-manager/services.yaml, монитор Kuma n8n.buryans.ru на паузе — Prometheus больше не шумит. Три задачи: gitea_selfheal.py (Hermes 5 мин, 2-strike restart CT140), path_monitor_light.py (каждые 5 мин: gw/wg/vds TCP 443/8444/8445 + TLS, алерт при 30-мин недоступности публичного VDS при живом WG), restic_restore_file.py (реальное восстановление /etc/pve/storage.cfg из pve-config, ежедневно 08:40; проверено ok 326 байт). Бонус: CT107 86%→79%

This commit is contained in:
root committed 2026-11-17 11:02:03 +03:00
1 parent cd911d7d9f
commit 03c05d8638
6 files changed
+325 -14

No files matched your search

+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""Самовосстановление Gitea (замена n8n-воркфлоу «Uptime Kuma → Gitea»).
Раз в 5 минут проверяет health Гит��и. Если не отвечает две проверки
подряд — перезапускает контейнер в CT140 и проверяет снова. Успех или
провал — событие в ALERT (без спама: дедуп по ключу).
"""
import json
import os
import subprocess
import sys
import urllib.request as u
URL = "http://192.168.1.140:3000/api/healthz"
CT = "140"
CONTAINER = "gitea"
STATE = "/var/lib/gitea-selfheal/streak"
NOTIFY = "/opt/buryan-hub/scripts/notify.py"
def health(timeout=8):
try:
with u.urlopen(URL, timeout=timeout) as r:
return r.status == 200
except Exception:
return False
def notify(title, text, priority="high"):
try:
subprocess.run(["/usr/bin/python3", NOTIFY, "--priority", priority,
"--title", title, text], capture_output=True,
text=True, timeout=120)
except Exception:
pass
def main():
if health():
_set(0)
print("gitea: ok")
return 0
print("gitea: не отвечает")
streak = _get() + 1
_set(streak)
if streak < 2:
return 1
r = subprocess.run(["pct", "exec", CT, "--", "docker", "restart", CONTAINER],
capture_output=True, text=True, timeout=180)
out = ((r.stdout or "") + (r.stderr or "")).strip()[-200:]
for _ in range(12):
import time as _t
_t.sleep(5)
if health():
_set(0)
notify("Gitea восстановлена", "Контейнер перезапущен, health снова ok.")
return 0
notify("Gitea не поднимается",
"Перезапуск контейнера не помог: %s" % out)
return 2
def _get():
try:
return int(open(STATE).read().strip() or 0)
except Exception:
return 0
def _set(n):
try:
os.makedirs(os.path.dirname(STATE), exist_ok=True)
open(STATE, "w").write(str(n))
except Exception:
pass
if __name__ == "__main__":
sys.exit(main())
+97
View File
@@ -0,0 +1,97 @@
#!/usr/bin/env python3
"""Лёгкий постоянный монитор пути до VDS (раз в 5 минут).
Что пишет: RTT до шлюза, до VDS по WG и по публичному адресу, доступность
TCP 443/8444 публично, TLS-рукопожатие 443. Одна строка JSONL на замер.
Если публичный VDS недоступен 30 минут подряд, а WG жив — уведомляет:
похоже на блокировку адреса (а не поломку сервера).
"""
import json
import os
import socket
import ssl
import subprocess
import sys
import time
from datetime import date
OUTDIR = "/var/lib/path-monitor-light"
STATE = OUTDIR + "/tcp-streak"
VDS = "193.233.210.184"
WG = "10.88.0.1"
GW = "192.168.1.1"
NOTIFY = "/opt/buryan-hub/scripts/notify.py"
def ping(host, count=2, timeout=3):
r = subprocess.run(["ping", "-c", str(count), "-W", str(timeout), host],
capture_output=True, text=True)
out = (r.stdout or "")
for line in out.splitlines():
if "rtt min/avg/max" in line:
return float(line.split("=")[1].split("/")[1])
return None
def tcp(host, port, timeout=4):
t0 = time.time()
try:
s = socket.create_connection((host, port), timeout=timeout)
s.close()
return round((time.time() - t0) * 1000)
except Exception:
return None
def tls(host, port=443, timeout=6):
try:
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
s = socket.create_connection((host, port), timeout=timeout)
ss = ctx.wrap_socket(s, server_hostname="git.buryans.ru")
v = ss.version()
ss.close()
return v
except Exception:
return None
def main():
# ICMP до VDS/WG часто фильтруется: WG жив, если SSH 10.88.0.1:22
rec = {"ts": time.strftime("%Y-%m-%dT%H:%M:%S"),
"gw_ms": ping(GW), "wg_ms": tcp(WG, 22),
"vds_ms": tcp(VDS, 443),
"tcp443": tcp(VDS, 443), "tcp8444": tcp(VDS, 8444),
"tcp8445": tcp(VDS, 8445), "tls443": tls(VDS)}
os.makedirs(OUTDIR, exist_ok=True)
with open(os.path.join(OUTDIR, "%s.jsonl" % date.today().isoformat()), "a",
encoding="utf-8") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
print(json.dumps(rec, ensure_ascii=False))
bad = rec["tcp443"] is None
streak = 0
try:
streak = int(open(STATE).read().strip() or 0)
except Exception:
streak = 0
streak = streak + 1 if bad else 0
try:
open(STATE, "w").write(str(streak))
except Exception:
pass
if streak == 6 and rec["wg_ms"] is not None: # 30 минут
try:
subprocess.run(["/usr/bin/python3", NOTIFY, "--priority", "high",
"--title", "VDS: публичный адрес недоступен",
"Публичный %s не отвечает 30 минут, WG живой (%s мс). "
"Похоже на блокировку адреса." % (VDS, rec["wg_ms"])],
capture_output=True, text=True, timeout=120)
except Exception:
pass
return 0
if __name__ == "__main__":
sys.exit(main())
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
"""Проверка восстановления ОДНОГО файла из restic (не только check).
Берёт последний снапшот pve-config, восстанавливает /etc/pve/storage.cfg
во временный каталог, проверяет содержимое, удаляет. Раз в неделю.
"""
import json
import os
import shutil
import subprocess
import sys
ENV = dict(os.environ,
RESTIC_PASSWORD_FILE="/root/.restic-password",
RESTIC_REPOSITORY="sftp:root@10.88.0.1:/backup/restic-repo")
TMP = "/tmp/restic-file-restore"
TARGET = "/etc/pve/storage.cfg"
NOTIFY = "/opt/buryan-hub/scripts/notify.py"
def run(cmd, t=300):
r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=t, env=ENV)
return r.returncode, ((r.stdout or "") + (r.stderr or ""))
def notify(title, text, priority="high"):
try:
subprocess.run(["/usr/bin/python3", NOTIFY, "--priority", priority,
"--title", title, text], capture_output=True,
text=True, timeout=120, env=ENV)
except Exception:
pass
def main():
rc, out = run("restic snapshots --json --tag pve-config --latest 1")
start = out.find("[")
if rc != 0 or start < 0:
notify("restic: нет снапшота pve-config", out[-300:])
return 1
try:
snaps = json.loads(out[start:])
snap = snaps[-1]["short_id"]
except Exception as e:
notify("restic: не разобрал снапшоты", str(e)[:200])
return 1
shutil.rmtree(TMP, ignore_errors=True)
os.makedirs(TMP, exist_ok=True)
rc, out = run("restic restore %s --target %s --include %s" % (snap, TMP, TARGET))
path = os.path.join(TMP, TARGET.lstrip("/"))
if rc == 0 and os.path.isfile(path) and os.path.getsize(path) > 0:
size = os.path.getsize(path)
txt = open(path, encoding="utf-8", errors="replace").read()
looks_ok = (":" in txt)
notify("restic: восстановление файла ok",
"Снапшот %s, %s — %d байт" % (snap, TARGET, size),
"normal" if looks_ok else "high")
print("ok:", snap, size)
shutil.rmtree(TMP, ignore_errors=True)
return 0
notify("restic: восстановление файла ПРОВАЛЕНО", out[-400:])
print("fail:", out[-500:])
return 1
if __name__ == "__main__":
sys.exit(main())