app.js 102 KB

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