fix(设备池): 指纹对账纠正 IP 复用导致的身份错位
- reconcile_serial_identity:按物理指纹交换两条记录的名字/指纹,同步分组/任务引用,不删身份 - 实际指纹不在池里只告警,不擅自改名 - 后台对账默认每 300s(DEVICE_FP_AUDIT / _INTERVAL),启动 20s 后开始 - 设备页「指纹对账」+ POST /api/devices/pool/fingerprint_audit - TaskManager.swap_device_serials 同步内存副本,不重启即生效 - 新增 test_device_pool_audit.py;文档 §37/API/DEVELOPMENT 同步
This commit is contained in:
@@ -10,9 +10,12 @@
|
||||
红线:全模块不 connect / 不 kill-server / 不 disconnect,遵守既有技术约束。
|
||||
后台线程(task_manager 等)调用时由本模块自行推 app context,调用方无需关心。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import threading
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
from config import ADB_PATH, USB_ADB_HOST, USB_ADB_PORT
|
||||
from core.adb_helper import _adb, _adb_remote
|
||||
@@ -26,6 +29,8 @@ _app = None
|
||||
# 由 web_server 装配时注册为 TaskManager.sync_device_serial——
|
||||
# 分组/任务的内存副本在 TaskManager 里,只改库不改内存不生效(见 _move_device_row)
|
||||
_move_hook = None
|
||||
# 设备身份互换(指纹对账)后的回调:(serial_a, serial_b) -> None
|
||||
_swap_hook = None
|
||||
|
||||
|
||||
def set_move_hook(fn):
|
||||
@@ -34,6 +39,12 @@ def set_move_hook(fn):
|
||||
_move_hook = fn
|
||||
|
||||
|
||||
def set_swap_hook(fn):
|
||||
"""注册"设备身份互换"回调(web_server 创建完 TaskManager 后调用)。"""
|
||||
global _swap_hook
|
||||
_swap_hook = fn
|
||||
|
||||
|
||||
def init_app(app):
|
||||
"""web_server 启动时调用:绑定 Flask app(供后台线程推 db context),
|
||||
并后台刷新一次设备型号(首次启动/设备更换后型号可能变化)。"""
|
||||
@@ -316,6 +327,154 @@ def relocate_device(old_serial, new_serial, fingerprint=""):
|
||||
return True, name, f"『{name or old_serial}』已迁到 {new_serial},分组/任务引用已同步"
|
||||
|
||||
|
||||
# ================== 指纹对账(IP 被另一台已登记设备复用) ==================
|
||||
def _swap_serial_refs(s1, s2):
|
||||
"""交换分组/任务里的 serial 引用(跟随身份,不跟随地址)。"""
|
||||
from core.models import DeviceGroup, TaskJob
|
||||
for g in DeviceGroup.query.all():
|
||||
serials = g.get_serials()
|
||||
if not isinstance(serials, list):
|
||||
continue
|
||||
if s1 in serials or s2 in serials:
|
||||
g.set_serials([s2 if x == s1 else s1 if x == s2 else x for x in serials])
|
||||
for j in TaskJob.query.all():
|
||||
target = j.get_target()
|
||||
if not isinstance(target, dict):
|
||||
continue
|
||||
if target.get("mode") == "serial" and target.get("serial") in (s1, s2):
|
||||
target["serial"] = s2 if target.get("serial") == s1 else s1
|
||||
j.set_target(target)
|
||||
|
||||
|
||||
def reconcile_serial_identity(serial, physical_fp):
|
||||
"""核对一台设备的"实际指纹"与池中登记,必要时交换两条记录的身份。
|
||||
|
||||
背景:DHCP 重分配 IP 后,一个地址可能被**另一台已在池里的设备**占用。
|
||||
claim_device 只认领"新地址",不会复查"已存在地址背后换了设备",于是
|
||||
名字/分组跟着错。这里按物理指纹把两条记录的名字/指纹(以及分组/任务里的
|
||||
serial 引用)互换,**不删除任何身份**。
|
||||
|
||||
返回 None(无需处理)或 dict:
|
||||
{"type": "swapped", ...} 已交换
|
||||
{"type": "unknown", ...} 实际指纹不在池里 —— 只告警,绝不擅自改名
|
||||
"""
|
||||
serial = (serial or "").strip()
|
||||
physical_fp = (physical_fp or "").strip()
|
||||
if not serial or not physical_fp:
|
||||
return None
|
||||
with _ctx():
|
||||
cur = Device.query.get(serial)
|
||||
if cur is None:
|
||||
return None
|
||||
stored = (cur.fingerprint or "").strip()
|
||||
if physical_fp == stored:
|
||||
return None
|
||||
other = Device.query.filter(Device.fingerprint == physical_fp,
|
||||
Device.serial != serial).first()
|
||||
if other is None:
|
||||
msg = (f"地址 {serial} 的实际指纹 {physical_fp} 不在设备池里"
|
||||
f"(登记的是『{cur.name or serial}』/{stored or '无指纹'});"
|
||||
f"未自动改名,请人工确认")
|
||||
_log.warning("设备指纹对账: " + msg)
|
||||
return {"serial": serial, "type": "unknown", "msg": msg}
|
||||
s2 = other.serial
|
||||
n1, f1 = (cur.name or ""), (cur.fingerprint or "")
|
||||
n2, f2 = (other.name or ""), (other.fingerprint or "")
|
||||
# 三条记录借用临时值,避开 name_uq / fingerprint_uq 唯一索引:
|
||||
# cur → 临时;other → cur 旧身份;cur → other 旧身份
|
||||
tmp = "__fp_swap_" + uuid.uuid4().hex[:8] + "__"
|
||||
cur.name, cur.fingerprint = tmp + "n", tmp + "f"
|
||||
db.session.flush()
|
||||
other.name, other.fingerprint = n1, f1
|
||||
db.session.flush()
|
||||
cur.name, cur.fingerprint = n2, f2
|
||||
db.session.flush()
|
||||
# 分组/任务里的 serial 引用跟着"名字"走(A09/A10 换地址后仍指向各自手机)
|
||||
_swap_serial_refs(serial, s2)
|
||||
db.session.commit()
|
||||
refresh_names()
|
||||
if _swap_hook is not None:
|
||||
try:
|
||||
_swap_hook(serial, s2)
|
||||
except Exception as e:
|
||||
_log.warning(f"设备身份互换后同步分组/任务内存副本失败: {e}")
|
||||
_log.warning(f"设备指纹对账: {serial} 实际是『{n2 or s2}』、"
|
||||
f"{s2} 实际是『{n1 or serial}』→ 已交换身份")
|
||||
return {"serial": serial, "other_serial": s2, "type": "swapped",
|
||||
"name_at_serial": n2, "name_at_other": n1}
|
||||
|
||||
|
||||
def fingerprint_audit(serials=None):
|
||||
"""对在线池设备读取实际指纹并对账。返回有动作/告警的结果列表。
|
||||
|
||||
serials 为空时核对所有在线且带 IP 的池内设备。只读 adb `getprop`,不连接、
|
||||
不断开、不影响正在执行的任务。
|
||||
"""
|
||||
try:
|
||||
online = set(list_online())
|
||||
except Exception:
|
||||
online = set()
|
||||
with _ctx():
|
||||
rows = Device.query.filter_by(enabled=True).all()
|
||||
candidates = [r.serial for r in rows
|
||||
if r.serial in online and ":" in (r.serial or "")]
|
||||
if serials:
|
||||
wanted = set(serials)
|
||||
candidates = [s for s in candidates if s in wanted]
|
||||
out = []
|
||||
for s in candidates:
|
||||
fp = read_fingerprint(s)
|
||||
if not fp:
|
||||
continue
|
||||
try:
|
||||
res = reconcile_serial_identity(s, fp)
|
||||
except Exception as e:
|
||||
_log.warning(f"设备指纹对账 {s} 失败: {e}")
|
||||
res = {"serial": s, "type": "error", "msg": str(e)}
|
||||
if res:
|
||||
out.append(res)
|
||||
return out
|
||||
|
||||
|
||||
_fp_audit_started = False
|
||||
|
||||
|
||||
def start_fingerprint_audit(interval=None):
|
||||
"""后台定时对账(web_server 启动时调用)。
|
||||
|
||||
DEVICE_FP_AUDIT=0 关闭;DEVICE_FP_AUDIT_INTERVAL 调整周期(秒,最小 60)。
|
||||
"""
|
||||
global _fp_audit_started
|
||||
if _fp_audit_started:
|
||||
return False
|
||||
if (os.environ.get("DEVICE_FP_AUDIT", "1") or "1").strip() == "0":
|
||||
_log.info("设备指纹对账已按 DEVICE_FP_AUDIT=0 关闭")
|
||||
return False
|
||||
try:
|
||||
sec = int(interval or os.environ.get("DEVICE_FP_AUDIT_INTERVAL") or 300)
|
||||
except Exception:
|
||||
sec = 300
|
||||
sec = max(60, sec)
|
||||
_fp_audit_started = True
|
||||
threading.Thread(target=_fp_audit_loop, args=(sec,),
|
||||
name="device-fp-audit", daemon=True).start()
|
||||
_log.info(f"设备指纹对账已启动: 每 {sec}s")
|
||||
return True
|
||||
|
||||
|
||||
def _fp_audit_loop(interval):
|
||||
# 启动后先等 20s,避开设备池启动采集
|
||||
time.sleep(20)
|
||||
while True:
|
||||
try:
|
||||
res = fingerprint_audit()
|
||||
if res:
|
||||
_log.warning(f"设备指纹对账本次处理 {len(res)} 条")
|
||||
except Exception as e:
|
||||
_log.debug(f"设备指纹对账周期失败: {e}")
|
||||
time.sleep(interval)
|
||||
|
||||
|
||||
# ================== 管理(CRUD) ==================
|
||||
def add_device(serial, name="", note="", enabled=True, fingerprint=""):
|
||||
"""添加/更新设备(upsert)。返回 True 新增 / False 已存在并更新。"""
|
||||
|
||||
Reference in New Issue
Block a user