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
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Wi-Fi signal: ``/proc/net/wireless`` first, NetworkManager as the fallback.
|
|
2
|
+
|
|
3
|
+
Kernels without wireless extensions for Wi-Fi 7 cards (MT7925 on 7.0, for example) list no
|
|
4
|
+
interfaces in ``/proc/net/wireless``, so ``wifi_nm`` asks NetworkManager instead. Having no
|
|
5
|
+
Wi-Fi, or no NetworkManager, is a normal *unavailable* state with a reason, never an error.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from sensitivebox.hwmon.reader import Opener, default_opener, read_attr
|
|
13
|
+
|
|
14
|
+
SOURCE_PROC = "/proc/net/wireless"
|
|
15
|
+
SOURCE_NM = "NetworkManager"
|
|
16
|
+
|
|
17
|
+
# Link quality is reported out of a driver-specific maximum that only an ioctl reveals;
|
|
18
|
+
# cfg80211 (every modern driver) uses 70.
|
|
19
|
+
_WEXT_QUALITY_MAX = 70.0
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True, slots=True)
|
|
23
|
+
class WifiSignal:
|
|
24
|
+
iface: str
|
|
25
|
+
percent: int # 0 to 100
|
|
26
|
+
dbm: int | None # only /proc/net/wireless reports it
|
|
27
|
+
source: str # SOURCE_PROC or SOURCE_NM
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def label(self) -> str:
|
|
31
|
+
return f"Signal {self.percent} %"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True, slots=True)
|
|
35
|
+
class WifiStatus:
|
|
36
|
+
"""Exactly one of ``signal`` and ``reason`` is set."""
|
|
37
|
+
|
|
38
|
+
signal: WifiSignal | None = None
|
|
39
|
+
reason: str | None = None
|
|
40
|
+
|
|
41
|
+
@classmethod
|
|
42
|
+
def ok(cls, signal: WifiSignal) -> "WifiStatus":
|
|
43
|
+
return cls(signal=signal)
|
|
44
|
+
|
|
45
|
+
@classmethod
|
|
46
|
+
def unavailable(cls, reason: str) -> "WifiStatus":
|
|
47
|
+
return cls(reason=reason)
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def available(self) -> bool:
|
|
51
|
+
return self.signal is not None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _number(text: str) -> float | None:
|
|
55
|
+
try:
|
|
56
|
+
return float(text.rstrip("."))
|
|
57
|
+
except ValueError:
|
|
58
|
+
return None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def parse_proc_wireless(text: str) -> dict[str, WifiSignal]:
|
|
62
|
+
"""Two header lines, then ``iface: status link level noise …`` (values may end in ``.``)."""
|
|
63
|
+
out: dict[str, WifiSignal] = {}
|
|
64
|
+
for line in text.splitlines()[2:]:
|
|
65
|
+
iface, sep, rest = line.partition(":")
|
|
66
|
+
fields = rest.split()
|
|
67
|
+
if not sep or len(fields) < 3:
|
|
68
|
+
continue
|
|
69
|
+
link, level = _number(fields[1]), _number(fields[2])
|
|
70
|
+
if link is None:
|
|
71
|
+
continue
|
|
72
|
+
percent = round(min(max(link / _WEXT_QUALITY_MAX, 0.0), 1.0) * 100)
|
|
73
|
+
dbm = int(level) if level is not None and level < 0 else None
|
|
74
|
+
name = iface.strip()
|
|
75
|
+
out[name] = WifiSignal(name, percent, dbm, SOURCE_PROC)
|
|
76
|
+
return out
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def read_proc_wireless(proc_root: Path, opener: Opener = default_opener) -> dict[str, WifiSignal]:
|
|
80
|
+
text = read_attr(proc_root / "net" / "wireless", opener)
|
|
81
|
+
return parse_proc_wireless(text) if text else {}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def choose(proc: Mapping[str, WifiSignal], nm: WifiStatus | None) -> WifiStatus:
|
|
85
|
+
"""Prefer ``/proc/net/wireless``; otherwise NetworkManager's answer (``None`` = not asked)."""
|
|
86
|
+
if proc:
|
|
87
|
+
return WifiStatus.ok(proc[min(proc)])
|
|
88
|
+
if nm is not None:
|
|
89
|
+
return nm
|
|
90
|
+
return WifiStatus.unavailable("no entry in /proc/net/wireless; NetworkManager not asked")
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
"""Wi-Fi signal from NetworkManager over the system D-Bus, by subscription rather than polling.
|
|
2
|
+
|
|
3
|
+
``NmWifiWatcher.start`` reads the state once: the Wi-Fi device, its ``ActiveAccessPoint`` and
|
|
4
|
+
that access point's ``Strength``. After that it only listens for signals:
|
|
5
|
+
|
|
6
|
+
- ``PropertiesChanged`` on the access point (``Strength``),
|
|
7
|
+
- ``PropertiesChanged`` on the device (``ActiveAccessPoint``: a roam, a connect, a disconnect),
|
|
8
|
+
- ``NameOwnerChanged`` for NetworkManager (it stopped or restarted), and
|
|
9
|
+
- ``DeviceAdded``/``DeviceRemoved`` (a USB dongle plugged in or pulled out).
|
|
10
|
+
|
|
11
|
+
``current()`` returns the cached status, so the daemon's 1 s poll costs no D-Bus traffic. The
|
|
12
|
+
SSID is never read.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import asyncio
|
|
16
|
+
import contextlib
|
|
17
|
+
from collections.abc import Coroutine
|
|
18
|
+
from typing import Any, cast
|
|
19
|
+
|
|
20
|
+
from dbus_fast import Message, MessageType
|
|
21
|
+
|
|
22
|
+
from sensitivebox.sources.dbus import (
|
|
23
|
+
DBUS,
|
|
24
|
+
INVALID_REPLY,
|
|
25
|
+
NO_BUS,
|
|
26
|
+
PROPERTIES,
|
|
27
|
+
Bus,
|
|
28
|
+
DBusCallError,
|
|
29
|
+
add_match,
|
|
30
|
+
call,
|
|
31
|
+
get_property,
|
|
32
|
+
reason_for,
|
|
33
|
+
remove_match,
|
|
34
|
+
remove_matches,
|
|
35
|
+
signal_rule,
|
|
36
|
+
unwrap,
|
|
37
|
+
)
|
|
38
|
+
from sensitivebox.sources.wifi import SOURCE_NM, WifiSignal, WifiStatus
|
|
39
|
+
|
|
40
|
+
NM = "org.freedesktop.NetworkManager"
|
|
41
|
+
NM_PATH = "/org/freedesktop/NetworkManager"
|
|
42
|
+
DEVICE = f"{NM}.Device"
|
|
43
|
+
WIRELESS = f"{NM}.Device.Wireless"
|
|
44
|
+
ACCESS_POINT = f"{NM}.AccessPoint"
|
|
45
|
+
DEVICE_TYPE_WIFI = 2
|
|
46
|
+
|
|
47
|
+
NOT_RUNNING = f"{SOURCE_NM} not running"
|
|
48
|
+
NO_WIFI = "no Wi-Fi device"
|
|
49
|
+
NOT_CONNECTED = "Wi-Fi not connected"
|
|
50
|
+
|
|
51
|
+
NAME_OWNER_RULE = signal_rule(sender=DBUS, interface=DBUS, member="NameOwnerChanged", arg0=NM)
|
|
52
|
+
DEVICE_ADDED_RULE = signal_rule(sender=NM, interface=NM, member="DeviceAdded", path=NM_PATH)
|
|
53
|
+
DEVICE_REMOVED_RULE = signal_rule(sender=NM, interface=NM, member="DeviceRemoved", path=NM_PATH)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def props_rule(path: str, interface: str) -> str:
|
|
57
|
+
return signal_rule(
|
|
58
|
+
sender=NM, interface=PROPERTIES, member="PropertiesChanged", path=path, arg0=interface
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
async def find_wifi_device(bus: Bus) -> tuple[str, str] | None:
|
|
63
|
+
"""``(object path, interface name)`` of the first Wi-Fi device, by path."""
|
|
64
|
+
(paths,) = await call(bus, NM, NM_PATH, NM, "GetDevices", expected="ao")
|
|
65
|
+
for path in sorted(str(p) for p in paths):
|
|
66
|
+
if await get_property(bus, NM, path, DEVICE, "DeviceType") == DEVICE_TYPE_WIFI:
|
|
67
|
+
return path, str(await get_property(bus, NM, path, DEVICE, "Interface"))
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def signal_status(iface: str, strength: Any) -> WifiStatus:
|
|
72
|
+
if not isinstance(strength, int): # Strength is a byte; anything else is a broken reply
|
|
73
|
+
raise DBusCallError(INVALID_REPLY, f"Strength is {type(strength).__name__}")
|
|
74
|
+
percent = min(max(int(strength), 0), 100)
|
|
75
|
+
return WifiStatus.ok(WifiSignal(iface, percent, None, SOURCE_NM))
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
async def read_nm_wifi_once(bus: Bus | None) -> WifiStatus:
|
|
79
|
+
"""One-shot read for ``sensitivebox doctor``; the daemon uses ``NmWifiWatcher``."""
|
|
80
|
+
if bus is None:
|
|
81
|
+
return WifiStatus.unavailable(NO_BUS)
|
|
82
|
+
try:
|
|
83
|
+
found = await find_wifi_device(bus)
|
|
84
|
+
if found is None:
|
|
85
|
+
return WifiStatus.unavailable(NO_WIFI)
|
|
86
|
+
device, iface = found
|
|
87
|
+
ap = str(await get_property(bus, NM, device, WIRELESS, "ActiveAccessPoint"))
|
|
88
|
+
if ap in ("", "/"):
|
|
89
|
+
return WifiStatus.unavailable(NOT_CONNECTED)
|
|
90
|
+
return signal_status(iface, await get_property(bus, NM, ap, ACCESS_POINT, "Strength"))
|
|
91
|
+
except DBusCallError as exc:
|
|
92
|
+
return WifiStatus.unavailable(reason_for(exc, SOURCE_NM))
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class NmWifiWatcher:
|
|
96
|
+
def __init__(self) -> None:
|
|
97
|
+
self._bus: Bus | None = None
|
|
98
|
+
self._status = WifiStatus.unavailable("not started")
|
|
99
|
+
self._device: str | None = None
|
|
100
|
+
self._iface: str | None = None
|
|
101
|
+
self._ap: str | None = None
|
|
102
|
+
self._rules: set[str] = set()
|
|
103
|
+
self._tasks: set[asyncio.Task[None]] = set()
|
|
104
|
+
self._lock = asyncio.Lock()
|
|
105
|
+
|
|
106
|
+
def current(self) -> WifiStatus:
|
|
107
|
+
return self._status
|
|
108
|
+
|
|
109
|
+
async def start(self, bus: Bus | None) -> WifiStatus:
|
|
110
|
+
"""Subscribe and read once. Starting again on the same bus changes nothing; on another
|
|
111
|
+
bus, the old subscriptions are dropped first (ADV-017)."""
|
|
112
|
+
if bus is not None and bus is self._bus:
|
|
113
|
+
return self._status
|
|
114
|
+
await self.close()
|
|
115
|
+
if bus is None:
|
|
116
|
+
self._status = WifiStatus.unavailable(NO_BUS)
|
|
117
|
+
return self._status
|
|
118
|
+
self._bus = bus
|
|
119
|
+
bus.add_message_handler(self._on_message)
|
|
120
|
+
try:
|
|
121
|
+
for rule in (NAME_OWNER_RULE, DEVICE_ADDED_RULE, DEVICE_REMOVED_RULE):
|
|
122
|
+
await self._match(rule)
|
|
123
|
+
except DBusCallError as exc:
|
|
124
|
+
await self.close()
|
|
125
|
+
self._status = WifiStatus.unavailable(reason_for(exc, "D-Bus"))
|
|
126
|
+
return self._status
|
|
127
|
+
await self._rescan()
|
|
128
|
+
return self._status
|
|
129
|
+
|
|
130
|
+
async def settle(self) -> None:
|
|
131
|
+
"""Wait for the follow-up reads that signals scheduled (tests, orderly shutdown)."""
|
|
132
|
+
while self._tasks:
|
|
133
|
+
await asyncio.gather(*self._tasks)
|
|
134
|
+
|
|
135
|
+
async def close(self) -> None:
|
|
136
|
+
for task in self._tasks:
|
|
137
|
+
task.cancel()
|
|
138
|
+
await asyncio.gather(*self._tasks, return_exceptions=True)
|
|
139
|
+
bus, self._bus = self._bus, None
|
|
140
|
+
if bus is None:
|
|
141
|
+
return
|
|
142
|
+
bus.remove_message_handler(self._on_message)
|
|
143
|
+
rules, self._rules = sorted(self._rules), set()
|
|
144
|
+
self._device = self._iface = self._ap = None
|
|
145
|
+
await remove_matches(bus, rules)
|
|
146
|
+
|
|
147
|
+
# -- subscriptions ----------------------------------------------------------------------
|
|
148
|
+
|
|
149
|
+
async def _match(self, rule: str) -> None:
|
|
150
|
+
if self._bus is not None and rule not in self._rules:
|
|
151
|
+
await add_match(self._bus, rule)
|
|
152
|
+
self._rules.add(rule)
|
|
153
|
+
|
|
154
|
+
async def _unmatch(self, rule: str) -> None:
|
|
155
|
+
if self._bus is not None and rule in self._rules:
|
|
156
|
+
self._rules.discard(rule)
|
|
157
|
+
with contextlib.suppress(DBusCallError):
|
|
158
|
+
await remove_match(self._bus, rule)
|
|
159
|
+
|
|
160
|
+
async def _forget_device(self) -> None:
|
|
161
|
+
await self._forget_ap()
|
|
162
|
+
if self._device is not None:
|
|
163
|
+
await self._unmatch(props_rule(self._device, WIRELESS))
|
|
164
|
+
self._device = self._iface = None
|
|
165
|
+
|
|
166
|
+
async def _forget_ap(self) -> None:
|
|
167
|
+
if self._ap is not None:
|
|
168
|
+
await self._unmatch(props_rule(self._ap, ACCESS_POINT))
|
|
169
|
+
self._ap = None
|
|
170
|
+
|
|
171
|
+
# -- state ------------------------------------------------------------------------------
|
|
172
|
+
|
|
173
|
+
async def _rescan(self) -> None:
|
|
174
|
+
async with self._lock:
|
|
175
|
+
bus = self._bus
|
|
176
|
+
if bus is None:
|
|
177
|
+
return
|
|
178
|
+
try:
|
|
179
|
+
found = await find_wifi_device(bus)
|
|
180
|
+
if found is None:
|
|
181
|
+
await self._forget_device()
|
|
182
|
+
self._status = WifiStatus.unavailable(NO_WIFI)
|
|
183
|
+
return
|
|
184
|
+
device, iface = found
|
|
185
|
+
if device != self._device:
|
|
186
|
+
await self._forget_device()
|
|
187
|
+
# Subscribe before reading, so a change in between isn't missed.
|
|
188
|
+
await self._match(props_rule(device, WIRELESS))
|
|
189
|
+
self._device, self._iface = device, iface
|
|
190
|
+
ap = str(await get_property(bus, NM, device, WIRELESS, "ActiveAccessPoint"))
|
|
191
|
+
await self._follow_ap_locked(ap)
|
|
192
|
+
except DBusCallError as exc:
|
|
193
|
+
await self._forget_device()
|
|
194
|
+
self._status = WifiStatus.unavailable(reason_for(exc, SOURCE_NM))
|
|
195
|
+
|
|
196
|
+
async def _follow_ap(self, ap: str) -> None:
|
|
197
|
+
async with self._lock:
|
|
198
|
+
try:
|
|
199
|
+
await self._follow_ap_locked(ap)
|
|
200
|
+
except DBusCallError as exc:
|
|
201
|
+
await self._forget_ap()
|
|
202
|
+
self._status = WifiStatus.unavailable(reason_for(exc, SOURCE_NM))
|
|
203
|
+
|
|
204
|
+
async def _follow_ap_locked(self, ap: str) -> None:
|
|
205
|
+
if self._bus is None or self._iface is None:
|
|
206
|
+
return
|
|
207
|
+
if ap in ("", "/"):
|
|
208
|
+
await self._forget_ap()
|
|
209
|
+
self._status = WifiStatus.unavailable(NOT_CONNECTED)
|
|
210
|
+
return
|
|
211
|
+
if ap != self._ap:
|
|
212
|
+
await self._forget_ap()
|
|
213
|
+
await self._match(props_rule(ap, ACCESS_POINT))
|
|
214
|
+
self._ap = ap
|
|
215
|
+
strength = await get_property(self._bus, NM, ap, ACCESS_POINT, "Strength")
|
|
216
|
+
self._status = signal_status(self._iface, strength)
|
|
217
|
+
|
|
218
|
+
async def _nm_gone(self) -> None:
|
|
219
|
+
async with self._lock:
|
|
220
|
+
await self._forget_device()
|
|
221
|
+
self._status = WifiStatus.unavailable(NOT_RUNNING)
|
|
222
|
+
|
|
223
|
+
def _spawn(self, coro: Coroutine[Any, Any, None]) -> None:
|
|
224
|
+
task = asyncio.get_running_loop().create_task(coro)
|
|
225
|
+
self._tasks.add(task)
|
|
226
|
+
task.add_done_callback(self._tasks.discard)
|
|
227
|
+
|
|
228
|
+
# -- signals ----------------------------------------------------------------------------
|
|
229
|
+
|
|
230
|
+
def _on_message(self, msg: Message) -> None:
|
|
231
|
+
if msg.message_type != MessageType.SIGNAL:
|
|
232
|
+
return
|
|
233
|
+
body: list[Any] = msg.body
|
|
234
|
+
if msg.interface == DBUS and msg.member == "NameOwnerChanged":
|
|
235
|
+
if len(body) == 3 and body[0] == NM:
|
|
236
|
+
self._spawn(self._rescan() if body[2] else self._nm_gone())
|
|
237
|
+
elif msg.interface == PROPERTIES and msg.member == "PropertiesChanged":
|
|
238
|
+
self._on_properties_changed(msg.path, body)
|
|
239
|
+
elif (
|
|
240
|
+
msg.interface == NM
|
|
241
|
+
and msg.path == NM_PATH
|
|
242
|
+
and msg.member
|
|
243
|
+
in (
|
|
244
|
+
"DeviceAdded",
|
|
245
|
+
"DeviceRemoved",
|
|
246
|
+
)
|
|
247
|
+
):
|
|
248
|
+
self._spawn(self._rescan())
|
|
249
|
+
|
|
250
|
+
def _on_properties_changed(self, path: str | None, body: list[Any]) -> None:
|
|
251
|
+
if len(body) < 2 or not isinstance(body[1], dict):
|
|
252
|
+
return
|
|
253
|
+
interface: Any = body[0]
|
|
254
|
+
changed: dict[str, Any] = unwrap(body[1])
|
|
255
|
+
# A property can also be *invalidated*: it changed, but the new value isn't in the
|
|
256
|
+
# signal and has to be read (D-Bus spec, PropertiesChanged; review ADV-011).
|
|
257
|
+
names = cast(list[Any], body[2]) if len(body) > 2 and isinstance(body[2], list) else []
|
|
258
|
+
invalidated = {str(name) for name in names}
|
|
259
|
+
ap = self._ap
|
|
260
|
+
if ap is not None and path == ap and interface == ACCESS_POINT:
|
|
261
|
+
if "Strength" in changed and self._iface is not None:
|
|
262
|
+
self._status = signal_status(self._iface, changed["Strength"])
|
|
263
|
+
elif "Strength" in invalidated:
|
|
264
|
+
self._spawn(self._follow_ap(ap)) # re-reads Strength
|
|
265
|
+
elif path == self._device and interface == WIRELESS:
|
|
266
|
+
if "ActiveAccessPoint" in changed:
|
|
267
|
+
self._spawn(self._follow_ap(str(changed["ActiveAccessPoint"])))
|
|
268
|
+
elif "ActiveAccessPoint" in invalidated:
|
|
269
|
+
self._spawn(self._rescan()) # re-reads ActiveAccessPoint
|
sensitivebox/status.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Typed status and per-signal rule views, without starting a new alert engine."""
|
|
2
|
+
|
|
3
|
+
from collections import Counter
|
|
4
|
+
from collections.abc import Sequence
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
from sensitivebox.alerts import Rule, State, format_duration
|
|
8
|
+
from sensitivebox.alerts.model import Severity
|
|
9
|
+
from sensitivebox.doctor import format_bytes
|
|
10
|
+
from sensitivebox.hwmon import Group, Kind, ReadStatus
|
|
11
|
+
from sensitivebox.sample import Sample
|
|
12
|
+
from sensitivebox.store.db import FLUSH_EVERY_S
|
|
13
|
+
from sensitivebox.store.mutes import ActiveMute
|
|
14
|
+
from sensitivebox.store.status import History, poll_interval
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True, slots=True)
|
|
18
|
+
class RuleRow:
|
|
19
|
+
rule_id: str
|
|
20
|
+
signal: str | None
|
|
21
|
+
state: State
|
|
22
|
+
reason: str
|
|
23
|
+
fresh: bool
|
|
24
|
+
alert_severity: Severity | None = None
|
|
25
|
+
no_data: bool = False
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True, slots=True)
|
|
29
|
+
class RuleView:
|
|
30
|
+
rules: tuple[RuleRow, ...]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def rule_rows(
|
|
34
|
+
rules: Sequence[Rule], sample: Sample, history: History, now: float
|
|
35
|
+
) -> tuple[RuleRow, ...]:
|
|
36
|
+
stored = {(e.rule_id, e.signal): e for e in history.evaluations}
|
|
37
|
+
loaded = {r.id: r for r in history.rules}
|
|
38
|
+
rows: list[RuleRow] = []
|
|
39
|
+
for rule in rules:
|
|
40
|
+
matched = {s for s in sample.signals if rule.matches(s)}
|
|
41
|
+
matched.update(s for rid, s in stored if rid == rule.id and rule.matches(s))
|
|
42
|
+
if not matched:
|
|
43
|
+
rows.append(RuleRow(rule.id, None, State.UNKNOWN, "no matching signal", True))
|
|
44
|
+
for signal in sorted(matched):
|
|
45
|
+
entry = stored.get((rule.id, signal))
|
|
46
|
+
fresh = (
|
|
47
|
+
entry is not None
|
|
48
|
+
and entry.metadata_known
|
|
49
|
+
and loaded.get(rule.id) == rule
|
|
50
|
+
and 0
|
|
51
|
+
<= now - entry.at
|
|
52
|
+
<= 3 * poll_interval(signal, history.interval) + FLUSH_EVERY_S
|
|
53
|
+
)
|
|
54
|
+
if fresh and entry is not None:
|
|
55
|
+
rows.append(
|
|
56
|
+
RuleRow(
|
|
57
|
+
rule.id,
|
|
58
|
+
signal,
|
|
59
|
+
entry.state,
|
|
60
|
+
entry.reason,
|
|
61
|
+
True,
|
|
62
|
+
entry.alert_severity,
|
|
63
|
+
entry.no_data,
|
|
64
|
+
)
|
|
65
|
+
)
|
|
66
|
+
else:
|
|
67
|
+
reason = history.reason or "alert state stale or missing; start sbox watch"
|
|
68
|
+
if entry is not None and loaded.get(rule.id) != rule:
|
|
69
|
+
reason = "configured rule differs from daemon; restart sbox watch"
|
|
70
|
+
rows.append(RuleRow(rule.id, signal, State.UNKNOWN, reason, False))
|
|
71
|
+
return tuple(rows)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True, slots=True)
|
|
75
|
+
class Readings:
|
|
76
|
+
temperatures: dict[str, float]
|
|
77
|
+
fans: dict[str, float]
|
|
78
|
+
memory_used_pct: float | None
|
|
79
|
+
memory_pressure: float | None
|
|
80
|
+
swap_bytes: int | None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass(frozen=True, slots=True)
|
|
84
|
+
class Status:
|
|
85
|
+
host: str
|
|
86
|
+
host_uptime: float | None
|
|
87
|
+
health: int
|
|
88
|
+
fresh: bool
|
|
89
|
+
readings: Readings
|
|
90
|
+
open_alerts: dict[str, int]
|
|
91
|
+
states: dict[str, int]
|
|
92
|
+
rules_watching: int
|
|
93
|
+
hint: str | None
|
|
94
|
+
alerts: tuple[RuleRow, ...]
|
|
95
|
+
muted: tuple[ActiveMute, ...] | None = None
|
|
96
|
+
network_today: None = None
|
|
97
|
+
network_month: None = None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def status(sample: Sample, rows: Sequence[RuleRow]) -> Status:
|
|
101
|
+
active = Counter(r.alert_severity for r in rows if r.fresh and r.alert_severity is not None)
|
|
102
|
+
fresh = any(r.signal and r.fresh for r in rows) and all(r.fresh for r in rows)
|
|
103
|
+
health = 2 if active["critical"] else 1 if active["warning"] or not fresh else 0
|
|
104
|
+
temperatures: dict[str, float] = {}
|
|
105
|
+
fans: dict[str, float] = {}
|
|
106
|
+
for chip in sample.chips:
|
|
107
|
+
for sensor in chip.sensors:
|
|
108
|
+
value = sample.readings[sensor.id]
|
|
109
|
+
if value.status is ReadStatus.OK and value.value is not None:
|
|
110
|
+
if sensor.kind is Kind.TEMP:
|
|
111
|
+
temperatures[sensor.id] = value.value
|
|
112
|
+
elif sensor.kind is Kind.FAN:
|
|
113
|
+
fans[sensor.id] = value.value
|
|
114
|
+
memory = sample.sources.meminfo
|
|
115
|
+
pressure = sample.sources.pressure.get("memory")
|
|
116
|
+
readings = Readings(
|
|
117
|
+
temperatures,
|
|
118
|
+
fans,
|
|
119
|
+
memory.used_fraction * 100 if memory else None,
|
|
120
|
+
pressure.some.avg10 if pressure else None,
|
|
121
|
+
memory.swap_used if memory else None,
|
|
122
|
+
)
|
|
123
|
+
return Status(
|
|
124
|
+
sample.host,
|
|
125
|
+
sample.uptime,
|
|
126
|
+
health,
|
|
127
|
+
bool(fresh),
|
|
128
|
+
readings,
|
|
129
|
+
{s: active[s] for s in ("info", "warning", "critical")},
|
|
130
|
+
{s.value: sum(r.state == s for r in rows) for s in State},
|
|
131
|
+
len({r.rule_id for r in rows if r.signal is not None}),
|
|
132
|
+
None if fresh else "alert state stale or missing; start sbox watch",
|
|
133
|
+
tuple(r for r in rows if r.fresh and r.alert_severity is not None),
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def render_status(sample: Sample, view: Status) -> str:
|
|
138
|
+
state = (
|
|
139
|
+
"critical"
|
|
140
|
+
if view.health == 2
|
|
141
|
+
else "warning"
|
|
142
|
+
if view.open_alerts["warning"]
|
|
143
|
+
else "ok"
|
|
144
|
+
if view.fresh
|
|
145
|
+
else "unknown"
|
|
146
|
+
)
|
|
147
|
+
uptime = format_duration(view.host_uptime) if view.host_uptime is not None else "unavailable"
|
|
148
|
+
temperatures: list[str] = []
|
|
149
|
+
for group in (Group.CPU, Group.GPU, Group.STORAGE):
|
|
150
|
+
values = [
|
|
151
|
+
view.readings.temperatures[s.id]
|
|
152
|
+
for c in sample.chips
|
|
153
|
+
for s in c.sensors
|
|
154
|
+
if s.group == group and s.id in view.readings.temperatures
|
|
155
|
+
]
|
|
156
|
+
label = "NVMe" if group is Group.STORAGE else group.value
|
|
157
|
+
temperatures.append(f"{label} {max(values):g} °C" if values else f"{label} unavailable")
|
|
158
|
+
fans = "/".join(f"{v / 1000:.1f}k" for v in view.readings.fans.values())
|
|
159
|
+
temperatures.append(f"Fans {fans} RPM" if fans else "Fans unavailable")
|
|
160
|
+
reading = view.readings
|
|
161
|
+
memory = (
|
|
162
|
+
f"{reading.memory_used_pct:.0f} %" if reading.memory_used_pct is not None else "unavailable"
|
|
163
|
+
)
|
|
164
|
+
pressure = (
|
|
165
|
+
f"{reading.memory_pressure:.1f}" if reading.memory_pressure is not None else "unavailable"
|
|
166
|
+
)
|
|
167
|
+
swap = format_bytes(reading.swap_bytes) if reading.swap_bytes is not None else "unavailable"
|
|
168
|
+
active = " · ".join(f"{n} {s}" for s, n in view.open_alerts.items() if n) or "Nothing firing"
|
|
169
|
+
counts = " · ".join(f"{view.states[s]} {s}" for s in ("unknown", "warming", "pending"))
|
|
170
|
+
muted = (
|
|
171
|
+
"unavailable"
|
|
172
|
+
if view.muted is None
|
|
173
|
+
else str(len(view.muted))
|
|
174
|
+
+ " ("
|
|
175
|
+
+ ", ".join(
|
|
176
|
+
f"{m.rule_id}, "
|
|
177
|
+
+ (
|
|
178
|
+
"until reboot"
|
|
179
|
+
if m.remaining_s is None
|
|
180
|
+
else f"{format_duration(m.remaining_s)} left"
|
|
181
|
+
)
|
|
182
|
+
for m in view.muted
|
|
183
|
+
)
|
|
184
|
+
+ ")"
|
|
185
|
+
)
|
|
186
|
+
lines = [
|
|
187
|
+
f"{view.host} · {state} · host uptime {uptime}",
|
|
188
|
+
" ".join(temperatures),
|
|
189
|
+
f"Memory {memory} pressure {pressure} Swap {swap} "
|
|
190
|
+
"↓/↑ today: unavailable · month: unavailable",
|
|
191
|
+
f"{active} · {view.rules_watching} rules watching · muted: {muted} · {counts}",
|
|
192
|
+
]
|
|
193
|
+
lines.extend(f"{r.alert_severity} · {r.rule_id} · {r.signal}: {r.reason}" for r in view.alerts)
|
|
194
|
+
if view.hint:
|
|
195
|
+
lines.append(view.hint)
|
|
196
|
+
return "\n".join(lines)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def render_rules(rows: Sequence[RuleRow]) -> str:
|
|
200
|
+
return "\n".join(
|
|
201
|
+
[
|
|
202
|
+
"RULE SIGNAL STATE REASON",
|
|
203
|
+
*(f"{r.rule_id} {r.signal or '—'} {r.state.value} {r.reason}" for r in rows),
|
|
204
|
+
]
|
|
205
|
+
)
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Persistent baselines, change markers and bounded apt cursors."""
|
|
2
|
+
|
|
3
|
+
import sqlite3
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
from sensitivebox.alerts.engine import Clock
|
|
7
|
+
|
|
8
|
+
CREATE = (
|
|
9
|
+
"CREATE TABLE IF NOT EXISTS change_baselines (kind TEXT PRIMARY KEY,value TEXT NOT NULL)",
|
|
10
|
+
"""CREATE TABLE IF NOT EXISTS change_markers (
|
|
11
|
+
id INTEGER PRIMARY KEY, ts REAL NOT NULL, kind TEXT NOT NULL, value TEXT NOT NULL,
|
|
12
|
+
identity TEXT UNIQUE)""",
|
|
13
|
+
"""CREATE TABLE IF NOT EXISTS apt_cursors (
|
|
14
|
+
identity TEXT PRIMARY KEY, offset INTEGER NOT NULL, digest TEXT NOT NULL,
|
|
15
|
+
pending TEXT NOT NULL, updated REAL NOT NULL)""",
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True, slots=True)
|
|
20
|
+
class ChangeMarker:
|
|
21
|
+
id: int
|
|
22
|
+
ts: float
|
|
23
|
+
kind: str
|
|
24
|
+
value: str
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Changes:
|
|
28
|
+
def __init__(self, db: sqlite3.Connection, clock: Clock) -> None:
|
|
29
|
+
self.db, self.clock = db, clock
|
|
30
|
+
|
|
31
|
+
def observe(self, kind: str, value: str) -> None:
|
|
32
|
+
if not value:
|
|
33
|
+
return
|
|
34
|
+
with self.db:
|
|
35
|
+
row = self.db.execute(
|
|
36
|
+
"SELECT value FROM change_baselines WHERE kind=?", (kind,)
|
|
37
|
+
).fetchone()
|
|
38
|
+
if row and row[0] != value:
|
|
39
|
+
self.marker(kind, value)
|
|
40
|
+
self.db.execute("INSERT OR REPLACE INTO change_baselines VALUES(?,?)", (kind, value))
|
|
41
|
+
|
|
42
|
+
def marker(self, kind: str, value: str, identity: str | None = None) -> None:
|
|
43
|
+
self.db.execute(
|
|
44
|
+
"INSERT OR IGNORE INTO change_markers(ts,kind,value,identity) VALUES(?,?,?,?)",
|
|
45
|
+
(self.clock(), kind, value, identity),
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
def markers(self, limit: int = 1000) -> list[ChangeMarker]:
|
|
49
|
+
return [
|
|
50
|
+
ChangeMarker(*r)
|
|
51
|
+
for r in self.db.execute(
|
|
52
|
+
"SELECT id,ts,kind,value FROM change_markers ORDER BY id DESC LIMIT ?", (limit,)
|
|
53
|
+
)
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
def prune(self, now: float) -> None:
|
|
57
|
+
self.db.execute("DELETE FROM change_markers WHERE ts<?", (now - 400 * 86400,))
|
|
58
|
+
self.db.execute("DELETE FROM apt_cursors WHERE updated<?", (now - 400 * 86400,))
|