[VPN] Разбор ночных замеров: 13 сбоев TLS были в окне бэкапов (01:13 и 02:12-02:48) — это I/O-зависание хоста, а не провайдер; исправлено лимитами. После ребута: сбоев до VDS 3, у контрольного microsoft 4 => основное — локальные микро-провалы. Замеры каналов: Reality 8/10 затем 10/10, WS 10/10, TCP 20/20. Поставлен vpn-health.timer (каждые 10 мин: 443/8444/8445/CF, уведомление на смену состояния), CF-туннель закреплён службой cf-tunnel на VDS (адрес eden-processing-hit-latino), QR обновлён. Постоянный CF требует переноса NS на CF
This commit is contained in:
1 parent
e94dd6cc10
commit
b8d8a588b5
4 files changed
+238
-2
No files matched your search
@@ -55,13 +55,13 @@ def tcp(host, port, timeout=5):
|
||||
return {"ok": False, "ms": None, "err": type(e).__name__}
|
||||
|
||||
|
||||
def tls(host, sni, timeout=8):
|
||||
def tls(host, sni, timeout=8, port=443):
|
||||
t0 = time.time()
|
||||
ctx = ssl.create_default_context()
|
||||
ctx.check_hostname = False
|
||||
ctx.verify_mode = ssl.CERT_NONE
|
||||
try:
|
||||
with socket.create_connection((host, 443), timeout=timeout) as raw:
|
||||
with socket.create_connection((host, port), timeout=timeout) as raw:
|
||||
with ctx.wrap_socket(raw, server_hostname=sni) as ss:
|
||||
ver = ss.version()
|
||||
return {"ok": True, "ms": round((time.time() - t0) * 1000, 1), "tls": ver}
|
||||
@@ -96,6 +96,8 @@ def main():
|
||||
# контроль: обычный зарубежный сайт. Если в момент волны он жив,
|
||||
# а наш VDS мёртв — фильтруют конкретно наш адрес.
|
||||
rec["control_tls"] = tls("www.microsoft.com", "www.microsoft.com")
|
||||
# сравнение каналов: WS на 8445 и (если известен) Cloudflare
|
||||
rec["ws_tls"] = tls(VPS, SNI, port=8445)
|
||||
rec["net_tcp"] = tcp("ya.ru", 443)
|
||||
path = os.path.join(OUT, time.strftime("%Y-%m-%d") + ".jsonl")
|
||||
with open(path, "a", encoding="utf-8") as f:
|
||||
|
||||
Executable
+129
@@ -0,0 +1,129 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка каналов доступа: Reality 443, WS 8445, XHTTP 8444, Cloudflare.
|
||||
|
||||
Пишет /var/lib/vpn-health/<дата>.jsonl, при деградации шлёт уведомление
|
||||
в /notify (один раз на переход состояния, без спама).
|
||||
|
||||
Запуск: systemd-таймер каждые 10 минут.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
VDS = "193.233.210.184"
|
||||
SNI = "git.buryans.ru"
|
||||
OUT = "/var/lib/vpn-health"
|
||||
STATE = "/var/lib/vpn-health/last.json"
|
||||
CF_LOG = "/var/log/cf-tunnel.log"
|
||||
|
||||
|
||||
def tls(port, timeout=8):
|
||||
t0 = time.time()
|
||||
ctx = ssl.create_default_context()
|
||||
ctx.check_hostname = False
|
||||
ctx.verify_mode = ssl.CERT_NONE
|
||||
try:
|
||||
with socket.create_connection((VDS, port), timeout=timeout) as raw:
|
||||
with ctx.wrap_socket(raw, server_hostname=SNI) as ss:
|
||||
return {"ok": True, "ms": round((time.time() - t0) * 1000, 1),
|
||||
"tls": ss.version()}
|
||||
except Exception as e:
|
||||
return {"ok": False, "ms": round((time.time() - t0) * 1000, 1),
|
||||
"err": type(e).__name__}
|
||||
|
||||
|
||||
CF_FILE = "/root/buryan-infra/ops/vpn/cf-host.txt"
|
||||
|
||||
|
||||
def cf_host():
|
||||
try:
|
||||
h = open(CF_FILE, encoding="utf-8").read().strip()
|
||||
if h.startswith("https://"):
|
||||
return h
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
for line in reversed(open(CF_LOG, encoding="utf-8", errors="replace").read().splitlines()):
|
||||
if "trycloudflare.com" in line:
|
||||
for tok in line.split():
|
||||
if tok.startswith("https://") and "trycloudflare.com" in tok:
|
||||
return tok.strip()
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def http(url, timeout=12):
|
||||
t0 = time.time()
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return {"ok": True, "ms": round((time.time() - t0) * 1000, 1),
|
||||
"code": r.status}
|
||||
except urllib.error.HTTPError as e:
|
||||
# 404/400 от xray — это норма (ждёт WebSocket), значит канал живой
|
||||
return {"ok": e.code in (400, 404), "ms": round((time.time() - t0) * 1000, 1),
|
||||
"code": e.code}
|
||||
except Exception as e:
|
||||
return {"ok": False, "ms": round((time.time() - t0) * 1000, 1),
|
||||
"err": type(e).__name__}
|
||||
|
||||
|
||||
def notify(title, message):
|
||||
try:
|
||||
body = json.dumps({"title": title, "message": message,
|
||||
"priority": "high"}).encode()
|
||||
req = urllib.request.Request("http://127.0.0.1:9120/notify", data=body,
|
||||
headers={"Content-Type": "application/json"})
|
||||
urllib.request.urlopen(req, timeout=10).read()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def main():
|
||||
rec = {"ts": time.strftime("%Y-%m-%dT%H:%M:%S")}
|
||||
rec["reality443"] = tls(443)
|
||||
rec["ws8445"] = tls(8445)
|
||||
rec["xhttp8444"] = tls(8444)
|
||||
cf = cf_host()
|
||||
rec["cf_host"] = cf
|
||||
rec["cf"] = http(cf + "/") if cf else {"ok": False, "err": "no_host"}
|
||||
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
with open(os.path.join(OUT, time.strftime("%Y-%m-%d") + ".jsonl"), "a",
|
||||
encoding="utf-8") as f:
|
||||
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
||||
|
||||
# состояние: сравниваем с прошлым замером
|
||||
prev = {}
|
||||
try:
|
||||
prev = json.load(open(STATE, encoding="utf-8"))
|
||||
except Exception:
|
||||
pass
|
||||
open(STATE, "w", encoding="utf-8").write(json.dumps(rec, ensure_ascii=False))
|
||||
|
||||
names = {"reality443": "Reality 443", "ws8445": "WS 8445",
|
||||
"xhttp8444": "XHTTP 8444", "cf": "Cloudflare"}
|
||||
dead_now = [names[k] for k in names if not rec[k]["ok"]]
|
||||
dead_prev = [names[k] for k in names if prev.get(k) and not prev[k].get("ok")]
|
||||
|
||||
if dead_now and dead_now != dead_prev:
|
||||
alive = [names[k] for k in names if rec[k]["ok"]]
|
||||
notify("VPN: канал недоступен",
|
||||
"Не работают: %s.\nРаботают: %s.\nПроверьте профиль в клиенте."
|
||||
% (", ".join(dead_now), ", ".join(alive) or "нет"))
|
||||
elif not dead_now and dead_prev:
|
||||
notify("VPN: каналы восстановлены",
|
||||
"Все каналы отвечают: Reality 443, WS 8445, XHTTP 8444, Cloudflare.")
|
||||
|
||||
print(rec["ts"], "ok" if not dead_now else "СБОЙ: " + ",".join(dead_now),
|
||||
"| CF:", cf or "нет")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user