1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-02 17:06:09 +00:00

fix(computes): a chart places each reading at the time it came

The CPU, memory, disk and network charts of a host and of a VM put their
readings at equal steps: a reading that took 20 s looked like one 5 s
after the one before. The x axis now counts seconds, a reading standing
at the time it came; each tick is at a reading and named with the
panel's time of it, as before. Checked with Chart.js in a browser: a
20 s step is four times as wide as a 5 s one.
This commit is contained in:
catborise 2026-11-13 16:17:42 +03:00
parent be4616ee85
commit 275bf11aed
3 changed files with 93 additions and 13 deletions

View file

@ -145,8 +145,8 @@ class GraphScriptTestCase(TestCase):
poll.request();
const label = charts[0].options.plugins.tooltip.callbacks.label({dataset: {label: "Usage"}, formattedValue: "3", dataIndex: 0});
console.log(JSON.stringify({requests, timeouts, label, shown, state: elements.graph_state.textContent,
cpu: charts[0].data.datasets[0].data,
mem: charts[1].data.datasets[0].data, memMax: charts[1].options.scales.y.max}));
cpu: charts[0].data.datasets[0].data.map((point) => point.y),
mem: charts[1].data.datasets[0].data.map((point) => point.y), memMax: charts[1].options.scales.y.max}));
""".replace("SCRIPT", json.dumps(script)).replace("CHARTS", json.dumps(CHARTS_JS.read_text())).replace(
"DATASET", json.dumps(dataset))
out = subprocess.run(["node", "-e", js], capture_output=True, text=True, timeout=30)
@ -162,3 +162,47 @@ class GraphScriptTestCase(TestCase):
self.assertEqual(result["shown"], ["3 %", "1 / 2 GiB", "Updated at t."])
self.assertEqual(result["state"], "Not updated since t.")
self.assertTrue(result["label"].endswith(": 3 % (average over 5.1 s)"), result["label"])
@unittest.skipUnless(shutil.which("node"), "node is not installed")
class ChartAxisTestCase(unittest.TestCase):
"""A reading stands at the time it came, labelled with the panel's time:
one that took 20 s stands four times as far as one of 5 s."""
def test_readings_are_spaced_by_their_time(self):
js = """
const vm = require("vm");
let chart;
const page = {
document: {body: {}},
getComputedStyle: () => ({getPropertyValue: () => ""}),
Chart: Object.assign(function (canvas, config) {
this.data = config.data; this.options = config.options; this.update = () => {}; chart = this;
}, {defaults: {}}),
};
const context = vm.createContext(page);
vm.runInContext(CHARTS, context);
vm.runInContext("var c = lineChart({}, '%', ['Usage']);"
+ " addPoint(c, '12:00:00', [1], 100); addPoint(c, '12:00:05', [2], 105); addPoint(c, '12:00:25', [null], 125);",
context);
// 20 px a second: each reading 100 px from the next or more
const axis = {chart, getPixelForValue: (value) => value * 20};
chart.options.scales.x.afterBuildTicks(axis);
const label = (a) => a.ticks.map((tick, i) => chart.options.scales.x.ticks.callback.call(a, tick.value, i, a.ticks));
const labels = label(axis);
// 4 px a second: a 5 s step (20 px) leaves no room for its label, a 20 s one (80 px) does
const packed = {chart, getPixelForValue: (value) => value * 4};
chart.options.scales.x.afterBuildTicks(packed);
const packedLabels = label(packed);
const title = chart.options.plugins.tooltip.callbacks.title([{chart, parsed: {x: 105}}]);
console.log(JSON.stringify({points: chart.data.datasets[0].data, type: chart.options.scales.x.type, labels, packedLabels,
title}));
""".replace("CHARTS", json.dumps(CHARTS_JS.read_text()))
out = subprocess.run(["node", "-e", js], capture_output=True, text=True, timeout=30)
self.assertEqual(out.returncode, 0, out.stderr)
result = json.loads(out.stdout)
self.assertEqual(result["type"], "linear")
self.assertEqual(result["points"], [{"x": 100, "y": 1}, {"x": 105, "y": 2}, {"x": 125, "y": None}])
self.assertEqual(result["labels"], ["12:00:00", "12:00:05", "12:00:25"])
self.assertEqual(result["packedLabels"], ["", "12:00:05", "12:00:25"])
self.assertEqual(result["title"], "12:00:05")

View file

@ -215,9 +215,9 @@ class StatsScriptTestCase(TestDriverVM, TestCase):
fail = false;
poll.request();
const label = charts[0].options.plugins.tooltip.callbacks.label({dataset: {label: "Usage"}, formattedValue: "3", dataIndex: 0});
console.log(JSON.stringify({requests, label, every: [poll.interval, poll.first], cpu: charts[0].data.datasets[0].data,
disk: charts[2].data.datasets[1].data, net: charts[3].data.datasets[0].data,
mem: charts[1].data.datasets[0].data, memMax: charts[1].options.scales.y.max}));
console.log(JSON.stringify({requests, label, every: [poll.interval, poll.first], cpu: charts[0].data.datasets[0].data.map((point) => point.y),
disk: charts[2].data.datasets[1].data.map((point) => point.y), net: charts[3].data.datasets[0].data.map((point) => point.y),
mem: charts[1].data.datasets[0].data.map((point) => point.y), memMax: charts[1].options.scales.y.max}));
""".replace("SCRIPT", json.dumps(script)).replace("CHARTS", json.dumps(CHARTS_JS.read_text())).replace(
"DATASET", json.dumps(dataset)).replace("CANVASES", json.dumps(canvases))
out = subprocess.run(["node", "-e", js], capture_output=True, text=True, timeout=30)

