app.js 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989
  1. /* =====================================================================
  2. L2 Physical Topology — display-only interactive map.
  3. Groups switches into frames (COBCO outer → workshop/DataCenter/Core),
  4. colours links by speed, nodes by latency & alarm, supports dark mode,
  5. terminal show / only-offline, live + historical snapshots, MAC/IP search.
  6. ===================================================================== */
  7. (function () {
  8. 'use strict';
  9. var CFG = window.L2_CFG || {};
  10. var T = window.L2_I18N || {};
  11. var META = window.L2_META || {};
  12. var SNAP = window.L2SNAP || null;
  13. var colors = CFG.colors || {100:'#F39C12',1000:'#2ECC71',10000:'#3498DB',20000:'#9B59B6',unknown:'#E74C3C',down:'#C0392B'};
  14. var LATW = (CFG.latency_warn != null) ? +CFG.latency_warn : 3;
  15. var LATB = (CFG.latency_bad != null) ? +CFG.latency_bad : 5;
  16. var TIER_BG = {core:'#1F4E78', dist:'#2E75B6', access:'#548235'};
  17. var TIER_BG_DARK = {core:'#1B4A72', dist:'#2A5E93', access:'#3E6B2E'};
  18. var SEV_COLORS = ['#97AAB3','#7499FF','#FFC859','#FFA059','#E97659','#E45959'];
  19. var NODE_W = 156, NODE_H = 50, GX = 26, GY = 18, PADX = 20, PADY = 42;
  20. var DGAP_X = 18, DGAP_Y = 26;
  21. var GROUP_GAP_X = 46, GROUP_GAP_Y = 48, MAXW = 2800;
  22. // overview ("全景") tiles
  23. var TILE_W = 232, TILE_H = 116, TILE_GAP_X = 24, TILE_GAP_Y = 22;
  24. var cy = null;
  25. var dark = false;
  26. var showTerm = false;
  27. var onlyOff = false;
  28. var pinnedTerm = null;
  29. var paused = false;
  30. var countdown = 0;
  31. var timer = null;
  32. var lastSnap = null;
  33. var viewGroup = null; // direct-link focus group, never hides the full chart
  34. var detailNet = null; // null/auto, 'SURVE' or 'OFFICE' inside a workshop
  35. var focusGroupLabel = null; // ?g= target, zoomed after the full chart is built
  36. var pathParent = {}; // child -> parent chain for hover highlighting
  37. var lastRoleMap = {}; // switch id -> computed display role
  38. var lockedPath = null; // switch id whose path is locked by click
  39. function el(id) { return document.getElementById(id); }
  40. function t(k, d) { return (T[k] != null) ? T[k] : (d != null ? d : k); }
  41. /* ---------------- name parsing / grouping ---------------- */
  42. function parseName(name) {
  43. var r = {workshop:'', floor:'', cab:'', u:'', area:'', role:'', ip:''};
  44. if (!name) return r;
  45. var toks = String(name).split('-');
  46. for (var i = 0; i < toks.length; i++) {
  47. var tk = toks[i];
  48. if (/^\d{1,3}(\.\d{1,3}){3}$/.test(tk)) { r.ip = tk; continue; }
  49. if (!r.workshop && /^\d{4}[A-Za-z]?$/.test(tk)) { r.workshop = tk; continue; }
  50. if (!r.floor) {
  51. var fm = /^(GRD|\d{1,2}F)([A-Z])?(\d+)?$/i.exec(tk);
  52. if (fm) { r.floor = fm[1].toUpperCase(); r.cab = fm[2] || ''; r.u = fm[3] || ''; continue; }
  53. }
  54. if (r.floor && !r.u && /^\d{1,3}$/.test(tk)) { r.u = tk; continue; }
  55. if (!r.area && /^(OFFICE|SURVE|GRDA|DC|IDC|LAB|PROD)$/i.test(tk)) { r.area = tk.toUpperCase(); continue; }
  56. if (!r.role && /^(Dist|Access|Core)$/i.test(tk)) { r.role = tk; }
  57. }
  58. return r;
  59. }
  60. function labelFor(n) {
  61. var p = parseName(n.name);
  62. var l1 = [];
  63. if (p.workshop) l1.push(p.workshop);
  64. if (p.area) l1.push(p.area);
  65. if (!l1.length) {
  66. l1.push((n.name || '').split('-')[0] || n.ip);
  67. }
  68. var l2 = [];
  69. if (p.floor) { var loc = p.floor + 'F' + (p.cab || '') + (p.u ? '-' + p.u + 'U' : ''); l1.push(loc); }
  70. if (p.role) l2.push(p.role);
  71. l2.push(n.ip);
  72. return l1.join(' · ') + '\n' + l2.join(' · ');
  73. }
  74. function detailLabel(n) {
  75. var s = labelFor(n);
  76. if (viewGroup) {
  77. var p = viewGroup + ' · ';
  78. if (s.indexOf(p) === 0) s = s.substring(p.length);
  79. }
  80. return s;
  81. }
  82. function rowLabel(n) {
  83. var s = String((n && n.name) || (n && n.ip) || '');
  84. s = s.replace(/^COBCO-/i, '');
  85. if (viewGroup) {
  86. try { s = s.replace(new RegExp('^' + viewGroup + '-', 'i'), ''); } catch (e) {}
  87. }
  88. return s;
  89. }
  90. function rootLabel(n) {
  91. var s = rowLabel(n);
  92. var m = /^(.+?)-(SURVE|OFFICE|OTHER)-(Dist|Access)-(.+)$/i.exec(s);
  93. if (m) return m[2].toUpperCase() + ' · ' + m[1] + '\n' + m[3] + ' · ' + m[4];
  94. return s;
  95. }
  96. function expandLabel(tpl, m) {
  97. return String(tpl).replace(/\$(\d)/g, function (_, d) { return m && m[+d] != null ? m[+d] : ''; });
  98. }
  99. function groupOf(n) {
  100. var name = n.name || n.ip || '';
  101. var rules = CFG.group_rules || [];
  102. for (var i = 0; i < rules.length; i++) {
  103. var r = rules[i];
  104. if (r.match === 'regex') {
  105. var re;
  106. try { re = new RegExp(r.pattern); } catch (e) { continue; }
  107. var m = re.exec(name);
  108. if (m) return {label: expandLabel(r.label, m) || (CFG.other_label || 'Other'), big: !!r.big};
  109. } else {
  110. if (name.toLowerCase().indexOf(String(r.pattern).toLowerCase()) >= 0) return {label: r.label || (CFG.other_label || 'Other'), big: !!r.big};
  111. }
  112. }
  113. return {label: CFG.other_label || 'Other', big: false};
  114. }
  115. /* ---------------- overview layout (workshop tiles) ---------------- */
  116. function groupStats(snap) {
  117. var map = {};
  118. var nodeById = {};
  119. (snap.nodes || []).forEach(function (n) {
  120. nodeById[n.id] = n;
  121. var g = groupOf(n);
  122. var s = map[g.label] || (map[g.label] = {label: g.label, big: g.big, nodes: [], alarms: 0, offline: 0, maxsev: -1, latmax: 0, up: 0});
  123. s.nodes.push(n);
  124. s.offline += (n.offline || n.oper === 'down') ? 1 : 0;
  125. if (n.alarms && n.alarms.length) {
  126. s.alarms += n.alarms.length;
  127. var sev = (n.maxsev != null && +n.maxsev >= 0) ? +n.maxsev : -1;
  128. n.alarms.forEach(function (a) { if (a && a.sev != null && +a.sev > sev) sev = +a.sev; });
  129. if (sev > s.maxsev) s.maxsev = sev;
  130. }
  131. if (n.latency_ms != null && +n.latency_ms > s.latmax) s.latmax = +n.latency_ms;
  132. });
  133. (snap.edges || []).forEach(function (e) {
  134. var a = nodeById[e.source], b = nodeById[e.target];
  135. if (!a || !b) return;
  136. var ga = groupOf(a), gb = groupOf(b);
  137. if (ga.label === gb.label) return;
  138. // count links that leave this workshop towards a core switch
  139. if ((/core/i.test(a.tier || '') || /core/i.test(a.name || '')) && map[gb.label]) map[gb.label].up++;
  140. if ((/core/i.test(b.tier || '') || /core/i.test(b.name || '')) && map[ga.label]) map[ga.label].up++;
  141. });
  142. return map;
  143. }
  144. function groupRank(l) {
  145. if (/core/i.test(l)) return 0;
  146. if (/data\s*center/i.test(l)) return 1;
  147. var m = /^(\d{4})([A-Za-z]?)$/.exec(l);
  148. if (m) return 1000 + parseInt(m[1], 10) * 40 + (m[2] ? m[2].toUpperCase().charCodeAt(0) - 64 : 0);
  149. return 5000;
  150. }
  151. function computeOverview(snap) {
  152. var stats = groupStats(snap);
  153. var labels = Object.keys(stats).sort(function (a, b) { return groupRank(a) - groupRank(b); });
  154. var special = labels.filter(function (l) { return groupRank(l) < 1000; });
  155. var others = labels.filter(function (l) { return groupRank(l) >= 1000; });
  156. var COLS = Math.max(4, Math.min(7, Math.ceil(Math.sqrt(Math.max(1, others.length)))));
  157. var gridW = COLS * TILE_W + (COLS - 1) * TILE_GAP_X;
  158. var pos = {}, tiles = [], y = 0;
  159. if (special.length) {
  160. var sW = special.length * TILE_W + (special.length - 1) * TILE_GAP_X;
  161. var sx = Math.max(0, (gridW - sW) / 2);
  162. special.forEach(function (l) {
  163. tiles.push({label: l, x: sx, y: y, w: TILE_W, h: TILE_H});
  164. pos[l] = {x: sx + TILE_W / 2, y: y + TILE_H / 2};
  165. sx += TILE_W + TILE_GAP_X;
  166. });
  167. y += TILE_H + 46;
  168. }
  169. var maxX = gridW, maxY = y;
  170. for (var i = 0; i < others.length; i += COLS) {
  171. var row = others.slice(i, i + COLS);
  172. var rW = row.length * TILE_W + (row.length - 1) * TILE_GAP_X;
  173. var rx = Math.max(0, (gridW - rW) / 2);
  174. row.forEach(function (l, j) {
  175. tiles.push({label: l, x: rx + j * (TILE_W + TILE_GAP_X), y: y, w: TILE_W, h: TILE_H});
  176. pos[l] = {x: rx + j * (TILE_W + TILE_GAP_X) + TILE_W / 2, y: y + TILE_H / 2};
  177. });
  178. y += TILE_H + TILE_GAP_Y;
  179. maxY = y - TILE_GAP_Y;
  180. maxX = Math.max(maxX, rx + rW);
  181. }
  182. var root = {x: -34, y: -64, w: maxX + 68, h: maxY + 64 + 40};
  183. root.cx = root.x + root.w / 2; root.cy = root.y + root.h / 2;
  184. return {stats: stats, labels: labels, pos: pos, tiles: tiles, root: root};
  185. }
  186. function aggregateEdges(snap) {
  187. var gid = {};
  188. (snap.nodes || []).forEach(function (n) { gid[n.id] = groupOf(n).label; });
  189. var pairs = {};
  190. (snap.edges || []).forEach(function (e) {
  191. var a = gid[e.source], b = gid[e.target];
  192. if (!a || !b || a === b) return;
  193. var k = (a < b) ? (a + '\u0001' + b) : (b + '\u0001' + a);
  194. var p = pairs[k] || (pairs[k] = {a: a, b: b, count: 0, speed: 0, down: false});
  195. p.count++;
  196. if ((parseFloat(e.speed) || 0) > p.speed) p.speed = parseFloat(e.speed) || 0;
  197. if (e.state && e.state !== 'up') p.down = true;
  198. });
  199. return Object.keys(pairs).map(function (k) { return pairs[k]; });
  200. }
  201. /* ---------------- detail layout (one workshop, left-to-right tree) ---------------- */
  202. function floorInfo(n) {
  203. var toks = String((n && n.name) || '').split('-');
  204. for (var i = 0; i < toks.length; i++) {
  205. var tk = toks[i];
  206. var bm = /^B(\d+)$/i.exec(tk);
  207. if (bm) { var bn = parseInt(bm[1], 10); return {key: 'B' + bn, label: 'B' + bn, rank: -200 + bn}; }
  208. if (/^GRD/i.test(tk)) return {key: 'GRD', label: 'GRD', rank: -100};
  209. var fm = /^(\d+(?:\.\d+)?)F/i.exec(tk);
  210. if (fm) {
  211. var num = parseFloat(fm[1]);
  212. var txt = (num % 1 ? num.toFixed(1) : String(num)) + 'F';
  213. return {key: txt, label: txt, rank: num * 10};
  214. }
  215. var cm = /^(\d)([A-Z])(\w+)$/i.exec(tk);
  216. if (cm) {
  217. var n2 = parseInt(cm[1], 10);
  218. return {key: n2 + 'F', label: n2 + 'F', rank: n2 * 10};
  219. }
  220. }
  221. return {key: 'NA', label: t('l2.floor_na', 'Other'), rank: -500};
  222. }
  223. function baseNetworkOf(n) {
  224. var s = String((n && n.name) || '').toUpperCase();
  225. if (s.indexOf('SURVE') >= 0) return 'SURVE';
  226. if (s.indexOf('OFFICE') >= 0) return 'OFFICE';
  227. var ip = String((n && n.ip) || '');
  228. if (/^10\.169\./.test(ip)) return 'SURVE';
  229. if (/^10\.160\./.test(ip)) return 'OFFICE';
  230. return 'OTHER';
  231. }
  232. function networkOf(n) { return baseNetworkOf(n); }
  233. function networkLabel(key) {
  234. if (key === 'SURVE') return t('l2.net_surve', 'SURVE 监控网');
  235. if (key === 'OFFICE') return t('l2.net_office', 'OFFICE 办公网');
  236. return t('l2.net_other', '其他网络');
  237. }
  238. function computeDetail(snap, label) {
  239. var all = snap.nodes || [];
  240. var byId = {}, groupNodes = [];
  241. all.forEach(function (n) { byId[n.id] = n; if (groupOf(n).label === label) groupNodes.push(n); });
  242. // Split one workshop by physical network first: office and surveillance never mix.
  243. var gids = {}, rawAdj = {};
  244. groupNodes.forEach(function (n) { gids[n.id] = true; rawAdj[n.id] = []; });
  245. (snap.edges || []).forEach(function (e) {
  246. if (gids[e.source] && gids[e.target]) { rawAdj[e.source].push(e.target); rawAdj[e.target].push(e.source); }
  247. });
  248. var netMap = {};
  249. groupNodes.forEach(function (n) { netMap[n.id] = baseNetworkOf(n); });
  250. // Unlabelled access switches inherit the network of the distribution they hang from.
  251. for (var pass = 0; pass < 4; pass++) {
  252. groupNodes.forEach(function (n) {
  253. if (netMap[n.id] !== 'OTHER') return;
  254. var votes = {};
  255. rawAdj[n.id].forEach(function (id) {
  256. var k = netMap[id];
  257. if (k && k !== 'OTHER') votes[k] = (votes[k] || 0) + 1;
  258. });
  259. var best = null, bestN = 0;
  260. Object.keys(votes).forEach(function (k) { if (votes[k] > bestN) { best = k; bestN = votes[k]; } });
  261. if (best) netMap[n.id] = best;
  262. });
  263. }
  264. var counts = {}, nets = [];
  265. groupNodes.forEach(function (n) {
  266. var k = netMap[n.id];
  267. if (!counts[k]) { counts[k] = 0; nets.push(k); }
  268. counts[k]++;
  269. });
  270. nets.sort(function (a, b) {
  271. if (a === 'SURVE') return -1;
  272. if (b === 'SURVE') return 1;
  273. if (a === 'OFFICE') return -1;
  274. if (b === 'OFFICE') return 1;
  275. return counts[b] - counts[a];
  276. });
  277. var activeNet = (detailNet && counts[detailNet]) ? detailNet : (nets.length ? nets[0] : 'OTHER');
  278. var nodes = groupNodes.filter(function (n) { return netMap[n.id] === activeNet; });
  279. var ids = {};
  280. nodes.forEach(function (n) { ids[n.id] = true; });
  281. var internal = [], external = [];
  282. (snap.edges || []).forEach(function (e) {
  283. var a = ids[e.source], b = ids[e.target];
  284. if (a && b) internal.push(e);
  285. else if (a || b) external.push(e);
  286. });
  287. var adj = {};
  288. nodes.forEach(function (n) { adj[n.id] = []; });
  289. internal.forEach(function (e) { adj[e.source].push(e.target); adj[e.target].push(e.source); });
  290. // Distribution switches are the left-hand roots of the workshop tree.
  291. var dists = nodes.filter(function (n) { return /dist/i.test(n.tier || '') && /dist/i.test(n.name || ''); })
  292. .sort(function (a, b) { return (adj[b.id].length - adj[a.id].length) || String(a.name).localeCompare(String(b.name)); });
  293. if (!dists.length) {
  294. var cand = nodes.slice().sort(function (a, b) { return adj[b.id].length - adj[a.id].length; })[0];
  295. if (cand) dists = [cand];
  296. }
  297. // One physical root per network tab; peer/redundant distribution switches are listed below it.
  298. if (dists.length > 1) dists = [dists[0]];
  299. // Group all non-distribution switches into floor buckets (GRD lowest, then 1F/2F/3F...).
  300. var floorMap = {};
  301. nodes.forEach(function (n) {
  302. if (dists.indexOf(n) >= 0) return;
  303. if (/core/i.test(n.tier || '')) return;
  304. var fi = floorInfo(n);
  305. var f = floorMap[fi.key] || (floorMap[fi.key] = {key: fi.key, label: fi.label, rank: fi.rank, nodes: []});
  306. f.nodes.push(n);
  307. });
  308. var floors = Object.keys(floorMap).map(function (k) { return floorMap[k]; });
  309. floors.forEach(function (f) {
  310. f.nodes.sort(function (a, b) {
  311. var pa = parseName(a.name), pb = parseName(b.name);
  312. var ca = (pa.cab || '') + (pa.u || ''), cb = (pb.cab || '') + (pb.u || '');
  313. if (ca !== cb) return ca.localeCompare(cb);
  314. return String(a.name).localeCompare(String(b.name));
  315. });
  316. });
  317. // Highest floor at the top, GRD at the bottom.
  318. floors.sort(function (a, b) { return b.rank - a.rank; });
  319. var WORK_L = 300, FLOOR_X = 520, DIST_FRAME_W = 190, TOP_OFF = 34;
  320. var ROW_W = 380, ROW_H = 24, ROW_GAP = 8, FLOOR_HEAD = 28, FLOOR_GAP = 12;
  321. var floorW = ROW_W + PADX * 2 + 110;
  322. floors.forEach(function (f) {
  323. f.cols = 1;
  324. f.rows = f.nodes.length;
  325. f.innerW = ROW_W;
  326. f.h = FLOOR_HEAD + f.rows * ROW_H + Math.max(0, f.rows - 1) * ROW_GAP + 10;
  327. });
  328. var workRight = FLOOR_X + floorW + 14;
  329. var workW = workRight - WORK_L;
  330. var pos = {}, top = 44 + TOP_OFF;
  331. floors.forEach(function (f) {
  332. f.frame = {x: FLOOR_X, y: top, w: floorW, h: f.h};
  333. f.nodes.forEach(function (n, i) {
  334. pos[n.id] = {
  335. x: FLOOR_X + PADX + ROW_W / 2,
  336. y: top + FLOOR_HEAD + i * (ROW_H + ROW_GAP) + ROW_H / 2
  337. };
  338. });
  339. top += f.h + FLOOR_GAP;
  340. });
  341. var workH = Math.max(220, top + 6);
  342. var distFrame = dists.length ? {x: WORK_L + 8, y: 44 + TOP_OFF, w: DIST_FRAME_W, h: workH - (44 + TOP_OFF) - 14} : null;
  343. var distX = WORK_L + 8 + DIST_FRAME_W / 2;
  344. if (dists.length) {
  345. var childYs = floors.reduce(function (acc, f) {
  346. return acc.concat(f.nodes.map(function (n) { return pos[n.id] ? pos[n.id].y : 0; }));
  347. }, []);
  348. var cy = childYs.length ? (Math.min.apply(null, childYs) + Math.max.apply(null, childYs)) / 2 : distFrame.y + distFrame.h / 2;
  349. pos[dists[0].id] = {x: distX, y: cy};
  350. }
  351. var missing = nodes.filter(function (n) { return !pos[n.id]; });
  352. missing.forEach(function (n, i) {
  353. pos[n.id] = {x: distX, y: (distFrame ? distFrame.y + 30 : 80) + i * (NODE_H + 12)};
  354. });
  355. // One ghost core per external core→distribution uplink, aligned left of its distribution switch.
  356. var ghosts = [], ghostSeen = {};
  357. external.forEach(function (e) {
  358. var inside = ids[e.source] ? e.source : e.target;
  359. var outside = ids[e.source] ? e.target : e.source;
  360. if (!pos[inside] || !byId[outside]) return;
  361. // Only a real core uplink gets a ghost; other cross-group edges are not drawn as cores.
  362. if (!/core/i.test(byId[outside].tier || '') && !/core/i.test(byId[outside].name || '')) return;
  363. var key = outside + '|' + inside;
  364. if (ghostSeen[key]) return;
  365. var g = {id: 'gh_' + outside + '_' + inside, to: inside, node: byId[outside], speed: e.speed, state: e.state};
  366. ghostSeen[key] = g;
  367. ghosts.push(g);
  368. });
  369. var ghostAt = {};
  370. ghosts.forEach(function (g) {
  371. var base = pos[g.to];
  372. var k = ghostAt[g.to] || 0;
  373. ghostAt[g.to] = k + 1;
  374. g.x = 92;
  375. g.y = base.y + (k ? (k % 2 ? 1 : -1) * 46 * Math.ceil(k / 2) : 0);
  376. });
  377. // Root each tree at the distribution switch; remember every child's parent for path highlighting.
  378. var parentOf = {}, ghostOfDist = {};
  379. ghosts.forEach(function (g) { if (!ghostOfDist[g.to]) ghostOfDist[g.to] = g.id; });
  380. var seen = {};
  381. dists.forEach(function (d) {
  382. if (seen[d.id]) return;
  383. seen[d.id] = true;
  384. parentOf[d.id] = ghostOfDist[d.id] || null;
  385. var queue = [d.id];
  386. while (queue.length) {
  387. var cur = queue.shift();
  388. adj[cur].forEach(function (nb) {
  389. if (seen[nb]) return;
  390. seen[nb] = true;
  391. parentOf[nb] = cur;
  392. queue.push(nb);
  393. });
  394. }
  395. });
  396. nodes.forEach(function (n) { if (!seen[n.id]) seen[n.id] = true; });
  397. var workshop = {x: WORK_L, y: 0, w: workW, h: workH, label: label + ' · ' + networkLabel(activeNet) + ' · ' + nodes.length + ' ' + t('l2.unit_sw', 'sw')};
  398. var distFrameFull = distFrame ? {
  399. x: distFrame.x, y: distFrame.y, w: distFrame.w, h: distFrame.h,
  400. label: t('l2.dist', 'Distribution') + ' · ' + dists.length
  401. } : null;
  402. floors.forEach(function (f) {
  403. f.frame.label = f.label + ' · ' + f.nodes.length + ' ' + t('l2.unit_sw', 'sw');
  404. });
  405. var root = {x: -20, y: -48, w: workRight + 40, h: workH + 80};
  406. root.cx = root.x + root.w / 2; root.cy = root.y + root.h / 2;
  407. return {
  408. nodes: nodes, byId: byId, pos: pos, ghosts: ghosts, parentOf: parentOf,
  409. dists: dists, floors: floors, frames: {workshop: workshop, dist: distFrameFull},
  410. root: root, totalW: workRight, ids: ids, internal: internal,
  411. nets: nets.map(function (k) { return {key: k, count: counts[k]}; }), activeNet: activeNet, totalNodes: groupNodes.length
  412. };
  413. }
  414. /* ---------------- one-chart layout: fixed columns by tier ----------------
  415. Left to right: physical core → each network's main switch → every
  416. workshop distribution switch → access switches. A workshop frame spans
  417. the distribution + access columns; each floor is a small frame inside it.
  418. Same workshop on two networks is always two separate frames. */
  419. var CORE_X = 130, MAIN_X = 430, DIST_X = 790, ACCESS_X = 1300;
  420. var CORE_W = 200, MAIN_W = 300, NODE_W3 = 300;
  421. var WORK_LEFT = 610, WORK_RIGHT = 1530;
  422. var FLOOR_LEFT = 1130;
  423. var CHART_W = 1560;
  424. var ACCESS_STEP = 380, DIST_STEP = 86;
  425. var SEC_HEAD = 46, CORE_ROW = 92, WORK_TOP = 148;
  426. var ROW_H = 34, ROW_GAP = 14, WS_GAP = 36, SEC_GAP = 52;
  427. var FLOOR_GAP = 26;
  428. function makeNetworks() {
  429. var raw = CFG.networks;
  430. if (!raw || !raw.length) {
  431. raw = [
  432. {key: 'SURVE', label: t('l2.net_surve', 'SURVE 监控网'), keywords: ['SURVE', '10.169.'], color: '#2E75B6'},
  433. {key: 'OFFICE', label: t('l2.net_office', 'OFFICE 办公网'), keywords: ['OFFICE', '10.160.'], color: '#548235'}
  434. ];
  435. }
  436. return raw.map(function (n, i) {
  437. var kws = n.keywords;
  438. if (!(kws instanceof Array)) kws = String(kws || '').split(/[,,;;\s]+/);
  439. return {
  440. key: String(n.key || ('NET' + i)).trim().toUpperCase(),
  441. label: String(n.label || n.key || ('NET' + i)),
  442. keywords: kws.map(function (s) { return String(s).trim(); }).filter(Boolean),
  443. color: /^#[0-9a-fA-F]{6}$/.test(String(n.color || '')) ? n.color : '#607D8B'
  444. };
  445. });
  446. }
  447. var NETWORKS = makeNetworks();
  448. function netLabel(key) {
  449. for (var i = 0; i < NETWORKS.length; i++) if (NETWORKS[i].key === key) return NETWORKS[i].label;
  450. return key === 'OTHER' ? t('l2.net_other', '其他网络') : String(key || '');
  451. }
  452. function netColor(key) {
  453. for (var i = 0; i < NETWORKS.length; i++) if (NETWORKS[i].key === key) return NETWORKS[i].color;
  454. return '#607D8B';
  455. }
  456. function rawNetOf(n) {
  457. var hay = (String((n && n.name) || '') + ' ' + String((n && n.ip) || '')).toUpperCase();
  458. for (var i = 0; i < NETWORKS.length; i++) {
  459. for (var j = 0; j < NETWORKS[i].keywords.length; j++) {
  460. if (hay.indexOf(String(NETWORKS[i].keywords[j]).toUpperCase()) >= 0) return NETWORKS[i].key;
  461. }
  462. }
  463. return 'OTHER';
  464. }
  465. // Core/root switch rules are configured from the L2 tab, one row per core.
  466. // Multiple cores in the same network are supported and all of them are
  467. // placed in the left-most core column.
  468. function coreRules() {
  469. var r = CFG.core_rules;
  470. return (r instanceof Array) ? r : [];
  471. }
  472. function coreRuleHit(rule, n) {
  473. var pattern = String(rule.pattern || '');
  474. if (!pattern) return false;
  475. var net = String(rule.net || '').toUpperCase();
  476. if (net) {
  477. var raw = rawNetOf(n);
  478. // A core with no recognisable network keyword may still be assigned by
  479. // the rule; a switch already known to belong to another network must
  480. // not be stolen by a broad pattern.
  481. if (raw !== 'OTHER' && raw !== net) return false;
  482. }
  483. var hay = String((n && n.name) || '') + ' ' + String((n && n.ip) || '');
  484. if (String(rule.match || 'contains') === 'regex') {
  485. try { return new RegExp(pattern, 'i').test(hay); } catch (e) { return false; }
  486. }
  487. return hay.toLowerCase().indexOf(pattern.toLowerCase()) >= 0;
  488. }
  489. function configuredCore(n) {
  490. var rules = coreRules();
  491. for (var i = 0; i < rules.length; i++) if (coreRuleHit(rules[i], n)) return true;
  492. return false;
  493. }
  494. function configuredCoreNet(n) {
  495. var rules = coreRules();
  496. for (var i = 0; i < rules.length; i++) {
  497. if (coreRuleHit(rules[i], n) && String(rules[i].net || '').trim() !== '') return String(rules[i].net).toUpperCase();
  498. }
  499. return '';
  500. }
  501. // Network is decided first by name/IP keyword, then by the rest of the
  502. // workshop, then by graph adjacency. No switch is ever shown under the
  503. // wrong upstream network.
  504. function assignNetworks(snap) {
  505. var nodes = snap.nodes || [], byId = {}, net = {}, adj = {};
  506. nodes.forEach(function (n) {
  507. byId[n.id] = n; net[n.id] = rawNetOf(n); adj[n.id] = [];
  508. var cn = configuredCoreNet(n);
  509. if (cn) net[n.id] = cn;
  510. });
  511. (snap.edges || []).forEach(function (e) {
  512. if (adj[e.source] && adj[e.target]) { adj[e.source].push(e.target); adj[e.target].push(e.source); }
  513. });
  514. var groupVote = {};
  515. nodes.forEach(function (n) {
  516. var k = groupOf(n).label, v = net[n.id];
  517. if (v && v !== 'OTHER') (groupVote[k] = groupVote[k] || {})[v] = true;
  518. });
  519. nodes.forEach(function (n) {
  520. if (net[n.id] !== 'OTHER') return;
  521. var v = groupVote[groupOf(n).label], keys = v ? Object.keys(v) : [];
  522. if (keys.length === 1) net[n.id] = keys[0];
  523. });
  524. for (var pass = 0; pass < 8; pass++) {
  525. var changed = false;
  526. nodes.forEach(function (n) {
  527. if (net[n.id] !== 'OTHER') return;
  528. var votes = {};
  529. adj[n.id].forEach(function (id) { if (net[id] && net[id] !== 'OTHER') votes[net[id]] = (votes[net[id]] || 0) + 1; });
  530. var best = null, bn = 0;
  531. Object.keys(votes).forEach(function (k) { if (votes[k] > bn) { best = k; bn = votes[k]; } });
  532. if (best) { net[n.id] = best; changed = true; }
  533. });
  534. if (!changed) break;
  535. }
  536. return net;
  537. }
  538. function roleOf(n) {
  539. var p = parseName(n.name || '');
  540. var r = String(p.role || '').toLowerCase();
  541. var tier = String(n.tier || '').toLowerCase();
  542. var childCount = parseInt(n.children, 10);
  543. if (isNaN(childCount)) childCount = -1;
  544. if (configuredCore(n)) return 'core';
  545. // Backward-compatible fallback only when the core list is absent (old
  546. // config). An explicitly empty list means the administrator wants no
  547. // configured core column.
  548. if (!(CFG.core_rules instanceof Array) && (/^core(\s|-)/i.test(String(n.name || '')) || groupOf(n).label === 'Core')) return 'core';
  549. // Hostname role is the display truth for Access switches. An access
  550. // switch may itself have access children (cascade/stack); it still stays
  551. // an access node and the children simply take a further-right column.
  552. // A Dist switch stays a distribution point even when it has only one child.
  553. if (r === 'access') return 'access';
  554. if (r === 'dist') {
  555. // Old snapshots sometimes call a leaf "Dist"; if it has no children and
  556. // the collector already marked it as access, keep it an access leaf.
  557. if (tier === 'access' && childCount <= 0) return 'access';
  558. return 'dist';
  559. }
  560. if (r === 'core') return childCount > 0 ? 'dist' : 'main';
  561. if (tier === 'core') {
  562. if (childCount > 0) return 'dist';
  563. return 'main';
  564. }
  565. if (childCount > 0) return 'dist';
  566. if (tier === 'distribution') return 'dist';
  567. return 'access';
  568. }
  569. function roleName(r) {
  570. if (r === 'core') return t('l2.core', '核心');
  571. if (r === 'main') return t('l2.main', '主交换');
  572. if (r === 'dist') return t('l2.dist', '汇聚');
  573. return t('l2.access', '接入');
  574. }
  575. function shortLoc(n) {
  576. var p = parseName(n.name || '');
  577. if (!p.floor) return '';
  578. return p.floor + (p.cab || '') + (p.u ? '-' + p.u : '');
  579. }
  580. function switchLabel(n, role, netKey) {
  581. var g = groupOf(n).label;
  582. if (role === 'core') return roleName('core') + ' · ' + (netKey || rawNetOf(n)) + ' · ' + (n.ip || '');
  583. if (role === 'main') return roleName('main') + ' · ' + g + ' · ' + (n.ip || '');
  584. var loc = shortLoc(n);
  585. return [g, loc, roleName(role)].filter(Boolean).join(' · ') + ' · ' + (n.ip || '');
  586. }
  587. // A workshop is the physical area served by one distribution switch, not
  588. // the four-digit prefix printed on each access switch. The same dist can
  589. // serve access switches in several rooms/buildings; they must share one
  590. // frame, otherwise their uplink line would cross unrelated frames.
  591. function workshopKeys(snap) {
  592. var byId = {}, adj = {}, keys = {};
  593. (snap.nodes || []).forEach(function (n) { byId[n.id] = n; adj[n.id] = []; });
  594. (snap.edges || []).forEach(function (e) {
  595. if (adj[e.source] && adj[e.target]) { adj[e.source].push(e.target); adj[e.target].push(e.source); }
  596. });
  597. function depthOf(n) {
  598. var d = parseInt(n && n.depth, 10);
  599. return (isFinite(d) && d >= 0 && d < 99) ? d : 999;
  600. }
  601. // Walk upstream to the highest non-core node. This is the real workshop
  602. // anchor. It keeps cascaded access (2.59 -> 2.75) in the 4401 frame while
  603. // still allowing an access switch that is itself an anchor (4504 -> .118/
  604. // 6109 access) to own one frame. No protocol edge is changed here.
  605. function rootOf(n) {
  606. var cur = n, guard = 0;
  607. while (cur && guard++ < 80) {
  608. var cd = depthOf(cur), best = null;
  609. (adj[cur.id] || []).forEach(function (id) {
  610. var up = byId[id];
  611. if (!up || up.id === cur.id) return;
  612. var ud = depthOf(up);
  613. if (ud < cd) {
  614. if (!best || ud < depthOf(best)) best = up;
  615. }
  616. });
  617. if (!best) return cur;
  618. if (roleOf(best) === 'core') return cur;
  619. cur = best;
  620. }
  621. return cur || n;
  622. }
  623. (snap.nodes || []).forEach(function (n) {
  624. var r = roleOf(n);
  625. if (r === 'core' || r === 'main') return;
  626. var root = rootOf(n);
  627. keys[n.id] = groupOf(root || n).label;
  628. });
  629. return keys;
  630. }
  631. function workshopList(snap, netMap, netKey, wsKeys) {
  632. var map = {}, order = [];
  633. (snap.nodes || []).forEach(function (n) {
  634. if (netMap[n.id] !== netKey) return;
  635. var r = roleOf(n);
  636. if (r === 'core' || r === 'main') return;
  637. var g = (wsKeys && wsKeys[n.id]) || groupOf(n).label;
  638. if (!map[g]) { map[g] = {key: g, label: g, extra: [], net: netKey, dists: [], access: [], all: []}; order.push(g); }
  639. map[g].all.push(n);
  640. if (r === 'dist') map[g].dists.push(n); else map[g].access.push(n);
  641. });
  642. return order.map(function (g) { return map[g]; }).filter(function (w) { return w.all.length > 0; })
  643. .map(function (w) {
  644. w.access.forEach(function (a) {
  645. var raw = groupOf(a).label;
  646. if (raw !== w.key && w.extra.indexOf(raw) < 0) w.extra.push(raw);
  647. });
  648. w.label = w.key + (w.extra.length ? ' + ' + w.extra.slice(0, 3).join('/') + (w.extra.length > 3 ? '…' : '') : '');
  649. return w;
  650. });
  651. }
  652. function layoutWorkshop(w, top, snap) {
  653. var rowH = ROW_H + ROW_GAP + (showTerm ? 24 : 0);
  654. var floorMap = {}, floors = [], accessFloor = {};
  655. w.access.forEach(function (n) {
  656. var fi = floorInfo(n);
  657. var k = fi.key;
  658. if (!floorMap[k]) { floorMap[k] = {key: k, label: fi.label, rank: (fi.key === 'NA' ? 999 : fi.rank), nodes: [], rows: []}; floors.push(floorMap[k]); }
  659. floorMap[k].nodes.push(n);
  660. accessFloor[n.id] = k;
  661. });
  662. floors.sort(function (a, b) { return a.rank - b.rank || String(a.label).localeCompare(String(b.label)); });
  663. // Build the access sub-columns from the real graph: direct children of a
  664. // dist are column 0, their access children column 1, and so on. No
  665. // logical parent/child is replaced by this; it only decides x positions.
  666. var byId = {}, adj = {}, member = {};
  667. w.all.forEach(function (n) { byId[n.id] = n; adj[n.id] = []; member[n.id] = true; });
  668. (snap.edges || []).forEach(function (e) {
  669. if (member[e.source] && member[e.target]) { adj[e.source].push(e.target); adj[e.target].push(e.source); }
  670. });
  671. function numDepth(n) {
  672. var d = parseInt(n && n.depth, 10);
  673. return (isFinite(d) && d >= 0 && d < 99) ? d : 99;
  674. }
  675. var starts = w.dists.map(function (n) { return n.id; });
  676. if (!starts.length) {
  677. // A frame with no Dist (e.g. 4504 when its hostname says Access) still
  678. // has a top access node. Find nodes with no upstream member.
  679. w.access.forEach(function (n) {
  680. var up = false;
  681. (adj[n.id] || []).forEach(function (id) {
  682. var other = byId[id];
  683. if (other && numDepth(other) < numDepth(n)) up = true;
  684. });
  685. if (!up) starts.push(n.id);
  686. });
  687. if (!starts.length && w.access.length) starts.push(w.access[0].id);
  688. }
  689. var level = {}, queue = [];
  690. starts.forEach(function (id) { if (byId[id]) { level[id] = 0; queue.push(id); } });
  691. while (queue.length) {
  692. var cur = queue.shift();
  693. (adj[cur] || []).forEach(function (id) {
  694. if (!byId[id] || level[id] != null) return;
  695. level[id] = level[cur] + 1;
  696. queue.push(id);
  697. });
  698. }
  699. var base = w.dists.length ? 1 : 0;
  700. w.access.forEach(function (n) {
  701. var lv = level[n.id];
  702. n._col = (lv == null) ? 0 : Math.max(0, lv - base);
  703. if (n._col > 12) n._col = 12;
  704. });
  705. var maxCol = 0;
  706. floors.forEach(function (f) {
  707. // A child fed from another floor (e.g. 1FA-27 2.59 -> GRD 2.75) is put
  708. // at the top of its own floor frame. Its straight line then stays out
  709. // of the labels of the floor's normal first column.
  710. function parentFloorKey(n) {
  711. var best = null, bestD = 999;
  712. (adj[n.id] || []).forEach(function (id) {
  713. var up = byId[id];
  714. if (!up || !accessFloor[id]) return;
  715. var ud = numDepth(up);
  716. if (ud < numDepth(n) && ud < bestD) { best = up; bestD = ud; }
  717. });
  718. return best ? accessFloor[best.id] : f.key;
  719. }
  720. f.nodes.sort(function (a, b) {
  721. var ca = (parentFloorKey(a) === f.key ? 1 : 0) - (parentFloorKey(b) === f.key ? 1 : 0);
  722. if (ca) return ca;
  723. var cc = (a._col || 0) - (b._col || 0);
  724. if (cc) return cc;
  725. return String(a.name).localeCompare(String(b.name));
  726. });
  727. f.nodes.forEach(function (n) { maxCol = Math.max(maxCol, n._col || 0); f.maxCol = Math.max(f.maxCol || 0, n._col || 0); });
  728. f.crossFloor = f.nodes.some(function (n) { return parentFloorKey(n) !== f.key; });
  729. f.h = 28 + f.nodes.length * rowH + 10;
  730. });
  731. var accessH = 0;
  732. floors.forEach(function (f) { accessH += f.h; });
  733. if (floors.length > 1) accessH += (floors.length - 1) * FLOOR_GAP;
  734. var distH = w.dists.length ? (w.dists.length * DIST_STEP + (w.dists.length - 1) * 10) : 0;
  735. var inner = Math.max(accessH, distH, 54);
  736. var h = 40 + inner + 12;
  737. w.top = top; w.h = h; w.rowH = rowH;
  738. w.right = Math.max(WORK_RIGHT, ACCESS_X + maxCol * ACCESS_STEP + NODE_W3 / 2 + 26);
  739. // Floors are stacked bottom-up: GRD lowest, then 1F → 3F → 4F → 7F.
  740. var cursor = top + h - 10;
  741. floors.forEach(function (f) {
  742. cursor -= f.h;
  743. var floorW = Math.max(340, ACCESS_X + (f.maxCol || 0) * ACCESS_STEP + NODE_W3 / 2 + 26 - FLOOR_LEFT);
  744. f.frame = {x: FLOOR_LEFT, y: cursor, w: floorW, h: f.h};
  745. if (f.crossFloor) f.labelX = FLOOR_LEFT + 72;
  746. f.nodes.forEach(function (n, i) {
  747. f.rows.push({id: n.id, x: ACCESS_X + (n._col || 0) * ACCESS_STEP, y: cursor + 28 + rowH / 2 + i * rowH});
  748. });
  749. cursor -= FLOOR_GAP;
  750. });
  751. var dstart = top + 40 + (inner - distH) / 2;
  752. w.distPos = w.dists.map(function (n, i) {
  753. return {id: n.id, x: DIST_X, y: dstart + DIST_STEP / 2 + i * (DIST_STEP + 10)};
  754. });
  755. w.floors = floors;
  756. w.title = w.label + ' · ' + netLabel(w.net) + ' · ' + w.all.length + ' ' + t('l2.unit_sw', '台');
  757. // A workshop without a distribution switch only needs a box around its
  758. // access columns; keeping the full dist-column width would leave a large
  759. // empty rectangle and make the chart look sparse.
  760. var frameLeft = w.dists.length ? WORK_LEFT : FLOOR_LEFT - 40;
  761. w.frame = {x: frameLeft, y: top, w: w.right - frameLeft, h: h};
  762. return h;
  763. }
  764. function computeFull(snap) {
  765. var nodes = snap.nodes || [];
  766. var netMap = assignNetworks(snap);
  767. var sections = [], placements = [], frames = [], roleMap = {};
  768. var wsKeys = workshopKeys(snap);
  769. var y = 100, maxRight = CHART_W;
  770. NETWORKS.forEach(function (net) {
  771. var secNodes = nodes.filter(function (n) { return netMap[n.id] === net.key; });
  772. if (!secNodes.length) return;
  773. var cores = [], main = null;
  774. secNodes.forEach(function (n) {
  775. roleMap[n.id] = roleOf(n);
  776. if (roleMap[n.id] === 'core') cores.push(n);
  777. if (roleMap[n.id] === 'main' && !main) main = n;
  778. });
  779. var ws = workshopList(snap, netMap, net.key, wsKeys);
  780. var sec = {
  781. key: net.key, label: netLabel(net.key) + ' · ' + secNodes.length + ' ' + t('l2.unit_sw', '台'),
  782. x: 10, y: y, w: CHART_W - 20, h: 0, color: netColor(net.key),
  783. core: cores[0] || null, cores: cores, main: main, workshops: ws
  784. };
  785. var cur = y + WORK_TOP;
  786. ws.forEach(function (w) {
  787. layoutWorkshop(w, cur, snap);
  788. maxRight = Math.max(maxRight, w.right || WORK_RIGHT);
  789. cur += w.h + WS_GAP;
  790. frames.push({id: 'ws_' + net.key + '_' + w.key, type: 'wsframe', x: w.frame.x, y: w.frame.y, w: w.frame.w, h: w.frame.h,
  791. label: w.title, group: w.key, net: net.key, color: net.color});
  792. w.floors.forEach(function (f, fi) {
  793. frames.push({id: 'ff_' + net.key + '_' + w.key + '_' + fi, type: 'floorframe', x: f.frame.x, y: f.frame.y,
  794. w: f.frame.w, h: f.frame.h, label: f.label + ' · ' + f.nodes.length + ' ' + t('l2.unit_sw', '台'), labelX: f.labelX, net: net.key, color: net.color});
  795. });
  796. w.distPos.forEach(function (p) {
  797. var n = nodes.filter(function (x) { return x.id === p.id; })[0];
  798. if (n) placements.push({node: n, role: 'dist', x: p.x, y: p.y, w: NODE_W3, h: 26, net: net.key, group: w.key, ws: net.key + '|' + w.key});
  799. });
  800. w.floors.forEach(function (f) {
  801. f.rows.forEach(function (p) {
  802. var n = nodes.filter(function (x) { return x.id === p.id; })[0];
  803. if (n) placements.push({node: n, role: 'access', x: p.x, y: p.y, w: NODE_W3, h: 26, net: net.key, group: w.key, ws: net.key + '|' + w.key});
  804. });
  805. });
  806. });
  807. sec.h = (cur - y) + 16;
  808. // The network main switch stays at the top of its tier column (its access
  809. // children sit directly under it, as in the reference chart); the core
  810. // sits lower in the column so its uplinks fan symmetrically.
  811. sec.mainY = y + SEC_HEAD + 46;
  812. sec.coreY = y + Math.max(CORE_ROW + SEC_HEAD, Math.round(sec.h * 0.55));
  813. if (cores.length) {
  814. var coreStep = 64;
  815. var coreTop = sec.coreY - ((cores.length - 1) * coreStep) / 2;
  816. cores.forEach(function (cn, ci) {
  817. placements.push({node: cn, role: 'core', x: CORE_X, y: coreTop + ci * coreStep, w: CORE_W, h: 54, net: net.key, group: 'Core'});
  818. });
  819. }
  820. if (main) placements.push({node: main, role: 'main', x: MAIN_X, y: sec.mainY, w: MAIN_W, h: 46, net: net.key, group: groupOf(main).label});
  821. sections.push(sec);
  822. y += sec.h + SEC_GAP;
  823. });
  824. var chartW = Math.max(CHART_W, maxRight + 40);
  825. sections.forEach(function (sec) { sec.w = chartW - 20; });
  826. var root = {x: 0, y: 0, w: chartW, h: y + 6};
  827. return {sections: sections, placements: placements, frames: frames, netMap: netMap, roleMap: roleMap, root: root};
  828. }
  829. // Immediate upstream parent per switch: access -> its workshop dist;
  830. // dist -> core when directly attached, otherwise the network main switch.
  831. function buildParents(snap, L) {
  832. var byId = {}, adj = {}, edgeSpeed = {};
  833. L.placements.forEach(function (p) { byId[p.node.id] = p; });
  834. (snap.nodes || []).forEach(function (n) { adj[n.id] = []; });
  835. (snap.edges || []).forEach(function (e) {
  836. if (!adj[e.source] || !adj[e.target]) return;
  837. adj[e.source].push(e.target); adj[e.target].push(e.source);
  838. edgeSpeed[e.source + '|' + e.target] = edgeSpeed[e.target + '|' + e.source] = parseFloat(e.speed) || 0;
  839. });
  840. var parent = {};
  841. Object.keys(byId).forEach(function (id) {
  842. var role = L.roleMap[id] || 'access';
  843. if (role === 'core') return;
  844. var p = byId[id], cands = (adj[id] || []).map(function (x) { return {id: x, role: L.roleMap[x] || 'access', p: byId[x]}; })
  845. .filter(function (c) { return c.p; });
  846. var want = role === 'main' ? ['core'] : (role === 'dist' ? ['core', 'main'] : ['dist', 'main', 'core']);
  847. var best = null;
  848. for (var wi = 0; wi < want.length && !best; wi++) {
  849. var list = cands.filter(function (c) {
  850. if (c.role !== want[wi]) return false;
  851. if (role === 'access' && want[wi] === 'dist' && c.p.ws && p.ws && c.p.ws !== p.ws) return false;
  852. return true;
  853. });
  854. if (list.length) {
  855. list.sort(function (a, b) { return (edgeSpeed[id + '|' + b.id] || 0) - (edgeSpeed[id + '|' + a.id] || 0); });
  856. best = list[0];
  857. }
  858. }
  859. if (best) parent[id] = best.id;
  860. });
  861. return parent;
  862. }
  863. /* ---------------- speed colour ---------------- */
  864. function speedColor(speed, state) {
  865. if (state && state !== 'up') return colors.down;
  866. var s = parseFloat(speed);
  867. if (!isFinite(s) || s <= 0) return colors.unknown;
  868. if (s <= 100) return colors['100'];
  869. if (s <= 1000) return colors['1000'];
  870. if (s <= 10000) return colors['10000'];
  871. return colors['20000'];
  872. }
  873. function speedWidth(speed) {
  874. var s = parseFloat(speed) || 0;
  875. if (s >= 20000) return 4.5;
  876. if (s >= 10000) return 3.6;
  877. if (s >= 1000) return 2.6;
  878. return 1.8;
  879. }
  880. function speedText(speed) {
  881. var s = parseFloat(speed) || 0;
  882. if (!s) return '?';
  883. if (s >= 1000) return (s / 1000) + 'G';
  884. return s + 'M';
  885. }
  886. function terminalOnline(tm) {
  887. return tm && (tm.online === true || tm.online === 1 || tm.online === '1' || tm.online === 'true');
  888. }
  889. function terminalText(tm) {
  890. return tm.mac + '\n' + speedText(tm.speed);
  891. }
  892. /* ---------------- style ---------------- */
  893. function styleFor(d) {
  894. var bg = d ? TIER_BG_DARK : TIER_BG;
  895. return [
  896. {selector: 'node', style: {
  897. 'width': 'data(w)', 'height': 'data(h)', 'shape': 'round-rectangle',
  898. 'background-color': 'data(bg)', 'border-width': 2, 'border-color': 'data(bd)',
  899. 'label': 'data(label)', 'color': d ? '#eaf1fb' : '#ffffff',
  900. 'font-size': 11.5, 'font-weight': 600, 'text-valign': 'center', 'text-halign': 'center',
  901. 'text-wrap': 'wrap', 'text-max-width': NODE_W - 16, 'padding': '2px',
  902. 'overlay-opacity': 0, 'z-index-compare': 'manual', 'z-index': 20
  903. }},
  904. {selector: 'node[type="frame"]', style: {
  905. 'background-opacity': d ? 0.05 : 0.035, 'background-color': d ? '#5b7bb0' : '#8fa6c4',
  906. 'border-width': 1.6, 'border-style': 'dashed', 'border-color': d ? '#3f5377' : '#c2ccdb',
  907. 'label': 'data(label)', 'text-valign': 'top', 'text-halign': 'center',
  908. 'font-size': 'data(fs)', 'font-weight': 800, 'color': d ? '#aebfd8' : '#526178',
  909. 'text-margin-y': 8, 'padding': '0px', 'events': 'no', 'z-index-compare': 'manual', 'z-index': 2
  910. }},
  911. {selector: 'node[type="netframe"]', style: {
  912. 'background-opacity': d ? 0.03 : 0.02, 'background-color': d ? '#7b91b8' : '#adc0d8',
  913. 'border-width': 3, 'border-style': 'solid', 'border-color': 'data(bd)',
  914. 'label': 'data(label)', 'text-valign': 'top', 'text-halign': 'center',
  915. 'font-size': 22, 'font-weight': 900, 'color': d ? '#dbe9ff' : '#29425f',
  916. 'text-margin-y': 8, 'padding': '0px', 'events': 'no',
  917. 'z-index-compare': 'manual', 'z-index': 1
  918. }},
  919. {selector: 'node[type="wsframe"]', style: {
  920. 'background-opacity': d ? 0.02 : 0.014, 'background-color': d ? '#6f8fc4' : '#8fa6c4',
  921. 'border-width': 2.2, 'border-style': 'solid', 'border-color': 'data(bd)',
  922. 'label': 'data(label)', 'text-valign': 'top', 'text-halign': 'center', 'text-wrap': 'none',
  923. 'font-size': 15.5, 'font-weight': 900, 'color': d ? '#d7e6ff' : '#2f4560',
  924. 'text-margin-x': 0, 'text-margin-y': 7, 'padding': '0px', 'events': 'no',
  925. 'z-index-compare': 'manual', 'z-index': 2
  926. }},
  927. {selector: 'node[type="floorframe"]', style: {
  928. 'background-opacity': d ? 0.04 : 0.025, 'background-color': d ? '#5b7bb0' : '#8fa6c4',
  929. 'border-width': 1.1, 'border-style': 'dashed', 'border-color': 'data(bd)',
  930. 'label': 'data(label)', 'text-valign': 'top', 'text-halign': 'center', 'text-wrap': 'none',
  931. 'font-size': 11.5, 'font-weight': 800, 'color': d ? '#a9c1e3' : '#425a78',
  932. 'text-margin-x': 0, 'text-margin-y': 6, 'padding': '0px', 'events': 'no',
  933. 'z-index-compare': 'manual', 'z-index': 3
  934. }},
  935. {selector: 'node[type="root"]', style: {
  936. 'background-opacity': d ? 0.02 : 0.012, 'background-color': d ? '#7aa0d8' : '#8ea6c2',
  937. 'border-width': 2.2, 'border-style': 'solid', 'border-color': d ? '#476492' : '#9fb0c6',
  938. 'label': 'data(label)', 'text-valign': 'top', 'text-halign': 'center',
  939. 'font-size': 28, 'font-weight': 900, 'color': d ? '#cfe0ff' : '#33465f',
  940. 'text-margin-y': 10, 'events': 'no', 'z-index-compare': 'manual', 'z-index': 0
  941. }},
  942. {selector: 'node[type="roottitle"]', style: {
  943. 'width': 'data(w)', 'height': 20, 'shape': 'rectangle', 'background-opacity': 0, 'border-width': 0,
  944. 'label': 'data(label)', 'text-valign': 'center', 'text-halign': 'center', 'text-wrap': 'none',
  945. 'font-size': 24, 'font-weight': 900, 'color': d ? '#cfe0ff' : '#33465f', 'events': 'no',
  946. 'z-index-compare': 'manual', 'z-index': 5
  947. }},
  948. {selector: 'node[type="nettitle"]', style: {
  949. 'width': 'data(w)', 'height': 20, 'shape': 'rectangle', 'background-opacity': 0, 'border-width': 0,
  950. 'label': 'data(label)', 'text-valign': 'center', 'text-halign': 'center', 'text-wrap': 'none',
  951. 'font-size': 20, 'font-weight': 900, 'color': d ? '#dbe9ff' : '#29425f', 'events': 'no',
  952. 'z-index-compare': 'manual', 'z-index': 5
  953. }},
  954. {selector: 'node[type="wslabel"]', style: {
  955. 'width': 'data(w)', 'height': 16, 'shape': 'rectangle', 'background-opacity': 0, 'border-width': 0,
  956. 'label': 'data(label)', 'text-valign': 'center', 'text-halign': 'center', 'text-wrap': 'none',
  957. 'font-size': 15, 'font-weight': 900, 'color': d ? '#d7e6ff' : '#2f4560', 'events': 'no',
  958. 'z-index-compare': 'manual', 'z-index': 5
  959. }},
  960. {selector: 'node[type="floorlabel"]', style: {
  961. 'width': 'data(w)', 'height': 16, 'shape': 'rectangle', 'background-opacity': 0, 'border-width': 0,
  962. 'label': 'data(label)', 'text-valign': 'center', 'text-halign': 'center', 'text-wrap': 'none',
  963. 'font-size': 11, 'font-weight': 800, 'color': d ? '#a9c1e3' : '#425a78', 'events': 'no',
  964. 'z-index-compare': 'manual', 'z-index': 5
  965. }},
  966. {selector: 'node[type="tile"]', style: {
  967. 'width': 'data(w)', 'height': 'data(h)', 'shape': 'round-rectangle',
  968. 'background-color': 'data(bg)', 'background-opacity': 0.97,
  969. 'border-width': 2.5, 'border-color': 'data(bd)',
  970. 'label': 'data(label)', 'color': 'data(fg)',
  971. 'font-size': 16, 'font-weight': 700, 'text-valign': 'center', 'text-halign': 'center',
  972. 'text-wrap': 'wrap', 'text-max-width': TILE_W - 26, 'line-height': 1.45,
  973. 'padding': '6px', 'overlay-opacity': 0, 'z-index-compare': 'manual', 'z-index': 20
  974. }},
  975. {selector: 'node[type="tile"].alarm', style: {'border-width': 5}},
  976. {selector: 'node[type="tile"].core', style: {'border-width': 3.5}},
  977. {selector: 'node[type="ghost"]', style: {
  978. 'width': 190, 'height': 40, 'shape': 'round-rectangle',
  979. 'background-color': d ? '#52667f' : '#c8d3e2', 'background-opacity': 0.55,
  980. 'border-width': 1.2, 'border-style': 'dashed', 'border-color': d ? '#7d93ad' : '#8fa3bc',
  981. 'label': 'data(label)', 'color': d ? '#dce8fa' : '#3b4f68',
  982. 'font-size': 11, 'font-weight': 600, 'text-wrap': 'wrap', 'text-max-width': 176,
  983. 'z-index-compare': 'manual', 'z-index': 15
  984. }},
  985. {selector: 'node[type="edgepoint"]', style: {
  986. 'width': 1, 'height': 1, 'opacity': 0, 'events': 'no'
  987. }},
  988. {selector: 'node[type="term"]', style: {
  989. 'width': 7, 'height': 7, 'shape': 'ellipse', 'background-color': 'data(bg)',
  990. 'border-width': 1, 'border-color': d ? '#2a3648' : '#cfd8e3',
  991. 'label': 'data(label)', 'font-size': 9, 'font-weight': 700,
  992. 'color': d ? '#eaf1fb' : '#182c44',
  993. 'text-valign': 'bottom', 'text-halign': 'center', 'text-margin-y': 4,
  994. 'text-wrap': 'wrap', 'text-max-width': 160,
  995. 'text-background-color': d ? '#0d1b2a' : '#ffffff', 'text-background-opacity': 0.9,
  996. 'text-background-padding': '2px',
  997. 'z-index-compare': 'manual', 'z-index': 30
  998. }},
  999. {selector: 'edge[type="tilelink"]', style: {
  1000. 'width': 'data(w)', 'line-color': 'data(color)', 'opacity': 0.55,
  1001. 'curve-style': 'bezier', 'target-arrow-shape': 'none',
  1002. 'z-index-compare': 'manual', 'z-index': 5
  1003. }},
  1004. {selector: 'edge[type="ghost"]', style: {
  1005. 'width': 1.2, 'line-color': d ? '#6b809b' : '#a9b6c8', 'line-style': 'dashed', 'opacity': 0.7,
  1006. 'curve-style': 'bezier', 'target-arrow-shape': 'none',
  1007. 'z-index-compare': 'manual', 'z-index': 8
  1008. }},
  1009. {selector: 'edge[type="uplink"]', style: {
  1010. 'width': 'data(w)', 'line-color': 'data(color)', 'line-style': 'data(ls)', 'opacity': 0.95,
  1011. 'curve-style': 'bezier', 'target-arrow-shape': 'none',
  1012. 'label': 'data(lbl)', 'font-size': 10, 'font-weight': 700,
  1013. 'color': d ? '#dce8fa' : '#25405f',
  1014. 'text-background-color': d ? '#0d1b2a' : '#ffffff', 'text-background-opacity': 0.88,
  1015. 'text-background-padding': '2px', 'text-rotation': 'autorotate',
  1016. 'z-index-compare': 'manual', 'z-index': 40
  1017. }},
  1018. {selector: 'edge', style: {
  1019. 'width': 'data(w)', 'line-color': 'data(color)', 'line-style': 'data(ls)',
  1020. 'curve-style': 'bezier', 'opacity': 0.92, 'target-arrow-shape': 'none',
  1021. 'z-index-compare': 'manual', 'z-index': 12
  1022. }},
  1023. {selector: 'edge[type="link"]', style: {
  1024. 'width': 'data(w)', 'line-color': 'data(color)', 'line-style': 'data(ls)',
  1025. 'opacity': 0.62, 'curve-style': 'straight',
  1026. 'source-endpoint': '0% 50%', 'target-endpoint': '0% 50%',
  1027. 'target-arrow-shape': 'none', 'z-index-compare': 'manual', 'z-index': 1
  1028. }},
  1029. {selector: 'edge[type="term"]', style: {
  1030. 'width': 0.7, 'line-color': d ? '#3b4a5e' : '#c5cfdb', 'opacity': 0.55,
  1031. 'curve-style': 'bezier', 'z-index-compare': 'manual', 'z-index': 11
  1032. }},
  1033. // Latency is a secondary label signal; alarm and offline must win over
  1034. // latency so an alarmed/offline switch is never shown as merely orange.
  1035. {selector: 'node.lat-warn', style: {'border-color': '#F39C12', 'border-width': 4, 'border-style': 'solid'}},
  1036. {selector: 'node.lat-bad', style: {'border-color': '#E74C3C', 'border-width': 6}},
  1037. {selector: 'node.alarm', style: {'border-color': '#E45959', 'border-width': 6}},
  1038. {selector: 'node.offline', style: {'border-color': '#C0392B', 'border-width': 6, 'border-style': 'dashed', 'opacity': 0.9}},
  1039. {selector: 'node.dim', style: {'opacity': 0.12}},
  1040. {selector: 'edge.dim', style: {'opacity': 0.08}},
  1041. {selector: 'edge.hl', style: {'width': 5, 'line-color': '#FFD54A', 'opacity': 1, 'z-index-compare': 'manual', 'z-index': 45}},
  1042. {selector: 'node.hl', style: {'border-color': '#ff0', 'border-width': 7, 'overlay-color': '#ff0', 'overlay-opacity': 0.25, 'overlay-padding': 6}},
  1043. {selector: 'node.pathhl', style: {'border-width': 5, 'border-color': '#FFD54A', 'overlay-color': '#FFD54A', 'overlay-opacity': 0.2, 'overlay-padding': 4}},
  1044. {selector: 'edge.pathhl', style: {'width': 5.5, 'line-color': '#FFD54A', 'opacity': 1}},
  1045. {selector: 'edge.detail', style: {'opacity': 0.72, 'curve-style': 'straight', 'source-endpoint': '0% 50%', 'target-endpoint': '0% 50%'}},
  1046. {selector: 'node[type="switch"]', style: {
  1047. 'background-color': function (e) { return e.data('bg'); },
  1048. 'text-max-width': 'data(tw)', 'text-wrap': 'none',
  1049. 'text-halign': 'center', 'font-size': 10.5
  1050. }},
  1051. {selector: 'node[type="switch"].root', style: {'text-wrap': 'wrap'}}
  1052. ];
  1053. }
  1054. /* ---------------- render ---------------- */
  1055. // One tall column chart cannot be squeezed into a wide window without
  1056. // wasting half the canvas. The initial view fits the chart WIDTH and
  1057. // anchors at the top (core switches first); the user can pan down or press
  1058. // "适应窗口" to see the entire graph. This keeps labels readable.
  1059. function initialView() {
  1060. if (!cy) return;
  1061. var bb = cy.elements().boundingBox();
  1062. if (!bb || !bb.w || !bb.h) return;
  1063. var zw = (cy.width() - 30) / bb.w;
  1064. var zh = (cy.height() - 30) / bb.h;
  1065. var tall = (bb.h * zw > cy.height() * 1.5);
  1066. var z = tall ? zw * 0.95 : Math.min(zw, zh);
  1067. cy.zoom({level: z});
  1068. if (tall) {
  1069. cy.pan({x: 15 - bb.x * z, y: 28 - bb.y * z});
  1070. } else {
  1071. cy.pan({x: (cy.width() - bb.w * z) / 2 - bb.x * z, y: (cy.height() - bb.h * z) / 2 - bb.y * z});
  1072. }
  1073. }
  1074. function applyElements(els, keepView) {
  1075. if (!cy) {
  1076. cy = cytoscape({
  1077. container: el('l2-cy'),
  1078. elements: els,
  1079. style: styleFor(dark),
  1080. layout: {name: 'preset', fit: false},
  1081. wheelSensitivity: 0.2,
  1082. minZoom: 0.02, maxZoom: 4
  1083. });
  1084. bindCy();
  1085. setTimeout(initialView, 0);
  1086. } else {
  1087. var z = cy.zoom(), p = cy.pan();
  1088. cy.elements().remove();
  1089. cy.add(els);
  1090. cy.style(styleFor(dark));
  1091. cy.layout({name: 'preset', fit: false}).run();
  1092. if (keepView) { cy.zoom(z); cy.pan(p); }
  1093. else { initialView(); }
  1094. }
  1095. }
  1096. function fitGroup(label) {
  1097. if (!cy || !label) return;
  1098. var eles = cy.nodes().filter(function (n) {
  1099. return n.data('blockGroup') === label || n.data('group') === label;
  1100. });
  1101. if (eles.length) cy.fit(eles, 70);
  1102. }
  1103. function render(snap) {
  1104. if (!snap || !snap.nodes) {
  1105. el('l2-cy').innerHTML = '<div class="l2-empty">' + t('l2.no_data', 'No data') + '</div>';
  1106. return;
  1107. }
  1108. lastSnap = snap;
  1109. renderFull(snap);
  1110. updateStats(snap);
  1111. buildLegend();
  1112. buildAlarms(snap);
  1113. buildOffline(snap);
  1114. buildTerminals(snap);
  1115. buildHistory();
  1116. }
  1117. function renderFull(snap) {
  1118. var L = computeFull(snap), els = [];
  1119. if (!L.placements.length) { applyElements([], false); return; }
  1120. lastRoleMap = L.roleMap || {};
  1121. var byId = {};
  1122. L.placements.forEach(function (p) { byId[p.node.id] = p; });
  1123. els.push({group: 'nodes', data: {id: '__root', type: 'root', label: '', w: L.root.w, h: L.root.h},
  1124. position: {x: L.root.w / 2, y: L.root.h / 2}, selectable: false, grabbable: false});
  1125. els.push({group: 'nodes', data: {id: '__roottitle', type: 'roottitle', label: CFG.root_label || 'COBCO', w: L.root.w, h: 20},
  1126. position: {x: L.root.w / 2, y: 22}, selectable: false, grabbable: false});
  1127. L.sections.forEach(function (sec, si) {
  1128. els.push({group: 'nodes', data: {
  1129. id: '__net_' + si, type: 'netframe', label: '', w: sec.w, h: sec.h, net: sec.key, bd: sec.color
  1130. }, position: {x: sec.x + sec.w / 2, y: sec.y + sec.h / 2}, selectable: false, grabbable: false});
  1131. els.push({group: 'nodes', data: {id: '__nettitle_' + si, type: 'nettitle', label: sec.label, w: sec.w, h: 20},
  1132. position: {x: sec.x + sec.w / 2, y: sec.y + 21}, selectable: false, grabbable: false});
  1133. });
  1134. L.frames.forEach(function (f) {
  1135. els.push({group: 'nodes', data: {
  1136. id: f.id, type: f.type, label: '', w: f.w, h: f.h, group: f.group || '', net: f.net, bd: f.color || netColor(f.net)
  1137. }, position: {x: f.x + f.w / 2, y: f.y + f.h / 2}, selectable: false, grabbable: false});
  1138. var tt = f.type === 'floorframe' ? 'floorlabel' : 'wslabel';
  1139. var ty = f.type === 'floorframe' ? 11 : 18;
  1140. els.push({group: 'nodes', data: {id: 'label_' + f.id, type: tt, label: f.label, w: f.w, h: 16},
  1141. position: {x: (f.labelX != null ? f.labelX : f.x + f.w / 2), y: f.y + ty}, selectable: false, grabbable: false});
  1142. });
  1143. L.placements.forEach(function (p) {
  1144. var n = p.node, cls = [];
  1145. var bg = p.role === 'core' ? TIER_BG.core : (p.role === 'main' ? '#2E75B6' : (p.role === 'dist' ? TIER_BG.dist : TIER_BG.access));
  1146. var bd = bg;
  1147. if (n.alarms && n.alarms.length) { cls.push('alarm'); bd = '#E45959'; }
  1148. if (n.offline || n.oper === 'down') cls.push('offline');
  1149. if (n.latency_ms != null) {
  1150. if (+n.latency_ms > LATB) cls.push('lat-bad');
  1151. else if (+n.latency_ms > LATW) cls.push('lat-warn');
  1152. }
  1153. if (p.role === 'core') cls.push('root');
  1154. els.push({group: 'nodes', data: {
  1155. id: n.id, type: 'switch', name: n.name, ip: n.ip, tier: n.tier, depth: n.depth, hostid: n.hostid, oper: n.oper,
  1156. offline: !!(n.offline || n.oper === 'down'), last_online: n.last_online,
  1157. maxsev: n.maxsev, alarms: n.alarms || [], term_online: n.term_online, term_offline: 0, latency_ms: n.latency_ms,
  1158. label: switchLabel(n, p.role, p.net), tw: p.w - 12, bg: bg, bd: bd, w: p.w, h: p.h,
  1159. group: p.group + ' · ' + netLabel(p.net), blockGroup: p.group, net: p.net, role: p.role
  1160. }, position: {x: p.x, y: p.y}, classes: cls.join(' ')});
  1161. });
  1162. // Every protocol-discovered link = one straight segment. Cytoscape's
  1163. // percentage endpoints are unreliable with preset labels, so use two
  1164. // invisible anchor nodes placed exactly on the label left-edge midpoint.
  1165. // The labels paint on top, so a parent line starts under the parent label
  1166. // and ends exactly at the child's left edge.
  1167. pathParent = buildParents(snap, L);
  1168. (snap.edges || []).forEach(function (e, i) {
  1169. var ps = byId[e.source], pt = byId[e.target];
  1170. if (!ps || !pt) return;
  1171. var sp = 'sp_' + i, tp = 'tp_' + i;
  1172. els.push({group: 'nodes', data: {id: sp, type: 'edgepoint'}, position: {x: ps.x - ps.w / 2, y: ps.y}, selectable: false, grabbable: false});
  1173. els.push({group: 'nodes', data: {id: tp, type: 'edgepoint'}, position: {x: pt.x - pt.w / 2, y: pt.y}, selectable: false, grabbable: false});
  1174. var col = speedColor(e.speed, e.state);
  1175. els.push({group: 'edges', data: {
  1176. id: 'e_' + i, type: 'link', source: sp, target: tp, p: e.source, c: e.target,
  1177. speed: e.speed, state: e.state, a_port: e.a_port, b_port: e.b_port,
  1178. color: col, ls: (e.state && e.state !== 'up') ? 'dashed' : 'solid', w: Math.min(4, speedWidth(e.speed))
  1179. }});
  1180. });
  1181. if (showTerm) addTerminals(L, byId, els);
  1182. applyElements(els, true);
  1183. if (focusGroupLabel) {
  1184. setTimeout(function () { fitGroup(focusGroupLabel); }, 80);
  1185. focusGroupLabel = null;
  1186. }
  1187. }
  1188. function addTerminals(L, byId, els) {
  1189. var bySw = {};
  1190. ((lastSnap && lastSnap.terminals) || []).forEach(function (tm) {
  1191. if (!byId[tm.sw_ip]) return;
  1192. if (!terminalOnline(tm)) return;
  1193. (bySw[tm.sw_ip] = bySw[tm.sw_ip] || []).push(tm);
  1194. });
  1195. Object.keys(bySw).forEach(function (sw) {
  1196. var p = byId[sw]; if (!p || p.role === 'core' || p.role === 'main') return;
  1197. bySw[sw].sort(function (a, b) { return (terminalOnline(a) === terminalOnline(b)) ? 0 : (terminalOnline(a) ? -1 : 1); });
  1198. // A search hit is pinned into the visible 24 so any MAC in the snapshot
  1199. // can be located even when its switch has more than 24 terminals.
  1200. if (pinnedTerm) {
  1201. for (var pi = 0; pi < bySw[sw].length; pi++) {
  1202. if (bySw[sw][pi].mac === pinnedTerm) {
  1203. if (pi > 0) { var pin = bySw[sw].splice(pi, 1)[0]; bySw[sw].unshift(pin); }
  1204. break;
  1205. }
  1206. }
  1207. }
  1208. bySw[sw].slice(0, 24).forEach(function (tm, k) {
  1209. var col = k % 12, row = Math.floor(k / 12);
  1210. var x = p.x - p.w / 2 + 16 + col * 9;
  1211. var y = p.y + 16 + row * 9;
  1212. els.push({group: 'nodes', data: {
  1213. id: 't_' + tm.mac, type: 'term', bg: terminalOnline(tm) ? '#2ECC71' : '#95a5a6',
  1214. mac: tm.mac, ip: tm.ip, online: terminalOnline(tm), speed: tm.speed,
  1215. sw_name: tm.sw_name, port: tm.port, label: '', termText: terminalText(tm)
  1216. }, position: {x: x, y: y}, selectable: false});
  1217. els.push({group: 'edges', data: {id: 'te_' + tm.mac, type: 'term', source: sw, target: 't_' + tm.mac}});
  1218. });
  1219. });
  1220. }
  1221. function renderOverview(snap) {
  1222. var O = computeOverview(snap), els = [], idx = {};
  1223. var nb = el('l2-net-tabs'); if (nb) { nb.style.display = 'none'; nb.innerHTML = ''; }
  1224. if (O.root) {
  1225. els.push({group: 'nodes', data: {id: '__root', type: 'root', label: CFG.root_label || 'COBCO', w: O.root.w, h: O.root.h},
  1226. position: {x: O.root.cx, y: O.root.cy}, selectable: false, grabbable: false});
  1227. }
  1228. O.tiles.forEach(function (tile, i) {
  1229. var s = O.stats[tile.label] || {nodes: [], alarms: 0, offline: 0, maxsev: -1};
  1230. idx[tile.label] = 'grp_' + i;
  1231. var isCore = /core/i.test(tile.label) || /data\s*center/i.test(tile.label);
  1232. var bd = s.alarms ? '#E45959' : (dark ? '#41597c' : '#b9c8dc');
  1233. var bg = isCore ? TIER_BG.core : (dark ? '#22344e' : '#eef3fb');
  1234. var fg = isCore ? '#ffffff' : (dark ? '#dfe9fb' : '#1e3352');
  1235. var lbl = tile.label + '\n' + s.nodes.length + ' ' + t('l2.unit_sw', 'sw') +
  1236. (s.up ? ' ↑ ' + s.up : '') + (s.alarms ? ' ⚠ ' + s.alarms : '') + (s.offline ? ' ◌ ' + s.offline : '');
  1237. var cls = [];
  1238. if (s.alarms) cls.push('alarm');
  1239. if (isCore) cls.push('core');
  1240. els.push({group: 'nodes', data: {
  1241. id: idx[tile.label], type: 'tile', group: tile.label,
  1242. n: s.nodes.length, alarms: s.alarms, offline: s.offline, maxsev: s.maxsev, up: s.up,
  1243. label: lbl, bg: bg, fg: fg, bd: bd, w: TILE_W, h: TILE_H
  1244. }, position: {x: tile.x + tile.w / 2, y: tile.y + tile.h / 2}, classes: cls.join(' ')});
  1245. });
  1246. applyElements(els);
  1247. }
  1248. function renderNetTabs(D) {
  1249. var box = el('l2-net-tabs');
  1250. if (!box) return;
  1251. box.innerHTML = '';
  1252. if (!D.nets || D.nets.length < 2) { box.style.display = 'none'; return; }
  1253. box.style.display = 'flex';
  1254. D.nets.forEach(function (n) {
  1255. var b = document.createElement('button');
  1256. b.type = 'button';
  1257. b.className = 'l2-net-tab' + (n.key === D.activeNet ? ' active' : '');
  1258. b.textContent = networkLabel(n.key) + ' · ' + n.count + ' ' + t('l2.unit_sw', 'sw');
  1259. b.addEventListener('click', function () { detailNet = n.key; render(lastSnap); });
  1260. box.appendChild(b);
  1261. });
  1262. }
  1263. function renderDetail(snap) {
  1264. var D = computeDetail(snap, viewGroup), els = [];
  1265. renderNetTabs(D);
  1266. function frameEl(id, type, fr) {
  1267. els.push({group: 'nodes', data: {id: id, type: type, label: fr.label, w: fr.w, h: fr.h},
  1268. position: {x: fr.x + fr.w / 2, y: fr.y + fr.h / 2}, selectable: false, grabbable: false});
  1269. }
  1270. frameEl('__ws', 'wsframe', {x: D.frames.workshop.x, y: 36, w: D.frames.workshop.w, h: D.frames.workshop.h + 36, label: D.frames.workshop.label});
  1271. if (D.frames.dist) frameEl('__dist', 'floorframe', D.frames.dist);
  1272. D.floors.forEach(function (f, i) { frameEl('__floor_' + i, 'floorframe', f.frame); });
  1273. (D.ghosts || []).forEach(function (g) {
  1274. var nm = (g.node && g.node.name) || g.id;
  1275. var ip = (g.node && g.node.ip) || '';
  1276. var tail = String(nm).split(/[-\s]+/).filter(Boolean).slice(-1)[0] || '';
  1277. var short = (tail ? tail + ' · ' : '') + ip;
  1278. els.push({group: 'nodes', data: {id: g.id, type: 'ghost', label: short}, position: {x: g.x, y: g.y}, selectable: false, grabbable: false});
  1279. els.push({group: 'edges', data: {
  1280. id: 'ghe_' + g.id, type: 'uplink', source: g.id, target: g.to,
  1281. speed: g.speed, state: g.state, lbl: speedText(g.speed),
  1282. color: speedColor(g.speed, g.state), ls: (g.state && g.state !== 'up') ? 'dashed' : 'solid',
  1283. w: Math.max(2.6, speedWidth(g.speed))
  1284. }});
  1285. });
  1286. var switchIds = {};
  1287. D.nodes.forEach(function (n, ni) {
  1288. switchIds[n.id] = true;
  1289. var p = D.pos[n.id] || {x: 0, y: 0};
  1290. var tier = n.tier || 'access';
  1291. var tkey = (tier.indexOf('dist') === 0) ? 'dist' : (tier.indexOf('core') === 0 ? 'core' : 'access');
  1292. var isRoot = D.dists && D.dists.length && n.id === D.dists[0].id;
  1293. var cls = [];
  1294. var bd = (dark ? TIER_BG_DARK[tkey] : TIER_BG[tkey]) || '#555';
  1295. var bg = (dark ? TIER_BG_DARK[tkey] : TIER_BG[tkey]) || '#777';
  1296. if (!isRoot && ni % 2 === 1) bg = dark ? '#4f8a3a' : '#6ca75a';
  1297. if (n.alarms && n.alarms.length) {
  1298. cls.push('alarm');
  1299. bd = '#E45959';
  1300. }
  1301. if (n.latency_ms != null) {
  1302. if (+n.latency_ms > LATB) cls.push('lat-bad');
  1303. else if (+n.latency_ms > LATW) cls.push('lat-warn');
  1304. }
  1305. if (isRoot) cls.push('root');
  1306. els.push({group: 'nodes', data: {
  1307. id: n.id, type: 'switch', name: n.name, ip: n.ip, tier: tier, depth: n.depth,
  1308. hostid: n.hostid, oper: n.oper, maxsev: n.maxsev, alarms: n.alarms || [],
  1309. term_online: n.term_online, term_offline: n.term_offline, latency_ms: n.latency_ms,
  1310. label: isRoot ? rootLabel(n) : rowLabel(n), tw: isRoot ? 150 : 360,
  1311. bg: bg, bd: isRoot ? bd : '#25501e',
  1312. w: isRoot ? 170 : 380, h: isRoot ? 50 : 24, group: viewGroup
  1313. }, position: p, classes: cls.join(' ')});
  1314. });
  1315. D.internal.forEach(function (e, i) {
  1316. var root = D.dists && D.dists[0];
  1317. if (root && (e.source === root.id || e.target === root.id)) {
  1318. var childId = e.source === root.id ? e.target : e.source;
  1319. var pp = D.pos[root.id], cp = D.pos[childId];
  1320. if (pp && cp) {
  1321. var sp = 'sp_' + i, tp = 'tp_' + i;
  1322. // Exact left-edge midpoints, straight line. The parent label is
  1323. // allowed to cover the line where it exits the parent.
  1324. els.push({group: 'nodes', data: {id: sp, type: 'edgepoint'}, position: {x: pp.x - 86, y: pp.y}, selectable: false, grabbable: false});
  1325. els.push({group: 'nodes', data: {id: tp, type: 'edgepoint'}, position: {x: cp.x - 191, y: cp.y}, selectable: false, grabbable: false});
  1326. els.push({group: 'edges', data: {
  1327. id: 'e_' + i, type: 'detail', source: sp, target: tp, p: root.id, c: childId,
  1328. speed: e.speed, state: e.state, a_port: e.a_port, b_port: e.b_port,
  1329. color: speedColor(e.speed, e.state), ls: (e.state && e.state !== 'up') ? 'dashed' : 'solid',
  1330. w: Math.min(2.4, speedWidth(e.speed))
  1331. }, classes: 'detail'});
  1332. return;
  1333. }
  1334. }
  1335. els.push({group: 'edges', data: {
  1336. id: 'e_' + i, source: e.source, target: e.target, speed: e.speed, state: e.state,
  1337. a_port: e.a_port, b_port: e.b_port,
  1338. color: speedColor(e.speed, e.state), ls: (e.state && e.state !== 'up') ? 'dashed' : 'solid',
  1339. w: Math.min(2.4, speedWidth(e.speed))
  1340. }, classes: 'detail'});
  1341. });
  1342. if (showTerm) {
  1343. var bySw = {};
  1344. (snap.terminals || []).forEach(function (tm) {
  1345. if (!switchIds[tm.sw_ip]) return;
  1346. if (!terminalOnline(tm)) return;
  1347. (bySw[tm.sw_ip] = bySw[tm.sw_ip] || []).push(tm);
  1348. });
  1349. Object.keys(bySw).forEach(function (sw) {
  1350. var base = D.pos[sw]; if (!base) return;
  1351. bySw[sw].sort(function (a, b) { return (a.online === b.online) ? 0 : (a.online ? -1 : 1); });
  1352. bySw[sw].forEach(function (tm, k) {
  1353. var col = k % 9, row = Math.floor(k / 9);
  1354. var x = base.x - 54 + col * 13;
  1355. var y = base.y + NODE_H / 2 + 16 + row * 13;
  1356. els.push({group: 'nodes', data: {id: 't_' + tm.mac, type: 'term', bg: '#2ECC71', mac: tm.mac, ip: tm.ip, online: true},
  1357. position: {x: x, y: y}, selectable: false});
  1358. els.push({group: 'edges', data: {id: 'te_' + tm.mac, type: 'term', source: sw, target: 't_' + tm.mac}});
  1359. });
  1360. });
  1361. }
  1362. pathParent = D.parentOf || {};
  1363. lockedPath = null;
  1364. applyElements(els);
  1365. }
  1366. /* ---------------- side panels & stats ---------------- */
  1367. function updateStats(snap) {
  1368. var s = snap.stats || {};
  1369. var txt = '● ' + (s.switches || 0) + ' | ⇄ ' + (s.edges || 0) + ' | ' +
  1370. (s.term_total || 0) + ' ' + t('l2.terminals', 'terminals') + ' | ' +
  1371. (s.switches_offline || 0) + ' ' + t('l2.offline_short', 'offline SW') + ' | ⚠ ' + (s.alarms || 0);
  1372. var up = snap.generated_iso ? (' · ' + t('l2.updated', 'Updated') + ' ' + snap.generated_iso) : '';
  1373. el('l2-stats').textContent = txt + up;
  1374. }
  1375. function buildLegend() {
  1376. var h = '';
  1377. function sw(c, label, dashed) { return '<div class="lg-row"><span class="lg-line' + (dashed ? ' lg-dash' : '') + '" style="border-top-color:' + c + '"></span>' + label + '</div>'; }
  1378. h += '<div class="lg-title">' + t('l2.legend_speed', 'Link speed') + '</div>';
  1379. h += sw(colors['100'], '100M') + sw(colors['1000'], '1G') + sw(colors['10000'], '10G') + sw(colors['20000'], '20G+');
  1380. h += sw(colors.unknown, t('lbl.color_unknown', 'Unknown'));
  1381. h += sw(colors.down, t('lbl.color_down', 'Down'), true);
  1382. h += '<div class="lg-title">' + t('l2.legend_tier', 'Tier') + '</div>';
  1383. h += '<div class="lg-row"><span class="lg-box" style="background:' + TIER_BG.core + '"></span>' + t('l2.core', 'Core') +
  1384. '<span class="lg-box" style="background:#2E75B6;margin-left:8px"></span>' + t('l2.main', 'Main switch') +
  1385. '<span class="lg-box" style="background:' + TIER_BG.dist + ';margin-left:8px"></span>' + t('l2.dist', 'Distribution') +
  1386. '<span class="lg-box" style="background:' + TIER_BG.access + ';margin-left:8px"></span>' + t('l2.access', 'Access') + '</div>';
  1387. h += '<div class="lg-title">' + t('l2.legend_lat', 'Latency') + '</div>';
  1388. h += '<div class="lg-row"><span class="lg-box" style="background:#F39C12;border-radius:2px"></span>&gt;' + LATW + 'ms' +
  1389. '<span class="lg-box" style="background:#E74C3C;border-radius:2px;margin-left:8px"></span>&gt;' + LATB + 'ms</div>';
  1390. h += '<div class="lg-row"><span class="lg-box" style="background:#E45959;border-radius:2px"></span>' + t('l2.alarms', 'Alarms') + '</div>';
  1391. h += '<div class="lg-row"><span class="lg-box" style="background:#2ECC71;border-radius:50%"></span>' + t('l2.term_on', 'Online') +
  1392. '<span class="lg-box" style="background:#C0392B;border-radius:2px;margin-left:8px"></span>' + t('l2.offline', 'Offline switch') + '</div>';
  1393. h += '<div class="lg-row" style="opacity:.72;margin-top:4px">' + t('l2.click_hint', 'Hover a switch to highlight its full upstream path') + '</div>';
  1394. el('l2-legend').innerHTML = h;
  1395. }
  1396. function buildAlarms(snap) {
  1397. var items = [];
  1398. (snap.nodes || []).forEach(function (n) {
  1399. if (n.maxsev != null && n.maxsev >= 0 && n.alarms && n.alarms.length) {
  1400. n.alarms.forEach(function (a) {
  1401. items.push({sev: n.maxsev, title: (a.name || a.description || ''), host: n.name, ip: n.ip, id: n.id, hostid: n.hostid});
  1402. });
  1403. }
  1404. });
  1405. el('l2-alarm-count').textContent = items.length;
  1406. if (!items.length) { el('l2-alarm-list').innerHTML = '<div class="panel-empty">' + t('l2.alarm_empty', 'No active alarms.') + '</div>'; return; }
  1407. items.sort(function (a, b) { return b.sev - a.sev; });
  1408. var h = '';
  1409. items.forEach(function (it) {
  1410. var col = SEV_COLORS[Math.max(0, Math.min(5, it.sev))] || '#999';
  1411. h += '<div class="alarm-row" data-id="' + (it.id || '') + '" data-hostid="' + (it.hostid || '') + '">' +
  1412. '<span class="alarm-dot" style="background:' + col + '"></span>' +
  1413. '<div class="alarm-main"><div class="alarm-title">' + esc(it.title) + '</div>' +
  1414. '<div class="alarm-sub">' + esc(it.host || '') + (it.ip ? ' · ' + esc(it.ip) : '') + '</div></div></div>';
  1415. });
  1416. var box = el('l2-alarm-list');
  1417. box.innerHTML = h;
  1418. box.querySelectorAll('.alarm-row').forEach(function (r) {
  1419. r.addEventListener('click', function () {
  1420. var id = r.getAttribute('data-id');
  1421. if (id) revealById(id);
  1422. else { var hid = r.getAttribute('data-hostid'); if (hid) window.open(META.zabbixHostUrl.replace('__HOSTID__', hid), '_blank'); }
  1423. });
  1424. });
  1425. }
  1426. function fmtTs(ts) {
  1427. if (!ts) return '—';
  1428. try {
  1429. var d = new Date(Number(ts) * 1000);
  1430. var p = function (x) { return (x < 10 ? '0' : '') + x; };
  1431. return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) + ' ' + p(d.getHours()) + ':' + p(d.getMinutes());
  1432. } catch (e) { return '—'; }
  1433. }
  1434. function buildOffline(snap) {
  1435. var off = (snap.nodes || []).filter(function (n) { return n.offline || n.oper === 'down'; });
  1436. el('l2-offline-count').textContent = off.length;
  1437. if (!off.length) { el('l2-offline-list').innerHTML = '<div class="panel-empty">' + t('l2.offline_empty', 'No offline switches.') + '</div>'; return; }
  1438. off.sort(function (a, b) {
  1439. var ra = roleOf(a), rb = roleOf(b);
  1440. if (ra !== rb) return ra === 'dist' ? -1 : 1;
  1441. return String(a.name || '').localeCompare(String(b.name || ''));
  1442. });
  1443. var h = '';
  1444. off.forEach(function (n) {
  1445. var role = roleOf(n);
  1446. var roleTxt = role === 'dist' ? t('l2.dist', 'Distribution') : t('l2.access', 'Access');
  1447. h += '<div class="off-row sw-row" data-id="' + esc(n.id) + '">' +
  1448. '<span class="term-dot" style="background:#C0392B"></span>' +
  1449. '<div class="off-main"><div class="off-mac">' + esc(n.name || n.ip) + '</div>' +
  1450. '<div class="off-sub">' + esc(roleTxt) + ' · ' + esc(n.ip || '') +
  1451. ' · ' + t('l2.last_online', 'last online') + ': ' + esc(fmtTs(n.last_online)) + '</div></div></div>';
  1452. });
  1453. var box = el('l2-offline-list');
  1454. box.innerHTML = h;
  1455. box.querySelectorAll('.off-row').forEach(function (r) {
  1456. r.addEventListener('click', function () {
  1457. var id = r.getAttribute('data-id');
  1458. if (id) revealById(id);
  1459. });
  1460. });
  1461. }
  1462. function buildTerminals(snap) {
  1463. var list = (snap.terminals || []).filter(function (tm) { return terminalOnline(tm); });
  1464. if (el('l2-term-count')) el('l2-term-count').textContent = list.length;
  1465. var box = el('l2-term-list');
  1466. if (!box) return;
  1467. if (!showTerm) {
  1468. box.innerHTML = '<div class="panel-empty">' + t('l2.show_term', 'Show terminals') + '</div>';
  1469. return;
  1470. }
  1471. if (!list.length) {
  1472. box.innerHTML = '<div class="panel-empty">' + t('l2.no_data', 'No data') + '</div>';
  1473. return;
  1474. }
  1475. list.sort(function (a, b) {
  1476. var x = String(a.sw_name || a.sw_ip || '').localeCompare(String(b.sw_name || b.sw_ip || ''));
  1477. return x || String(a.mac).localeCompare(String(b.mac));
  1478. });
  1479. var h = '';
  1480. list.forEach(function (tm) {
  1481. h += '<div class="off-row term-row" data-mac="' + esc(tm.mac) + '">' +
  1482. '<span class="term-dot" style="background:#2ECC71"></span>' +
  1483. '<div class="off-main"><div class="off-mac">' + esc(tm.mac) + '</div>' +
  1484. '<div class="off-sub"><span class="term-rate">' + esc(speedText(tm.speed)) + '</span> · ' +
  1485. esc(tm.sw_name || tm.sw_ip || '') + ' · ' + esc(tm.port || '') + '</div></div></div>';
  1486. });
  1487. box.innerHTML = h;
  1488. box.querySelectorAll('.term-row').forEach(function (r) {
  1489. r.addEventListener('click', function () { revealById('t_' + r.getAttribute('data-mac')); });
  1490. });
  1491. }
  1492. function buildHistory() {
  1493. var box = el('l2-history-list');
  1494. if (!box) return;
  1495. var list = window.L2_HISTORY || [];
  1496. var used = window.L2_META && window.L2_META.usedTs ? String(window.L2_META.usedTs) : '';
  1497. var h = '<div class="off-row hist-row' + (used ? '' : ' active') + '" data-ts=""><div class="off-main">' +
  1498. '<div class="off-mac">' + t('l2.history_live', 'Live / latest') + '</div>' +
  1499. '<div class="off-sub">' + t('l2.history_live_hint', 'Newest snapshot, auto refresh') + '</div></div></div>';
  1500. if (!list.length) {
  1501. h += '<div class="panel-empty">' + t('l2.history_empty', 'No history snapshots yet.') + '</div>';
  1502. } else {
  1503. list.forEach(function (it) {
  1504. var st = it.stats || {};
  1505. var ts = String(it.ts || '');
  1506. var sub = (st.switches != null ? st.switches + ' ' + t('l2.unit_sw', 'sw') : '') +
  1507. (st.term_total != null ? ' · ' + st.term_total + ' ' + t('l2.terminals', 'terminals') : '') +
  1508. (st.switches_offline ? ' · ' + st.switches_offline + ' ' + t('l2.offline_short', 'offline SW') : '');
  1509. h += '<div class="off-row hist-row' + (ts === used ? ' active' : '') + '" data-ts="' + esc(ts) + '">' +
  1510. '<div class="off-main"><div class="off-mac">' + esc(it.captured_at || fmtTs(it.ts)) + '</div>' +
  1511. '<div class="off-sub">' + esc(sub) + '</div></div></div>';
  1512. });
  1513. }
  1514. box.innerHTML = h;
  1515. box.querySelectorAll('.hist-row').forEach(function (r) {
  1516. r.addEventListener('click', function () {
  1517. var ts = r.getAttribute('data-ts');
  1518. var u = new URL(window.location.href);
  1519. u.searchParams.set('action', 'l2.topology.view');
  1520. if (ts) u.searchParams.set('ts', ts);
  1521. else u.searchParams.delete('ts');
  1522. window.location.href = u.toString();
  1523. });
  1524. });
  1525. if (el('l2-history-count')) el('l2-history-count').textContent = list.length;
  1526. // Keep the toolbar selector in sync with the same history list. The
  1527. // side panel is the primary entry point; the selector is a shortcut.
  1528. var sel = el('l2-ts');
  1529. if (sel) {
  1530. var old = sel.value;
  1531. sel.innerHTML = '';
  1532. var live = document.createElement('option');
  1533. live.value = '';
  1534. live.textContent = t('l2.time_live', 'Live');
  1535. sel.appendChild(live);
  1536. list.forEach(function (it) {
  1537. var opt = document.createElement('option');
  1538. opt.value = String(it.ts || '');
  1539. opt.textContent = it.captured_at || fmtTs(it.ts);
  1540. sel.appendChild(opt);
  1541. });
  1542. sel.value = used || old || '';
  1543. }
  1544. }
  1545. function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'})[c]; }); }
  1546. /* ---------------- interactions ---------------- */
  1547. function focusNode(id) {
  1548. if (!cy) return;
  1549. var n = cy.getElementById(id);
  1550. if (!n || n.empty() || n.length === 0) return;
  1551. cy.elements().removeClass('hl');
  1552. n.addClass('hl');
  1553. cy.animate({center: {eles: n}, zoom: Math.max(cy.zoom(), 1.1), duration: 380});
  1554. setTimeout(function () { n.removeClass('hl'); }, 2600);
  1555. }
  1556. function exportPng() {
  1557. if (!cy) return;
  1558. var btn = el('l2-export'), oldText = btn ? btn.textContent : '';
  1559. if (btn) { btn.disabled = true; btn.textContent = t('l2.exporting', '正在导出…'); }
  1560. var wasDark = dark;
  1561. try {
  1562. // The exported file must always be the day palette, even when the
  1563. // operator is currently using Zabbix dark mode.
  1564. cy.elements().removeClass('hl dim pathhl');
  1565. cy.style(styleFor(false));
  1566. if (typeof cy.forceRender === 'function') cy.forceRender();
  1567. var data = cy.png({full: true, scale: 1, maxWidth: 2600, maxHeight: 18000, bg: '#ffffff'});
  1568. var now = new Date();
  1569. function p2(v) { return (v < 10 ? '0' : '') + v; }
  1570. var suffix = META.usedTs ? ('_' + META.usedTs) : '_live';
  1571. var name = 'L2_Topology_' + now.getFullYear() + p2(now.getMonth() + 1) + p2(now.getDate()) +
  1572. '_' + p2(now.getHours()) + p2(now.getMinutes()) + suffix + '.png';
  1573. var a = document.createElement('a');
  1574. a.href = data;
  1575. a.download = name;
  1576. document.body.appendChild(a);
  1577. a.click();
  1578. document.body.removeChild(a);
  1579. } catch (e) {
  1580. window.alert(t('l2.export_fail', '导出失败,请重试。'));
  1581. } finally {
  1582. cy.style(styleFor(wasDark));
  1583. if (typeof cy.forceRender === 'function') cy.forceRender();
  1584. if (btn) { btn.disabled = false; btn.textContent = oldText; }
  1585. }
  1586. }
  1587. function groupOfNodeId(id) {
  1588. var hit = (lastSnap && lastSnap.nodes || []).filter(function (n) { return n.id === id; })[0];
  1589. return hit ? groupOf(hit).label : null;
  1590. }
  1591. // Make sure a switch/terminal is visible (auto-opens its workshop from overview).
  1592. function revealById(id) {
  1593. if (!lastSnap) return;
  1594. id = String(id);
  1595. if (id.indexOf('t_') === 0) {
  1596. var tm = (lastSnap.terminals || []).filter(function (x) { return 't_' + x.mac === id; })[0];
  1597. if (!tm) return;
  1598. pinnedTerm = tm.mac;
  1599. showTerm = true;
  1600. if (el('l2-showterm')) el('l2-showterm').checked = true;
  1601. if (!cy || cy.getElementById(id).empty()) render(lastSnap);
  1602. setTimeout(function () {
  1603. // Center the switch that the terminal hangs under, then flash the
  1604. // terminal dot so the exact port location is obvious.
  1605. focusNode(tm.sw_ip || id);
  1606. var tn = cy && cy.getElementById(id);
  1607. if (tn && tn.length) {
  1608. tn.addClass('hl');
  1609. setTimeout(function () { tn.removeClass('hl'); }, 2600);
  1610. }
  1611. }, 90);
  1612. } else {
  1613. focusNode(id);
  1614. }
  1615. }
  1616. function clearPath() {
  1617. if (!cy) return;
  1618. cy.elements().removeClass('dim pathhl');
  1619. lockedPath = null;
  1620. }
  1621. function upstreamGraph(nodeId) {
  1622. var snap = lastSnap || {};
  1623. var nodes = snap.nodes || [], edges = snap.edges || [];
  1624. var byId = {}, adj = {};
  1625. nodes.forEach(function (n) { byId[n.id] = n; adj[n.id] = []; });
  1626. edges.forEach(function (e) {
  1627. if (adj[e.source] && adj[e.target]) { adj[e.source].push(e.target); adj[e.target].push(e.source); }
  1628. });
  1629. var coreIds = nodes.filter(function (n) {
  1630. return (lastRoleMap[n.id] || roleOf(n)) === 'core';
  1631. }).map(function (n) { return n.id; });
  1632. // If the configured core list is empty, fall back to the collector's root
  1633. // tier so the upstream chain still starts at the physical core.
  1634. if (!coreIds.length) {
  1635. nodes.forEach(function (n) {
  1636. if (String(n.tier || '').toLowerCase() === 'core' || /^core(\s|-)/i.test(String(n.name || ''))) coreIds.push(n.id);
  1637. });
  1638. }
  1639. var level = {}, queue = [];
  1640. coreIds.forEach(function (id) { level[id] = 0; queue.push(id); });
  1641. while (queue.length) {
  1642. var cur = queue.shift();
  1643. (adj[cur] || []).forEach(function (nb) {
  1644. if (level[nb] == null) { level[nb] = level[cur] + 1; queue.push(nb); }
  1645. });
  1646. }
  1647. var nodeSet = {}, edgeSet = {}, stack = [nodeId];
  1648. nodeSet[nodeId] = true;
  1649. while (stack.length) {
  1650. var cur = stack.pop();
  1651. var curLv = level[cur];
  1652. if (curLv == null || curLv <= 0) continue;
  1653. (adj[cur] || []).forEach(function (nb) {
  1654. if (level[nb] !== curLv - 1) return;
  1655. // Cytoscape edges are anchored to hidden edgepoint nodes; the real
  1656. // switch pair is stored in p/c, so identify both orientations.
  1657. edgeSet[cur + '|' + nb] = true;
  1658. edgeSet[nb + '|' + cur] = true;
  1659. if (!nodeSet[nb]) { nodeSet[nb] = true; stack.push(nb); }
  1660. });
  1661. }
  1662. return {nodes: nodeSet, edges: edgeSet};
  1663. }
  1664. function highlightPath(nodeId) {
  1665. if (!cy) return;
  1666. var up = upstreamGraph(nodeId);
  1667. cy.elements('node[type="switch"], node[type="ghost"], edge').addClass('dim').removeClass('pathhl');
  1668. var nodes = cy.collection();
  1669. Object.keys(up.nodes).forEach(function (id) {
  1670. var n = cy.getElementById(id);
  1671. if (n && n.length) nodes = nodes.union(n);
  1672. });
  1673. nodes.removeClass('dim').addClass('pathhl');
  1674. var edges = cy.edges().filter(function (e) {
  1675. var p = e.data('p'), c = e.data('c');
  1676. return p && c && (up.edges[p + '|' + c] || up.edges[c + '|' + p]);
  1677. });
  1678. edges.removeClass('dim').addClass('pathhl');
  1679. }
  1680. function bindCy() {
  1681. cy.on('mouseover', 'node[type="switch"]', function (e) {
  1682. highlightPath(e.target.id());
  1683. var d = e.target.data();
  1684. var arr = d.alarms || [];
  1685. var sev = (d.maxsev != null && d.maxsev >= 0) ? ('<span style="color:' + SEV_COLORS[d.maxsev] + '">● ' + SEV_NAMES[d.maxsev] + '</span>') : '—';
  1686. var lat = (d.latency_ms != null) ? (d.latency_ms + ' ms') : '—';
  1687. var stat = (d.offline || d.oper === 'down') ? ('<span style="color:#E45959">' + esc(t('l2.offline', 'Offline')) + '</span>') : esc(d.oper || 'up');
  1688. var html = '<b>' + esc(d.name) + '</b><br>' + esc(d.ip) + ' · ' + esc(d.group || '') + '<br>' +
  1689. 'Tier: ' + esc(d.tier) + ' · ' + stat + '<br>' +
  1690. 'Latency: ' + lat + '<br>' +
  1691. 'Terminals: ' + (d.term_online || 0) + '<br>' +
  1692. 'Alarm: ' + sev;
  1693. if (d.offline || d.oper === 'down') html += '<br>' + esc(t('l2.last_online', 'last online')) + ': ' + esc(fmtTs(d.last_online));
  1694. if (arr.length) html += '<hr>' + arr.map(function (a) { return esc(a.name || a.description || ''); }).join('<br>');
  1695. showTip(e, html);
  1696. });
  1697. cy.on('mouseout', 'node[type="switch"]', function () {
  1698. if (!lockedPath) clearPath();
  1699. hideTip();
  1700. });
  1701. cy.on('mouseover', 'edge:not([type="term"])', function (e) {
  1702. var d = e.target.data();
  1703. var sp = (parseFloat(d.speed) || 0) >= 1000 ? ((parseFloat(d.speed) / 1000) + 'G') : (d.speed + 'M');
  1704. showTip(e, 'Link ' + esc(d.a_port || '') + ' ↔ ' + esc(d.b_port || '') + '<br>' + sp + ' · ' + esc(d.state || ''));
  1705. });
  1706. cy.on('mouseout', 'edge', hideTip);
  1707. cy.on('mouseover', 'node[type="term"]', function (e) {
  1708. var d = e.target.data();
  1709. e.target.data('label', d.termText || '');
  1710. showTip(e, '<b>' + esc(t('l2.term_title', 'Terminal')) + ' ' + esc(d.mac || '') + '</b><br>' +
  1711. esc(t('l2.term_mac', 'MAC address')) + ': ' + esc(d.mac || '') + '<br>' +
  1712. esc(t('l2.term_ip', 'IP address')) + ': ' + esc(d.ip || '—') + '<br>' +
  1713. esc(t('l2.term_rate', 'Link rate')) + ': ' + esc(speedText(d.speed)) + '<br>' +
  1714. esc(t('l2.term_switch', 'Switch')) + ': ' + esc(d.sw_name || '—') + '<br>' +
  1715. esc(t('l2.term_port', 'Port')) + ': ' + esc(d.port || '—'));
  1716. });
  1717. cy.on('mouseout', 'node[type="term"]', function (e) {
  1718. e.target.data('label', '');
  1719. hideTip();
  1720. });
  1721. cy.on('tap', 'node[type="switch"]', function (e) {
  1722. lockedPath = e.target.id();
  1723. highlightPath(lockedPath);
  1724. });
  1725. cy.on('tap', 'node[type="wsframe"]', function (e) {
  1726. cy.fit(e.target, 60);
  1727. });
  1728. cy.on('tap', function (e) {
  1729. if (e.target === cy) clearPath();
  1730. });
  1731. cy.on('dbltap', 'node[type="switch"]', function (e) {
  1732. var hid = e.target.data('hostid');
  1733. if (hid) window.open(META.zabbixHostUrl.replace('__HOSTID__', hid), '_blank');
  1734. });
  1735. }
  1736. var SEV_NAMES = ['未分类','信息','警告','一般严重','严重','灾难'];
  1737. function showTip(e, html) {
  1738. var tip = el('l2-tip');
  1739. tip.innerHTML = html;
  1740. tip.style.display = 'block';
  1741. var p = e.renderedPosition || {x: 0, y: 0};
  1742. var box = el('l2-cy').getBoundingClientRect();
  1743. var x = box.left + p.x + 16, y = box.top + p.y + 16;
  1744. tip.style.left = x + 'px'; tip.style.top = y + 'px';
  1745. }
  1746. function hideTip() { el('l2-tip').style.display = 'none'; }
  1747. /* ---------------- search ---------------- */
  1748. function buildIndex(snap) {
  1749. var idx = [];
  1750. (snap.nodes || []).forEach(function (n) { idx.push({id: n.id, label: n.name, sub: n.ip, kind: 'sw'}); });
  1751. (snap.terminals || []).forEach(function (tm) {
  1752. if (!terminalOnline(tm)) return;
  1753. idx.push({id: 't_' + tm.mac, label: tm.mac, sub: (tm.ip || '') + ' · ' + speedText(tm.speed) + ' · ' + (tm.sw_name || ''), kind: 'term', mac: tm.mac});
  1754. });
  1755. return idx;
  1756. }
  1757. var INDEX = [];
  1758. function doSearch(q) {
  1759. var box = el('l2-sug');
  1760. q = (q || '').trim().toLowerCase();
  1761. if (!q) { box.style.display = 'none'; box.innerHTML = ''; return; }
  1762. var hits = [];
  1763. var qn = q.replace(/[^a-z0-9]/g, '');
  1764. for (var i = 0; i < INDEX.length && hits.length < 14; i++) {
  1765. var it = INDEX[i];
  1766. var hay = ((it.label || '') + ' ' + (it.sub || '')).toLowerCase();
  1767. var hayN = hay.replace(/[^a-z0-9]/g, '');
  1768. if (hay.indexOf(q) >= 0 || (qn && hayN.indexOf(qn) >= 0)) hits.push(it);
  1769. }
  1770. if (!hits.length) { box.innerHTML = '<div class="sug-empty">—</div>'; box.style.display = 'block'; return; }
  1771. box.innerHTML = hits.map(function (h) {
  1772. return '<div class="sug-row" data-id="' + esc(h.id) + '"><span class="sug-kind ' + h.kind + '">' + (h.kind === 'sw' ? 'SW' : 'PC') + '</span>' +
  1773. '<span class="sug-lbl">' + esc(h.label) + '</span><span class="sug-sub">' + esc(h.sub || '') + '</span></div>';
  1774. }).join('');
  1775. box.style.display = 'block';
  1776. box.querySelectorAll('.sug-row').forEach(function (r) {
  1777. r.addEventListener('click', function () {
  1778. var id = r.getAttribute('data-id');
  1779. revealById(id);
  1780. box.style.display = 'none';
  1781. });
  1782. });
  1783. }
  1784. /* ---------------- toolbar wiring ---------------- */
  1785. function isZabbixDark() {
  1786. var html = document.documentElement;
  1787. var cs = String(html.getAttribute('color-scheme') || '').toLowerCase();
  1788. if (cs === 'dark') return true;
  1789. if (cs === 'light') return false;
  1790. var body = document.body;
  1791. var theme = [
  1792. html.getAttribute('theme'), html.getAttribute('data-theme'), html.className,
  1793. body ? body.getAttribute('theme') : '', body ? body.getAttribute('data-theme') : '',
  1794. body ? body.className : ''
  1795. ].join(' ');
  1796. return /dark/i.test(theme);
  1797. }
  1798. function applyTheme() {
  1799. var nd = isZabbixDark();
  1800. var changed = nd !== dark;
  1801. dark = nd;
  1802. var wrap = el('l2-wrap');
  1803. if (wrap) wrap.classList.toggle('l2-dark', dark);
  1804. if (changed && cy) cy.style(styleFor(dark));
  1805. }
  1806. function fitViewport() {
  1807. var wrap = el('l2-wrap');
  1808. if (!wrap) return;
  1809. var top = Math.max(0, wrap.getBoundingClientRect().top);
  1810. var h = Math.max(520, window.innerHeight - top - 8);
  1811. wrap.style.height = h + 'px';
  1812. if (cy) cy.resize();
  1813. }
  1814. function setupControls() {
  1815. applyTheme();
  1816. if (window.MutationObserver) {
  1817. var mo = new MutationObserver(applyTheme);
  1818. mo.observe(document.documentElement, {attributes: true, attributeFilter: ['theme', 'data-theme', 'color-scheme', 'class']});
  1819. if (document.body) {
  1820. mo.observe(document.body, {attributes: true, attributeFilter: ['theme', 'data-theme', 'color-scheme', 'class']});
  1821. }
  1822. }
  1823. var back = el('l2-back');
  1824. if (back) back.style.display = 'none';
  1825. el('l2-showterm').addEventListener('change', function () { showTerm = el('l2-showterm').checked; render(lastSnap); });
  1826. el('l2-zin').addEventListener('click', function () { if (cy) cy.zoom({level: cy.zoom() * 1.25, renderedPosition: {x: cy.width() / 2, y: cy.height() / 2}}); });
  1827. el('l2-zout').addEventListener('click', function () { if (cy) cy.zoom({level: cy.zoom() / 1.25, renderedPosition: {x: cy.width() / 2, y: cy.height() / 2}}); });
  1828. el('l2-fit').addEventListener('click', function () { if (cy) cy.fit(cy.elements(), 50); });
  1829. if (el('l2-export')) el('l2-export').addEventListener('click', exportPng);
  1830. el('l2-refresh-btn').addEventListener('click', function () { reload(true); });
  1831. window.addEventListener('resize', fitViewport);
  1832. var s = el('l2-search');
  1833. s.addEventListener('input', function () { doSearch(s.value); });
  1834. document.addEventListener('click', function (ev) {
  1835. if (!ev.target.closest('.l2-search-wrap')) el('l2-sug').style.display = 'none';
  1836. });
  1837. el('l2-ts').addEventListener('change', function () {
  1838. var v = el('l2-ts').value;
  1839. var u = '/zabbix.php?action=l2.topology.view';
  1840. if (v) u += '&ts=' + encodeURIComponent(v);
  1841. window.location = u;
  1842. });
  1843. el('l2-pause').addEventListener('click', function () {
  1844. paused = !paused;
  1845. el('l2-pause').classList.toggle('on', paused);
  1846. el('l2-pause').textContent = paused ? '▶' : '❚❚';
  1847. el('l2-pause').title = paused ? t('l2.resume', 'Resume') : t('l2.pause', 'Pause');
  1848. });
  1849. }
  1850. function reload(manual) {
  1851. if (!META.isLive) return;
  1852. fetch(META.snapshotUrl + '?t=' + Date.now(), {cache: 'no-store'})
  1853. .then(function (r) { return r.json(); })
  1854. .then(function (j) { if (j && j.nodes) { SNAP = j; INDEX = buildIndex(j); render(j); } })
  1855. .catch(function () {})
  1856. .then(function () { if (manual) resetCountdown(); });
  1857. }
  1858. function resetCountdown() { countdown = META.refreshSeconds || 300; }
  1859. function startTimer() {
  1860. if (!META.isLive) return;
  1861. resetCountdown();
  1862. timer = setInterval(function () {
  1863. if (paused) { el('l2-countdown').textContent = '⏸'; return; }
  1864. countdown--;
  1865. if (countdown <= 0) { countdown = META.refreshSeconds || 300; reload(false); }
  1866. var m = Math.floor(countdown / 60), s = countdown % 60;
  1867. el('l2-countdown').textContent = '↻ ' + m + ':' + (s < 10 ? '0' + s : s);
  1868. }, 1000);
  1869. }
  1870. /* ---------------- boot ---------------- */
  1871. function boot() {
  1872. setupControls();
  1873. fitViewport();
  1874. try {
  1875. var qs = new URLSearchParams(window.location.search);
  1876. var qg = qs.get('g');
  1877. if (qg) focusGroupLabel = qg;
  1878. } catch (e) {}
  1879. if (!SNAP || !SNAP.nodes) {
  1880. el('l2-cy').innerHTML = '<div class="l2-empty">' + t('l2.no_data', 'No data') + '</div>';
  1881. } else {
  1882. INDEX = buildIndex(SNAP);
  1883. render(SNAP);
  1884. }
  1885. setTimeout(fitViewport, 60);
  1886. if (META.isLive) startTimer();
  1887. else { el('l2-pause').disabled = true; el('l2-countdown').textContent = t('l2.snapshot', 'Snapshot'); }
  1888. }
  1889. if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot);
  1890. else boot();
  1891. })();