-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstats-api.js
More file actions
1818 lines (1502 loc) · 51.9 KB
/
stats-api.js
File metadata and controls
1818 lines (1502 loc) · 51.9 KB
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// - Serves JSON at /stats and static UI from ./ui
// - Samples lightweight history on the server (shared for all clients)
// - Tries to work both on host and inside containers (prefers /host/* mounts when present)
import http from "node:http";
import { URL } from "node:url";
import os from "node:os";
import { execSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { createSpeedtestController } from "./speedtest-api.js";
/* ============================================================================
Config
- All knobs via env vars (sane defaults)
============================================================================ */
const PORT = Number(process.env.PORT || 3012);
const NET_IFACE = (process.env.NET_IFACE || "").trim();
const GPU_POLL_MS = Number(process.env.GPU_POLL_MS || 1000);
const GPU_TIMEOUT_MS = Number(process.env.GPU_TIMEOUT_MS || 1000);
const HISTORY_SAMPLE_MS = Number(process.env.HISTORY_SAMPLE_MS || 1000);
const HISTORY_MAX_MIN = Number(process.env.HISTORY_MAX_MIN || 120);
const HISTORY_DB_PATH = process.env.HISTORY_DB_PATH || "./data/history_state.json";
const DISK_PATHS = (process.env.DISK_PATHS || "/")
.split(",")
.map((s) => s.trim())
.filter(Boolean);
/* ============================================================================
Update Proxy (GitHub Releases Atom Feed)
============================================================================ */
const GITHUB_DEFAULT_REPO = (process.env.GITHUB_DEFAULT_REPO || "G-grbz/argusSyS").trim();
// Validate "owner/repo" slug.
function isValidRepoSlug(s) {
return /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(String(s || ""));
}
// Parse the *first* <entry> from GitHub releases.atom as "latest"
function parseLatestReleaseFromAtom(xmlText) {
const xml = String(xmlText || "");
const entry = xml.match(/<entry>([\s\S]*?)<\/entry>/i)?.[1] || "";
if (!entry) return null;
const pick = (re) => entry.match(re)?.[1]?.trim() || "";
const title = pick(/<title[^>]*>([\s\S]*?)<\/title>/i);
const link = pick(/<link[^>]*href="([^"]+)"[^>]*\/?>/i);
const updated = pick(/<updated[^>]*>([\s\S]*?)<\/updated>/i);
const content = pick(/<content[^>]*type="html"[^>]*>([\s\S]*?)<\/content>/i);
const tag = title.replace(/^release\s+/i, "").trim();
return {
tag_name: tag,
name: title,
body_html: content,
html_url: link,
published_at: updated,
};
}
// Fetch and parse latest GitHub release via Atom feed (no token needed).
async function fetchLatestReleaseFromAtom(repo) {
const url = `https://github.com/${repo}/releases.atom`;
const r = await fetch(url, {
method: "GET",
headers: {
"User-Agent": "stats-api-update-proxy",
"Cache-Control": "no-store",
},
});
const text = await r.text().catch(() => "");
if (!r.ok) throw new Error(`Atom HTTP ${r.status} ${r.statusText} :: ${text.slice(0, 200)}`);
return parseLatestReleaseFromAtom(text);
}
/* ============================================================================
Runtime State
- Small in-memory caches for delta computations and polling
============================================================================ */
let lastGpu = null;
let lastGpuTs = 0;
let lastGpuErr = null;
let lastNetSample = null;
let lastCpuTimes = null;
let lastDiskIo = new Map();
/* ============================================================================
Shared History (server-side)
- Sampled independently from clients
- Persisted to a local JSON file (best-effort)
============================================================================ */
// Ensure directory exists for a file path (best-effort)
function ensureDirFor(filePath) {
try {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
} catch {}
}
// Clamp a number into [a..b]
function clamp(n, a, b) {
return Math.max(a, Math.min(b, n));
}
const history = {
v: 1,
maxMin: HISTORY_MAX_MIN,
sampleMs: HISTORY_SAMPLE_MS,
ts: [],
cpu1: [],
cpu5: [],
cpu15: [],
cpu_util: [],
gpu_util: [],
vram_used_b: [],
ram_used_b: [],
ram_free_b: [],
swap_used_b: [],
net_down_bps: [],
net_up_bps: [],
};
// Compute max history length based on sampling interval and max minutes
function maxHistoryLen() {
const maxSec = clamp(history.maxMin * 60, 60, 120 * 60);
const per = Math.max(1, Math.floor(history.sampleMs / 1000));
return Math.ceil(maxSec / per);
}
// Push a value into a history array and trim it to length L
function pushHist(key, val, L) {
const arr = history[key];
if (!Array.isArray(arr)) return;
arr.push(val);
if (arr.length > L) arr.splice(0, arr.length - L);
}
// Trim every array field in history to length L
function trimAll(L) {
for (const k of Object.keys(history)) {
if (Array.isArray(history[k]) && history[k].length > L) {
history[k].splice(0, history[k].length - L);
}
}
}
// Load persisted history from disk (best-effort)
function loadHistoryFromDisk() {
try {
const raw = fs.readFileSync(HISTORY_DB_PATH, "utf8");
const st = JSON.parse(raw);
if (!st || st.v !== 1) return;
for (const k of Object.keys(history)) {
if (Array.isArray(history[k]) && Array.isArray(st[k])) {
history[k] = st[k].slice();
}
}
if (Array.isArray(st.ts)) history.ts = st.ts.slice();
trimAll(maxHistoryLen());
} catch {}
}
let lastHistoryFlush = 0;
// Persist history to disk (throttled unless forced)
function flushHistoryToDisk(force = false) {
const now = Date.now();
if (!force && now - lastHistoryFlush < 100) return;
lastHistoryFlush = now;
try {
ensureDirFor(HISTORY_DB_PATH);
const payload = {
v: 1,
savedAt: now,
maxMin: history.maxMin,
sampleMs: history.sampleMs,
ts: history.ts,
cpu1: history.cpu1,
cpu5: history.cpu5,
cpu15: history.cpu15,
cpu_util: history.cpu_util,
gpu_util: history.gpu_util,
vram_used_b: history.vram_used_b,
ram_used_b: history.ram_used_b,
ram_free_b: history.ram_free_b,
swap_used_b: history.swap_used_b,
net_down_bps: history.net_down_bps,
net_up_bps: history.net_up_bps,
};
fs.writeFileSync(HISTORY_DB_PATH, JSON.stringify(payload), "utf8");
} catch {}
}
// Sample current metrics into the shared history ring buffers
function sampleForHistory() {
const L = maxHistoryLen();
const ts = Date.now();
const cpu = cpuSummary();
const cpu_util = cpuUtilPct();
const cpuUtilVal = Number.isFinite(cpu_util) ? cpu_util : 0;
const gpu = gpuSummary();
const g0 = gpu?.primary || null;
const gpuUtilVal = Number.isFinite(Number(g0?.util_pct)) ? Number(g0.util_pct) : 0;
const vramUsedB = Number.isFinite(Number(g0?.mem_used_b)) ? Number(g0.mem_used_b) : 0;
const mem = memBytes();
const ramUsedB = Number.isFinite(mem.used) ? mem.used : 0;
const ramFreeB = Number.isFinite(mem.available) ? mem.available : 0;
const swapUsedB = Number.isFinite(mem.swap_used) ? mem.swap_used : 0;
const ns = netSpeedSample();
const downBps = Number.isFinite(ns.down_bps) ? Math.max(0, ns.down_bps) : 0;
const upBps = Number.isFinite(ns.up_bps) ? Math.max(0, ns.up_bps) : 0;
history.ts.push(ts);
if (history.ts.length > L) history.ts.splice(0, history.ts.length - L);
pushHist("cpu1", cpu.load1, L);
pushHist("cpu5", cpu.load5, L);
pushHist("cpu15", cpu.load15, L);
pushHist("cpu_util", cpuUtilVal, L);
pushHist("gpu_util", gpuUtilVal, L);
pushHist("vram_used_b", vramUsedB, L);
pushHist("ram_used_b", ramUsedB, L);
pushHist("ram_free_b", ramFreeB, L);
pushHist("swap_used_b", swapUsedB, L);
pushHist("net_down_bps", downBps, L);
pushHist("net_up_bps", upBps, L);
flushHistoryToDisk(false);
}
loadHistoryFromDisk();
/* ============================================================================
Speedtest Controller
============================================================================ */
// Create controller that can run speedtests on demand / schedule (see speedtest-api.js)
const speedtest = createSpeedtestController({
timeoutMs: Number(process.env.SPEEDTEST_TIMEOUT_MS || 120000),
defaultIntervalMin: Number(process.env.SPEEDTEST_INTERVAL_MIN || 0),
});
// Tick speedtest scheduler (lightweight)
setInterval(() => {
try {
speedtest.tick();
} catch {}
}, 1000);
// Sample shared history continuously
setInterval(() => {
try {
sampleForHistory();
} catch {}
}, HISTORY_SAMPLE_MS);
/* ============================================================================
Small FS Helpers
============================================================================ */
// Check if a path exists and is accessible
function exists(p) {
try {
fs.accessSync(p);
return true;
} catch {
return false;
}
}
// Read a text file and trim it (or return null)
function readText(p) {
try {
return fs.readFileSync(p, "utf8").trim();
} catch {
return null;
}
}
// Read file as UTF-8 string (or null)
function safeReadFile(p) {
try {
return fs.readFileSync(p, "utf8");
} catch {
return null;
}
}
// Read file as Buffer (or null)
function safeReadBuf(p) {
try {
return fs.readFileSync(p);
} catch {
return null;
}
}
// List directory entries safely (or null)
function listDirSafe(p) {
try {
return fs.readdirSync(p);
} catch {
return null;
}
}
// Try reading the first non-empty text from a list of paths
function readTextFirst(paths) {
for (const p of paths) {
try {
if (fs.existsSync(p)) {
const v = fs.readFileSync(p, "utf8").trim();
if (v) return v;
}
} catch {}
}
return null;
}
// Check if a command exists in PATH
function which(cmd) {
try {
execSync(`command -v ${cmd}`, { stdio: ["ignore", "pipe", "ignore"] });
return true;
} catch {
return false;
}
}
// Detect if running inside a container (best-effort)
function inContainer() {
return fs.existsSync("/.dockerenv") || fs.existsSync("/run/.containerenv");
}
/* ============================================================================
System / BIOS / Battery
============================================================================ */
// Read BIOS firmware + version/date (container-friendly, best-effort)
function biosInfo() {
const firmware =
fs.existsSync("/sys/firmware/efi") || fs.existsSync("/host/sys/firmware/efi")
? "UEFI"
: "Legacy";
if (inContainer() && which("dmidecode")) {
try {
const version = execSync("dmidecode -s bios-version", { encoding: "utf8" }).trim();
const date = execSync("dmidecode -s bios-release-date", { encoding: "utf8" }).trim();
if (version || date) return { firmware, version: version || null, date: date || null };
} catch {}
}
const version = readTextFirst([
"/host/sys/class/dmi/id/bios_version",
"/sys/class/dmi/id/bios_version",
]);
const date = readTextFirst(["/host/sys/class/dmi/id/bios_date", "/sys/class/dmi/id/bios_date"]);
if (version || date) return { firmware, version: version || null, date: date || null };
return { firmware, version: null, date: null };
}
// List power_supply entries from sysfs
function listPowerSupplies() {
const base = "/sys/class/power_supply";
let names = [];
try {
names = fs.readdirSync(base);
} catch {
return [];
}
return names.map((name) => {
const dir = `${base}/${name}`;
const type = readText(`${dir}/type`);
const online = readText(`${dir}/online`);
const capacity = readText(`${dir}/capacity`);
const status = readText(`${dir}/status`);
return { name, dir, type, online, capacity, status };
});
}
// Return laptop battery info (filters out peripheral “batteries” like mice/headsets)
function batteryInfo() {
try {
const items = listPowerSupplies();
if (!items.length) return null;
const ac = items.find((x) => (x.type || "").toLowerCase() === "mains") || null;
const ac_online = ac?.online == null ? null : String(ac.online).trim() === "1";
const battCandidates = items.filter((x) => (x.type || "").toLowerCase() === "battery");
const isPeripheral = (name) =>
/hidpp|mouse|kbd|keyboard|headset|phone|bluetooth|wireless/i.test(name || "");
const bat = battCandidates.find((x) => !isPeripheral(x.name)) || null;
if (!bat) {
return { present: false, capacity_pct: null, status: null, ac_online };
}
const cap = bat.capacity != null ? Number(bat.capacity) : null;
const capacity_pct = Number.isFinite(cap) ? cap : null;
const status = bat.status || null;
return { present: true, capacity_pct, status, ac_online };
} catch {
return null;
}
}
/* ============================================================================
System / DMI (Manufacturer / Product / Serial)
============================================================================ */
// Read DMI field from /sys (prefers /host when available)
function readDmiField(name) {
return readTextFirst([
`/host/sys/class/dmi/id/${name}`,
`/sys/class/dmi/id/${name}`,
]);
}
// Basic system identity from DMI (best-effort, container-friendly)
function systemIdentity() {
const manufacturer = readDmiField("sys_vendor") || null;
const product_name = readDmiField("product_name") || null;
const system_version = readDmiField("product_version") || null;
const serial_number =
readDmiField("product_serial") ||
readDmiField("chassis_serial") ||
readDmiField("board_serial") ||
null;
const product_family = readDmiField("product_family") || null;
const product_sku = readDmiField("product_sku") || null;
const clean = (v) => {
const s = (v || "").trim();
if (!s) return null;
if (/^(none|unknown|to be filled by o\.e\.m\.|default string)$/i.test(s)) return null;
return s;
};
return {
manufacturer: clean(manufacturer),
product_name: clean(product_name),
system_version: clean(system_version),
serial_number: clean(serial_number),
product_family: clean(product_family),
product_sku: clean(product_sku),
};
}
/* ============================================================================
Host Session / Desktop Detection
- Best-effort detection; useful for UI “System” card
============================================================================ */
// Return the proc root to inspect (prefers /host/proc when mounted)
function hostProcRoot() {
if (exists("/host/proc/1")) return "/host/proc";
if (exists("/proc/1")) return "/proc";
return null;
}
// Try detecting host display server by checking host runtime files
function detectDisplayServerFromHost() {
const x11 =
exists("/host/tmp/.X11-unix") &&
fs.readdirSync("/host/tmp/.X11-unix").some((n) => /^X\d+$/.test(n));
let wayland = false;
try {
if (exists("/host/run/user")) {
const uids = (listDirSafe("/host/run/user") || []).filter((n) => /^\d+$/.test(n));
for (const uid of uids) {
const dir = `/host/run/user/${uid}`;
if (!exists(dir)) continue;
const hit = (listDirSafe(dir) || []).some((n) => n.startsWith("wayland-"));
if (hit) {
wayland = true;
break;
}
}
}
} catch {}
if (wayland) return "wayland";
if (x11) return "x11";
return null;
}
// Detect desktop environment by scanning process cmdlines for known markers
function detectDesktopFromProcCmdline() {
const markers = [
{ key: "GNOME", match: ["gnome-shell", "gnome-session"] },
{ key: "KDE", match: ["plasmashell", "ksmserver", "kwin_wayland", "kwin_x11"] },
{ key: "XFCE", match: ["xfce4-session"] },
{ key: "Cinnamon", match: ["cinnamon-session"] },
{ key: "MATE", match: ["mate-session"] },
{ key: "Sway", match: ["sway"] },
{ key: "Hyprland", match: ["hyprland"] },
{ key: "i3", match: ["i3", "i3bar"] },
{ key: "bspwm", match: ["bspwm"] },
{ key: "Openbox", match: ["openbox"] },
{ key: "Awesome", match: ["awesome"] },
{ key: "Qtile", match: ["qtile"] },
{ key: "Xmonad", match: ["xmonad"] },
];
const proc = hostProcRoot();
if (!proc) return null;
let pids = [];
try {
pids = fs.readdirSync(proc).filter((x) => /^\d+$/.test(x));
} catch {
return null;
}
for (const pid of pids) {
const cmdBuf = safeReadBuf(`${proc}/${pid}/cmdline`);
if (!cmdBuf?.length) continue;
const cmd = cmdBuf.toString("utf8").split("\0").filter(Boolean).join(" ");
if (!cmd) continue;
for (const m of markers) {
if (m.match.some((w) => cmd.includes(w))) return m.key;
}
}
return null;
}
// Parse /etc/os-release content into a key/value object
function parseOsRelease(txt) {
if (!txt) return null;
const out = {};
for (const line of txt.split("\n")) {
const m = line.match(/^([A-Z0-9_]+)=(.*)$/);
if (!m) continue;
let v = (m[2] || "").trim();
if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
v = v.slice(1, -1);
}
out[m[1]] = v;
}
return out;
}
// Parse a NUL-separated /proc/<pid>/environ buffer into an object
function parseEnviron(buf) {
if (!buf || !buf.length) return {};
const s = buf.toString("utf8");
const out = {};
for (const part of s.split("\0")) {
if (!part) continue;
const eq = part.indexOf("=");
if (eq <= 0) continue;
out[part.slice(0, eq)] = part.slice(eq + 1);
}
return out;
}
// Pick a “good enough” desktop/session env by scanning host processes
function pickSessionEnvFromHostProc() {
const proc = hostProcRoot();
if (!proc) return null;
let pids = [];
try {
pids = fs.readdirSync(proc).filter((x) => /^\d+$/.test(x));
} catch {
return null;
}
const wantedCmd = [
"gnome-session",
"plasmashell",
"ksmserver",
"xfce4-session",
"lxqt-session",
"cinnamon-session",
"mate-session",
"sway",
"hyprland",
];
for (const pid of pids) {
const base = `${proc}/${pid}`;
try {
const cmdBuf = safeReadBuf(`${base}/cmdline`);
if (!cmdBuf || !cmdBuf.length) continue;
const cmd = cmdBuf.toString("utf8").split("\0").filter(Boolean).join(" ");
if (!cmd) continue;
if (!wantedCmd.some((w) => cmd.includes(w))) continue;
const env = parseEnviron(safeReadBuf(`${base}/environ`));
const desktop =
(env.XDG_CURRENT_DESKTOP || env.DESKTOP_SESSION || env.GDMSESSION || "").trim() ||
null;
const sessionType = (env.XDG_SESSION_TYPE || "").trim() || null;
const displayServer = env.WAYLAND_DISPLAY ? "wayland" : env.DISPLAY ? "x11" : null;
if (desktop || sessionType || displayServer) {
return { desktop, session_type: sessionType, display_server: displayServer };
}
} catch {
continue;
}
}
let scanned = 0;
for (const pid of pids) {
if (scanned++ > 2500) break;
const base = `${proc}/${pid}`;
try {
const env = parseEnviron(safeReadBuf(`${base}/environ`));
if (!env || (!env.XDG_SESSION_TYPE && !env.XDG_CURRENT_DESKTOP && !env.DESKTOP_SESSION)) {
continue;
}
const desktop =
(env.XDG_CURRENT_DESKTOP || env.DESKTOP_SESSION || env.GDMSESSION || "").trim() ||
null;
const sessionType = (env.XDG_SESSION_TYPE || "").trim() || null;
const displayServer = env.WAYLAND_DISPLAY ? "wayland" : env.DISPLAY ? "x11" : null;
if (desktop || sessionType || displayServer) {
return { desktop, session_type: sessionType, display_server: displayServer };
}
} catch {
continue;
}
}
return null;
}
// Collect high-level system info (distro/kernel/desktop/session)
function systemInfo() {
const hostOsRel = safeReadFile("/host/etc/os-release");
const localOsRel = safeReadFile("/etc/os-release");
const osr = parseOsRelease(hostOsRel || localOsRel);
const distro = (osr && (osr.PRETTY_NAME || osr.NAME)) || (os.platform ? os.platform() : "linux");
let kernel = null;
try {
kernel = execSync("uname -r", { encoding: "utf8" }).trim();
} catch {}
const hostSess = pickSessionEnvFromHostProc();
const displayGuess = detectDisplayServerFromHost();
const xdgDesktop =
hostSess?.desktop ??
detectDesktopFromProcCmdline() ??
((process.env.XDG_CURRENT_DESKTOP || process.env.DESKTOP_SESSION || "").trim() || null);
const displayServer =
hostSess?.display_server ??
displayGuess ??
(process.env.WAYLAND_DISPLAY ? "wayland" : process.env.DISPLAY ? "x11" : null);
const sessionType =
(hostSess?.session_type ?? null) ||
((process.env.XDG_SESSION_TYPE || "").trim() || null) ||
displayServer ||
null;
return {
distro,
kernel,
arch: os.arch(),
platform: os.platform(),
hostname: os.hostname(),
desktop: xdgDesktop,
session_type: sessionType,
display_server: displayServer,
};
}
/* ============================================================================
Light Caching
============================================================================ */
let sysCache = null;
let sysCacheTs = 0;
const SYS_CACHE_MS = Number(process.env.SYS_CACHE_MS || 10000);
// Cached wrapper for systemInfo()
function systemInfoCached() {
const now = Date.now();
if (sysCache && now - sysCacheTs < SYS_CACHE_MS) return sysCache;
sysCache = systemInfo();
sysCacheTs = now;
return sysCache;
}
let disksCache = null;
let disksCacheTs = 0;
const DISK_CACHE_MS = Number(process.env.DISK_CACHE_MS || 4000);
// Cached dfBytes for configured disk paths
function disksCached() {
const now = Date.now();
if (disksCache && now - disksCacheTs < DISK_CACHE_MS) return disksCache;
const disks = {};
for (const p of DISK_PATHS) {
try {
const d = dfBytes(p);
disks[keyify(p)] = d;
} catch (e) {
disks[keyify(p)] = { path: p, error: String(e) };
}
}
disksCache = disks;
disksCacheTs = now;
return disksCache;
}
/* ============================================================================
Host Mountpoints
- Used to validate that requested paths are host-mounted (when in container)
============================================================================ */
// Convert mountinfo escaped sequences to real characters
function unescapeMountPath(p) {
return String(p || "")
.replace(/\\040/g, " ")
.replace(/\\011/g, "\t")
.replace(/\\012/g, "\n")
.replace(/\\134/g, "\\");
}
let hostMountMapCache = null;
let hostMountMapTs = 0;
const HOST_MOUNT_CACHE_MS = 3000;
// Read host mountpoints into a map: mountpoint -> { fstype, source, major_minor }
function readHostMountpointsMap() {
const now = Date.now();
if (hostMountMapCache && now - hostMountMapTs < HOST_MOUNT_CACHE_MS) {
return hostMountMapCache;
}
const map = new Map();
const mountinfoPath = exists("/host/proc/1/mountinfo")
? "/host/proc/1/mountinfo"
: exists("/proc/1/mountinfo")
? "/proc/1/mountinfo"
: exists("/proc/self/mountinfo")
? "/proc/self/mountinfo"
: null;
const mountsPath = exists("/host/proc/1/mounts")
? "/host/proc/1/mounts"
: exists("/proc/1/mounts")
? "/proc/1/mounts"
: exists("/proc/self/mounts")
? "/proc/self/mounts"
: null;
try {
if (!mountinfoPath) throw new Error("no mountinfo path");
const txt = fs.readFileSync(mountinfoPath, "utf8");
for (const line of txt.split("\n")) {
if (!line) continue;
const sep = line.indexOf(" - ");
if (sep < 0) continue;
const left = line.slice(0, sep).split(" ");
const right = line.slice(sep + 3).split(" ");
const majorMinor = (left[2] || "").trim();
const mp = unescapeMountPath(left[4]);
const fstype = (right[0] || "").trim();
const source = (right[1] || "").trim();
const normMp = mp ? mp.replace(/\/+$/, "") || "/" : null;
if (normMp) map.set(normMp, { fstype, source, major_minor: majorMinor || null });
}
} catch {
try {
if (!mountsPath) throw new Error("no mounts path");
const txt = fs.readFileSync(mountsPath, "utf8");
for (const line of txt.split("\n")) {
if (!line) continue;
const parts = line.split(" ");
const source = unescapeMountPath(parts[0]);
const mp = unescapeMountPath(parts[1]);
const fstype = (parts[2] || "").trim();
const normMp = mp ? mp.replace(/\/+$/, "") || "/" : null;
if (normMp) map.set(normMp, { fstype, source });
}
} catch {}
}
hostMountMapCache = map;
hostMountMapTs = now;
return map;
}
// Lookup host mount info for a path (exact mountpoint match)
function getHostMountInfo(pathStr) {
const norm = (p) => String(p || "").replace(/\/+$/, "") || "/";
const p = norm(pathStr);
const map = readHostMountpointsMap();
return map.get(p) || null;
}
// Check if a given path is mounted on the host (exact mountpoint match)
function isMountedOnHost(pathStr) {
return !!getHostMountInfo(pathStr);
}
/* ============================================================================
Disk
- df for disk usage + optional lsblk metadata (model/label/uuid)
============================================================================ */
let blkMetaCache = null;
let blkMetaTs = 0;
const BLK_META_CACHE_MS = Number(process.env.BLK_META_CACHE_MS || 15000);
// Normalize lsblk "NAME" into /dev/* path
function toDevPath(name) {
if (!name) return null;
const s = String(name).trim();
if (!s) return null;
return s.startsWith("/dev/") ? s : `/dev/${s}`;
}
// Infer parent disk device from a partition device path
function parentDevFromPart(devPath) {
const base = String(devPath || "");
if (!base.startsWith("/dev/")) return null;
const n = base.slice(5);
const mNvme = n.match(/^(nvme\d+n\d+)p\d+$/);
if (mNvme) return `/dev/${mNvme[1]}`;
const mMmc = n.match(/^(mmcblk\d+)p\d+$/);
if (mMmc) return `/dev/${mMmc[1]}`;
const mSd = n.match(/^(sd[a-z]+)\d+$/);
if (mSd) return `/dev/${mSd[1]}`;
return null;
}
// Query lsblk JSON and build a map from /dev/* -> {type, model, label, uuid}
function readLsblkMeta() {
try {
const out = execSync("lsblk -J -o NAME,TYPE,MODEL,LABEL,PARTLABEL,UUID", {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
}).trim();
if (!out) return new Map();
const j = JSON.parse(out);
const map = new Map();
function walk(node, parentDiskDev) {
const dev = toDevPath(node.name);
const type = (node.type || "").trim();
if (!dev) return;
if (type === "disk") {
const model = (node.model || "").trim();
map.set(dev, { dev, type, model, label: "", uuid: "" });
parentDiskDev = dev;
} else {
const label = (node.label || node.partlabel || "").trim();
const uuid = (node.uuid || "").trim();
const parentModel = parentDiskDev ? map.get(parentDiskDev)?.model || "" : "";
map.set(dev, { dev, type, model: parentModel, label, uuid });
}
if (Array.isArray(node.children)) {
for (const ch of node.children) walk(ch, parentDiskDev);
}
}
for (const n of j.blockdevices || []) walk(n, null);
return map;
} catch {
return new Map();
}
}
// Cached wrapper for readLsblkMeta()
function lsblkMetaCached() {
const now = Date.now();
if (blkMetaCache && now - blkMetaTs < BLK_META_CACHE_MS) return blkMetaCache;
blkMetaCache = readLsblkMeta();
blkMetaTs = now;
return blkMetaCache;
}
// Make a stable key from a path (used to flatten disk fields)
function keyify(p) {
return p.replace(/^\/+/, "").replace(/\//g, "_").replace(/[^\w]/g, "_");
}
// Run df and enrich with host mount + lsblk metadata
function dfBytes(pathStr) {
const isSpecial = pathStr === "/host" || pathStr === "/";
const expectHostMount = !isSpecial;
if (inContainer() && expectHostMount && !isMountedOnHost(pathStr)) {
throw new Error(`not mounted on host (${pathStr})`);
}
const out = execSync(`df -B1 -P -- ${JSON.stringify(pathStr)}`, { encoding: "utf8" }).trim();
const line = out.split("\n")[1] || "";
if (!line) throw new Error(`df returned no data (${pathStr})`);
const parts = line.split(/\s+/);
const total = Number(parts[1]);
const used = Number(parts[2]);
const free = Number(parts[3]);
const mount = parts[5] || pathStr;
const hostLookupPath = pathStr === "/host" ? "/" : (pathStr === "/" ? "/" : pathStr);
const mi = getHostMountInfo(hostLookupPath);
const fstype = mi?.fstype || null;
const source = mi?.source || null;
const major_minor = mi?.major_minor || null;
let blk_model = null;
let blk_label = null;
let blk_uuid = null;
try {
if (source && String(source).startsWith("/dev/")) {
const meta = lsblkMetaCached();
const hit = meta.get(source) || meta.get(toDevPath(source));
const parent = parentDevFromPart(source);
const parentHit = parent ? meta.get(parent) : null;
blk_model = (hit?.model || parentHit?.model || "").trim() || null;
blk_label = (hit?.label || "").trim() || null;
blk_uuid = (hit?.uuid || "").trim() || null;
}
} catch {}
const isSystem = pathStr === "/host" || pathStr === "/";
const stableKey = isSystem ? "__system__" : keyify(pathStr);
const label_key = isSystem ? "disk.label.system" : null;
const label = isSystem ? "System Disk" : mount;