Files
buryan-infra/ops/mesh/mesh_watch.py
T
buryan-agent f420e9079b Mesh: найдена причина падений — пересечение DHCP-пула с серверами и плавающий IP узла
Слабый сигнал исключён: бэкхол Кабинета RSSI -53. Настоящая причина:
1) DHCP-пул главного был 192.168.1.33-152, а серверы занимают 101-161 —
   клиенты и узлы могли получить занятый адрес (например .108 с n8n);
2) у узла Кабинет не было статического резерва, его IP плавал (.108, .185, .3),
   из-за чего он «пропадал» для мониторинга и клиентов;
3) на главном было включено автообновление компонентов — оба узла имели
   одинаковый uptime, то есть перезагружались вместе.

Исправлено: пул сужен до .170-.250, добавлен резерв 50:ff:20:ed:de:23 → .3
(через CLI, RCI не умеет), автообновление выключено, каналы закреплены
(1 и 11 по 20 МГц, 5 ГГц 36/80). Сторож mesh_watch ищет узлы по MAC через
контроллер, уведомляет в Matrix и сам применяет настройки.
2026-10-21 10:39:42 +03:00

131 lines
4.6 KiB
Python

"""Сторож mesh: находит узлы по MAC через контроллер, чинит настройки, уведомляет."""
import json
import os
import subprocess
import sys
import time
import urllib.request
sys.path.insert(0, "/opt/hub-core")
from keenetic_client import Keenetic # noqa: E402
STATE = "/var/lib/hub-mesh/state.json"
NOTIFY = "http://127.0.0.1:9120/notify"
CONTROLLER = "http://192.168.1.1"
PASSWORD = "73145146"
THRESHOLD = 2
NODES = {
"50:ff:20:ed:de:23": {"name": "Кабинет", "expected": "192.168.1.3"},
"d4:9c:53:25:cb:2e": {"name": "Родители", "expected": "192.168.1.63"},
}
def ping(ip):
r = subprocess.run(["ping", "-c", "2", "-W", "2", ip],
capture_output=True, text=True, timeout=15)
return r.returncode == 0
def notify(title, message):
body = json.dumps({"title": title, "message": message}).encode()
req = urllib.request.Request(NOTIFY, data=body, method="POST",
headers={"Content-Type": "application/json"})
try:
urllib.request.urlopen(req, timeout=15).read()
except Exception as e:
print("notify error:", e, flush=True)
def load():
try:
return json.load(open(STATE, encoding="utf-8"))
except Exception:
return {}
def save(state):
os.makedirs(os.path.dirname(STATE), exist_ok=True)
json.dump(state, open(STATE, "w", encoding="utf-8"))
def resolve(controller, mac):
hosts = controller.rci("/rci/show/ip/hotspot/host")
for h in hosts if isinstance(hosts, list) else []:
if str(h.get("mac", "")).lower() == mac.lower():
ip = h.get("ip")
if ip and ip != "0.0.0.0":
return ip, bool(h.get("active"))
return None, False
def fix_node(ip, expected):
k = Keenetic(f"http://{ip}", "admin", PASSWORD)
ok, _ = k.auth()
if not ok:
return "нет доступа"
acts = []
if ip != expected:
acts.append(f"IP {ip} (ожидался {expected})")
ch = k.rci("/rci/show/interface/WifiMaster0")
if ch.get("channel") not in (1, 6, 11):
k._req("POST", "/rci/", [{"interface": {"WifiMaster0": {"channel": 11}}}])
acts.append("канал 2,4 → 11")
if str(ch.get("bandwidth")) != "20":
k._req("POST", "/rci/", [{"interface": {"WifiMaster0": {"channel": {"width": 20}}}}])
acts.append("ширина 2,4 → 20")
st, hd, raw = k._req("GET", "/rci/show/running-config")
if "auto-update no disable" in raw.decode("utf-8", "replace"):
k._req("POST", "/rci/", [{"components": {"auto-update": {"disable": {}}}}])
acts.append("автообновление выкл")
if acts and any(a.startswith(("канал", "ширина", "авто")) for a in acts):
k._req("POST", "/rci/", [{"system": {"configuration": {"save": {}}}}])
return ", ".join(acts) or "ок"
def main():
state = load()
now = time.time()
ctrl = Keenetic(CONTROLLER, "admin", PASSWORD)
ok, _ = ctrl.auth()
for mac, meta in NODES.items():
st = state.setdefault(mac, {"down": 0, "notified": False, "fixed": False})
name = meta["name"]
expected = meta["expected"]
ip, active = (resolve(ctrl, mac) if ok else (None, False))
target = ip or expected
alive = ping(target) if target else False
if not alive and ip and ip != expected:
alive = ping(expected)
if alive:
if st.get("notified"):
mins = int((now - st.get("down_since", now)) / 60)
notify(f"Mesh: {name} снова в сети",
f"Узел {target} отвечает. Падение длилось около {mins} мин.")
st["notified"] = False
st["down"] = 0
result = fix_node(target, expected)
if result not in ("нет доступа", "ок"):
notify(f"Mesh: {name} настроен", f"Применил: {result}")
st["fixed"] = True
else:
st["down"] = st.get("down", 0) + 1
if st["down"] == THRESHOLD and not st.get("notified"):
st["down_since"] = now
st["notified"] = True
hint = "Проверьте питание и расстояние до главного роутера."
notify(f"Mesh: {name} не отвечает",
f"Узел {expected} недоступен {THRESHOLD} проверки подряд. {hint}")
st["last_ip"] = target
state[mac] = st
save(state)
print(json.dumps(state, ensure_ascii=False), flush=True)
if __name__ == "__main__":
main()