🔥 Sync 2026-11-16 16:50:07

This commit is contained in:
github-actions[bot] committed 2026-11-16 16:50:08 +08:00
1 parent 6b8b3fec62
commit a2bf4e439b
87 files changed
+2498 -180

No files matched your search

+6 -1
View File
@@ -3,6 +3,7 @@
| Suite | Command | Needs |
|---|---|---|
| Unit: formatting, i18n, devices, ARP, IPv6, brands (`carbon.test.js`) | `npm test` | Node 18+ |
| Unit: per-device counter deltas, resets, sampling intervals and read-only collector permissions (`traffic-provider.test.js`) | `npm test` | Node 18+ |
| Unit: LuCI glue — poll pause, language list/switch, menu cache | `npm test` | Node 18+ |
| Unit: release-notes Markdown | `npm test` | Node 18+ |
| Unit: settings backend — logo upload validation (types, size, unsafe SVG) (`settings-backend.test.js`; `CARBON_TEST_SH=/bin/dash` for a strict shell) | `npm test` | Node 18+, `sh` |
@@ -13,10 +14,12 @@
| Theme templates rendered by OpenWrt's ucode | see below | Docker |
| Updater (APK and IPK) | see [online-update.md](../docs/online-update.md#maintainers) | Docker |
The browser suite also checks every bundled catalogue in the sidebar, the custom-logo hero, the settings page layout (`tests/fixtures/settings.html`), the language listbox, and the plugin adapters (DiskMan partition bar) against copied plugin markup. It serves the repository and a minified copy locally, runs `tests/navigation.html` at 390 × 844, loads the preview in Chinese/English × light/dark × desktop/phone (screenshots go to `.cache/screenshots/`), checks the dashboard data, the language switch, keyboard/touch behaviour of the rail and drawer, and compares computed styles of the minified release build with the sources.
The browser suite also checks every bundled catalogue in the sidebar, the custom-logo hero, the settings page layout (`tests/fixtures/settings.html`), the language listbox, and the plugin adapters (DiskMan partition bar) against copied plugin markup. Table dropdown regressions use LuCI's open/closed DOM states to check that options beyond the last row receive pointer events, including plugin cells without `.cbi-value-field`, on desktop/phone and in light/dark mode against source/minified CSS. It serves the repository and a minified copy locally, runs `tests/navigation.html` at 390 × 844, loads the preview in Chinese/English × light/dark × desktop/phone (screenshots go to `.cache/screenshots/`), checks the dashboard data, the language switch, keyboard/touch behaviour of the rail and drawer, and compares computed styles of the minified release build with the sources.
Device regressions cover DHCP-disabled side routers with static or DHCP-client LAN, failed DHCP RPC calls, retained leases, gateway labels, and separate static WAN neighbours. These use the production dashboard with simulated provider responses. `CARBON_TEST_BROWSER` can point to an installed Chromium executable instead of Playwright's bundled browser. On a real router, also verify ARP reads after logging out and back in following an upgrade; an older session may lack the dashboard permissions. An IPv6-only device without a lease or local Wi-Fi association is not discoverable: this provider reads IPv4 ARP, while IPv6 addresses come from leases and host hints.
Realtime graph regressions (`node --test tests/browser/realtime.test.js`) execute pinned OpenWrt 24.10 load, bandwidth and connection plotting code with simulated RPC replies. They verify sidebar collapse/expansion, desktop/mobile resizing, continued polling, retained samples, unscaled text, hidden interface charts and the fallback without `ResizeObserver`, against source and minified theme scripts. Modern SVGs with their own `viewBox` and charts outside realtime pages are left alone. On a router, open Status → Realtime Graphs, wait for samples, collapse/expand the sidebar and resize the window; curves and time markers should fill the plot without refreshing the page.
Render the templates with the real ucode runtime:
```bash
@@ -33,6 +36,8 @@ Also verify in a disposable LuCI environment: open a multi-page app with an acti
For signed APK and native IPK updater integration tests, see [online-update.md](../docs/online-update.md#maintainers).
Device-speed browser coverage checks upload/download values, missing records, untouched DHCP lease labels, unsupported collectors, hidden-tab suspension/resume, error backoff and mobile overflow. Real-device checks should compare network/DHCP/firewall/nlbwmon configuration before and after installing the theme, and keep the collector's existing interval and running state. An inactive or absent collector is expected to leave the speed display hidden; do not enable it as part of a theme test.
## Release notes
Run `node --test tests/markdown.test.js` to check the built-in Markdown renderer (`htdocs/luci-static/resources/carbon/markdown.js`): release-note structures, unsafe HTML/URLs, pathological input and unchanged-content polling. In LuCI, check for updates and confirm the notes render as headings, lists, links, tables and code, in both appearance modes and at 390px width. Long code/table content must scroll inside the notes; status polling must retain the reading position and text selection.
@@ -134,6 +134,79 @@ test('side-router discovery works without DHCP and distinguishes neighbours, gat
}
});
test('device speeds preserve leases, handle missing data and pause when hidden', async () => {
const mock = fs.readFileSync(path.join(ROOT, 'preview', 'mock.js'), 'utf8');
const context = await browser.newContext({ viewport: { width: 390, height: 844 } });
const page = await context.newPage();
try {
await page.route('**/preview/mock.js', (route) => route.fulfill({ contentType: 'text/javascript', body: mock + '\n(' + (() => {
window.trafficReads = 0;
window.trafficFail = false;
window.CarbonPreview.provider.deviceTraffic = async () => {
window.trafficReads++;
if (window.trafficFail) throw new Error('collector unavailable');
return { interval: 5, columns: ['mac', 'rx_bytes', 'tx_bytes'], data: [
['A6:83:E7:2C:91:0F', window.trafficReads * 10240, window.trafficReads * 5120],
['00:11:22:33:44:99', 99999999, 99999999]
] };
};
}).toString() + ')();' }));
await page.clock.install();
await page.goto(base + '/src/preview/index.html?lang=en');
await dashboardReady(page);
const phone = page.locator('.cb-clients li').filter({ hasText: 'iPhone-15-Pro' });
const laptop = page.locator('.cb-clients li').filter({ hasText: 'MacBook-Air' });
assert.match(await phone.textContent(), /DHCP lease · 10h 33m left/);
assert.equal(await phone.locator('.cb-device-rates').textContent(), '↓ —↑ —');
const count = await page.textContent('.cb-count');
await page.clock.runFor(5100);
assert.match(await phone.locator('.cb-device-rates').textContent(), /↓ [\d.]+ KB\/s↑ [\d.]+ [KB]+\/s/);
assert.equal(await laptop.locator('.cb-device-rates').textContent(), '↓ —↑ —');
assert.equal(await page.textContent('.cb-count'), count, 'historical traffic cannot create devices');
assert.match(await phone.textContent(), /DHCP lease · 10h 33m left/);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true);
await page.screenshot({ path: path.join(SHOTS, 'device-speeds-phone.png'), fullPage: true });
await page.evaluate(() => {
Object.defineProperty(document, 'hidden', { configurable: true, value: true });
document.dispatchEvent(new Event('visibilitychange'));
});
const reads = await page.evaluate(() => window.trafficReads);
await page.clock.runFor(20000);
assert.equal(await page.evaluate(() => window.trafficReads), reads);
await page.evaluate(() => {
Object.defineProperty(document, 'hidden', { configurable: true, value: false });
document.dispatchEvent(new Event('visibilitychange'));
});
await page.clock.runFor(5000);
assert.equal(await phone.locator('.cb-device-rates').textContent(), '↓ —↑ —', 'resume establishes a fresh baseline');
await page.clock.runFor(5000);
assert.match(await phone.locator('.cb-device-rates').textContent(), /KB\/s/);
await page.evaluate(() => { window.trafficFail = true; });
await page.clock.runFor(5000);
assert.equal(await phone.locator('.cb-device-rates').textContent(), '↓ —↑ —');
assert.match(await page.textContent('.cb-device-rate-note'), /Unavailable/);
const failedReads = await page.evaluate(() => window.trafficReads);
await page.clock.runFor(55000);
assert.equal(await page.evaluate(() => window.trafficReads), failedReads, 'failed sources back off for a minute');
assert.match(await phone.textContent(), /DHCP lease/);
} finally { await context.close(); }
});
test('firmware without a traffic collector keeps the device list without misleading zero speeds', async () => {
const mock = fs.readFileSync(path.join(ROOT, 'preview', 'mock.js'), 'utf8');
const context = await browser.newContext();
const page = await context.newPage();
try {
await page.route('**/preview/mock.js', (route) => route.fulfill({ contentType: 'text/javascript',
body: mock + '\nwindow.CarbonPreview.provider.deviceTraffic = async () => { throw new Error("unsupported"); };' }));
await page.goto(base + '/src/preview/index.html?lang=en');
await dashboardReady(page);
assert.equal(await page.locator('.cb-device-rate-note').isVisible(), false);
assert.equal(await page.locator('.cb-device-rates:visible').count(), 0);
assert.match(await page.textContent('.cb-clients'), /DHCP lease/);
} finally { await context.close(); }
});
test('navigation regression page passes at phone width', async () => {
const { page, context } = await open('/src/tests/navigation.html', { width: 390, height: 844 });
await page.waitForFunction(() => /^(PASS|FAIL)/.test(document.title));
@@ -306,6 +379,84 @@ test('DiskMan partition bar stays inside its card on desktop and phone', async (
}
});
/* Styling fixture for LuCI ui.Dropdown's closed/open DOM states. The menu
stays inside its table cell, including plugins without .cbi-value-field. */
function tableDropdownFixture(mount, tag, field, appearance) {
const row = tag === 'table' ? 'tr' : 'div';
const cell = tag === 'table' ? 'td' : 'div';
return `<!doctype html><html data-darkmode="${appearance === 'dark'}"><head><meta charset="utf-8">
<link rel="stylesheet" href="/${mount}/htdocs/luci-static/carbon/carbon.css">
</head><body data-page="admin-system-diskman-disks"><main id="maincontent" style="padding:24px">
<div class="cbi-section"><${tag} class="table cbi-section-table">
<${row} class="tr"><${cell} class="td">/dev/nvme0n1p1 · /boot</${cell}></${row}>
<${row} class="tr"><${cell} class="td${field ? ' cbi-value-field' : ''}">
<div id="mount-device" class="cbi-dropdown" tabindex="0"><ul>
<li selected="" placeholder="" display="0" data-value="">-- Please choose --</li>
<li data-value="/dev/sda1">/dev/sda1</li><li data-value="/dev/sdb1">/dev/sdb1</li>
</ul><span class="open">▾</span></div>
</${cell}></${row}></${tag}></div>
<div class="cbi-section"><h3>Create</h3><div class="cbi-section-node">RAID</div></div>
</main></body></html>`;
}
test('table dropdown options escape the last row and remain clickable', async () => {
for (const mount of ['src', 'min']) {
for (const width of [1280, 390]) {
for (const appearance of ['light', 'dark']) {
for (const [tag, field] of [['table', false], ['div', true]]) {
const label = `${mount} ${width}px ${appearance} ${tag}`;
const { page, context } = await open('/src/preview/index.html', { width, height: 800, appearance });
try {
await page.setContent(tableDropdownFixture(mount, tag, field, appearance), { waitUntil: 'load' });
const closed = await page.locator('.table').boundingBox();
await page.locator('#mount-device').evaluate((sb) => {
const ul = sb.querySelector('ul');
const preview = ul.cloneNode(true);
preview.className = 'preview';
const height = sb.offsetHeight;
// These are the DOM changes made by LuCI's openDropdown().
sb.setAttribute('open', '');
sb.closest('.cbi-value-field')?.classList.add('cbi-dropdown-open');
ul.className = 'dropdown';
ul.style.top = height + 'px';
ul.style.maxHeight = '300px';
sb.insertBefore(preview, ul);
ul.addEventListener('click', (event) => { sb.dataset.clicked = event.target.dataset.value; });
});
const options = await page.locator('ul.dropdown > li[data-value]:not([placeholder])').evaluateAll((items) => items.map((el) => {
const rect = el.getBoundingClientRect();
return {
value: el.dataset.value,
belowTable: rect.top > el.closest('.table').getBoundingClientRect().bottom,
clickable: el.contains(document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2))
};
}));
assert.equal(options.length, 2, label);
for (const option of options) {
assert.ok(option.belowTable, `${label}: ${option.value} exercises overflow beyond the table`);
assert.ok(option.clickable, `${label}: ${option.value} must be visible and receive pointer events`);
}
await page.locator('ul.dropdown > li[data-value="/dev/sdb1"]').click({ timeout: 2000 });
assert.equal(await page.locator('#mount-device').getAttribute('data-clicked'), '/dev/sdb1', label);
if (mount === 'src' && tag === 'table')
await page.screenshot({ path: path.join(SHOTS, `diskman-dropdown-${appearance}-${width}.png`) });
await page.locator('#mount-device').evaluate((sb) => {
sb.querySelector('.preview').remove();
sb.removeAttribute('open');
sb.closest('.cbi-value-field')?.classList.remove('cbi-dropdown-open');
const ul = sb.querySelector('ul');
ul.className = '';
ul.removeAttribute('style');
});
assert.deepEqual(await page.locator('.table').boundingBox(), closed, `${label}: closing preserves the table layout`);
assert.equal(await page.locator('.table').evaluate((el) => getComputedStyle(el).overflow), width > 760 ? 'hidden' : 'visible', `${label}: closed table keeps its original clipping`);
} finally { await context.close(); }
}
}
}
}
});
test('settings page: buttons, links, fields and status text share one centre line', async () => {
for (const width of [1200, 390]) {
const { page, context, errors } = await open('/src/tests/fixtures/settings.html', { width });
@@ -0,0 +1,212 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const http = require('node:http');
const { chromium } = require('playwright');
const { transform } = require('esbuild');
const ROOT = path.resolve(__dirname, '../..');
const SHOTS = path.join(ROOT, '.cache/screenshots');
const fixture = (name) => fs.readFileSync(path.join(ROOT, 'tests/fixtures/luci-realtime', name), 'utf8');
let server, base, browser;
test.before(async () => {
fs.mkdirSync(SHOTS, { recursive: true });
const source = fs.readFileSync(path.join(ROOT, 'htdocs/luci-static/carbon/carbon.js'), 'utf8');
const css = fs.readFileSync(path.join(ROOT, 'htdocs/luci-static/carbon/carbon.css'), 'utf8');
const minified = (await transform(source, { minify: true, loader: 'js' })).code;
server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
if (url.pathname.endsWith('.js')) {
res.setHeader('content-type', 'text/javascript');
res.end(url.pathname === '/min.js' ? minified : source);
}
else {
res.setHeader('content-type', 'text/html');
res.end(`<!doctype html><html lang="en"><head><style>${css}</style>
<script src="/${url.searchParams.has('min') ? 'min' : 'source'}.js"></script></head>
<body data-page="${url.searchParams.has('outside') ? 'admin-status-overview' : 'admin-status-realtime-load'}"><div class="cb-app">
<aside class="cb-sidebar"><button id="cb-collapse"></button></aside>
<main class="cb-main"><div id="maincontent" class="cb-content"><div id="view"></div></div></main>
</div><script>Carbon.initShell();</script></body></html>`);
}
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
base = 'http://127.0.0.1:' + server.address().port;
browser = await chromium.launch({ executablePath: process.env.CARBON_TEST_BROWSER || undefined });
});
test.after(async () => {
if (browser) await browser.close();
if (server) await new Promise((resolve) => server.close(resolve));
});
async function mount(page, kind, count = 1) {
await page.evaluate(({ source, svg, kind, count }) => {
const ticks = [];
let timestamp = 1000;
window.rpcCalls = 0;
const rpc = { declare: (spec) => () => {
if (spec.method !== 'getRealtimeStats') return Promise.resolve([]);
window.rpcCalls++;
const start = timestamp;
timestamp += 60;
return Promise.resolve(Array.from({ length: 60 }, (_, i) =>
[start + i, 10000 + i * 100, 20000 + i * 80, 30 + i % 5]));
} };
const L = { bind: (fn, ctx) => fn.bind(ctx), resolveDefault: (p, value) => Promise.resolve(p).catch(() => value) };
const view = new Function('view', 'poll', 'request', 'rpc', 'L', source)(
{ extend: (v) => v }, { add: (fn) => ticks.push(fn) }, {}, rpc, L);
// The connection table is independent of the SVG plot under test.
view.updateConntrack = () => {};
const ids = { load: ['load01', 'load05', 'load15'], bandwidth: ['rx', 'tx'], connections: ['tcp', 'udp', 'other'] }[kind];
window.graphs = [];
for (let i = 0; i < count; i++) {
const container = document.createElement('div');
container.style.cssText = 'width:100%;height:300px;border:1px solid #000;background:#fff';
container.innerHTML = svg.slice(svg.indexOf('<svg'));
document.querySelector('#view').appendChild(container);
const lines = ids.map((line) => ({ line, counter: kind === 'bandwidth' }));
if (kind === 'bandwidth') view.updateGraph('eth' + i, container, lines);
else view.updateGraph(container, lines);
graphs.push(container);
}
view.pollData();
window.tick = () => Promise.all(ticks.map((fn) => fn()));
}, { source: fixture(kind + '.js'), svg: fixture(kind + '.svg'), kind, count });
await page.evaluate(() => tick());
}
async function settle(page) {
await page.waitForFunction(() => !document.querySelector('.cb-main').getAnimations().length);
await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))));
}
async function geometry(page, index = 0) {
return page.evaluate((index) => {
const svg = graphs[index].firstElementChild;
const edge = svg.getBoundingClientRect().right;
const lines = [...svg.querySelectorAll('polyline')];
const end = (line) => {
const p = line.points.getItem(line.points.numberOfItems - 1);
return new DOMPoint(p.x, p.y).matrixTransform(line.getScreenCTM()).x;
};
return {
gaps: lines.map((line) => edge - end(line)),
points: lines.map((line) => line.getAttribute('points')),
labels: [...svg.querySelectorAll('text')].map((el) => {
const m = el.getScreenCTM();
return { scaleX: m.a, scaleY: m.d };
}),
grid: [...svg.querySelectorAll('line')].filter((el) => el.getAttribute('x1') === el.getAttribute('x2')).map((el) => {
const p = new DOMPoint(el.x1.baseVal.value, 0).matrixTransform(el.getScreenCTM());
return (edge - p.x) / svg.clientWidth;
})
};
}, index);
}
function fillsPlot(result) {
for (const gap of result.gaps) assert(Math.abs(gap) < 1, 'curve must reach the right edge; gap=' + gap);
for (const label of result.labels) assert.deepEqual(label, { scaleX: 1, scaleY: 1 }, 'labels must not stretch');
}
for (const kind of ['load', 'bandwidth', 'connections']) {
for (const min of [false, true]) {
test(`${kind} fills the plot after sidebar and viewport changes (${min ? 'minified' : 'source'})`, async () => {
const page = await browser.newPage({ viewport: { width: 1280, height: 850 } });
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
try {
await page.goto(base + (min ? '/?min' : '/'));
await mount(page, kind);
await settle(page);
const initial = await geometry(page);
fillsPlot(initial);
const calls = await page.evaluate(() => rpcCalls);
await page.locator('#cb-collapse').click();
await settle(page);
const collapsed = await geometry(page);
fillsPlot(collapsed);
if (kind === 'load' && !min) await page.screenshot({ path: path.join(SHOTS, 'realtime-load-collapsed.png') });
assert.deepEqual(collapsed.points, initial.points, 'resizing preserves samples');
initial.grid.forEach((v, i) => assert(Math.abs(v - collapsed.grid[i]) < 0.001, 'time grid stays aligned'));
assert.equal(await page.evaluate(() => rpcCalls), calls, 'resizing does not fetch new data');
await page.evaluate(() => tick());
await settle(page);
fillsPlot(await geometry(page));
assert.notDeepEqual((await geometry(page)).points, initial.points, 'native polling still updates samples');
await page.locator('#cb-collapse').click();
await settle(page);
fillsPlot(await geometry(page));
for (const width of [1600, 1100, 390, 1280]) {
await page.setViewportSize({ width, height: 850 });
await settle(page);
fillsPlot(await geometry(page));
if (kind === 'load' && !min && width === 390) await page.screenshot({ path: path.join(SHOTS, 'realtime-load-mobile.png') });
}
assert.deepEqual(errors, []);
}
finally { await page.close(); }
});
}
}
test('hidden interface charts resize when revealed; unrelated SVGs are untouched', async () => {
const page = await browser.newPage({ viewport: { width: 1280, height: 850 } });
try {
await page.goto(base);
await mount(page, 'bandwidth', 2);
await page.evaluate(() => {
graphs[1].hidden = true;
document.querySelector('#view').insertAdjacentHTML('beforeend', '<svg id="unrelated" viewBox="0 0 100 100"><polyline points="0,100 100,0 100,100"/></svg>');
const modern = graphs[0].firstElementChild.cloneNode(true);
modern.id = 'modern';
modern.setAttribute('viewBox', '0 0 934 298');
modern.querySelectorAll('[transform]').forEach((el) => el.removeAttribute('transform'));
document.querySelector('#view').appendChild(modern);
});
await page.locator('#cb-collapse').click();
await settle(page);
await page.evaluate(() => { graphs[1].hidden = false; });
await settle(page);
fillsPlot(await geometry(page, 1));
assert.equal(await page.locator('#unrelated polyline').getAttribute('transform'), null);
assert.equal(await page.locator('#modern polyline').first().getAttribute('transform'), null);
}
finally { await page.close(); }
});
test('legacy resize fallback handles sidebar changes with and without motion', async () => {
const page = await browser.newPage({ viewport: { width: 1280, height: 850 } });
try {
await page.addInitScript(() => { window.ResizeObserver = undefined; });
await page.goto(base);
await mount(page, 'load');
for (const reducedMotion of ['no-preference', 'reduce']) {
await page.emulateMedia({ reducedMotion });
await page.locator('#cb-collapse').click();
await settle(page);
fillsPlot(await geometry(page));
}
await page.setViewportSize({ width: 1600, height: 850 });
await settle(page);
fillsPlot(await geometry(page));
}
finally { await page.close(); }
});
test('the adapter does not modify matching SVGs outside realtime pages', async () => {
const page = await browser.newPage();
try {
await page.goto(base + '/?outside');
await mount(page, 'load');
await page.locator('#cb-collapse').click();
await settle(page);
assert.equal(await page.locator('#load01').getAttribute('transform'), null);
}
finally { await page.close(); }
});
+33
View File
@@ -81,6 +81,39 @@ test('byte formatting', () => {
assert.deepEqual(Array.from(C.fmt.bytes(null)), ['—', '']);
});
test('device speeds use per-MAC counter deltas with correct directions and actual elapsed time', () => {
const tracker = new (load().DeviceRates)();
const sample = (data) => ({ interval: 30, columns: ['tx_bytes', 'mac', 'rx_bytes'], data });
assert.equal(tracker.update(sample([[100, 'AA:11:22:33:44:55', 200]]), 1000).rates.size, 0);
const r = tracker.update(sample([[400, 'aa:11:22:33:44:55', 1700], [50, '00:11:22:33:44:66', 100]]), 31000);
assert.deepEqual(JSON.parse(JSON.stringify(r.rates.get('aa:11:22:33:44:55'))), { down: 50, up: 10 });
assert.equal(r.rates.has('00:11:22:33:44:66'), false, 'new records need a baseline');
assert.equal(tracker.update(sample([[400, 'aa:11:22:33:44:55', 1700]]), 61000).rates.get('aa:11:22:33:44:55').down, 0);
});
test('counter reset, missing device, failed read, suspend and changed interval do not show false device speeds', () => {
const tracker = new (load().DeviceRates)();
const sample = (n, interval = 30) => ({ interval, columns: ['mac', 'rx_bytes', 'tx_bytes'], data: [['00:11:22:33:44:55', n, n]] });
tracker.update(sample(1000), 0);
assert.equal(tracker.update(sample(10), 30000).rates.size, 0, 'reset');
assert.equal(tracker.update({ ...sample(20), data: [] }, 60000).rates.size, 0, 'missing');
assert.equal(tracker.update(sample(30), 90000).rates.size, 0, 'reappearing');
assert.equal(tracker.update(null, 120000), null);
assert.equal(tracker.update(sample(100), 150000).rates.size, 0, 'first read after error');
assert.equal(tracker.update(sample(1000), 400000).rates.size, 0, 'suspend');
assert.equal(tracker.update(sample(1100, 60), 460000).rates.size, 0, 'cadence changed');
assert.equal(tracker.update(sample(NaN), 520000), null);
assert.equal(tracker.update(sample(Number.MAX_SAFE_INTEGER + 1), 550000), null);
});
test('early reads do not move the device-speed baseline or invent short-window spikes', () => {
const tracker = new (load().DeviceRates)();
const sample = (n) => ({ interval: 30, columns: ['mac', 'rx_bytes', 'tx_bytes'], data: [['00:11:22:33:44:55', n, n]] });
tracker.update(sample(0), 0);
assert.equal(tracker.update(sample(100), 5000).rates.size, 0);
assert.equal(tracker.update(sample(300), 30000).rates.get('00:11:22:33:44:55').down, 10);
});
test('language matching maps LuCI codes to the installed catalogue', () => {
const C = load();
const options = [{ code: 'en' }, { code: 'zh_cn' }, { code: 'zh_tw' }, { code: 'pt_br' }];
@@ -0,0 +1,15 @@
# LuCI realtime graph fixtures
Files copied from OpenWrt LuCI's `openwrt-24.10` branch at
[`aa4865e8e6472d6ba68e541688065fc2235bbd83`](https://github.com/openwrt/luci/tree/aa4865e8e6472d6ba68e541688065fc2235bbd83/modules/luci-mod-status/htdocs/luci-static/resources):
- `view/status/{load,bandwidth,connections}.js`
- `svg/{load,bandwidth,connections}.svg`
Only trailing whitespace has been removed; the upstream code is otherwise unchanged.
The browser regression executes the original `updateGraph()` and `pollData()`
methods with simulated RPC replies. Only the unrelated connection table update
is stubbed. This retains the fixed-width drawing behavior behind issue #8,
including subsequent polls overwriting the SVG points. These fixtures are test
inputs only and are never installed on the router.
@@ -0,0 +1,322 @@
'use strict';
'require view';
'require dom';
'require poll';
'require request';
'require ui';
'require rpc';
'require network';
var callLuciRealtimeStats = rpc.declare({
object: 'luci',
method: 'getRealtimeStats',
params: [ 'mode', 'device' ],
expect: { result: [] }
});
var graphPolls = [],
pollInterval = 3;
Math.log2 = Math.log2 || function(x) { return Math.log(x) * Math.LOG2E; };
function rate(n, br) {
n = (n || 0).toFixed(2);
return [ '%1024.2mbit/s'.format(n * 8), br ? E('br') : ' ', '(%1024.2mB/s)'.format(n) ]
}
return view.extend({
load: function() {
return Promise.all([
this.loadSVG(L.resource('svg/bandwidth.svg')),
network.getDevices()
]);
},
updateGraph: function(ifname, svg, lines, cb) {
var G = svg.firstElementChild;
var view = document.querySelector('#view');
var width = view.offsetWidth - 2;
var height = 300 - 2;
var step = 5;
var data_wanted = Math.floor(width / step);
var data_values = [],
line_elements = [];
for (var i = 0; i < lines.length; i++)
if (lines[i] != null)
data_values.push([]);
var info = {
line_current: [],
line_average: [],
line_peak: []
};
/* prefill datasets */
for (var i = 0; i < data_values.length; i++)
for (var j = 0; j < data_wanted; j++)
data_values[i][j] = 0;
/* plot horizontal time interval lines */
for (var i = width % (step * 60); i < width; i += step * 60) {
var line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', i);
line.setAttribute('y1', 0);
line.setAttribute('x2', i);
line.setAttribute('y2', '100%');
line.setAttribute('style', 'stroke:black;stroke-width:0.1');
var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.setAttribute('x', i + 5);
text.setAttribute('y', 15);
text.setAttribute('style', 'fill:#eee; font-size:9pt; font-family:sans-serif; text-shadow:1px 1px 1px #000');
text.appendChild(document.createTextNode(Math.round((width - i) / step / 60) + 'm'));
G.appendChild(line);
G.appendChild(text);
}
info.interval = pollInterval;
info.timeframe = data_wanted / 60;
graphPolls.push({
ifname: ifname,
svg: svg,
lines: lines,
cb: cb,
info: info,
width: width,
height: height,
step: step,
values: data_values,
timestamp: 0,
fill: 1
});
},
pollData: function() {
poll.add(L.bind(function() {
var tasks = [];
for (var i = 0; i < graphPolls.length; i++) {
var ctx = graphPolls[i];
tasks.push(L.resolveDefault(callLuciRealtimeStats('interface', ctx.ifname), []));
}
return Promise.all(tasks).then(L.bind(function(datasets) {
for (var gi = 0; gi < graphPolls.length; gi++) {
var ctx = graphPolls[gi],
data = datasets[gi],
values = ctx.values,
lines = ctx.lines,
info = ctx.info;
var data_scale = 0;
var data_wanted = Math.floor(ctx.width / ctx.step);
var last_timestamp = NaN;
for (var i = 0, di = 0; di < lines.length; di++) {
if (lines[di] == null)
continue;
var multiply = (lines[di].multiply != null) ? lines[di].multiply : 1,
offset = (lines[di].offset != null) ? lines[di].offset : 0;
for (var j = ctx.timestamp ? 0 : 1; j < data.length; j++) {
/* skip overlapping entries */
if (data[j][0] <= ctx.timestamp)
continue;
if (i == 0) {
ctx.fill++;
last_timestamp = data[j][0];
}
if (lines[di].counter) {
/* normalize difference against time interval */
if (j > 0) {
var time_delta = data[j][0] - data[j - 1][0];
if (time_delta) {
info.line_current[i] = (data[j][di + 1] * multiply - data[j - 1][di + 1] * multiply) / time_delta;
info.line_current[i] -= Math.min(info.line_current[i], offset);
values[i].push(info.line_current[i]);
}
}
}
else {
info.line_current[i] = data[j][di + 1] * multiply;
info.line_current[i] -= Math.min(info.line_current[i], offset);
values[i].push(info.line_current[i]);
}
}
i++;
}
/* cut off outdated entries */
ctx.fill = Math.min(ctx.fill, data_wanted);
for (var i = 0; i < values.length; i++) {
var len = values[i].length;
values[i] = values[i].slice(len - data_wanted, len);
/* find peaks, averages */
info.line_peak[i] = NaN;
info.line_average[i] = 0;
for (var j = 0; j < values[i].length; j++) {
info.line_peak[i] = isNaN(info.line_peak[i]) ? values[i][j] : Math.max(info.line_peak[i], values[i][j]);
info.line_average[i] += values[i][j];
}
info.line_average[i] = info.line_average[i] / ctx.fill;
}
info.peak = Math.max.apply(Math, info.line_peak);
/* remember current timestamp, calculate horizontal scale */
if (!isNaN(last_timestamp))
ctx.timestamp = last_timestamp;
var size = Math.floor(Math.log2(info.peak)),
div = Math.pow(2, size - (size % 10)),
mult = info.peak / div,
mult = (mult < 5) ? 2 : ((mult < 50) ? 10 : ((mult < 500) ? 100 : 1000));
info.peak = info.peak + (mult * div) - (info.peak % (mult * div));
data_scale = ctx.height / info.peak;
/* plot data */
for (var i = 0, di = 0; di < lines.length; di++) {
if (lines[di] == null)
continue;
var el = ctx.svg.firstElementChild.getElementById(lines[di].line),
pt = '0,' + ctx.height,
y = 0;
if (!el)
continue;
for (var j = 0; j < values[i].length; j++) {
var x = j * ctx.step;
y = ctx.height - Math.floor(values[i][j] * data_scale);
//y -= Math.floor(y % (1 / data_scale));
y = isNaN(y) ? ctx.height : y;
pt += ' ' + x + ',' + y;
}
pt += ' ' + ctx.width + ',' + y + ' ' + ctx.width + ',' + ctx.height;
el.setAttribute('points', pt);
i++;
}
info.label_25 = 0.25 * info.peak;
info.label_50 = 0.50 * info.peak;
info.label_75 = 0.75 * info.peak;
if (typeof(ctx.cb) == 'function')
ctx.cb(ctx.svg, info);
}
}, this));
}, this), pollInterval);
},
loadSVG: function(src) {
return request.get(src).then(function(response) {
if (!response.ok)
throw new Error(response.statusText);
return E('div', {
'style': 'width:100%;height:300px;border:1px solid #000;background:#fff'
}, E(response.text()));
});
},
render: function([svg, devs]) {
var v = E('div', { 'class': 'cbi-map', 'id': 'map' }, E('div'));
for (var i = 0; i < devs.length; i++) {
var ifname = devs[i].getName();
const ssid = devs[i].wif?.getSSID?.() || null;
if (!ifname || !devs[i].isUp() || devs[i].wif?.isDisabled())
continue;
var csvg = svg.cloneNode(true);
v.firstElementChild.appendChild(E('div', { 'class': 'cbi-section', 'data-tab': ifname, 'data-tab-title': ssid ? `${ifname} ${ssid}` : ifname }, [
csvg,
E('div', { 'class': 'right' }, E('small', { 'id': 'scale' }, '-')),
E('br'),
E('table', { 'class': 'table', 'style': 'width:100%;table-layout:fixed' }, [
E('tr', { 'class': 'tr' }, [
E('td', { 'class': 'td right top' }, E('strong', { 'style': 'border-bottom:2px solid blue' }, [ _('Inbound:') ])),
E('td', { 'class': 'td', 'id': 'rx_bw_cur' }, rate(0, true)),
E('td', { 'class': 'td right top' }, E('strong', {}, [ _('Average:') ])),
E('td', { 'class': 'td', 'id': 'rx_bw_avg' }, rate(0, true)),
E('td', { 'class': 'td right top' }, E('strong', {}, [ _('Peak:') ])),
E('td', { 'class': 'td', 'id': 'rx_bw_peak' }, rate(0, true))
]),
E('tr', { 'class': 'tr' }, [
E('td', { 'class': 'td right top' }, E('strong', { 'style': 'border-bottom:2px solid green' }, [ _('Outbound:') ])),
E('td', { 'class': 'td', 'id': 'tx_bw_cur' }, rate(0, true)),
E('td', { 'class': 'td right top' }, E('strong', {}, [ _('Average:') ])),
E('td', { 'class': 'td', 'id': 'tx_bw_avg' }, rate(0, true)),
E('td', { 'class': 'td right top' }, E('strong', {}, [ _('Peak:') ])),
E('td', { 'class': 'td', 'id': 'tx_bw_peak' }, rate(0, true))
])
]),
E('div', {'class': 'cbi-section-create'})
]));
this.updateGraph(ifname, csvg, [ { line: 'rx', counter: true }, null, { line: 'tx', counter: true } ], function(svg, info) {
var G = svg.firstElementChild, tab = svg.parentNode;
G.getElementById('label_25').firstChild.data = rate(info.label_25).join('');
G.getElementById('label_50').firstChild.data = rate(info.label_50).join('');
G.getElementById('label_75').firstChild.data = rate(info.label_75).join('');
tab.querySelector('#scale').firstChild.data = _('(%d minute window, %d second interval)').format(info.timeframe, info.interval);
dom.content(tab.querySelector('#rx_bw_cur'), rate(info.line_current[0], true));
dom.content(tab.querySelector('#rx_bw_avg'), rate(info.line_average[0], true));
dom.content(tab.querySelector('#rx_bw_peak'), rate(info.line_peak[0], true));
dom.content(tab.querySelector('#tx_bw_cur'), rate(info.line_current[1], true));
dom.content(tab.querySelector('#tx_bw_avg'), rate(info.line_average[1], true));
dom.content(tab.querySelector('#tx_bw_peak'), rate(info.line_peak[1], true));
});
}
ui.tabs.initTabGroup(v.firstElementChild.childNodes);
this.pollData();
return E([], [
E('h2', _('Bandwidth')),
E('div', {'class': 'cbi-map-descr'}, _('This page displays the bandwidth used for all available physical interfaces.')),
v
]);
},
handleSaveApply: null,
handleSave: null,
handleReset: null
});
@@ -0,0 +1,16 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">
<polyline id="rx" points="" style="fill:blue;fill-opacity:0.4;stroke:blue;stroke-width:1" />
<polyline id="tx" points="" style="fill:green;fill-opacity:0.4;stroke:green;stroke-width:1" />
<line x1="0" y1="25%" x2="100%" y2="25%" style="stroke:black;stroke-width:0.1" />
<text id="label_75" x="20" y="24%" style="fill:#eee; font-size:9pt; font-family:sans-serif; text-shadow:1px 1px 1px #000"> </text>
<line x1="0" y1="50%" x2="100%" y2="50%" style="stroke:black;stroke-width:0.1" />
<text id="label_50" x="20" y="49%" style="fill:#eee; font-size:9pt; font-family:sans-serif; text-shadow:1px 1px 1px #000"> </text>
<line x1="0" y1="75%" x2="100%" y2="75%" style="stroke:black;stroke-width:0.1" />
<text id="label_25" x="20" y="74%" style="fill:#eee; font-size:9pt; font-family:sans-serif; text-shadow:1px 1px 1px #000"> </text>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

@@ -0,0 +1,473 @@
'use strict';
'require view';
'require poll';
'require request';
'require rpc';
var callLuciRealtimeStats = rpc.declare({
object: 'luci',
method: 'getRealtimeStats',
params: [ 'mode', 'device' ],
expect: { result: [] }
});
var callLuciConntrackList = rpc.declare({
object: 'luci',
method: 'getConntrackList',
expect: { result: [] }
});
var callNetworkRrdnsLookup = rpc.declare({
object: 'network.rrdns',
method: 'lookup',
params: [ 'addrs', 'timeout', 'limit' ],
expect: { '': {} }
});
var graphPolls = [],
pollInterval = 3,
dns_cache = {},
enableLookups = false,
filterText = '';
var recheck_lookup_queue = {};
Math.log2 = Math.log2 || function(x) { return Math.log(x) * Math.LOG2E; };
return view.extend({
load: function() {
return Promise.all([
this.loadSVG(L.resource('svg/connections.svg'))
]);
},
updateGraph: function(svg, lines, cb) {
var G = svg.firstElementChild;
var view = document.querySelector('#view');
var width = view.offsetWidth - 2;
var height = 300 - 2;
var step = 5;
var data_wanted = Math.floor(width / step);
var data_values = [],
line_elements = [];
for (var i = 0; i < lines.length; i++)
if (lines[i] != null)
data_values.push([]);
var info = {
line_current: [],
line_average: [],
line_peak: []
};
/* prefill datasets */
for (var i = 0; i < data_values.length; i++)
for (var j = 0; j < data_wanted; j++)
data_values[i][j] = 0;
/* plot horizontal time interval lines */
for (var i = width % (step * 60); i < width; i += step * 60) {
var line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', i);
line.setAttribute('y1', 0);
line.setAttribute('x2', i);
line.setAttribute('y2', '100%');
line.setAttribute('style', 'stroke:black;stroke-width:0.1');
var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.setAttribute('x', i + 5);
text.setAttribute('y', 15);
text.setAttribute('style', 'fill:#eee; font-size:9pt; font-family:sans-serif; text-shadow:1px 1px 1px #000');
text.appendChild(document.createTextNode(Math.round((width - i) / step / 60) + 'm'));
G.appendChild(line);
G.appendChild(text);
}
info.interval = pollInterval;
info.timeframe = data_wanted / 60;
graphPolls.push({
svg: svg,
lines: lines,
cb: cb,
info: info,
width: width,
height: height,
step: step,
values: data_values,
timestamp: 0,
fill: 1
});
},
updateConntrack: function(conn) {
var lookup_queue = [ ];
var rows = [];
conn.sort(function(a, b) {
return b.bytes - a.bytes;
});
for (var i = 0; i < conn.length; i++)
{
var c = conn[i];
if ((c.src == '127.0.0.1' && c.dst == '127.0.0.1') ||
(c.src == '::1' && c.dst == '::1'))
continue;
if (!dns_cache[c.src] && lookup_queue.indexOf(c.src) == -1)
lookup_queue.push(c.src);
if (!dns_cache[c.dst] && lookup_queue.indexOf(c.dst) == -1)
lookup_queue.push(c.dst);
var src = dns_cache[c.src] || (c.layer3 == 'ipv6' ? '[' + c.src + ']' : c.src);
var dst = dns_cache[c.dst] || (c.layer3 == 'ipv6' ? '[' + c.dst + ']' : c.dst);
const network = c.layer3.toUpperCase();
const protocol = c.layer4.toUpperCase();
const source ='%h'.format(c.hasOwnProperty('sport') ? (src + ':' + c.sport) : src);
const destination = '%h'.format(c.hasOwnProperty('dport') ? (dst + ':' + c.dport) : dst);
const transfer = [ c.bytes, '%1024.2mB (%d %s)'.format(c.bytes, c.packets, _('Pkts.')) ];
if (filterText) {
let filterTextExpressions = filterText.split(' ');
if (filterTextExpressions.some((element) => element.toUpperCase() !== network && element.toUpperCase() !== protocol
&& !(c.src.includes(element) || source.includes(element))
&& !(c.dst.includes(element) || destination.includes(element)))) {
continue;
}
}
rows.push([
network,
protocol,
source,
destination,
transfer,
]);
}
cbi_update_table('#connections', rows, E('em', _('No information available')));
if (enableLookups && lookup_queue.length > 0) {
var reduced_lookup_queue = lookup_queue;
if (lookup_queue.length > 100)
reduced_lookup_queue = lookup_queue.slice(0, 100);
callNetworkRrdnsLookup(reduced_lookup_queue, 5000, 1000).then(function(replies) {
for (var index in reduced_lookup_queue) {
var address = reduced_lookup_queue[index];
if (!address)
continue;
if (replies[address]) {
dns_cache[address] = replies[address];
lookup_queue.splice(reduced_lookup_queue.indexOf(address), 1);
continue;
}
if (recheck_lookup_queue[address] > 2) {
dns_cache[address] = (address.match(/:/)) ? '[' + address + ']' : address;
lookup_queue.splice(index, 1);
}
else {
recheck_lookup_queue[address] = (recheck_lookup_queue[address] || 0) + 1;
}
}
var btn = document.querySelector('.btn.toggle-lookups');
if (btn) {
btn.firstChild.data = enableLookups ? _('Disable DNS lookups') : _('Enable DNS lookups');
btn.classList.remove('spinning');
btn.disabled = false;
}
});
}
},
pollData: function() {
poll.add(L.bind(function() {
var tasks = [
L.resolveDefault(callLuciConntrackList(), [])
];
for (var i = 0; i < graphPolls.length; i++) {
var ctx = graphPolls[i];
tasks.push(L.resolveDefault(callLuciRealtimeStats('conntrack'), []));
}
return Promise.all(tasks).then(L.bind(function(datasets) {
this.updateConntrack(datasets[0]);
for (var gi = 0; gi < graphPolls.length; gi++) {
var ctx = graphPolls[gi],
data = datasets[gi + 1],
values = ctx.values,
lines = ctx.lines,
info = ctx.info;
var data_scale = 0;
var data_wanted = Math.floor(ctx.width / ctx.step);
var last_timestamp = NaN;
for (var i = 0, di = 0; di < lines.length; di++) {
if (lines[di] == null)
continue;
var multiply = (lines[di].multiply != null) ? lines[di].multiply : 1,
offset = (lines[di].offset != null) ? lines[di].offset : 0;
for (var j = ctx.timestamp ? 0 : 1; j < data.length; j++) {
/* skip overlapping entries */
if (data[j][0] <= ctx.timestamp)
continue;
if (i == 0) {
ctx.fill++;
last_timestamp = data[j][0];
}
info.line_current[i] = data[j][di + 1] * multiply;
info.line_current[i] -= Math.min(info.line_current[i], offset);
values[i].push(info.line_current[i]);
}
i++;
}
/* cut off outdated entries */
ctx.fill = Math.min(ctx.fill, data_wanted);
for (var i = 0; i < values.length; i++) {
var len = values[i].length;
values[i] = values[i].slice(len - data_wanted, len);
/* find peaks, averages */
info.line_peak[i] = NaN;
info.line_average[i] = 0;
for (var j = 0; j < values[i].length; j++) {
info.line_peak[i] = isNaN(info.line_peak[i]) ? values[i][j] : Math.max(info.line_peak[i], values[i][j]);
info.line_average[i] += values[i][j];
}
info.line_average[i] = info.line_average[i] / ctx.fill;
}
info.peak = Math.max.apply(Math, info.line_peak);
/* remember current timestamp, calculate horizontal scale */
if (!isNaN(last_timestamp))
ctx.timestamp = last_timestamp;
var size = Math.floor(Math.log2(info.peak)),
div = Math.pow(2, size - (size % 10)),
mult = info.peak / div,
mult = (mult < 5) ? 2 : ((mult < 50) ? 10 : ((mult < 500) ? 100 : 1000));
info.peak = info.peak + (mult * div) - (info.peak % (mult * div));
data_scale = ctx.height / info.peak;
/* plot data */
for (var i = 0, di = 0; di < lines.length; di++) {
if (lines[di] == null)
continue;
var el = ctx.svg.firstElementChild.getElementById(lines[di].line),
pt = '0,' + ctx.height,
y = 0;
if (!el)
continue;
for (var j = 0; j < values[i].length; j++) {
var x = j * ctx.step;
y = ctx.height - Math.floor(values[i][j] * data_scale);
//y -= Math.floor(y % (1 / data_scale));
y = isNaN(y) ? ctx.height : y;
pt += ' ' + x + ',' + y;
}
pt += ' ' + ctx.width + ',' + y + ' ' + ctx.width + ',' + ctx.height;
el.setAttribute('points', pt);
i++;
}
info.label_25 = 0.25 * info.peak;
info.label_50 = 0.50 * info.peak;
info.label_75 = 0.75 * info.peak;
if (typeof(ctx.cb) == 'function')
ctx.cb(ctx.svg, info);
}
}, this));
}, this), pollInterval);
},
loadSVG: function(src) {
return request.get(src).then(function(response) {
if (!response.ok)
throw new Error(response.statusText);
return E('div', {
'style': 'width:100%;height:300px;border:1px solid #000;background:#fff'
}, E(response.text()));
});
},
render: function(data) {
var svg = data[0];
var v = E('div', { 'class': 'cbi-map', 'id': 'map' }, [
E('h2', _('Connections')),
E('div', {'class': 'cbi-map-descr'}, _('This page displays the active connections via this device.')),
E('div', { 'class': 'cbi-section' }, [
svg,
E('div', { 'class': 'right' }, E('small', { 'id': 'scale' }, '-')),
E('br'),
E('table', { 'class': 'table', 'style': 'width:100%;table-layout:fixed' }, [
E('tr', { 'class': 'tr' }, [
E('td', { 'class': 'td right top' }, E('strong', { 'style': 'border-bottom:2px solid blue' }, [ _('UDP:') ])),
E('td', { 'class': 'td', 'id': 'lb_udp_cur' }, [ '0' ]),
E('td', { 'class': 'td right top' }, E('strong', {}, [ _('Average:') ])),
E('td', { 'class': 'td', 'id': 'lb_udp_avg' }, [ '0' ]),
E('td', { 'class': 'td right top' }, E('strong', {}, [ _('Peak:') ])),
E('td', { 'class': 'td', 'id': 'lb_udp_peak' }, [ '0' ])
]),
E('tr', { 'class': 'tr' }, [
E('td', { 'class': 'td right top' }, E('strong', { 'style': 'border-bottom:2px solid green' }, [ _('TCP:') ])),
E('td', { 'class': 'td', 'id': 'lb_tcp_cur' }, [ '0' ]),
E('td', { 'class': 'td right top' }, E('strong', {}, [ _('Average:') ])),
E('td', { 'class': 'td', 'id': 'lb_tcp_avg' }, [ '0' ]),
E('td', { 'class': 'td right top' }, E('strong', {}, [ _('Peak:') ])),
E('td', { 'class': 'td', 'id': 'lb_tcp_peak' }, [ '0' ])
]),
E('tr', { 'class': 'tr' }, [
E('td', { 'class': 'td right top' }, E('strong', { 'style': 'border-bottom:2px solid red' }, [ _('Other:') ])),
E('td', { 'class': 'td', 'id': 'lb_otr_cur' }, [ '0' ]),
E('td', { 'class': 'td right top' }, E('strong', {}, [ _('Average:') ])),
E('td', { 'class': 'td', 'id': 'lb_otr_avg' }, [ '0' ]),
E('td', { 'class': 'td right top' }, E('strong', {}, [ _('Peak:') ])),
E('td', { 'class': 'td', 'id': 'lb_otr_peak' }, [ '0' ])
])
]),
E('br'),
E('div', {
id: 'settings-row',
style: 'display: flex',
}, [
E('span', {
class: 'filter',
style: 'flex: auto',
}, [
E('input', {
id: 'filter-connections',
type: 'text',
placeholder: '192.168.1.15 / UDP 1.15 / :443',
class: 'cbi-input-text',
style: 'width: 100%',
keyup: function(ev) {
filterText = this.value;
}
})
]),
E('span', {
class: 'right',
style: 'flex: auto',
}, [
E('button', {
'class': 'btn cbi-button cbi-button-apply toggle-lookups',
'click': function(ev) {
if (!enableLookups) {
ev.currentTarget.classList.add('spinning');
ev.currentTarget.disabled = true;
enableLookups = true;
}
else {
ev.currentTarget.firstChild.data = _('Enable DNS lookups');
enableLookups = false;
}
this.blur();
}
}, [ enableLookups ? _('Disable DNS lookups') : _('Enable DNS lookups') ])
]),
]),
E('br'),
E('div', { 'class': 'cbi-section-node' }, [
E('table', { 'class': 'table', 'id': 'connections' }, [
E('tr', { 'class': 'tr table-titles' }, [
E('th', { 'class': 'th col-2 hide-xs' }, [ _('Network') ]),
E('th', { 'class': 'th col-2' }, [ _('Protocol') ]),
E('th', { 'class': 'th col-7' }, [ _('Source') ]),
E('th', { 'class': 'th col-7' }, [ _('Destination') ]),
E('th', { 'class': 'th col-4' }, [ _('Transfer') ])
]),
E('tr', { 'class': 'tr placeholder' }, [
E('td', { 'class': 'td' }, [
E('em', {}, [ _('Collecting data...') ])
])
])
])
])
])
]);
this.updateGraph(svg, [ { line: 'udp' }, { line: 'tcp' }, { line: 'other' } ], function(svg, info) {
var G = svg.firstElementChild, tab = svg.parentNode;
G.getElementById('label_25').firstChild.data = '%d'.format(info.label_25);
G.getElementById('label_50').firstChild.data = '%d'.format(info.label_50);
G.getElementById('label_75').firstChild.data = '%d'.format(info.label_75);
tab.querySelector('#scale').firstChild.data = _('(%d minute window, %d second interval)').format(info.timeframe, info.interval);
tab.querySelector('#lb_udp_cur').firstChild.data = '%d'.format(info.line_current[0]);
tab.querySelector('#lb_udp_avg').firstChild.data = '%d'.format(info.line_average[0]);
tab.querySelector('#lb_udp_peak').firstChild.data = '%d'.format(info.line_peak[0]);
tab.querySelector('#lb_tcp_cur').firstChild.data = '%d'.format(info.line_current[1]);
tab.querySelector('#lb_tcp_avg').firstChild.data = '%d'.format(info.line_average[1]);
tab.querySelector('#lb_tcp_peak').firstChild.data = '%d'.format(info.line_peak[1]);
tab.querySelector('#lb_otr_cur').firstChild.data = '%d'.format(info.line_current[2]);
tab.querySelector('#lb_otr_avg').firstChild.data = '%d'.format(info.line_average[2]);
tab.querySelector('#lb_otr_peak').firstChild.data = '%d'.format(info.line_peak[2]);
});
this.pollData();
return v;
},
handleSaveApply: null,
handleSave: null,
handleReset: null
});
@@ -0,0 +1,17 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">
<polyline id="tcp" points="" style="fill:green;fill-opacity:0.4;stroke:green;stroke-width:1" />
<polyline id="udp" points="" style="fill:blue;fill-opacity:0.4;stroke:blue;stroke-width:1" />
<polyline id="other" points="" style="fill:red;fill-opacity:0.4;stroke:red;stroke-width:1" />
<line x1="0" y1="25%" x2="100%" y2="25%" style="stroke:black;stroke-width:0.1" />
<text id="label_75" x="20" y="24%" style="fill:#eee; font-size:9pt; font-family:sans-serif; text-shadow:1px 1px 1px #000"> </text>
<line x1="0" y1="50%" x2="100%" y2="50%" style="stroke:black;stroke-width:0.1" />
<text id="label_50" x="20" y="49%" style="fill:#eee; font-size:9pt; font-family:sans-serif; text-shadow:1px 1px 1px #000"> </text>
<line x1="0" y1="75%" x2="100%" y2="75%" style="stroke:black;stroke-width:0.1" />
<text id="label_25" x="20" y="74%" style="fill:#eee; font-size:9pt; font-family:sans-serif; text-shadow:1px 1px 1px #000"> </text>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

+299
View File
@@ -0,0 +1,299 @@
'use strict';
'require view';
'require poll';
'require request';
'require rpc';
var callLuciRealtimeStats = rpc.declare({
object: 'luci',
method: 'getRealtimeStats',
params: [ 'mode', 'device' ],
expect: { result: [] }
});
var graphPolls = [],
pollInterval = 3;
Math.log2 = Math.log2 || function(x) { return Math.log(x) * Math.LOG2E; };
return view.extend({
load: function() {
return Promise.all([
this.loadSVG(L.resource('svg/load.svg'))
]);
},
updateGraph: function(svg, lines, cb) {
var G = svg.firstElementChild;
var view = document.querySelector('#view');
var width = view.offsetWidth - 2;
var height = 300 - 2;
var step = 5;
var data_wanted = Math.floor(width / step);
var data_values = [],
line_elements = [];
for (var i = 0; i < lines.length; i++)
if (lines[i] != null)
data_values.push([]);
var info = {
line_current: [],
line_average: [],
line_peak: []
};
/* prefill datasets */
for (var i = 0; i < data_values.length; i++)
for (var j = 0; j < data_wanted; j++)
data_values[i][j] = 0;
/* plot horizontal time interval lines */
for (var i = width % (step * 60); i < width; i += step * 60) {
var line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', i);
line.setAttribute('y1', 0);
line.setAttribute('x2', i);
line.setAttribute('y2', '100%');
line.setAttribute('style', 'stroke:black;stroke-width:0.1');
var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.setAttribute('x', i + 5);
text.setAttribute('y', 15);
text.setAttribute('style', 'fill:#eee; font-size:9pt; font-family:sans-serif; text-shadow:1px 1px 1px #000');
text.appendChild(document.createTextNode(Math.round((width - i) / step / 60) + 'm'));
G.appendChild(line);
G.appendChild(text);
}
info.interval = pollInterval;
info.timeframe = data_wanted / 60;
graphPolls.push({
svg: svg,
lines: lines,
cb: cb,
info: info,
width: width,
height: height,
step: step,
values: data_values,
timestamp: 0,
fill: 1
});
},
pollData: function() {
poll.add(L.bind(function() {
var tasks = [];
for (var i = 0; i < graphPolls.length; i++) {
var ctx = graphPolls[i];
tasks.push(L.resolveDefault(callLuciRealtimeStats('load'), []));
}
return Promise.all(tasks).then(L.bind(function(datasets) {
for (var gi = 0; gi < graphPolls.length; gi++) {
var ctx = graphPolls[gi],
data = datasets[gi],
values = ctx.values,
lines = ctx.lines,
info = ctx.info;
var data_scale = 0;
var data_wanted = Math.floor(ctx.width / ctx.step);
var last_timestamp = NaN;
for (var i = 0, di = 0; di < lines.length; di++) {
if (lines[di] == null)
continue;
var multiply = (lines[di].multiply != null) ? lines[di].multiply : 1,
offset = (lines[di].offset != null) ? lines[di].offset : 0;
for (var j = ctx.timestamp ? 0 : 1; j < data.length; j++) {
/* skip overlapping entries */
if (data[j][0] <= ctx.timestamp)
continue;
if (i == 0) {
ctx.fill++;
last_timestamp = data[j][0];
}
info.line_current[i] = data[j][di + 1] * multiply;
info.line_current[i] -= Math.min(info.line_current[i], offset);
values[i].push(info.line_current[i]);
}
i++;
}
/* cut off outdated entries */
ctx.fill = Math.min(ctx.fill, data_wanted);
for (var i = 0; i < values.length; i++) {
var len = values[i].length;
values[i] = values[i].slice(len - data_wanted, len);
/* find peaks, averages */
info.line_peak[i] = NaN;
info.line_average[i] = 0;
for (var j = 0; j < values[i].length; j++) {
info.line_peak[i] = isNaN(info.line_peak[i]) ? values[i][j] : Math.max(info.line_peak[i], values[i][j]);
info.line_average[i] += values[i][j];
}
info.line_average[i] = info.line_average[i] / ctx.fill;
}
info.peak = Math.max.apply(Math, info.line_peak);
/* remember current timestamp, calculate horizontal scale */
if (!isNaN(last_timestamp))
ctx.timestamp = last_timestamp;
var size = Math.floor(Math.log2(info.peak)),
div = Math.pow(2, size - (size % 10)),
mult = info.peak / div,
mult = (mult < 5) ? 2 : ((mult < 50) ? 10 : ((mult < 500) ? 100 : 1000));
info.peak = info.peak + (mult * div) - (info.peak % (mult * div));
data_scale = ctx.height / info.peak;
/* plot data */
for (var i = 0, di = 0; di < lines.length; di++) {
if (lines[di] == null)
continue;
var el = ctx.svg.firstElementChild.getElementById(lines[di].line),
pt = '0,' + ctx.height,
y = 0;
if (!el)
continue;
for (var j = 0; j < values[i].length; j++) {
var x = j * ctx.step;
y = ctx.height - Math.floor(values[i][j] * data_scale);
//y -= Math.floor(y % (1 / data_scale));
y = isNaN(y) ? ctx.height : y;
pt += ' ' + x + ',' + y;
}
pt += ' ' + ctx.width + ',' + y + ' ' + ctx.width + ',' + ctx.height;
el.setAttribute('points', pt);
i++;
}
info.label_25 = 0.25 * info.peak;
info.label_50 = 0.50 * info.peak;
info.label_75 = 0.75 * info.peak;
if (typeof(ctx.cb) == 'function')
ctx.cb(ctx.svg, info);
}
}, this));
}, this), pollInterval);
},
loadSVG: function(src) {
return request.get(src).then(function(response) {
if (!response.ok)
throw new Error(response.statusText);
return E('div', {
'style': 'width:100%;height:300px;border:1px solid #000;background:#fff'
}, E(response.text()));
});
},
render: function(data) {
var svg = data[0];
var v = E('div', { 'class': 'cbi-map', 'id': 'map' }, [
E('h2', _('System load')),
E('div', {'class': 'cbi-map-descr'}, _('Load Average is a metric that is used by Linux to keep track of system resources.')),
E('div', { 'class': 'cbi-section' }, [
svg,
E('div', { 'class': 'right' }, E('small', { 'id': 'scale' }, '-')),
E('br'),
E('table', { 'class': 'table', 'style': 'width:100%;table-layout:fixed' }, [
E('tr', { 'class': 'tr' }, [
E('td', { 'class': 'td right top' }, E('strong', { 'style': 'border-bottom:2px solid #f00' }, [ _('1 Minute Load:') ])),
E('td', { 'class': 'td', 'id': 'lb_load01_cur' }, [ '0.00' ]),
E('td', { 'class': 'td right top' }, E('strong', {}, [ _('Average:') ])),
E('td', { 'class': 'td', 'id': 'lb_load01_avg' }, [ '0.00' ]),
E('td', { 'class': 'td right top' }, E('strong', {}, [ _('Peak:') ])),
E('td', { 'class': 'td', 'id': 'lb_load01_peak' }, [ '0.00' ])
]),
E('tr', { 'class': 'tr' }, [
E('td', { 'class': 'td right top' }, E('strong', { 'style': 'border-bottom:2px solid #f60' }, [ _('5 Minute Load:') ])),
E('td', { 'class': 'td', 'id': 'lb_load05_cur' }, [ '0.00' ]),
E('td', { 'class': 'td right top' }, E('strong', {}, [ _('Average:') ])),
E('td', { 'class': 'td', 'id': 'lb_load05_avg' }, [ '0.00' ]),
E('td', { 'class': 'td right top' }, E('strong', {}, [ _('Peak:') ])),
E('td', { 'class': 'td', 'id': 'lb_load05_peak' }, [ '0.00' ])
]),
E('tr', { 'class': 'tr' }, [
E('td', { 'class': 'td right top' }, E('strong', { 'style': 'border-bottom:2px solid #fa0' }, [ _('15 Minute Load:') ])),
E('td', { 'class': 'td', 'id': 'lb_load15_cur' }, [ '0.00' ]),
E('td', { 'class': 'td right top' }, E('strong', {}, [ _('Average:') ])),
E('td', { 'class': 'td', 'id': 'lb_load15_avg' }, [ '0.00' ]),
E('td', { 'class': 'td right top' }, E('strong', {}, [ _('Peak:') ])),
E('td', { 'class': 'td', 'id': 'lb_load15_peak' }, [ '0.00' ])
])
])
])
]);
this.updateGraph(svg, [ { line: 'load01' }, { line: 'load05' }, { line: 'load15' } ], function(svg, info) {
var G = svg.firstElementChild, tab = svg.parentNode;
G.getElementById('label_25').firstChild.data = '%.2f'.format(info.label_25 / 100);
G.getElementById('label_50').firstChild.data = '%.2f'.format(info.label_50 / 100);
G.getElementById('label_75').firstChild.data = '%.2f'.format(info.label_75 / 100);
tab.querySelector('#scale').firstChild.data = _('(%d minute window, %d second interval)').format(info.timeframe, info.interval);
tab.querySelector('#lb_load01_cur').firstChild.data = '%.2f'.format(info.line_current[0] / 100);
tab.querySelector('#lb_load01_avg').firstChild.data = '%.2f'.format(info.line_average[0] / 100);
tab.querySelector('#lb_load01_peak').firstChild.data = '%.2f'.format(info.line_peak[0] / 100);
tab.querySelector('#lb_load05_cur').firstChild.data = '%.2f'.format(info.line_current[1] / 100);
tab.querySelector('#lb_load05_avg').firstChild.data = '%.2f'.format(info.line_average[1] / 100);
tab.querySelector('#lb_load05_peak').firstChild.data = '%.2f'.format(info.line_peak[1] / 100);
tab.querySelector('#lb_load15_cur').firstChild.data = '%.2f'.format(info.line_current[2] / 100);
tab.querySelector('#lb_load15_avg').firstChild.data = '%.2f'.format(info.line_average[2] / 100);
tab.querySelector('#lb_load15_peak').firstChild.data = '%.2f'.format(info.line_peak[2] / 100);
});
this.pollData();
return v;
},
handleSaveApply: null,
handleSave: null,
handleReset: null
});
+17
View File
@@ -0,0 +1,17 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">
<polyline id="load01" points="" style="fill:#ff0000;fill-opacity:0.4;stroke:#ff0000;stroke-width:1" />
<polyline id="load05" points="" style="fill:#ff6600;fill-opacity:0.4;stroke:#ff6600;stroke-width:1" />
<polyline id="load15" points="" style="fill:#ffaa00;fill-opacity:0.4;stroke:#ffaa00;stroke-width:1" />
<line x1="0" y1="25%" x2="100%" y2="25%" style="stroke:black;stroke-width:0.1" />
<text id="label_75" x="20" y="24%" style="fill:#eee; font-size:9pt; font-family:sans-serif; text-shadow:1px 1px 1px #000"> </text>
<line x1="0" y1="50%" x2="100%" y2="50%" style="stroke:black;stroke-width:0.1" />
<text id="label_50" x="20" y="49%" style="fill:#eee; font-size:9pt; font-family:sans-serif; text-shadow:1px 1px 1px #000"> </text>
<line x1="0" y1="75%" x2="100%" y2="75%" style="stroke:black;stroke-width:0.1" />
<text id="label_25" x="20" y="74%" style="fill:#eee; font-size:9pt; font-family:sans-serif; text-shadow:1px 1px 1px #000"> </text>
</svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

@@ -0,0 +1,54 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const source = fs.readFileSync('htdocs/luci-static/resources/carbon/traffic.js', 'utf8');
function load(values, result = { columns: ['mac', 'rx_bytes', 'tx_bytes'], data: [] }) {
const calls = [];
const subject = vm.runInNewContext('(function() {\n' + source + '\n})()', {
baseclass: { extend: (x) => x },
rpc: { declare: (spec) => async (...args) => { calls.push([spec.object, spec.method, ...args]); return values; } },
fs: { exec_direct: async (...args) => { calls.push(['exec', ...args]); if (result instanceof Error) throw result; return result; } }
});
return { subject, calls };
}
test('traffic adapter follows the collector cadence and only invokes the fixed read command', async () => {
for (const [input, expected] of [['30s', 30], ['2m', 120], ['1', 5], [undefined, 30]]) {
const f = load({ config: { '.type': 'nlbwmon', refresh_interval: input } });
assert.equal((await f.subject.read()).interval, expected);
await f.subject.read();
assert.deepEqual(JSON.parse(JSON.stringify(f.calls)), [
['uci', 'get', 'nlbwmon'],
['exec', '/usr/sbin/nlbw', ['-c', 'json', '-g', 'mac', '-n'], 'json'],
['exec', '/usr/sbin/nlbw', ['-c', 'json', '-g', 'mac', '-n'], 'json']
]);
}
});
test('missing, ambiguous or invalid collector configuration never starts a command', async () => {
for (const config of [{}, { one: { '.type': 'nlbwmon', refresh_interval: '0' } },
{ one: { '.type': 'nlbwmon', refresh_interval: '30;reboot' } },
{ one: { '.type': 'nlbwmon' }, two: { '.type': 'nlbwmon' } }]) {
const f = load(config);
assert.equal(await f.subject.read(), null);
assert.equal(f.calls.length, 1);
}
});
test('unavailable collector is propagated for the dashboard to handle without changing configuration', async () => {
const f = load({ cfg: { '.type': 'nlbwmon' } }, new Error('not running'));
await assert.rejects(f.subject.read(), /not running/);
assert.equal(f.calls.length, 2);
});
test('traffic permissions grant only the fixed counter read and read-only collector configuration', () => {
const acl = JSON.parse(fs.readFileSync('root/usr/share/rpcd/acl.d/luci-theme-carbon.json'))['luci-theme-carbon'];
assert.deepEqual(acl.read.file['/usr/sbin/nlbw -c json -g mac -n'], ['exec']);
assert.deepEqual(Object.entries(acl.read.file).filter(([, rights]) => rights.includes('exec')).map(([name]) => name),
['/usr/sbin/nlbw -c json -g mac -n']);
assert.ok(acl.read.uci.includes('nlbwmon'));
assert.deepEqual(acl.write.uci, ['luci']);
});