sys_tasks.py
12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
"""系统自带任务:连通测试、自检(DMS 登录态 + 只读查询,可选截图)、上传日志文件、收集诊断、版本更新、清理本地日志。"""
import datetime
import json
import logging
import glob
import hashlib
import os
import platform
import shutil
import sys
import zipfile
from .. import __version__, actions
from ..core import updater
from ..core.tasks import task
from ..infra import cleanup, envinfo, logs, netdiag
from ..infra.logs import scrub
log = logging.getLogger("edge")
@task("sys.ping", "连通测试")
def ping(ctx, p):
return {"pong": True, "version": __version__}
@task("sys.check", "自检")
def check(ctx, p):
r = actions.check(ctx.cfg, ctx.sess, p.get("parts") or [], steps=ctx, take_screenshot=p.get("screenshot", True))
bad = [s["step"] for s in r["steps"] if not s["ok"]]
return {"ok": r["ok"], "steps": r["steps"], "message": "全部通过" if r["ok"] else "失败项:" + "、".join(bad)}
NL = chr(10)
TEXT_EXT = (".json", ".jsonl", ".html", ".txt", ".log", ".csv", ".har")
UPLOAD_MAX_RUNS = 80 # 日志包里最多带多少次任务现场(每次动作一个结果目录)
UPLOAD_FILE_LIMIT = 4 * 1024 * 1024 # 单个任务现场文件(截图等二进制)超过这个大小就跳过
UPLOAD_TEXT_LIMIT = 20 * 1024 * 1024 # 文本类(抓包 .har、诊断 json、页面 html)压缩率高,放宽;browser.har 常有 4~5 MB
UPLOAD_TOTAL_LIMIT = 80 * 1024 * 1024 # 日志包里文件原始大小总和上限,超了的文件跳过并写进 MANIFEST.txt
def _day_stamps(days):
return {d.strftime("%Y%m%d") for d in days}
def _run_dirs(cfg, stamps):
"""指定日期的任务结果目录(edge_data/YYYYMMDD/HHMMSS_动作),最新的在前。"""
out = []
for st in stamps:
day = os.path.join(cfg.data_dir, st)
if os.path.isdir(day):
out += [os.path.join(day, d) for d in os.listdir(day) if os.path.isdir(os.path.join(day, d))]
return sorted(out, key=os.path.getmtime, reverse=True)[:UPLOAD_MAX_RUNS]
@task("sys.upload_logs", "上传日志文件")
def upload_logs(ctx, p):
"""把指定日期(默认今天和昨天)的日志打包上传云端:服务 / 菜单 / 网络失败日志、WinSW 启停记录,
以及这些天每次任务的现场(审计时间线 audit.html、截图、ui_blocked / debug 诊断 json、抓包、summary),
外加版本 / 生效配置(密码打码)/ 运行状态 / 上次崩溃记录。只读本机文件,不登录、不发请求。"""
day = p.get("date") or ""
cfg = ctx.cfg
today = datetime.date.today()
try:
days = ([datetime.datetime.strptime(day.replace("-", ""), "%Y%m%d").date()] if day
else [today, today - datetime.timedelta(days=1)])
except ValueError:
return {"ok": False, "message": "日期格式不对:%s(应为 2026-10-29)" % day}
stamps = _day_stamps(days)
log_files = [f for d in days for k in ("edge", "tool", "net") for f in logs.day_files(cfg.log_dir, k, d)]
for f in glob.glob(os.path.join(cfg.log_dir, "service", "*")): # WinSW 的启停 / 崩溃重启记录
if os.path.isfile(f) and (datetime.date.fromtimestamp(os.path.getmtime(f)) in days
or any(st in os.path.basename(f) for st in stamps)):
log_files.append(f)
runs = _run_dirs(cfg, stamps)
if not log_files and not runs:
return {"ok": False, "message": "没有找到日志文件"}
out = os.path.join(cfg.data_dir, "upload_logs_%s.zip" % datetime.datetime.now().strftime("%Y%m%d_%H%M%S"))
os.makedirs(cfg.data_dir, exist_ok=True)
manifest, skipped, total, seen, same = [], [], 0, {}, []
with ctx.step("upload", "打包 %d 个日志文件、%d 次任务现场" % (len(log_files), len(runs)), timeout=300):
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z:
def add(path, arc, limit=None):
nonlocal total
try:
size = os.path.getsize(path)
if (limit and size > limit) or total + size > UPLOAD_TOTAL_LIMIT:
skipped.append("%s(%.1f MB)" % (arc, size / 1048576.0))
return
if size > 100 * 1024: # 大文件内容相同的只存一份(同一次失败会存 3~4 张一样的截图)
with open(path, "rb") as f:
key = (size, hashlib.md5(f.read()).hexdigest())
if key in seen:
same.append("%s = %s" % (arc, seen[key]))
return
seen[key] = arc
if arc.endswith(TEXT_EXT): # 文本文件打包时再脱敏一遍(写入时已脱敏,这里是兜底)
with open(path, "rb") as f:
z.writestr(arc, scrub(f.read().decode("utf-8", "replace")).encode("utf-8"))
else:
z.write(path, arc)
total += size
manifest.append(arc)
except OSError:
pass
for f in log_files:
add(f, "logs/" + os.path.relpath(f, cfg.log_dir).replace("\\", "/"))
for name in ("status.json", "last_crash.txt"):
if os.path.exists(os.path.join(cfg.run_dir, name)):
add(os.path.join(cfg.run_dir, name), "run/" + name)
for r in runs:
rel = os.path.relpath(r, cfg.data_dir).replace("\\", "/")
for f in sorted(os.listdir(r)):
if os.path.isfile(os.path.join(r, f)):
add(os.path.join(r, f), "edge_data/%s/%s" % (rel, f),
UPLOAD_TEXT_LIMIT if f.endswith(TEXT_EXT) else UPLOAD_FILE_LIMIT)
z.writestr("meta/version.json", scrub(json.dumps({
"version": __version__, "packed_at": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"days": sorted(stamps), "python": sys.version, "platform": platform.platform(),
"frozen": bool(getattr(sys, "frozen", False)), "root": cfg.root}, ensure_ascii=False, indent=2)))
z.writestr("meta/config_effective.json",
scrub(json.dumps(effective_config(cfg), ensure_ascii=False, indent=2, default=str)))
z.writestr("MANIFEST.txt", "包含 %d 个文件,%d 次任务现场" % (len(manifest), len(runs)) + NL + NL.join(manifest) +
((NL + "超过大小限制未打包:" + NL + NL.join(skipped)) if skipped else "") +
((NL + "内容与前面某个文件完全相同,没有重复打包(左 = 右):" + NL + NL.join(same)) if same else ""))
eid = ctx.upload(out, "file")
os.remove(out)
return {"ok": True, "files": [os.path.basename(f) for f in log_files], "runs": len(runs), "skipped": skipped,
"message": "日志包已上传(%d 个日志文件、%d 次任务现场%s)" % (
len(log_files), len(runs), ",%d 个大文件未打包" % len(skipped) if skipped else ""),
"evidence": [eid] if eid else []}
@task("sys.update", "更新取数端版本")
def update(ctx, p):
"""下载云端的更新包 → 校验 → 装到 app\\<版本> → 回传结果后重启进程(服务模式自动拉起新版本)。"""
return updater.install(ctx.cc, ctx.cfg.root, str(p["version"]), p.get("sha256") or "", ctx, size=p.get("size"))
@task("sys.restart", "重启取数端")
def restart(ctx, p):
"""回传结果后重启取数端进程(服务模式由 Windows 服务约 10 秒后自动拉起)。登录态已持久化,重启后不用重新登录。
不是以服务运行的(tool.bat 菜单 / 命令行)没人能把进程拉起来,直接拒绝,免得取数端退出后再也上不了线。"""
if not updater.RESTART["auto"]:
return {"ok": False, "auto_restart": False,
"message": "取数端不是以 Windows 服务运行,无法远程重启:请在门店电脑上关闭后重新打开取数端"}
updater.RESTART["pending"] = True
return {"ok": True, "auto_restart": True, "from": __version__, "message": "取数端马上重启,约 10~30 秒后重新上线"}
@task("sys.cleanup", "清理本地日志")
def cleanup_local(ctx, p):
"""按天数删除本机过期的日志(logs\\)和结果目录(edge_data\\)。天数有下限(日志 30、结果 3),今天的不删,
run\\(登录态、待补发数据)和配置不碰;删前删后各记一行日志(随日志上传云端留痕)。不登录、不发请求。"""
with ctx.step("cleanup", "清理本地日志和结果目录", timeout=600):
r = cleanup.run(ctx.cfg, p.get("logs_days"), p.get("data_days"), source="cloud")
r["ok"] = True
r["message"] = "已删除 %d 天前的日志 %d 个、%d 天前的结果目录 %d 个(约 %.1f MB)%s" % (
r["logs_days"], r["deleted_log_files"], r["data_days"], r["deleted_data_items"], r["log_mb"] + r["data_mb"],
";填的天数低于下限,已按下限(日志 30 天、结果 3 天)保留" if r["raised"] else "")
return r
SECRET_KEYS = ("password", "edge_token", "fallback_public_key")
def effective_config(cfg):
"""当前生效的配置(密码 / 令牌打码),写进诊断包。"""
out = {}
for k, v in sorted(vars(cfg).items()):
if k.startswith("_"):
continue
if k in SECRET_KEYS and v:
v = "<已打码,长度 %d>" % len(str(v))
out[k] = v if isinstance(v, (str, int, float, bool, list, dict, type(None))) else str(v)
return out
@task("sys.collect_diag", "收集诊断")
def collect_diag(ctx, p):
"""环境 + 各域名网络诊断 + auth-api 对照测试 + 日志 / 最近任务的审计与抓包,打包上传云端。不登录、不发密码。"""
cfg = ctx.cfg
stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
work = os.path.join(cfg.data_dir, "diag_" + stamp)
os.makedirs(work, exist_ok=True)
rounds = int(p.get("rounds") or 5)
result = {"ok": True}
try:
with ctx.step("env", "采集电脑环境", timeout=120):
summary, detail = envinfo.collect(cfg, work)
result["env"] = summary
_dump(work, "env.json", detail)
_dump(work, "config_effective.json", effective_config(cfg))
with ctx.step("netdiag", "各域名 DNS / TCP / TLS / HTTP(各 %d 轮)" % rounds, timeout=60 + rounds * 60):
rows = netdiag.run(cfg, rounds=rounds)
_dump(work, "netdiag.json", rows)
result["netdiag"] = [{k: r.get(k) for k in ("name", "host", "success", "ok", "dns", "tls", "http",
"failures")} for r in rows]
with ctx.step("browser_probe", "auth-api 对照测试(Python / 浏览器各种方式)", timeout=120 + rounds * 90):
pr = envinfo.probes(cfg, rounds, bool(p.get("browser_probe", True)))
_dump(work, "probes.json", pr)
result["probes"] = pr
zpath = os.path.join(cfg.data_dir, "diag_%s.zip" % stamp)
with ctx.step("pack", "打包日志与最近任务数据", timeout=300):
n, size = envinfo.pack(cfg, work, zpath, int(p.get("days") or 3), int(p.get("recent_tasks") or 20))
with ctx.step("upload", "上传诊断包(%d 个文件,%.1f MB)" % (n, size / 1048576.0), timeout=600):
eid = ctx.upload(zpath, "file")
result["evidence"] = [eid] if eid else []
bad = [r["name"] for r in result.get("probes", []) + result.get("netdiag", []) if not r.get("ok")]
result["message"] = "诊断包已上传(%d 个文件);%s" % (n, ("异常项:" + "、".join(bad)) if bad else "各项测试都正常")
try:
os.remove(zpath)
except OSError:
pass
return result
finally:
shutil.rmtree(work, ignore_errors=True)
def _dump(d, name, obj):
with open(os.path.join(d, name), "w", encoding="utf-8") as f:
f.write(scrub(json.dumps(obj, ensure_ascii=False, indent=2, default=str)))