Files

105 lines
4.2 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
"""Сторож Ollama: ловит «сервер жив, но генерация висит».
Симптом: /api/tags отвечает быстро, а /api/generate уходит в таймаут —
runner завис. Именно так ломался RAG и LLM-сбор. Раньше это замечали
только по жалобам; теперь будет событие в шине.
"""
import json
import subprocess
import os
import sys
import urllib.request as u
OLLAMA = "http://192.168.1.229:11434"
HUB = "http://127.0.0.1:9120"
GEN_TIMEOUT = 60 # загрузка 3b занимает ~26 с
def get(path, timeout=8):
with u.urlopen(OLLAMA + path, timeout=timeout) as r:
return json.loads(r.read())
def post(path, payload, timeout):
body = json.dumps(payload).encode()
req = u.Request(OLLAMA + path, data=body, headers={"Content-Type": "application/json"})
with u.urlopen(req, timeout=timeout) as r:
return json.loads(r.read())
def notify(text, priority="high"):
# шлюз принимает title/message (поле text он игнорирует → «empty»)
body = json.dumps({"title": "Ollama", "message": text,
"priority": priority}).encode()
req = u.Request(HUB + "/notify", data=body,
headers={"Content-Type": "application/json"})
try:
with u.urlopen(req, timeout=10) as r:
return r.status
except Exception:
return 0
def main():
try:
tags = get("/api/tags")
except Exception as e:
print("Ollama недоступна:", str(e)[:80])
notify("🔴 Ollama (192.168.1.229) не отвечает: %s" % str(e)[:60])
return 1
models = [m.get("name") for m in (tags.get("models") or [])]
try:
post("/api/generate", {"model": "qwen2.5:3b", "prompt": "1",
"stream": False, "keep_alive": "30m",
"options": {"num_predict": 5}},
GEN_TIMEOUT)
try:
open("/var/lib/buryan-checks/ollama-streak", "w").write("0")
except Exception:
pass
print("Ollama в порядке, моделей:", len(models))
return 0
except Exception as e:
# Отличаем «занята нашими воркерами» от настоящего зависания:
# если к Ollama есть соединения от llm_research — это очередь, а не сбой.
busy = 0
try:
out = subprocess.run("ss -tnp 2>/dev/null | grep 11434 | grep -c llm_research",
shell=True, capture_output=True, text=True, timeout=15).stdout
busy = int((out or "0").strip() or 0)
except Exception:
busy = 0
if busy:
print("Ollama занята воркерами (соединений: %d): %s" % (busy, str(e)[:50]))
notify("ℹ️ Ollama (192.168.1.229) занята сбором данных: %d воркеров "
"держат генерацию. RAG временно на текстовом запасе." % busy,
priority="low")
return 0
# 2 подряд: первый «висит» может быть загрузкой модели
state = "/var/lib/buryan-checks/ollama-streak"
streak = 0
try:
streak = int(open(state).read().strip() or 0)
except Exception:
streak = 0
streak += 1
try:
os.makedirs(os.path.dirname(state), exist_ok=True)
open(state, "w").write(str(streak))
except Exception:
pass
print("Ollama не ответила (подряд %d): %s" % (streak, str(e)[:80]))
if streak >= 2:
notify("🔴 Ollama (192.168.1.229): генерация не отвечает две проверки "
"подряд (таймаут %ss). Нужен перезапуск на 229 — от этого "
"зависит RAG и LLM-сбор." % GEN_TIMEOUT)
return 1
print(" (первый сбой, жду подтверждения)")
return 0
if __name__ == "__main__":
sys.exit(main())