-
-
Notifications
You must be signed in to change notification settings - Fork 162
/
stats.src.js
567 lines (547 loc) · 26.5 KB
/
stats.src.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
/*!
* Authentic Theme (https://github.com/authentic-theme/authentic-theme)
* Copyright Ilia Rostovtsev <ilia@virtualmin.com>
* Licensed under MIT (https://github.com/authentic-theme/authentic-theme/blob/master/LICENSE)
*/
/* jshint strict: true */
/* jshint esversion: 6 */
/* jshint jquery: true */
"use strict";
// Stats module
const stats = {
sys: {
// Define variables
error: 0,
tried: 0,
activating: 0,
requery: null,
socket: null,
// Import globals
/* jshint -W117 */
_: {
prefix: v___location_prefix,
error: connection_error,
language: theme_language,
convert: {
size: Convert.nice_size,
},
chart: Chartist,
dayjs: dayjs,
locale: {
time: config_portable_theme_locale_format_time,
offset: () => {
return get_utc_offset();
},
},
can_conn_ws: can_conn_ws,
blocked: theme_updating,
getHistoryData: function () {
return vars.stats.history;
},
},
// Define reusable selectors
selector: {
chart: {
container: {
parent: "live_stats",
data: "data-chart",
},
loader: "data-charts-loader",
},
collapse: "collapse",
dashboard: "system-status",
slider: "info-container",
piechart: "piechart",
defaultClassLabel: "bg-semi-transparent",
defaultSliderClassLabel: "bg-semi-transparent-dark",
},
// Get current data to submit to the socket
getSocketDefs: function () {
return {
session: session.server.data("session-hash"),
paused: !this.canRender() ? 1 : 0,
interval: this.getInterval(),
disable: !this.isEnabled() ? 1 : 0,
shutdown: settings_sysinfo_real_time_shutdown_on_last ? 1 : 0,
};
},
// Update settings for the current client on the socket server
// updateSocket: function () {
// if (this.isEnabled() && this.socket &&
// this.socket.readyState === 1) {
// const socketData = this.getSocketDefs();
// // Update socket settings
// this.socket.send(JSON.stringify(socketData));
// }
// },
// Check if graphs can be rendered
graphsCanPreRender: function () {
return document.querySelector(`[${this.selector.chart.loader}]`) ? 1 : 0;
},
// Get interval call for the stats update
getInterval: function () {
return settings_sysinfo_real_time_run_rate / 1000;
},
// Get the stored data duration period (e.g., from 300 to 86400 seconds)
getStoredDuration: function () {
return settings_sysinfo_real_time_stored_duration;
},
// Check if the received data has multiple datasets
getRenderType: function(graphs) {
graphs = graphs.graphs;
let hasMultipleDatasets = false;
for (const key in graphs) {
if (graphs.hasOwnProperty(key) && Array.isArray(graphs[key])) {
if (graphs[key].length > 1) {
hasMultipleDatasets = true;
break;
}
}
}
// Received graphs stats have history
// data (3) or a single slice (null)
return hasMultipleDatasets ? 3 : null;
},
// Can we update the stats in the UI?
canRender: function() {
return theme.visibility.get();
},
// Check if the stats are enabled
isEnabled: function () {
const stats_enabled = settings_sysinfo_real_time_status ? 1 : 0,
stats_can = this._.can_conn_ws();
return stats_enabled && stats_can;
},
// Restart the stats by shutting down and enabling them
restart: function () {
this.shutdown();
setTimeout(() => {
this.enable();
}, this.getInterval() * 1000 * 4);
},
// Disable the stats broadcast for the client
disable: function () {
if (this.socket && this.socket.readyState === 1) {
// console.warn("Disabling stats broadcast");
const socketData = this.getSocketDefs();
socketData.paused = 1;
this.socket.send(JSON.stringify(socketData));
}
},
// Enable the stats broadcast for the client
enable: function () {
if (this.isEnabled()) {
// console.warn("Enabling stats broadcast");
if (this.graphsCanPreRender()) {
this.preRender();
}
if (this.socket) {
// console.warn("Sending ..", this.socket.readyState === 1),
this.socket.readyState === 1 &&
this.socket.send(JSON.stringify(this.getSocketDefs()));
} else {
// console.warn("Activating .."),
this.activate();
}
}
},
// Shutdown the stats broadcast for all
// clients by shutting down the socket
shutdown: function () {
if (this.socket && this.socket.readyState === 1) {
const socketData = this.getSocketDefs();
socketData.disable = 1;
this.socket.send(JSON.stringify(socketData));
}
},
// Activate the stats server unless already up and open
// the socket to receive the data for the current tab
activate: function () {
// Already called for this tab?
if (this.activating++ ||
this._.blocked() ||
this.socket) {
return;
}
// Tried too many times?
if (this.tried++ > 4) {
return;
}
$.ajax({
context: this,
url: `${this._.prefix}/stats.cgi`,
error: function () {
// Reset activating flag
this.activating = 0;
// Show error
if (this.error++ > 3) {
return;
}
// Retry again
!this.requery &&
(this.requery = setTimeout(() => {
this.requery = null;
this.activate();
}, this.getInterval() * 1000 * 4));
},
success: function (data) {
// Do we have socket opened?
if (data.success) {
// Open socket
// console.warn("WebSocket connection opened", data);
this.socket = new WebSocket(data.socket);
// On socket open
this.socket.onopen = () => {
this.tried = 0;
this.activating = 0;
// console.log("WebSocket connection established",
// this.getSocketDefs());
this.socket.send(
JSON.stringify(this.getSocketDefs()));
};
// On socket message
this.socket.onmessage = (event) => {
const message = JSON.parse(event.data),
renderType = this.getRenderType(message);
// Pause stats broadcast for this client
// if the tab is not visible
// err: no need, as redundant with enable/disable?
// if (this.canRender.last != this.canRender()) {
// console.log("Visibility changed", this.canRender());
// this.canRender.last = this.canRender();
// this.updateSocket();
// }
// console.log("Received stats", renderType, message);
this.render(message, renderType);
};
// On socket close
this.socket.onclose = () => {
// console.warn("WebSocket connection closed");
setTimeout(() => {
this.socket = null;
this.activating = 0;
this.enable();
}, this.getInterval() * 1000 * 4);
};
} else {
// Reset activating flag
this.activating = 0;
}
// Reset error counter
this.error = 0;
},
dataType: "json",
});
},
// Draw initial graphs either using stored data or empty placeholders
preRender: function () {
this.render(this._.getHistoryData(), 2);
},
// Display changes
render: function (data, graphs) {
// Iterate through response
Object.entries(data).map(([target, data]) => {
let v = parseInt(data),
vo = typeof data === "object" ? data[data.length - 1] : false,
vt = vo ? vo : v,
$pc = $(
`#${this.selector.dashboard} .${this.selector.piechart}[data-charts*="${target}"]`
),
$lc = $(`.${this.selector.slider} .${target}_percent`),
$od = $(`#${this.selector.dashboard} span[data-id="sysinfo_${target}"],
.${this.selector.slider} span[data-data="${target}"]`),
cached = target === "graphs" ? (graphs ? (graphs === 3 ? 3 : 2) : (this.graphsCanPreRender() ? 2 : 1)) : 0;
if (Number.isInteger(v)) {
// Update pie-charts
if ($pc.length) {
let piechart = $pc.data("easyPieChart");
piechart && piechart.update(v);
}
// Update line-charts
if ($lc.length) {
$lc.find(".bar").attr("style", "width:" + v + "%");
// Update line-charts' text
let $dp = $lc.find(".description"),
$lb = $dp.text().split(":")[0],
uv = $lb + ": " + v + "% (" + vo + ")";
// Flatten and plunk the data for some graphs
if (target !== "cpu") {
uv = plugins.slider.update.stats.graphs.flatten(uv);
if (target !== "virt") {
uv = plugins.slider.update.stats.graphs.plunk(uv);
}
}
$dp.attr("title", vo).text(uv);
}
// Update other data
if ($od.length) {
if ($od.find("a").length) {
$od.find("a").text(vt);
} else {
$od.text(vt);
}
}
}
// Update sensors data
if (target === "sensors" && vo) {
// Iterate through sensors
Object.entries(vo).forEach(([sensor, value]) => {
let this_ = this,
$lb1 = $(`#${this.selector.dashboard} span[data-stats="${sensor}"]`),
$lb2 = $(`.${this.selector.slider} span[data-stats="${sensor}"]`);
if ($lb1 && $lb1.length) {
let lb_count1 = $lb1.length,
lb_count2 = $lb2.length;
// Sort the values based on 'fan' or 'core' field
value.sort((a, b) =>
sensor === "fans" ? a.fan - b.fan : a.core - b.core
);
// Function to update individual label
const updateLabel = function ($label, data, isSingleLabel, sideSlider) {
if (!data) {
return;
}
// Update the label text based on count condition
if (isSingleLabel) {
// Replace only the numeric part, preserving unit (°C or RPM)
$label.html(function (_, html) {
const iSFahrenheit = html.includes("°F");
return html.replace(
/\d+/,
sensor === "fans"
? data.rpm
: (iSFahrenheit ? Math.round((data.temp * 9) / 5 + 32) : data.temp));
});
} else {
// Replace the numeric part after the colon, preserving prefix and unit
$label.html(function (_, html) {
const iSFahrenheit = html.includes("°F");
return html.replace(
/: \d+/,
`: ${sensor === "fans" ? data.rpm :
(iSFahrenheit ? Math.round((data.temp * 9) / 5 + 32) : data.temp)}`
);
});
}
const label_text = $label.text().replace(/.*?\d+:\s*/, "");
let className =
HTML.label.textMaxLevels(sensor, label_text) ||
(sideSlider
? this_.selector.defaultSliderClassLabel
: this_.selector.defaultClassLabel);
if (sideSlider && className === this_.selector.defaultClassLabel) {
className = this_.selector.defaultSliderClassLabel;
}
// Update class based on current label text
$label
.removeClass((i, c) => (c.match(/\bbg-\S+/g) || []).join(" "))
.addClass(className);
};
// Handle $lb1 labels
if (lb_count1 === 1) {
updateLabel($lb1, value[0], true);
} else {
// Handle multiple labels for $lb1
$lb1.each((index, el) => {
if (value[index]) {
updateLabel($(el), value[index], false);
}
});
}
// Handle $lb2 labels similarly
if (lb_count2 === 1) {
updateLabel($lb2, value[0], true, true);
} else {
$lb2.each((index, el) => {
if (value[index]) {
updateLabel($(el), value[index], false, true);
}
});
}
}
});
}
// Draw history graphs
if (cached) {
let lds = `${this.selector.chart.container.parent}-${this.selector.collapse}`,
ld = $(`#${lds}`).find(`[${this.selector.chart.loader}]`);
// Process each supplied graph
Object.entries(data).map(([type, array]) => {
let options = {
chart: {
type: () => {
return type === "proc" || type === "disk" || type === "net";
},
bandwidth: () => {
return type === "disk" || type === "net";
},
fill: function () {
return this.type() ? false : true;
},
high: function () {
return this.type() ? undefined : 100;
},
threshold: function () {
return this.type() ? -1 : 80;
},
height: "100px",
},
},
lg = this._.language(`${this.selector.chart.container.parent}_${type}`),
tg = $(`#${lds}`).find(
`[${this.selector.chart.container.data}=${type}]`
),
sr = [
{
name: `series-${type}`,
data: array,
},
];
// Don't run further in case there is no container
if (!tg.length) {
return;
}
// Extend data object expected way to draw multiple series in single graph
if (array[0] && typeof array[0].y === "object") {
sr = [];
array[0].y.forEach(function (x, i) {
let data = [];
array.forEach(function (n) {
data.push({
data: { x: n.x, y: n.y[i] },
});
});
sr.push({
name: `series-${type}-${i}`,
data: data,
});
});
}
// Update series if chart already
// exist unless it's a re-draw
if (tg[0] && tg[0].textContent && cached !== 3) {
if (cached === 1) {
let lf = parseInt(this.getStoredDuration());
if (lf < 300 || lf > 86400) {
lf = 1200;
}
let tdata = sr,
cdata = this[`chart_${type}`].data.series,
cdata_start,
cdata_end,
cdata_ready = new Promise((resolve) => {
tdata.forEach(function (d, i, a) {
cdata_start =
cdata[i].data[0].x || cdata[i].data[0].data.x;
cdata_end =
cdata[i].data[cdata[i].data.length - 1].x ||
cdata[i].data[cdata[i].data.length - 1].data.x;
cdata[i].data.push(d.data[0]);
if (cdata_end - cdata_start > lf) {
cdata[i].data.shift();
}
if (i === a.length - 1) {
resolve();
}
});
});
cdata_ready.then(() => {
this[`chart_${type}`].update({
series: cdata,
});
});
}
}
// Initialize chart the first time (2) or fully
// update (3) the chart if it's already drawn
else if (cached === 2 || cached === 3) {
this[`chart_${type}`] = new this._.chart.Line(
tg[0],
{
series: sr,
},
{
axisX: {
type: this._.chart.FixedScaleAxis,
divisor: 12,
labelInterpolationFnc: (value) => {
return this._.dayjs(value * 1000)
.utcOffset(this._.locale.offset())
.format(this._.locale.time);
},
},
height: options.chart.height,
showArea: options.chart.fill(),
showPoint: !options.chart.fill(),
high: options.chart.high(),
low: 0,
fullWidth: true,
chartPadding: {
left: 25,
},
axisY: {
onlyInteger: true,
labelInterpolationFnc: (value) => {
if (options.chart.fill()) {
return value ? value + "%" : value;
} else if (options.chart.bandwidth(value)) {
if (type === "net") {
return value
? this._.convert.size(value, {
fixed: 0,
bits: 1,
round: 1,
})
: value;
}
return value
? this._.convert.size(value * 1024, {
fixed: 0,
round: 1,
})
: value;
} else {
return value;
}
},
},
plugins: [
this._.chart.plugins.ctAxisTitle({
axisY: {
axisTitle: lg,
axisClass: "ct-axis-title",
offset: {
x: 0,
y: 9,
},
flipTitle: true,
},
}),
this._.chart.plugins.ctThreshold({
threshold: options.chart.threshold(),
}),
],
}
);
// Remove loader
this[`chart_${type}`].on("created", (data) => {
// Add labels to the first foreign object
const ffObj = data.svg.getNode().querySelector('foreignObject');
if (ffObj) {
const readLbl = this._.language(`dashboard_chart_${type}_read`),
writeLbl = this._.language(`dashboard_chart_${type}_write`);
if (readLbl && writeLbl) {
ffObj.setAttribute('data-label-read', `▪ ${readLbl}`);
ffObj.setAttribute('data-label-write', `▪ ${writeLbl}`);
}
}
// Clean-up loader
ld.remove();
});
}
});
}
});
},
},
};