l2_snapshot.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """Merge collectors' TSVs + Zabbix alarms -> snapshot.json for the L2 topology page."""
  4. import csv, json, os, re, collections, time, datetime, urllib.request, gzip, base64, subprocess
  5. import l2cfg
  6. TOK = 'd3abb125eb301a021ef80a2847a803a7cd2d0b1d3c8337a14d09db9d571369b5'
  7. API = 'http://192.168.87.20:8080/api_jsonrpc.php'
  8. OUT = '/opt/zabbix/zabbix-server/web-modules/WecomCenter/assets/l2topology/snapshot.json'
  9. STP = '/tmp/stp_topology.tsv'
  10. EP = '/tmp/fdb_endpoints.tsv'
  11. PS = '/tmp/port_status.tsv'
  12. LAT = '/tmp/latency.tsv'
  13. POE = '/tmp/poe_switches.tsv'
  14. MYSQL_CONTAINER = os.environ.get('L2_MYSQL_CONTAINER', 'zabbix-mysql')
  15. MYSQL_USER = os.environ.get('L2_MYSQL_USER', 'root')
  16. MYSQL_PASS = os.environ.get('L2_MYSQL_PASS', 'CobcoIT132')
  17. MYSQL_DB = os.environ.get('L2_MYSQL_DB', 'zabbix')
  18. SEV = ['NC', 'INFO', 'WARN', 'AVG', 'HIGH', 'DISASTER'] # names localized on the frontend
  19. PHYS = {'6', '62', '117'}
  20. def api(m, p):
  21. d = json.dumps({"jsonrpc": "2.0", "method": m, "params": p, "id": 1}).encode()
  22. q = urllib.request.Request(API, data=d, headers={'Content-Type': 'application/json', 'Authorization': 'Bearer ' + TOK})
  23. return json.loads(urllib.request.urlopen(q, timeout=60).read())
  24. def load(path):
  25. with open(path, encoding='utf-8') as f:
  26. return list(csv.DictReader(f, delimiter='\t'))
  27. def norm(s):
  28. return re.sub(r'\s+', ' ', (s or '').strip())
  29. PHYS_TYPES = {'6', '62', '117'}
  30. IFACE_SPEED_RE = re.compile(r'^(?:(100GE|50GE|40GE|25GE|10GE|XGE|2\.5GE|GE|FE))', re.I)
  31. def port_max_mbps(name, current=0):
  32. """Best effort front-panel capability from the interface name.
  33. ``ifSpeed``/``ifHighSpeed`` is the negotiated link rate, not the port's
  34. maximum capability (a 10GE port with a 1G module reports 1000). Huawei
  35. interface names retain the hardware family, so use that prefix; fall back
  36. to the observed rate when the name is not descriptive.
  37. """
  38. s = (name or '').strip().upper().replace(' ', '')
  39. m = IFACE_SPEED_RE.match(s)
  40. if m:
  41. fam = m.group(1).upper()
  42. return {
  43. '100GE': 100000, '50GE': 50000, '40GE': 40000, '25GE': 25000,
  44. '10GE': 10000, 'XGE': 10000, '2.5GE': 2500, 'GE': 1000, 'FE': 100
  45. }.get(fam, current or 0)
  46. if s.startswith('XGIGABITETHERNET'):
  47. return 10000
  48. if s.startswith('GIGABITETHERNET'):
  49. return 1000
  50. if s.startswith('FASTETHERNET'):
  51. return 100
  52. try:
  53. return int(current or 0)
  54. except Exception:
  55. return 0
  56. def is_physical_port(row):
  57. itype = str(row.get('ifType') or '').strip()
  58. if itype not in PHYS_TYPES:
  59. return False
  60. name = (row.get('ifName') or row.get('ifDescr') or '').strip()
  61. if not name:
  62. return False
  63. if re.search(r'(?i)^(ETH-TRUNK|VLANIF|NULL|INLOOPBACK|STACK-PORT|LOOPBACK|TUNNEL|METH|VBDIF)', name):
  64. return False
  65. return True
  66. def load_latency():
  67. lat = {}
  68. try:
  69. with open(LAT, encoding='utf-8') as f:
  70. for line in f:
  71. p = line.rstrip('\n').split('\t')
  72. if len(p) >= 2 and p[0] and p[1]:
  73. try:
  74. lat[p[0]] = float(p[1])
  75. except ValueError:
  76. pass
  77. except Exception:
  78. pass
  79. return lat
  80. def load_poe():
  81. out = {}
  82. try:
  83. for row in load(POE):
  84. ip = (row.get('switch_ip') or '').strip()
  85. if ip:
  86. out[ip] = (row.get('poe') or '0').strip() == '1'
  87. except Exception:
  88. pass
  89. return out
  90. def mysql(sql):
  91. return subprocess.run(
  92. ['docker', 'exec', '-i', MYSQL_CONTAINER, 'mysql',
  93. '-u' + MYSQL_USER, '-p' + MYSQL_PASS, MYSQL_DB,
  94. '--default-character-set=utf8mb4'],
  95. input=sql.encode('utf-8'), capture_output=True, timeout=120)
  96. def write_history(snap, now):
  97. cfg = l2cfg.config()
  98. days = max(1, min(30, int(cfg.get('history_days') or 7)))
  99. interval = max(5, int(cfg.get('history_interval_min') or 5))
  100. interval_sec = interval * 60
  101. raw = json.dumps(snap, ensure_ascii=False, separators=(',', ':')).encode('utf-8')
  102. b64 = base64.b64encode(gzip.compress(raw, 9)).decode('ascii')
  103. st = json.dumps(snap.get('stats', {}), ensure_ascii=False)
  104. cap = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  105. # One row per configured interval. The guard makes both run_full.sh and
  106. # refresh_alarms.sh safe to call this function: whichever runs first at a
  107. # boundary inserts, the other calls become no-ops. Old rows are always
  108. # pruned, so retention is a hard cap rather than a best effort.
  109. sql = (
  110. "CREATE TABLE IF NOT EXISTS l2_topology_history ("
  111. "id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, ts BIGINT NOT NULL, "
  112. "captured_at DATETIME NOT NULL, stats TEXT, snapshot MEDIUMBLOB, "
  113. "PRIMARY KEY (id), KEY idx_l2_ts (ts)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;\n"
  114. "INSERT INTO l2_topology_history (ts,captured_at,stats,snapshot) "
  115. "SELECT %d,'%s','%s',FROM_BASE64('%s') FROM DUAL "
  116. "WHERE NOT EXISTS (SELECT 1 FROM l2_topology_history WHERE ts > %d);\n"
  117. "DELETE FROM l2_topology_history WHERE ts < %d;\n"
  118. % (now, cap, st, b64, now - interval_sec, now - days * 86400)
  119. )
  120. r = mysql(sql)
  121. if r.returncode != 0:
  122. print('history write failed:', r.stderr.decode('utf-8', 'ignore')[:400])
  123. def main():
  124. now = int(time.time())
  125. edges_raw = load(STP); eps = load(EP); ps = load(PS)
  126. lat = load_latency()
  127. poe = load_poe()
  128. # Previous snapshot is the switch inventory / last-known-position source.
  129. # Terminals are deliberately NOT compared with it: a terminal is shown
  130. # only if it is present in the current collection.
  131. prev_snap = {}
  132. try:
  133. with open(OUT, encoding='utf-8') as f:
  134. prev_snap = json.load(f)
  135. except Exception:
  136. pass
  137. prev_nodes = {str(n.get('id')): n for n in prev_snap.get('nodes', []) if n.get('id')}
  138. prev_edges = prev_snap.get('edges', []) or []
  139. days = int(l2cfg.config().get('history_days') or 7)
  140. cutoff = now - days * 86400
  141. # ---------- port status maps ----------
  142. pmap = {} # (ip, ifName) -> row
  143. for r in ps:
  144. pmap[(r['switch_ip'], r['ifName'])] = r
  145. # Full physical front-panel inventory, including unused ports. This is
  146. # what the topology page uses to draw the switch port matrix when the
  147. # "show terminals" option is enabled.
  148. ports_by_ip = collections.defaultdict(list)
  149. for r in ps:
  150. if not is_physical_port(r):
  151. continue
  152. ip = (r.get('switch_ip') or '').strip()
  153. name = (r.get('ifName') or r.get('ifDescr') or '').strip()
  154. if not ip or not name:
  155. continue
  156. try:
  157. speed = int(float(r.get('speed_mbps') or 0))
  158. except Exception:
  159. speed = 0
  160. try:
  161. order = int(r.get('ifIndex') or 0)
  162. except Exception:
  163. order = 0
  164. ports_by_ip[ip].append({
  165. 'name': name, 'order': order, 'speed': speed,
  166. 'max': port_max_mbps(name, speed),
  167. 'up': (r.get('oper_status') == 'up'),
  168. })
  169. for ip in ports_by_ip:
  170. # Keep one row per interface name; sort by ifIndex so the front-panel
  171. # order is deterministic across collection runs.
  172. uniq = {}
  173. for p in ports_by_ip[ip]:
  174. uniq[p['name']] = p
  175. ports_by_ip[ip] = sorted(uniq.values(), key=lambda p: (p['order'], p['name']))
  176. # ---------- switch identity ----------
  177. sname = {}
  178. for e in edges_raw:
  179. sname[e['down_ip']] = norm(e['down_switch'])
  180. sname[e['up_ip']] = norm(e['up_switch'])
  181. # ---------- undirected graph & depth ----------
  182. adj = collections.defaultdict(set); pair = {}
  183. for e in edges_raw:
  184. a, b = e['down_ip'], e['up_ip']
  185. if a == b: continue
  186. adj[a].add(b); adj[b].add(a)
  187. k = tuple(sorted([a, b]))
  188. pair.setdefault(k, {}).setdefault('ports', {})
  189. pair[k]['ports'].setdefault(a, {})['down'] = e['down_port']
  190. pair[k]['ports'].setdefault(b, {})['up'] = e['up_port']
  191. downcnt = collections.Counter(e['down_ip'] for e in edges_raw)
  192. nodes_ip = set(adj)
  193. # components + true root (fewest times as downstream) -> depth, parent, children
  194. depth = {}; parent = {}; children = collections.defaultdict(list); roots = []
  195. seen = set()
  196. for start in nodes_ip:
  197. if start in seen: continue
  198. comp = []; st = [start]
  199. while st:
  200. u = st.pop()
  201. if u in seen: continue
  202. seen.add(u); comp.append(u); st.extend(adj[u] - seen)
  203. root = min(comp, key=lambda n: (downcnt.get(n, 0), -len(adj[n]), n))
  204. roots.append(root); depth[root] = 0; parent[root] = None
  205. order = [root]; qi = 0
  206. while qi < len(order):
  207. u = order[qi]; qi += 1
  208. for v in sorted(adj[u]):
  209. if v not in depth:
  210. depth[v] = depth[u] + 1; parent[v] = u; children[u].append(v); order.append(v)
  211. def tier(ip):
  212. d = depth.get(ip, 99)
  213. if d == 0: return 'core'
  214. if children.get(ip): return 'distribution'
  215. return 'access'
  216. # ---------- alarms ----------
  217. problems = api('problem.get', {'output': ['eventid', 'objectid', 'name', 'severity', 'clock', 'acknowledged'], 'recent': False})['result']
  218. trigids = sorted(set(p['objectid'] for p in problems))
  219. trig = {}
  220. if trigids:
  221. tg = api('trigger.get', {'triggerids': trigids, 'output': ['triggerid'], 'selectHosts': ['hostid', 'name', 'interfaces']})['result']
  222. for t in tg:
  223. trig[t['triggerid']] = t.get('hosts', [])
  224. ip_alarms = collections.defaultdict(list)
  225. # hosts & availability (need hostid -> ip for alarms)
  226. hs = api('host.get', {'output': ['hostid', 'name'], 'selectInterfaces': ['ip', 'type', 'available', 'error']})['result']
  227. hid_ip = {}; ip_name = {}; hid_by_ip = {}; avail = {}
  228. for h in hs:
  229. cand = [i for i in h['interfaces'] if i.get('ip')]
  230. if not cand: continue
  231. snmp = [i for i in cand if i['type'] == '2']
  232. pick = (snmp or cand)[0]
  233. hid_ip.setdefault(h['hostid'], pick['ip'])
  234. ip_name[pick['ip']] = h['name']; hid_by_ip[pick['ip']] = h['hostid']
  235. for i in snmp:
  236. avail[i['ip']] = i.get('available', '0')
  237. for p in problems:
  238. for h in trig.get(p['objectid'], []):
  239. ip = hid_ip.get(h['hostid'])
  240. if not ip: continue
  241. ip_alarms[ip].append({'sev': int(p['severity']), 'name': p['name'], 'clock': int(p['clock']), 'ack': p['acknowledged'] == '1'})
  242. for ip, av in avail.items():
  243. if av == '2':
  244. ip_alarms[ip].append({'sev': 4, 'name': 'SNMP unreachable / host unavailable', 'clock': now, 'ack': False})
  245. # ---------- switch inventory / hosts ----------
  246. def is_switch_name(name):
  247. n = (name or '').upper()
  248. return bool(re.search(r'-(DIST|ACCESS|CORE)(-|$)', n)) or bool(re.match(r'^COBCO-', n))
  249. switch_hosts = {}
  250. for h in hs:
  251. hn = norm(h.get('name') or '')
  252. if not is_switch_name(hn):
  253. continue
  254. for i in h.get('interfaces', []):
  255. if i.get('type') == '2' and i.get('ip'):
  256. switch_hosts[i['ip']] = {
  257. 'name': hn, 'hostid': h.get('hostid'),
  258. 'available': str(i.get('available', '0')),
  259. 'error': i.get('error', '') or ''
  260. }
  261. # ---------- terminals (current collection only; online only) ----------
  262. # An FDB entry on a port that is not up is stale and is not an "offline
  263. # terminal": the product only displays terminals that are present now.
  264. terminals = []
  265. for t in eps:
  266. mac = (t['mac'] or '').lower()
  267. if not mac: continue
  268. st = pmap.get((t['switch_ip'], t['port']), {})
  269. oper = st.get('oper_status', '')
  270. try: mc = int(st.get('mac_count', '0') or 0)
  271. except: mc = 0
  272. if oper != 'up' or mc <= 0:
  273. continue
  274. terminals.append({'mac': mac, 'ip': t['ip'], 'name': t['name'], 'sw_ip': t['switch_ip'],
  275. 'sw_name': norm(t['switch_name']), 'port': t['port'], 'alias': t.get('port_alias', ''),
  276. 'speed': st.get('speed_mbps', ''), 'online': True, 'last_seen': now})
  277. # terminal counts per switch (online only)
  278. tcnt = collections.defaultdict(lambda: {'online': 0, 'offline': 0})
  279. for t in terminals:
  280. tcnt[t['sw_ip']]['online'] += 1
  281. # ---------- switch inventory: online topology + recorded offline ----------
  282. offline_ips = set()
  283. # Hosts whose SNMP interface is unavailable are offline even if they have no
  284. # current STP edge. This is how a failed switch stays on the map.
  285. for ip, hn in switch_hosts.items():
  286. if hn['available'] == '2':
  287. offline_ips.add(ip)
  288. # Keep a previously recorded switch for history_days when it disappears
  289. # from the protocol-derived graph. The last_online stamp prevents old
  290. # decommissioned devices from living forever.
  291. for ip, pn in prev_nodes.items():
  292. if ip in nodes_ip:
  293. continue
  294. last_online = int(pn.get('last_online') or pn.get('last_seen') or prev_snap.get('generated') or 0)
  295. if last_online >= cutoff:
  296. offline_ips.add(ip)
  297. known_ips = set(nodes_ip) | offline_ips
  298. def name_role(name):
  299. n = (name or '').upper()
  300. if re.search(r'-(DIST)(-|$)', n): return 'distribution'
  301. if re.search(r'-(ACCESS)(-|$)', n): return 'access'
  302. if re.search(r'-(CORE)(-|$)', n): return 'core'
  303. return ''
  304. def node_tier(ip, name, pn=None):
  305. pn = pn or {}
  306. ch = int(pn.get('children') or 0)
  307. pt = str(pn.get('tier') or '').lower()
  308. # Graph degree is the protocol truth: a switch with children is an
  309. # aggregation/distribution point, regardless of a wrong name suffix.
  310. if ch > 0:
  311. return 'distribution'
  312. if pt in ('distribution', 'access'):
  313. return pt
  314. nr = name_role(name)
  315. if nr:
  316. return nr
  317. if pt == 'core': return 'core'
  318. return 'access'
  319. nodes = []
  320. for ip in sorted(known_ips, key=lambda x: (depth.get(x, 99), x)):
  321. online = ip in nodes_ip
  322. pn = prev_nodes.get(ip, {})
  323. hn = switch_hosts.get(ip, {})
  324. nm = sname.get(ip) or pn.get('name') or hn.get('name') or ip_name.get(ip) or ip
  325. al = ip_alarms.get(ip, [])
  326. maxsev = max([a['sev'] for a in al], default=-1)
  327. if online:
  328. ntier = tier(ip)
  329. ndepth = depth.get(ip, 99)
  330. nchildren = len(children.get(ip, []))
  331. oper = 'down' if avail.get(ip) == '2' else 'up'
  332. last_online = now
  333. else:
  334. ntier = node_tier(ip, nm, pn)
  335. ndepth = int(pn.get('depth', 99))
  336. nchildren = int(pn.get('children') or 0)
  337. oper = 'down'
  338. last_online = int(pn.get('last_online') or pn.get('last_seen') or prev_snap.get('generated') or now)
  339. nodes.append({
  340. 'id': ip, 'name': nm, 'ip': ip, 'tier': ntier, 'depth': ndepth,
  341. 'hostid': hid_by_ip.get(ip) or hn.get('hostid') or pn.get('hostid'),
  342. 'oper': oper, 'offline': not online,
  343. 'alarms': sorted(al, key=lambda a: -a['sev']), 'maxsev': maxsev,
  344. 'term_online': tcnt[ip]['online'], 'term_offline': 0,
  345. 'latency_ms': lat.get(ip) if online else pn.get('latency_ms'),
  346. 'children': nchildren, 'poe': bool(poe.get(ip, pn.get('poe', False))),
  347. 'ports': ports_by_ip.get(ip, []),
  348. 'last_online': last_online
  349. })
  350. # ---------- edges ----------
  351. edges = []
  352. edge_pairs = set()
  353. for k, d in pair.items():
  354. a, b = k
  355. p = d['ports']
  356. pa = p.get(a, {}); pb = p.get(b, {})
  357. a_port = pa.get('down') or pa.get('up') or ''
  358. b_port = pb.get('up') or pb.get('down') or ''
  359. speeds = []
  360. for ip, port in ((a, a_port), (b, b_port)):
  361. row = pmap.get((ip, port), {})
  362. try: sp = int(row.get('speed_mbps', '0') or 0)
  363. except: sp = 0
  364. speeds.append(sp)
  365. speed = max(speeds) if speeds else 0
  366. ops = []
  367. for ip, port in ((a, a_port), (b, b_port)):
  368. row = pmap.get((ip, port))
  369. ops.append(row.get('oper_status') if row else None)
  370. state = 'down' if ('down' in ops) else 'up'
  371. if a not in known_ips or b not in known_ips:
  372. continue
  373. edges.append({'source': a, 'target': b, 'speed': speed, 'state': state,
  374. 'a_port': a_port, 'b_port': b_port})
  375. edge_pairs.add(tuple(sorted((a, b))))
  376. # Keep the last-known uplink for an offline switch so it is shown in its
  377. # workshop frame and its historical position is not lost.
  378. for e in prev_edges:
  379. a, b = str(e.get('source')), str(e.get('target'))
  380. k = tuple(sorted((a, b)))
  381. if k in edge_pairs or a not in known_ips or b not in known_ips:
  382. continue
  383. if a in nodes_ip and b in nodes_ip:
  384. continue
  385. edges.append({'source': a, 'target': b, 'speed': e.get('speed', 0), 'state': 'down',
  386. 'a_port': e.get('a_port', ''), 'b_port': e.get('b_port', '')})
  387. edge_pairs.add(k)
  388. stats = {
  389. 'switches': len(nodes), 'switches_online': len(nodes_ip), 'switches_offline': len(offline_ips),
  390. 'poe_switches': sum(1 for n in nodes if n.get('poe')),
  391. 'ports': sum(len(n.get('ports') or []) for n in nodes),
  392. 'edges': len(edges),
  393. 'term_total': len(terminals), 'term_online': len(terminals), 'term_offline': 0,
  394. 'alarms': sum(len(n['alarms']) for n in nodes),
  395. 'devices_alarm': sum(1 for n in nodes if n['alarms']),
  396. 'maxsev': max([n['maxsev'] for n in nodes], default=-1)
  397. }
  398. in_nodes = set(known_ips)
  399. other = []
  400. for ip, al in ip_alarms.items():
  401. if ip in in_nodes:
  402. continue
  403. for a in al:
  404. other.append({'ip': ip, 'host': ip_name.get(ip, ip), 'sev': a['sev'], 'name': a['name'], 'clock': a['clock']})
  405. other.sort(key=lambda x: -x['sev'])
  406. stats['other_alarms'] = len(other)
  407. snap = {'generated': now, 'generated_iso': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  408. 'refresh_default': 300, 'roots': roots, 'stats': stats,
  409. 'other_alarms': other,
  410. 'nodes': nodes, 'edges': edges, 'terminals': terminals}
  411. os.makedirs(os.path.dirname(OUT), exist_ok=True)
  412. tmp = OUT + '.tmp'
  413. with open(tmp, 'w', encoding='utf-8') as f:
  414. json.dump(snap, f, ensure_ascii=False, separators=(',', ':'))
  415. os.replace(tmp, OUT)
  416. print('snapshot', OUT, os.path.getsize(OUT), 'bytes;', stats)
  417. if os.environ.get('L2_WRITE_HISTORY', '0') == '1':
  418. try:
  419. write_history(snap, now)
  420. except Exception as e:
  421. print('history write error:', e)
  422. if __name__ == '__main__':
  423. main()