display.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. 'use strict';
  2. 'require view';
  3. 'require network';
  4. 'require request';
  5. 'require fs';
  6. 'require ui';
  7. 'require rpc';
  8. 'require dom';
  9. var callNetworkRrdnsLookup = rpc.declare({
  10. object: 'network.rrdns',
  11. method: 'lookup',
  12. params: [ 'addrs', 'timeout', 'limit' ],
  13. expect: { '': {} }
  14. });
  15. var chartRegistry = {},
  16. trafficPeriods = [],
  17. trafficData = { columns: [], data: [] },
  18. hostNames = {},
  19. hostInfo = {},
  20. ouiData = [];
  21. return view.extend({
  22. load: function() {
  23. return Promise.all([
  24. this.loadHosts(),
  25. this.loadPeriods(),
  26. this.loadData(),
  27. this.loadOUI()
  28. ]);
  29. },
  30. loadHosts: function() {
  31. return L.resolveDefault(network.getHostHints()).then(function(res) {
  32. if (res) {
  33. var hints = res.getMACHints();
  34. for (var i = 0; i < hints.length; i++) {
  35. hostInfo[hints[i][0]] = {
  36. name: res.getHostnameByMACAddr(hints[i][0]),
  37. ipv6: res.getIP6AddrByMACAddr(hints[i][0]),
  38. ipv4: res.getIPAddrByMACAddr(hints[i][0])
  39. };
  40. }
  41. }
  42. });
  43. },
  44. loadOUI: function() {
  45. var url = 'https://raw.githubusercontent.com/jow-/oui-database/master/oui.json';
  46. return L.resolveDefault(request.get(url, { cache: true })).then(function(res) {
  47. res = res ? res.json() : [];
  48. if (Array.isArray(res))
  49. ouiData = res;
  50. });
  51. },
  52. loadPeriods: function() {
  53. return L.resolveDefault(fs.exec_direct('/usr/libexec/nlbwmon-action', [ 'periods' ], 'json')).then(function(res) {
  54. if (L.isObject(res) && Array.isArray(res.periods))
  55. trafficPeriods = res.periods;
  56. });
  57. },
  58. loadData: function(period) {
  59. var args = [ 'download', '-g', 'family,mac,ip,layer7', '-o', '-rx_bytes,-tx_bytes' ];
  60. if (period)
  61. args.push('-t', period);
  62. return fs.exec_direct('/usr/libexec/nlbwmon-action', args, 'json').then(L.bind(function(res) {
  63. if (!L.isObject(res) || !Array.isArray(res.columns) || !Array.isArray(res.data))
  64. throw new Error(_('Malformed data received'));
  65. trafficData = res;
  66. var addrs = this.query(null, [ 'ip' ], null),
  67. ipAddrs = [];
  68. for (var i = 0; i < addrs.length; i++)
  69. if (ipAddrs.indexOf(addrs[i].ip) < 0)
  70. ipAddrs.push(addrs[i].ip);
  71. if (ipAddrs.length)
  72. return L.resolveDefault(callNetworkRrdnsLookup(ipAddrs, 1000, 1000), {}).then(function(res) {
  73. hostNames = res;
  74. });
  75. }, this)).catch(function(err) {
  76. ui.addNotification(null, _('Unable to fetch traffic statistic data: %s').format(err.message));
  77. });
  78. },
  79. off: function(elem) {
  80. var val = [0, 0];
  81. do {
  82. if (!isNaN(elem.offsetLeft) && !isNaN(elem.offsetTop)) {
  83. val[0] += elem.offsetLeft;
  84. val[1] += elem.offsetTop;
  85. }
  86. }
  87. while ((elem = elem.offsetParent) != null);
  88. return val;
  89. },
  90. kpi: function(id, val1, val2, val3) {
  91. var e = L.dom.elem(id) ? id : document.getElementById(id);
  92. if (val1 && val2 && val3)
  93. e.innerHTML = _('%s, %s and %s').format(val1, val2, val3);
  94. else if (val1 && val2)
  95. e.innerHTML = _('%s and %s').format(val1, val2);
  96. else if (val1)
  97. e.innerHTML = val1;
  98. e.parentNode.style.display = val1 ? 'list-item' : '';
  99. },
  100. pie: function(id, data) {
  101. var total = data.reduce(function(n, d) { return n + d.value }, 0);
  102. data.sort(function(a, b) { return b.value - a.value });
  103. if (total === 0)
  104. data = [{
  105. value: 1,
  106. color: '#cccccc',
  107. label: [ _('no traffic') ]
  108. }];
  109. for (var i = 0; i < data.length; i++) {
  110. if (!data[i].color) {
  111. var hue = 120 / (data.length-1) * i;
  112. data[i].color = 'hsl(%u, 80%%, 50%%)'.format(hue);
  113. data[i].label.push(hue);
  114. }
  115. }
  116. var node = L.dom.elem(id) ? id : document.getElementById(id),
  117. key = L.dom.elem(id) ? id.id : id,
  118. ctx = node.getContext('2d');
  119. if (chartRegistry.hasOwnProperty(key))
  120. chartRegistry[key].destroy();
  121. chartRegistry[key] = new Chart(ctx).Doughnut(data, {
  122. segmentStrokeWidth: 1,
  123. percentageInnerCutout: 30
  124. });
  125. return chartRegistry[key];
  126. },
  127. oui: function(mac) {
  128. var m, l = 0, r = ouiData.length / 3 - 1;
  129. var mac1 = parseInt(mac.replace(/[^a-fA-F0-9]/g, ''), 16);
  130. while (l <= r) {
  131. m = l + Math.floor((r - l) / 2);
  132. var mask = (0xffffffffffff -
  133. (Math.pow(2, 48 - ouiData[m * 3 + 1]) - 1));
  134. var mac1_hi = ((mac1 / 0x10000) & (mask / 0x10000)) >>> 0;
  135. var mac1_lo = ((mac1 & 0xffff) & (mask & 0xffff)) >>> 0;
  136. var mac2 = parseInt(ouiData[m * 3], 16);
  137. var mac2_hi = (mac2 / 0x10000) >>> 0;
  138. var mac2_lo = (mac2 & 0xffff) >>> 0;
  139. if (mac1_hi === mac2_hi && mac1_lo === mac2_lo)
  140. return ouiData[m * 3 + 2];
  141. if (mac2_hi > mac1_hi ||
  142. (mac2_hi === mac1_hi && mac2_lo > mac1_lo))
  143. r = m - 1;
  144. else
  145. l = m + 1;
  146. }
  147. return null;
  148. },
  149. query: function(filter, group, order) {
  150. var keys = [], columns = {}, records = {}, result = [];
  151. if (typeof(group) !== 'function' && typeof(group) !== 'object')
  152. group = ['mac'];
  153. for (var i = 0; i < trafficData.columns.length; i++)
  154. columns[trafficData.columns[i]] = i;
  155. for (var i = 0; i < trafficData.data.length; i++) {
  156. var record = trafficData.data[i];
  157. if (typeof(filter) === 'function' && filter(columns, record) !== true)
  158. continue;
  159. var key;
  160. if (typeof(group) === 'function') {
  161. key = group(columns, record);
  162. }
  163. else {
  164. key = [];
  165. for (var j = 0; j < group.length; j++)
  166. if (columns.hasOwnProperty(group[j]))
  167. key.push(record[columns[group[j]]]);
  168. key = key.join(',');
  169. }
  170. if (!records.hasOwnProperty(key)) {
  171. var rec = {};
  172. for (var col in columns)
  173. rec[col] = record[columns[col]];
  174. records[key] = rec;
  175. result.push(rec);
  176. }
  177. else {
  178. records[key].conns += record[columns.conns];
  179. records[key].rx_bytes += record[columns.rx_bytes];
  180. records[key].rx_pkts += record[columns.rx_pkts];
  181. records[key].tx_bytes += record[columns.tx_bytes];
  182. records[key].tx_pkts += record[columns.tx_pkts];
  183. }
  184. }
  185. if (typeof(order) === 'function')
  186. result.sort(order);
  187. return result;
  188. },
  189. renderPeriods: function() {
  190. if (!trafficPeriods.length)
  191. return E([]);
  192. var choices = {},
  193. keys = [];
  194. for (var e, i = trafficPeriods.length - 1; e = trafficPeriods[i]; i--) {
  195. var ymd1 = e.split(/-/);
  196. var d1 = new Date(+ymd1[0], +ymd1[1] - 1, +ymd1[2]);
  197. var ymd2, d2, pd;
  198. if (i) {
  199. ymd2 = trafficPeriods[i - 1].split(/-/);
  200. d2 = new Date(+ymd2[0], +ymd2[1] - 1, +ymd2[2]);
  201. d2.setDate(d2.getDate() - 1);
  202. pd = e;
  203. }
  204. else {
  205. d2 = new Date();
  206. pd = '-';
  207. }
  208. keys.push(pd);
  209. choices[pd] = '%04d-%02d-%02d - %04d-%02d-%02d'.format(
  210. d1.getFullYear(), d1.getMonth() + 1, d1.getDate(),
  211. d2.getFullYear(), d2.getMonth() + 1, d2.getDate()
  212. );
  213. }
  214. var dropdown = new ui.Dropdown('-', choices, { sort: keys, optional: false }).render();
  215. dropdown.addEventListener('cbi-dropdown-change', ui.createHandlerFn(this, function(ev) {
  216. ui.hideTooltip(ev);
  217. var period = ev.detail.value.value != '-' ? ev.detail.value.value : null;
  218. return this.loadData(period).then(L.bind(function() {
  219. this.renderHostData();
  220. this.renderLayer7Data();
  221. this.renderIPv6Data();
  222. }, this));
  223. }));
  224. return E([], [
  225. E('p', [ _('Select accounting period:'), ' ', dropdown ]),
  226. E('hr')
  227. ]);
  228. },
  229. formatHostname: function(dns) {
  230. if (dns === undefined || dns === null || dns === '')
  231. return '-';
  232. dns = dns.split('.')[0];
  233. if (dns.length > 12)
  234. return '<span title="%q">%h…</span>'.format(dns, dns.substr(0, 12));
  235. return '%h'.format(dns);
  236. },
  237. renderHostData: function() {
  238. var trafData = [], connData = [];
  239. var rx_total = 0, tx_total = 0, conn_total = 0;
  240. var hostData = this.query(
  241. function(c, r) {
  242. return (r[c.rx_bytes] > 0 || r[c.tx_bytes] > 0);
  243. },
  244. ['mac'],
  245. //function(c, r) {
  246. // return (r[c.mac] !== '00:00:00:00:00:00') ? r[c.mac] : r[c.ip];
  247. //},
  248. function(r1, r2) {
  249. return ((r2.rx_bytes + r2.tx_bytes) - (r1.rx_bytes + r1.tx_bytes));
  250. }
  251. );
  252. var rows = [];
  253. for (var i = 0; i < hostData.length; i++) {
  254. var rec = hostData[i],
  255. mac = rec.mac.toUpperCase(),
  256. key = (mac !== '00:00:00:00:00:00') ? mac : rec.ip,
  257. dns = hostInfo[mac] ? hostInfo[mac].name : null;
  258. var cell = E('div', this.formatHostname(dns));
  259. rows.push([
  260. cell,
  261. E('a', {
  262. 'href': '#' + rec.mac,
  263. 'data-col': 'ip',
  264. 'data-tooltip': _('Source IP')
  265. }, (mac !== '00:00:00:00:00:00') ? mac : _('other')),
  266. [ rec.conns, E('a', {
  267. 'href': '#' + rec.mac,
  268. 'data-col': 'layer7',
  269. 'data-tooltip': _('Protocol')
  270. }, '%1000.2m'.format(rec.conns)) ],
  271. [ rec.rx_bytes, '%1024.2mB'.format(rec.rx_bytes) ],
  272. [ rec.rx_pkts, '%1000.2mP'.format(rec.rx_pkts) ],
  273. [ rec.tx_bytes, '%1024.2mB'.format(rec.tx_bytes) ],
  274. [ rec.tx_pkts, '%1000.2mP'.format(rec.tx_pkts) ]
  275. ]);
  276. trafData.push({
  277. value: rec.rx_bytes + rec.tx_bytes,
  278. label: ["%s: %%1024.2mB".format(key), cell]
  279. });
  280. connData.push({
  281. value: rec.conns,
  282. label: ["%s: %%1000.2m".format(key), cell]
  283. });
  284. rx_total += rec.rx_bytes;
  285. tx_total += rec.tx_bytes;
  286. conn_total += rec.conns;
  287. }
  288. cbi_update_table('#host-data', rows, E('em', _('No data recorded yet.')));
  289. this.pie('traf-pie', trafData);
  290. this.pie('conn-pie', connData);
  291. this.kpi('rx-total', '%1024.2mB'.format(rx_total));
  292. this.kpi('tx-total', '%1024.2mB'.format(tx_total));
  293. this.kpi('conn-total', '%1000m'.format(conn_total));
  294. this.kpi('host-total', '%u'.format(hostData.length));
  295. },
  296. renderLayer7Data: function() {
  297. var rxData = [], txData = [];
  298. var topConn = [[0],[0],[0]], topRx = [[0],[0],[0]], topTx = [[0],[0],[0]];
  299. var layer7Data = this.query(
  300. null, ['layer7'],
  301. function(r1, r2) {
  302. return ((r2.rx_bytes + r2.tx_bytes) - (r1.rx_bytes + r1.tx_bytes));
  303. }
  304. );
  305. var rows = [];
  306. for (var i = 0, c = 0; i < layer7Data.length; i++) {
  307. var rec = layer7Data[i],
  308. cell = E('div', rec.layer7 || _('other'));
  309. rows.push([
  310. cell,
  311. [ rec.conns, '%1000m'.format(rec.conns) ],
  312. [ rec.rx_bytes, '%1024.2mB'.format(rec.rx_bytes) ],
  313. [ rec.rx_pkts, '%1000.2mP'.format(rec.rx_pkts) ],
  314. [ rec.tx_bytes, '%1024.2mB'.format(rec.tx_bytes) ],
  315. [ rec.tx_pkts, '%1000.2mP'.format(rec.tx_pkts) ]
  316. ]);
  317. rxData.push({
  318. value: rec.rx_bytes,
  319. label: ["%s: %%1024.2mB".format(rec.layer7 || _('other')), cell]
  320. });
  321. txData.push({
  322. value: rec.tx_bytes,
  323. label: ["%s: %%1024.2mB".format(rec.layer7 || _('other')), cell]
  324. });
  325. if (rec.layer7) {
  326. topRx.push([rec.rx_bytes, rec.layer7]);
  327. topTx.push([rec.tx_bytes, rec.layer7]);
  328. topConn.push([rec.conns, rec.layer7]);
  329. }
  330. }
  331. cbi_update_table('#layer7-data', rows, E('em', _('No data recorded yet.')));
  332. this.pie('layer7-rx-pie', rxData);
  333. this.pie('layer7-tx-pie', txData);
  334. topRx.sort(function(a, b) { return b[0] - a[0] });
  335. topTx.sort(function(a, b) { return b[0] - a[0] });
  336. topConn.sort(function(a, b) { return b[0] - a[0] });
  337. this.kpi('layer7-total', layer7Data.length);
  338. this.kpi('layer7-most-rx', topRx[0][1], topRx[1][1], topRx[2][1]);
  339. this.kpi('layer7-most-tx', topTx[0][1], topTx[1][1], topTx[2][1]);
  340. this.kpi('layer7-most-conn', topConn[0][1], topConn[1][1], topConn[2][1]);
  341. },
  342. renderIPv6Data: function() {
  343. var col = { },
  344. rx4_total = 0,
  345. tx4_total = 0,
  346. rx6_total = 0,
  347. tx6_total = 0,
  348. v4_total = 0,
  349. v6_total = 0,
  350. ds_total = 0,
  351. families = { },
  352. records = { };
  353. var ipv6Data = this.query(
  354. null, ['family', 'mac'],
  355. function(r1, r2) {
  356. return ((r2.rx_bytes + r2.tx_bytes) - (r1.rx_bytes + r1.tx_bytes));
  357. }
  358. );
  359. for (var i = 0, c = 0; i < ipv6Data.length; i++) {
  360. var rec = ipv6Data[i],
  361. mac = rec.mac.toUpperCase(),
  362. ip = rec.ip,
  363. fam = families[mac] || 0,
  364. recs = records[mac] || {};
  365. if (rec.family == 4) {
  366. rx4_total += rec.rx_bytes;
  367. tx4_total += rec.tx_bytes;
  368. fam |= 1;
  369. }
  370. else {
  371. rx6_total += rec.rx_bytes;
  372. tx6_total += rec.tx_bytes;
  373. fam |= 2;
  374. }
  375. recs[rec.family] = rec;
  376. records[mac] = recs;
  377. families[mac] = fam;
  378. }
  379. for (var mac in families) {
  380. switch (families[mac])
  381. {
  382. case 3:
  383. ds_total++;
  384. break;
  385. case 2:
  386. v6_total++;
  387. break;
  388. case 1:
  389. v4_total++;
  390. break;
  391. }
  392. }
  393. var rows = [];
  394. for (var mac in records) {
  395. if (mac === '00:00:00:00:00:00')
  396. continue;
  397. var dns = hostInfo[mac] ? hostInfo[mac].name : null,
  398. rec4 = records[mac][4],
  399. rec6 = records[mac][6];
  400. rows.push([
  401. this.formatHostname(dns),
  402. mac,
  403. [
  404. 0,
  405. E([], [
  406. E('span', _('IPv4')),
  407. E('span', _('IPv6'))
  408. ])
  409. ],
  410. [
  411. (rec4 ? rec4.rx_bytes : 0) + (rec6 ? rec6.rx_bytes : 0),
  412. E([], [
  413. E('span', rec4 ? '%1024.2mB'.format(rec4.rx_bytes) : '-'),
  414. E('span', rec6 ? '%1024.2mB'.format(rec6.rx_bytes) : '-')
  415. ])
  416. ],
  417. [
  418. (rec4 ? rec4.rx_pkts : 0) + (rec6 ? rec6.rx_pkts : 0),
  419. E([], [
  420. E('span', rec4 ? '%1000.2mP'.format(rec4.rx_pkts) : '-'),
  421. E('span', rec6 ? '%1000.2mP'.format(rec6.rx_pkts) : '-')
  422. ])
  423. ],
  424. [
  425. (rec4 ? rec4.tx_bytes : 0) + (rec6 ? rec6.tx_bytes : 0),
  426. E([], [
  427. E('span', rec4 ? '%1024.2mB'.format(rec4.tx_bytes) : '-'),
  428. E('span', rec6 ? '%1024.2mB'.format(rec6.tx_bytes) : '-')
  429. ])
  430. ],
  431. [
  432. (rec4 ? rec4.tx_pkts : 0) + (rec6 ? rec6.tx_pkts : 0),
  433. E([], [
  434. E('span', rec4 ? '%1000.2mP'.format(rec4.tx_pkts) : '-'),
  435. E('span', rec6 ? '%1000.2mP'.format(rec6.tx_pkts) : '-')
  436. ])
  437. ]
  438. ]);
  439. }
  440. cbi_update_table('#ipv6-data', rows, E('em', _('No data recorded yet.')));
  441. var shareData = [], hostsData = [];
  442. if (rx4_total > 0 || tx4_total > 0)
  443. shareData.push({
  444. value: rx4_total + tx4_total,
  445. label: ["IPv4: %1024.2mB"],
  446. color: 'hsl(140, 100%, 50%)'
  447. });
  448. if (rx6_total > 0 || tx6_total > 0)
  449. shareData.push({
  450. value: rx6_total + tx6_total,
  451. label: ["IPv6: %1024.2mB"],
  452. color: 'hsl(180, 100%, 50%)'
  453. });
  454. if (v4_total > 0)
  455. hostsData.push({
  456. value: v4_total,
  457. label: [_('%d IPv4-only hosts')],
  458. color: 'hsl(140, 100%, 50%)'
  459. });
  460. if (v6_total > 0)
  461. hostsData.push({
  462. value: v6_total,
  463. label: [_('%d IPv6-only hosts')],
  464. color: 'hsl(180, 100%, 50%)'
  465. });
  466. if (ds_total > 0)
  467. hostsData.push({
  468. value: ds_total,
  469. label: [_('%d dual-stack hosts')],
  470. color: 'hsl(50, 100%, 50%)'
  471. });
  472. this.pie('ipv6-share-pie', shareData);
  473. this.pie('ipv6-hosts-pie', hostsData);
  474. this.kpi('ipv6-hosts', '%.2f%%'.format(100 / (ds_total + v4_total + v6_total) * (ds_total + v6_total)));
  475. this.kpi('ipv6-share', '%.2f%%'.format(100 / (rx4_total + rx6_total + tx4_total + tx6_total) * (rx6_total + tx6_total)));
  476. this.kpi('ipv6-rx', '%1024.2mB'.format(rx6_total));
  477. this.kpi('ipv6-tx', '%1024.2mB'.format(tx6_total));
  478. },
  479. renderHostDetail: function(node, tooltip) {
  480. var key = node.getAttribute('href').substr(1),
  481. col = node.getAttribute('data-col'),
  482. label = node.getAttribute('data-tooltip');
  483. var detailData = this.query(
  484. function(c, r) {
  485. return ((r[c.mac] === key || r[c.ip] === key) &&
  486. (r[c.rx_bytes] > 0 || r[c.tx_bytes] > 0));
  487. },
  488. [col],
  489. function(r1, r2) {
  490. return ((r2.rx_bytes + r2.tx_bytes) - (r1.rx_bytes + r1.tx_bytes));
  491. }
  492. );
  493. var rxData = [], txData = [];
  494. dom.content(tooltip, [
  495. E('div', { 'class': 'head' }, [
  496. E('div', { 'class': 'pie' }, [
  497. E('label', _('Download', 'Traffic counter')),
  498. E('canvas', { 'id': 'bubble-pie1', 'width': 100, 'height': 100 })
  499. ]),
  500. E('div', { 'class': 'pie' }, [
  501. E('label', _('Upload', 'Traffic counter')),
  502. E('canvas', { 'id': 'bubble-pie2', 'width': 100, 'height': 100 })
  503. ]),
  504. E('div', { 'class': 'kpi' }, [
  505. E('ul', [
  506. E('li', _('Hostname: <big id="bubble-hostname">example.org</big>')),
  507. E('li', _('Vendor: <big id="bubble-vendor">Example Corp.</big>'))
  508. ])
  509. ])
  510. ]),
  511. E('table', { 'class': 'table' }, [
  512. E('tr', { 'class': 'tr table-titles' }, [
  513. E('th', { 'class': 'th' }, label || col),
  514. E('th', { 'class': 'th' }, _('Conn.')),
  515. E('th', { 'class': 'th' }, _('Down. (Bytes)')),
  516. E('th', { 'class': 'th' }, _('Down. (Pkts.)')),
  517. E('th', { 'class': 'th' }, _('Up. (Bytes)')),
  518. E('th', { 'class': 'th' }, _('Up. (Pkts.)')),
  519. ])
  520. ])
  521. ]);
  522. var rows = [];
  523. for (var i = 0; i < detailData.length; i++) {
  524. var rec = detailData[i],
  525. cell = E('div', rec[col] || _('other'));
  526. rows.push([
  527. cell,
  528. [ rec.conns, '%1000.2m'.format(rec.conns) ],
  529. [ rec.rx_bytes, '%1024.2mB'.format(rec.rx_bytes) ],
  530. [ rec.rx_pkts, '%1000.2mP'.format(rec.rx_pkts) ],
  531. [ rec.tx_bytes, '%1024.2mB'.format(rec.tx_bytes) ],
  532. [ rec.tx_pkts, '%1000.2mP'.format(rec.tx_pkts) ]
  533. ]);
  534. rxData.push({
  535. label: ['%s: %%1024.2mB'.format(rec[col] || _('other')), cell],
  536. value: rec.rx_bytes
  537. });
  538. txData.push({
  539. label: ['%s: %%1024.2mB'.format(rec[col] || _('other')), cell],
  540. value: rec.tx_bytes
  541. });
  542. }
  543. cbi_update_table(tooltip.lastElementChild, rows);
  544. this.pie(tooltip.querySelector('#bubble-pie1'), rxData);
  545. this.pie(tooltip.querySelector('#bubble-pie2'), txData);
  546. var mac = key.toUpperCase();
  547. var name = hostInfo.hasOwnProperty(mac) ? hostInfo[mac].name : null;
  548. if (!name)
  549. for (var i = 0; i < detailData.length; i++)
  550. if ((name = hostNames[detailData[i].ip]) !== undefined)
  551. break;
  552. if (mac !== '00:00:00:00:00:00') {
  553. this.kpi(tooltip.querySelector('#bubble-hostname'), name);
  554. this.kpi(tooltip.querySelector('#bubble-vendor'), this.oui(mac));
  555. }
  556. else {
  557. this.kpi(tooltip.querySelector('#bubble-hostname'));
  558. this.kpi(tooltip.querySelector('#bubble-vendor'));
  559. }
  560. var rect = node.getBoundingClientRect(), x, y;
  561. if ('ontouchstart' in window || window.innerWidth <= 992) {
  562. var vpHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0),
  563. scrollFrom = window.pageYOffset,
  564. scrollTo = scrollFrom + rect.top - vpHeight * 0.5,
  565. start = null;
  566. tooltip.style.top = (rect.top + rect.height + window.pageYOffset) + 'px';
  567. tooltip.style.left = 0;
  568. var scrollStep = function(timestamp) {
  569. if (!start)
  570. start = timestamp;
  571. var duration = Math.max(timestamp - start, 1);
  572. if (duration < 100) {
  573. document.body.scrollTop = scrollFrom + (scrollTo - scrollFrom) * (duration / 100);
  574. window.requestAnimationFrame(scrollStep);
  575. }
  576. else {
  577. document.body.scrollTop = scrollTo;
  578. }
  579. };
  580. window.requestAnimationFrame(scrollStep);
  581. }
  582. else {
  583. x = rect.left + rect.width + window.pageXOffset,
  584. y = rect.top + window.pageYOffset;
  585. if ((y + tooltip.offsetHeight) > (window.innerHeight + window.pageYOffset))
  586. y -= ((y + tooltip.offsetHeight) - (window.innerHeight + window.pageYOffset));
  587. tooltip.style.top = y + 'px';
  588. tooltip.style.left = x + 'px';
  589. }
  590. return false;
  591. },
  592. setupCharts: function() {
  593. Chart.defaults.global.customTooltips = L.bind(function(tooltip) {
  594. var tooltipEl = document.getElementById('chartjs-tooltip');
  595. if (!tooltipEl) {
  596. tooltipEl = document.createElement('div');
  597. tooltipEl.setAttribute('id', 'chartjs-tooltip');
  598. document.body.appendChild(tooltipEl);
  599. }
  600. if (!tooltip) {
  601. if (tooltipEl.row)
  602. tooltipEl.row.style.backgroundColor = '';
  603. tooltipEl.style.opacity = 0;
  604. return;
  605. }
  606. var pos = this.off(tooltip.chart.canvas);
  607. tooltipEl.className = tooltip.yAlign;
  608. tooltipEl.innerHTML = tooltip.text[0];
  609. tooltipEl.style.opacity = 1;
  610. tooltipEl.style.left = pos[0] + tooltip.x + 'px';
  611. tooltipEl.style.top = pos[1] + tooltip.y - tooltip.caretHeight - tooltip.caretPadding + 'px';
  612. var row = findParent(tooltip.text[1], '.tr'),
  613. hue = tooltip.text[2];
  614. if (row && !isNaN(hue)) {
  615. row.style.backgroundColor = 'hsl(%u, 100%%, 80%%)'.format(hue);
  616. tooltipEl.row = row;
  617. }
  618. }, this);
  619. Chart.defaults.global.tooltipFontSize = 10;
  620. Chart.defaults.global.tooltipTemplate = function(tip) {
  621. tip.label[0] = tip.label[0].format(tip.value);
  622. return tip.label;
  623. };
  624. this.renderHostData();
  625. this.renderLayer7Data();
  626. this.renderIPv6Data();
  627. },
  628. handleDownload: function(type, group, order) {
  629. var args = [ 'download', '-f', type ];
  630. if (group)
  631. args.push('-g', group);
  632. if (order)
  633. args.push('-o', order);
  634. return fs.exec_direct('/usr/libexec/nlbwmon-action', args, 'blob').then(function(blob) {
  635. var data = blob.slice(0, blob.size, (type == 'csv') ? 'text/csv' : 'application/json'),
  636. name = 'nlbwmon-data.%s'.format(type),
  637. url = window.URL.createObjectURL(data),
  638. link = E('a', { 'style': 'display:none', 'href': url, 'download': name });
  639. document.body.appendChild(link);
  640. link.click();
  641. document.body.removeChild(link);
  642. window.URL.revokeObjectURL(url);
  643. }).catch(function(err) {
  644. ui.addNotification(null, E('p', [ _('Failed to download traffic data: %s').format(err.message) ]));
  645. });
  646. },
  647. handleCommit: function() {
  648. return fs.exec('/usr/libexec/nlbwmon-action', [ 'commit' ]).then(function(res) {
  649. if (res.code != 0)
  650. throw new Error(res.stderr || res.stdout);
  651. window.location.reload(true);
  652. }).catch(function(err) {
  653. ui.addNotification(null, E('p', [ _('Failed to commit database: %s').format(err.message) ]));
  654. });
  655. },
  656. render: function() {
  657. document.addEventListener('tooltip-open', L.bind(function(ev) {
  658. this.renderHostDetail(ev.detail.target, ev.target);
  659. }, this));
  660. if ('ontouchstart' in window) {
  661. document.addEventListener('touchstart', function(ev) {
  662. var tooltip = document.querySelector('.cbi-tooltip');
  663. if (tooltip === ev.target || tooltip.contains(ev.target))
  664. return;
  665. ui.hideTooltip(ev);
  666. });
  667. }
  668. var node = E([], [
  669. E('link', { 'rel': 'stylesheet', 'href': L.resource('view/nlbw.css') }),
  670. E('script', {
  671. 'type': 'text/javascript',
  672. 'src': L.resource('nlbw.chart.min.js'),
  673. 'load': L.bind(this.setupCharts, this)
  674. }),
  675. E('h2', [ _('Netlink Bandwidth Monitor') ]),
  676. this.renderPeriods(),
  677. E('div', [
  678. E('div', { 'class': 'cbi-section', 'data-tab': 'traffic', 'data-tab-title': _('Traffic Distribution') }, [
  679. E('div', { 'class': 'head' }, [
  680. E('div', { 'class': 'pie' }, [
  681. E('label', [ _('Traffic / Host') ]),
  682. E('canvas', { 'id': 'traf-pie', 'width': 200, 'height': 200 })
  683. ]),
  684. E('div', { 'class': 'pie' }, [
  685. E('label', [ _('Connections / Host') ]),
  686. E('canvas', { 'id': 'conn-pie', 'width': 200, 'height': 200 })
  687. ]),
  688. E('div', { 'class': 'kpi' }, [
  689. E('ul', [
  690. E('li', _('<big id="host-total">0</big> hosts')),
  691. E('li', _('<big id="rx-total">0</big> download')),
  692. E('li', _('<big id="tx-total">0</big> upload')),
  693. E('li', _('<big id="conn-total">0</big> connections'))
  694. ])
  695. ])
  696. ]),
  697. E('table', { 'class': 'table', 'id': 'host-data' }, [
  698. E('tr', { 'class': 'tr table-titles' }, [
  699. E('th', { 'class': 'th left hostname' }, [ _('Host') ]),
  700. E('th', { 'class': 'th right' }, [ _('MAC') ]),
  701. E('th', { 'class': 'th right' }, [ _('Connections') ]),
  702. E('th', { 'class': 'th right' }, [ _('Download (Bytes)') ]),
  703. E('th', { 'class': 'th right' }, [ _('Download (Packets)') ]),
  704. E('th', { 'class': 'th right' }, [ _('Upload (Bytes)') ]),
  705. E('th', { 'class': 'th right' }, [ _('Upload (Packets)') ]),
  706. ]),
  707. E('tr', { 'class': 'tr placeholder' }, [
  708. E('td', { 'class': 'td' }, [
  709. E('em', { 'class': 'spinning' }, [ _('Collecting data...') ])
  710. ])
  711. ])
  712. ]),
  713. E('div', { 'class': 'right' }, [
  714. E('button', {
  715. 'class': 'cbi-button',
  716. 'click': ui.createHandlerFn(this, 'handleCommit')
  717. }, _('Force reload…')
  718. )
  719. ])
  720. ]),
  721. E('div', { 'class': 'cbi-section', 'data-tab': 'layer7', 'data-tab-title': _('Application Protocols') }, [
  722. E('div', { 'class': 'head' }, [
  723. E('div', { 'class': 'pie' }, [
  724. E('label', [ _('Download / Application') ]),
  725. E('canvas', { 'id': 'layer7-rx-pie', 'width': 200, 'height': 200 })
  726. ]),
  727. E('div', { 'class': 'pie' }, [
  728. E('label', [ _('Upload / Application') ]),
  729. E('canvas', { 'id': 'layer7-tx-pie', 'width': 200, 'height': 200 })
  730. ]),
  731. E('div', { 'class': 'kpi' }, [
  732. E('ul', [
  733. E('li', _('<big id="layer7-total">0</big> different application protocols')),
  734. E('li', _('<big id="layer7-most-rx">0</big> cause the most download')),
  735. E('li', _('<big id="layer7-most-tx">0</big> cause the most upload')),
  736. E('li', _('<big id="layer7-most-conn">0</big> cause the most connections'))
  737. ])
  738. ])
  739. ]),
  740. E('table', { 'class': 'table', 'id': 'layer7-data' }, [
  741. E('tr', { 'class': 'tr table-titles' }, [
  742. E('th', { 'class': 'th left' }, [ _('Application') ]),
  743. E('th', { 'class': 'th right' }, [ _('Connections') ]),
  744. E('th', { 'class': 'th right' }, [ _('Download (Bytes)') ]),
  745. E('th', { 'class': 'th right' }, [ _('Download (Packets)') ]),
  746. E('th', { 'class': 'th right' }, [ _('Upload (Bytes)') ]),
  747. E('th', { 'class': 'th right' }, [ _('Upload (Packets)') ]),
  748. ]),
  749. E('tr', { 'class': 'tr placeholder' }, [
  750. E('td', { 'class': 'td' }, [
  751. E('em', { 'class': 'spinning' }, [ _('Collecting data...') ])
  752. ])
  753. ])
  754. ]),
  755. E('div', { 'class': 'right' }, [
  756. E('button', {
  757. 'class': 'cbi-button',
  758. 'click': ui.createHandlerFn(this, 'handleCommit')
  759. }, _('Force reload…')
  760. )
  761. ])
  762. ]),
  763. E('div', { 'class': 'cbi-section', 'data-tab': 'ipv6', 'data-tab-title': _('IPv6') }, [
  764. E('div', { 'class': 'head' }, [
  765. E('div', { 'class': 'pie' }, [
  766. E('label', [ _('IPv4 vs. IPv6') ]),
  767. E('canvas', { 'id': 'ipv6-share-pie', 'width': 200, 'height': 200 })
  768. ]),
  769. E('div', { 'class': 'pie' }, [
  770. E('label', [ _('Dualstack enabled hosts') ]),
  771. E('canvas', { 'id': 'ipv6-hosts-pie', 'width': 200, 'height': 200 })
  772. ]),
  773. E('div', { 'class': 'kpi' }, [
  774. E('ul', [
  775. E('li', _('<big id="ipv6-hosts">0%</big> IPv6 support rate among hosts')),
  776. E('li', _('<big id="ipv6-share">0%</big> of the total traffic is IPv6')),
  777. E('li', _('<big id="ipv6-rx">0B</big> total IPv6 download')),
  778. E('li', _('<big id="ipv6-tx">0B</big> total IPv6 upload'))
  779. ])
  780. ])
  781. ]),
  782. E('table', { 'class': 'table', 'id': 'ipv6-data' }, [
  783. E('tr', { 'class': 'tr table-titles' }, [
  784. E('th', { 'class': 'th left' }, [ _('Host') ]),
  785. E('th', { 'class': 'th right' }, [ _('MAC') ]),
  786. E('th', { 'class': 'th double right hide-xs' }, [ _('Family') ]),
  787. E('th', { 'class': 'th double right' }, [ _('Download (Bytes)') ]),
  788. E('th', { 'class': 'th double right' }, [ _('Download (Packets)') ]),
  789. E('th', { 'class': 'th double right' }, [ _('Upload (Bytes)') ]),
  790. E('th', { 'class': 'th double right' }, [ _('Upload (Packets)') ]),
  791. ]),
  792. E('tr', { 'class': 'tr placeholder' }, [
  793. E('td', { 'class': 'td' }, [
  794. E('em', { 'class': 'spinning' }, [ _('Collecting data...') ])
  795. ])
  796. ])
  797. ]),
  798. E('div', { 'class': 'right' }, [
  799. E('button', {
  800. 'class': 'cbi-button',
  801. 'click': ui.createHandlerFn(this, 'handleCommit')
  802. }, _('Force reload…')
  803. )
  804. ])
  805. ]),
  806. E('div', { 'class': 'cbi-section', 'data-tab': 'export', 'data-tab-title': _('Export') }, [
  807. E('div', { 'class': 'cbi-section-node cbi-sction-node-tabbed' }, [
  808. E('div', { 'class': 'cbi-value' }, [
  809. E('label', { 'class': 'cbi-value-title' }, _('Grouped by MAC (CSV)')),
  810. E('div', { 'class': 'cbi-value-field' }, [
  811. E('button', {
  812. 'class': 'cbi-button',
  813. 'click': ui.createHandlerFn(this, 'handleDownload', 'csv', 'mac', '-rx,-tx')
  814. }, [ _('Export') ])
  815. ])
  816. ]),
  817. E('div', { 'class': 'cbi-value' }, [
  818. E('label', { 'class': 'cbi-value-title' }, _('Grouped by IP (CSV)')),
  819. E('div', { 'class': 'cbi-value-field' }, [
  820. E('button', {
  821. 'class': 'cbi-button',
  822. 'click': ui.createHandlerFn(this, 'handleDownload', 'csv', 'ip', '-rx,-tx')
  823. }, [ _('Export') ])
  824. ])
  825. ]),
  826. E('div', { 'class': 'cbi-value' }, [
  827. E('label', { 'class': 'cbi-value-title' }, _('Grouped by protocol (CSV)')),
  828. E('div', { 'class': 'cbi-value-field' }, [
  829. E('button', {
  830. 'class': 'cbi-button',
  831. 'click': ui.createHandlerFn(this, 'handleDownload', 'csv', 'layer7', '-rx,-tx')
  832. }, [ _('Export') ])
  833. ])
  834. ]),
  835. E('div', { 'class': 'cbi-value' }, [
  836. E('label', { 'class': 'cbi-value-title' }, _('Dump (JSON)')),
  837. E('div', { 'class': 'cbi-value-field' }, [
  838. E('button', {
  839. 'class': 'cbi-button',
  840. 'click': ui.createHandlerFn(this, 'handleDownload', 'json', null, null)
  841. }, [ _('Export') ])
  842. ])
  843. ])
  844. ])
  845. ])
  846. ])
  847. ]);
  848. ui.tabs.initTabGroup(node.lastElementChild.childNodes);
  849. return node;
  850. },
  851. handleSave: null,
  852. handleSaveApply: null,
  853. handleReset: null
  854. });