l2_snapshot.py 15 KB

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