diff --git a/ops/audits/THREE-TASKS-N8N-2026-11-17.md b/ops/audits/THREE-TASKS-N8N-2026-11-17.md new file mode 100644 index 0000000..b48ba5f --- /dev/null +++ b/ops/audits/THREE-TASKS-N8N-2026-11-17.md @@ -0,0 +1,75 @@ +# Три задачи + n8n-алерты (17.11.2026) + +## 0. Критический алерт Prometheus по n8n — убран + +Секретарь присылал «КРИТИЧНО: n8n не отвечает 7 минут» (Prometheus rule +`КритичнаяСлужбаНеОтвечает`) и «Монитор: n8n.buryans.ru — Down» (Kuma). + +Причина: после вывода n8n из эксплуатации остались два «наблюдателя»: + +* метрика `buryan_service_up{name="n8n"}` — её генерирует + `export-service-metrics.py` из **`ops/update-manager/services.yaml`** + (второй каталог служб, отдельный от `hub-core/services.yaml`); +* монитор `n8n.buryans.ru` в Uptime Kuma (id=2). + +Исправлено: + +* блок `n8n:` удалён из `ops/update-manager/services.yaml`, метрики + перегенерированы → `buryan_service_up{name="n8n"}` **исчезла**; +* монитор Kuma переведён в `active=0` (пауза), Kuma перезапущена. + +Проверка: Alertmanager больше не содержит алертов по n8n. + +## 1. Gitea self-healing (замена n8n-воркфлоу) + +n8n-воркфлоу «Uptime Kuma → Gitea Self-Healing» выключен вместе с n8n. +Замена — Hermes-правило `gitea_selfheal.py`: + +* проверка `http://192.168.1.140:3000/api/healthz` каждые 5 минут; +* 2 неудачи подряд → `pct exec 140 -- docker restart gitea`; +* проверка после рестарта, уведомление в ALERT (успех/провал). + +## 2. Лёгкий постоянный монитор пути + +`path_monitor_light.py` — каждые 5 минут, одна строка JSONL: + +``` +{"gw_ms": 0.35, "wg_ms": 48, "vds_ms": 48, + "tcp443": 46, "tcp8444": 50, "tcp8445": 47, "tls443": null} +``` + +* ICMP до VDS/WG фильтруется — проверяем TCP (WG: 10.88.0.1:22, VDS: 443); +* TLS-рукопожатие 443 пишется как факт (в волны `null` — это и есть + диагностика блокировки); +* если публичный VDS недоступен 30 минут, а WG жив — уведомление + «похоже на блокировку адреса» (не поломку сервера). + +Лог: `/var/lib/path-monitor-light/YYYY-MM-DD.jsonl`. Hermes: каждые 5 мин. + +## 3. Проверка восстановления файла из restic + +`restic_restore_file.py` — не `check`, а реальное восстановление: + +* берёт последний снапшот `pve-config`; +* восстанавливает `/etc/pve/storage.cfg` во временный каталог; +* проверяет размер и содержимое, удаляет; +* результат — в ALERT. Hermes: ежедневно 08:40 (дёшево). + +Проверка: `ok: f97afce5 326` байт. + +## Бонус: диск utils-lxc (CT107) + +Алерт «Мало места» (86%). Очищены неиспользуемые docker-образы: +**86% → 79%**, освобождено 156 МБ (остальные слои общие, не мусор). +Алерт закроется после переоценки правила (порог 85%). + +## Проверка + +``` +Prometheus: алертов по n8n нет +Kuma: монитор n8n на паузе +Hermes: gitea-selfheal, path-monitor-light, restic-restore-file активны +path-light: gw 0.35 мс, WG 48 мс, VDS TCP 46 мс +restic: восстановление файла ok +CT107: 79% (было 86%) +``` diff --git a/ops/automations/registry.yaml b/ops/automations/registry.yaml index 644c8ca..828aeb2 100644 --- a/ops/automations/registry.yaml +++ b/ops/automations/registry.yaml @@ -1,10 +1,10 @@ # Реестр автоматизаций Buryans Hub -# Сгенерировано: 2026-11-17 10:16 (ops/scripts/build_automations_registry.py) -total: 165 +# Сгенерировано: 2026-11-17 11:02 (ops/scripts/build_automations_registry.py) +total: 168 by_source: cron.d: 49 crontab: 15 - hermes: 58 + hermes: 61 systemd: 43 items: - {"source": "crontab", "line": "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"} @@ -172,3 +172,6 @@ items: - {"source": "hermes", "job": "cf-tunnel-sync", "schedule": "every 300s", "command": "/usr/bin/python3 /root/buryan-infra/ops/scripts/cf_tunnel_sync.py"} - {"source": "hermes", "job": "pg-conn-monitor", "schedule": "every 300s", "command": "/usr/bin/python3 /root/buryan-infra/ops/scripts/pg_conn_monitor.py"} - {"source": "hermes", "job": "ollama-guard", "schedule": "every 1800s", "command": "/usr/bin/python3 /root/buryan-infra/ops/scripts/ollama_guard.py"} +- {"source": "hermes", "job": "restic-restore-file", "schedule": "daily 08:40", "command": "/usr/bin/python3 /root/buryan-infra/ops/scripts/restic_restore_file.py"} +- {"source": "hermes", "job": "gitea-selfheal", "schedule": "every 300s", "command": "/usr/bin/python3 /root/buryan-infra/ops/scripts/gitea_selfheal.py"} +- {"source": "hermes", "job": "path-monitor-light", "schedule": "every 300s", "command": "/usr/bin/python3 /root/buryan-infra/ops/scripts/path_monitor_light.py"} diff --git a/ops/scripts/gitea_selfheal.py b/ops/scripts/gitea_selfheal.py new file mode 100755 index 0000000..1b65f40 --- /dev/null +++ b/ops/scripts/gitea_selfheal.py @@ -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()) diff --git a/ops/scripts/path_monitor_light.py b/ops/scripts/path_monitor_light.py new file mode 100755 index 0000000..da1ddca --- /dev/null +++ b/ops/scripts/path_monitor_light.py @@ -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()) diff --git a/ops/scripts/restic_restore_file.py b/ops/scripts/restic_restore_file.py new file mode 100755 index 0000000..9bdb3be --- /dev/null +++ b/ops/scripts/restic_restore_file.py @@ -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()) diff --git a/ops/update-manager/services.yaml b/ops/update-manager/services.yaml index e10d4dc..d3c069b 100644 --- a/ops/update-manager/services.yaml +++ b/ops/update-manager/services.yaml @@ -46,17 +46,6 @@ services: backup: snapshot container: matrix-synapse image: matrixdotorg/synapse:latest - n8n: - ct_id: 108 - compose_path: /opt/ct108 - healthcheck: - url: http://192.168.1.108:5680/healthz - timeout: 15 - retries: 3 - critical: true - backup: snapshot - container: n8n - image: n8nio/n8n:latest prometheus: ct_id: 134 compose_path: /opt/prometheus