ros_control: централизованное управление парком MikroTik RouterOS

Control Server (FastAPI) с WEB UI (Jinja2 + HTMX) и JSON API для группового
администрирования устройств RouterOS 7 через REST.

- Устройства: список, статус (модель, канал, версии ROS/FW, uptime, доступные
  обновления), примечания, пароли шифруются (Fernet); фоновый опрос каждые 30 с
  и быстрое обнаружение недоступности (таймаут соединения 4 с).
- Группы устройств и фильтры (устройства, резервные копии).
- Резервные копии: .backup и .rsc (show-sensitive) создаются через REST,
  скачиваются сервером и загружаются в S3 (Yandex Object Storage).
- Обновление ROS/FW и выбор канала, групповые операции задачами.
- Интерфейс по утверждённому макету: светлая/тёмная темы, окна, шрифты IBM Plex
  локально. Docker Compose, SQLite в томе, минимальный набор тестов.
- Планы и итоги каждого изменения — в docs/changes/.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
ayurishchevandClaude Sonnet 5 committed 2026-09-19 13:13:29 +03:00
commit 4c1841b61b
85 files changed
+3579

No files matched your search

View File
Whitespace-only changes.
+49
View File
@@ -0,0 +1,49 @@
"""Список бэкапов из бакета с фильтрами (устройство, группа, тип, даты, текст)."""
from datetime import date
from app import s3
from app.services import devices, groups
def _kind(key: str) -> str:
return "backup" if key.endswith(".backup") else "rsc" if key.endswith(".rsc") else "other"
async def search(device: str = "", group: str = "", kind: str = "", date_from: date | None = None,
date_to: date | None = None, q: str = "") -> tuple[list[dict], dict]:
"""Отфильтрованные бэкапы и итоги по всему бакету ({"total": N, "size": байты}).
Ключи вида backups/<устройство>/<файл>: устройство берётся из ключа, группа — по имени устройства.
group: "" — все, "none" — без группы (в т.ч. бэкапы удалённых устройств), иначе id группы.
Даты — по времени изменения объекта (UTC), включительно."""
group_names = {g["id"]: g["name"] for g in groups.list_groups()}
device_group = {d.name: group_names.get(d.group_id) for d in devices.list_devices()}
want_group = group_names.get(int(group)) if group.isdigit() else None
everything = await s3.list_backups(None)
stats = {"total": len(everything), "size": sum(i["size"] for i in everything)}
q = q.strip().lower()
out = []
for item in everything:
parts = item["key"].split("/")
name = parts[1] if len(parts) >= 3 else ""
item = {**item, "device": name, "group": device_group.get(name), "kind": _kind(item["key"])}
if device and name != device:
continue
if group == "none" and item["group"] is not None:
continue
if group.isdigit() and (want_group is None or item["group"] != want_group):
continue
if kind and item["kind"] != kind:
continue
day = item["last_modified"].date()
if (date_from and day < date_from) or (date_to and day > date_to):
continue
if q and q not in item["key"].lower():
continue
out.append(item)
return out, stats
async def list_backups(device: str = "", group: str = "", kind: str = "", date_from: date | None = None,
date_to: date | None = None, q: str = "") -> list[dict]:
return (await search(device, group, kind, date_from, date_to, q))[0]
+168
View File
@@ -0,0 +1,168 @@
import re
from dataclasses import dataclass
from app import security
from app.config import get_settings
from app.db import session_scope
from app.models import Device, Group
from app.ros.client import RosClient
NAME_RE = re.compile(r"^[A-Za-z0-9._-]{1,64}$") # имя попадает в ключи S3 — только безопасные символы
@dataclass
class Conn:
id: int
name: str
host: str
port: int
username: str
password: str
verify_tls: bool
use_tls: bool
def validate_name(name: str) -> None:
if not NAME_RE.match(name):
raise ValueError("Имя: латиница, цифры, '.', '_', '-' (до 64 символов)")
def list_devices() -> list[Device]:
with session_scope() as s:
return list(s.query(Device).order_by(Device.name))
def get_device(device_id: int) -> Device:
with session_scope() as s:
d = s.get(Device, device_id)
if d is None:
raise LookupError(f"Устройство {device_id} не найдено")
return d
def _check_group(s, group_id: int | None) -> None:
if group_id is not None and s.get(Group, group_id) is None:
raise LookupError(f"Группа {group_id} не найдена")
NOTE_MAX = 500
def _clean_note(note: str | None) -> str | None:
note = (note or "").strip()
if len(note) > NOTE_MAX:
raise ValueError(f"Примечание: не более {NOTE_MAX} символов")
return note or None
def _resolve_group(s, group_id: int | None, new_group: str | None) -> int | None:
"""Группа устройства. new_group создаёт группу (или берёт существующую с таким именем)
в той же транзакции, что и устройство: при ошибке не остаётся лишней группы."""
name = (new_group or "").strip()
if name:
if len(name) > 64:
raise ValueError("Название группы: от 1 до 64 символов")
g = s.query(Group).filter_by(name=name).first()
if g is None:
g = Group(name=name)
s.add(g)
s.flush()
return g.id
_check_group(s, group_id)
return group_id
def create_device(name, host, port, username, password, verify_tls=False, use_tls=True,
group_id: int | None = None, new_group: str | None = None, note: str | None = None) -> Device:
validate_name(name)
note = _clean_note(note)
with session_scope() as s:
group_id = _resolve_group(s, group_id, new_group)
if s.query(Device).filter_by(name=name).first():
raise ValueError(f"Устройство с именем {name} уже существует")
d = Device(name=name, host=host, port=port, username=username,
password_enc=security.encrypt(password), verify_tls=verify_tls, use_tls=use_tls,
group_id=group_id, note=note)
s.add(d)
s.flush()
return d
def update_device(device_id: int, **fields) -> Device:
with session_scope() as s:
d = s.get(Device, device_id)
if d is None:
raise LookupError(f"Устройство {device_id} не найдено")
if fields.get("name") and fields["name"] != d.name:
validate_name(fields["name"])
d.name = fields["name"]
for k in ("host", "port", "username", "verify_tls", "use_tls"):
if fields.get(k) is not None:
setattr(d, k, fields[k])
if "group_id" in fields or fields.get("new_group"): # group_id=None — открепить от группы
d.group_id = _resolve_group(s, fields.get("group_id"), fields.get("new_group"))
if "note" in fields: # пустое примечание — очистить
d.note = _clean_note(fields["note"])
if fields.get("password"): # пустой пароль = не менять
d.password_enc = security.encrypt(fields["password"])
return d
def delete_device(device_id: int) -> None:
with session_scope() as s:
d = s.get(Device, device_id)
if d is None:
raise LookupError(f"Устройство {device_id} не найдено")
s.delete(d)
def get_conn(device_id: int) -> Conn:
d = get_device(device_id)
return Conn(d.id, d.name, d.host, d.port, d.username,
security.decrypt(d.password_enc), d.verify_tls, d.use_tls)
def open_client(conn: Conn) -> RosClient:
return RosClient(conn.host, conn.port, conn.username, conn.password,
conn.verify_tls, get_settings().ros_timeout, conn.use_tls,
connect_timeout=get_settings().ros_connect_timeout)
def has_ros_update(st: dict) -> bool:
return bool(st.get("ros_latest") and st.get("ros_installed") and st["ros_latest"] != st["ros_installed"])
def has_fw_update(st: dict) -> bool:
return bool(st.get("fw_current") and st.get("fw_upgrade") and st["fw_upgrade"] != st["fw_current"])
def filter_devices(devs: list[Device], group: str = "", q: str = "", status: str = "",
updates: str = "", channel: str = "") -> list[Device]:
"""Общий фильтр списка устройств для UI и API (по кэшу статуса).
group: "" — все, "none" — без группы, иначе id группы. status: online/offline.
updates: ros / fw / any (есть обновление) / none (обновлений нет).
"""
q = q.strip().lower()
out = []
for d in devs:
st = d.status
if group == "none" and d.group_id is not None:
continue
if group not in ("", "none") and str(d.group_id) != group:
continue
if q and q not in " ".join((d.name, d.host, st.get("model") or "")).lower():
continue
if status == "online" and d.online is not True:
continue
if status == "offline" and d.online is True:
continue
ros_new, fw_new = has_ros_update(st), has_fw_update(st)
if (updates == "ros" and not ros_new) or (updates == "fw" and not fw_new):
continue
if (updates == "any" and not (ros_new or fw_new)) or (updates == "none" and (ros_new or fw_new)):
continue
if channel and st.get("channel") != channel:
continue
out.append(d)
return out
+68
View File
@@ -0,0 +1,68 @@
from sqlalchemy import func, update
from app.db import session_scope
from app.models import Device, Group
def _clean(name: str) -> str:
name = (name or "").strip()
if not name or len(name) > 64:
raise ValueError("Название группы: от 1 до 64 символов")
return name
def list_groups() -> list[dict]:
"""Группы с числом устройств, по алфавиту."""
with session_scope() as s:
counts = dict(s.query(Device.group_id, func.count(Device.id)).group_by(Device.group_id))
return [{"id": g.id, "name": g.name, "device_count": counts.get(g.id, 0)}
for g in s.query(Group).order_by(Group.name)]
def get_group(group_id: int) -> Group:
with session_scope() as s:
g = s.get(Group, group_id)
if g is None:
raise LookupError(f"Группа {group_id} не найдена")
return g
def create_group(name: str) -> Group:
name = _clean(name)
with session_scope() as s:
if s.query(Group).filter_by(name=name).first():
raise ValueError(f"Группа «{name}» уже существует")
g = Group(name=name)
s.add(g)
s.flush()
return g
def rename_group(group_id: int, name: str) -> Group:
name = _clean(name)
with session_scope() as s:
g = s.get(Group, group_id)
if g is None:
raise LookupError(f"Группа {group_id} не найдена")
if s.query(Group).filter(Group.name == name, Group.id != group_id).first():
raise ValueError(f"Группа «{name}» уже существует")
g.name = name
return g
def delete_group(group_id: int) -> None:
"""Удаляет группу; устройства остаются и становятся «Без группы» (FK в SQLite не включены)."""
with session_scope() as s:
g = s.get(Group, group_id)
if g is None:
raise LookupError(f"Группа {group_id} не найдена")
s.execute(update(Device).where(Device.group_id == group_id).values(group_id=None))
s.delete(g)
def move_devices(device_ids: list[int], group_id: int | None) -> None:
"""Переносит устройства в группу (None — «Без группы»)."""
with session_scope() as s:
if group_id is not None and s.get(Group, group_id) is None:
raise LookupError(f"Группа {group_id} не найдена")
s.execute(update(Device).where(Device.id.in_(device_ids)).values(group_id=group_id))
+81
View File
@@ -0,0 +1,81 @@
"""Фоновые задачи: запись в таблицу jobs, параллелизм ограничен MAX_CONCURRENCY."""
import asyncio
from app.config import get_settings
from app.db import session_scope
from app.models import Device, Job, now
from app.services import ops
JOB_TYPES = {
"backup": ops.run_backup,
"ros_update": ops.run_ros_update,
"fw_update": ops.run_fw_update,
}
_tasks: set[asyncio.Task] = set()
_sem: asyncio.Semaphore | None = None
def _semaphore() -> asyncio.Semaphore:
global _sem
if _sem is None:
_sem = asyncio.Semaphore(get_settings().max_concurrency)
return _sem
def _finish(job_id: int, status: str, message: str) -> None:
with session_scope() as s:
j = s.get(Job, job_id)
j.status, j.message = status, message
if status in ("done", "failed"):
j.finished_at = now()
async def _run(job_id: int, job_type: str, device_id: int) -> None:
async with _semaphore():
_finish(job_id, "running", "")
try:
_finish(job_id, "done", await JOB_TYPES[job_type](device_id))
except Exception as e: # noqa: BLE001 — любой сбой фиксируем в задаче
_finish(job_id, "failed", str(e))
def start_jobs(job_type: str, device_ids: list[int]) -> list[int]:
"""Создаёт задачи для списка устройств и запускает их в фоне. Возвращает id задач."""
if job_type not in JOB_TYPES:
raise ValueError(f"Неизвестный тип задачи: {job_type}")
job_ids = []
with session_scope() as s:
for did in device_ids:
d = s.get(Device, did)
if d is None:
raise LookupError(f"Устройство {did} не найдено")
j = Job(device_id=did, device_name=d.name, type=job_type)
s.add(j)
s.flush()
job_ids.append((j.id, did))
for jid, did in job_ids:
task = asyncio.create_task(_run(jid, job_type, did))
_tasks.add(task)
task.add_done_callback(_tasks.discard)
return [jid for jid, _ in job_ids]
def list_jobs(limit: int = 50) -> list[Job]:
with session_scope() as s:
return list(s.query(Job).order_by(Job.id.desc()).limit(limit))
def get_job(job_id: int) -> Job:
with session_scope() as s:
j = s.get(Job, job_id)
if j is None:
raise LookupError(f"Задача {job_id} не найдена")
return j
def fail_stale_jobs() -> None:
"""После перезапуска сервера незавершённые задачи помечаются как прерванные."""
with session_scope() as s:
for j in s.query(Job).filter(Job.status.in_(("pending", "running"))):
j.status, j.message, j.finished_at = "failed", "Прервано перезапуском сервера", now()
+124
View File
@@ -0,0 +1,124 @@
"""Оркестрация операций: RouterOS + S3 + БД."""
import asyncio
import json
import tempfile
from datetime import datetime, timezone
from pathlib import Path
from app import s3
from app.config import get_settings
from app.db import session_scope
from app.models import Backup, Device, now
from app.ros import operations as ros
from app.ros.client import RosError
from app.services import devices
def _save_status(device_id: int, fields: dict) -> None:
with session_scope() as s:
d = s.get(Device, device_id)
if d is not None: # устройство могли удалить во время опроса
for k, v in fields.items():
setattr(d, k, v)
d.status_at = now()
async def refresh_status(device_id: int) -> None:
"""Полный опрос: статус, версии и проверка обновлений. Недоступность — не исключение."""
conn = devices.get_conn(device_id)
try:
async with devices.open_client(conn) as c:
status = await ros.get_status(c)
fields = dict(online=True, status_json=json.dumps(status), last_error=None)
except RosError as e:
fields = dict(online=False, last_error=str(e))
_save_status(device_id, fields)
async def poll_device(device_id: int, full: bool = False) -> None:
"""Фоновый опрос. Лёгкий (один запрос system/resource) обновляет online, uptime и версию ROS;
полный — если нужна проверка обновлений (full) либо устройство было недоступно/ещё не опрошено
(после возвращения версии могли измениться)."""
d = devices.get_device(device_id)
if full or d.online is not True or not d.status:
return await refresh_status(device_id)
try:
async with devices.open_client(devices.get_conn(device_id)) as c:
res = await c.get("system/resource")
except RosError as e:
return _save_status(device_id, dict(online=False, last_error=str(e)))
status = {**d.status, "uptime": res.get("uptime"), "ros_version": res.get("version")}
_save_status(device_id, dict(online=True, status_json=json.dumps(status), last_error=None))
async def refresh_many(device_ids: list[int] | None = None) -> None:
ids = device_ids if device_ids is not None else [d.id for d in devices.list_devices()]
sem = asyncio.Semaphore(get_settings().max_concurrency)
async def one(i: int):
async with sem:
await refresh_status(i)
await asyncio.gather(*(one(i) for i in ids))
async def run_backup(device_id: int) -> str:
"""Бэкап .backup + .rsc: создать на устройстве → скачать через REST во временную папку →
загрузить в S3 от имени сервера → удалить файлы с устройства."""
conn = devices.get_conn(device_id)
stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
base = f"ros_control-{stamp}"
files = { # имя на устройстве -> ключ в S3
f"{base}.backup": f"{s3.device_prefix(conn.name)}{stamp}.backup",
f"{base}.rsc": f"{s3.device_prefix(conn.name)}{stamp}.rsc",
}
key_bin, key_rsc = files[f"{base}.backup"], files[f"{base}.rsc"]
with session_scope() as s:
b = Backup(device_id=device_id, key_binary=key_bin, key_rsc=key_rsc)
s.add(b)
s.get(Device, device_id).last_backup_requested_at = b.requested_at = now()
s.flush()
backup_id = b.id
status, error = "failed", "прервано"
try:
with tempfile.TemporaryDirectory(prefix="ros_control-") as tmp:
async with devices.open_client(conn) as c:
try:
await ros.create_backup_files(c, base)
for name, key in files.items():
local = Path(tmp) / name
await ros.download_file(c, name, local)
await s3.upload_file(local, key)
finally:
for name in files: # на устройстве файлы не остаются ни при успехе, ни при сбое
try:
await ros.remove_file(c, name)
except RosError:
pass
status, error = "done", None
except Exception as e:
error = str(e)
raise
finally:
with session_scope() as s:
b = s.get(Backup, backup_id)
b.status, b.error = status, error
return f"Бэкап загружен в S3: {key_bin}, {key_rsc}"
async def set_channel(device_id: int, channel: str) -> None:
async with devices.open_client(devices.get_conn(device_id)) as c:
await ros.set_channel(c, channel)
await refresh_status(device_id)
async def run_ros_update(device_id: int) -> str:
async with devices.open_client(devices.get_conn(device_id)) as c:
return await ros.install_ros_update(c)
async def run_fw_update(device_id: int) -> str:
async with devices.open_client(devices.get_conn(device_id)) as c:
return await ros.upgrade_firmware(c)
+45
View File
@@ -0,0 +1,45 @@
"""Фоновый опрос устройств: быстрое обнаружение недоступности (period = POLL_INTERVAL)."""
import asyncio
import logging
import time
from app.config import get_settings
from app.services import devices, ops
log = logging.getLogger("ros_control.poller")
async def cycle(last_full: dict[int, float]) -> None:
"""Один проход по всем устройствам (параллельно, не более MAX_CONCURRENCY одновременно)."""
s = get_settings()
ids = [d.id for d in devices.list_devices()]
for gone in set(last_full) - set(ids):
del last_full[gone]
sem = asyncio.Semaphore(s.max_concurrency)
started = time.monotonic()
async def one(device_id: int) -> None:
async with sem:
full = started - last_full.get(device_id, float("-inf")) >= s.update_check_interval
try:
await ops.poll_device(device_id, full)
except LookupError: # удалили во время цикла
return
except Exception: # noqa: BLE001 — сбой одного устройства не должен ронять опрос остальных
log.exception("poll failed: device %s", device_id)
return
if full:
last_full[device_id] = time.monotonic()
await asyncio.gather(*(one(i) for i in ids))
async def run() -> None:
last_full: dict[int, float] = {}
interval = get_settings().poll_interval
while True:
try:
await cycle(last_full)
except Exception: # noqa: BLE001
log.exception("poll cycle failed")
await asyncio.sleep(interval)