-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsystemcheck.py
More file actions
1264 lines (1134 loc) · 51.5 KB
/
systemcheck.py
File metadata and controls
1264 lines (1134 loc) · 51.5 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Linux System Check — colorful hardware report with storage deep-dive.
Features
- System: vendor/model/version/serial, chassis; Motherboard: vendor/name/version/serial
- OS: pretty name, version/ID, kernel, architecture
- CPU: model/vendor/arch, cores, freq, utilization
- Memory: totals, usage, swap (per-DIMM modules intentionally not collected)
- GPU: adapters with vendor/model/driver; VRAM (and usage if NVIDIA tools available)
- Storage HW: per-disk model, vendor, size, transport, block sizes, TYPE (HDD/SSD/NVMe)
- Filesystems: per-mount capacity/usage + largest directories and largest files
- Output modes: TTY colored text (default), JSON (--json), Beautiful HTML (--html)
- Safety: timeouts for deep scans and configurable limits
"""
import argparse
import datetime as _dt
import heapq
import html
import json
import logging
import os
import re
import shutil
import subprocess
import sys
from typing import Any, Dict, List, Optional, Tuple
# Optional live metrics
try:
import psutil # type: ignore
except ImportError:
psutil = None # type: ignore
# Logging: default to WARNING so normal runs are quiet; set SYSTEMCHECK_DEBUG=1 for debug
_LOG = logging.getLogger("systemcheck")
def _init_logging(debug: bool = False) -> None:
level = logging.DEBUG if (debug or os.environ.get("SYSTEMCHECK_DEBUG")) else logging.WARNING
logging.basicConfig(
level=level,
format="%(name)s: %(levelname)s: %(message)s",
stream=sys.stderr,
)
# ---------------- Helpers ----------------
def which(cmd: str) -> bool:
return shutil.which(cmd) is not None
def sh(cmd: List[str], timeout: Optional[int] = None, input_text: Optional[str] = None) -> str:
try:
out = subprocess.check_output(
cmd,
input=input_text.encode() if input_text else None,
stderr=subprocess.DEVNULL,
timeout=timeout,
)
return out.decode(errors="replace")
except subprocess.TimeoutExpired:
_LOG.debug("Command timed out: %s", cmd)
return ""
except (subprocess.CalledProcessError, OSError, UnicodeDecodeError) as e:
_LOG.debug("Command failed: %s: %s", cmd, e)
return ""
def _run_allow_nonzero(
cmd: List[str], timeout: Optional[int] = None
) -> str:
"""Run command and return stdout even when exit code is non-zero (e.g. du/find with permission denied)."""
try:
r = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
timeout=timeout,
)
return r.stdout.decode(errors="replace") if r.stdout else ""
except subprocess.TimeoutExpired:
_LOG.debug("Command timed out: %s", cmd)
return ""
except (OSError, UnicodeDecodeError) as e:
_LOG.debug("Command failed: %s: %s", cmd, e)
return ""
def human_bytes(n: Optional[int]) -> str:
if n is None:
return "N/A"
units = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"]
i = 0
x = float(n)
while x >= 1024 and i < len(units) - 1:
x /= 1024.0
i += 1
return f"{x:.2f} {units[i]}"
def shlex_quote(s: str) -> str:
return "'" + s.replace("'", "'\"'\"'") + "'"
def parse_size_to_bytes(s: Optional[str]) -> Optional[int]:
if not s:
return None
s = s.strip()
if s.lower() in ("unknown", "no module installed"):
return None
m = re.match(r"(?i)\s*([\d.]+)\s*(b|kb|mb|gb|tb|pb)\s*$", s)
if not m:
return None
val = float(m.group(1))
unit = m.group(2).lower()
factor = {"b":1,"kb":1024,"mb":1024**2,"gb":1024**3,"tb":1024**4,"pb":1024**5}[unit]
return int(val * factor)
# ---------------- Colors for TTY ----------------
class Color:
def __init__(self, enabled: bool):
self.enabled = enabled and sys.stdout.isatty()
def code(self, s: str) -> str:
return s if self.enabled else ""
@property
def R(self): return self.code("\033[31m") # red
@property
def G(self): return self.code("\033[32m") # green
@property
def Y(self): return self.code("\033[33m") # yellow
@property
def B(self): return self.code("\033[34m") # blue
@property
def M(self): return self.code("\033[35m") # magenta
@property
def C(self): return self.code("\033[36m") # cyan
@property
def W(self): return self.code("\033[37m") # white
@property
def BOLD(self): return self.code("\033[1m")
@property
def DIM(self): return self.code("\033[2m")
@property
def RESET(self): return self.code("\033[0m")
# ---------------- Progress bar (TTY) ----------------
def progress_bar(pct: Optional[float], color: Color, width: int = 28) -> str:
c = color
if pct is None:
return f"Usage: {c.DIM}N/A{c.RESET}"
p = max(0.0, min(100.0, float(pct)))
filled = int(round((p / 100.0) * width))
empty = width - filled
col = c.G if p < 60 else (c.Y if p < 85 else c.R)
return f"[{col}{'■'*filled}{c.RESET}{'·'*empty}] {p:5.1f}%"
# ---------------- OS / System ----------------
def parse_os_release() -> Dict[str, str]:
d: Dict[str, str] = {}
path = "/etc/os-release"
if not os.path.exists(path):
return d
with open(path, "r", encoding="utf-8", errors="ignore") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, v = line.split("=", 1)
v = v.strip().strip('"').strip("'")
d[k] = v
return d
def get_os_info() -> Dict[str, Any]:
info: Dict[str, Any] = {
"name": None, "pretty_name": None, "version": None, "id": None, "id_like": None,
"kernel": None, "architecture": None,
}
osr = parse_os_release()
if osr:
info["pretty_name"] = osr.get("PRETTY_NAME")
info["name"] = osr.get("NAME")
info["version"] = osr.get("VERSION") or osr.get("VERSION_ID")
info["id"] = osr.get("ID")
info["id_like"] = osr.get("ID_LIKE")
if which("hostnamectl"):
txt = sh(["hostnamectl"], timeout=3)
if txt:
m = re.search(r"Operating System:\s*(.+)", txt)
if m and not info["pretty_name"]:
info["pretty_name"] = m.group(1).strip()
m = re.search(r"Kernel:\s*(.+)", txt)
if m:
info["kernel"] = m.group(1).strip()
m = re.search(r"Architecture:\s*(.+)", txt)
if m:
info["architecture"] = m.group(1).strip()
if which("lsb_release") and not info.get("pretty_name"):
out = sh(["lsb_release", "-a"], timeout=3)
if out:
desc = re.search(r"Description:\s*(.+)", out)
if desc:
info["pretty_name"] = desc.group(1).strip()
rel = re.search(r"Release:\s*(.+)", out)
if rel and not info["version"]:
info["version"] = rel.group(1).strip()
dist = re.search(r"Distributor ID:\s*(.+)", out)
if dist and not info["name"]:
info["name"] = dist.group(1).strip()
try:
u = os.uname()
if not info["kernel"]:
info["kernel"] = f"{u.sysname} {u.release}"
if not info["architecture"]:
info["architecture"] = u.machine
except OSError as e:
_LOG.debug("os.uname: %s", e)
return info
def read_dmi_file(name: str) -> Optional[str]:
path = f"/sys/devices/virtual/dmi/id/{name}"
try:
if os.path.exists(path):
with open(path, "r", encoding="utf-8", errors="ignore") as f:
val = f.read().strip()
return val if val and val != "None" else None
except OSError as e:
_LOG.debug("Cannot read DMI file %s: %s", path, e)
return None
def parse_dmidecode_sections(typ: str) -> List[str]:
txt = sh(["dmidecode", "-t", typ], timeout=5) if which("dmidecode") else ""
if not txt:
return []
blocks = [b.strip() for b in re.split(r"\n\s*\n", txt) if "Information" in b or "Device" in b]
return blocks
def get_system_info() -> Dict[str, Any]:
sys_vendor = read_dmi_file("sys_vendor")
product_name = read_dmi_file("product_name")
product_version = read_dmi_file("product_version")
product_serial = read_dmi_file("product_serial")
chassis_type = read_dmi_file("chassis_type")
chassis_vendor = read_dmi_file("chassis_vendor")
board_vendor = read_dmi_file("board_vendor")
board_name = read_dmi_file("board_name")
board_version = read_dmi_file("board_version")
board_serial = read_dmi_file("board_serial")
if not (sys_vendor and product_name):
for b in parse_dmidecode_sections("system"):
if not sys_vendor:
m = re.search(r"Manufacturer:\s*(.+)", b)
if m: sys_vendor = m.group(1).strip()
if not product_name:
m = re.search(r"Product Name:\s*(.+)", b)
if m: product_name = m.group(1).strip()
if not product_version:
m = re.search(r"Version:\s*(.+)", b)
if m: product_version = m.group(1).strip()
if not product_serial:
m = re.search(r"Serial Number:\s*(.+)", b)
if m: product_serial = m.group(1).strip()
if not (board_vendor and board_name):
for b in parse_dmidecode_sections("baseboard"):
if not board_vendor:
m = re.search(r"Manufacturer:\s*(.+)", b)
if m: board_vendor = m.group(1).strip()
if not board_name:
m = re.search(r"Product Name:\s*(.+)", b)
if m: board_name = m.group(1).strip()
if not board_version:
m = re.search(r"Version:\s*(.+)", b)
if m: board_version = m.group(1).strip()
if not board_serial:
m = re.search(r"Serial Number:\s*(.+)", b)
if m: board_serial = m.group(1).strip()
if which("lshw") and (not sys_vendor or not product_name):
out = sh(["lshw", "-class", "system", "-json"], timeout=5)
try:
data = json.loads(out) if out else None
except json.JSONDecodeError as e:
_LOG.debug("lshw JSON parse failed: %s", e)
data = None
if isinstance(data, dict):
sys_vendor = sys_vendor or data.get("vendor")
product_name = product_name or data.get("product")
product_version = product_version or data.get("version")
product_serial = product_serial or data.get("serial")
return {
"vendor": sys_vendor,
"product_name": product_name,
"product_version": product_version,
"serial": product_serial,
"chassis_vendor": chassis_vendor,
"chassis_type": chassis_type,
"motherboard": {
"vendor": board_vendor,
"name": board_name,
"version": board_version,
"serial": board_serial,
},
}
# ---------------- CPU ----------------
def get_cpu_info() -> Dict[str, Any]:
info: Dict[str, Any] = {
"model": None, "architecture": None, "vendor": None,
"logical_cores": None, "physical_cores": None,
"base_freq_hz": None, "max_freq_hz": None,
"current_utilization_percent": None,
}
if which("lscpu"):
out = sh(["lscpu", "-J"])
if out:
try:
data = json.loads(out)
kv = {i["field"].strip(":"): i["data"] for i in data.get("lscpu", [])}
info["model"] = kv.get("Model name") or kv.get("Model Name")
info["architecture"] = kv.get("Architecture")
info["vendor"] = kv.get("Vendor ID")
try:
info["logical_cores"] = int(kv.get("CPU(s)")) if kv.get("CPU(s)") else None
except (TypeError, ValueError):
pass
try:
sockets = int(kv.get("Socket(s)") or 1)
cores_per_socket = int(kv.get("Core(s) per socket") or 0)
info["physical_cores"] = sockets * cores_per_socket or None
except (TypeError, ValueError):
pass
def parse_freq(s: Optional[str]) -> Optional[int]:
if not s: return None
m = re.search(r"([\d.]+)\s*(MHz|GHz)", s)
if not m: return None
val = float(m.group(1))
return int(val * (1_000_000 if m.group(2) == "MHz" else 1_000_000_000))
info["base_freq_hz"] = parse_freq(kv.get("CPU MHz") or kv.get("CPU max MHz"))
info["max_freq_hz"] = parse_freq(kv.get("CPU max MHz"))
except (KeyError, TypeError, ValueError, json.JSONDecodeError) as e:
_LOG.debug("lscpu parse error: %s", e)
if (info["model"] is None) and os.path.exists("/proc/cpuinfo"):
try:
with open("/proc/cpuinfo", "r", encoding="utf-8", errors="ignore") as f:
txt = f.read()
m = re.search(r"^model name\s*:\s*(.+)$", txt, re.M)
v = re.search(r"^vendor_id\s*:\s*(.+)$", txt, re.M)
info["model"] = info["model"] or (m.group(1).strip() if m else None)
info["vendor"] = info["vendor"] or (v.group(1).strip() if v else None)
if info["logical_cores"] is None:
info["logical_cores"] = len(re.findall(r"^processor\s*:\s*\d+", txt, re.M))
except OSError as e:
_LOG.debug("Cannot read /proc/cpuinfo: %s", e)
if psutil:
try:
info["current_utilization_percent"] = psutil.cpu_percent(interval=0.5)
except (AttributeError, TypeError) as e:
_LOG.debug("psutil cpu_percent: %s", e)
try:
freq = psutil.cpu_freq()
if freq:
if not info["base_freq_hz"] and freq.min:
info["base_freq_hz"] = int(freq.min * 1_000_000)
if not info["max_freq_hz"] and freq.max:
info["max_freq_hz"] = int(freq.max * 1_000_000)
except (AttributeError, TypeError) as e:
_LOG.debug("psutil cpu_freq: %s", e)
try:
if info["physical_cores"] is None:
info["physical_cores"] = psutil.cpu_count(logical=False)
if info["logical_cores"] is None:
info["logical_cores"] = psutil.cpu_count(logical=True)
except (AttributeError, TypeError) as e:
_LOG.debug("psutil cpu_count: %s", e)
return info
# ---------------- Memory (totals only) ----------------
def get_memory_info() -> Dict[str, Any]:
info: Dict[str, Any] = {
"total_bytes": None, "available_bytes": None, "used_bytes": None, "free_bytes": None,
"usage_percent": None, "swap_total_bytes": None, "swap_used_bytes": None,
"swap_free_bytes": None, "swap_usage_percent": None,
}
if psutil:
try:
vm = psutil.virtual_memory()
info.update(dict(
total_bytes=int(vm.total), available_bytes=int(vm.available),
used_bytes=int(vm.used), free_bytes=int(vm.free), usage_percent=float(vm.percent)
))
except (AttributeError, TypeError, ValueError) as e:
_LOG.debug("psutil virtual_memory: %s", e)
try:
sm = psutil.swap_memory()
info.update(dict(
swap_total_bytes=int(sm.total), swap_used_bytes=int(sm.used),
swap_free_bytes=int(sm.free), swap_usage_percent=float(sm.percent)
))
except (AttributeError, TypeError, ValueError) as e:
_LOG.debug("psutil swap_memory: %s", e)
if info["total_bytes"] is None and os.path.exists("/proc/meminfo"):
kv: Dict[str, int] = {}
try:
with open("/proc/meminfo", "r", encoding="utf-8", errors="ignore") as f:
for line in f:
parts = line.split(":")
if len(parts) != 2:
continue
m = re.search(r"(\d+)\s*kB", parts[1])
if m:
kv[parts[0].strip()] = int(m.group(1)) * 1024
except OSError as e:
_LOG.debug("Cannot read /proc/meminfo: %s", e)
return info
total = kv.get("MemTotal")
avail = kv.get("MemAvailable", kv.get("MemFree"))
used = total - avail if total and avail else None
pct = (used / total * 100.0) if used and total else None
info.update(dict(
total_bytes=total, available_bytes=avail, used_bytes=used, free_bytes=kv.get("MemFree"),
usage_percent=pct, swap_total_bytes=kv.get("SwapTotal"), swap_free_bytes=kv.get("SwapFree"),
swap_used_bytes=(kv.get("SwapTotal", 0)-kv.get("SwapFree", 0)) if kv.get("SwapTotal") else None,
swap_usage_percent=((kv.get("SwapTotal", 0)-kv.get("SwapFree", 0))/kv.get("SwapTotal")*100.0)
if kv.get("SwapTotal") else None
))
return info
# ---------------- GPU ----------------
def parse_nvidia_smi() -> List[Dict[str, Any]]:
gpus: List[Dict[str, Any]] = []
if not which("nvidia-smi"):
return gpus
# Use list form to avoid shell injection; nvidia-smi is in PATH
out = sh(
["nvidia-smi", "--query-gpu=name,driver_version,memory.total,memory.used,memory.free,pci.bus_id", "--format=csv,noheader,nounits"],
timeout=4,
)
for line in out.splitlines():
parts = [p.strip() for p in line.split(",")]
if len(parts) < 6:
continue
name, driver, mem_total, mem_used, mem_free, bus = parts[:6]
def mib_to_bytes(x: str) -> Optional[int]:
try:
return int(float(x)) * 1024 * 1024
except (ValueError, TypeError):
return None
total_b = mib_to_bytes(mem_total)
used_b = mib_to_bytes(mem_used)
free_b = mib_to_bytes(mem_free)
pct = None
if total_b and used_b is not None:
try:
pct = used_b / total_b * 100.0
except (ZeroDivisionError, TypeError):
pct = None
gpus.append({
"vendor": "NVIDIA",
"model": name or None,
"driver": driver or None,
"bus": bus or None,
"vram_total_bytes": total_b,
"vram_used_bytes": used_b,
"vram_free_bytes": free_b,
"vram_usage_percent": pct,
"source": "nvidia-smi",
})
return gpus
def parse_lshw_display() -> List[Dict[str, Any]]:
if not which("lshw"):
return []
out = sh(["lshw", "-class", "display", "-json"], timeout=6)
gpus: List[Dict[str, Any]] = []
try:
data = json.loads(out) if out else None
except json.JSONDecodeError as e:
_LOG.debug("lshw display JSON parse failed: %s", e)
data = None
def walk(n):
if isinstance(n, dict):
yield n
for ch in n.get("children", []) or []:
yield from walk(ch)
elif isinstance(n, list):
for it in n:
yield from walk(it)
if data:
for node in walk(data):
if not isinstance(node, dict): continue
if node.get("class") != "display": continue
prod = node.get("product") or node.get("description")
vend = node.get("vendor")
drv = None
conf = node.get("configuration") or {}
if isinstance(conf, dict):
drv = conf.get("driver") or conf.get("driverversion")
size_b = node.get("size")
gpus.append({
"vendor": vend,
"model": prod,
"driver": drv,
"bus": node.get("businfo"),
"vram_total_bytes": int(size_b) if isinstance(size_b, int) else None,
"vram_used_bytes": None,
"vram_free_bytes": None,
"vram_usage_percent": None,
"source": "lshw",
})
return gpus
def parse_lspci_display() -> List[Dict[str, Any]]:
if not which("lspci"):
return []
# Run lspci and filter in Python to avoid shell
out = sh(["lspci", "-mm", "-nn"], timeout=4)
gpus: List[Dict[str, Any]] = []
display_keywords = ("vga", "3d", "display")
for line in out.splitlines():
line_lower = line.lower()
if not any(kw in line_lower for kw in display_keywords):
continue
m = re.search(r'^\S+\s+"[^"]+"\s+"([^"]+)"\s+"([^"]+)"', line)
vend = prod = None
if m:
vend = m.group(1)
prod = m.group(2)
else:
parts = line.split(": ", 1)
if len(parts) == 2:
prod = parts[1]
gpus.append({
"vendor": vend,
"model": prod,
"driver": None,
"bus": None,
"vram_total_bytes": None,
"vram_used_bytes": None,
"vram_free_bytes": None,
"vram_usage_percent": None,
"source": "lspci",
})
return gpus
def get_gpu_info() -> List[Dict[str, Any]]:
gpus = parse_nvidia_smi()
if not gpus:
gpus = parse_lshw_display()
if not gpus:
gpus = parse_lspci_display()
return gpus
# ---------------- Storage hardware & FS ----------------
def classify_disk(entry: Dict[str, Any]) -> str:
name = (entry.get("name") or "").lower()
tran = (entry.get("transport") or "").lower()
rota = entry.get("rota")
typ = (entry.get("type") or "").lower()
if name.startswith("nvme") or tran == "nvme":
return "NVMe SSD"
if typ == "rom":
return "Optical"
if rota == 0:
return "SSD"
if rota == 1:
return "HDD"
return "Disk"
def get_lsblk() -> Dict[str, Any]:
if not which("lsblk"):
return {}
out = sh(["lsblk", "-J", "-O"])
try:
return json.loads(out) if out else {}
except json.JSONDecodeError as e:
_LOG.debug("lsblk JSON parse failed: %s", e)
return {}
def normalize_devices(lsblk_json: Dict[str, Any]) -> List[Dict[str, Any]]:
devices: List[Dict[str, Any]] = []
for b in lsblk_json.get("blockdevices", []) or []:
if b.get("type") != "disk":
continue
dev = {
"name": b.get("name"),
"type": b.get("type"),
"model": b.get("model"),
"serial": b.get("serial"),
"vendor": b.get("vendor"),
"transport": b.get("tran"),
"rota": b.get("rota"),
"logical_block_size": b.get("log-sec") or b.get("LOG-SEC"),
"physical_block_size": b.get("phy-sec") or b.get("PHY-SEC"),
"size_bytes": b.get("size") if isinstance(b.get("size"), int) else None,
"children": [],
}
for c in b.get("children", []) or []:
dev["children"].append({
"name": c.get("name"),
"type": c.get("type"),
"fstype": c.get("fstype"),
"mountpoint": c.get("mountpoint"),
"size_bytes": c.get("size") if isinstance(c.get("size"), int) else None,
})
dev["class"] = classify_disk(dev)
devices.append(dev)
return devices
def get_mounts() -> List[Dict[str, Any]]:
mounts: List[Dict[str, Any]] = []
if psutil:
try:
for p in psutil.disk_partitions(all=False):
if p.fstype in ("tmpfs", "devtmpfs", "squashfs", "overlay"):
continue
try:
usage = psutil.disk_usage(p.mountpoint)
except (OSError, PermissionError) as e:
_LOG.debug("disk_usage %s: %s", p.mountpoint, e)
continue
mounts.append(dict(
mountpoint=p.mountpoint, device=p.device, fstype=p.fstype,
total_bytes=int(usage.total), used_bytes=int(usage.used),
free_bytes=int(usage.free), usage_percent=float(usage.percent)
))
except (AttributeError, OSError) as e:
_LOG.debug("psutil disk_partitions: %s", e)
if not mounts:
out = sh(["df", "-P", "-B1"])
for line in out.splitlines()[1:]:
parts = line.split()
if len(parts) < 6: continue
dev, total, used, avail, pct, mnt = parts[:6]
if dev.startswith("tmpfs") or dev.startswith("devtmpfs"):
continue
try:
mounts.append(dict(
mountpoint=mnt, device=dev, fstype=None,
total_bytes=int(total), used_bytes=int(used),
free_bytes=int(avail),
usage_percent=float(pct.strip("%")) if pct.endswith("%") else None
))
except (ValueError, TypeError):
continue
return mounts
# ---------------- Deep usage scan (largest dirs/files) ----------------
def largest_dirs(mountpoint: str, top: int, timeout: int) -> List[Tuple[int, str]]:
"""Return the top N largest directories (by total size) on the mount, any depth."""
if not which("du"):
return []
# -x: one filesystem; -B1: sizes in bytes; no -d: all directories recursively
# Use _run_allow_nonzero: du exits 1 on "Permission denied" but still prints valid data
out = _run_allow_nonzero(["du", "-x", "-B1", mountpoint], timeout=timeout)
rows: List[Tuple[int, str]] = []
mount_rstrip = mountpoint.rstrip("/")
for line in out.splitlines():
parts = line.strip().split("\t", 1)
if len(parts) != 2:
parts = line.strip().split(None, 1)
if len(parts) != 2:
continue
try:
size = int(parts[0])
path = parts[1].rstrip("/")
if path == mount_rstrip:
continue
rows.append((size, path))
except (ValueError, IndexError):
continue
rows.sort(key=lambda x: x[0], reverse=True)
return rows[:top]
def largest_files(mountpoint: str, top: int, timeout: int) -> List[Tuple[int, str]]:
"""Return the top N largest files on the mount. Uses heap so we only keep top N in memory."""
if not which("find"):
return []
top_n = max(1, int(top))
# Use _run_allow_nonzero: find can exit 1 on permission denied but still output valid lines
text = _run_allow_nonzero(
["find", mountpoint, "-xdev", "-type", "f", "-printf", r"%s\t%p\n"],
timeout=timeout,
)
if not text:
return []
# Min-heap: keep only top N by size (heap[0] = smallest of the top N)
heap: List[Tuple[int, str]] = []
for line in text.splitlines():
parts = line.strip().split("\t", 1)
if len(parts) != 2:
continue
try:
size = int(parts[0])
path = parts[1]
except ValueError:
continue
if len(heap) < top_n:
heapq.heappush(heap, (size, path))
elif size > heap[0][0]:
heapq.heapreplace(heap, (size, path))
heap.sort(key=lambda x: x[0], reverse=True)
return heap
# ---------------- Collect & Render (Text + JSON) ----------------
def collect_report(deep: bool, top_n: int, max_mounts: int, per_mount_timeout: int) -> Dict[str, Any]:
os_info = get_os_info()
sys_info = get_system_info()
storage_hw_raw = get_lsblk()
devices = normalize_devices(storage_hw_raw) if storage_hw_raw else []
mounts = get_mounts()
gpus = get_gpu_info()
scanned = 0
for m in mounts:
if not deep:
continue
# Skip remote/special filesystems (cannot reliably run du/find)
fstype = (m.get("fstype") or "").lower()
dev = (m.get("device") or "").lower()
if fstype.startswith("nfs") or fstype.startswith("cifs") or fstype in ("smbfs", "fuse.sshfs") or dev.startswith("overlay"):
continue
# Optional cap: max_mounts <= 0 means no limit (scan all local filesystems)
if max_mounts > 0 and scanned >= max_mounts:
continue
m["largest_dirs"] = [
{"path": p, "size_bytes": int(sz)}
for sz, p in largest_dirs(m["mountpoint"], top_n, per_mount_timeout)
]
m["largest_files"] = [
{"path": p, "size_bytes": int(sz)}
for sz, p in largest_files(m["mountpoint"], top_n, per_mount_timeout)
]
scanned += 1
return {
"generated_at": _dt.datetime.now().isoformat(timespec="seconds"),
"os": os_info,
"system": sys_info,
"cpu": get_cpu_info(),
"memory": get_memory_info(),
"gpu": gpus,
"storage": {"devices": devices, "mounts": mounts},
}
def render_text(report: Dict[str, Any], color: Color, top_n: int) -> str:
c = color
lines: List[str] = []
H = lambda s: f"{c.BOLD}{c.C}{s}{c.RESET}"
# Header timestamp
ts = report.get("generated_at")
if ts:
lines.append(f"{c.DIM}Generated at: {ts}{c.RESET}\n")
# System
sysi = report.get("system", {}) or {}
lines.append(H("Computer — System"))
lines.append(f"{c.BOLD}Vendor/Model:{c.RESET} {sysi.get('vendor') or 'N/A'} {sysi.get('product_name') or ''}".rstrip())
lines.append(f"{c.BOLD}Version:{c.RESET} {sysi.get('product_version') or 'N/A'} {c.DIM}Serial:{c.RESET} {sysi.get('serial') or 'N/A'}")
chv = sysi.get("chassis_vendor"); cht = sysi.get("chassis_type")
if chv or cht:
lines.append(f"{c.DIM}Chassis:{c.RESET} {chv or '—'} type={cht or '—'}")
mb = sysi.get("motherboard") or {}
lines.append(f"{c.BOLD}Motherboard:{c.RESET} {mb.get('vendor') or 'N/A'} {mb.get('name') or ''}".rstrip())
lines.append(f" {c.DIM}Version:{c.RESET} {mb.get('version') or 'N/A'} {c.DIM}Serial:{c.RESET} {mb.get('serial') or 'N/A'}\n")
# OS
osi = report.get("os", {}) or {}
lines.append(H("OS"))
pn = osi.get("pretty_name") or f"{osi.get('name') or 'N/A'} {osi.get('version') or ''}".strip()
lines.append(f"{c.BOLD}{pn}{c.RESET}")
lines.append(f"{c.DIM}Kernel:{c.RESET} {osi.get('kernel') or 'N/A'} {c.DIM}Arch:{c.RESET} {osi.get('architecture') or 'N/A'}\n")
# CPU
cpu = report.get("cpu", {})
lines.append(H("CPU"))
lines.append(f"{c.BOLD}Model:{c.RESET} {cpu.get('model') or 'N/A'}")
lines.append(f"{c.BOLD}Vendor:{c.RESET} {cpu.get('vendor') or 'N/A'} {c.DIM}Arch:{c.RESET} {cpu.get('architecture') or 'N/A'}")
lines.append(f"{c.BOLD}Cores:{c.RESET} {cpu.get('physical_cores') or 'N/A'} phys / {cpu.get('logical_cores') or 'N/A'} logical")
base = human_bytes(cpu.get("base_freq_hz")) if cpu.get("base_freq_hz") else "N/A"
mx = human_bytes(cpu.get("max_freq_hz")) if cpu.get("max_freq_hz") else "N/A"
lines.append(f"{c.BOLD}Freq:{c.RESET} base≈{base} max≈{mx}")
util = cpu.get("current_utilization_percent")
util_s = f"{util:.1f}%" if isinstance(util, (int, float)) else "N/A"
util_color = c.G if isinstance(util, (int, float)) and util < 60 else (c.Y if isinstance(util, (int, float)) and util < 85 else c.R)
lines.append(f"{c.BOLD}Util:{c.RESET} {util_color}{util_s}{c.RESET}\n")
# Memory (totals only)
mem = report.get("memory", {})
lines.append(H("Memory"))
lines.append(f"Total {c.BOLD}{human_bytes(mem.get('total_bytes'))}{c.RESET} "
f"Used {c.Y}{human_bytes(mem.get('used_bytes'))}{c.RESET} "
f"Free {c.G}{human_bytes(mem.get('free_bytes'))}{c.RESET} "
f"Avail {c.G}{human_bytes(mem.get('available_bytes'))}{c.RESET}")
mp = mem.get("usage_percent")
mp_s = f"{mp:.1f}%" if isinstance(mp, (int, float)) else "N/A"
lines.append(f"Usage: {c.BOLD}{mp_s}{c.RESET}")
lines.append(f"{c.DIM}Swap:{c.RESET} total {human_bytes(mem.get('swap_total_bytes'))}, "
f"used {human_bytes(mem.get('swap_used_bytes'))}, "
f"free {human_bytes(mem.get('swap_free_bytes'))}\n")
# GPU
lines.append(H("GPU"))
gpus = report.get("gpu") or []
if not gpus:
lines.append(f"{c.DIM}(No GPU adapters detected; consider installing lshw or NVIDIA drivers){c.RESET}\n")
else:
for g in gpus:
vram_total = human_bytes(g.get("vram_total_bytes"))
vram_used = human_bytes(g.get("vram_used_bytes"))
vram_free = human_bytes(g.get("vram_free_bytes"))
pct = g.get("vram_usage_percent")
usage = f"{pct:.1f}%" if isinstance(pct, (int, float)) else None
bar = progress_bar(pct, color) if isinstance(pct, (int, float)) else None
lines.append(f"- {c.BOLD}{g.get('vendor') or '—'} {g.get('model') or '—'}{c.RESET}")
lines.append(f" driver={g.get('driver') or '—'} bus={g.get('bus') or '—'} source={g.get('source') or '—'}")
if g.get("vram_total_bytes") is not None:
lines.append(f" VRAM: total={vram_total} used={vram_used} free={vram_free}" + (f" ({usage})" if usage else ""))
if bar:
lines.append(f" {bar}")
lines.append("")
# Storage hardware
lines.append(H("Storage — Hardware"))
devs = report.get("storage", {}).get("devices", []) or []
if not devs:
lines.append(f"{c.DIM}(lsblk not available or no disks detected){c.RESET}\n")
else:
for d in devs:
tclass = d.get("class") or "Disk"
color_map = {"NVMe SSD": c.M, "SSD": c.C, "HDD": c.Y, "Disk": c.W}
tcol = color_map.get(tclass, c.W)
lines.append(f"{tcol}{c.BOLD}/dev/{d.get('name')}{c.RESET} [{tclass}] "
f"{c.DIM}{d.get('transport') or ''}{' ' if d.get('transport') else ''}({d.get('vendor') or '—'}){c.RESET}")
lines.append(f" Model: {d.get('model') or 'N/A'} Serial: {d.get('serial') or 'N/A'}")
lines.append(f" Size: {human_bytes(d.get('size_bytes'))} "
f"Block: logical={d.get('logical_block_size') or 'N/A'}, physical={d.get('physical_block_size') or 'N/A'}")
ch = d.get("children") or []
if ch:
lines.append(f" {c.DIM}Partitions/LVs:{c.RESET}")
for cpart in ch:
mp = cpart.get("mountpoint") or "—"
lines.append(f" - {c.BOLD}{cpart.get('name')}{c.RESET} "
f"fs={cpart.get('fstype') or 'N/A'} size={human_bytes(cpart.get('size_bytes'))} mount={mp}")
lines.append("")
# Filesystems with deep usage
lines.append(H("Storage — Filesystems & Usage"))
mnts = report.get("storage", {}).get("mounts", []) or []
if not mnts:
lines.append(f"{c.DIM}(no mounts detected){c.RESET}")
for m in sorted(mnts, key=lambda x: x.get("mountpoint") or ""):
used_pct = m.get("usage_percent")
bar = progress_bar(used_pct if isinstance(used_pct, (int, float)) else None, color)
head = f"{c.BOLD}{m.get('mountpoint')}{c.RESET} " \
f"dev={m.get('device')} fs={m.get('fstype') or 'N/A'}\n" \
f" total={human_bytes(m.get('total_bytes'))} used={human_bytes(m.get('used_bytes'))} free={human_bytes(m.get('free_bytes'))}\n" \
f" {bar}"
lines.append(head)
ldirs = m.get("largest_dirs")
if isinstance(ldirs, list) and ldirs:
lines.append(f" {c.DIM}Largest directories:{c.RESET}")
for entry in ldirs:
lines.append(f" - {human_bytes(entry['size_bytes']).rjust(12)} {entry['path']}")
lf = m.get("largest_files")
if isinstance(lf, list) and lf:
lines.append(f" {c.DIM}Largest files:{c.RESET}")
for entry in lf:
lines.append(f" - {human_bytes(entry['size_bytes']).rjust(12)} {entry['path']}")
lines.append("")
return "\n".join(lines)
# ---------------- HTML Rendering ----------------
def _pct(v: Optional[float]) -> Optional[float]:
if v is None:
return None
try:
return max(0.0, min(100.0, float(v)))
except (TypeError, ValueError):
return None
def _usage_bar_html(pct: Optional[float]) -> str:
if pct is None:
return '<div class="bar bar-na" title="N/A">N/A</div>'
p = _pct(pct) or 0.0
# Color thresholds: green <60, amber <85, red otherwise
cls = "ok" if p < 60 else ("warn" if p < 85 else "bad")
return f'''
<div class="bar {cls}" aria-valuenow="{p:.1f}" aria-valuemin="0" aria-valuemax="100">
<div class="bar-fill" style="width:{p:.1f}%"></div>
<div class="bar-label">{p:.1f}%</div>
</div>'''.strip()
def escape(s: Any) -> str:
if s is None:
return "—"
return html.escape(str(s))
def render_html(report: Dict[str, Any], top_n: int) -> str:
ts = escape(report.get("generated_at"))
osi = report.get("os", {}) or {}
sysi = report.get("system", {}) or {}
cpu = report.get("cpu", {}) or {}
mem = report.get("memory", {}) or {}
gpus = report.get("gpu") or []
devs = (report.get("storage", {}) or {}).get("devices", []) or []
mnts = (report.get("storage", {}) or {}).get("mounts", []) or []
def human(n): return escape(human_bytes(n))
# Build device cards
dev_cards = []
for d in devs:
parts = []
parts.append(f'<div class="kv"><span>Device</span><span>/dev/{escape(d.get("name"))}</span></div>')
parts.append(f'<div class="kv"><span>Type</span><span>{escape(d.get("class") or "Disk")}</span></div>')
parts.append(f'<div class="kv"><span>Transport</span><span>{escape(d.get("transport"))}</span></div>')
parts.append(f'<div class="kv"><span>Vendor</span><span>{escape(d.get("vendor"))}</span></div>')
parts.append(f'<div class="kv"><span>Model</span><span>{escape(d.get("model"))}</span></div>')
parts.append(f'<div class="kv"><span>Serial</span><span>{escape(d.get("serial"))}</span></div>')
parts.append(f'<div class="kv"><span>Capacity</span><span>{human(d.get("size_bytes"))}</span></div>')
parts.append(f'<div class="kv"><span>Block Sizes</span><span>logical={escape(d.get("logical_block_size"))}, physical={escape(d.get("physical_block_size"))}</span></div>')
# partitions
ch = d.get("children") or []
if ch:
rows = []
for c in ch:
rows.append(f"<tr><td>{escape(c.get('name'))}</td><td>{escape(c.get('fstype'))}</td><td>{human(c.get('size_bytes'))}</td><td>{escape(c.get('mountpoint'))}</td></tr>")
parts.append(f'''
<table class="mini">
<thead><tr><th>Partition</th><th>FS</th><th>Size</th><th>Mount</th></tr></thead>
<tbody>{''.join(rows)}</tbody>
</table>''')
dev_cards.append(f'<div class="card">{"".join(parts)}</div>')
# Build filesystem cards
fs_cards = []
for m in sorted(mnts, key=lambda x: x.get("mountpoint") or ""):
used_pct = m.get("usage_percent")
bar = _usage_bar_html(used_pct if isinstance(used_pct, (int, float)) else None)
parts = []
parts.append(f'<div class="kv title"><span>{escape(m.get("mountpoint"))}</span><span>fs={escape(m.get("fstype"))} • dev={escape(m.get("device"))}</span></div>')
parts.append(f'<div class="kv"><span>Total</span><span>{human(m.get("total_bytes"))}</span></div>')
parts.append(f'<div class="kv"><span>Used</span><span>{human(m.get("used_bytes"))}</span></div>')
parts.append(f'<div class="kv"><span>Free</span><span>{human(m.get("free_bytes"))}</span></div>')
parts.append(bar)
ldirs = m.get("largest_dirs")
if isinstance(ldirs, list) and ldirs:
rows = []
for e in ldirs: