# -*- coding: utf-8 -*- """心跳上报:后台线程周期向中心机上报本机状态,供中心机监控在线/离线并钉钉告警。""" from __future__ import annotations import json import logging import socket import threading import time import urllib.request from fileserver.core import config from fileserver.core import store log = logging.getLogger("fileserver.heartbeat") _START_TS = time.time() def _server_status() -> dict: """收集本服务器状态快照:文件数/占用/主机/IP/运行时长等。""" metas = store.list_files() total = sum(int(m.get("size") or 0) for m in metas) hostname = socket.gethostname() try: ip = socket.gethostbyname(hostname) except OSError: # noqa: BLE001 ip = "" return { "host": config.BASE_URL, # 中心机以其唯一标识本服务器(默认=对外下载根) "base_url": config.BASE_URL, "hostname": hostname, "ip": ip, "port": config.PORT, "file_count": len(metas), "total_size": total, "version": config.VERSION, "uptime_sec": int(time.time() - _START_TS), } def _post_heartbeat() -> bool: """单次上报心跳到中心机;成功返回 True。""" payload = json.dumps(_server_status(), ensure_ascii=False).encode("utf-8") req = urllib.request.Request( f"{config.CONTROLPLANE_URL}/api/fileserver/heartbeat", data=payload, method="POST") req.add_header("Content-Type", "application/json") if config.CONTROLPLANE_TOKEN: req.add_header("X-API-Token", config.CONTROLPLANE_TOKEN) try: with urllib.request.urlopen(req, timeout=10) as resp: return resp.status < 400 except OSError as exc: # noqa: BLE001 网络/中心机异常按失败处理 log.warning("心跳上报失败:%s", exc) return False def _loop() -> None: """周期上报;每次最多重试 3 次(项目级重试约定),三次失败记错误日志;不阻塞文件服务。""" if not config.CONTROLPLANE_URL: log.info("未配置 CONTROLPLANE_URL,跳过心跳上报") return while True: try: ok = False for _i in range(3): if _post_heartbeat(): ok = True break if not ok: log.error("心跳上报连续失败(3 次):%s", config.CONTROLPLANE_URL) except Exception: # noqa: BLE001 log.exception("心跳上报线程异常") time.sleep(max(5, config.HEARTBEAT_INTERVAL)) def start() -> None: """启动心跳上报线程(daemon)。""" threading.Thread(target=_loop, daemon=True, name="fileserver-heartbeat").start()