apitrace.py
3.85 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
# -*- coding: utf-8 -*-
"""DMS 接口调用流水(审计用):任务执行期间每一次 DMS 业务接口调用都记一条。
一条 = 序号、时间、接口名、地址、请求体、HTTP 状态、header.code / message / traceId、耗时、返回行数、是否成功、
错误、完整响应文本(已脱敏:只打码登记过的密码 / token 和 JWT,业务数据原样保留)。
core/service.run_task 在每个任务开始时 start()、结束时 stop():
* 完整流水写成 gzip 的 JSON Lines 文件,作为任务证据上传云端(kind=api_trace),本地结果目录也留一份;
* 不含响应正文的摘要随任务结果回传(result.api_calls),云端写进 edge_api_calls 表,后台审计时间线逐条可查。
时间:按心跳对出来的「云端时间 - 本机时间」偏差校正后记录(本机时钟不准时,审计时间线上的先后顺序才对得上)。
"""
import gzip
import json
import os
import threading
import time
from .logutil import scrub
MAX_BODY = 4 * 1024 * 1024 # 单条响应正文超过 4MB 截断(正常业务接口远小于此)
CLOCK = {"offset": 0.0, "synced": False} # 云端时间 - 本机时间(秒),心跳成功时更新
def set_offset(seconds):
CLOCK.update(offset=float(seconds), synced=True)
def cloud_now():
"""按云端时钟校正后的当前时间(time.struct_time)。"""
return time.localtime(time.time() + CLOCK["offset"])
def _rows_of(body):
"""返回行数:列表本身 / body.content / body.data 的长度;不是列表返回 None。"""
if isinstance(body, list):
return len(body)
if isinstance(body, dict):
for k in ("content", "data", "rows", "records"):
v = body.get(k)
if isinstance(v, list):
return len(v)
return None
class ApiTrace(object):
def __init__(self):
self._lock = threading.Lock()
self.calls = None
self.task_id = None
def start(self, task_id=None):
with self._lock:
self.calls, self.task_id = [], task_id
def active(self):
return self.calls is not None
def add(self, name, method, url, req_body, status, elapsed, header=None, body=None, text="", error="", ok=False):
if self.calls is None:
return
header = header or {}
rec = {"ts": time.strftime("%Y-%m-%d %H:%M:%S", cloud_now()), "endpoint": name, "method": method,
"url": url.split("?")[0], "request": req_body, "status": status, "elapsed": round(elapsed or 0, 3),
"code": None if header.get("code") is None else str(header.get("code")),
"message": header.get("message"), "trace_id": header.get("traceId"),
"rows": _rows_of(body), "ok": bool(ok), "error": (error or "")[:1000],
"response": scrub(text[:MAX_BODY]) if text else ""}
with self._lock:
if self.calls is not None:
rec["seq"] = len(self.calls) + 1
self.calls.append(rec)
def stop(self):
with self._lock:
calls, self.calls, self.task_id = self.calls or [], None, None
return calls
@staticmethod
def summary(calls):
"""不含请求体 / 响应正文的摘要(随任务结果回传)。"""
keys = ("seq", "ts", "endpoint", "method", "status", "elapsed", "code", "message", "trace_id", "rows", "ok",
"error")
return [{k: c.get(k) for k in keys} for c in calls]
@staticmethod
def write(calls, path):
"""完整流水写成 .jsonl.gz。返回路径。"""
d = os.path.dirname(path)
if d:
os.makedirs(d, exist_ok=True)
with gzip.open(path, "wt", encoding="utf-8") as f:
for c in calls:
f.write(json.dumps(c, ensure_ascii=False, default=str) + "\n")
return path
TRACE = ApiTrace()