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/runtime.py
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
"""Assemble the foreground watcher and packaged demos.
|
|
2
|
+
|
|
3
|
+
Watch reads sysfs/procfs and stores real history. Demo uses packaged or explicitly selected
|
|
4
|
+
fixture inputs and scripted readings, with in-memory history and optional desktop popups.
|
|
5
|
+
Buses are injected; an explicit machine root never connects host buses. The collector, engine,
|
|
6
|
+
store and notifier pipeline are shared by live monitoring and demos.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import socket
|
|
11
|
+
import time
|
|
12
|
+
import uuid
|
|
13
|
+
from collections.abc import Awaitable, Callable
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from sensitivebox import __version__
|
|
18
|
+
from sensitivebox.alerts import Engine, Router, Rule
|
|
19
|
+
from sensitivebox.alerts.engine import Clock
|
|
20
|
+
from sensitivebox.alerts.mute import PersistentMute, boot_id
|
|
21
|
+
from sensitivebox.api import ApiState, create_app
|
|
22
|
+
from sensitivebox.api.server import serve_api
|
|
23
|
+
from sensitivebox.collector import Collector
|
|
24
|
+
from sensitivebox.daemon import Daemon, SignalSource, TickResult
|
|
25
|
+
from sensitivebox.fixtures import MachineRoot
|
|
26
|
+
from sensitivebox.hwmon.reader import default_opener
|
|
27
|
+
from sensitivebox.live import live_status, render_live
|
|
28
|
+
from sensitivebox.notify import DesktopNotifier, LogNotifier, Notifier, NotifierHub
|
|
29
|
+
from sensitivebox.output import Document, encode
|
|
30
|
+
from sensitivebox.redact import device_label, redact
|
|
31
|
+
from sensitivebox.simulate import Simulation, fixture_opener, resolve_fixture, scenario_named
|
|
32
|
+
from sensitivebox.sources.bluez import BluetoothStatus
|
|
33
|
+
from sensitivebox.sources.bluez_watch import BluezWatcher
|
|
34
|
+
from sensitivebox.sources.changes import ChangeTracker
|
|
35
|
+
from sensitivebox.sources.dbus import Bus
|
|
36
|
+
from sensitivebox.sources.logind import LogindWatcher
|
|
37
|
+
from sensitivebox.sources.power_profiles import PowerProfileWatcher
|
|
38
|
+
from sensitivebox.sources.wifi import choose
|
|
39
|
+
from sensitivebox.sources.wifi_nm import NmWifiWatcher
|
|
40
|
+
from sensitivebox.store import Store
|
|
41
|
+
|
|
42
|
+
HEARTBEAT_S = 30.0
|
|
43
|
+
MAX_GAP_POLLS = 3 # docs/BIBLE.md, "Time"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True, slots=True)
|
|
47
|
+
class RunOptions:
|
|
48
|
+
sysfs_root: Path
|
|
49
|
+
proc_root: Path
|
|
50
|
+
interval: float
|
|
51
|
+
db: Path | None # None: in memory
|
|
52
|
+
simulate: str | None = None
|
|
53
|
+
scenario: str = "idle"
|
|
54
|
+
desktop: bool = True # send desktop notifications
|
|
55
|
+
heartbeat_s: float = HEARTBEAT_S
|
|
56
|
+
root: MachineRoot | None = None
|
|
57
|
+
json: bool = False
|
|
58
|
+
fixture_notifications: bool = False
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(frozen=True, slots=True)
|
|
62
|
+
class Buses:
|
|
63
|
+
system: Bus | None = None # BlueZ, logind
|
|
64
|
+
session: Bus | None = None # desktop notifications
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _run_all(hooks: list[Callable[[], None]]) -> None:
|
|
68
|
+
for hook in hooks:
|
|
69
|
+
hook()
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def describe_bluetooth(status: BluetoothStatus) -> str:
|
|
73
|
+
if not status.available:
|
|
74
|
+
return f"bluetooth: {status.reason}"
|
|
75
|
+
state = "on" if status.powered else "off"
|
|
76
|
+
devices = ", ".join(device_label(d) for d in status.devices) # never device names
|
|
77
|
+
return f"bluetooth: {state}" + (f" · {devices}" if devices else " · no devices connected")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
async def run_daemon(
|
|
81
|
+
options: RunOptions,
|
|
82
|
+
rules: list[Rule],
|
|
83
|
+
buses: Buses,
|
|
84
|
+
stop: asyncio.Event,
|
|
85
|
+
out: Callable[[str], None] = print,
|
|
86
|
+
*,
|
|
87
|
+
clock: Clock = time.monotonic,
|
|
88
|
+
wall: Clock = time.time,
|
|
89
|
+
sleep: Callable[[float], Awaitable[None]] | None = None,
|
|
90
|
+
) -> None:
|
|
91
|
+
|
|
92
|
+
def say(line: str, kind: str = "message", data: object | None = None) -> None:
|
|
93
|
+
out(
|
|
94
|
+
encode(Document(kind, data if data is not None else line))
|
|
95
|
+
if options.json
|
|
96
|
+
else redact(line)
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
simulated = options.simulate is not None
|
|
100
|
+
if options.root is not None:
|
|
101
|
+
sysfs_root, proc_root = options.root.sys, options.root.proc
|
|
102
|
+
elif options.simulate is not None:
|
|
103
|
+
fixture = resolve_fixture(options.simulate)
|
|
104
|
+
sysfs_root, proc_root = fixture.sys, fixture.proc
|
|
105
|
+
else:
|
|
106
|
+
sysfs_root, proc_root = options.sysfs_root, options.proc_root
|
|
107
|
+
collector = Collector(
|
|
108
|
+
sysfs_root,
|
|
109
|
+
proc_root,
|
|
110
|
+
clock=clock,
|
|
111
|
+
poll_interval=options.interval,
|
|
112
|
+
opener=fixture_opener if simulated or options.root is not None else default_opener,
|
|
113
|
+
)
|
|
114
|
+
source: SignalSource = collector
|
|
115
|
+
simulation: Simulation | None = None
|
|
116
|
+
if options.simulate is not None:
|
|
117
|
+
simulation = Simulation(collector, scenario_named(options.scenario), clock)
|
|
118
|
+
source = simulation
|
|
119
|
+
|
|
120
|
+
store = Store(options.db, clock=wall)
|
|
121
|
+
engine = Engine(
|
|
122
|
+
rules,
|
|
123
|
+
clock=clock,
|
|
124
|
+
limits=collector.limits,
|
|
125
|
+
journal=store.journal,
|
|
126
|
+
max_gap=MAX_GAP_POLLS * options.interval, # a longer gap is MISSING, never breach time
|
|
127
|
+
)
|
|
128
|
+
notifiers: list[Notifier] = [
|
|
129
|
+
LogNotifier(say, now=wall, event=lambda n, text: say(text, "alert", n))
|
|
130
|
+
]
|
|
131
|
+
if options.desktop and buses.session is not None:
|
|
132
|
+
notifiers.append(DesktopNotifier(buses.session))
|
|
133
|
+
|
|
134
|
+
hooks: list[Callable[[], None]] = [] # the simulation's, once the daemon exists
|
|
135
|
+
heartbeat = _Heartbeat(
|
|
136
|
+
say,
|
|
137
|
+
wall,
|
|
138
|
+
clock,
|
|
139
|
+
options.heartbeat_s,
|
|
140
|
+
lambda: daemon.firing(),
|
|
141
|
+
emit=lambda kind, data, text: say(text, kind, data),
|
|
142
|
+
)
|
|
143
|
+
try:
|
|
144
|
+
boot = boot_id(proc_root)
|
|
145
|
+
except OSError:
|
|
146
|
+
boot = uuid.uuid4().hex # unavailable boot identity cannot carry mutes across sessions
|
|
147
|
+
mute = PersistentMute(store.mutes, boot, clock, wall)
|
|
148
|
+
router = Router(mute=mute)
|
|
149
|
+
router_key = f"router:{boot}"
|
|
150
|
+
row = store.mutes.db.execute(
|
|
151
|
+
"SELECT value FROM operations_meta WHERE key=?", (router_key,)
|
|
152
|
+
).fetchone()
|
|
153
|
+
if row:
|
|
154
|
+
router.restore(row[0])
|
|
155
|
+
engine.restore_alerts(router.open_alerts())
|
|
156
|
+
|
|
157
|
+
previous_router = str(row[0]) if row else None
|
|
158
|
+
|
|
159
|
+
def save_router(payload: str) -> None:
|
|
160
|
+
nonlocal previous_router
|
|
161
|
+
if payload == previous_router:
|
|
162
|
+
return
|
|
163
|
+
with store.mutes.db:
|
|
164
|
+
store.mutes.db.execute("DELETE FROM operations_meta WHERE key LIKE 'router:%'")
|
|
165
|
+
store.mutes.db.execute("INSERT INTO operations_meta VALUES(?,?)", (router_key, payload))
|
|
166
|
+
previous_router = payload
|
|
167
|
+
|
|
168
|
+
bluez = BluezWatcher(lambda status: say(describe_bluetooth(status)))
|
|
169
|
+
wifi = NmWifiWatcher()
|
|
170
|
+
fixture_bluetooth: BluetoothStatus | None = None
|
|
171
|
+
fixture_wifi = None
|
|
172
|
+
api = ApiState(
|
|
173
|
+
store,
|
|
174
|
+
collector,
|
|
175
|
+
engine=engine,
|
|
176
|
+
clock=clock,
|
|
177
|
+
wall=wall,
|
|
178
|
+
boot=boot,
|
|
179
|
+
interval=options.interval,
|
|
180
|
+
bluetooth=lambda: fixture_bluetooth if fixture_bluetooth is not None else bluez.current(),
|
|
181
|
+
wifi=lambda: choose(
|
|
182
|
+
collector.wireless, fixture_wifi if fixture_wifi is not None else wifi.current()
|
|
183
|
+
),
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
def tick(result: TickResult) -> None:
|
|
187
|
+
heartbeat.tick(result)
|
|
188
|
+
api.tick(result)
|
|
189
|
+
|
|
190
|
+
daemon = Daemon(
|
|
191
|
+
source=source,
|
|
192
|
+
engine=engine,
|
|
193
|
+
router=router,
|
|
194
|
+
save_router=save_router,
|
|
195
|
+
muted=lambda: store.mutes.active(boot, clock()),
|
|
196
|
+
store=store,
|
|
197
|
+
notifiers=NotifierHub(notifiers),
|
|
198
|
+
clock=clock,
|
|
199
|
+
interval=options.interval,
|
|
200
|
+
sleep=sleep,
|
|
201
|
+
on_loop=lambda: _run_all(hooks),
|
|
202
|
+
on_tick=tick,
|
|
203
|
+
)
|
|
204
|
+
if simulation is not None:
|
|
205
|
+
hooks.append(simulation.loop_hook(daemon.on_suspend, daemon.on_resume))
|
|
206
|
+
|
|
207
|
+
apt_root = (
|
|
208
|
+
options.root.path / "var/log/apt"
|
|
209
|
+
if options.root is not None
|
|
210
|
+
else Path("/var/log/apt")
|
|
211
|
+
if not simulated and proc_root == Path("/proc") and sysfs_root == Path("/sys")
|
|
212
|
+
else proc_root.parent / "var/log/apt"
|
|
213
|
+
)
|
|
214
|
+
tracker = ChangeTracker(store.changes, sysfs_root, proc_root, apt_root)
|
|
215
|
+
last_changes = float("-inf")
|
|
216
|
+
|
|
217
|
+
def scan_changes() -> None:
|
|
218
|
+
nonlocal last_changes
|
|
219
|
+
if clock() - last_changes >= 60:
|
|
220
|
+
tracker.scan(__version__)
|
|
221
|
+
last_changes = clock()
|
|
222
|
+
|
|
223
|
+
hooks.append(scan_changes)
|
|
224
|
+
profiles = PowerProfileWatcher(lambda value: store.changes.observe("power_profile", value))
|
|
225
|
+
logind = LogindWatcher(daemon.on_suspend, daemon.on_resume)
|
|
226
|
+
say(_banner(options, collector, rules, simulation), "startup")
|
|
227
|
+
if options.desktop and buses.session is None:
|
|
228
|
+
say("notifications were not sent: no session bus; start a desktop session for popups")
|
|
229
|
+
try:
|
|
230
|
+
if options.root is not None:
|
|
231
|
+
fixture_bluetooth, fixture_wifi = await options.root.snapshot()
|
|
232
|
+
say(describe_bluetooth(fixture_bluetooth))
|
|
233
|
+
elif not simulated:
|
|
234
|
+
await profiles.start(buses.system)
|
|
235
|
+
await bluez.start(buses.system)
|
|
236
|
+
await wifi.start(buses.system)
|
|
237
|
+
if not await logind.start(buses.system):
|
|
238
|
+
say("sleep/resume: logind not available; evaluation won't pause across sleep")
|
|
239
|
+
os_release = (
|
|
240
|
+
Path("/etc/os-release")
|
|
241
|
+
if not simulated and options.root is None and proc_root == Path("/proc")
|
|
242
|
+
else proc_root.parent / "etc/os-release"
|
|
243
|
+
)
|
|
244
|
+
app = create_app(api, proc_root=proc_root, os_release=os_release)
|
|
245
|
+
async with serve_api(app, say):
|
|
246
|
+
try:
|
|
247
|
+
await daemon.run(stop)
|
|
248
|
+
finally:
|
|
249
|
+
api.close()
|
|
250
|
+
finally:
|
|
251
|
+
await profiles.close()
|
|
252
|
+
await bluez.close()
|
|
253
|
+
await wifi.close()
|
|
254
|
+
await logind.close()
|
|
255
|
+
store.close()
|
|
256
|
+
say("stopped", "stopped")
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _store_label(options: RunOptions) -> str:
|
|
260
|
+
return "memory (simulation)" if options.db is None else str(options.db)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _banner(
|
|
264
|
+
options: RunOptions,
|
|
265
|
+
collector: Collector,
|
|
266
|
+
rules: list[Rule],
|
|
267
|
+
simulation: Simulation | None,
|
|
268
|
+
) -> str:
|
|
269
|
+
lines = [
|
|
270
|
+
f"Sensitive Box {__version__} · {socket.gethostname()} · polling every "
|
|
271
|
+
f"{options.interval:g} s",
|
|
272
|
+
f"{len(collector.limits)} sensors · {len(rules)} rules · store: {_store_label(options)}",
|
|
273
|
+
]
|
|
274
|
+
if simulation is not None:
|
|
275
|
+
scenario = simulation.scenario
|
|
276
|
+
lines.append(
|
|
277
|
+
f"simulating {options.simulate} · scenario {scenario.name}: {scenario.description}"
|
|
278
|
+
)
|
|
279
|
+
lines.append("Ctrl-C to stop")
|
|
280
|
+
return "\n".join(lines)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
class _Heartbeat:
|
|
284
|
+
"""One quiet status line every ``every`` seconds, so a silent run is visibly alive."""
|
|
285
|
+
|
|
286
|
+
def __init__(
|
|
287
|
+
self,
|
|
288
|
+
out: Callable[[str], None],
|
|
289
|
+
wall: Clock,
|
|
290
|
+
clock: Clock,
|
|
291
|
+
every: float,
|
|
292
|
+
firing: Callable[[], int],
|
|
293
|
+
emit: Callable[[str, object, str], None] | None = None,
|
|
294
|
+
) -> None:
|
|
295
|
+
self._out, self._wall, self._clock, self._every = out, wall, clock, every
|
|
296
|
+
self._firing = firing
|
|
297
|
+
self._emit = emit
|
|
298
|
+
self._last = clock()
|
|
299
|
+
|
|
300
|
+
def tick(self, result: TickResult) -> None:
|
|
301
|
+
now = self._clock()
|
|
302
|
+
if now - self._last < self._every:
|
|
303
|
+
return
|
|
304
|
+
self._last = now
|
|
305
|
+
stamp = time.strftime("%H:%M:%S", time.localtime(self._wall()))
|
|
306
|
+
self._out(
|
|
307
|
+
f"{stamp} ok {len(result.snapshot.signals)} signals · {self._firing()} firing"
|
|
308
|
+
)
|
|
309
|
+
view = live_status(result)
|
|
310
|
+
if self._emit is not None:
|
|
311
|
+
self._emit("status", view, render_live(view))
|
|
312
|
+
else:
|
|
313
|
+
self._out(render_live(view))
|
sensitivebox/sample.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""One fresh read of available sources for one-shot CLI commands."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import socket
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from sensitivebox import hwmon, sources
|
|
9
|
+
from sensitivebox.alerts import Missing
|
|
10
|
+
from sensitivebox.alerts.model import Value
|
|
11
|
+
from sensitivebox.fixtures import MachineRoot
|
|
12
|
+
from sensitivebox.hwmon import Chip, Reading, ReadStatus
|
|
13
|
+
from sensitivebox.hwmon.reader import default_opener, read_attr
|
|
14
|
+
from sensitivebox.simulate import fixture_opener
|
|
15
|
+
from sensitivebox.sources import SourcesReport
|
|
16
|
+
from sensitivebox.sources.power_supply import read_power_supplies
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True, slots=True)
|
|
20
|
+
class Sample:
|
|
21
|
+
host: str
|
|
22
|
+
uptime: float | None
|
|
23
|
+
chips: tuple[Chip, ...]
|
|
24
|
+
readings: dict[str, Reading]
|
|
25
|
+
sources: SourcesReport
|
|
26
|
+
signals: dict[str, Value]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
async def sample(sysfs_root: Path, proc_root: Path, root: MachineRoot | None = None) -> Sample:
|
|
30
|
+
opener = fixture_opener if root is not None else default_opener
|
|
31
|
+
try:
|
|
32
|
+
chips = tuple(hwmon.discover(sysfs_root, opener=opener))
|
|
33
|
+
except FileNotFoundError:
|
|
34
|
+
chips = ()
|
|
35
|
+
readings = hwmon.read_all(chips, opener)
|
|
36
|
+
report = sources.gather(proc_root, sysfs_root, opener)
|
|
37
|
+
bt, wifi = await (root.snapshot() if root is not None else sources.system_bus_snapshot())
|
|
38
|
+
report = sources.with_dbus(report, bt, wifi)
|
|
39
|
+
signals: dict[str, Value] = {
|
|
40
|
+
name: r.value
|
|
41
|
+
if r.status is ReadStatus.OK and r.value is not None
|
|
42
|
+
else Missing(r.reason or r.status.value)
|
|
43
|
+
for name, r in readings.items()
|
|
44
|
+
}
|
|
45
|
+
pressure = report.pressure.get("memory")
|
|
46
|
+
signals["psi/memory/some_avg10"] = (
|
|
47
|
+
pressure.some.avg10 if pressure else Missing("PSI unavailable")
|
|
48
|
+
)
|
|
49
|
+
signals["psi/memory/full_avg10"] = (
|
|
50
|
+
pressure.full.avg10 if pressure and pressure.full else Missing("PSI unavailable")
|
|
51
|
+
)
|
|
52
|
+
mem = report.meminfo
|
|
53
|
+
signals["memory/available_pct"] = (
|
|
54
|
+
mem.available / mem.total * 100 if mem and mem.total else Missing("memory unavailable")
|
|
55
|
+
)
|
|
56
|
+
signals["vmstat/oom_kill_delta"] = Missing("one sample: no counter baseline")
|
|
57
|
+
for supply in read_power_supplies(sysfs_root, opener):
|
|
58
|
+
prefix = f"power_supply/{supply.name}"
|
|
59
|
+
if supply.kind == "Battery":
|
|
60
|
+
signals[f"{prefix}/capacity"] = (
|
|
61
|
+
float(supply.capacity)
|
|
62
|
+
if supply.capacity is not None
|
|
63
|
+
else Missing("capacity unavailable")
|
|
64
|
+
)
|
|
65
|
+
signals[f"{prefix}/status"] = supply.status or Missing("status unavailable")
|
|
66
|
+
if supply.is_usb_source:
|
|
67
|
+
signals[f"{prefix}/power_w"] = (
|
|
68
|
+
supply.power_w
|
|
69
|
+
if supply.online is not False and supply.power_w is not None
|
|
70
|
+
else Missing("port offline")
|
|
71
|
+
)
|
|
72
|
+
text = read_attr(proc_root / "uptime", opener)
|
|
73
|
+
try:
|
|
74
|
+
uptime = float(text.split()[0]) if text else None
|
|
75
|
+
if uptime is not None and (not math.isfinite(uptime) or uptime < 0):
|
|
76
|
+
uptime = None
|
|
77
|
+
except (ValueError, IndexError):
|
|
78
|
+
uptime = None
|
|
79
|
+
host = (
|
|
80
|
+
read_attr(proc_root / "sys/kernel/hostname", opener) or "fixture host"
|
|
81
|
+
if root is not None
|
|
82
|
+
else socket.gethostname()
|
|
83
|
+
)
|
|
84
|
+
return Sample(host.strip(), uptime, chips, readings, report, signals)
|
sensitivebox/service.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Install and manage the user service, preserving all differing user-owned files."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import shutil
|
|
5
|
+
import sys
|
|
6
|
+
from collections.abc import Callable, Sequence
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from importlib.resources import files
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from sensitivebox.process import run as run_process
|
|
12
|
+
from sensitivebox.redact import redact
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True, slots=True)
|
|
16
|
+
class ServicePaths:
|
|
17
|
+
config: Path
|
|
18
|
+
data: Path
|
|
19
|
+
executable: Path
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
def unit(self) -> Path:
|
|
23
|
+
return self.config / "systemd/user/sensitivebox.service"
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def launcher(self) -> Path:
|
|
27
|
+
return self.data / "applications/sensitivebox.desktop"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def default_paths() -> ServicePaths:
|
|
31
|
+
executable = shutil.which("sbox") or str(Path(sys.executable).with_name("sbox"))
|
|
32
|
+
return ServicePaths(
|
|
33
|
+
Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config"),
|
|
34
|
+
Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local/share"),
|
|
35
|
+
Path(executable).absolute(),
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def quoted(executable: Path, *, desktop: bool = False) -> str:
|
|
40
|
+
value = str(executable)
|
|
41
|
+
if any(c in value for c in "\n\r\0") or not executable.is_absolute():
|
|
42
|
+
raise OSError("service executable needs an absolute path without control characters")
|
|
43
|
+
if desktop:
|
|
44
|
+
value = value.replace("\\", "\\\\\\\\").replace('"', '\\\\"')
|
|
45
|
+
value = value.replace("`", "\\\\`").replace("$", "\\\\$")
|
|
46
|
+
else:
|
|
47
|
+
value = value.replace("\\", "\\\\").replace('"', '\\"').replace("$", "$$")
|
|
48
|
+
return '"' + value.replace("%", "%%") + '"'
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
ICON_SIZES = (128, 256, 512)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _matches(path: Path, content: str | bytes) -> bool:
|
|
55
|
+
if not path.is_file():
|
|
56
|
+
return False
|
|
57
|
+
if isinstance(content, bytes):
|
|
58
|
+
return path.read_bytes() == content
|
|
59
|
+
return path.read_text() == content
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _create(path: Path, content: str | bytes) -> None:
|
|
63
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
64
|
+
data = content.encode() if isinstance(content, str) else content
|
|
65
|
+
with path.open("xb") as stream:
|
|
66
|
+
stream.write(data)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def manage(
|
|
70
|
+
enabled: bool,
|
|
71
|
+
*,
|
|
72
|
+
paths: ServicePaths | None = None,
|
|
73
|
+
run: Callable[[Sequence[str]], str] = run_process,
|
|
74
|
+
) -> str:
|
|
75
|
+
paths = paths or default_paths()
|
|
76
|
+
resource = files("sensitivebox").joinpath("data")
|
|
77
|
+
expected: tuple[tuple[Path, str | bytes], ...] = (
|
|
78
|
+
(
|
|
79
|
+
paths.unit,
|
|
80
|
+
resource.joinpath("sensitivebox.service.in")
|
|
81
|
+
.read_text()
|
|
82
|
+
.replace("@EXECUTABLE@", quoted(paths.executable)),
|
|
83
|
+
),
|
|
84
|
+
(
|
|
85
|
+
paths.launcher,
|
|
86
|
+
resource.joinpath("sensitivebox.desktop.in")
|
|
87
|
+
.read_text()
|
|
88
|
+
.replace("@EXECUTABLE@", quoted(paths.executable, desktop=True)),
|
|
89
|
+
),
|
|
90
|
+
*(
|
|
91
|
+
(
|
|
92
|
+
paths.data / f"icons/hicolor/{size}x{size}/apps/sensitivebox.png",
|
|
93
|
+
resource.joinpath(f"icons/{size}.png").read_bytes(),
|
|
94
|
+
)
|
|
95
|
+
for size in ICON_SIZES
|
|
96
|
+
),
|
|
97
|
+
)
|
|
98
|
+
# Check every destination before creating any. Symlinks are never installed over.
|
|
99
|
+
for path, content in expected:
|
|
100
|
+
if path.is_symlink() or (path.exists() and not _matches(path, content)):
|
|
101
|
+
raise OSError(redact(f"{path} differs from generated file; refusing to overwrite"))
|
|
102
|
+
if enabled:
|
|
103
|
+
for path, content in expected:
|
|
104
|
+
if not path.exists():
|
|
105
|
+
_create(path, content)
|
|
106
|
+
run(["systemctl", "--user", "daemon-reload"])
|
|
107
|
+
run(
|
|
108
|
+
["systemctl", "--user", "enable" if enabled else "disable", "--now", "sensitivebox.service"]
|
|
109
|
+
)
|
|
110
|
+
return (
|
|
111
|
+
"Sensitive Box enabled and started." if enabled else "Sensitive Box stopped and disabled."
|
|
112
|
+
)
|