l2_snapshot.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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. def load_latency():
  30. lat = {}
  31. try:
  32. with open(LAT, encoding='utf-8') as f:
  33. for line in f:
  34. p = line.rstrip('\n').split('\t')
  35. if len(p) >= 2 and p[0] and p[1]:
  36. try:
  37. lat[p[0]] = float(p[1])
  38. except ValueError:
  39. pass
  40. except Exception:
  41. pass
  42. return lat
  43. def load_poe():
  44. out = {}
  45. try:
  46. for row in load(POE):
  47. ip = (row.get('switch_ip') or '').strip()
  48. if ip:
  49. out[ip] = (row.get('poe') or '0').strip() == '1'
  50. except Exception:
  51. pass
  52. return out
  53. def mysql(sql):
  54. return subprocess.run(
  55. ['docker', 'exec', '-i', MYSQL_CONTAINER, 'mysql',
  56. '-u' + MYSQL_USER, '-p' + MYSQL_PASS, MYSQL_DB,
  57. '--default-character-set=utf8mb4'],
  58. input=sql.encode('utf-8'), capture_output=True, timeout=120)
  59. def write_history(snap, now):
  60. cfg = l2cfg.config()
  61. days = int(cfg.get('history_days') or 7)
  62. raw = json.dumps(snap, ensure_ascii=False, separators=(',', ':')).encode('utf-8')
  63. b64 = base64.b64encode(gzip.compress(raw, 9)).decode('ascii')
  64. st = json.dumps(snap.get('stats', {}), ensure_ascii=False)
  65. cap = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  66. sql = (
  67. "CREATE TABLE IF NOT EXISTS l2_topology_history ("
  68. "id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, ts BIGINT NOT NULL, "
  69. "captured_at DATETIME NOT NULL, stats TEXT, snapshot MEDIUMBLOB, "
  70. "PRIMARY KEY (id), KEY idx_l2_ts (ts)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;\n"
  71. "INSERT INTO l2_topology_history (ts,captured_at,stats,snapshot) VALUES "
  72. "(%d,'%s','%s',FROM_BASE64('%s'));\n"
  73. "DELETE FROM l2_topology_history WHERE ts < %d;\n"
  74. % (now, cap, st, b64, now - days * 86400)
  75. )
  76. r = mysql(sql)
  77. if r.returncode != 0:
  78. print('history write failed:', r.stderr.decode('utf-8', 'ignore')[:400])
  79. def main():
  80. now = int(time.time())
  81. edges_raw = load(STP); eps = load(EP); ps = load(PS)
  82. lat = load_latency()
  83. poe = load_poe()
  84. # Previous snapshot is the switch inventory / last-known-position source.
  85. # Terminals are deliberately NOT compared with it: a terminal is shown
  86. # only if it is present in the current collection.
  87. prev_snap = {}
  88. try:
  89. with open(OUT, encoding='utf-8') as f:
  90. prev_snap = json.load(f)
  91. except Exception:
  92. pass
  93. prev_nodes = {str(n.get('id')): n for n in prev_snap.get('nodes', []) if n.get('id')}
  94. prev_edges = prev_snap.get('edges', []) or []
  95. days = int(l2cfg.config().get('history_days') or 7)
  96. cutoff = now - days * 86400
  97. # ---------- port status maps ----------
  98. pmap = {} # (ip, ifName) -> row
  99. for r in ps:
  100. pmap[(r['switch_ip'], r['ifName'])] = r
  101. # ---------- switch identity ----------
  102. sname = {}
  103. for e in edges_raw:
  104. sname[e['down_ip']] = norm(e['down_switch'])
  105. sname[e['up_ip']] = norm(e['up_switch'])
  106. # ---------- undirected graph & depth ----------
  107. adj = collections.defaultdict(set); pair = {}
  108. for e in edges_raw:
  109. a, b = e['down_ip'], e['up_ip']
  110. if a == b: continue
  111. adj[a].add(b); adj[b].add(a)
  112. k = tuple(sorted([a, b]))
  113. pair.setdefault(k, {}).setdefault('ports', {})
  114. pair[k]['ports'].setdefault(a, {})['down'] = e['down_port']
  115. pair[k]['ports'].setdefault(b, {})['up'] = e['up_port']
  116. downcnt = collections.Counter(e['down_ip'] for e in edges_raw)
  117. nodes_ip = set(adj)
  118. # components + true root (fewest times as downstream) -> depth, parent, children
  119. depth = {}; parent = {}; children = collections.defaultdict(list); roots = []
  120. seen = set()
  121. for start in nodes_ip:
  122. if start in seen: continue
  123. comp = []; st = [start]
  124. while st:
  125. u = st.pop()
  126. if u in seen: continue
  127. seen.add(u); comp.append(u); st.extend(adj[u] - seen)
  128. root = min(comp, key=lambda n: (downcnt.get(n, 0), -len(adj[n]), n))
  129. roots.append(root); depth[root] = 0; parent[root] = None
  130. order = [root]; qi = 0
  131. while qi < len(order):
  132. u = order[qi]; qi += 1
  133. for v in sorted(adj[u]):
  134. if v not in depth:
  135. depth[v] = depth[u] + 1; parent[v] = u; children[u].append(v); order.append(v)
  136. def tier(ip):
  137. d = depth.get(ip, 99)
  138. if d == 0: return 'core'
  139. if children.get(ip): return 'distribution'
  140. return 'access'
  141. # ---------- alarms ----------
  142. problems = api('problem.get', {'output': ['eventid', 'objectid', 'name', 'severity', 'clock', 'acknowledged'], 'recent': False})['result']
  143. trigids = sorted(set(p['objectid'] for p in problems))
  144. trig = {}
  145. if trigids:
  146. tg = api('trigger.get', {'triggerids': trigids, 'output': ['triggerid'], 'selectHosts': ['hostid', 'name', 'interfaces']})['result']
  147. for t in tg:
  148. trig[t['triggerid']] = t.get('hosts', [])
  149. ip_alarms = collections.defaultdict(list)
  150. # hosts & availability (need hostid -> ip for alarms)
  151. hs = api('host.get', {'output': ['hostid', 'name'], 'selectInterfaces': ['ip', 'type', 'available', 'error']})['result']
  152. hid_ip = {}; ip_name = {}; hid_by_ip = {}; avail = {}
  153. for h in hs:
  154. cand = [i for i in h['interfaces'] if i.get('ip')]
  155. if not cand: continue
  156. snmp = [i for i in cand if i['type'] == '2']
  157. pick = (snmp or cand)[0]
  158. hid_ip.setdefault(h['hostid'], pick['ip'])
  159. ip_name[pick['ip']] = h['name']; hid_by_ip[pick['ip']] = h['hostid']
  160. for i in snmp:
  161. avail[i['ip']] = i.get('available', '0')
  162. for p in problems:
  163. for h in trig.get(p['objectid'], []):
  164. ip = hid_ip.get(h['hostid'])
  165. if not ip: continue
  166. ip_alarms[ip].append({'sev': int(p['severity']), 'name': p['name'], 'clock': int(p['clock']), 'ack': p['acknowledged'] == '1'})
  167. for ip, av in avail.items():
  168. if av == '2':
  169. ip_alarms[ip].append({'sev': 4, 'name': 'SNMP unreachable / host unavailable', 'clock': now, 'ack': False})
  170. # ---------- switch inventory / hosts ----------
  171. def is_switch_name(name):
  172. n = (name or '').upper()
  173. return bool(re.search(r'-(DIST|ACCESS|CORE)(-|$)', n)) or bool(re.match(r'^COBCO-', n))
  174. switch_hosts = {}
  175. for h in hs:
  176. hn = norm(h.get('name') or '')
  177. if not is_switch_name(hn):
  178. continue
  179. for i in h.get('interfaces', []):
  180. if i.get('type') == '2' and i.get('ip'):
  181. switch_hosts[i['ip']] = {
  182. 'name': hn, 'hostid': h.get('hostid'),
  183. 'available': str(i.get('available', '0')),
  184. 'error': i.get('error', '') or ''
  185. }
  186. # ---------- terminals (current collection only; online only) ----------
  187. # An FDB entry on a port that is not up is stale and is not an "offline
  188. # terminal": the product only displays terminals that are present now.
  189. terminals = []
  190. for t in eps:
  191. mac = (t['mac'] or '').lower()
  192. if not mac: continue
  193. st = pmap.get((t['switch_ip'], t['port']), {})
  194. oper = st.get('oper_status', '')
  195. try: mc = int(st.get('mac_count', '0') or 0)
  196. except: mc = 0
  197. if oper != 'up' or mc <= 0:
  198. continue
  199. terminals.append({'mac': mac, 'ip': t['ip'], 'name': t['name'], 'sw_ip': t['switch_ip'],
  200. 'sw_name': norm(t['switch_name']), 'port': t['port'], 'alias': t.get('port_alias', ''),
  201. 'speed': st.get('speed_mbps', ''), 'online': True, 'last_seen': now})
  202. # terminal counts per switch (online only)
  203. tcnt = collections.defaultdict(lambda: {'online': 0, 'offline': 0})
  204. for t in terminals:
  205. tcnt[t['sw_ip']]['online'] += 1
  206. # ---------- switch inventory: online topology + recorded offline ----------
  207. offline_ips = set()
  208. # Hosts whose SNMP interface is unavailable are offline even if they have no
  209. # current STP edge. This is how a failed switch stays on the map.
  210. for ip, hn in switch_hosts.items():
  211. if hn['available'] == '2':
  212. offline_ips.add(ip)
  213. # Keep a previously recorded switch for history_days when it disappears
  214. # from the protocol-derived graph. The last_online stamp prevents old
  215. # decommissioned devices from living forever.
  216. for ip, pn in prev_nodes.items():
  217. if ip in nodes_ip:
  218. continue
  219. last_online = int(pn.get('last_online') or pn.get('last_seen') or prev_snap.get('generated') or 0)
  220. if last_online >= cutoff:
  221. offline_ips.add(ip)
  222. known_ips = set(nodes_ip) | offline_ips
  223. def name_role(name):
  224. n = (name or '').upper()
  225. if re.search(r'-(DIST)(-|$)', n): return 'distribution'
  226. if re.search(r'-(ACCESS)(-|$)', n): return 'access'
  227. if re.search(r'-(CORE)(-|$)', n): return 'core'
  228. return ''
  229. def node_tier(ip, name, pn=None):
  230. pn = pn or {}
  231. ch = int(pn.get('children') or 0)
  232. pt = str(pn.get('tier') or '').lower()
  233. # Graph degree is the protocol truth: a switch with children is an
  234. # aggregation/distribution point, regardless of a wrong name suffix.
  235. if ch > 0:
  236. return 'distribution'
  237. if pt in ('distribution', 'access'):
  238. return pt
  239. nr = name_role(name)
  240. if nr:
  241. return nr
  242. if pt == 'core': return 'core'
  243. return 'access'
  244. nodes = []
  245. for ip in sorted(known_ips, key=lambda x: (depth.get(x, 99), x)):
  246. online = ip in nodes_ip
  247. pn = prev_nodes.get(ip, {})
  248. hn = switch_hosts.get(ip, {})
  249. nm = sname.get(ip) or pn.get('name') or hn.get('name') or ip_name.get(ip) or ip
  250. al = ip_alarms.get(ip, [])
  251. maxsev = max([a['sev'] for a in al], default=-1)
  252. if online:
  253. ntier = tier(ip)
  254. ndepth = depth.get(ip, 99)
  255. nchildren = len(children.get(ip, []))
  256. oper = 'down' if avail.get(ip) == '2' else 'up'
  257. last_online = now
  258. else:
  259. ntier = node_tier(ip, nm, pn)
  260. ndepth = int(pn.get('depth', 99))
  261. nchildren = int(pn.get('children') or 0)
  262. oper = 'down'
  263. last_online = int(pn.get('last_online') or pn.get('last_seen') or prev_snap.get('generated') or now)
  264. nodes.append({
  265. 'id': ip, 'name': nm, 'ip': ip, 'tier': ntier, 'depth': ndepth,
  266. 'hostid': hid_by_ip.get(ip) or hn.get('hostid') or pn.get('hostid'),
  267. 'oper': oper, 'offline': not online,
  268. 'alarms': sorted(al, key=lambda a: -a['sev']), 'maxsev': maxsev,
  269. 'term_online': tcnt[ip]['online'], 'term_offline': 0,
  270. 'latency_ms': lat.get(ip) if online else pn.get('latency_ms'),
  271. 'children': nchildren, 'poe': bool(poe.get(ip, pn.get('poe', False))),
  272. 'last_online': last_online
  273. })
  274. # ---------- edges ----------
  275. edges = []
  276. edge_pairs = set()
  277. for k, d in pair.items():
  278. a, b = k
  279. p = d['ports']
  280. pa = p.get(a, {}); pb = p.get(b, {})
  281. a_port = pa.get('down') or pa.get('up') or ''
  282. b_port = pb.get('up') or pb.get('down') or ''
  283. speeds = []
  284. for ip, port in ((a, a_port), (b, b_port)):
  285. row = pmap.get((ip, port), {})
  286. try: sp = int(row.get('speed_mbps', '0') or 0)
  287. except: sp = 0
  288. speeds.append(sp)
  289. speed = max(speeds) if speeds else 0
  290. ops = []
  291. for ip, port in ((a, a_port), (b, b_port)):
  292. row = pmap.get((ip, port))
  293. ops.append(row.get('oper_status') if row else None)
  294. state = 'down' if ('down' in ops) else 'up'
  295. if a not in known_ips or b not in known_ips:
  296. continue
  297. edges.append({'source': a, 'target': b, 'speed': speed, 'state': state,
  298. 'a_port': a_port, 'b_port': b_port})
  299. edge_pairs.add(tuple(sorted((a, b))))
  300. # Keep the last-known uplink for an offline switch so it is shown in its
  301. # workshop frame and its historical position is not lost.
  302. for e in prev_edges:
  303. a, b = str(e.get('source')), str(e.get('target'))
  304. k = tuple(sorted((a, b)))
  305. if k in edge_pairs or a not in known_ips or b not in known_ips:
  306. continue
  307. if a in nodes_ip and b in nodes_ip:
  308. continue
  309. edges.append({'source': a, 'target': b, 'speed': e.get('speed', 0), 'state': 'down',
  310. 'a_port': e.get('a_port', ''), 'b_port': e.get('b_port', '')})
  311. edge_pairs.add(k)
  312. stats = {
  313. 'switches': len(nodes), 'switches_online': len(nodes_ip), 'switches_offline': len(offline_ips),
  314. 'poe_switches': sum(1 for n in nodes if n.get('poe')),
  315. 'edges': len(edges),
  316. 'term_total': len(terminals), 'term_online': len(terminals), 'term_offline': 0,
  317. 'alarms': sum(len(n['alarms']) for n in nodes),
  318. 'devices_alarm': sum(1 for n in nodes if n['alarms']),
  319. 'maxsev': max([n['maxsev'] for n in nodes], default=-1)
  320. }
  321. in_nodes = set(known_ips)
  322. other = []
  323. for ip, al in ip_alarms.items():
  324. if ip in in_nodes:
  325. continue
  326. for a in al:
  327. other.append({'ip': ip, 'host': ip_name.get(ip, ip), 'sev': a['sev'], 'name': a['name'], 'clock': a['clock']})
  328. other.sort(key=lambda x: -x['sev'])
  329. stats['other_alarms'] = len(other)
  330. snap = {'generated': now, 'generated_iso': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  331. 'refresh_default': 300, 'roots': roots, 'stats': stats,
  332. 'other_alarms': other,
  333. 'nodes': nodes, 'edges': edges, 'terminals': terminals}
  334. os.makedirs(os.path.dirname(OUT), exist_ok=True)
  335. tmp = OUT + '.tmp'
  336. with open(tmp, 'w', encoding='utf-8') as f:
  337. json.dump(snap, f, ensure_ascii=False, separators=(',', ':'))
  338. os.replace(tmp, OUT)
  339. print('snapshot', OUT, os.path.getsize(OUT), 'bytes;', stats)
  340. if os.environ.get('L2_WRITE_HISTORY', '0') == '1':
  341. try:
  342. write_history(snap, now)
  343. except Exception as e:
  344. print('history write error:', e)
  345. if __name__ == '__main__':
  346. main()