Files

289 lines
12 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Фаза 3: ночной разбор журналов по сигнатурам.
Не «ещё один хвост ошибок», а детектор НОВОГО:
1. собирает warning/err за сутки и нормализует строки в сигнатуры
(ID, числа, пути, IP → плейсхолдеры);
2. сравнивает с базой за последние 7 дней;
3. находит новые сигнатуры, всплески (рост в разы) и корреляции
(разные службы в одном 5-минутном окне);
4. локальная модель пишет короткий дайджест с гипотезами;
5. при находках — уведомление в ALERT, иначе только файл.
Хранение: /var/lib/log-signatures/YYYY-MM-DD.json
Отчёт: /var/log/hub/log-digest-YYYY-MM-DD.md
Запуск:
python3 log_signatures.py # собрать за сутки, файл
python3 log_signatures.py --notify # + уведомление при находках
python3 log_signatures.py --days 7 # собрать базу за 7 дней (бэкфилл)
"""
import json
import os
import re
import subprocess
import sys
from datetime import date, datetime, timedelta
sys.path.insert(0, "/opt/hub-core")
STORE = "/var/lib/log-signatures"
OUTDIR = "/var/log/hub"
KEEP_DAYS = 14
NOISE = (
"read-only file system", "name resolution", "openipmi", "postfix",
"nfsdcld", "wtmpdb", "grub-common", "org.gnome", "avahi", "bluetooth",
"pam_unix", "session opened", "session closed",
"write access unavailable, skipping orphan cleanup",
"does not support file handles, falling back to xino=off",
)
def sh(cmd, timeout=120):
try:
r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout)
return (r.stdout or "")
except Exception:
return ""
def norm(line):
"""Нормализует строку журнала в устойчивую сигнатуру."""
s = line
# префикс journald: "Nov 16 13:00:01 pve unit[123]: "
s = re.sub(r"^[A-Z][a-z]{2}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\S+\s+", "", s)
s = re.sub(r"\b[0-9a-fA-F]{8,}\b", "<hex>", s)
s = re.sub(r"\b\d{1,3}(?:\.\d{1,3}){3}\b", "<ip>", s)
s = re.sub(r"\[\d+\]", "[pid]", s)
s = re.sub(r"\b\d+(?:\.\d+)?\b", "<n>", s)
s = re.sub(r"/[^\s:'\"]+", "<path>", s)
s = re.sub(r"\s+", " ", s).strip()
return s[:160]
def unit_of(line):
m = re.search(r"\s([A-Za-z0-9_.@-]+)\[\d+\]:", line)
if m:
return m.group(1)
m = re.search(r"\s([A-Za-z0-9_.@-]+\(\d+\)):", line)
if m:
return m.group(1)
m = re.search(r"pve\s+([A-Za-z0-9_.@-]+):", line)
return m.group(1) if m else "?"
def collect(hours=24, limit=8000, since=None, until=None):
if since and until:
cmd = ("journalctl --since '%s 00:00:00' --until '%s 00:00:00' "
"-p warning --no-pager -n %d 2>/dev/null" % (since, until, limit))
else:
cmd = "journalctl --since '-%dh' -p warning --no-pager -n %d 2>/dev/null" % (hours, limit)
raw = sh(cmd, timeout=240)
sigs = {}
for line in raw.splitlines():
low = line.lower()
if any(n in low for n in NOISE):
continue
u = unit_of(line)
s = norm(line)
if len(s) < 8:
continue
rec = sigs.setdefault(s, {"count": 0, "units": {}, "sample": line.strip()[:240]})
rec["count"] += 1
rec["units"][u] = rec["units"].get(u, 0) + 1
return sigs
def store_day(day, sigs):
os.makedirs(STORE, exist_ok=True)
path = os.path.join(STORE, day + ".json")
json.dump(sigs, open(path, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
return path
def load_days(days=7, before=None):
"""Загружает базу за предыдущие дни (словарь сигнатура → суммарный count)."""
base = {}
before = before or date.today()
for i in range(1, days + 1):
d = (before - timedelta(days=i)).isoformat()
p = os.path.join(STORE, d + ".json")
if not os.path.exists(p):
continue
try:
data = json.load(open(p, encoding="utf-8"))
except Exception:
continue
for sig, rec in data.items():
base[sig] = base.get(sig, 0) + int(rec.get("count") or 0)
return base
def analyze(today_sigs, base):
new = []
spikes = []
for sig, rec in today_sigs.items():
n = int(rec.get("count") or 0)
if sig not in base:
new.append((n, sig, rec))
else:
prev = base[sig] / 7.0 # среднее в день
if n >= 5 and prev > 0 and n >= prev * 3:
spikes.append((n, round(prev, 1), sig, rec))
new.sort(key=lambda x: -x[0])
spikes.sort(key=lambda x: -x[0])
return new[:15], spikes[:10]
def correlations(hours=24, window_min=5):
"""Службы, у которых предупреждения совпали в одном окне."""
raw = sh("journalctl --since '-%dh' -p warning --no-pager -n 4000 2>/dev/null"
% hours, timeout=180)
buckets = {}
for line in raw.splitlines():
m = re.match(r"^[A-Z][a-z]{2}\s+(\d{1,2})\s+(\d{2}):(\d{2}):\d{2}", line)
if not m:
continue
day, hh, mm = int(m.group(1)), int(m.group(2)), int(m.group(3))
key = (day, hh, mm // window_min)
u = unit_of(line)
if u == "?":
continue
buckets.setdefault(key, {}).setdefault(u, 0)
buckets[key][u] += 1
found = []
for key, units in buckets.items():
if len(units) >= 2 and sum(units.values()) >= 3:
found.append((sum(units.values()), key, units))
found.sort(reverse=True)
out = []
for total, key, units in found[:5]:
d, hh, mi = key
out.append({"when": "%02d:%02d-%02d:%02d" % (hh, mi * window_min,
hh, mi * window_min + window_min),
"units": dict(sorted(units.items(), key=lambda x: -x[1])[:5]),
"total": total})
return out
def llm_digest(new, spikes, corr):
"""Короткий дайджест локальной моделью (3b → DeepSeek через фолбэк)."""
if not (new or spikes or corr):
return {}, None
facts = []
for n, sig, rec in new[:5]:
facts.append("НОВАЯ x%d: %s [%s]\n пример: %s"
% (n, sig, ",".join(rec["units"]), rec.get("sample", "")[:200]))
for n, prev, sig, rec in spikes[:4]:
facts.append("ВСПЛЕСК x%d (было ~%.1f): %s [%s]\n пример: %s"
% (n, prev, sig, ",".join(rec["units"]), rec.get("sample", "")[:200]))
for c in corr[:3]:
facts.append("КОРРЕЛЯЦИЯ %s: %s" % (c["when"], ", ".join(c["units"])))
prompt = ("Ниже факты из журнала сервера за сутки. Напиши короткий разбор "
"для владельца: что нового и опасно, что делать. Только по фактам. "
"В headline — конкретика: служба/файловая система + число, без общих слов. "
"Если опасного нет — headline: \"Новых проблем нет\". "
"Если в фактах есть write access unavailable, read-only, I/O error, "
"OOM, segfault — это КРИТИЧНО: в action укажи, что проверить (диск, "
"файловая система, память), не пиши «действий не требуется».\n\n"
+ "\n".join(facts)
+ "\n\nОтветь JSON: {\"headline\":\"...\",\"items\":[{\"what\":\"...\","
"\"action\":\"...\",\"severity\":\"critical|high|normal|low\"}]}")
try:
from llm_fallback import ask
r = ask(prompt, max_tokens=250, temperature=0.2,
chain=[{"name": "qwen2.5:3b", "kind": "ollama", "timeout": 60},
{"name": "deepseek-chat", "kind": "deepseek", "timeout": 40}])
txt = (r.get("text") or "").strip()
m = re.search(r"\{.*\}", txt, re.S)
if m:
d = json.loads(m.group(0))
return d, r.get("model")
except Exception:
pass
return {"headline": "Разбор без модели", "items": []}, None
def main():
notify = "--notify" in sys.argv
days = 1
if "--days" in sys.argv:
try:
days = int(sys.argv[sys.argv.index("--days") + 1])
except Exception:
days = 1
today = date.today().isoformat()
if days > 1:
# бэкфилл: пишем отдельные файлы по дням, сегодня не трогаем
for i in range(1, days + 1):
d = (date.today() - timedelta(days=i)).isoformat()
dn = (date.today() - timedelta(days=i - 1)).isoformat()
day_sigs = collect(since=d, until=dn)
store_day(d, day_sigs)
print(" база %s: %d сигнатур" % (d, len(day_sigs)))
sigs = collect(hours=24)
store_day(today, sigs)
print("сегодня: %d сигнатур" % len(sigs))
else:
sigs = collect(hours=24)
store_day(today, sigs)
print("сигнатур: %d (за сутки)" % len(sigs))
base = load_days(7, before=date.today())
if not base:
# базы ещё нет: это бэкфилл, «нового» пока не бывает
new, spikes = [], []
print("база пуста — сравнение начнётся со следующего запуска")
else:
new, spikes = analyze(sigs, base)
corr = correlations(hours=24 * days)
print("новых: %d | всплесков: %d | корреляций: %d" % (len(new), len(spikes), len(corr)))
digest, model = llm_digest(new, spikes, corr)
os.makedirs(OUTDIR, exist_ok=True)
report = os.path.join(OUTDIR, "log-digest-%s.md" % today)
lines = ["# Ночной разбор журналов — %s" % today, "",
"Сигнатур: %d. База: %d дней." % (len(sigs), 7), ""]
if digest:
lines += ["## Дайджест", "", "**%s**" % digest.get("headline", ""), ""]
for it in digest.get("items") or []:
lines.append("- [%s] %s → %s" % (it.get("severity", "?"),
it.get("what", ""), it.get("action", "")))
lines.append("")
if new:
lines += ["## Новые сигнатуры", ""]
for n, sig, rec in new:
lines.append("- x%d `%s` — `%s`" % (n, sig, ",".join(rec["units"])))
lines.append("")
if spikes:
lines += ["## Всплески", ""]
for n, prev, sig, rec in spikes:
lines.append("- x%d (было ~%.1f/день) `%s`" % (n, prev, sig))
lines.append("")
if corr:
lines += ["## Корреляции", ""]
for c in corr:
lines.append("- %s: %s" % (c["when"],
", ".join("%s×%d" % (k, v) for k, v in c["units"].items())))
lines.append("")
open(report, "w", encoding="utf-8").write("\n".join(lines))
print("отчёт:", report, "| модель:", model)
findings = len(new) + len(spikes)
if notify and findings:
head = (digest or {}).get("headline") or ("Новых сигнатур: %d, всплесков: %d"
% (len(new), len(spikes)))
msg = "🌙 Ночной разбор журналов\n%s\n\nНовых: %d · всплесков: %d · корреляций: %d\nОтчёт: %s" % (
head, len(new), len(spikes), len(corr), report)
rc = subprocess.run(["/usr/bin/python3", "/opt/buryan-hub/scripts/notify.py",
"--priority", "high", "--title", "Ночной разбор журналов", msg],
capture_output=True, text=True, timeout=120)
print("уведомление:", (rc.stdout or rc.stderr).strip()[:120])
elif notify:
print("находок нет — уведомление не отправляю")
if __name__ == "__main__":
main()