sensitivebox 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sensitivebox/__init__.py +10 -0
- sensitivebox/alerts/__init__.py +94 -0
- sensitivebox/alerts/config.py +85 -0
- sensitivebox/alerts/defaults.toml +126 -0
- sensitivebox/alerts/engine.py +624 -0
- sensitivebox/alerts/events.py +87 -0
- sensitivebox/alerts/globs.py +84 -0
- sensitivebox/alerts/model.py +215 -0
- sensitivebox/alerts/mute.py +55 -0
- sensitivebox/alerts/replay.py +99 -0
- sensitivebox/alerts/routing.py +247 -0
- sensitivebox/api/__init__.py +6 -0
- sensitivebox/api/app.py +225 -0
- sensitivebox/api/data.py +109 -0
- sensitivebox/api/host.py +27 -0
- sensitivebox/api/model.py +90 -0
- sensitivebox/api/security.py +89 -0
- sensitivebox/api/server.py +108 -0
- sensitivebox/api/state.py +220 -0
- sensitivebox/api/static/assets/archivo-latin-wdth-normal-DY7AcnAa.woff2 +0 -0
- sensitivebox/api/static/assets/ibm-plex-mono-medium-BpyVxOr_.woff2 +0 -0
- sensitivebox/api/static/assets/index-BH9EydfS.js +10 -0
- sensitivebox/api/static/assets/index-RMruxW54.css +1 -0
- sensitivebox/api/static/assets/mark-on-dark-CpSxozdM.png +0 -0
- sensitivebox/api/static/assets/mark-on-light-DgUAeHTp.png +0 -0
- sensitivebox/api/static/assets/mark-raised-Bg5z6PGs.png +0 -0
- sensitivebox/api/static/index.html +14 -0
- sensitivebox/browser.py +106 -0
- sensitivebox/cli.py +467 -0
- sensitivebox/collector.py +319 -0
- sensitivebox/completion.py +117 -0
- sensitivebox/daemon.py +181 -0
- sensitivebox/data/icons/128.png +0 -0
- sensitivebox/data/icons/256.png +0 -0
- sensitivebox/data/icons/512.png +0 -0
- sensitivebox/data/proart-p16.tar.gz +0 -0
- sensitivebox/data/sensitivebox.desktop.in +8 -0
- sensitivebox/data/sensitivebox.service.in +11 -0
- sensitivebox/doctor.py +322 -0
- sensitivebox/fixtures.py +177 -0
- sensitivebox/history.py +298 -0
- sensitivebox/hwmon/__init__.py +20 -0
- sensitivebox/hwmon/classify.py +74 -0
- sensitivebox/hwmon/discovery.py +139 -0
- sensitivebox/hwmon/ids.py +35 -0
- sensitivebox/hwmon/model.py +78 -0
- sensitivebox/hwmon/normalise.py +42 -0
- sensitivebox/hwmon/reader.py +65 -0
- sensitivebox/inspect.py +175 -0
- sensitivebox/live.py +56 -0
- sensitivebox/notify/__init__.py +7 -0
- sensitivebox/notify/base.py +60 -0
- sensitivebox/notify/desktop.py +84 -0
- sensitivebox/notify/log.py +30 -0
- sensitivebox/operations.py +44 -0
- sensitivebox/output.py +76 -0
- sensitivebox/process.py +25 -0
- sensitivebox/py.typed +0 -0
- sensitivebox/redact.py +85 -0
- sensitivebox/report.py +357 -0
- sensitivebox/runtime.py +313 -0
- sensitivebox/sample.py +84 -0
- sensitivebox/service.py +112 -0
- sensitivebox/simulate.py +220 -0
- sensitivebox/sources/__init__.py +83 -0
- sensitivebox/sources/apps.py +135 -0
- sensitivebox/sources/bluez.py +96 -0
- sensitivebox/sources/bluez_watch.py +214 -0
- sensitivebox/sources/changes.py +121 -0
- sensitivebox/sources/cpu.py +152 -0
- sensitivebox/sources/dbus.py +174 -0
- sensitivebox/sources/logind.py +88 -0
- sensitivebox/sources/memory.py +127 -0
- sensitivebox/sources/net.py +128 -0
- sensitivebox/sources/power_profiles.py +116 -0
- sensitivebox/sources/power_supply.py +70 -0
- sensitivebox/sources/psi.py +78 -0
- sensitivebox/sources/report.py +85 -0
- sensitivebox/sources/wifi.py +90 -0
- sensitivebox/sources/wifi_nm.py +269 -0
- sensitivebox/status.py +205 -0
- sensitivebox/store/__init__.py +5 -0
- sensitivebox/store/changes.py +58 -0
- sensitivebox/store/db.py +423 -0
- sensitivebox/store/events.py +337 -0
- sensitivebox/store/mutes.py +58 -0
- sensitivebox/store/quality.py +51 -0
- sensitivebox/store/read.py +40 -0
- sensitivebox/store/schema.py +194 -0
- sensitivebox/store/status.py +105 -0
- sensitivebox-0.1.0.dist-info/METADATA +424 -0
- sensitivebox-0.1.0.dist-info/RECORD +95 -0
- sensitivebox-0.1.0.dist-info/WHEEL +4 -0
- sensitivebox-0.1.0.dist-info/entry_points.txt +4 -0
- sensitivebox-0.1.0.dist-info/licenses/LICENSE +21 -0
sensitivebox/doctor.py
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
"""Render ``sensitivebox doctor`` output: every chip and sensor, for bug reports.
|
|
2
|
+
|
|
3
|
+
Unavailable and junk sensors are listed too (the dashboard hides them), because a bug report needs
|
|
4
|
+
to show exactly what the kernel exposed. Both renderers return redacted text (``redact``): it goes
|
|
5
|
+
into public bug reports.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from collections.abc import Mapping, Sequence
|
|
9
|
+
|
|
10
|
+
from sensitivebox.alerts import Rule
|
|
11
|
+
from sensitivebox.hwmon import Chip, Group, Kind, Reading, ReadStatus, Sensor
|
|
12
|
+
from sensitivebox.redact import device_label, redact
|
|
13
|
+
from sensitivebox.sources import SourcesReport
|
|
14
|
+
from sensitivebox.sources.psi import PsiLine
|
|
15
|
+
|
|
16
|
+
_HEADERS = ("GROUP", "ID", "LABEL", "KIND", "VALUE", "LIMITS", "DEFAULT RULES", "STATUS")
|
|
17
|
+
_GROUP_ORDER = {group: i for i, group in enumerate(Group)}
|
|
18
|
+
_STATUS_TEXT = {
|
|
19
|
+
ReadStatus.OK: "ok",
|
|
20
|
+
ReadStatus.UNAVAILABLE: "unavailable",
|
|
21
|
+
ReadStatus.JUNK: "junk",
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def format_value(kind: Kind, value: float) -> str:
|
|
26
|
+
match kind:
|
|
27
|
+
case Kind.TEMP:
|
|
28
|
+
return f"{value:.1f} °C"
|
|
29
|
+
case Kind.FAN:
|
|
30
|
+
return f"{value:.0f} RPM"
|
|
31
|
+
case Kind.PWM:
|
|
32
|
+
return f"{value:.0f} %"
|
|
33
|
+
case Kind.IN:
|
|
34
|
+
return f"{value:.2f} V"
|
|
35
|
+
case Kind.CURR:
|
|
36
|
+
return f"{value:.3f} A"
|
|
37
|
+
case Kind.POWER:
|
|
38
|
+
return f"{value:.2f} W"
|
|
39
|
+
case Kind.FREQ:
|
|
40
|
+
return f"{value / 1e6:.0f} MHz" if value >= 1e6 else f"{value:.0f} Hz"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _format_limits(sensor: Sensor) -> str:
|
|
44
|
+
"""Limits share the VALUE column's unit, so it's left off: ``max 86.8, crit 89.8``."""
|
|
45
|
+
limits = sensor.limits
|
|
46
|
+
parts = [
|
|
47
|
+
f"{name} {format_value(sensor.kind, value).rsplit(' ', 1)[0]}"
|
|
48
|
+
for name, value in (("min", limits.min), ("max", limits.max), ("crit", limits.crit))
|
|
49
|
+
if value is not None
|
|
50
|
+
]
|
|
51
|
+
if limits.alarm:
|
|
52
|
+
parts.append("ALARM")
|
|
53
|
+
return ", ".join(parts) or "-"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _rules_for(sensor: Sensor, rules: Sequence[Rule]) -> str:
|
|
57
|
+
"""Rule ids watching this sensor; ``-`` means none, so the dashboard shows it grey."""
|
|
58
|
+
return ",".join(r.id for r in rules if r.matches(sensor.id)) or "-"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _row(sensor: Sensor, reading: Reading | None, rules: Sequence[Rule]) -> tuple[str, ...]:
|
|
62
|
+
status = reading.status if reading else ReadStatus.UNAVAILABLE
|
|
63
|
+
if reading and reading.value is not None:
|
|
64
|
+
value = format_value(sensor.kind, reading.value)
|
|
65
|
+
elif reading and reading.raw is not None:
|
|
66
|
+
value = f"raw {reading.raw}"
|
|
67
|
+
else:
|
|
68
|
+
value = "N/A"
|
|
69
|
+
status_text = _STATUS_TEXT[status]
|
|
70
|
+
if status is ReadStatus.UNAVAILABLE:
|
|
71
|
+
status_text += f" ({reading.reason if reading and reading.reason else 'not read'})"
|
|
72
|
+
return (
|
|
73
|
+
sensor.group.value,
|
|
74
|
+
sensor.id,
|
|
75
|
+
sensor.label,
|
|
76
|
+
sensor.kind.value,
|
|
77
|
+
value,
|
|
78
|
+
_format_limits(sensor),
|
|
79
|
+
_rules_for(sensor, rules),
|
|
80
|
+
status_text,
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _table(rows: Sequence[tuple[str, ...]], *, header: bool = False, indent: str = "") -> list[str]:
|
|
85
|
+
"""Left-aligned columns, two spaces apart; ``header`` underlines the first row."""
|
|
86
|
+
widths = [max(len(row[i]) for row in rows) for i in range(len(rows[0]))]
|
|
87
|
+
lines: list[str] = []
|
|
88
|
+
for n, row in enumerate(rows):
|
|
89
|
+
cells = " ".join(cell.ljust(w) for cell, w in zip(row, widths, strict=True))
|
|
90
|
+
lines.append((indent + cells).rstrip())
|
|
91
|
+
if header and n == 0:
|
|
92
|
+
lines.append(indent + " ".join("-" * w for w in widths))
|
|
93
|
+
return lines
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def render(
|
|
97
|
+
chips: Sequence[Chip],
|
|
98
|
+
readings: Mapping[str, Reading],
|
|
99
|
+
*,
|
|
100
|
+
verbose: bool = False,
|
|
101
|
+
rules: Sequence[Rule] = (),
|
|
102
|
+
) -> str:
|
|
103
|
+
"""The doctor report. ``verbose`` lists each chip without sensors on its own line, with its
|
|
104
|
+
path; otherwise they're named in a single summary line. ``rules`` fills the RULES column."""
|
|
105
|
+
# Stable sort: within a group, keep discovery order (chips by name, channels naturally).
|
|
106
|
+
sensors = sorted(
|
|
107
|
+
(s for chip in chips for s in chip.sensors),
|
|
108
|
+
key=lambda s: _GROUP_ORDER[s.group],
|
|
109
|
+
)
|
|
110
|
+
lines: list[str] = []
|
|
111
|
+
if sensors:
|
|
112
|
+
rows = [_HEADERS, *(_row(s, readings.get(s.id), rules) for s in sensors)]
|
|
113
|
+
lines += _table(rows, header=True)
|
|
114
|
+
else:
|
|
115
|
+
lines.append("No hwmon sensors found.")
|
|
116
|
+
|
|
117
|
+
counts = {status: 0 for status in ReadStatus}
|
|
118
|
+
for s in sensors:
|
|
119
|
+
reading = readings.get(s.id)
|
|
120
|
+
counts[reading.status if reading else ReadStatus.UNAVAILABLE] += 1
|
|
121
|
+
lines += [
|
|
122
|
+
"",
|
|
123
|
+
f"{len(chips)} chips, {len(sensors)} sensors: {counts[ReadStatus.OK]} ok, "
|
|
124
|
+
f"{counts[ReadStatus.UNAVAILABLE]} unavailable, {counts[ReadStatus.JUNK]} junk"
|
|
125
|
+
" (unavailable and junk sensors are hidden from the dashboard).",
|
|
126
|
+
]
|
|
127
|
+
|
|
128
|
+
empty = [c for c in chips if not c.sensors]
|
|
129
|
+
if empty and verbose:
|
|
130
|
+
lines.append("Chips with no sensors:")
|
|
131
|
+
lines += _table([(c.name, c.bus_id, str(c.path)) for c in empty], indent=" ")
|
|
132
|
+
elif empty:
|
|
133
|
+
names = ", ".join(c.name for c in empty)
|
|
134
|
+
lines.append(f"Chips with no sensors (hidden, --verbose for details): {names}")
|
|
135
|
+
|
|
136
|
+
dropped = [
|
|
137
|
+
f"{s.id} {name} {value:.2f} {s.unit}" for s in sensors for name, value in s.dropped_limits
|
|
138
|
+
]
|
|
139
|
+
if dropped:
|
|
140
|
+
lines.append("Dropped junk limits:")
|
|
141
|
+
lines += [f" {entry}" for entry in dropped]
|
|
142
|
+
return redact("\n".join(lines))
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
# -- System sources -------------------------------------------------------------------------
|
|
146
|
+
|
|
147
|
+
NOT_HERE = "not available on this box"
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def format_bytes(n: float) -> str:
|
|
151
|
+
"""Decimal units, as the dashboard shows them: ``2.4 GB``."""
|
|
152
|
+
for unit in ("B", "kB", "MB", "GB"):
|
|
153
|
+
if abs(n) < 1000:
|
|
154
|
+
return f"{n:.0f} {unit}" if unit == "B" else f"{n:.1f} {unit}"
|
|
155
|
+
n /= 1000
|
|
156
|
+
return f"{n:.1f} TB"
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
_PSI_W = 20
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _pct(fraction: float, digits: int = 0) -> str:
|
|
163
|
+
return f"{fraction * 100:.{digits}f} %"
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _psi(line: PsiLine | None) -> str:
|
|
167
|
+
return " - / - " if line is None else f"{line.avg10:5.2f} / {line.avg60:5.2f}"
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _memory_rows(report: SourcesReport) -> list[tuple[str, str]]:
|
|
171
|
+
mem = report.meminfo
|
|
172
|
+
if mem is None:
|
|
173
|
+
return [("Memory", NOT_HERE), ("Swap", NOT_HERE)]
|
|
174
|
+
return [
|
|
175
|
+
(
|
|
176
|
+
"Memory",
|
|
177
|
+
f"{format_bytes(mem.used)} of {format_bytes(mem.total)} used "
|
|
178
|
+
f"({_pct(mem.used_fraction)}), {format_bytes(mem.available)} available; "
|
|
179
|
+
f"cached {format_bytes(mem.cached)}, dirty {format_bytes(mem.dirty)}",
|
|
180
|
+
),
|
|
181
|
+
(
|
|
182
|
+
"Swap",
|
|
183
|
+
f"{format_bytes(mem.swap_used)} of {format_bytes(mem.swap_total)} used"
|
|
184
|
+
if mem.swap_total
|
|
185
|
+
else "none",
|
|
186
|
+
),
|
|
187
|
+
]
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _zram_rows(report: SourcesReport) -> list[tuple[str, str]]:
|
|
191
|
+
if not report.zram:
|
|
192
|
+
return [("zram", NOT_HERE)]
|
|
193
|
+
rows: list[tuple[str, str]] = []
|
|
194
|
+
for n, z in enumerate(report.zram):
|
|
195
|
+
text = (
|
|
196
|
+
f"{z.name} {z.ratio:.1f}\N{MULTIPLICATION SIGN}, {format_bytes(z.saved_bytes)} saved "
|
|
197
|
+
f"({format_bytes(z.orig_bytes)} stored in {format_bytes(z.mem_used_bytes)})"
|
|
198
|
+
if z.ratio is not None
|
|
199
|
+
else f"{z.name} empty"
|
|
200
|
+
)
|
|
201
|
+
rows.append(("zram" if n == 0 else "", text))
|
|
202
|
+
return rows
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _pressure_rows(report: SourcesReport) -> list[tuple[str, str]]:
|
|
206
|
+
if not report.pressure:
|
|
207
|
+
return [("Pressure", f"{NOT_HERE} (PSI off)")]
|
|
208
|
+
rows = [("Pressure", f"{'':<6} {'some avg10 / avg60 %':<{_PSI_W}} full avg10 / avg60 %")]
|
|
209
|
+
for name, p in report.pressure.items():
|
|
210
|
+
trend = " rising" if p.some.rising else ""
|
|
211
|
+
rows.append(("", f"{name:<6} {_psi(p.some):<{_PSI_W}} {_psi(p.full)}{trend}"))
|
|
212
|
+
return rows
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _vm_row(report: SourcesReport) -> tuple[str, str]:
|
|
216
|
+
vm = report.vmstat
|
|
217
|
+
if vm is None:
|
|
218
|
+
return ("VM", NOT_HERE)
|
|
219
|
+
|
|
220
|
+
def n(value: int | None) -> str:
|
|
221
|
+
return "n/a" if value is None else f"{value:,}"
|
|
222
|
+
|
|
223
|
+
return (
|
|
224
|
+
"VM",
|
|
225
|
+
f"{n(vm.oom_kill)} OOM kills; swapped in {n(vm.pswpin)} pages, "
|
|
226
|
+
f"out {n(vm.pswpout)} pages (since boot)",
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _ghz(hz: float) -> str:
|
|
231
|
+
return f"{hz / 1e9:.2f}"
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _cpu_row(report: SourcesReport) -> tuple[str, str]:
|
|
235
|
+
parts: list[str] = []
|
|
236
|
+
count = len(report.cpu_times.cores) if report.cpu_times else len(report.cpu_freqs)
|
|
237
|
+
if count:
|
|
238
|
+
parts.append(f"{count} cores")
|
|
239
|
+
current = [f.cur_hz for f in report.cpu_freqs if f.cur_hz is not None]
|
|
240
|
+
if current:
|
|
241
|
+
avg = sum(current) / len(current)
|
|
242
|
+
span = f"{_ghz(min(current))}\N{EN DASH}{_ghz(max(current))}"
|
|
243
|
+
parts.append(f"now {span} GHz (avg {_ghz(avg)})")
|
|
244
|
+
ceilings = [f.max_hz for f in report.cpu_freqs if f.max_hz is not None]
|
|
245
|
+
if ceilings:
|
|
246
|
+
parts.append(f"max {_ghz(max(ceilings))} GHz")
|
|
247
|
+
else:
|
|
248
|
+
parts.append("clock speed not available")
|
|
249
|
+
if report.cpu_times:
|
|
250
|
+
parts.append(f"{_pct(report.cpu_times.busy_since_boot, 1)} busy since boot")
|
|
251
|
+
return ("CPU", "; ".join(parts) if count else NOT_HERE)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _net_rows(report: SourcesReport) -> list[tuple[str, str]]:
|
|
255
|
+
if not report.net:
|
|
256
|
+
return [("Network", "no interfaces (lo, veth*, docker*, br-* are skipped)")]
|
|
257
|
+
width = max(len(name) for name in report.net)
|
|
258
|
+
return [
|
|
259
|
+
(
|
|
260
|
+
"Network" if n == 0 else "",
|
|
261
|
+
f"{c.iface:<{width}} {c.operstate or '?':<7} ↓ {format_bytes(c.rx_bytes)} "
|
|
262
|
+
f"↑ {format_bytes(c.tx_bytes)} since boot{' (virtual)' if c.virtual else ''}",
|
|
263
|
+
)
|
|
264
|
+
for n, c in enumerate(report.net.values())
|
|
265
|
+
]
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _wifi_row(report: SourcesReport) -> tuple[str, str]:
|
|
269
|
+
signal = report.wifi.signal
|
|
270
|
+
if signal is None:
|
|
271
|
+
return ("Wi-Fi", f"unavailable ({report.wifi.reason})")
|
|
272
|
+
dbm = f", {signal.dbm} dBm" if signal.dbm is not None else ""
|
|
273
|
+
return ("Wi-Fi", f"{signal.iface} {signal.label}{dbm} (source: {signal.source})")
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _bluetooth_rows(report: SourcesReport) -> list[tuple[str, str]]:
|
|
277
|
+
bt = report.bluetooth
|
|
278
|
+
if bt is None:
|
|
279
|
+
return [("Bluetooth", "not queried")]
|
|
280
|
+
if not bt.available:
|
|
281
|
+
return [("Bluetooth", f"unavailable ({bt.reason})")]
|
|
282
|
+
rows: list[tuple[str, str]] = []
|
|
283
|
+
for n, adapter in enumerate(bt.adapters):
|
|
284
|
+
devices = [d for d in bt.devices if d.adapter == adapter.name]
|
|
285
|
+
listed = ", ".join(device_label(d) for d in devices) # never names or addresses
|
|
286
|
+
state = "on" if adapter.powered else "off"
|
|
287
|
+
text = f"{adapter.name} powered {state}; {len(devices)} connected"
|
|
288
|
+
rows.append(("Bluetooth" if n == 0 else "", f"{text}: {listed}" if listed else text))
|
|
289
|
+
return rows
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _apps_rows(report: SourcesReport) -> list[tuple[str, str]]:
|
|
293
|
+
if report.apps is None:
|
|
294
|
+
used = f"memory {_pct(report.meminfo.used_fraction)}, " if report.meminfo else ""
|
|
295
|
+
return [("Top apps", f"not sampled ({used}memory pressure steady)")]
|
|
296
|
+
if not report.apps:
|
|
297
|
+
return [("Top apps", report.apps_reason or "none found")]
|
|
298
|
+
width = max(len(a.name) for a in report.apps)
|
|
299
|
+
return [
|
|
300
|
+
(
|
|
301
|
+
"Top apps" if n == 0 else "",
|
|
302
|
+
f"{a.name:<{width}} {format_bytes(a.bytes)}"
|
|
303
|
+
+ (f" ({a.units} units)" if a.units > 1 else ""),
|
|
304
|
+
)
|
|
305
|
+
for n, a in enumerate(report.apps)
|
|
306
|
+
]
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def render_sources(report: SourcesReport) -> str:
|
|
310
|
+
"""The "System sources" block printed below the sensor table."""
|
|
311
|
+
rows = [
|
|
312
|
+
*_memory_rows(report),
|
|
313
|
+
*_zram_rows(report),
|
|
314
|
+
*_pressure_rows(report),
|
|
315
|
+
_vm_row(report),
|
|
316
|
+
_cpu_row(report),
|
|
317
|
+
*_net_rows(report),
|
|
318
|
+
_wifi_row(report),
|
|
319
|
+
*_bluetooth_rows(report),
|
|
320
|
+
*_apps_rows(report),
|
|
321
|
+
]
|
|
322
|
+
return redact("\n".join(["System sources", *_table(rows, indent=" ")]))
|
sensitivebox/fixtures.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""Validated machine roots and read-only D-Bus snapshots; never fall back to host buses."""
|
|
2
|
+
|
|
3
|
+
import tarfile
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from dataclasses import dataclass, replace
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from tempfile import TemporaryDirectory
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import msgspec
|
|
11
|
+
from dbus_fast import Message, MessageType, Variant
|
|
12
|
+
|
|
13
|
+
from sensitivebox.sources.bluez import BluetoothStatus, read_bluetooth
|
|
14
|
+
from sensitivebox.sources.wifi import WifiStatus
|
|
15
|
+
from sensitivebox.sources.wifi_nm import NM, NM_PATH, read_nm_wifi_once
|
|
16
|
+
|
|
17
|
+
type Properties = dict[str, dict[str, dict[str, str | bool | int]]]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class FixtureError(ValueError):
|
|
21
|
+
"""An invalid fixture, with instructions for repairing it."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _objects(path: Path) -> Properties:
|
|
25
|
+
try:
|
|
26
|
+
objects = msgspec.json.decode(path.read_bytes(), type=Properties)
|
|
27
|
+
for interfaces in objects.values():
|
|
28
|
+
for props in interfaces.values():
|
|
29
|
+
for name, value in props.items():
|
|
30
|
+
expected = (
|
|
31
|
+
bool
|
|
32
|
+
if name in {"Powered", "Connected", "Paired", "Discoverable", "Discovering"}
|
|
33
|
+
else int
|
|
34
|
+
if name in {"Percentage", "Strength", "DeviceType", "Frequency"}
|
|
35
|
+
else str
|
|
36
|
+
)
|
|
37
|
+
if type(value) is not expected:
|
|
38
|
+
raise ValueError(f"invalid {name}")
|
|
39
|
+
return objects
|
|
40
|
+
except (OSError, ValueError, msgspec.DecodeError) as exc:
|
|
41
|
+
raise FixtureError(f"cannot read {path}: {exc}; fix the fixture JSON and retry") from exc
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True, slots=True)
|
|
45
|
+
class MachineRoot:
|
|
46
|
+
path: Path
|
|
47
|
+
bus: "SnapshotBus"
|
|
48
|
+
temporary: TemporaryDirectory[str] | None = None
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def sys(self) -> Path:
|
|
52
|
+
return self.path / "sys"
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def proc(self) -> Path:
|
|
56
|
+
return self.path / "proc"
|
|
57
|
+
|
|
58
|
+
@classmethod
|
|
59
|
+
def load(cls, path: Path) -> "MachineRoot":
|
|
60
|
+
if not all((path / name).is_dir() for name in ("sys", "proc", "dbus")):
|
|
61
|
+
raise FixtureError(
|
|
62
|
+
f"invalid root {path}; provide a machine folder with sys/, proc/, dbus/"
|
|
63
|
+
)
|
|
64
|
+
resolved = path.resolve()
|
|
65
|
+
for entry in path.rglob("*"):
|
|
66
|
+
if entry.is_symlink() and not entry.resolve().is_relative_to(resolved):
|
|
67
|
+
raise FixtureError(f"fixture link {entry} escapes root; fix the link and retry")
|
|
68
|
+
bluez = path / "dbus" / "bluez-managed-objects.json"
|
|
69
|
+
nm = path / "dbus" / "nm-wifi.json"
|
|
70
|
+
objects = _objects(bluez) if bluez.exists() else None
|
|
71
|
+
network: dict[str, Properties] | None = None
|
|
72
|
+
if nm.exists():
|
|
73
|
+
try:
|
|
74
|
+
network = msgspec.json.decode(nm.read_bytes(), type=dict[str, Properties])
|
|
75
|
+
if set(network) != {"devices", "access_points"}:
|
|
76
|
+
raise ValueError("expected devices and access_points")
|
|
77
|
+
# Validate the same property types as the BlueZ snapshot.
|
|
78
|
+
for group in network.values():
|
|
79
|
+
for ifaces in group.values():
|
|
80
|
+
for props in ifaces.values():
|
|
81
|
+
for key, value in props.items():
|
|
82
|
+
expected = (
|
|
83
|
+
int if key in {"Strength", "Frequency", "DeviceType"} else str
|
|
84
|
+
)
|
|
85
|
+
if type(value) is not expected:
|
|
86
|
+
raise ValueError(f"invalid {key}")
|
|
87
|
+
except (OSError, ValueError, msgspec.DecodeError) as exc:
|
|
88
|
+
raise FixtureError(
|
|
89
|
+
f"cannot read {nm}: {exc}; fix the fixture JSON and retry"
|
|
90
|
+
) from exc
|
|
91
|
+
return cls(path, SnapshotBus(objects, network))
|
|
92
|
+
|
|
93
|
+
async def snapshot(self) -> tuple[BluetoothStatus, WifiStatus]:
|
|
94
|
+
bt = await read_bluetooth(self.bus)
|
|
95
|
+
wifi = await read_nm_wifi_once(self.bus)
|
|
96
|
+
if self.bus.bluez is None:
|
|
97
|
+
bt = BluetoothStatus(reason="BlueZ snapshot missing in fixture")
|
|
98
|
+
if self.bus.nm is None:
|
|
99
|
+
wifi = WifiStatus.unavailable("NetworkManager snapshot missing in fixture")
|
|
100
|
+
return bt, wifi
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class SnapshotBus:
|
|
104
|
+
"""Only the read methods used by the existing BlueZ/NM parsers; no socket connection."""
|
|
105
|
+
|
|
106
|
+
def __init__(self, bluez: Properties | None, nm: dict[str, Properties] | None) -> None:
|
|
107
|
+
self.bluez = bluez
|
|
108
|
+
self.nm = nm
|
|
109
|
+
|
|
110
|
+
async def call(self, msg: Message) -> Message:
|
|
111
|
+
signature = ""
|
|
112
|
+
body: list[Any] = []
|
|
113
|
+
if msg.member in {"AddMatch", "RemoveMatch"}:
|
|
114
|
+
pass
|
|
115
|
+
elif msg.member == "GetManagedObjects" and self.bluez is not None:
|
|
116
|
+
signature = "a{oa{sa{sv}}}"
|
|
117
|
+
body = [
|
|
118
|
+
{
|
|
119
|
+
p: {
|
|
120
|
+
i: {k: _variant(v) for k, v in props.items()} for i, props in ifaces.items()
|
|
121
|
+
}
|
|
122
|
+
for p, ifaces in self.bluez.items()
|
|
123
|
+
}
|
|
124
|
+
]
|
|
125
|
+
elif msg.destination == NM and self.nm is not None:
|
|
126
|
+
if msg.path == NM_PATH and msg.member == "GetDevices":
|
|
127
|
+
signature, body = "ao", [sorted(self.nm["devices"])]
|
|
128
|
+
elif msg.member == "Get":
|
|
129
|
+
interface, prop = str(msg.body[0]), str(msg.body[1])
|
|
130
|
+
objects = {**self.nm["devices"], **self.nm["access_points"]}
|
|
131
|
+
try:
|
|
132
|
+
value = objects[str(msg.path)][interface][prop]
|
|
133
|
+
except KeyError:
|
|
134
|
+
return self._unavailable()
|
|
135
|
+
signature, body = "v", [_variant(value)]
|
|
136
|
+
else:
|
|
137
|
+
return self._unavailable()
|
|
138
|
+
else:
|
|
139
|
+
return self._unavailable()
|
|
140
|
+
return Message(
|
|
141
|
+
message_type=MessageType.METHOD_RETURN, reply_serial=1, signature=signature, body=body
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
def _unavailable(self) -> Message:
|
|
145
|
+
return Message(
|
|
146
|
+
message_type=MessageType.ERROR,
|
|
147
|
+
reply_serial=1,
|
|
148
|
+
error_name="org.freedesktop.DBus.Error.Failed",
|
|
149
|
+
signature="s",
|
|
150
|
+
body=["service snapshot missing in fixture"],
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
def add_message_handler(self, handler: Callable[[Message], Any]) -> None:
|
|
154
|
+
pass
|
|
155
|
+
|
|
156
|
+
def remove_message_handler(self, handler: Callable[[Message], Any]) -> None:
|
|
157
|
+
pass
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _variant(value: str | bool | int) -> Variant:
|
|
161
|
+
signature = "b" if isinstance(value, bool) else "u" if isinstance(value, int) else "s"
|
|
162
|
+
if isinstance(value, str) and value.startswith("/"):
|
|
163
|
+
signature = "o"
|
|
164
|
+
return Variant(signature, value)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def demo_root() -> MachineRoot:
|
|
168
|
+
temporary = TemporaryDirectory(prefix="sensitivebox-demo-")
|
|
169
|
+
try:
|
|
170
|
+
archive = Path(__file__).parent / "data" / "proart-p16.tar.gz"
|
|
171
|
+
with tarfile.open(archive) as bundle:
|
|
172
|
+
bundle.extractall(temporary.name, filter="data")
|
|
173
|
+
root = MachineRoot.load(Path(temporary.name) / "proart-p16")
|
|
174
|
+
return replace(root, temporary=temporary)
|
|
175
|
+
except BaseException:
|
|
176
|
+
temporary.cleanup()
|
|
177
|
+
raise
|