l2_snapshot.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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 = int(cfg.get('history_days') or 7)
  99. raw = json.dumps(snap, ensure_ascii=False, separators=(',', ':')).encode('utf-8')
  100. b64 = base64.b64encode(gzip.compress(raw, 9)).decode('ascii')
  101. st = json.dumps(snap.get('stats', {}), ensure_ascii=False)
  102. cap = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  103. sql = (
  104. "CREATE TABLE IF NOT EXISTS l2_topology_history ("
  105. "id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, ts BIGINT NOT NULL, "
  106. "captured_at DATETIME NOT NULL, stats TEXT, snapshot MEDIUMBLOB, "
  107. "PRIMARY KEY (id), KEY idx_l2_ts (ts)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;\n"
  108. "INSERT INTO l2_topology_history (ts,captured_at,stats,snapshot) VALUES "
  109. "(%d,'%s','%s',FROM_BASE64('%s'));\n"
  110. "DELETE FROM l2_topology_history WHERE ts < %d;\n"
  111. % (now, cap, st, b64, now - days * 86400)
  112. )
  113. r = mysql(sql)
  114. if r.returncode != 0:
  115. print('history write failed:', r.stderr.decode('utf-8', 'ignore')[:400])
  116. def main():
  117. now = int(time.time())
  118. edges_raw = load(STP); eps = load(EP); ps = load(PS)
  119. lat = load_latency()
  120. poe = load_poe()
  121. # Previous snapshot is the switch inventory / last-known-position source.
  122. # Terminals are deliberately NOT compared with it: a terminal is shown
  123. # only if it is present in the current collection.
  124. prev_snap = {}
  125. try:
  126. with open(OUT, encoding='utf-8') as f:
  127. prev_snap = json.load(f)
  128. except Exception:
  129. pass
  130. prev_nodes = {str(n.get('id')): n for n in prev_snap.get('nodes', []) if n.get('id')}
  131. prev_edges = prev_snap.get('edges', []) or []
  132. days = int(l2cfg.config().get('history_days') or 7)
  133. cutoff = now - days * 86400
  134. # ---------- port status maps ----------
  135. pmap = {} # (ip, ifName) -> row
  136. for r in ps:
  137. pmap[(r['switch_ip'], r['ifName'])] = r
  138. # Full physical front-panel inventory, including unused ports. This is
  139. # what the topology page uses to draw the switch port matrix when the
  140. # "show terminals" option is enabled.
  141. ports_by_ip = collections.defaultdict(list)
  142. for r in ps:
  143. if not is_physical_port(r):
  144. continue
  145. ip = (r.get('switch_ip') or '').strip()
  146. name = (r.get('ifName') or r.get('ifDescr') or '').strip()
  147. if not ip or not name:
  148. continue
  149. try:
  150. speed = int(float(r.get('speed_mbps') or 0))
  151. except Exception:
  152. speed = 0
  153. try:
  154. order = int(r.get('ifIndex') or 0)
  155. except Exception:
  156. order = 0
  157. ports_by_ip[ip].append({
  158. 'name': name, 'order': order, 'speed': speed,
  159. 'max': port_max_mbps(name, speed),
  160. 'up': (r.get('oper_status') == 'up'),
  161. })
  162. for ip in ports_by_ip:
  163. # Keep one row per interface name; sort by ifIndex so the front-panel
  164. # order is deterministic across collection runs.
  165. uniq = {}
  166. for p in ports_by_ip[ip]:
  167. uniq[p['name']] = p
  168. ports_by_ip[ip] = sorted(uniq.values(), key=lambda p: (p['order'], p['name']))
  169. # ---------- switch identity ----------
  170. sname = {}
  171. for e in edges_raw:
  172. sname[e['down_ip']] = norm(e['down_switch'])
  173. sname[e['up_ip']] = norm(e['up_switch'])
  174. # ---------- undirected graph & depth ----------
  175. adj = collections.defaultdict(set); pair = {}
  176. for e in edges_raw:
  177. a, b = e['down_ip'], e['up_ip']
  178. if a == b: continue
  179. adj[a].add(b); adj[b].add(a)
  180. k = tuple(sorted([a, b]))
  181. pair.setdefault(k, {}).setdefault('ports', {})
  182. pair[k]['ports'].setdefault(a, {})['down'] = e['down_port']
  183. pair[k]['ports'].setdefault(b, {})['up'] = e['up_port']
  184. downcnt = collections.Counter(e['down_ip'] for e in edges_raw)
  185. nodes_ip = set(adj)
  186. # components + true root (fewest times as downstream) -> depth, parent, children
  187. depth = {}; parent = {}; children = collections.defaultdict(list); roots = []
  188. seen = set()
  189. for start in nodes_ip:
  190. if start in seen: continue
  191. comp = []; st = [start]
  192. while st:
  193. u = st.pop()
  194. if u in seen: continue
  195. seen.add(u); comp.append(u); st.extend(adj[u] - seen)
  196. root = min(comp, key=lambda n: (downcnt.get(n, 0), -len(adj[n]), n))
  197. roots.append(root); depth[root] = 0; parent[root] = None
  198. order = [root]; qi = 0
  199. while qi < len(order):
  200. u = order[qi]; qi += 1
  201. for v in sorted(adj[u]):
  202. if v not in depth:
  203. depth[v] = depth[u] + 1; parent[v] = u; children[u].append(v); order.append(v)
  204. def tier(ip):
  205. d = depth.get(ip, 99)
  206. if d == 0: return 'core'
  207. if children.get(ip): return 'distribution'
  208. return 'access'
  209. # ---------- alarms ----------
  210. problems = api('problem.get', {'output': ['eventid', 'objectid', 'name', 'severity', 'clock', 'acknowledged'], 'recent': False})['result']
  211. trigids = sorted(set(p['objectid'] for p in problems))
  212. trig = {}
  213. if trigids:
  214. tg = api('trigger.get', {'triggerids': trigids, 'output': ['triggerid'], 'selectHosts': ['hostid', 'name', 'interfaces']})['result']
  215. for t in tg:
  216. trig[t['triggerid']] = t.get('hosts', [])
  217. ip_alarms = collections.defaultdict(list)
  218. # hosts & availability (need hostid -> ip for alarms)
  219. hs = api('host.get', {'output': ['hostid', 'name'], 'selectInterfaces': ['ip', 'type', 'available', 'error']})['result']
  220. hid_ip = {}; ip_name = {}; hid_by_ip = {}; avail = {}
  221. for h in hs:
  222. cand = [i for i in h['interfaces'] if i.get('ip')]
  223. if not cand: continue
  224. snmp = [i for i in cand if i['type'] == '2']
  225. pick = (snmp or cand)[0]
  226. hid_ip.setdefault(h['hostid'], pick['ip'])
  227. ip_name[pick['ip']] = h['name']; hid_by_ip[pick['ip']] = h['hostid']
  228. for i in snmp:
  229. avail[i['ip']] = i.get('available', '0')
  230. for p in problems:
  231. for h in trig.get(p['objectid'], []):
  232. ip = hid_ip.get(h['hostid'])
  233. if not ip: continue
  234. ip_alarms[ip].append({'sev': int(p['severity']), 'name': p['name'], 'clock': int(p['clock']), 'ack': p['acknowledged'] == '1'})
  235. for ip, av in avail.items():
  236. if av == '2':
  237. ip_alarms[ip].append({'sev': 4, 'name': 'SNMP unreachable / host unavailable', 'clock': now, 'ack': False})
  238. # ---------- switch inventory / hosts ----------
  239. def is_switch_name(name):
  240. n = (name or '').upper()
  241. return bool(re.search(r'-(DIST|ACCESS|CORE)(-|$)', n)) or bool(re.match(r'^COBCO-', n))
  242. switch_hosts = {}
  243. for h in hs:
  244. hn = norm(h.get('name') or '')
  245. if not is_switch_name(hn):
  246. continue
  247. for i in h.get('interfaces', []):
  248. if i.get('type') == '2' and i.get('ip'):
  249. switch_hosts[i['ip']] = {
  250. 'name': hn, 'hostid': h.get('hostid'),
  251. 'available': str(i.get('available', '0')),
  252. 'error': i.get('error', '') or ''
  253. }
  254. # ---------- terminals (current collection only; online only) ----------
  255. # An FDB entry on a port that is not up is stale and is not an "offline
  256. # terminal": the product only displays terminals that are present now.
  257. terminals = []
  258. for t in eps:
  259. mac = (t['mac'] or '').lower()
  260. if not mac: continue
  261. st = pmap.get((t['switch_ip'], t['port']), {})
  262. oper = st.get('oper_status', '')
  263. try: mc = int(st.get('mac_count', '0') or 0)
  264. except: mc = 0
  265. if oper != 'up' or mc <= 0:
  266. continue
  267. terminals.append({'mac': mac, 'ip': t['ip'], 'name': t['name'], 'sw_ip': t['switch_ip'],
  268. 'sw_name': norm(t['switch_name']), 'port': t['port'], 'alias': t.get('port_alias', ''),
  269. 'speed': st.get('speed_mbps', ''), 'online': True, 'last_seen': now})
  270. # terminal counts per switch (online only)
  271. tcnt = collections.defaultdict(lambda: {'online': 0, 'offline': 0})
  272. for t in terminals:
  273. tcnt[t['sw_ip']]['online'] += 1
  274. # ---------- switch inventory: online topology + recorded offline ----------
  275. offline_ips = set()
  276. # Hosts whose SNMP interface is unavailable are offline even if they have no
  277. # current STP edge. This is how a failed switch stays on the map.
  278. for ip, hn in switch_hosts.items():
  279. if hn['available'] == '2':
  280. offline_ips.add(ip)
  281. # Keep a previously recorded switch for history_days when it disappears
  282. # from the protocol-derived graph. The last_online stamp prevents old
  283. # decommissioned devices from living forever.
  284. for ip, pn in prev_nodes.items():
  285. if ip in nodes_ip:
  286. continue
  287. last_online = int(pn.get('last_online') or pn.get('last_seen') or prev_snap.get('generated') or 0)
  288. if last_online >= cutoff:
  289. offline_ips.add(ip)
  290. known_ips = set(nodes_ip) | offline_ips
  291. def name_role(name):
  292. n = (name or '').upper()
  293. if re.search(r'-(DIST)(-|$)', n): return 'distribution'
  294. if re.search(r'-(ACCESS)(-|$)', n): return 'access'
  295. if re.search(r'-(CORE)(-|$)', n): return 'core'
  296. return ''
  297. def node_tier(ip, name, pn=None):
  298. pn = pn or {}
  299. ch = int(pn.get('children') or 0)
  300. pt = str(pn.get('tier') or '').lower()
  301. # Graph degree is the protocol truth: a switch with children is an
  302. # aggregation/distribution point, regardless of a wrong name suffix.
  303. if ch > 0:
  304. return 'distribution'
  305. if pt in ('distribution', 'access'):
  306. return pt
  307. nr = name_role(name)
  308. if nr:
  309. return nr
  310. if pt == 'core': return 'core'
  311. return 'access'
  312. nodes = []
  313. for ip in sorted(known_ips, key=lambda x: (depth.get(x, 99), x)):
  314. online = ip in nodes_ip
  315. pn = prev_nodes.get(ip, {})
  316. hn = switch_hosts.get(ip, {})
  317. nm = sname.get(ip) or pn.get('name') or hn.get('name') or ip_name.get(ip) or ip
  318. al = ip_alarms.get(ip, [])
  319. maxsev = max([a['sev'] for a in al], default=-1)
  320. if online:
  321. ntier = tier(ip)
  322. ndepth = depth.get(ip, 99)
  323. nchildren = len(children.get(ip, []))
  324. oper = 'down' if avail.get(ip) == '2' else 'up'
  325. last_online = now
  326. else:
  327. ntier = node_tier(ip, nm, pn)
  328. ndepth = int(pn.get('depth', 99))
  329. nchildren = int(pn.get('children') or 0)
  330. oper = 'down'
  331. last_online = int(pn.get('last_online') or pn.get('last_seen') or prev_snap.get('generated') or now)
  332. nodes.append({
  333. 'id': ip, 'name': nm, 'ip': ip, 'tier': ntier, 'depth': ndepth,
  334. 'hostid': hid_by_ip.get(ip) or hn.get('hostid') or pn.get('hostid'),
  335. 'oper': oper, 'offline': not online,
  336. 'alarms': sorted(al, key=lambda a: -a['sev']), 'maxsev': maxsev,
  337. 'term_online': tcnt[ip]['online'], 'term_offline': 0,
  338. 'latency_ms': lat.get(ip) if online else pn.get('latency_ms'),
  339. 'children': nchildren, 'poe': bool(poe.get(ip, pn.get('poe', False))),
  340. 'ports': ports_by_ip.get(ip, []),
  341. 'last_online': last_online
  342. })
  343. # ---------- edges ----------
  344. edges = []
  345. edge_pairs = set()
  346. for k, d in pair.items():
  347. a, b = k
  348. p = d['ports']
  349. pa = p.get(a, {}); pb = p.get(b, {})
  350. a_port = pa.get('down') or pa.get('up') or ''
  351. b_port = pb.get('up') or pb.get('down') or ''
  352. speeds = []
  353. for ip, port in ((a, a_port), (b, b_port)):
  354. row = pmap.get((ip, port), {})
  355. try: sp = int(row.get('speed_mbps', '0') or 0)
  356. except: sp = 0
  357. speeds.append(sp)
  358. speed = max(speeds) if speeds else 0
  359. ops = []
  360. for ip, port in ((a, a_port), (b, b_port)):
  361. row = pmap.get((ip, port))
  362. ops.append(row.get('oper_status') if row else None)
  363. state = 'down' if ('down' in ops) else 'up'
  364. if a not in known_ips or b not in known_ips:
  365. continue
  366. edges.append({'source': a, 'target': b, 'speed': speed, 'state': state,
  367. 'a_port': a_port, 'b_port': b_port})
  368. edge_pairs.add(tuple(sorted((a, b))))
  369. # Keep the last-known uplink for an offline switch so it is shown in its
  370. # workshop frame and its historical position is not lost.
  371. for e in prev_edges:
  372. a, b = str(e.get('source')), str(e.get('target'))
  373. k = tuple(sorted((a, b)))
  374. if k in edge_pairs or a not in known_ips or b not in known_ips:
  375. continue
  376. if a in nodes_ip and b in nodes_ip:
  377. continue
  378. edges.append({'source': a, 'target': b, 'speed': e.get('speed', 0), 'state': 'down',
  379. 'a_port': e.get('a_port', ''), 'b_port': e.get('b_port', '')})
  380. edge_pairs.add(k)
  381. stats = {
  382. 'switches': len(nodes), 'switches_online': len(nodes_ip), 'switches_offline': len(offline_ips),
  383. 'poe_switches': sum(1 for n in nodes if n.get('poe')),
  384. 'ports': sum(len(n.get('ports') or []) for n in nodes),
  385. 'edges': len(edges),
  386. 'term_total': len(terminals), 'term_online': len(terminals), 'term_offline': 0,
  387. 'alarms': sum(len(n['alarms']) for n in nodes),
  388. 'devices_alarm': sum(1 for n in nodes if n['alarms']),
  389. 'maxsev': max([n['maxsev'] for n in nodes], default=-1)
  390. }
  391. in_nodes = set(known_ips)
  392. other = []
  393. for ip, al in ip_alarms.items():
  394. if ip in in_nodes:
  395. continue
  396. for a in al:
  397. other.append({'ip': ip, 'host': ip_name.get(ip, ip), 'sev': a['sev'], 'name': a['name'], 'clock': a['clock']})
  398. other.sort(key=lambda x: -x['sev'])
  399. stats['other_alarms'] = len(other)
  400. snap = {'generated': now, 'generated_iso': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  401. 'refresh_default': 300, 'roots': roots, 'stats': stats,
  402. 'other_alarms': other,
  403. 'nodes': nodes, 'edges': edges, 'terminals': terminals}
  404. os.makedirs(os.path.dirname(OUT), exist_ok=True)
  405. tmp = OUT + '.tmp'
  406. with open(tmp, 'w', encoding='utf-8') as f:
  407. json.dump(snap, f, ensure_ascii=False, separators=(',', ':'))
  408. os.replace(tmp, OUT)
  409. print('snapshot', OUT, os.path.getsize(OUT), 'bytes;', stats)
  410. if os.environ.get('L2_WRITE_HISTORY', '0') == '1':
  411. try:
  412. write_history(snap, now)
  413. except Exception as e:
  414. print('history write error:', e)
  415. if __name__ == '__main__':
  416. main()