netparse-cmdb 0.8.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- netparse/__init__.py +96 -0
- netparse/__main__.py +8 -0
- netparse/adapters/__init__.py +1 -0
- netparse/adapters/incumbent.py +299 -0
- netparse/cli/__init__.py +148 -0
- netparse/cli/__main__.py +8 -0
- netparse/cli/all.py +32 -0
- netparse/cli/diff.py +1351 -0
- netparse/cli/parse.py +216 -0
- netparse/cli/readonly.py +158 -0
- netparse/cli/route_forms.py +255 -0
- netparse/engine.py +1834 -0
- netparse/masking.py +163 -0
- netparse/paths.py +48 -0
- netparse/py.typed +0 -0
- netparse_cmdb-0.8.0.dist-info/METADATA +221 -0
- netparse_cmdb-0.8.0.dist-info/RECORD +21 -0
- netparse_cmdb-0.8.0.dist-info/WHEEL +5 -0
- netparse_cmdb-0.8.0.dist-info/entry_points.txt +2 -0
- netparse_cmdb-0.8.0.dist-info/licenses/LICENSE +21 -0
- netparse_cmdb-0.8.0.dist-info/top_level.txt +1 -0
netparse/cli/diff.py
ADDED
|
@@ -0,0 +1,1351 @@
|
|
|
1
|
+
"""能力 B:在只读生产语料上比较 incumbent 与 netparse 的 19 列台账差异。
|
|
2
|
+
|
|
3
|
+
三侧都复用生产 `build_excel.build_rows`;incumbent 产物不重跑、不修改。
|
|
4
|
+
临时 JSON 保留原文件名中的采集时间戳,并在 finally 中清理。
|
|
5
|
+
|
|
6
|
+
用法::
|
|
7
|
+
|
|
8
|
+
netparse diff --sample 20
|
|
9
|
+
netparse diff --all --out-dir diff-report/full --jobs 12
|
|
10
|
+
netparse diff --dry-run
|
|
11
|
+
|
|
12
|
+
`--jobs N` 只影响速度,不影响结果:单文件处理是纯函数(process_entry),
|
|
13
|
+
主进程按提交顺序合并(merge_entry),所以 `--jobs 1` 与 `--jobs N` 的产物逐字节一致。
|
|
14
|
+
|
|
15
|
+
生产依赖
|
|
16
|
+
--------
|
|
17
|
+
本模块需要只读加载生产脚本 `build_excel.py`(路径见 PRODUCTION_TOOLS)。该依赖是**惰性**的:
|
|
18
|
+
导入本模块不会触发它,只有真正执行 `main()` 时才加载 —— 否则 `netparse parse`
|
|
19
|
+
在没挂生产盘的机器上会被这个 import 连带拖死。
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
import argparse
|
|
23
|
+
import collections
|
|
24
|
+
import datetime
|
|
25
|
+
import hashlib
|
|
26
|
+
import json
|
|
27
|
+
import os
|
|
28
|
+
import random
|
|
29
|
+
import re
|
|
30
|
+
import signal
|
|
31
|
+
import subprocess
|
|
32
|
+
import sys
|
|
33
|
+
import tempfile
|
|
34
|
+
import time
|
|
35
|
+
|
|
36
|
+
from .. import engine
|
|
37
|
+
from ..engine import mask_value
|
|
38
|
+
from ..masking import SECRET_SHAPE_PATTERNS, is_secret_shape
|
|
39
|
+
from ..paths import baseline_template, change_dir, default_template, repo_root
|
|
40
|
+
from ..adapters.incumbent import MAPPING_SPEC, to_incumbent_shape
|
|
41
|
+
|
|
42
|
+
ROOT = repo_root()
|
|
43
|
+
CHANGE = change_dir()
|
|
44
|
+
BASELINE = baseline_template()
|
|
45
|
+
CURRENT = default_template()
|
|
46
|
+
|
|
47
|
+
#: 生产只读语料根目录(incumbent 的输入)
|
|
48
|
+
RAW_ROOT = "E:\\配置文件\\BRAS&SR\\原始配置"
|
|
49
|
+
PARSED_ROOT = "E:\\配置文件\\BRAS&SR\\解析后"
|
|
50
|
+
INDEX = os.path.join(PARSED_ROOT, "_index.json")
|
|
51
|
+
PRODUCTION_TOOLS = "E:\\配置文件\\配置解析\\华为"
|
|
52
|
+
READONLY_ROOTS = [RAW_ROOT, PARSED_ROOT, PRODUCTION_TOOLS]
|
|
53
|
+
|
|
54
|
+
SIDES = ("incumbent", "netparse_before_fix", "netparse_after_fix")
|
|
55
|
+
|
|
56
|
+
#: 19 列台账口径(冻结副本)。
|
|
57
|
+
#: 生产真值来自 `build_excel.COLUMNS`,这里留一份是为了**导入期不需要生产脚本**:
|
|
58
|
+
#: 否则 `import netparse.cli.diff` 会连带 `import build_excel`,没挂生产盘的机器直接炸。
|
|
59
|
+
#: 执行时 `load_build_excel()` 会把真实列名与本表逐一比对,不一致立刻报错 ——
|
|
60
|
+
#: 宁可硬失败,也不能拿着过期的列名产出一份口径错位的报告。
|
|
61
|
+
COLUMNS = [
|
|
62
|
+
"设备名称", "管理IP", "采集时间", "接口", "接口描述",
|
|
63
|
+
"接口入流限速(M)", "接口出流限速(M)", "端口IPv4", "端口IPv6",
|
|
64
|
+
"IPv4静态路由明细", "IPv6静态路由明细", "VPN实例", "域名名称", "组播类型",
|
|
65
|
+
"入方向流量策略", "出方向流量策略", "PVLAN", "CVLAN", "VLAN封装类型",
|
|
66
|
+
]
|
|
67
|
+
|
|
68
|
+
_build_excel = None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def load_build_excel():
|
|
72
|
+
"""惰性只读加载生产 build_excel,并校验 19 列口径未漂移。
|
|
73
|
+
|
|
74
|
+
为什么不能模块级 import:这个模块是库的一部分,`netparse parse` / `netparse lint`
|
|
75
|
+
在没挂 E 盘的机器上必须能用。生产脚本只在真跑 diff 时才需要。
|
|
76
|
+
"""
|
|
77
|
+
global _build_excel
|
|
78
|
+
if _build_excel is not None:
|
|
79
|
+
return _build_excel
|
|
80
|
+
|
|
81
|
+
if PRODUCTION_TOOLS not in sys.path:
|
|
82
|
+
sys.path.insert(0, PRODUCTION_TOOLS)
|
|
83
|
+
try:
|
|
84
|
+
import build_excel
|
|
85
|
+
except (ImportError, OSError) as exc:
|
|
86
|
+
raise RuntimeError("无法只读加载生产 build_excel.py(%s):%r" % (PRODUCTION_TOOLS, exc))
|
|
87
|
+
|
|
88
|
+
real = [name for name, _width in build_excel.COLUMNS]
|
|
89
|
+
if real != COLUMNS:
|
|
90
|
+
raise RuntimeError(
|
|
91
|
+
"生产 build_excel 的 19 列口径已变化,本工具的冻结副本过期。\n"
|
|
92
|
+
" 生产:%r\n 本工具:%r" % (real, COLUMNS))
|
|
93
|
+
_build_excel = build_excel
|
|
94
|
+
return build_excel
|
|
95
|
+
|
|
96
|
+
CATEGORIES = ("EthTrunkMember", "Bgp", "BgpPeers", "Acls", "AclRules", "Nqas", "NqaSessions")
|
|
97
|
+
INTERFACE_NP = ("AdminStatus", "CarrierDownHoldTime", "Dcn", "Duplex", "EthTrunkMember",
|
|
98
|
+
"Isis", "Mtu", "Speed", "Statistic", "Type", "UserVlan")
|
|
99
|
+
INTERFACE_INC = ("QOS", "VLAN", "bas", "multicast", "qos-profile", "traffic-policy")
|
|
100
|
+
DEFAULT_SAMPLE_SEED = 8440
|
|
101
|
+
|
|
102
|
+
# 命令族识别沿用 probe_coverage3 的 skeleton/family;regex 仅用于挑选相关真实 trace。
|
|
103
|
+
COLUMN_PATTERNS = {
|
|
104
|
+
"接口描述": r"^\s*description\s+",
|
|
105
|
+
"接口入流限速(M)": r"^\s*(?:qos\s+(?:car|profile)|qos-profile\s+)",
|
|
106
|
+
"接口出流限速(M)": r"^\s*(?:qos\s+(?:car|profile)|qos-profile\s+)",
|
|
107
|
+
"端口IPv4": r"^\s*ip\s+address\s+", "端口IPv6": r"^\s*ipv6\s+address\s+",
|
|
108
|
+
"IPv4静态路由明细": r"^\s*ip\s+route-static\s+", "IPv6静态路由明细": r"^\s*ipv6\s+route-static\s+",
|
|
109
|
+
# 实测 VPN 有两个形态:接口下 `ip binding vpn-instance X`(193 条)与
|
|
110
|
+
# BAS 业务块内 `vpn-instance X`(81 条)。只认前者会漏掉后者的真实命令族。
|
|
111
|
+
"VPN实例": r"^\s*(?:ip\s+binding\s+vpn-instance|vpn-instance)\s+",
|
|
112
|
+
"域名名称": r"^\s*(?:access-type\s+layer2-subscriber\b|bas\s*$)",
|
|
113
|
+
"组播类型": r"^\s*(?:multicast\b|pim\s+sm\b)",
|
|
114
|
+
"入方向流量策略": r"^\s*traffic-policy\s+\S+\s+inbound\b",
|
|
115
|
+
"出方向流量策略": r"^\s*traffic-policy\s+\S+\s+outbound\b",
|
|
116
|
+
# 实测外层 VLAN 不是独立命令,而是与内层同行的 `user-vlan 1000 1999 qinq 2000`;
|
|
117
|
+
# PVLAN 证据必须取含 qinq 的行,否则会把纯 user-vlan 行误当外层证据。
|
|
118
|
+
"PVLAN": r"^\s*(?:qinq\b.*|user-vlan\s+.*\bqinq\b.*)",
|
|
119
|
+
"CVLAN": r"^\s*(?:vlan-type|user-vlan|port\s+default\s+vlan)\b",
|
|
120
|
+
"VLAN封装类型": r"^\s*(?:vlan-type|user-vlan|qinq|port\s+link-type)\b",
|
|
121
|
+
}
|
|
122
|
+
# 两侧台账都不收的形态:不能拿来当缺口证据,否则会误判成「解析丢了记录」。
|
|
123
|
+
# · NULL0 是黑洞下一跳,不是显式出接口;
|
|
124
|
+
# · 第3段参数就是 IPv4 地址 = 纯下一跳(后面跟 preference/description 也算),
|
|
125
|
+
# 这类路由两侧都不进第10列。
|
|
126
|
+
# 出接口形态第3段是接口名(Eth-Trunk185.100),不会被排除。
|
|
127
|
+
EXCLUDE_FROM_EVIDENCE = {
|
|
128
|
+
"IPv4静态路由明细": re.compile(
|
|
129
|
+
r"\bNULL0\b"
|
|
130
|
+
# vpn 变体:vpn-instance <name> <dst> <mask> <nexthop:IPv4>
|
|
131
|
+
r"|^ip\s+route-static\s+vpn-instance\s+\S+\s+\S+\s+\S+\s+\d{1,3}(?:\.\d{1,3}){3}(?:\s|$)"
|
|
132
|
+
# plain 变体:<dst> <mask> <nexthop:IPv4>;用 (?!vpn-instance) 防止把关键字当 dst
|
|
133
|
+
r"|^ip\s+route-static\s+(?!vpn-instance\s)\S+\s+\S+\s+\d{1,3}(?:\.\d{1,3}){3}(?:\s|$)",
|
|
134
|
+
re.I),
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
REQUIRED_FIELDS = {
|
|
138
|
+
"设备名称": "Device.SysName", "管理IP": "Device.RouterId",
|
|
139
|
+
"接口": "Interfaces.Name", "接口描述": "Interfaces.Description",
|
|
140
|
+
"接口入流限速(M)": "Interfaces.QOS / QosProfiles", "接口出流限速(M)": "Interfaces.QOS / QosProfiles",
|
|
141
|
+
"端口IPv4": "Interfaces.IpAddress.Address,Mask", "端口IPv6": "Interfaces.IpAddress.Address,Mask",
|
|
142
|
+
"IPv4静态路由明细": "RouteStatics.NextHopIface", "IPv6静态路由明细": "RouteStaticsV6(集合未声明)",
|
|
143
|
+
"VPN实例": "Interfaces.IpBindingVpn", "域名名称": "Interfaces.bas.damian(未声明)",
|
|
144
|
+
"组播类型": "Interfaces.multicast.type(未声明)", "入方向流量策略": "Interfaces.traffic-policy.in(未声明)",
|
|
145
|
+
"出方向流量策略": "Interfaces.traffic-policy.out(未声明)", "PVLAN": "Interfaces.VLAN.QinQ(未声明)",
|
|
146
|
+
"CVLAN": "Interfaces.VLAN.user-vlan / dot1q(结构不同)", "VLAN封装类型": "Interfaces.VLAN.type(结构不同)",
|
|
147
|
+
}
|
|
148
|
+
EFFORT = {
|
|
149
|
+
"设备名称": 0.25, "管理IP": 0.25, "接口": 0.5, "接口描述": 0.25,
|
|
150
|
+
"接口入流限速(M)": 1.0, "接口出流限速(M)": 1.0, "端口IPv4": 0.5, "端口IPv6": 0.5,
|
|
151
|
+
"IPv4静态路由明细": 0.5, "IPv6静态路由明细": 0.75, "VPN实例": 0.25, "域名名称": 0.5,
|
|
152
|
+
"组播类型": 0.5, "入方向流量策略": 0.5, "出方向流量策略": 0.5,
|
|
153
|
+
"PVLAN": 1.0, "CVLAN": 1.0, "VLAN封装类型": 0.5,
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def read_json(path):
|
|
158
|
+
with open(path, encoding="utf-8") as f:
|
|
159
|
+
return json.load(f)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def load_index():
|
|
163
|
+
if not os.path.isfile(INDEX):
|
|
164
|
+
raise RuntimeError("incumbent 索引不存在:" + INDEX)
|
|
165
|
+
idx = read_json(INDEX)
|
|
166
|
+
entries, missing = [], []
|
|
167
|
+
for item in idx.get("files", []):
|
|
168
|
+
if item.get("status") != "ok":
|
|
169
|
+
continue
|
|
170
|
+
rel = item["file"].replace("/", os.sep).replace("\\", os.sep)
|
|
171
|
+
inc = os.path.join(PARSED_ROOT, rel)
|
|
172
|
+
stem = os.path.basename(rel)[:-5]
|
|
173
|
+
candidates = [os.path.join(RAW_ROOT, os.path.dirname(rel), stem),
|
|
174
|
+
os.path.join(RAW_ROOT, os.path.dirname(rel), stem + ".txt")]
|
|
175
|
+
raw = next((p for p in candidates if os.path.isfile(p)), None)
|
|
176
|
+
if raw is None or not os.path.isfile(inc):
|
|
177
|
+
missing.append(rel)
|
|
178
|
+
else:
|
|
179
|
+
entries.append({"json": inc, "raw": raw, "month": rel.split(os.sep)[0],
|
|
180
|
+
"stem": stem, "index": item})
|
|
181
|
+
if missing:
|
|
182
|
+
raise RuntimeError("原始配置 / incumbent JSON 映射缺失 %d 个,示例:%s" % (len(missing), missing[:20]))
|
|
183
|
+
return idx, entries
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def select_entries(entries, sample=None, month=None, sample_seed=DEFAULT_SAMPLE_SEED):
|
|
187
|
+
"""月份先打乱,月内随机不放回,再按月轮转;不重复文件凑数。"""
|
|
188
|
+
if month:
|
|
189
|
+
entries = [e for e in entries if month in e["month"]]
|
|
190
|
+
if sample is None:
|
|
191
|
+
return entries
|
|
192
|
+
if sample < 1:
|
|
193
|
+
raise RuntimeError("--sample 必须为正整数")
|
|
194
|
+
rng = random.Random(sample_seed)
|
|
195
|
+
by_month = collections.defaultdict(list)
|
|
196
|
+
for entry in entries:
|
|
197
|
+
by_month[entry["month"]].append(entry)
|
|
198
|
+
months = sorted(by_month)
|
|
199
|
+
rng.shuffle(months)
|
|
200
|
+
groups = []
|
|
201
|
+
for month_name in months:
|
|
202
|
+
group = list(by_month[month_name])
|
|
203
|
+
rng.shuffle(group)
|
|
204
|
+
groups.append(group)
|
|
205
|
+
selected = []
|
|
206
|
+
while len(selected) < sample:
|
|
207
|
+
progressed = False
|
|
208
|
+
for group in groups:
|
|
209
|
+
if group and len(selected) < sample:
|
|
210
|
+
selected.append(group.pop())
|
|
211
|
+
progressed = True
|
|
212
|
+
if not progressed:
|
|
213
|
+
break
|
|
214
|
+
return selected
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def sampling_meta(candidates, selected, requested, seed):
|
|
218
|
+
months = sorted({e["month"] for e in candidates})
|
|
219
|
+
expected = min(requested, len(months), len(candidates)) if requested is not None else len(months)
|
|
220
|
+
return {"available_months": months, "available_month_count": len(months),
|
|
221
|
+
"candidate_files": len(candidates), "requested_sample": requested,
|
|
222
|
+
"expected_distinct_months": expected, "months_covered": sorted({e["month"] for e in selected}),
|
|
223
|
+
"sample_seed": seed, "algorithm": "月份顺序固定seed打乱;月内随机不放回;按月轮转",
|
|
224
|
+
"estimation_note": "月份分层样本;不得把抽样填充率直接宣称为全量无偏估计"}
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def index_rows(rows):
|
|
228
|
+
out = {}
|
|
229
|
+
for row in rows:
|
|
230
|
+
key = str(row[3]).casefold()
|
|
231
|
+
if key in out:
|
|
232
|
+
raise RuntimeError("同一侧出现重名接口:%s" % row[3])
|
|
233
|
+
out[key] = row
|
|
234
|
+
return out
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def empty_side():
|
|
238
|
+
return {"filled": collections.Counter(), "total": 0,
|
|
239
|
+
"values": collections.Counter(), "both_nonempty_diff": collections.Counter()}
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def zero_stats():
|
|
243
|
+
return {side: empty_side() for side in SIDES}
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def add_stats(dst, src):
|
|
247
|
+
for side in SIDES:
|
|
248
|
+
for key in ("filled", "values", "both_nonempty_diff"):
|
|
249
|
+
dst[side][key].update(src[side][key])
|
|
250
|
+
dst[side]["total"] += src[side]["total"]
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def compare_three(inc_rows, before_rows, after_rows, samples):
|
|
254
|
+
indices = [index_rows(rows) for rows in (inc_rows, before_rows, after_rows)]
|
|
255
|
+
stats = zero_stats()
|
|
256
|
+
for key in sorted(set().union(*(set(index) for index in indices))):
|
|
257
|
+
rows = [index.get(key) for index in indices]
|
|
258
|
+
for i, col in enumerate(COLUMNS):
|
|
259
|
+
for side, row in zip(SIDES, rows):
|
|
260
|
+
if row is None:
|
|
261
|
+
continue
|
|
262
|
+
if i == 0:
|
|
263
|
+
stats[side]["total"] += 1
|
|
264
|
+
value = row[i]
|
|
265
|
+
if value not in (None, "", []):
|
|
266
|
+
stats[side]["filled"][col] += 1
|
|
267
|
+
# “值条数”是非空单元格数;不按逗号拆值(规格 Scenario 的逐行累加口径)。
|
|
268
|
+
stats[side]["values"][col] += 1
|
|
269
|
+
if all(row is not None for row in rows):
|
|
270
|
+
iv, bv, av = (row[i] for row in rows)
|
|
271
|
+
if iv not in (None, "") and av not in (None, "") and iv != av:
|
|
272
|
+
stats["incumbent"]["both_nonempty_diff"][col] += 1
|
|
273
|
+
if (iv, bv, av).count(iv) < 3 and len(samples[col]) < 20:
|
|
274
|
+
samples[col].append({"device": rows[0][0], "interface": rows[0][3],
|
|
275
|
+
"incumbent": report_value(iv),
|
|
276
|
+
"netparse_before_fix": report_value(bv),
|
|
277
|
+
"netparse_after_fix": report_value(av)})
|
|
278
|
+
both_after = len(set(indices[0]) & set(indices[2]))
|
|
279
|
+
return stats, [len(set(indices[0]) & set(x)) for x in indices], \
|
|
280
|
+
[len(set(indices[0]) - set(x)) for x in indices[1:]], \
|
|
281
|
+
[len(set(x) - set(indices[0])) for x in indices[1:]], both_after
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def skeleton(line):
|
|
285
|
+
text = line.strip()
|
|
286
|
+
text = re.sub(r"\b\d{1,3}(?:\.\d{1,3}){3}\b", "<ip>", text)
|
|
287
|
+
return re.sub(r"\b\d+\b", "<n>", text)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def family(line):
|
|
291
|
+
head = []
|
|
292
|
+
for token in skeleton(line).split():
|
|
293
|
+
if token.startswith("<"):
|
|
294
|
+
break
|
|
295
|
+
head.append(token)
|
|
296
|
+
if len(head) == 2:
|
|
297
|
+
break
|
|
298
|
+
return " ".join(head) if head else "(空)"
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def redact_text(text):
|
|
302
|
+
"""只用于证据样本;实际解析值仍由引擎在捕获时脱敏。"""
|
|
303
|
+
result = text
|
|
304
|
+
for pattern in SECRET_SHAPE_PATTERNS[:1]:
|
|
305
|
+
result = pattern.sub(engine.MASK_VALUE, result)
|
|
306
|
+
return result
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def report_value(value):
|
|
310
|
+
"""展示值复用引擎脱敏策略;不影响统计,不写回incumbent,也不改变计数。
|
|
311
|
+
|
|
312
|
+
两步:先按行内密文形态替换(证据里常是整行命令),再做整值高熵判定。
|
|
313
|
+
只做后者会漏掉 `peer x password cipher %^%#...%^%#` 这种嵌在行中的凭据。
|
|
314
|
+
"""
|
|
315
|
+
if isinstance(value, str):
|
|
316
|
+
return mask_value(redact_text(value), None, engine.MASK_VALUE, True, count=False)
|
|
317
|
+
return value
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def trace_records(traces, column):
|
|
321
|
+
"""保留原始行用于规则复核,展示行单独脱敏;两者不混用。"""
|
|
322
|
+
pattern = COLUMN_PATTERNS.get(column)
|
|
323
|
+
if not pattern:
|
|
324
|
+
return []
|
|
325
|
+
rx = re.compile(pattern, re.I)
|
|
326
|
+
return [{"line": no, "text": report_value(redact_text(line)), "raw_text": line,
|
|
327
|
+
"hit": collection, "collection": collection, "stack": stack}
|
|
328
|
+
for no, line, collection, stack in traces if rx.search(line)]
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def compile_rules(colls):
|
|
332
|
+
"""一次编译全部规则,供真实规则复核复用;不修改引擎。"""
|
|
333
|
+
compiled = {}
|
|
334
|
+
for coll in colls:
|
|
335
|
+
items = []
|
|
336
|
+
for index, rule in enumerate(coll.rules, 1):
|
|
337
|
+
try:
|
|
338
|
+
items.append((index, engine.compile_rule(rule, coll), rule))
|
|
339
|
+
except KeyError:
|
|
340
|
+
items.append((index, None, rule))
|
|
341
|
+
compiled[coll.name] = items
|
|
342
|
+
return compiled
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def rules_matching(compiled, line):
|
|
346
|
+
"""真实行在该模板下的全部命中规则(集合 + 规则序号 + 原文/目标)。"""
|
|
347
|
+
hits = []
|
|
348
|
+
for collection, items in compiled.items():
|
|
349
|
+
for index, compiled_rule, rule in items:
|
|
350
|
+
if compiled_rule is None:
|
|
351
|
+
continue
|
|
352
|
+
if compiled_rule.rx.match(line):
|
|
353
|
+
hits.append({"collection": collection, "rule_index": index,
|
|
354
|
+
"pattern": rule.pattern, "target": rule.target})
|
|
355
|
+
return hits
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def rules_tried(compiled, line, collection, limit=80):
|
|
359
|
+
"""指定集合内每条候选规则的匹配/失配结果,用于区分「没规则」和「规则全失配」。
|
|
360
|
+
|
|
361
|
+
limit 必须大于典型集合的规则数(Interfaces 有 20+ 条):截断会把真正命中的
|
|
362
|
+
后半段规则剪掉,产出「rule_matches 非空但 rules_tried 全失配」的矛盾证据。
|
|
363
|
+
命中规则永远保留在前,保证截断也不会藏掉匹配项。
|
|
364
|
+
"""
|
|
365
|
+
items = compiled.get(collection) or []
|
|
366
|
+
results = []
|
|
367
|
+
for index, compiled_rule, rule in items:
|
|
368
|
+
results.append({"collection": collection, "rule_index": index, "pattern": rule.pattern,
|
|
369
|
+
"target": rule.target,
|
|
370
|
+
"matched": bool(compiled_rule and compiled_rule.rx.match(line))})
|
|
371
|
+
results.sort(key=lambda item: (not item["matched"], item["rule_index"]))
|
|
372
|
+
return results[:limit]
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def relevant_collections(column):
|
|
376
|
+
"""从规格要求字段推导相关集合名(如 RouteStatics.NextHopIface → RouteStatics)。"""
|
|
377
|
+
names = []
|
|
378
|
+
for name in required_field_names(column):
|
|
379
|
+
head = name.split(".")[0]
|
|
380
|
+
if head and head not in names:
|
|
381
|
+
names.append(head)
|
|
382
|
+
return names
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def required_field_names(column):
|
|
386
|
+
"""把 REQUIRED_FIELDS 拆成精确的字段名集合。
|
|
387
|
+
|
|
388
|
+
必须按分隔符切并去括注,不能拿整串做子串包含 ——
|
|
389
|
+
`"RouteStatics.NextHop" in "RouteStatics.NextHopIface"` 为 True,
|
|
390
|
+
会把「只声明了 NextHop 的修前模板」误判成「已声明 NextHopIface」,
|
|
391
|
+
进而把真实的记录丢失错判成「字段已捕获、缺口不在解析层」。
|
|
392
|
+
"""
|
|
393
|
+
names = []
|
|
394
|
+
for chunk in re.split(r"[/,]", REQUIRED_FIELDS.get(column, "")):
|
|
395
|
+
name = chunk.split("(")[0].strip()
|
|
396
|
+
if not name:
|
|
397
|
+
continue
|
|
398
|
+
# 逗号后的裸名(`Interfaces.IpAddress.Address,Mask`、`...user-vlan / dot1q`)
|
|
399
|
+
# 要补上前一个字段的集合前缀,否则会变成永不匹配的孤立名。
|
|
400
|
+
if "." not in name and names:
|
|
401
|
+
name = names[-1].rsplit(".", 1)[0] + "." + name
|
|
402
|
+
if name not in names:
|
|
403
|
+
names.append(name)
|
|
404
|
+
return names
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def rel(path):
|
|
408
|
+
"""相对仓库根的 POSIX 风格路径。
|
|
409
|
+
|
|
410
|
+
报告要跨平台可复现:`os.path.relpath` 在 Windows 上给出 `templates\\huawei-vrp.cmdb`,
|
|
411
|
+
在 Linux 上给出 `templates/huawei-vrp.cmdb` —— 同一份报告两平台不一致,
|
|
412
|
+
下游拿它做 diff/断言就会假失败。统一成 `/`。
|
|
413
|
+
"""
|
|
414
|
+
return os.path.relpath(path, ROOT).replace(os.sep, "/")
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def template_declaration(path, colls, column):
|
|
418
|
+
required = REQUIRED_FIELDS.get(column, "")
|
|
419
|
+
wanted_fields = set(required_field_names(column))
|
|
420
|
+
declared = []
|
|
421
|
+
for coll in colls:
|
|
422
|
+
for field_path in coll.all_fields:
|
|
423
|
+
qualified = coll.name + "." + field_path
|
|
424
|
+
# 精确匹配,不用 in(见 required_field_names 里的说明)
|
|
425
|
+
if qualified in wanted_fields or (column == "CVLAN" and qualified == "Interfaces.UserVlan"):
|
|
426
|
+
declared.append(qualified)
|
|
427
|
+
existing = {c.name: c for c in colls}
|
|
428
|
+
wanted = relevant_collections(column)
|
|
429
|
+
rules = [{"collection": name, "rule_index": i, "pattern": r.pattern, "target": r.target}
|
|
430
|
+
for name in wanted if name in existing
|
|
431
|
+
for i, r in enumerate(existing[name].rules, 1)]
|
|
432
|
+
return {"path": path, "target": required, "target_declared": bool(declared),
|
|
433
|
+
"declared_fields": declared, "candidate_rules": rules,
|
|
434
|
+
"relevant_collections": wanted,
|
|
435
|
+
"missing_collections": [name for name in wanted if name not in existing],
|
|
436
|
+
"collection_count": len(colls)}
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def evidence_for(entry, traces, template, column, compiled, collection_counts):
|
|
440
|
+
"""采集某列的缺口证据。
|
|
441
|
+
|
|
442
|
+
选行规则(顺序敏感,决定根因是否成立):
|
|
443
|
+
1. 先排除**两侧都不入台账**的形态(第10列的 NULL0 黑洞路由),它不是缺口;
|
|
444
|
+
2. 缺口证据优先选**未被任何规则捕获**的真实行 —— 这类行才解释「为什么少了」;
|
|
445
|
+
3. 全都命中时退回首行,用于证明「捕获正常但列仍短」,交由门禁判待人工。
|
|
446
|
+
否则会拿一条正常命中并产生记录的行去解释缺口,得出自相矛盾的结论
|
|
447
|
+
(VPN 的 `ip binding vpn-instance`、CVLAN 的 `user-vlan` 都是这种情形)。
|
|
448
|
+
"""
|
|
449
|
+
exclude = EXCLUDE_FROM_EVIDENCE.get(column)
|
|
450
|
+
records = trace_records(traces, column)
|
|
451
|
+
if exclude is not None:
|
|
452
|
+
records = [r for r in records if not exclude.search(r["raw_text"])]
|
|
453
|
+
evidence = {"column": column, "input": None, "template": template,
|
|
454
|
+
"trace": {"source": "probe_stack.run(colls, lines, trace=trace)",
|
|
455
|
+
"command_family": None, "total_lines": len(records),
|
|
456
|
+
"hit_lines": sum(r["hit"] is not None for r in records),
|
|
457
|
+
"records": records[:5], "rule_matches": [], "rules_tried": [],
|
|
458
|
+
"collection_record_counts": collection_counts, "hit": False}}
|
|
459
|
+
if not records:
|
|
460
|
+
return evidence
|
|
461
|
+
unmatched, matched = [], []
|
|
462
|
+
for record in records:
|
|
463
|
+
record_matches = rules_matching(compiled, record["raw_text"])
|
|
464
|
+
(matched if record_matches else unmatched).append((record, record_matches))
|
|
465
|
+
chosen, matches = unmatched[0] if unmatched else matched[0]
|
|
466
|
+
tried = []
|
|
467
|
+
for collection in [m["collection"] for m in matches] or template.get("relevant_collections", []):
|
|
468
|
+
tried.extend(rules_tried(compiled, chosen["raw_text"], collection))
|
|
469
|
+
evidence["input"] = {"file": entry["stem"], "raw_path": entry["raw"],
|
|
470
|
+
"line": chosen["line"], "text": chosen["text"]}
|
|
471
|
+
evidence["trace"].update({"command_family": family(chosen["text"]),
|
|
472
|
+
"hit": chosen["hit"] is not None,
|
|
473
|
+
"rule_matches": matches,
|
|
474
|
+
"rules_tried": tried,
|
|
475
|
+
"matched_record": bool(matches),
|
|
476
|
+
"unmatched_line_count": len(unmatched),
|
|
477
|
+
"matched_line_count": len(matched)})
|
|
478
|
+
return evidence
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def evidence_complete(evidence):
|
|
482
|
+
"""三类证据缺一不可:真实输入、模板声明、真实 trace(含规则复核结果)。"""
|
|
483
|
+
if not evidence:
|
|
484
|
+
return False
|
|
485
|
+
inp = evidence.get("input")
|
|
486
|
+
template = evidence.get("template")
|
|
487
|
+
trace = evidence.get("trace")
|
|
488
|
+
return bool(inp and inp.get("file") and inp.get("line") and template and
|
|
489
|
+
template.get("path") and trace and trace.get("command_family") and
|
|
490
|
+
(trace.get("total_lines") or 0) > 0 and trace.get("hit_lines") is not None and
|
|
491
|
+
("rule_matches" in trace or "rules_tried" in trace))
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def classify_gap(evidence):
|
|
495
|
+
"""证据不全一律待人工;映射表 root_cause_if_empty 不参与自动判定。
|
|
496
|
+
|
|
497
|
+
顺序很关键:整条记录丢失要先于「模板未覆盖」,因为修前静态路由正是
|
|
498
|
+
「有候选规则但全部失配 → 记录整条没进结果」,不是模板没有这条命令。
|
|
499
|
+
"""
|
|
500
|
+
if not evidence_complete(evidence):
|
|
501
|
+
return {"root_cause": ["待人工判定"], "evidence_status": "INSUFFICIENT",
|
|
502
|
+
"evidence": evidence,
|
|
503
|
+
"reason": "缺真实文件/行号、模板声明或真实规则复核/trace,不猜根因"}
|
|
504
|
+
trace, template = evidence["trace"], evidence["template"]
|
|
505
|
+
if evidence.get("join"):
|
|
506
|
+
join = evidence["join"]
|
|
507
|
+
if (join.get("captured_original_fields") and join.get("source_collection") and
|
|
508
|
+
join.get("target_collection") and join.get("key") and
|
|
509
|
+
join.get("source_value") is not None and join.get("target_value") is not None and
|
|
510
|
+
join.get("before") is not None and join.get("after") is not None):
|
|
511
|
+
return {"root_cause": ["join缺失"], "evidence_status": "VERIFIED", "evidence": evidence}
|
|
512
|
+
return {"root_cause": ["待人工判定"], "evidence_status": "INSUFFICIENT", "evidence": evidence,
|
|
513
|
+
"reason": "未证明 join 所需原始字段已捕获"}
|
|
514
|
+
record_loss = evidence.get("record_loss")
|
|
515
|
+
if record_loss:
|
|
516
|
+
if (record_loss.get("incumbent") and record_loss.get("netparse_missing") and
|
|
517
|
+
(trace.get("rule_matches") or trace.get("rules_tried"))):
|
|
518
|
+
return {"root_cause": ["整条记录丢失"], "evidence_status": "VERIFIED", "evidence": evidence}
|
|
519
|
+
return {"root_cause": ["待人工判定"], "evidence_status": "INSUFFICIENT", "evidence": evidence,
|
|
520
|
+
"reason": "缺候选规则匹配/失配复核,无法解释记录为何缺失"}
|
|
521
|
+
matches = trace.get("rule_matches") or []
|
|
522
|
+
if not matches:
|
|
523
|
+
# 该真实行在模板全部规则中 0 命中:说明模板没有能捕获这条命令的规则。
|
|
524
|
+
# 注意不能用 target_declared 一概否定 —— 同列可能有多个命令形态
|
|
525
|
+
# (CVLAN 既有 user-vlan 也有 vlan-type dot1q;VPN 既有 ip binding 也有 BAS 内 vpn-instance),
|
|
526
|
+
# 字段声明存在但只覆盖其中一种,另一种就是「模板未覆盖该命令形态」。
|
|
527
|
+
if template.get("missing_collections") or not template.get("target_declared"):
|
|
528
|
+
return {"root_cause": ["模板未覆盖该命令"], "evidence_status": "VERIFIED",
|
|
529
|
+
"evidence": evidence,
|
|
530
|
+
"reason": "真实行 0 命中规则,且该列所需集合/字段未声明:"
|
|
531
|
+
+ repr(template.get("missing_collections") or template.get("target"))}
|
|
532
|
+
return {"root_cause": ["模板未覆盖该命令"], "evidence_status": "VERIFIED",
|
|
533
|
+
"evidence": evidence,
|
|
534
|
+
"reason": "该真实行 0 命中任何规则;同列字段虽已声明,但没有覆盖这一命令形态("
|
|
535
|
+
+ (evidence.get("input") or {}).get("text", "") + ")"}
|
|
536
|
+
if not template.get("target_declared"):
|
|
537
|
+
return {"root_cause": ["字段丢失"], "evidence_status": "VERIFIED", "evidence": evidence}
|
|
538
|
+
return {"root_cause": ["待人工判定"], "evidence_status": "INSUFFICIENT", "evidence": evidence,
|
|
539
|
+
"reason": "目标字段已声明/已捕获,缺口不在解析层;现有证据不能唯一归入所列根因",
|
|
540
|
+
"analysis": evidence.get("analysis")}
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def surplus_evidence(entry, traces, template, column, compiled, collection_counts):
|
|
544
|
+
"""netparse 多出值的证据:真实行 + 模板声明 + 规则命中,用于「语义不同」。
|
|
545
|
+
|
|
546
|
+
只对确有多出值的列调用;取第一条命中规则并已产生记录的真实行。
|
|
547
|
+
"""
|
|
548
|
+
records = trace_records(traces, column)
|
|
549
|
+
hits = [r for r in records if r["hit"] is not None]
|
|
550
|
+
if not records or not hits:
|
|
551
|
+
return None
|
|
552
|
+
record = hits[0]
|
|
553
|
+
matches = rules_matching(compiled, record["raw_text"])
|
|
554
|
+
if not matches:
|
|
555
|
+
return None
|
|
556
|
+
return {"column": column,
|
|
557
|
+
"input": {"file": entry["stem"], "raw_path": entry["raw"],
|
|
558
|
+
"line": record["line"], "text": record["text"]},
|
|
559
|
+
"template": template,
|
|
560
|
+
"trace": {"source": "probe_stack.run(colls, lines, trace=trace)",
|
|
561
|
+
"command_family": family(record["text"]),
|
|
562
|
+
"total_lines": len(records), "hit_lines": len(hits),
|
|
563
|
+
"records": hits[:3], "rule_matches": matches,
|
|
564
|
+
"rules_tried": rules_tried(compiled, record["raw_text"], matches[0]["collection"]),
|
|
565
|
+
"collection_record_counts": collection_counts, "hit": True},
|
|
566
|
+
"surplus": {"direction": "netparse_more",
|
|
567
|
+
"samples": [r["text"] for r in hits[:3]],
|
|
568
|
+
"note": "netparse 命中该命令并产生记录,incumbent 未按同一口径计入"}}
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
def classify_surplus(evidence):
|
|
572
|
+
"""netparse 多出值:只有真实行命中并产生记录才可判「语义不同」。"""
|
|
573
|
+
if not evidence_complete(evidence):
|
|
574
|
+
return {"root_cause": ["待人工判定"], "evidence_status": "INSUFFICIENT",
|
|
575
|
+
"evidence": evidence, "reason": "多出值缺真实行/模板声明/规则命中证据"}
|
|
576
|
+
return {"root_cause": ["语义不同"], "evidence_status": "VERIFIED", "evidence": evidence}
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
def route_loss(incumbent, np_results):
|
|
580
|
+
"""逐文件只产出可累加的计数;百分比一律由 finalize_route_loss 事后算。
|
|
581
|
+
|
|
582
|
+
百分比是比值,不能跨文件相加(9 个文件各 100% 会累加成 900%)。
|
|
583
|
+
"""
|
|
584
|
+
expected = sum(1 for r in (incumbent.get("route-static") or {}).get("IPV4", [])
|
|
585
|
+
if r.get("interface") and r["interface"].upper() != "NULL0")
|
|
586
|
+
out = {}
|
|
587
|
+
for label, result in np_results.items():
|
|
588
|
+
actual = sum(1 for r in result.get("RouteStatics", [])
|
|
589
|
+
if r.get("NextHopIface") and r["NextHopIface"].upper() != "NULL0")
|
|
590
|
+
out[label] = {"explicit_interface_routes": expected, "captured": actual,
|
|
591
|
+
"lost": max(0, expected - actual)}
|
|
592
|
+
return out
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def finalize_route_loss(route):
|
|
596
|
+
"""把累加后的计数换算成百分比;分母为 0 时记 0 并标注无可评估路由。"""
|
|
597
|
+
out = {}
|
|
598
|
+
for label, counters in route.items():
|
|
599
|
+
expected, lost = counters.get("explicit_interface_routes", 0), counters.get("lost", 0)
|
|
600
|
+
item = dict(counters)
|
|
601
|
+
item["loss_pct"] = round(100 * lost / expected, 2) if expected else 0
|
|
602
|
+
if not expected:
|
|
603
|
+
item["note"] = "该口径无显式出接口路由(已排除 NULL0),百分比不具意义"
|
|
604
|
+
out[label] = item
|
|
605
|
+
return out
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def route_record_loss_evidence(entry, incumbent, before, traces, template, compiled, collection_counts):
|
|
609
|
+
"""修前静态路由整条丢失的证据:incumbent 有出接口路由 → netparse 无对应记录。
|
|
610
|
+
|
|
611
|
+
必须同时证明:真实行存在、该行为何未产生记录(候选规则匹配/失配)。
|
|
612
|
+
"""
|
|
613
|
+
missing = []
|
|
614
|
+
before_keys = {(r.get("Prefix", ""), r.get("Mask", ""), r.get("NextHopIface", ""),
|
|
615
|
+
r.get("NextHop", ""), r.get("VpnInstance", "")) for r in before.get("RouteStatics", [])}
|
|
616
|
+
for route in (incumbent.get("route-static") or {}).get("IPV4", []):
|
|
617
|
+
if not route.get("interface") or route["interface"].upper() == "NULL0":
|
|
618
|
+
continue
|
|
619
|
+
cidr = "/".join(x for x in (route.get("dest", ""), route.get("mask", "")) if x)
|
|
620
|
+
if not any(cidr.split("/")[0] == key[0] for key in before_keys):
|
|
621
|
+
missing.append({"dest": route.get("dest", ""), "mask": route.get("mask", ""),
|
|
622
|
+
"interface": route.get("interface", "")})
|
|
623
|
+
records = trace_records(traces, "IPv4静态路由明细")
|
|
624
|
+
if not missing or not records:
|
|
625
|
+
return None
|
|
626
|
+
first = next((r for r in records
|
|
627
|
+
if any(str(m["dest"]) in r["text"] and str(m["interface"]) in r["text"] for m in missing)),
|
|
628
|
+
records[0])
|
|
629
|
+
matches = rules_matching(compiled, first["raw_text"])
|
|
630
|
+
tried = []
|
|
631
|
+
for collection in [m["collection"] for m in matches] or template.get("relevant_collections", []):
|
|
632
|
+
tried.extend(rules_tried(compiled, first["raw_text"], collection))
|
|
633
|
+
return {"column": "IPv4静态路由明细",
|
|
634
|
+
"input": {"file": entry["stem"], "raw_path": entry["raw"], "line": first["line"],
|
|
635
|
+
"text": first["text"]},
|
|
636
|
+
"template": template,
|
|
637
|
+
"trace": {"source": "probe_stack.run(colls, lines, trace=trace)",
|
|
638
|
+
"command_family": family(first["text"]), "total_lines": len(records),
|
|
639
|
+
"hit_lines": sum(r["hit"] is not None for r in records), "records": [first],
|
|
640
|
+
"rule_matches": matches, "rules_tried": tried,
|
|
641
|
+
"collection_record_counts": collection_counts, "hit": first["hit"] is not None},
|
|
642
|
+
"record_loss": {"incumbent": len(missing), "netparse_missing": len(missing),
|
|
643
|
+
"examples": missing[:5]},
|
|
644
|
+
"asset_layer_note": "interface 在命令层拆出;build_excel.build_route_index 只读取并跳过无 interface 的路由"}
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def evidence_signature(evidence):
|
|
648
|
+
"""证据分桶键:同命令族 + 同命中规则的结构归为一组,避免同一成因刷屏。"""
|
|
649
|
+
if not evidence:
|
|
650
|
+
return None
|
|
651
|
+
trace = evidence.get("trace") or {}
|
|
652
|
+
matches = trace.get("rule_matches") or []
|
|
653
|
+
key = (trace.get("command_family"),
|
|
654
|
+
tuple(sorted((m["collection"], m["rule_index"]) for m in matches)),
|
|
655
|
+
bool((evidence.get("template") or {}).get("target_declared")))
|
|
656
|
+
return key
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def add_evidence(buckets, evidence, per_signature=3, max_signatures=40):
|
|
660
|
+
"""按成因分桶留存证据;每桶保留有限样本,且限制桶总数(全量 8440 文件不能无界增长)。"""
|
|
661
|
+
signature = evidence_signature(evidence)
|
|
662
|
+
if signature is None:
|
|
663
|
+
return
|
|
664
|
+
if signature not in buckets and len(buckets) >= max_signatures:
|
|
665
|
+
return
|
|
666
|
+
bucket = buckets.setdefault(signature, [])
|
|
667
|
+
if len(bucket) < per_signature:
|
|
668
|
+
bucket.append(evidence)
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
def group_diagnoses(buckets, classifier):
|
|
672
|
+
"""把一列的全部证据按根因分组;每组各自带证据,不用单一标签掩盖多成因。"""
|
|
673
|
+
groups = []
|
|
674
|
+
for signature in sorted(buckets, key=lambda item: str(item)):
|
|
675
|
+
samples = buckets[signature]
|
|
676
|
+
if not samples:
|
|
677
|
+
continue
|
|
678
|
+
verdict = classifier(samples[0])
|
|
679
|
+
groups.append({"root_cause": verdict["root_cause"],
|
|
680
|
+
"evidence_status": verdict["evidence_status"],
|
|
681
|
+
"reason": verdict.get("reason"),
|
|
682
|
+
"sample_count": len(samples),
|
|
683
|
+
"evidence": samples[0]})
|
|
684
|
+
if not groups:
|
|
685
|
+
return {"root_cause": ["待人工判定"], "evidence_status": "INSUFFICIENT",
|
|
686
|
+
"reason": "本列无任何可定位的真实行/模板声明/trace 证据", "groups": []}
|
|
687
|
+
causes, insufficient = [], False
|
|
688
|
+
for group in groups:
|
|
689
|
+
for cause in group["root_cause"]:
|
|
690
|
+
if cause not in causes:
|
|
691
|
+
causes.append(cause)
|
|
692
|
+
if group["evidence_status"] != "VERIFIED":
|
|
693
|
+
insufficient = True
|
|
694
|
+
status = "INSUFFICIENT" if insufficient else "VERIFIED"
|
|
695
|
+
if insufficient and "待人工判定" not in causes:
|
|
696
|
+
causes.append("待人工判定")
|
|
697
|
+
return {"root_cause": causes, "evidence_status": status,
|
|
698
|
+
"reason": "同一列存在多组成因,分别见 groups;含未证实成因时为 INSUFFICIENT",
|
|
699
|
+
"groups": groups,
|
|
700
|
+
"verified_groups": [g["root_cause"] for g in groups if g["evidence_status"] == "VERIFIED"],
|
|
701
|
+
"pending_groups": [g["root_cause"] for g in groups if g["evidence_status"] != "VERIFIED"],
|
|
702
|
+
"evidence": groups[0]["evidence"]}
|
|
703
|
+
|
|
704
|
+
|
|
705
|
+
def count_records(result, name):
|
|
706
|
+
"""某集合在本文件实际产生的记录数(顶层 list/dict 与嵌套集合都算)。"""
|
|
707
|
+
value = result.get(name)
|
|
708
|
+
if isinstance(value, list):
|
|
709
|
+
return len(value)
|
|
710
|
+
if isinstance(value, dict):
|
|
711
|
+
return 1 if value else 0
|
|
712
|
+
return 0
|
|
713
|
+
|
|
714
|
+
|
|
715
|
+
def collection_record_counts(result):
|
|
716
|
+
return {name: count_records(result, name)
|
|
717
|
+
for name in ("Device", "Interfaces", "IpAddress", "RouteStatics",
|
|
718
|
+
"VpnInstances", "Bgp", "BgpPeers", "Acls", "AclRules",
|
|
719
|
+
"Nqas", "NqaSessions", "EthTrunkMember")}
|
|
720
|
+
|
|
721
|
+
|
|
722
|
+
def build_template(colls):
|
|
723
|
+
return {"collections": [c.name for c in colls],
|
|
724
|
+
"paths": sorted("%s.%s" % (c.name, path) for c in colls for path in c.all_fields)}
|
|
725
|
+
|
|
726
|
+
|
|
727
|
+
def count_category_records(value, category):
|
|
728
|
+
"""实际记录数;只看以该集合名为键的 list/dict 元素,不把容器自身算记录。"""
|
|
729
|
+
total = 0
|
|
730
|
+
if isinstance(value, dict):
|
|
731
|
+
for key, child in value.items():
|
|
732
|
+
if key == category:
|
|
733
|
+
if isinstance(child, list):
|
|
734
|
+
total += len(child)
|
|
735
|
+
elif isinstance(child, dict):
|
|
736
|
+
total += 1
|
|
737
|
+
if isinstance(child, (dict, list)):
|
|
738
|
+
total += count_category_records(child, category)
|
|
739
|
+
elif isinstance(value, list):
|
|
740
|
+
for child in value:
|
|
741
|
+
total += count_category_records(child, category)
|
|
742
|
+
return total
|
|
743
|
+
|
|
744
|
+
|
|
745
|
+
def capability(np_fields, inc_fields, category_counts, colls):
|
|
746
|
+
matched = {"Name": "name", "Description": "description", "IpAddress": "IP", "IpBindingVpn": "vpn"}
|
|
747
|
+
same = ["Device↔device", "Interfaces↔interfaces", "RouteStatics↔route-static"]
|
|
748
|
+
diff = ["IpAddress↔interfaces[].IP", "VpnInstances↔interfaces[].vpn"]
|
|
749
|
+
return {
|
|
750
|
+
"interface_level_fields": {
|
|
751
|
+
"_desc": "只统计接口记录直接子键,不含子集合内部字段;按业务语义对应。",
|
|
752
|
+
"matched": list(matched.values()), "only_incumbent": list(INTERFACE_INC),
|
|
753
|
+
"only_netparse": list(INTERFACE_NP),
|
|
754
|
+
"coverage": {"incumbent": 10, "netparse": 15, "matched": 4,
|
|
755
|
+
"only_netparse": 11, "only_incumbent": 6},
|
|
756
|
+
"observed_incumbent_fields": sorted(inc_fields), "observed_netparse_fields": sorted(np_fields),
|
|
757
|
+
"content_correspondence_diff_shape": [{"incumbent": "VLAN", "netparse": "UserVlan",
|
|
758
|
+
"note": "内容对应、结构不同;仅搬运已捕获 UserVlan,不合成 type/QinQ/dot1q"}],
|
|
759
|
+
},
|
|
760
|
+
"collection_level_fields": {
|
|
761
|
+
"qos_profile_top": {"incumbent": "list[{name,in:{cir},out:{cir}}]", "netparse": None,
|
|
762
|
+
"note": "模板无任何 qos-profile 规则"},
|
|
763
|
+
"route_static": {"incumbent": "{IPV4:[{dest,mask,interface?,nexthop,vpn}], IPV6:[...]}",
|
|
764
|
+
"netparse": "list[{Prefix,Mask,NextHop,NextHopIface,VpnInstance,...}]",
|
|
765
|
+
"after_fix": "NextHopIface 已补齐;IPv6 route-static 仍未覆盖"},
|
|
766
|
+
},
|
|
767
|
+
"asset_categories": {
|
|
768
|
+
"_taxonomy": {"shared_same_shape": same, "shared_diff_shape": diff,
|
|
769
|
+
"netparse_only": list(CATEGORIES), "incumbent_only": ["qos-profile(顶层命名空间定义)"]},
|
|
770
|
+
"incumbent": {"total_categories": 4, "shared_same_shape": 3, "shared_diff_shape": 0, "only": 1,
|
|
771
|
+
"list": ["device", "interfaces", "route-static", "qos-profile"]},
|
|
772
|
+
"netparse": {"total_categories": 12, "shared_same_shape": 3, "shared_diff_shape": 2, "only": 7,
|
|
773
|
+
"list": ["Device", "Interfaces", "IpAddress", "EthTrunkMember", "RouteStatics",
|
|
774
|
+
"VpnInstances", "Bgp", "BgpPeers", "Acls", "AclRules", "Nqas", "NqaSessions"]},
|
|
775
|
+
"netparse_only_instances": [{"category": k, "instances": category_counts[k]} for k in CATEGORIES],
|
|
776
|
+
},
|
|
777
|
+
"extra_value_note": "netparse 多出的11个接口直接字段不在19列台账内,可用于MTU/速率/双工/管理状态/聚合成员/ISIS等CI建模;不能抵消台账缺口。",
|
|
778
|
+
"declared_template": colls,
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
def roots_check():
|
|
783
|
+
missing = [p for p in READONLY_ROOTS if not os.path.isdir(p)]
|
|
784
|
+
if missing:
|
|
785
|
+
raise RuntimeError("只读目录不存在:" + repr(missing))
|
|
786
|
+
proc = subprocess.run([sys.executable, "-m", "netparse.cli.readonly", "--verify"],
|
|
787
|
+
capture_output=True, text=True)
|
|
788
|
+
if proc.returncode:
|
|
789
|
+
raise RuntimeError("只读校验失败:\n" + proc.stdout + proc.stderr)
|
|
790
|
+
return {"status": "OK", "checked_paths": READONLY_ROOTS, "message": "READ-ONLY OK"}
|
|
791
|
+
|
|
792
|
+
|
|
793
|
+
def git_commit(path, fallback="WORKTREE"):
|
|
794
|
+
try:
|
|
795
|
+
out = subprocess.check_output(["git", "-C", ROOT, "log", "-1", "--format=%H", "--", path],
|
|
796
|
+
text=True, stderr=subprocess.DEVNULL).strip()
|
|
797
|
+
return out or fallback
|
|
798
|
+
except (OSError, subprocess.CalledProcessError):
|
|
799
|
+
return fallback
|
|
800
|
+
|
|
801
|
+
|
|
802
|
+
def file_sha1(path):
|
|
803
|
+
digest = hashlib.sha1()
|
|
804
|
+
with open(path, "rb") as f:
|
|
805
|
+
for block in iter(lambda: f.read(1024 * 1024), b""):
|
|
806
|
+
digest.update(block)
|
|
807
|
+
return digest.hexdigest()
|
|
808
|
+
|
|
809
|
+
|
|
810
|
+
def scan_secret_values(value, path="$", hits=None):
|
|
811
|
+
hits = [] if hits is None else hits
|
|
812
|
+
if isinstance(value, dict):
|
|
813
|
+
for key, val in value.items():
|
|
814
|
+
scan_secret_values(val, path + "." + str(key), hits)
|
|
815
|
+
elif isinstance(value, list):
|
|
816
|
+
for i, val in enumerate(value):
|
|
817
|
+
scan_secret_values(val, "%s[%d]" % (path, i), hits)
|
|
818
|
+
elif isinstance(value, str):
|
|
819
|
+
for i, pattern in enumerate(SECRET_SHAPE_PATTERNS):
|
|
820
|
+
if i == 1:
|
|
821
|
+
# 与引擎完全同一判定入口,避免报告扫描规则漂移。
|
|
822
|
+
if is_secret_shape(value):
|
|
823
|
+
hits.append({"path": path, "start": 0, "end": len(value)})
|
|
824
|
+
continue
|
|
825
|
+
for match in pattern.finditer(value):
|
|
826
|
+
hits.append({"path": path, "start": match.start(), "end": match.end()})
|
|
827
|
+
return hits
|
|
828
|
+
|
|
829
|
+
|
|
830
|
+
def safe_write(path, text, data=None):
|
|
831
|
+
if data is not None:
|
|
832
|
+
hits = scan_secret_values(data)
|
|
833
|
+
elif path.endswith(".json"):
|
|
834
|
+
hits = scan_secret_values(json.loads(text))
|
|
835
|
+
else:
|
|
836
|
+
hits = [{"path": "$text", "start": m.start(), "end": m.end()}
|
|
837
|
+
for pattern in SECRET_SHAPE_PATTERNS[:1] for m in pattern.finditer(text)]
|
|
838
|
+
if hits:
|
|
839
|
+
if os.path.exists(path):
|
|
840
|
+
os.unlink(path)
|
|
841
|
+
raise RuntimeError("报告明文形态扫描失败(仅报告位置,不回显内容):%r" % hits[:10])
|
|
842
|
+
with open(path, "w", encoding="utf-8", newline="\n") as f:
|
|
843
|
+
f.write(text)
|
|
844
|
+
with open(path, encoding="utf-8") as f:
|
|
845
|
+
written = f.read()
|
|
846
|
+
if path.endswith(".json"):
|
|
847
|
+
verify_hits = scan_secret_values(json.loads(written))
|
|
848
|
+
else:
|
|
849
|
+
verify_hits = [m for pattern in SECRET_SHAPE_PATTERNS[:1] for m in pattern.finditer(written)]
|
|
850
|
+
if verify_hits:
|
|
851
|
+
os.unlink(path)
|
|
852
|
+
raise RuntimeError("写盘后密文扫描失败,已删除:" + path)
|
|
853
|
+
|
|
854
|
+
|
|
855
|
+
def side_stats(stats, side, column):
|
|
856
|
+
total = stats[side]["total"]
|
|
857
|
+
filled = stats[side]["filled"][column]
|
|
858
|
+
return {"filled": filled, "total": total, "rate": round(filled / total, 6) if total else 0}
|
|
859
|
+
|
|
860
|
+
|
|
861
|
+
def file_summary(entry, stats):
|
|
862
|
+
return {"file": entry["stem"], "month": entry["month"],
|
|
863
|
+
"columns": {col: {side: side_stats(stats, side, col) for side in SIDES} for col in COLUMNS}}
|
|
864
|
+
|
|
865
|
+
|
|
866
|
+
def diagnose_cell(buckets, classifier):
|
|
867
|
+
"""一列一侧的诊断入口:兼容单份证据(旧调用)与分桶证据(新采集)。"""
|
|
868
|
+
if not buckets:
|
|
869
|
+
return {"root_cause": ["待人工判定"], "evidence_status": "INSUFFICIENT",
|
|
870
|
+
"reason": "本列无任何可定位的真实行/模板声明/trace 证据", "groups": [], "evidence": None}
|
|
871
|
+
if "input" in buckets or "trace" in buckets: # 单份证据
|
|
872
|
+
verdict = classifier(buckets)
|
|
873
|
+
verdict.setdefault("groups", [])
|
|
874
|
+
return verdict
|
|
875
|
+
return group_diagnoses(buckets, classifier)
|
|
876
|
+
|
|
877
|
+
|
|
878
|
+
def summary(stats, evidence_by_side=None, surplus_by_side=None):
|
|
879
|
+
evidence_by_side = evidence_by_side or {}
|
|
880
|
+
surplus_by_side = surplus_by_side or {}
|
|
881
|
+
columns = {}
|
|
882
|
+
for col in COLUMNS:
|
|
883
|
+
sides = {side: side_stats(stats, side, col) for side in SIDES}
|
|
884
|
+
values = {side: stats[side]["values"][col] for side in SIDES}
|
|
885
|
+
deltas = {side: round(100 * abs(values["incumbent"] - values[side]) / values["incumbent"], 2)
|
|
886
|
+
if values["incumbent"] else (0 if values[side] == 0 else 100) for side in SIDES[1:]}
|
|
887
|
+
red = any(value > 20 for value in deltas.values())
|
|
888
|
+
diagnoses, surplus = {}, {}
|
|
889
|
+
for side in SIDES[1:]:
|
|
890
|
+
short = (stats[side]["filled"][col] < stats["incumbent"]["filled"][col] or
|
|
891
|
+
stats[side]["values"][col] < stats["incumbent"]["values"][col] or
|
|
892
|
+
stats[side]["total"] < stats["incumbent"]["total"])
|
|
893
|
+
over = (stats[side]["filled"][col] > stats["incumbent"]["filled"][col] or
|
|
894
|
+
stats[side]["values"][col] > stats["incumbent"]["values"][col])
|
|
895
|
+
diagnoses[side] = diagnose_cell(evidence_by_side.get(side, {}).get(col), classify_gap) if short \
|
|
896
|
+
else {"root_cause": [], "evidence_status": "NOT_APPLICABLE", "evidence": None, "groups": []}
|
|
897
|
+
# 正差异也必须被诊断:netparse 多出值时不能只把它标红就完事。
|
|
898
|
+
surplus[side] = diagnose_cell(surplus_by_side.get(side, {}).get(col), classify_surplus) if over \
|
|
899
|
+
else {"root_cause": [], "evidence_status": "NOT_APPLICABLE", "evidence": None, "groups": []}
|
|
900
|
+
directions = []
|
|
901
|
+
for side in SIDES[1:]:
|
|
902
|
+
if values[side] < values["incumbent"]:
|
|
903
|
+
directions.append("%s:netparse少" % side)
|
|
904
|
+
elif values[side] > values["incumbent"]:
|
|
905
|
+
directions.append("%s:netparse多" % side)
|
|
906
|
+
columns[col] = dict(sides,
|
|
907
|
+
global_values=values, delta_pct_before=deltas["netparse_before_fix"],
|
|
908
|
+
delta_pct_after=deltas["netparse_after_fix"], flag="RED" if red else "OK",
|
|
909
|
+
flag_reason="修前或修后全局值条数差 > 20%%;方向:%s" % ("、".join(directions) or "无") if red
|
|
910
|
+
else "三侧全局值条数差均不超过20%",
|
|
911
|
+
per_file_resolvable=not all(sides[side]["rate"] < .01 for side in SIDES),
|
|
912
|
+
note="本列逐文件差异不具分辨力,请以全局值条数为准" if all(sides[side]["rate"] < .01 for side in SIDES) else "",
|
|
913
|
+
diagnoses=diagnoses, surplus=surplus, required_field=REQUIRED_FIELDS.get(col),
|
|
914
|
+
both_nonempty_diff=stats["incumbent"]["both_nonempty_diff"][col])
|
|
915
|
+
return columns
|
|
916
|
+
|
|
917
|
+
|
|
918
|
+
def markdown(report):
|
|
919
|
+
meta, ledger = report["meta"], report["part1_ledger"]
|
|
920
|
+
columns = ledger["column_fill_rate"]
|
|
921
|
+
lines = ["# netparse 与 incumbent 配置解析差异报告", "",
|
|
922
|
+
"> 文件:%d;模式:%s;抽样种子 %s。三侧均复用生产 build_excel.build_rows。" %
|
|
923
|
+
(meta["files_processed"], meta["mode"], meta.get("sample_seed")), "",
|
|
924
|
+
"## 全局19列三栏(填充率 / 非空单元格值条数)", "",
|
|
925
|
+
"| 列 | incumbent | 修前 | 修后 | 全局值条数 inc/before/after | 修前差 | 修后差 | 标记 | 修后缺口根因 | 修后多值根因 |",
|
|
926
|
+
"|---|---:|---:|---:|---:|---:|---:|---|---|---|"]
|
|
927
|
+
notes = []
|
|
928
|
+
for col in COLUMNS:
|
|
929
|
+
c = columns[col]
|
|
930
|
+
rates = ["%.2f%%" % (100 * c[s]["rate"]) for s in SIDES]
|
|
931
|
+
values = " / ".join(str(c["global_values"][s]) for s in SIDES)
|
|
932
|
+
causes = "、".join(c["diagnoses"]["netparse_after_fix"]["root_cause"]) or "—"
|
|
933
|
+
over = "、".join(c["surplus"]["netparse_after_fix"]["root_cause"]) or "—"
|
|
934
|
+
lines.append("| %s | %s | %s | %s | %s | %.2f%% | %.2f%% | %s | %s | %s |" %
|
|
935
|
+
(col, rates[0], rates[1], rates[2], values, c["delta_pct_before"],
|
|
936
|
+
c["delta_pct_after"], "**RED**" if c["flag"] == "RED" else "OK", causes, over))
|
|
937
|
+
if c["note"]:
|
|
938
|
+
# 表格里插 colspan 单元格会破坏 Markdown 列对齐(标准 Markdown 不支持 colspan),
|
|
939
|
+
# 所以备注放到表下方的脚注区,用列名索引。
|
|
940
|
+
notes.append("- **%s**:%s" % (col, c["note"]))
|
|
941
|
+
lines += ["", "逐文件19列三栏保存在JSON `per_file_column_fill_rate`;每文件结构为 file/month/columns。", ""]
|
|
942
|
+
if notes:
|
|
943
|
+
lines += ["**列备注:**", ""] + notes + [""]
|
|
944
|
+
lines += ["## 根因证据门禁", "",
|
|
945
|
+
"自动根因必须有真实文件/行号、模板声明(含候选集合与规则)和真实 trace 规则复核;"
|
|
946
|
+
"不足为 `待人工判定 + INSUFFICIENT`。join缺失单列且先证明原始字段已捕获。"
|
|
947
|
+
"netparse 多出值同样单独诊断方向,不只标红。", "",
|
|
948
|
+
"```json", json.dumps({col: {"gap": c["diagnoses"], "surplus": c["surplus"]}
|
|
949
|
+
for col, c in columns.items()
|
|
950
|
+
if any(c["diagnoses"][s]["root_cause"] or c["surplus"][s]["root_cause"]
|
|
951
|
+
for s in SIDES[1:])}, ensure_ascii=False, indent=2), "```", "",
|
|
952
|
+
"## 静态路由修前/修后(两组口径不混算)", "", "```json",
|
|
953
|
+
json.dumps(report["route_static_validation"], ensure_ascii=False, indent=2), "```", "",
|
|
954
|
+
"## 接口与双向能力覆盖", ""]
|
|
955
|
+
cov = report["part2_capability"]["interface_level_fields"]["coverage"]
|
|
956
|
+
lines += ["- 接口 join(修后):both=%d / only_incumbent=%d / only_netparse=%d。" %
|
|
957
|
+
(ledger["interface_alignment"]["both"], ledger["interface_alignment"]["only_incumbent"], ledger["interface_alignment"]["only_netparse"]),
|
|
958
|
+
"- 接口直接子键:netparse=%d / incumbent=%d / 共有=%d / netparse独有=%d / incumbent独有=%d。" %
|
|
959
|
+
(cov["netparse"], cov["incumbent"], cov["matched"], cov["only_netparse"], cov["only_incumbent"]),
|
|
960
|
+
"- VLAN ↔ UserVlan:内容对应、结构不同,单列而非内容完全缺失。",
|
|
961
|
+
"- 资产:netparse 12类=共有结构同3+共有结构不同2+真正独有7;incumbent 4类=共有3+独有1。", "",
|
|
962
|
+
"## 差异样本", ""]
|
|
963
|
+
for col in COLUMNS:
|
|
964
|
+
samples = ledger["diff_samples"].get(col, [])
|
|
965
|
+
if samples:
|
|
966
|
+
lines += ["### " + col, "", "```json", json.dumps(samples[:3], ensure_ascii=False, indent=2), "```", ""]
|
|
967
|
+
lines += ["## 工作量与结论", "", "```json", json.dumps(report["workload_estimate"], ensure_ascii=False, indent=2), "```", "",
|
|
968
|
+
report["conclusion"], "", "## 复现锚点", "", "```json", json.dumps(report["repro"], ensure_ascii=False, indent=2), "```", "",
|
|
969
|
+
"只读校验:**%s**。" % report["readonly_check"]["message"]]
|
|
970
|
+
return "\n".join(lines) + "\n"
|
|
971
|
+
|
|
972
|
+
|
|
973
|
+
def process_entry(entry, ctx):
|
|
974
|
+
"""对单个文件跑三侧对比,只返回「可合并的局部结果」,不碰全局累积器。
|
|
975
|
+
|
|
976
|
+
抽成纯函数是为了能多进程并行:子进程之间不能共享 Counter/defaultdict,
|
|
977
|
+
必须把每文件的产物整体传回主进程,再按原始顺序合并 —— 顺序固定才能保证
|
|
978
|
+
--jobs N 与 --jobs 1 的产物逐字节一致(证据采样是「先到先留」的)。
|
|
979
|
+
"""
|
|
980
|
+
incumbent = read_json(entry["json"])
|
|
981
|
+
inc_rows = load_build_excel().build_rows(entry["json"])
|
|
982
|
+
with open(entry["raw"], encoding="utf-8", errors="replace") as f:
|
|
983
|
+
lines = f.readlines()
|
|
984
|
+
results, np_rows, traces, masks = [], [], [], collections.Counter()
|
|
985
|
+
collection_counts_per_template = []
|
|
986
|
+
evidence_local = {side: collections.defaultdict(dict) for side in SIDES[1:]}
|
|
987
|
+
surplus_local = {side: collections.defaultdict(dict) for side in SIDES[1:]}
|
|
988
|
+
for template_index, colls in enumerate(ctx["templates"]):
|
|
989
|
+
trace = []
|
|
990
|
+
result = engine.run(colls, lines, trace=trace)
|
|
991
|
+
masks.update(engine.STATS.as_dict()) # 每次run都reset,必须逐次累加
|
|
992
|
+
results.append(result)
|
|
993
|
+
traces.append(trace)
|
|
994
|
+
shaped = to_incumbent_shape(result)
|
|
995
|
+
# ⚠️ 必须保留原文件名:生产 build_excel 的「采集时间」取自文件名末尾时间戳,
|
|
996
|
+
# 用随机临时名会让该列整列为空(曾导致 both_nonempty_diff 从 3134 掉到 0)。
|
|
997
|
+
# 并行安全靠「每进程一个独立临时目录」保证,不靠改文件名。
|
|
998
|
+
path = os.path.join(ctx["tmp_dir"], entry["stem"] + ".json")
|
|
999
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
1000
|
+
json.dump(shaped, f, ensure_ascii=False)
|
|
1001
|
+
try:
|
|
1002
|
+
np_rows.append(load_build_excel().build_rows(path))
|
|
1003
|
+
finally:
|
|
1004
|
+
os.unlink(path)
|
|
1005
|
+
counts_now = collection_record_counts(result)
|
|
1006
|
+
# ⚠️ 这里只记录 trace 与记录数;缺口证据留到 compare_three 之后再采。
|
|
1007
|
+
# 先采会犯「该文件这一列根本没有缺口,却仍挑一条正常命中行当缺口证据」的错,
|
|
1008
|
+
# 这种证据必然归不进任何根因,只会把整列拖成 INSUFFICIENT
|
|
1009
|
+
# (实测 VPN 实例:`ip binding vpn-instance __dcn_vpn__` 两侧都正常捕获)。
|
|
1010
|
+
collection_counts_per_template.append(counts_now)
|
|
1011
|
+
samples = {col: [] for col in COLUMNS}
|
|
1012
|
+
part, both, only_inc, only_np, _ = compare_three(inc_rows, np_rows[0], np_rows[1], samples)
|
|
1013
|
+
# 缺口证据只对「该文件这一列确实比 incumbent 少」的侧采集。
|
|
1014
|
+
for side, template_index in zip(SIDES[1:], (0, 1)):
|
|
1015
|
+
traces_i = traces[template_index]
|
|
1016
|
+
counts_now = collection_counts_per_template[template_index]
|
|
1017
|
+
for col_index, col in enumerate(COLUMNS):
|
|
1018
|
+
if part[side]["filled"][col] >= part["incumbent"]["filled"][col]:
|
|
1019
|
+
continue
|
|
1020
|
+
ev = evidence_for(entry, traces_i, ctx["declarations"][template_index][col_index],
|
|
1021
|
+
col, ctx["compiled"][template_index], counts_now)
|
|
1022
|
+
if col == "IPv4静态路由明细" and template_index == 0:
|
|
1023
|
+
route_ev = route_record_loss_evidence(
|
|
1024
|
+
entry, incumbent, results[template_index], traces_i,
|
|
1025
|
+
ctx["declarations"][0][col_index], ctx["compiled"][0], counts_now)
|
|
1026
|
+
if route_ev:
|
|
1027
|
+
add_evidence(evidence_local[side][col], route_ev)
|
|
1028
|
+
if evidence_complete(ev):
|
|
1029
|
+
add_evidence(evidence_local[side][col], ev)
|
|
1030
|
+
# 正差异(netparse 多出)也要有真实行证据,不能只标红。
|
|
1031
|
+
for side, template_index in zip(SIDES[1:], (0, 1)):
|
|
1032
|
+
for col_index, col in enumerate(COLUMNS):
|
|
1033
|
+
if part[side]["values"][col] <= part["incumbent"]["values"][col]:
|
|
1034
|
+
continue
|
|
1035
|
+
ev = surplus_evidence(entry, traces[template_index],
|
|
1036
|
+
ctx["declarations"][template_index][col_index], col,
|
|
1037
|
+
ctx["compiled"][template_index],
|
|
1038
|
+
collection_record_counts(results[template_index]))
|
|
1039
|
+
if ev:
|
|
1040
|
+
add_evidence(surplus_local[side][col], ev)
|
|
1041
|
+
counts = [len(inc_rows), len(np_rows[0]), len(np_rows[1])]
|
|
1042
|
+
mismatch = None
|
|
1043
|
+
if counts[0] != counts[2]:
|
|
1044
|
+
mismatch = {"file": entry["stem"], "counts": counts,
|
|
1045
|
+
"only_incumbent": sorted(set(index_rows(inc_rows)) - set(index_rows(np_rows[1]))),
|
|
1046
|
+
"only_netparse": sorted(set(index_rows(np_rows[1])) - set(index_rows(inc_rows)))}
|
|
1047
|
+
categories = collections.Counter()
|
|
1048
|
+
for cat in CATEGORIES:
|
|
1049
|
+
categories[cat] += count_category_records(results[1], cat)
|
|
1050
|
+
return {
|
|
1051
|
+
"entry": {"stem": entry["stem"], "month": entry["month"]},
|
|
1052
|
+
"part": part, "samples": samples,
|
|
1053
|
+
"both": both, "only_inc": only_inc, "only_np": only_np,
|
|
1054
|
+
"evidence": {side: {col: dict(evidence_local[side][col]) for col in COLUMNS} for side in SIDES[1:]},
|
|
1055
|
+
"surplus": {side: {col: dict(surplus_local[side][col]) for col in COLUMNS} for side in SIDES[1:]},
|
|
1056
|
+
"masks": dict(masks), "mismatch": mismatch, "counts": counts,
|
|
1057
|
+
"inc_fields": sorted({k for it in incumbent.get("interfaces", []) for k in it}),
|
|
1058
|
+
"np_fields": sorted({k for it in results[1].get("Interfaces", []) for k in it}),
|
|
1059
|
+
"categories": dict(categories),
|
|
1060
|
+
"route": {label: dict(loss) for label, loss in
|
|
1061
|
+
route_loss(incumbent, dict(zip(SIDES[1:], results))).items()},
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
|
|
1065
|
+
def merge_entry(state, payload):
|
|
1066
|
+
"""把单文件结果按顺序并回全局累积器;合并逻辑与并行度无关。"""
|
|
1067
|
+
entry = payload["entry"]
|
|
1068
|
+
add_stats(state["stats"], payload["part"])
|
|
1069
|
+
for col, items in payload["samples"].items():
|
|
1070
|
+
bucket = state["samples"][col]
|
|
1071
|
+
for item in items:
|
|
1072
|
+
if len(bucket) < 20:
|
|
1073
|
+
bucket.append(item)
|
|
1074
|
+
state["per_file"].append(file_summary(entry, payload["part"]))
|
|
1075
|
+
for side in SIDES[1:]:
|
|
1076
|
+
for col in COLUMNS:
|
|
1077
|
+
for signature, samples in payload["evidence"][side][col].items():
|
|
1078
|
+
for sample in samples:
|
|
1079
|
+
add_evidence(state["evidence_acc"][side][col], sample)
|
|
1080
|
+
for signature, samples in payload["surplus"][side][col].items():
|
|
1081
|
+
for sample in samples:
|
|
1082
|
+
add_evidence(state["surplus_acc"][side][col], sample)
|
|
1083
|
+
for target, index in zip((state["align_before"], state["align"]), (1, 2)):
|
|
1084
|
+
target["both"] += payload["both"][index]
|
|
1085
|
+
target["only_incumbent"] += payload["only_inc"][index - 1]
|
|
1086
|
+
target["only_netparse"] += payload["only_np"][index - 1]
|
|
1087
|
+
if payload["mismatch"]:
|
|
1088
|
+
state["parity"]["files_mismatched"] += 1
|
|
1089
|
+
state["parity"]["mismatches"].append(payload["mismatch"])
|
|
1090
|
+
else:
|
|
1091
|
+
state["parity"]["files_matched"] += 1
|
|
1092
|
+
state["masks"].update(payload["masks"])
|
|
1093
|
+
state["inc_fields"].update(payload["inc_fields"])
|
|
1094
|
+
state["np_fields"].update(payload["np_fields"])
|
|
1095
|
+
for cat, count in payload["categories"].items():
|
|
1096
|
+
state["categories"][cat] += count
|
|
1097
|
+
for label, loss in payload["route"].items():
|
|
1098
|
+
state["route"][label].update(loss)
|
|
1099
|
+
|
|
1100
|
+
|
|
1101
|
+
def _worker_init(ctx):
|
|
1102
|
+
"""子进程初始化:装上下文 + 忽略 Ctrl-C(由主进程统一收尾)。
|
|
1103
|
+
|
|
1104
|
+
Windows 走 spawn,子进程不会继承父进程模块状态,必须显式传 ctx;
|
|
1105
|
+
fork 下这样写也等价,所以两边用同一条路径。
|
|
1106
|
+
"""
|
|
1107
|
+
_WORKER_CTX["ctx"] = ctx
|
|
1108
|
+
try:
|
|
1109
|
+
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
|
1110
|
+
except (AttributeError, ValueError):
|
|
1111
|
+
pass
|
|
1112
|
+
|
|
1113
|
+
|
|
1114
|
+
_WORKER_CTX = {}
|
|
1115
|
+
|
|
1116
|
+
|
|
1117
|
+
def _worker_task(entry):
|
|
1118
|
+
try:
|
|
1119
|
+
# 每进程一个临时目录:文件名必须保留原 stem(采集时间来自文件名),
|
|
1120
|
+
# 又不能跨进程互相覆盖同名产物,所以按进程隔离目录而非改文件名。
|
|
1121
|
+
if "tmp_dir" not in _WORKER_CTX:
|
|
1122
|
+
_WORKER_CTX["tmp_dir"] = tempfile.mkdtemp(prefix="netparse-worker-")
|
|
1123
|
+
_WORKER_CTX["ctx"]["tmp_dir"] = _WORKER_CTX["tmp_dir"]
|
|
1124
|
+
return {"ok": True, "payload": process_entry(entry, _WORKER_CTX["ctx"])}
|
|
1125
|
+
except Exception as exc:
|
|
1126
|
+
return {"ok": False, "failure": {"file": entry["stem"], "raw": entry["raw"],
|
|
1127
|
+
"error": "%s: %s" % (type(exc).__name__, exc)}}
|
|
1128
|
+
|
|
1129
|
+
|
|
1130
|
+
def _run_entries(args, selected, state, failures, ctx):
|
|
1131
|
+
"""按顺序处理所有文件;jobs=1 走内联,jobs>1 走进程池但同样按序回放。
|
|
1132
|
+
|
|
1133
|
+
顺序是报告可复现性的一部分:证据分桶是「先到先留」,采样也是先到先留,
|
|
1134
|
+
乱序合并会让同一批语料产出不同的证据样本。
|
|
1135
|
+
"""
|
|
1136
|
+
jobs = max(1, min(args.jobs or 1, len(selected) or 1))
|
|
1137
|
+
|
|
1138
|
+
def record(i, outcome):
|
|
1139
|
+
if outcome["ok"]:
|
|
1140
|
+
merge_entry(state, outcome["payload"])
|
|
1141
|
+
else:
|
|
1142
|
+
failures.append(outcome["failure"])
|
|
1143
|
+
if i % 10 == 0 or i == len(selected):
|
|
1144
|
+
print("%d/%d;失败 %d;耗时 %.1fs" % (i, len(selected), len(failures),
|
|
1145
|
+
time.time() - args.started), flush=True)
|
|
1146
|
+
|
|
1147
|
+
if jobs == 1:
|
|
1148
|
+
for i, entry in enumerate(selected, 1):
|
|
1149
|
+
try:
|
|
1150
|
+
outcome = {"ok": True, "payload": process_entry(entry, ctx)}
|
|
1151
|
+
except Exception as exc:
|
|
1152
|
+
outcome = {"ok": False, "failure": {"file": entry["stem"], "raw": entry["raw"],
|
|
1153
|
+
"error": "%s: %s" % (type(exc).__name__, exc)}}
|
|
1154
|
+
record(i, outcome)
|
|
1155
|
+
if len(failures) > args.max_failures:
|
|
1156
|
+
break
|
|
1157
|
+
return
|
|
1158
|
+
|
|
1159
|
+
import multiprocessing
|
|
1160
|
+
pool = multiprocessing.Pool(jobs, initializer=_worker_init, initargs=(ctx,))
|
|
1161
|
+
try:
|
|
1162
|
+
for i, outcome in enumerate(pool.imap(_worker_task, selected, chunksize=1), 1):
|
|
1163
|
+
record(i, outcome)
|
|
1164
|
+
if len(failures) > args.max_failures:
|
|
1165
|
+
pool.terminate()
|
|
1166
|
+
break
|
|
1167
|
+
except KeyboardInterrupt:
|
|
1168
|
+
pool.terminate()
|
|
1169
|
+
raise
|
|
1170
|
+
finally:
|
|
1171
|
+
pool.close()
|
|
1172
|
+
pool.join()
|
|
1173
|
+
# 子进程的临时目录不随父进程 TemporaryDirectory 回收,必须自己扫掉。
|
|
1174
|
+
for name in os.listdir(tempfile.gettempdir()):
|
|
1175
|
+
if not name.startswith("netparse-worker-"):
|
|
1176
|
+
continue
|
|
1177
|
+
path = os.path.join(tempfile.gettempdir(), name)
|
|
1178
|
+
if not os.path.isdir(path):
|
|
1179
|
+
continue
|
|
1180
|
+
for leftover in os.listdir(path):
|
|
1181
|
+
if leftover.endswith(".json"):
|
|
1182
|
+
os.unlink(os.path.join(path, leftover))
|
|
1183
|
+
if not os.listdir(path):
|
|
1184
|
+
os.rmdir(path)
|
|
1185
|
+
|
|
1186
|
+
|
|
1187
|
+
def run_diff(args, idx, entries):
|
|
1188
|
+
candidates = select_entries(entries, None, args.month)
|
|
1189
|
+
selected = select_entries(entries, args.sample, args.month, args.sample_seed)
|
|
1190
|
+
sample_info = sampling_meta(candidates, selected, args.sample, args.sample_seed)
|
|
1191
|
+
print("索引 %d;候选 %d;本次 %d;月份 %d" % (idx["file_count"], len(candidates), len(selected), len(sample_info["months_covered"])), flush=True)
|
|
1192
|
+
if args.dry_run:
|
|
1193
|
+
return {"status": "OK", "index_total": idx["file_count"], "mapped": len(entries),
|
|
1194
|
+
"candidate_files": len(candidates), "roots": READONLY_ROOTS, "sampling": sample_info}
|
|
1195
|
+
# 报告里记录**相对仓库根**的路径,不写绝对路径 ——
|
|
1196
|
+
# 绝对路径带用户名/盘符,换机器就失效,而且让人误以为结果不可复现。
|
|
1197
|
+
template_paths = [rel(BASELINE), rel(args.template)]
|
|
1198
|
+
templates = [engine.parse_template(os.path.join(ROOT, p)) for p in template_paths]
|
|
1199
|
+
lint_errors = [issue for colls in templates for issue in engine.lint(colls) if issue[0] == "错误"]
|
|
1200
|
+
if lint_errors:
|
|
1201
|
+
raise RuntimeError("模板 lint 失败:" + repr(lint_errors[:20]))
|
|
1202
|
+
compiled_templates = [compile_rules(colls) for colls in templates]
|
|
1203
|
+
declarations = [[template_declaration(path, colls, col) for col in COLUMNS]
|
|
1204
|
+
for path, colls in zip(template_paths, templates)]
|
|
1205
|
+
state = {"stats": zero_stats(), "samples": {col: [] for col in COLUMNS},
|
|
1206
|
+
# 分桶:每列每侧按「命令族+命中规则」归组,每组成因各带自己的证据。
|
|
1207
|
+
"evidence_acc": {side: collections.defaultdict(dict) for side in SIDES[1:]},
|
|
1208
|
+
"surplus_acc": {side: collections.defaultdict(dict) for side in SIDES[1:]},
|
|
1209
|
+
"align": {"both": 0, "only_incumbent": 0, "only_netparse": 0},
|
|
1210
|
+
"align_before": {"both": 0, "only_incumbent": 0, "only_netparse": 0},
|
|
1211
|
+
"parity": {"files_matched": 0, "files_mismatched": 0, "mismatches": []},
|
|
1212
|
+
"masks": collections.Counter(), "inc_fields": set(), "np_fields": set(),
|
|
1213
|
+
"categories": collections.Counter(),
|
|
1214
|
+
"route": collections.defaultdict(collections.Counter), "per_file": []}
|
|
1215
|
+
failures = []
|
|
1216
|
+
os.makedirs(args.out_dir, exist_ok=True)
|
|
1217
|
+
# 临时目录挂在 ctx 上:串行用一份,并行时各子进程各自建一份(见 _worker_task)。
|
|
1218
|
+
with tempfile.TemporaryDirectory(prefix="netparse-diff-") as tmp_dir:
|
|
1219
|
+
ctx = {"templates": templates, "compiled": compiled_templates,
|
|
1220
|
+
"declarations": declarations, "tmp_dir": tmp_dir}
|
|
1221
|
+
_run_entries(args, selected, state, failures, ctx)
|
|
1222
|
+
stats, samples = state["stats"], state["samples"]
|
|
1223
|
+
evidence_acc, surplus_acc = state["evidence_acc"], state["surplus_acc"]
|
|
1224
|
+
align, align_before, parity = state["align"], state["align_before"], state["parity"]
|
|
1225
|
+
masks, inc_fields, np_fields = state["masks"], state["inc_fields"], state["np_fields"]
|
|
1226
|
+
categories, route, per_file = state["categories"], state["route"], state["per_file"]
|
|
1227
|
+
# 证据已按成因分桶;这里只做浅拷贝,交给 summary 分组诊断。
|
|
1228
|
+
evidence = {side: {col: dict(evidence_acc[side][col]) for col in COLUMNS} for side in SIDES[1:]}
|
|
1229
|
+
surplus = {side: {col: dict(surplus_acc[side][col]) for col in COLUMNS} for side in SIDES[1:]}
|
|
1230
|
+
columns = summary(stats, evidence, surplus)
|
|
1231
|
+
global_counts = {col: dict(columns[col]["global_values"],
|
|
1232
|
+
delta_pct_before=columns[col]["delta_pct_before"], delta_pct_after=columns[col]["delta_pct_after"],
|
|
1233
|
+
flag=columns[col]["flag"], flag_reason=columns[col]["flag_reason"],
|
|
1234
|
+
per_file_resolvable=columns[col]["per_file_resolvable"], note=columns[col]["note"]) for col in COLUMNS}
|
|
1235
|
+
workload, pending, surplus_items = [], [], []
|
|
1236
|
+
for col in COLUMNS:
|
|
1237
|
+
c = columns[col]
|
|
1238
|
+
diagnosis = c["diagnoses"]["netparse_after_fix"]
|
|
1239
|
+
if c["netparse_after_fix"]["filled"] < c["incumbent"]["filled"] or c["both_nonempty_diff"]:
|
|
1240
|
+
item = {"column": col,
|
|
1241
|
+
"gap": "%d/%d" % (c["netparse_after_fix"]["filled"], c["incumbent"]["filled"]),
|
|
1242
|
+
"change": "templates/huawei-vrp.cmdb:" + (c.get("required_field") or "复核解析与业务口径"),
|
|
1243
|
+
"evidence_status": diagnosis["evidence_status"],
|
|
1244
|
+
"root_cause": diagnosis["root_cause"]}
|
|
1245
|
+
if diagnosis["evidence_status"] == "VERIFIED":
|
|
1246
|
+
item["effort_days"] = EFFORT.get(col, .5)
|
|
1247
|
+
item["note"] = "证据化模板补齐粗估,不含引擎正式化/跨厂商/CMDB接入"
|
|
1248
|
+
workload.append(item)
|
|
1249
|
+
else:
|
|
1250
|
+
item["effort_days"] = None
|
|
1251
|
+
item["note"] = "待诊断工作量;证据不足不套用自动人日常量"
|
|
1252
|
+
pending.append(item)
|
|
1253
|
+
over = c["surplus"]["netparse_after_fix"]
|
|
1254
|
+
if over["root_cause"]:
|
|
1255
|
+
# 多值不是「补模板」能修的,单独列,不混进补齐人日。
|
|
1256
|
+
surplus_items.append({"column": col, "direction": "netparse_more",
|
|
1257
|
+
"values_incumbent": c["global_values"]["incumbent"],
|
|
1258
|
+
"values_netparse_after_fix": c["global_values"]["netparse_after_fix"],
|
|
1259
|
+
"root_cause": over["root_cause"],
|
|
1260
|
+
"evidence_status": over["evidence_status"],
|
|
1261
|
+
"note": "netparse 多出值:属捕获范围/入表口径差异,需与 incumbent 对齐语义,不按模板补齐计人日"})
|
|
1262
|
+
effort_sum = sum(x["effort_days"] for x in workload)
|
|
1263
|
+
route_validation = {
|
|
1264
|
+
"latest_check_route_forms": {"command": "python tools/check_route_forms.py --sample 60",
|
|
1265
|
+
"files_consistent_after_fix": "60/60", "explicit_interface_routes_excluding_null0": 150,
|
|
1266
|
+
"before_lost": 150, "before_loss_pct": 100.0, "after_lost": 0},
|
|
1267
|
+
"previous_sample_historical_only": {"description": "60台/20250824/1651条;形态2出接口+下一跳",
|
|
1268
|
+
"routes": 75, "before_lost": 72, "loss_pct": 96.0, "note": "此前样本,不与最新150条混算"},
|
|
1269
|
+
"current_diff_corpus_route_loss": finalize_route_loss(route),
|
|
1270
|
+
}
|
|
1271
|
+
corpus_snapshots = [{"dir": key, "files": value} for key, value in sorted(collections.Counter(e["month"] for e in selected).items())]
|
|
1272
|
+
repro = {"command": "python tools/diff_incumbent.py %s --template %s --sample-seed %d" %
|
|
1273
|
+
("--all" if args.all else "--sample %s" % args.sample, rel(args.template), args.sample_seed),
|
|
1274
|
+
"command_baseline": "python tools/diff_incumbent.py %s --template .devforge/spec/changes/netparse-v3-diff-and-mask/baseline-template.cmdb --sample-seed %d" %
|
|
1275
|
+
("--all" if args.all else "--sample %s" % args.sample, args.sample_seed),
|
|
1276
|
+
"corpus_snapshots": corpus_snapshots, "corpus_total_files": len(selected),
|
|
1277
|
+
"git_commit_tool": git_commit("tools/diff_incumbent.py"),
|
|
1278
|
+
"git_commit_template_current": git_commit("templates/huawei-vrp.cmdb"),
|
|
1279
|
+
"git_commit_template_baseline": git_commit(".devforge/spec/changes/netparse-v3-diff-and-mask/baseline-template.cmdb"),
|
|
1280
|
+
"template_sha1": {rel(p): file_sha1(p)
|
|
1281
|
+
for p in (BASELINE, args.template)}}
|
|
1282
|
+
readonly = roots_check()
|
|
1283
|
+
report = {
|
|
1284
|
+
"meta": {"generated_at": datetime.datetime.now(datetime.timezone.utc).isoformat(), "incumbent_index": INDEX,
|
|
1285
|
+
"files_total": len(selected) if args.all else idx["file_count"],
|
|
1286
|
+
"files_selected": len(selected), "files_processed": len(selected) - len(failures), "files_failed": len(failures),
|
|
1287
|
+
"mode": "all" if args.all else "sample", "sample": args.sample, **sample_info,
|
|
1288
|
+
"elapsed_sec": round(time.time() - args.started, 3), "mask_value": engine.MASK_VALUE,
|
|
1289
|
+
"l1_hits": masks["l1_hits"], "l2_hits": masks["l2_hits"],
|
|
1290
|
+
"masking_note": "逐文件逐模板run后累加;L2高表示模板漏标secret"},
|
|
1291
|
+
"part1_ledger": {"_columns": COLUMNS, "column_fill_rate": columns,
|
|
1292
|
+
"per_file_column_fill_rate": per_file, "global_column_value_count": global_counts,
|
|
1293
|
+
"interface_alignment": align, "interface_alignment_before_fix": align_before,
|
|
1294
|
+
"interface_count_parity": parity, "diff_samples": {key: val for key, val in samples.items() if val}},
|
|
1295
|
+
"route_static_validation": route_validation,
|
|
1296
|
+
"part2_capability": capability(np_fields, inc_fields, categories, [build_template(c) for c in templates]),
|
|
1297
|
+
"repro": repro,
|
|
1298
|
+
"workload_estimate": {"per_column": workload, "pending_diagnosis": pending,
|
|
1299
|
+
"netparse_more_semantics": surplus_items,
|
|
1300
|
+
"total_effort_days": {"min": round(effort_sum, 2), "max": round(effort_sum * 1.5, 2)},
|
|
1301
|
+
"pending_diagnosis_count": len(pending),
|
|
1302
|
+
"compare_with_plan": {"final_plan_range": "68-104", "note": "只估算证据充分列的模板补齐;待诊断列不虚构人日;多值语义差异单列不计入"}},
|
|
1303
|
+
"conclusion": "台账缺口以19列三栏和工作量段为准;netparse 多出值(如 IPv6 自动地址)单列为语义/入表口径差异,不当作模板补齐项。netparse 真正独有7类资产、另有2类共有但结构不同,接口直接字段多11个;能力面并不更弱,不能只凭台账缺口决定路线。",
|
|
1304
|
+
"readonly_check": readonly, "failures": failures,
|
|
1305
|
+
}
|
|
1306
|
+
json_path = args.json_path or os.path.join(args.out_dir, "diff-report.json")
|
|
1307
|
+
md_path = args.markdown_path or os.path.join(args.out_dir, "diff-report.md")
|
|
1308
|
+
safe_write(json_path, json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
|
1309
|
+
safe_write(md_path, markdown(report))
|
|
1310
|
+
print("报告:%s\n %s" % (json_path, md_path))
|
|
1311
|
+
print("READ-ONLY OK:%s" % " / ".join(READONLY_ROOTS))
|
|
1312
|
+
print("处理 %d;失败 %d;L1 %d / L2 %d" % (report["meta"]["files_processed"], len(failures), masks["l1_hits"], masks["l2_hits"]))
|
|
1313
|
+
return 1 if failures else 0
|
|
1314
|
+
|
|
1315
|
+
|
|
1316
|
+
def add_arguments(parser):
|
|
1317
|
+
"""注册 diff 子命令参数(由 netparse.cli 主入口调用)。"""
|
|
1318
|
+
scope = parser.add_mutually_exclusive_group()
|
|
1319
|
+
scope.add_argument("--all", action="store_true", help="跑全量 8440 个文件")
|
|
1320
|
+
scope.add_argument("--sample", type=int, help="按分层抽样跑 N 个文件")
|
|
1321
|
+
parser.add_argument("--month", help="只跑某个快照月份")
|
|
1322
|
+
parser.add_argument("--template", default=CURRENT, help="修后模板;修前仍用 baseline-template.cmdb")
|
|
1323
|
+
parser.add_argument("--sample-seed", type=int, default=DEFAULT_SAMPLE_SEED)
|
|
1324
|
+
parser.add_argument("--out-dir", default=os.path.join(CHANGE, "diff-report", "latest"))
|
|
1325
|
+
parser.add_argument("--json", dest="json_path")
|
|
1326
|
+
parser.add_argument("--markdown", dest="markdown_path")
|
|
1327
|
+
parser.add_argument("--dry-run", action="store_true", help="只打印将要处理的范围,不真跑")
|
|
1328
|
+
parser.add_argument("--max-failures", type=int, default=0)
|
|
1329
|
+
parser.add_argument("--jobs", type=int, default=1,
|
|
1330
|
+
help="并行进程数;默认 1(串行)。结果与并行度无关,按提交顺序合并。")
|
|
1331
|
+
return parser
|
|
1332
|
+
|
|
1333
|
+
|
|
1334
|
+
def main(args):
|
|
1335
|
+
if not args.all and args.sample is None and not args.dry_run:
|
|
1336
|
+
raise SystemExit("请选择 --all、--sample N 或 --dry-run")
|
|
1337
|
+
if args.all and args.sample is not None:
|
|
1338
|
+
raise SystemExit("--all 与 --sample 不可同用")
|
|
1339
|
+
load_build_excel() # 提前校验生产 19 列口径,避免跑完半个语料才发现对不上
|
|
1340
|
+
args.started = time.time()
|
|
1341
|
+
idx, entries = load_index()
|
|
1342
|
+
result = run_diff(args, idx, entries)
|
|
1343
|
+
if args.dry_run:
|
|
1344
|
+
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
1345
|
+
return 0
|
|
1346
|
+
return result
|
|
1347
|
+
|
|
1348
|
+
|
|
1349
|
+
if __name__ == "__main__": # python -m netparse.cli.diff 直跑
|
|
1350
|
+
from . import main as _cli_main
|
|
1351
|
+
sys.exit(_cli_main(["diff"] + sys.argv[1:]))
|