View file

@ -1,7 +1,11 @@
// Live line charts of the host overview and the VM page (Chart.js 4): the
// last CHART_POINTS readings, a gap where a reading is missing, and the
// colours of the selected Bootstrap theme.
// colours of the selected Bootstrap theme. A reading is placed at the time
// it came: one that took longer stands farther from the one before. Each
// is labelled with the time the panel gave it.
var CHART_POINTS = 10;
// the pixels a tick's label needs from the next one
var TICK_ROOM = 60;
(function () {
var style = getComputedStyle(document.body);
@ -36,13 +40,33 @@ function lineChart(canvas, unit, labels, options) {
animation: false,
maintainAspectRatio: false,
scales: {
x: {ticks: {maxTicksLimit: CHART_POINTS, maxRotation: 0}},
x: {
type: "linear",
// a tick at each reading, named by its label
afterBuildTicks: function (axis) {
axis.ticks = axis.chart.data.datasets[0].data.map(function (point) { return {value: point.x}; });
},
// a reading's label, unless the next one stands too close for it to be read (a
// long step, after the page was hidden, leaves the others packed together)
ticks: {
maxRotation: 0,
autoSkip: false,
callback: function (value, index, ticks) {
var next = ticks[index + 1];
var room = next && this.getPixelForValue(next.value) - this.getPixelForValue(value);
return next && room < TICK_ROOM ? "" : labelAt(this.chart, value);
},
},
},
y: {min: 0, max: options.max, ticks: {callback: function (value) { return value + " " + unit; }}},
},
plugins: {
legend: {display: labels.length > 1},
tooltip: {
callbacks: {
title: function (items) {
return items.length ? labelAt(items[0].chart, items[0].parsed.x) : "";
},
label: function (context) {
var text = context.dataset.label + ": " + context.formattedValue + " " + unit;
return options.tooltip ? options.tooltip(context, text) : text;
@ -54,17 +78,29 @@ function lineChart(canvas, unit, labels, options) {
});
}
// values: one per line, null for a reading that is missing
function addPoint(chart, label, values) {
chart.data.labels.push(label);
// the label of the reading at x (seconds) of chart: the panel's time of it
function labelAt(chart, x) {
return (chart.timeLabels || {})[x] || "";
}
// values: one per line, null for a reading that is missing; at, the
// reading's time in seconds, now if not given
function addPoint(chart, label, values, at) {
var x = at === undefined ? Date.now() / 1000 : at;
chart.timeLabels = chart.timeLabels || {}; // a reading's x: its label
chart.timeLabels[x] = label;
chart.data.datasets.forEach(function (set, i) {
set.data.push(values[i] == null ? null : values[i]);
set.data.push({x: x, y: values[i] == null ? null : values[i]});
});
if (chart.data.labels.length > CHART_POINTS) {
chart.data.labels.shift();
if (chart.data.datasets[0].data.length > CHART_POINTS) {
var gone = chart.data.datasets[0].data[0].x;
chart.data.datasets.forEach(function (set) {
set.data.shift();
});
// the label goes with its last reading: two may have come at one time
if (!chart.data.datasets[0].data.some(function (point) { return point.x === gone; })) {
delete chart.timeLabels[gone];
}
}
chart.update();
}