-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_dashboard.py
More file actions
6639 lines (6238 loc) · 359 KB
/
Copy pathgenerate_dashboard.py
File metadata and controls
6639 lines (6238 loc) · 359 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
"""
NOC Dashboard generator.
Collects all infra sources (stdlib only, per-source isolation) and renders a
single self-contained static HTML file (inline CSS + SVG, no external assets).
Run every 15 min via cron; served by a tiny http.server systemd unit on :8080.
Reuses the exact API patterns proven in morning_briefing.py and the report_*.py
cron scripts. One failed source never kills the page - it renders a degraded card.
"""
import base64, html, json, os, re, sqlite3, ssl, sys, time
import urllib.request, urllib.parse, http.cookiejar
from collections import Counter
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
ENV_PATH = os.environ.get("HERMES_ENV", os.path.expanduser("~/.noc-dashboard/.env"))
OUT_DIR = os.environ.get("NOC_OUT_DIR", os.path.expanduser("~/noc-dashboard-output"))
OUT_FILE = os.environ.get("NOC_OUT_FILE", os.path.join(OUT_DIR, "index.html"))
TIMEOUT = 15
CERT_WARN_DAYS = 30
DEFAULT_DASHBOARD_TITLE = "NOC Dashboard"
DEFAULT_DASHBOARD_SUBTITLE = "Infrastructure Monitoring"
STATE_DIR = os.environ.get("NOC_STATE_DIR", os.path.join(OUT_DIR, "state"))
CONFIG_FILE = os.environ.get("NOC_CONFIG_FILE", os.path.join(STATE_DIR, "config.json"))
HEALTH_DB_FILE = os.environ.get("NOC_HEALTH_DB", os.path.join(STATE_DIR, "health_history.sqlite3"))
CTX = ssl.create_default_context()
CTX.check_hostname = False
CTX.verify_mode = ssl.CERT_NONE
def load_dashboard_config():
cfg = {
"dashboard_title": DEFAULT_DASHBOARD_TITLE,
"dashboard_subtitle": DEFAULT_DASHBOARD_SUBTITLE,
"logo_url": "",
"timezone": "UTC",
"show_ticker_bar": True,
"date_format": "YYYY-MM-DD",
"clock_format": "24hr",
}
try:
with open(CONFIG_FILE, encoding="utf-8") as f:
raw = json.load(f)
if isinstance(raw, dict):
for key in cfg:
val = raw.get(key)
if key == "show_ticker_bar":
if isinstance(val, bool):
cfg[key] = val
elif isinstance(val, str):
cfg[key] = val.strip()
except FileNotFoundError:
pass
except Exception as e:
print(f"warn: dashboard config load failed: {type(e).__name__}: {str(e)[:80]}")
cfg["dashboard_title"] = cfg["dashboard_title"] or DEFAULT_DASHBOARD_TITLE
cfg["dashboard_subtitle"] = cfg["dashboard_subtitle"] or DEFAULT_DASHBOARD_SUBTITLE
cfg["timezone"] = cfg.get("timezone") or "UTC"
if not isinstance(cfg.get("show_ticker_bar"), bool):
cfg["show_ticker_bar"] = True
if cfg.get("date_format") not in ("MM/DD/YYYY", "DD/MM/YYYY", "YYYY-MM-DD"):
cfg["date_format"] = "YYYY-MM-DD"
if cfg.get("clock_format") not in ("12hr", "24hr"):
cfg["clock_format"] = "24hr"
return cfg
def dashboard_logo_html(cfg):
logo = (cfg.get("logo_url") or "").strip()
if not logo:
return ""
return f'<img class="brand-logo" src="{esc(logo)}" alt="Dashboard logo">'
def load_env(path):
d = {}
with open(path, encoding="utf-8", errors="replace") as f:
for line in f:
# Accept normal .env syntax plus the variants humans inevitably
# paste in: leading whitespace, optional "export", and spaces
# around '='. Last-wins for duplicate blocks / stale placeholders.
m = re.match(r'^\s*(?:export\s+)?([A-Za-z_]\w*)\s*=\s*(.*)$', line.rstrip("\n"))
if m:
d[m.group(1)] = m.group(2)
# Cron runs do not inherit Hermes' process environment, but manual runs can.
# Let real process env override file values without ever printing secrets.
d.update({k: v for k, v in os.environ.items() if k.startswith(("LIMACHARLIE_", "LIMA_CHARLIE_", "LC_"))})
return d
E = load_env(ENV_PATH)
def _env_first(*keys):
"""Return the first non-placeholder value from supported .env aliases."""
for key in keys:
val = E.get(key, "")
if val is None:
continue
val = str(val).strip().strip('"').strip("'")
if val and not val.startswith("<"):
return val
return ""
def _service_base_url(host_or_url, scheme="https", port=None):
"""Normalize .env host fields that may be bare hosts or full URLs."""
raw = str(host_or_url or "").strip().rstrip("/")
if not raw:
return ""
if raw.startswith("http://") or raw.startswith("https://"):
return raw
if port is not None and ":" not in raw:
raw = f"{raw}:{port}"
return f"{scheme}://{raw}"
def _b64(s):
return base64.b64encode(s.encode()).decode()
def req(url, headers=None, data=None, method=None, cookiejar=None):
h = dict(headers or {})
if isinstance(data, dict):
data = json.dumps(data).encode()
h.setdefault("Content-Type", "application/json")
elif isinstance(data, str):
data = data.encode()
r = urllib.request.Request(url, data=data, headers=h, method=method)
if cookiejar is not None:
opener = urllib.request.build_opener(
urllib.request.HTTPSHandler(context=CTX),
urllib.request.HTTPCookieProcessor(cookiejar))
resp = opener.open(r, timeout=TIMEOUT)
else:
resp = urllib.request.urlopen(r, timeout=TIMEOUT, context=CTX)
return resp.read().decode("utf-8", "replace")
def jget(url, headers=None, data=None, method=None, cookiejar=None):
return json.loads(req(url, headers, data, method, cookiejar))
def collect_system_tools_suite():
base = E.get("SYSTEM_TOOLS_URL", "http://192.0.2.237:10233").strip().rstrip("/")
d = {"state": "error", "status": "unknown", "app": "System Tools Suite",
"version": "?", "tool_count": 23, "url": base}
if not base:
d.update({"state": "degraded", "note": "SYSTEM_TOOLS_URL not set"})
return d
try:
health = jget(f"{base}/api/health")
status = str(health.get("status", "unknown")).lower()
d["status"] = status
d["app"] = health.get("app") or d["app"]
if isinstance(health.get("tool_count"), int):
d["tool_count"] = health["tool_count"]
elif isinstance(health.get("tools"), list):
d["tool_count"] = len(health["tools"])
d["state"] = "ok" if status == "ok" else "warn"
d["note"] = health.get("note") or "health endpoint responding"
try:
info = jget(f"{base}/openapi.json").get("info", {})
d["version"] = str(info.get("version") or d["version"])
except Exception:
pass
return d
except Exception as e:
d["error"] = str(e)[:160]
return d
def collect_speedtest():
speed_state_dir = os.environ.get(
"NOC_SPEEDTEST_STATE_DIR",
os.path.join(os.environ.get("NOC_OUT_DIR", OUT_DIR), "state"),
)
latest_path = os.path.join(speed_state_dir, "speedtest-latest.json")
history_path = os.path.join(speed_state_dir, "speedtest-history.jsonl")
d = {"state": "error", "download": None, "upload": None, "ping": None,
"history": [], "samples": 0, "latest_path": latest_path}
try:
with open(latest_path, encoding="utf-8") as f:
latest = json.load(f)
def num(key):
val = latest.get(key)
try:
return float(val)
except (TypeError, ValueError):
return None
d["download"] = num("download")
d["upload"] = num("upload")
d["ping"] = num("ping")
d["timestamp"] = latest.get("timestamp")
d["received_at"] = latest.get("received_at")
hist = []
try:
with open(history_path, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
h = json.loads(line)
hist.append({
"download": float(h.get("download")),
"upload": float(h.get("upload")),
"ping": float(h.get("ping")),
"timestamp": h.get("timestamp"),
"received_at": h.get("received_at"),
})
except Exception:
continue
except FileNotFoundError:
pass
d["history"] = hist[-24:]
d["samples"] = len(d["history"])
if d["download"] is None or d["upload"] is None or d["ping"] is None:
d["state"] = "degraded"
d["note"] = "latest speedtest JSON missing download/upload/ping"
else:
d["state"] = "ok"
if d["ping"] >= 80:
d["state"] = "warn"
return d
except FileNotFoundError:
d["state"] = "degraded"
d["note"] = "speedtest-latest.json not found"
return d
except Exception as e:
d["error"] = f"{type(e).__name__}: {str(e)[:140]}"
return d
def _docker_mux_decode(buf):
"""Decode Docker exec multiplexed stdout/stderr frames."""
if isinstance(buf, str):
buf = buf.encode()
out = bytearray()
i = 0
while i + 8 <= len(buf) and buf[i] in (0, 1, 2):
size = int.from_bytes(buf[i+4:i+8], "big")
out.extend(buf[i+8:i+8+size])
i += 8 + size
if not out:
out.extend(buf)
return out.decode("utf-8", "replace")
def _pmox_auth():
tid = E.get("PROXMOX_TOKEN_ID", "")
if "!" not in tid and "@pam" in tid:
tid = tid.replace("@pam", "@pam!")
sec = E.get("PROXMOX_TOKEN_SECRET", "")
return {"Authorization": f"PVEAPIToken={tid}={sec}"}
# ============================ COLLECTORS ============================
# Each returns a dict. 'state' in {ok, warn, crit, degraded, error} drives color.
def collect_proxmox():
d = {"state": "ok", "vms_running": 0, "vms_total": 0, "cpu": 0.0,
"mem_used": 0.0, "mem_total": 0.0, "node": "?", "uptime_d": 0,
"down_vms": [], "storage": []}
auth = _pmox_auth()
base = _service_base_url(E.get("PROXMOX_HOST", "192.0.2.251"), "https", 8006) + "/api2/json"
nodes = jget(f"{base}/nodes", auth)["data"]
node = None
for n in nodes:
node = n["node"]
d["node"] = node
d["cpu"] = round(n.get("cpu", 0) * 100, 1)
d["mem_used"] = round(n.get("mem", 0) / 1e9, 1)
d["mem_total"] = round(n.get("maxmem", 1) / 1e9, 1)
d["uptime_d"] = int(n.get("uptime", 0)) // 86400
vms = jget(f"{base}/nodes/{node}/qemu", auth)["data"]
if vms:
vms = [v for v in vms if str(v.get("template", 0)) not in ("1", "true", "True")]
run = [v for v in vms if v.get("status") == "running"]
d["vms_running"] = len(run)
d["vms_total"] = len(vms)
d["down_vms"] = sorted(
f"{v['vmid']} {v.get('name','')}".strip()
for v in vms if v.get("status") != "running")
if d["down_vms"]:
d["state"] = "warn"
elif d["vms_total"] >= 0 and d["vms_running"] == d["vms_total"]:
d["state"] = "ok"
else:
d["state"] = "degraded"
d["note"] = "token has no ACL grant (0 VMs visible)"
# storage
st = jget(f"{base}/nodes/{node}/storage", auth)["data"]
qnap_overrides = qnap_storage_overrides()
for s in st:
if not s.get("total"):
continue
name = s["storage"]
used, tot = s.get("used", 0), s.get("total", 1)
source = "proxmox"
# Proxmox reports the NFS mount backing share, not the NAS volume.
# For the QNAP-backed stores, replace it with direct QNAP volume usage.
if name in qnap_overrides:
used, tot = qnap_overrides[name]
source = "qnap"
pct = round(100 * used / tot, 1) if tot else 0
d["storage"].append({"name": name, "pct": pct,
"used_g": round(used / 1e9, 1),
"total_g": round(tot / 1e9, 1),
"source": source})
d["storage"].sort(key=lambda x: -x["pct"])
if any(s["pct"] > 85 for s in d["storage"]):
d["state"] = "crit" if d["state"] != "degraded" else d["state"]
return d
def _smart_raw_int(v):
m = re.search(r"-?\d+", str(v or ""))
return int(m.group(0)) if m else 0
def _smart_short_model(disk):
return (disk.get("model") or disk.get("serial") or disk.get("devpath") or "disk")[:26]
def collect_smart_health():
"""Read-only SMART/disk health via Proxmox API.
Proxmox exposes host physical disk SMART. VM disks are virtual block devices;
guest SMART is not exposed through Proxmox for those, so the tile states that
explicitly instead of hallucinating green health inside every VM.
"""
d = {"state": "ok", "checked": 0, "passed": 0, "warn": 0, "fail": 0,
"prefail": 0, "problems": [], "disks": [], "vm_disks": 0, "vm_note": ""}
auth = _pmox_auth()
base = _service_base_url(E.get("PROXMOX_HOST", "192.0.2.251"), "https", 8006) + "/api2/json"
nodes = jget(f"{base}/nodes", auth).get("data", [])
if not nodes:
return {"state": "degraded", "note": "no Proxmox nodes visible", "checked": 0,
"passed": 0, "warn": 0, "fail": 0, "prefail": 0, "problems": [], "disks": []}
critical_names = ("realloc", "pending", "uncorrect", "offline_uncorrect", "reported_uncorrect",
"command_timeout", "media_wearout", "media_and_data_integrity")
for n in nodes:
node = n.get("node")
if not node:
continue
try:
vms = jget(f"{base}/nodes/{urllib.parse.quote(node)}/qemu", auth).get("data", [])
for vm in vms:
try:
cfg = jget(f"{base}/nodes/{urllib.parse.quote(node)}/qemu/{vm.get('vmid')}/config", auth).get("data", {})
d["vm_disks"] += sum(1 for k in cfg if re.match(r"^(ide|sata|scsi|virtio)\d+$", k))
except Exception:
pass
except Exception:
pass
disks = jget(f"{base}/nodes/{urllib.parse.quote(node)}/disks/list", auth).get("data", [])
for disk in disks:
dev = disk.get("devpath")
if not dev:
continue
rec = {"node": node, "dev": dev, "model": _smart_short_model(disk),
"health": disk.get("health") or "UNKNOWN", "wearout": disk.get("wearout"),
"issues": []}
d["checked"] += 1
health = str(rec["health"]).upper()
if health in ("PASSED", "OK", "GOOD"):
d["passed"] += 1
elif health in ("UNKNOWN", "N/A", ""):
d["warn"] += 1
rec["issues"].append("SMART health unknown")
else:
d["fail"] += 1
rec["issues"].append(f"SMART health {rec['health']}")
try:
url = f"{base}/nodes/{urllib.parse.quote(node)}/disks/smart?disk={urllib.parse.quote(dev, safe='')}"
sm = jget(url, auth).get("data", {})
txt = sm.get("text", "") or ""
attrs = sm.get("attributes", []) or []
for a in attrs:
name = str(a.get("name", ""))
fail = str(a.get("fail", "-")).strip()
flags = str(a.get("flags", ""))
raw = _smart_raw_int(a.get("raw"))
is_prefail = flags.startswith("P") or flags.startswith("PO")
if is_prefail:
d["prefail"] += 1
lname = name.lower()
if fail and fail != "-":
rec["issues"].append(f"{name} {fail}")
elif raw > 0 and any(x in lname for x in critical_names):
rec["issues"].append(f"{name} raw={raw}")
# NVMe text-only SMART checks.
m = re.search(r"Critical Warning:\s*(0x[0-9a-fA-F]+|\d+)", txt)
if m and int(m.group(1), 0) != 0:
rec["issues"].append(f"NVMe critical warning {m.group(1)}")
m = re.search(r"Media and Data Integrity Errors:\s*([\d,]+)", txt)
if m and int(m.group(1).replace(",", "")) > 0:
rec["issues"].append(f"NVMe media errors {m.group(1)}")
m = re.search(r"Temperature:\s*(\d+)\s+Celsius", txt)
if m and int(m.group(1)) >= 70:
rec["issues"].append(f"temperature {m.group(1)}C")
except Exception as e:
d["warn"] += 1
rec["issues"].append(f"SMART detail unavailable: {type(e).__name__}")
if rec["issues"]:
d["problems"].append(f"{rec['model']} {dev}: " + "; ".join(rec["issues"][:3]))
d["disks"].append(rec)
if not d["checked"]:
d["state"] = "degraded"
d["note"] = "no SMART-capable disks returned by Proxmox"
elif d["fail"] or any("raw=" in p or "critical" in p.lower() for p in d["problems"]):
d["state"] = "crit"
elif d["warn"] or d["problems"]:
d["state"] = "warn"
elif d["passed"] == d["checked"] and not d["problems"]:
# VM disks are virtual and their guest SMART is unobservable from
# Proxmox. That is informational; it must not turn a clean host disk
# result into a grey/degraded card.
d["state"] = "ok"
if d["vm_disks"]:
d["vm_note"] = f'{d["vm_disks"]} VM virtual disk(s); guest SMART not exposed by Proxmox'
return d
def collect_hyperv():
"""Hyper-V host via WinRM/NTLM. VM list + host resource summary."""
host = E.get("HYPERV_HOST", "").strip()
user = E.get("HYPERV_USERNAME", "").strip()
pwd = E.get("HYPERV_PASSWORD", "").strip()
base = {"vms": [], "vm_count": 0, "running": 0, "stopped": 0,
"host_cpus": "?", "host_mem_gb": "?"}
if not host or not user or not pwd or pwd.startswith("<"):
return {**base, "state": "degraded", "note": "Hyper-V creds not configured"}
try:
import winrm
except ImportError:
return {**base, "state": "error", "note": "pywinrm not installed"}
try:
sess = winrm.Session(host, auth=(user, pwd), transport="ntlm",
server_cert_validation="ignore",
operation_timeout_sec=20, read_timeout_sec=25)
ps_vms = (
"try { $vms = Get-VM | Select-Object Name, State, CPUUsage, "
"@{N='MemGB';E={[math]::Round($_.MemoryAssigned/1GB,2)}}; "
"if ($vms -eq $null) { Write-Output '[]' } "
"else { ConvertTo-Json -InputObject @($vms) -Depth 3 } "
"} catch { Write-Output '[]' }"
)
r_vms = sess.run_ps(ps_vms)
if r_vms.status_code != 0:
err = (r_vms.std_err or b"").decode("utf-8", "replace")[:180].strip()
return {**base, "state": "error", "note": f"WinRM error: {err or 'unknown'}"}
raw = (r_vms.std_out or b"").decode("utf-8", "replace").strip()
try:
import json as _j
vms_raw = _j.loads(raw) if raw else []
except Exception:
vms_raw = []
if isinstance(vms_raw, dict):
vms_raw = [vms_raw]
ps_host = (
"try { $h = Get-VMHost | Select-Object LogicalProcessorCount,"
"@{N='MemGB';E={[math]::Round($_.MemoryCapacity/1GB,0)}}; "
"ConvertTo-Json -InputObject $h } catch { Write-Output '{}' }"
)
r_host = sess.run_ps(ps_host)
host_raw = (r_host.std_out or b"").decode("utf-8", "replace").strip()
try:
import json as _j
host_info = _j.loads(host_raw) if host_raw else {}
except Exception:
host_info = {}
if isinstance(host_info, list):
host_info = host_info[0] if host_info else {}
vms, running, stopped = [], 0, 0
for vm in vms_raw:
if not isinstance(vm, dict):
continue
sr = str(vm.get("State", "")).strip()
if sr in ("2", "Running"):
vs, running = "Running", running + 1
elif sr in ("3", "Off"):
vs, stopped = "Off", stopped + 1
else:
vs, stopped = sr or "Unknown", stopped + 1
vms.append({"name": str(vm.get("Name", "?")), "state": vs,
"cpu": float(vm.get("CPUUsage", 0) or 0),
"mem_gb": float(vm.get("MemGB", 0) or 0)})
state = "error" if (not vms and not host_info) else ("warn" if stopped > 0 else "ok")
return {"state": state, "vm_count": len(vms), "running": running,
"stopped": stopped, "vms": vms,
"host_cpus": host_info.get("LogicalProcessorCount", "?"),
"host_mem_gb": host_info.get("MemGB", "?")}
except Exception as e:
return {**base, "state": "error", "note": f"{type(e).__name__}: {str(e)[:140]}"}
def collect_docker():
d = {"state": "ok", "running": 0, "total": 0, "envs": 0, "bad": []}
base = E.get("PORTAINER_URL", "").strip().rstrip("/")
user = E.get("PORTAINER_USERNAME", "").strip()
pw = E.get("PORTAINER_PASSWORD", "").strip()
if not base or not user or not pw or pw.startswith("<"):
return {"state": "degraded", "note": "Portainer creds not set", "running": 0, "total": 0}
jwt = jget(f"{base}/api/auth", data={"Username": user, "Password": pw}, method="POST")["jwt"]
auth = {"Authorization": f"Bearer {jwt}"}
endpoints = jget(f"{base}/api/endpoints", auth)
d["envs"] = len(endpoints)
for ep in endpoints:
epid = ep.get("Id")
try:
cs = jget(f"{base}/api/endpoints/{epid}/docker/containers/json?all=1", auth)
except Exception as e:
d["bad"].append(f"{ep.get('Name', epid)} unreachable: {type(e).__name__}")
continue
run = [c for c in cs if c.get("State") == "running"]
d["running"] += len(run)
d["total"] += len(cs)
for c in cs:
nm = c.get("Names", ["?"])[0].lstrip("/")
if "unhealthy" in c.get("Status", "").lower():
d["bad"].append(f"UNHEALTHY {nm}")
elif c.get("State") != "running":
d["bad"].append(f"down {nm}")
if d["bad"]:
d["state"] = "warn"
return d
def collect_pbs():
d = {"state": "ok", "ok": 0, "fail": 0, "run": 0, "last_backup": "?", "datastores": []}
tk = jget("https://192.0.2.77:8007/api2/json/access/ticket",
data=urllib.parse.urlencode({
"username": E.get("PBS_USERNAME", "root@pam"),
"password": E.get("PBS_PASSWORD", "")}),
headers={"Content-Type": "application/x-www-form-urlencoded"},
method="POST")["data"]["ticket"]
cookie = {"Cookie": f"PBSAuthCookie={urllib.parse.quote(tk, safe='')}"}
since = int(time.time()) - 86400
tasks = jget(f"https://192.0.2.77:8007/api2/json/nodes/localhost/tasks"
f"?since={since}&limit=500", cookie)["data"]
last_backup_epoch = 0
for t in tasks:
s = t.get("status", "running")
wt = t.get("worker_type", "")
if s == "running" or "endtime" not in t:
d["run"] += 1
elif s == "OK":
d["ok"] += 1
if wt == "backup" and t.get("endtime", 0) > last_backup_epoch:
last_backup_epoch = t.get("endtime", 0)
else:
d["fail"] += 1
if last_backup_epoch:
ago_h = (time.time() - last_backup_epoch) / 3600
d["last_backup"] = (f"{ago_h:.1f}h ago" if ago_h < 48
else f"{ago_h/24:.1f}d ago")
if ago_h > 26:
d["state"] = "warn"
else:
d["last_backup"] = "none in 24h"
d["state"] = "warn"
if d["fail"]:
d["state"] = "crit"
# datastore usage
try:
dss = jget("https://192.0.2.77:8007/api2/json/status/datastore-usage", cookie)["data"]
for ds in dss:
tot = ds.get("total", 0) or 0
used = ds.get("used", 0) or 0
pct = round(100 * used / tot, 1) if tot else 0
d["datastores"].append({"name": ds.get("store", "?"), "pct": pct})
except Exception:
pass
return d
def collect_uptime_kuma():
"""Uptime Kuma monitor status via per-monitor SQLite queries through Portainer exec.
Kuma 1.23 does not emit monitor_status in /metrics when the heartbeat b-tree
index is partially corrupted. We collect cert data from /metrics (which still
works) and get actual UP/DOWN status by querying the heartbeat table one
monitor at a time (bypassing the corrupted composite index).
"""
d = {"state": "ok", "up": 0, "total": 0, "down": [], "other": [], "certs": []}
base = E.get("UPTIME_KUMA_URL", "").strip().rstrip("/")
key = E.get("UPTIME_KUMA_API_KEY", "").strip()
if not base or not key or key.startswith("<"):
return {"state": "degraded", "note": "Uptime Kuma key not set", "up": 0, "total": 0,
"down": [], "other": [], "certs": []}
# --- Cert data from /metrics (still works even with corrupted heartbeat index) ---
cert_days, cert_valid = {}, {}
try:
auth = {"Authorization": "Basic " + _b64(f":{key}")}
text = req(f"{base}/metrics", auth)
for line in text.splitlines():
if not line or line[0] == "#":
continue
m = re.search(r'monitor_name="([^"]*)"', line)
if not m:
continue
name = m.group(1)
try:
val = float(line.rsplit("}", 1)[1])
except (ValueError, IndexError):
continue
if line.startswith("monitor_cert_days_remaining{"):
cert_days[name] = val
elif line.startswith("monitor_cert_is_valid{"):
cert_valid[name] = val
except Exception:
pass # cert data is optional; status comes from SQLite below
for k, days in cert_days.items():
valid = cert_valid.get(k, 1) == 1
d["certs"].append({"name": k, "days": int(days), "valid": valid})
d["certs"].sort(key=lambda x: x["days"])
# --- Actual UP/DOWN status via per-monitor SQLite heartbeat queries ---
try:
pbase = E.get("PORTAINER_URL", "").strip().rstrip("/")
puser = E.get("PORTAINER_USERNAME", "").strip()
ppw = E.get("PORTAINER_PASSWORD", "").strip()
if not (pbase and puser and ppw and not ppw.startswith("<")):
raise ValueError("Portainer creds missing")
jwt = jget(f"{pbase}/api/auth", data={"Username": puser, "Password": ppw}, method="POST")["jwt"]
ph = {"Authorization": f"Bearer {jwt}"}
cid = None
epid_used = None
for ep in jget(f"{pbase}/api/endpoints", ph):
epid = ep.get("Id")
cs = jget(f"{pbase}/api/endpoints/{epid}/docker/containers/json?all=1", ph)
cid = next((c.get("Id") for c in cs
if "uptime-kuma" in "/".join(c.get("Names") or []).lower()
or "uptime-kuma" in str(c.get("Image", "")).lower()), None)
if cid:
epid_used = epid
break
if not cid:
raise RuntimeError("uptime-kuma container not found via Portainer")
def _kuma_exec(cmd_list):
ex = jget(f"{pbase}/api/endpoints/{epid_used}/docker/containers/{urllib.parse.quote(cid)}/exec",
ph, {"AttachStdout": True, "AttachStderr": True, "Tty": True, "Cmd": cmd_list}, "POST")
raw = req(f"{pbase}/api/endpoints/{epid_used}/docker/exec/{urllib.parse.quote(ex['Id'])}/start",
ph, {"Detach": False, "Tty": True}, "POST")
return re.sub(r"[^\x20-\x7e\n|]", "", raw if isinstance(raw, str) else raw.decode("utf-8", "replace")).strip()
# Get all active monitors (monitor table is intact)
monitors_raw = _kuma_exec(["sqlite3", "-separator", "|", "/app/data/kuma.db",
"SELECT id,name FROM monitor WHERE active=1 ORDER BY name;"])
monitors = []
for line in monitors_raw.splitlines():
parts = line.strip().split("|")
if len(parts) >= 2:
try:
monitors.append((int(parts[0]), parts[1]))
except (ValueError, IndexError):
pass
if not monitors:
raise RuntimeError("no active monitors found in Kuma DB")
# Per-monitor heartbeat query — avoids corrupted composite index
SMAP_INT = {"0": "DOWN", "1": "UP", "2": "PENDING", "3": "MAINT"}
status = {} # name -> "UP"/"DOWN"/"PENDING"/"MAINT"/"unknown"
for mid, name in monitors:
q = f"SELECT status FROM heartbeat WHERE monitor_id={mid} ORDER BY id DESC LIMIT 1;"
out = _kuma_exec(["sqlite3", "/app/data/kuma.db", q]).strip()
if out and "error" not in out.lower() and "malformed" not in out.lower():
status[name] = SMAP_INT.get(out, f"?{out}")
else:
status[name] = "unknown"
d["total"] = len(monitors)
d["up"] = sum(1 for v in status.values() if v == "UP")
d["down"] = sorted(k for k, v in status.items() if v == "DOWN")
other_raw = [[k, v] for k, v in status.items() if v not in ("UP", "DOWN", "unknown")]
unknown = [k for k, v in status.items() if v == "unknown"]
d["other"] = sorted(other_raw)
d["status_map"] = {k: (1 if v == "UP" else 0 if v == "DOWN" else 2) for k, v in status.items()}
d["source"] = "sqlite"
if unknown:
d["note"] = f"{len(unknown)} monitor(s) status unreadable (DB corruption): {', '.join(unknown[:4])}"
if d["down"]:
d["state"] = "crit"
elif d["other"] or unknown:
d["state"] = "warn"
except Exception as e:
d["state"] = "degraded"
d["note"] = f"Kuma status unavailable: {type(e).__name__}: {e}"
return d
def collect_crowdsec():
d = {"state": "ok", "bans": 0, "local_bans": 0, "detections_24h": None, "top": []}
apikey = E.get("CROWDSEC_API_KEY", "")
dec = jget("http://192.0.2.237:18080/v1/decisions", {"X-Api-Key": apikey})
if isinstance(dec, list):
d["bans"] = len(dec)
local = [x for x in dec if x.get("origin") not in ("lists", "CAPI")]
d["local_bans"] = len(local)
scen = Counter(x.get("scenario", "?").split("/")[-1] for x in local)
d["top"] = [[k, v] for k, v in scen.most_common(3) if k != "?"]
# local detections 24h via watcher (creds usually empty -> stays None)
mu = E.get("CROWDSEC_MACHINE_USER", "")
mp = E.get("CROWDSEC_MACHINE_PASS", "")
if mu and mp:
try:
tok = jget("http://192.0.2.237:18080/v1/watchers/login",
{"Content-Type": "application/json"},
json.dumps({"machine_id": mu, "password": mp}).encode(), "POST")["token"]
alerts = jget("http://192.0.2.237:18080/v1/alerts?since=24h&limit=500",
{"Authorization": "Bearer " + tok})
if isinstance(alerts, list):
def is_local(a):
scope = (a.get("source", {}) or {}).get("scope", "") or ""
scen = a.get("scenario", "") or ""
return not scen.startswith("update :") and scope in ("Ip", "Range")
d["detections_24h"] = sum(1 for a in alerts if is_local(a))
except Exception:
d["detections_24h"] = None
return d
def collect_wazuh():
d = {"state": "ok", "active": 0, "total": 0, "down": []}
jwt = req("https://192.0.2.233:55000/security/user/authenticate?raw=true",
{"Authorization": "Basic " + _b64(
f"{E.get('WAZUH_API_USER','wazuh')}:{E.get('WAZUH_API_PASSWORD','')}")}).strip()
ag = jget("https://192.0.2.233:55000/agents?limit=500",
{"Authorization": f"Bearer {jwt}"})["data"]["affected_items"]
d["total"] = len(ag)
d["active"] = sum(1 for a in ag if a.get("status") == "active")
d["down"] = [f"{a.get('id')} {a.get('name','')}".strip()
for a in ag if a.get("status") != "active"]
if d["down"]:
d["state"] = "warn"
# alert volume from the indexer (last 24h). Manager API has no per-alert
# severity; that lives only in wazuh-alerts-*. Degrade silently if missing.
iu = E.get("WAZUH_INDEXER_USER", "").strip()
ip = E.get("WAZUH_INDEXER_PASS", "").strip()
if iu and ip:
ix = E.get("WAZUH_INDEXER_HOST", "https://192.0.2.233:9200").rstrip("/")
try:
q = {"size": 0,
"query": {"bool": {"filter": [
{"range": {"@timestamp": {"gte": "now-24h"}}}]}},
"aggs": {"hi": {"filter": {"range": {"rule.level": {"gte": 12}}}}}}
res = jget(f"{ix}/wazuh-alerts-*/_search",
{"Authorization": "Basic " + _b64(f"{iu}:{ip}")}, data=q,
method="POST")
tot = res.get("hits", {}).get("total", {})
d["alerts_24h"] = tot.get("value", tot) if isinstance(tot, dict) else tot
d["high_24h"] = res.get("aggregations", {}).get("hi", {}).get("doc_count", 0)
if d["high_24h"]:
d["state"] = "crit"
except Exception as e:
d["alerts_err"] = f"{type(e).__name__}"
return d
def collect_malware_sources():
"""Detection-source tiles (read-only) from the Wazuh indexer, last 24h.
Liveness is EXPLICIT, never inferred from alert counts (zero alerts must not
masquerade as "installed and clean" on a security tile). Each source carries
{live: bool, count: int|None}:
- not live -> render "—" (pending install/enrollment)
- live, 0 -> render "0" (installed, no detections in 24h)
- live, >0 -> render the count in warn (active detections)
Flip MALWARE_SOURCE_LIVE[<src>] = True as each source is actually installed
and confirmed emitting (ClamAV/YARA Tasks 1-2; Defender = Windows task)."""
# ---- explicit per-source liveness registry (data layer, not count-derived) ----
MALWARE_SOURCE_LIVE = {
"clamav": True, # live on 233 + 251 (EICAR -> rule 52502 confirmed 2026-06-09)
"yara": True, # live on 233 + 251 (EICAR -> rule 108001 confirmed 2026-06-09)
"virustotal": True, # already integrated and flowing
"defender": False, # -> True after Defender->Wazuh enrollment (Windows task)
}
SRC_QUERY = {
# Built-in 0320 ClamAV rules use groups clamd/freshclam/virus (NOT "clamav").
# Match the clamd group (covers detections rule 52502/52511 + daemon events).
"clamav": {"term": {"rule.groups": "clamd"}},
"yara": {"term": {"rule.groups": "yara"}},
"virustotal": {"term": {"rule.groups": "virustotal"}},
"defender": {"match_phrase": {
"data.win.system.providerName": "Microsoft-Windows-Windows Defender"}},
}
d = {"state": "ok",
"sources": {k: {"live": v, "count": None}
for k, v in MALWARE_SOURCE_LIVE.items()}}
iu = E.get("WAZUH_INDEXER_USER", "").strip()
ip = E.get("WAZUH_INDEXER_PASS", "").strip()
if not (iu and ip):
d["state"] = "degraded"
d["note"] = "indexer creds not set"
return d
ix = E.get("WAZUH_INDEXER_HOST", "https://192.0.2.233:9200").rstrip("/")
auth = {"Authorization": "Basic " + _b64(f"{iu}:{ip}")}
def cnt(extra):
q = {"size": 0, "query": {"bool": {"filter": [
{"range": {"@timestamp": {"gte": "now-24h"}}}, extra]}}}
res = jget(f"{ix}/wazuh-alerts-*/_search", auth, data=q, method="POST")
tot = res.get("hits", {}).get("total", {})
return tot.get("value", tot) if isinstance(tot, dict) else tot
# only query the 24h count for sources explicitly marked live
for key, live in MALWARE_SOURCE_LIVE.items():
if not live:
continue
try:
d["sources"][key]["count"] = cnt(SRC_QUERY[key])
except Exception as e:
d["sources"][key]["err"] = type(e).__name__
# active detections on any live source escalate the card to warn
hits = sum(s["count"] for s in d["sources"].values()
if s["live"] and isinstance(s["count"], int))
if hits:
d["state"] = "warn"
return d
def collect_unifi():
d = {"state": "ok", "wan": "?", "wan_ip": "?", "clients": 0, "ips_24h": 0,
"latency": None, "down_mbps": None, "up_mbps": None, "devices": [],
"ssids": [], "month_rx": None, "month_tx": None, "month_total": None,
"pia": None}
GW = "https://192.0.2.1"
NET = GW + "/proxy/network/api/s/default"
cj = http.cookiejar.CookieJar()
op = urllib.request.build_opener(
urllib.request.HTTPSHandler(context=CTX),
urllib.request.HTTPCookieProcessor(cj))
op.open(urllib.request.Request(
f"{GW}/api/auth/login",
data=json.dumps({"username": E.get("UNIFI_USERNAME", ""),
"password": E.get("UNIFI_PASSWORD", "")}).encode(),
headers={"Content-Type": "application/json"}, method="POST"), timeout=TIMEOUT)
csrf = None
tok = next((c.value for c in cj if c.name == "TOKEN"), None)
if tok:
try:
p = tok.split(".")[1]; p += "=" * (-len(p) % 4)
csrf = json.loads(base64.urlsafe_b64decode(p)).get("csrfToken")
except Exception:
pass
hdr = {"Content-Type": "application/json"}
if csrf:
hdr["X-CSRF-Token"] = csrf
def call(path, data=None, method="GET"):
body = json.dumps(data).encode() if data is not None else None
r = urllib.request.Request(NET + path, data=body, headers=hdr,
method=("POST" if data is not None else method))
return json.loads(op.open(r, timeout=TIMEOUT).read())
health = call("/stat/health").get("data", [])
wan = next((h for h in health if h.get("subsystem") == "wan"), {})
www = next((h for h in health if h.get("subsystem") == "www"), {})
d["wan"] = wan.get("status", "?")
d["wan_ip"] = wan.get("wan_ip", "?")
d["latency"] = www.get("latency")
d["down_mbps"] = www.get("xput_down")
d["up_mbps"] = www.get("xput_up")
# clients = sum of num_user across lan + wlan subsystems
clients = 0
for h in health:
if h.get("subsystem") in ("lan", "wlan"):
clients += int(h.get("num_user", 0) or 0)
d["clients"] = clients
if d["wan"] != "ok":
d["state"] = "crit"
# IPS alarms 24h
try:
alarms = call("/list/alarm").get("data", [])
cutoff = (time.time() - 86400) * 1000
ips = [a for a in alarms
if (a.get("time") or a.get("timestamp") or 0) >= cutoff
and (a.get("key") == "EVT_IPS_IpsAlert" or a.get("inner_alert_signature"))]
d["ips_24h"] = len(ips)
if len(ips) > 0 and d["state"] == "ok":
d["state"] = "warn"
except Exception:
d["ips_24h"] = 0
# Network devices: UDM-SE, switches, APs (name + uptime)
try:
devs = call("/stat/device").get("data", [])
TMAP = {"udm": "Gateway", "ugw": "Gateway", "usw": "Switch",
"uap": "Access Point", "usg": "Gateway"}
def fmt_uptime(s):
s = int(s or 0)
dd, hh = s // 86400, (s % 86400) // 3600
if dd:
return f"{dd}d {hh}h"
mm = (s % 3600) // 60
return f"{hh}h {mm}m"
torder = {"udm": 0, "ugw": 0, "usg": 0, "usw": 1, "uap": 2}
for dev in sorted(devs, key=lambda x: (torder.get(x.get("type"), 9),
x.get("name", ""))):
up = int(dev.get("uptime", 0) or 0)
online = dev.get("state") == 1
d["devices"].append({
"name": dev.get("name", dev.get("model", "?")),
"kind": TMAP.get(dev.get("type"), dev.get("type", "?")),
"model": dev.get("model", "?"),
"uptime": fmt_uptime(up) if online else "offline",
"online": online})
if not online:
d["problems"] = d.get("problems", [])
if d["state"] == "ok":
d["state"] = "warn"
except Exception:
pass
# ---- WiFi clients per SSID (from active stations) ----
try:
sta = call("/stat/sta").get("data", [])
ssid_ct = Counter()
for c in sta:
e = c.get("essid")
if e:
ssid_ct[e] += 1
# Always surface common demo networks, even at 0 clients
WANTED = ["Guest-5G", "Guest-2G", "IoT-Net"]
seen = set()
for name in WANTED:
d["ssids"].append({"name": name, "clients": int(ssid_ct.get(name, 0))})
seen.add(name)
for name, ct in ssid_ct.most_common():
if name not in seen:
d["ssids"].append({"name": name, "clients": int(ct)})
except Exception:
pass
# ---- Current-month WAN data usage ----
try:
rows = call("/stat/report/monthly.site",
{"attrs": ["wan-tx_bytes", "wan-rx_bytes", "time"], "n": 2},
"POST").get("data", [])
if rows:
cur = rows[-1]
d["month_tx"] = cur.get("wan-tx_bytes")
d["month_rx"] = cur.get("wan-rx_bytes")
d["month_total"] = (cur.get("wan-tx_bytes", 0) or 0) + (cur.get("wan-rx_bytes", 0) or 0)
except Exception:
pass
# ---- PIA VPN client status + uptime ----
try:
ncs = call("/rest/networkconf").get("data", [])
pia = next((n for n in ncs
if n.get("purpose") == "vpn-client"
and "pia" in (n.get("name", "").lower())), None)
if pia is None:
pia = next((n for n in ncs if n.get("purpose") == "vpn-client"), None)
if pia:
status = pia.get("openvpn_configuration_status", "?")
enabled = bool(pia.get("enabled"))
connected = (str(status).upper() == "VALID") and enabled
# The controller does not expose VPN-client uptime for a vpn-client
# network (no uptime/up field on the gateway), so we report status only.
d["pia"] = {"name": pia.get("name", "PIAVPN"), "status": str(status),
"enabled": enabled, "connected": connected, "uptime": "n/a"}
if not connected and d["state"] == "ok":
d["state"] = "warn"
except Exception:
pass
return d
def collect_adguard():
d = {"state": "ok", "queries": 0, "blocked": 0, "block_pct": 0.0, "avg_ms": 0.0}
base = E.get("ADGUARD_URL", "http://192.0.2.21").strip().rstrip("/")
user = E.get("ADGUARD_USERNAME", "admin")
s = jget(f"{base}/control/stats",
{"Authorization": "Basic " + _b64(f"{user}:{E.get('ADGUARD_PASSWORD','')}")})
tot = s.get("num_dns_queries", 0)
blk = s.get("num_blocked_filtering", 0)
d["queries"] = tot
d["blocked"] = blk
d["block_pct"] = round(100 * blk / tot, 1) if tot else 0.0
d["avg_ms"] = round(s.get("avg_processing_time", 0) * 1000, 1)
return d
def collect_urbackup():