本次提交包含多项功能更新: 1. 为多个插件(xq0002/0003/0004/0008/0010/0011/0020/0031_xq0032/0033/0035/0037/0045_xq0046/0047/0048)新增 UI 界面及配置支持 2. 新增运行日志集中回传功能,客户端自动上传运行日志到中心机集中存储 3. 新增插件分类字段支持,用于场景库分组管理 4. 优化 xq0034/0037/0048 等插件的功能及描述 5. 修复控制面响应兼容问题,支持新旧版本数据格式 6. 新增 xq0033 插件的状态存储模块,用于历史记录管理 7. 优化 CRM 登录窗口模式,支持全屏置顶
312 lines
15 KiB
Python
312 lines
15 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""中心机集中日志存储:运行日志(run_logs 表)+ 客户端壳日志(logs/shell/<device_id>.log 文件 + device_logs 元数据表)。
|
||
|
||
- 运行日志:客户端每次运行结束后整次回传,按 run_id 幂等 upsert(重复回传/离线补报安全);
|
||
日志正文以 JSON 数组存 MEDIUMTEXT({t, level, msg} 一行一条),列表查询不读该列,详情才解析。
|
||
- 壳日志:客户端增量上传(字节偏移游标),服务端以追加模式落盘 logs/shell/<device_id>.log;
|
||
device_logs 表只存元数据(账号/主机名/版本/累计字节/最近回传),内容按文件管理,避免大文本进库。
|
||
- 保留策略:LOG_RETENTION_DAYS(默认 30 天),启动 + 周期线程清理超期 run_logs 与设备壳日志。
|
||
- 并发说明:gunicorn 多 worker 下增量追加用「O_APPEND 单次 write」保证同设备内容不交错;
|
||
device_logs 元数据 upsert 用原子行更新(size_bytes 为服务端累计值,由本模块维护)。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import logging
|
||
import os
|
||
import re
|
||
import threading
|
||
import time
|
||
from datetime import datetime, timedelta
|
||
|
||
from controlplane.core import config
|
||
from controlplane.core.db import _db, _now
|
||
|
||
_LOGGER = logging.getLogger(__name__)
|
||
|
||
# 路径安全白名单:run_id / device_id 仅允许字母数字 _ -(杜绝目录穿越)
|
||
_RUN_ID_RE = re.compile(r"^[A-Za-z0-9_-]{8,64}$")
|
||
_DEVICE_ID_RE = re.compile(r"^[A-Za-z0-9_-]{4,64}$")
|
||
|
||
# 壳日志管理端展示单次最多读取字节(避免一次性把 10MB 全拉进页面;下载接口给全文)
|
||
SHELL_LOG_VIEW_MAX = 512 * 1024
|
||
# 后台清理周期(秒)
|
||
_CLEANUP_INTERVAL = 6 * 3600
|
||
|
||
|
||
def safe_run_id(run_id: str) -> str:
|
||
s = str(run_id or "")
|
||
return s if _RUN_ID_RE.match(s) else ""
|
||
|
||
|
||
def safe_device_id(device_id: str) -> str:
|
||
s = str(device_id or "")
|
||
return s if _DEVICE_ID_RE.match(s) else ""
|
||
|
||
|
||
def device_log_path(device_id: str) -> str | None:
|
||
"""设备壳日志文件路径;device_id 非法返回 None(调用方不得直接拼路径)。"""
|
||
dev = safe_device_id(device_id)
|
||
if not dev:
|
||
return None
|
||
config.SHELL_LOGS_DIR.mkdir(parents=True, exist_ok=True)
|
||
return str(config.SHELL_LOGS_DIR / f"{dev}.log")
|
||
|
||
|
||
# ==================== 运行日志 ====================
|
||
def store_run_log(payload: dict) -> None:
|
||
"""幂等存入一次运行日志(按 run_id upsert;重复回传只覆盖不重复)。payload 见 RunLogIn。"""
|
||
run_id = safe_run_id(payload.get("run_id", ""))
|
||
if not run_id:
|
||
return
|
||
logs = payload.get("logs") or []
|
||
log_json = json.dumps(logs if isinstance(logs, list) else [],
|
||
ensure_ascii=False)
|
||
with _db() as conn:
|
||
conn.execute(
|
||
"INSERT INTO run_logs(run_id, account, device_id, plugin_id, name, version, trigger_by, "
|
||
"schedule_id, status, ok, error, summary, started, finished, duration_sec, log_count, "
|
||
"logs, uploaded_at) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) "
|
||
"ON DUPLICATE KEY UPDATE "
|
||
"account = VALUES(account), device_id = VALUES(device_id), plugin_id = VALUES(plugin_id), "
|
||
"name = VALUES(name), version = VALUES(version), trigger_by = VALUES(trigger_by), "
|
||
"schedule_id = VALUES(schedule_id), status = VALUES(status), ok = VALUES(ok), "
|
||
"error = VALUES(error), summary = VALUES(summary), started = VALUES(started), "
|
||
"finished = VALUES(finished), duration_sec = VALUES(duration_sec), "
|
||
"log_count = VALUES(log_count), logs = VALUES(logs), uploaded_at = %s",
|
||
(run_id,
|
||
str(payload.get("account") or ""), str(payload.get("device_id") or ""),
|
||
str(payload.get("plugin_id") or ""), str(payload.get("name") or ""),
|
||
str(payload.get("version") or ""), str(payload.get("trigger") or "manual"),
|
||
str(payload.get("schedule_id") or ""), str(payload.get("status") or ""),
|
||
int(bool(payload.get("ok"))), str(payload.get("error") or ""),
|
||
str(payload.get("summary") or ""), int(payload.get("started") or 0),
|
||
int(payload.get("finished") or 0), int(payload.get("duration_sec") or 0),
|
||
int(payload.get("log_count") or len(logs)), log_json, _now(),
|
||
_now()))
|
||
conn.commit()
|
||
|
||
|
||
def _run_where(account: str, device: str, plugin: str, status: str, q: str, days: int) -> tuple[str, list]:
|
||
"""运行日志筛选条件;logs 列不参与 LIKE(大 JSON 慢查询),只搜元信息字段。"""
|
||
where, args = [], []
|
||
if account.strip():
|
||
where.append("account LIKE %s"); args.append(f"%{account.strip()}%")
|
||
if device.strip():
|
||
where.append("device_id LIKE %s"); args.append(f"%{device.strip()}%")
|
||
if plugin.strip():
|
||
where.append("plugin_id LIKE %s"); args.append(f"%{plugin.strip()}%")
|
||
if status.strip():
|
||
vals = [s.strip() for s in status.split(",") if s.strip()]
|
||
if len(vals) == 1:
|
||
where.append("status = %s"); args.append(vals[0])
|
||
elif len(vals) > 1:
|
||
where.append("status IN (%s)" % ", ".join(["%s"] * len(vals)))
|
||
args += vals
|
||
if q.strip():
|
||
where.append("(name LIKE %s OR plugin_id LIKE %s OR account LIKE %s "
|
||
"OR device_id LIKE %s OR error LIKE %s OR summary LIKE %s)")
|
||
args += [f"%{q.strip()}%"] * 6
|
||
if int(days or 0) > 0:
|
||
where.append("uploaded_at >= DATE_SUB(NOW(), INTERVAL %s DAY)")
|
||
args.append(int(days))
|
||
return (" WHERE " + " AND ".join(where)) if where else "", args
|
||
|
||
|
||
_RUN_COLS = ("id, run_id, account, device_id, plugin_id, name, version, trigger_by AS `trigger`, "
|
||
"schedule_id, status, ok, error, summary, started, finished, duration_sec, log_count, uploaded_at")
|
||
|
||
|
||
def query_run_logs(page: int, page_size: int, account: str = "", device: str = "",
|
||
plugin: str = "", status: str = "", q: str = "", days: int = 0) -> dict:
|
||
"""分页查询运行日志(列表不含 logs 正文,避免大列拖慢列表)。"""
|
||
where, args = _run_where(account, device, plugin, status, q, days)
|
||
limit = max(1, min(int(page_size), 1000))
|
||
offset = (max(1, int(page)) - 1) * limit
|
||
with _db() as conn:
|
||
total = conn.execute("SELECT COUNT(*) AS c FROM run_logs" + where, args).fetchone()["c"]
|
||
rows = [dict(r) for r in conn.execute(
|
||
"SELECT " + _RUN_COLS + " FROM run_logs" + where +
|
||
" ORDER BY id DESC LIMIT %s OFFSET %s", args + [limit, offset])]
|
||
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||
"SELECT account, nickname FROM accounts")}
|
||
for r in rows:
|
||
r["nickname"] = nick.get(r["account"], "")
|
||
r["started"] = int(r["started"] or 0)
|
||
r["finished"] = int(r["finished"] or 0)
|
||
r["duration_sec"] = int(r["duration_sec"] or 0)
|
||
r["log_count"] = int(r["log_count"] or 0)
|
||
return {"items": rows, "total": int(total or 0)}
|
||
|
||
|
||
def get_run_log(run_id: str) -> dict | None:
|
||
"""单次运行详情(含日志正文,解析为数组);不存在返回 None。"""
|
||
rid = safe_run_id(run_id)
|
||
if not rid:
|
||
return None
|
||
with _db() as conn:
|
||
row = conn.execute(
|
||
"SELECT " + _RUN_COLS + ", logs FROM run_logs WHERE run_id = %s", (rid,)).fetchone()
|
||
nick = ""
|
||
if row:
|
||
n = conn.execute("SELECT nickname FROM accounts WHERE account = %s",
|
||
(row["account"],)).fetchone()
|
||
nick = n["nickname"] if n else ""
|
||
if not row:
|
||
return None
|
||
d = dict(row)
|
||
d["nickname"] = nick
|
||
try:
|
||
logs = json.loads(d.pop("logs") or "[]")
|
||
d["logs"] = logs if isinstance(logs, list) else []
|
||
except Exception: # noqa: BLE001 损坏的日志列按空处理,不阻断详情
|
||
d["logs"] = []
|
||
return d
|
||
|
||
|
||
# ==================== 客户端壳日志(增量追加到文件) ====================
|
||
def append_shell_log(device_id: str, data: bytes, account: str = "", hostname: str = "",
|
||
client_version: str = "", reset: bool = False) -> dict:
|
||
"""追加一段壳日志到 logs/shell/<device_id>.log 并更新元数据;reset=True 先截断(客户端轮转后重传)。"""
|
||
dev = safe_device_id(device_id)
|
||
if not dev:
|
||
raise ValueError("device_id 非法")
|
||
path = device_log_path(dev)
|
||
if path is None:
|
||
raise ValueError("device_id 非法")
|
||
opened = "wb" if reset else "ab"
|
||
size_delta = 0
|
||
with open(path, opened) as f:
|
||
f.write(data or b"")
|
||
size_delta = len(data or b"")
|
||
with _db() as conn:
|
||
if reset:
|
||
conn.execute(
|
||
"INSERT INTO device_logs(device_id, account, hostname, client_version, "
|
||
"size_bytes, last_uploaded_at) VALUES (%s,%s,%s,%s,%s,%s) "
|
||
"ON DUPLICATE KEY UPDATE account = VALUES(account), "
|
||
"hostname = VALUES(hostname), client_version = VALUES(client_version), "
|
||
"size_bytes = %s, last_uploaded_at = %s",
|
||
(dev, str(account or ""), str(hostname or ""), str(client_version or ""),
|
||
size_delta, _now(), size_delta, _now()))
|
||
else:
|
||
conn.execute(
|
||
"INSERT INTO device_logs(device_id, account, hostname, client_version, "
|
||
"size_bytes, last_uploaded_at) VALUES (%s,%s,%s,%s,%s,%s) "
|
||
"ON DUPLICATE KEY UPDATE account = VALUES(account), "
|
||
"hostname = VALUES(hostname), client_version = VALUES(client_version), "
|
||
"size_bytes = size_bytes + %s, last_uploaded_at = %s",
|
||
(dev, str(account or ""), str(hostname or ""), str(client_version or ""),
|
||
size_delta, _now(), size_delta, _now()))
|
||
conn.commit()
|
||
return {"device_id": dev, "size_bytes": size_delta}
|
||
|
||
|
||
def query_device_logs(page: int, page_size: int, account: str = "", q: str = "") -> dict:
|
||
"""分页查询有壳日志回传的设备列表。"""
|
||
where, args = [], []
|
||
if account.strip():
|
||
where.append("account LIKE %s"); args.append(f"%{account.strip()}%")
|
||
if q.strip():
|
||
where.append("(device_id LIKE %s OR hostname LIKE %s OR account LIKE %s)")
|
||
args += [f"%{q.strip()}%"] * 3
|
||
cond = (" WHERE " + " AND ".join(where)) if where else ""
|
||
limit = max(1, min(int(page_size), 1000))
|
||
offset = (max(1, int(page)) - 1) * limit
|
||
with _db() as conn:
|
||
total = conn.execute("SELECT COUNT(*) AS c FROM device_logs" + cond, args).fetchone()["c"]
|
||
rows = [dict(r) for r in conn.execute(
|
||
"SELECT device_id, account, hostname, client_version, size_bytes, "
|
||
"last_uploaded_at, updated_at FROM device_logs" + cond +
|
||
" ORDER BY updated_at DESC LIMIT %s OFFSET %s", args + [limit, offset])]
|
||
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||
"SELECT account, nickname FROM accounts")}
|
||
for r in rows:
|
||
r["nickname"] = nick.get(r["account"], "")
|
||
r["size_bytes"] = int(r["size_bytes"] or 0)
|
||
return {"items": rows, "total": int(total or 0)}
|
||
|
||
|
||
def get_device_log(device_id: str, view_max: int = SHELL_LOG_VIEW_MAX) -> dict | None:
|
||
"""读取设备壳日志:返回尾部 view_max 字节(UTF-8 容错解码)供页面展示;无记录返回 None。"""
|
||
dev = safe_device_id(device_id)
|
||
if not dev:
|
||
return None
|
||
path = device_log_path(dev)
|
||
with _db() as conn:
|
||
meta = conn.execute(
|
||
"SELECT account, hostname, client_version, size_bytes, last_uploaded_at "
|
||
"FROM device_logs WHERE device_id = %s", (dev,)).fetchone()
|
||
if not meta or not path or not os.path.exists(path):
|
||
return None
|
||
size = int(meta["size_bytes"] or 0)
|
||
with open(path, "rb") as f:
|
||
f.seek(max(0, size - view_max))
|
||
raw = f.read()
|
||
content = raw.decode("utf-8", errors="replace")
|
||
truncated = size > view_max
|
||
return {"device_id": dev, "account": meta["account"] or "",
|
||
"hostname": meta["hostname"] or "", "client_version": meta["client_version"] or "",
|
||
"size_bytes": size, "last_uploaded_at": str(meta["last_uploaded_at"] or ""),
|
||
"content": content, "truncated": truncated}
|
||
|
||
|
||
# ==================== 保留策略清理 ====================
|
||
def cleanup_expired() -> dict:
|
||
"""清理超期日志:run_logs(按 uploaded_at)+ 设备壳日志(按 updated_at,含磁盘文件)。
|
||
|
||
幂等、多 worker 并发安全(条件 DELETE;文件删除前先查库认领,删不到文件仅告警不报错)。
|
||
返回本次清理计数;无 MySQL 配置时静默返回 0(不阻断启动)。
|
||
"""
|
||
result = {"deleted_run_logs": 0, "deleted_device_logs": 0, "skipped": False}
|
||
if not config.MYSQL_HOST:
|
||
result["skipped"] = True
|
||
return result
|
||
cutoff = (datetime.now() - timedelta(days=max(1, int(config.LOG_RETENTION_DAYS)))) \
|
||
.strftime("%Y-%m-%d %H:%M:%S")
|
||
try:
|
||
with _db() as conn:
|
||
cur = conn.execute(
|
||
"DELETE FROM run_logs WHERE uploaded_at < %s", (cutoff,))
|
||
result["deleted_run_logs"] = int(cur.rowcount or 0)
|
||
conn.commit()
|
||
except Exception: # noqa: BLE001 单表清理失败不阻断其余清理
|
||
_LOGGER.exception("运行日志清理失败")
|
||
try:
|
||
with _db() as conn:
|
||
rows = [dict(r) for r in conn.execute(
|
||
"SELECT device_id FROM device_logs WHERE updated_at < %s", (cutoff,))]
|
||
for r in rows:
|
||
dev = r["device_id"]
|
||
conn.execute("DELETE FROM device_logs WHERE device_id = %s AND updated_at < %s",
|
||
(dev, cutoff))
|
||
result["deleted_device_logs"] += 1
|
||
try:
|
||
p = device_log_path(dev)
|
||
if p:
|
||
os.unlink(p)
|
||
except OSError:
|
||
pass
|
||
conn.commit()
|
||
except Exception: # noqa: BLE001
|
||
_LOGGER.exception("设备壳日志清理失败")
|
||
if result["deleted_run_logs"] or result["deleted_device_logs"]:
|
||
_LOGGER.info("集中日志清理完成:run_logs %s 条、设备壳日志 %s 个(保留 %s 天)",
|
||
result["deleted_run_logs"], result["deleted_device_logs"],
|
||
config.LOG_RETENTION_DAYS)
|
||
return result
|
||
|
||
|
||
def _cleanup_loop() -> None:
|
||
while True:
|
||
try:
|
||
cleanup_expired()
|
||
except Exception: # noqa: BLE001 清理异常不退出线程,下轮重试
|
||
_LOGGER.exception("集中日志周期清理异常")
|
||
time.sleep(_CLEANUP_INTERVAL)
|
||
|
||
|
||
def start_log_cleanup() -> None:
|
||
"""启动集中日志后台清理线程(daemon,随进程退出)。"""
|
||
threading.Thread(target=_cleanup_loop, daemon=True, name="log-cleanup").start()
|