Files
buryan-infra/ops/scripts/path_monitor_light.py
T

98 lines
3.3 KiB
Python
Executable File

#!/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())