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/simulate.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""Scripted scenarios for ``sbox demo <scenario>``.
|
|
2
|
+
|
|
3
|
+
The simulator reads the fixture through the real :class:`~sensitivebox.collector.Collector`, so
|
|
4
|
+
every signal has the right name and shape, then replaces some of the values with a script. The
|
|
5
|
+
daemon, engine, store and notifiers run unchanged: it is for UI development, demos, screenshots
|
|
6
|
+
and the alerting scenario tests, never a second code path.
|
|
7
|
+
|
|
8
|
+
A scenario is data: *curves* (a signal glob and piecewise-linear points ``(seconds, value)``),
|
|
9
|
+
*pulses* (a value for one poll, for event-like signals such as an OOM kill) and *events*
|
|
10
|
+
(``suspend``/``resume``, as logind would send them). Seconds count from the start of the run.
|
|
11
|
+
Curves only replace signals that have a real value; a MISSING signal stays MISSING.
|
|
12
|
+
|
|
13
|
+
Every scenario also gives the simulated machine a proper 60 W USB-C charger, so the only alerts
|
|
14
|
+
you see are the ones the scenario is about (the fixture's own port is a 7.5 W slow charger).
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import errno
|
|
18
|
+
import os
|
|
19
|
+
from collections.abc import Callable, Mapping
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from fnmatch import fnmatchcase
|
|
22
|
+
from itertools import pairwise
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Literal
|
|
25
|
+
|
|
26
|
+
from sensitivebox.alerts.engine import Clock
|
|
27
|
+
from sensitivebox.alerts.model import Missing, Value
|
|
28
|
+
from sensitivebox.collector import Collector, Snapshot
|
|
29
|
+
from sensitivebox.fixtures import FixtureError, MachineRoot, demo_root
|
|
30
|
+
from sensitivebox.hwmon.model import Limits
|
|
31
|
+
|
|
32
|
+
type Curve = tuple[tuple[float, float], ...]
|
|
33
|
+
type EventKind = Literal["suspend", "resume"]
|
|
34
|
+
|
|
35
|
+
CPU_TEMP = ("k10temp/*/temp1", "coretemp/*/temp1")
|
|
36
|
+
GPU_TEMP = ("amdgpu/*/temp1",)
|
|
37
|
+
USB_C_POWER = "power_supply/ucsi-source-psy-*/power_w"
|
|
38
|
+
PSI_SOME = "psi/memory/some_avg10"
|
|
39
|
+
PSI_FULL = "psi/memory/full_avg10"
|
|
40
|
+
AVAILABLE = "memory/available_pct"
|
|
41
|
+
OOM = "vmstat/oom_kill_delta"
|
|
42
|
+
|
|
43
|
+
ENODATA_MARKER = "<ENODATA>"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class SimulationError(Exception):
|
|
47
|
+
"""Something the user asked for that can't be simulated, in words they can act on."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def value_at(curve: Curve, t: float) -> float:
|
|
51
|
+
"""Piecewise-linear: held at the first value before the first point and at the last after."""
|
|
52
|
+
if t <= curve[0][0]:
|
|
53
|
+
return curve[0][1]
|
|
54
|
+
for (t0, v0), (t1, v1) in pairwise(curve):
|
|
55
|
+
if t <= t1:
|
|
56
|
+
return v0 + (v1 - v0) * (t - t0) / (t1 - t0)
|
|
57
|
+
return curve[-1][1]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True, slots=True)
|
|
61
|
+
class Pulse:
|
|
62
|
+
glob: str
|
|
63
|
+
at: float # seconds; the value is published on the first poll at or after this
|
|
64
|
+
value: float
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass(frozen=True, slots=True)
|
|
68
|
+
class Scenario:
|
|
69
|
+
name: str
|
|
70
|
+
description: str
|
|
71
|
+
curves: Mapping[str, Curve]
|
|
72
|
+
pulses: tuple[Pulse, ...] = ()
|
|
73
|
+
events: tuple[tuple[float, EventKind], ...] = ()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _curves(globs: tuple[str, ...], curve: Curve) -> dict[str, Curve]:
|
|
77
|
+
return dict.fromkeys(globs, curve)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
GOOD_CHARGER: dict[str, Curve] = {USB_C_POWER: ((0.0, 60.0),)}
|
|
81
|
+
|
|
82
|
+
# CPU 40 -> 95 degC in a minute, then cooling (the bible's example). cpu-hot fires about 65 s in
|
|
83
|
+
# (90 degC held for 10 s) and resolves about 113 s in (below 85 for 10 s).
|
|
84
|
+
HEATWAVE_CPU: Curve = ((0, 40), (60, 95), (75, 95), (105, 84))
|
|
85
|
+
|
|
86
|
+
SCENARIOS: dict[str, Scenario] = {
|
|
87
|
+
s.name: s
|
|
88
|
+
for s in (
|
|
89
|
+
Scenario("idle", "Fixture values, nothing wrong: no alert fires.", dict(GOOD_CHARGER)),
|
|
90
|
+
Scenario(
|
|
91
|
+
"heatwave",
|
|
92
|
+
"CPU climbs 40 to 95 degC and cools again: 'CPU hot' fires about 65 s in and "
|
|
93
|
+
"resolves about 113 s in. The GPU warms up but stays below its limit.",
|
|
94
|
+
{
|
|
95
|
+
**GOOD_CHARGER,
|
|
96
|
+
**_curves(CPU_TEMP, HEATWAVE_CPU),
|
|
97
|
+
**_curves(GPU_TEMP, ((0, 45), (60, 78), (105, 60))),
|
|
98
|
+
},
|
|
99
|
+
),
|
|
100
|
+
Scenario(
|
|
101
|
+
"memory-crunch",
|
|
102
|
+
"Memory runs out, then recovers: 'Memory stall' fires about 39 s in, 'Memory "
|
|
103
|
+
"pressure' about 57 s, 'Low memory' about 79 s, an OOM kill is reported at 75 s, "
|
|
104
|
+
"and everything resolves by about 135 s.",
|
|
105
|
+
{
|
|
106
|
+
**GOOD_CHARGER,
|
|
107
|
+
AVAILABLE: ((0, 35), (60, 4), (90, 4), (110, 40)),
|
|
108
|
+
PSI_SOME: ((0, 0), (45, 34), (90, 34), (105, 5)),
|
|
109
|
+
PSI_FULL: ((0, 0), (45, 7.8), (90, 7.8), (105, 0)),
|
|
110
|
+
},
|
|
111
|
+
pulses=(Pulse(OOM, 75.0, 1.0),),
|
|
112
|
+
),
|
|
113
|
+
Scenario(
|
|
114
|
+
"suspend-resume",
|
|
115
|
+
"The lid closes while 'CPU hot' is open: suspend at 55 s, resume at 75 s. Nothing "
|
|
116
|
+
"fires or says 'no data' while asleep, the open alert is not notified again, and it "
|
|
117
|
+
"resolves about 115 s in once the CPU has cooled.",
|
|
118
|
+
{
|
|
119
|
+
**GOOD_CHARGER,
|
|
120
|
+
**_curves(CPU_TEMP, ((0, 40), (40, 95), (95, 95), (110, 80))),
|
|
121
|
+
},
|
|
122
|
+
events=((55.0, "suspend"), (75.0, "resume")),
|
|
123
|
+
),
|
|
124
|
+
)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class Simulation:
|
|
129
|
+
"""A :class:`~sensitivebox.daemon.SignalSource` that plays a scenario over a real collector."""
|
|
130
|
+
|
|
131
|
+
def __init__(self, base: Collector, scenario: Scenario, clock: Clock) -> None:
|
|
132
|
+
self._base = base
|
|
133
|
+
self._scenario = scenario
|
|
134
|
+
self._clock = clock
|
|
135
|
+
self._start = clock()
|
|
136
|
+
self._pulsed: set[Pulse] = set()
|
|
137
|
+
self._events_done = 0
|
|
138
|
+
self.limits: dict[str, Limits] = base.limits
|
|
139
|
+
|
|
140
|
+
@property
|
|
141
|
+
def scenario(self) -> Scenario:
|
|
142
|
+
return self._scenario
|
|
143
|
+
|
|
144
|
+
def elapsed(self) -> float:
|
|
145
|
+
return self._clock() - self._start
|
|
146
|
+
|
|
147
|
+
def collect(self) -> Snapshot:
|
|
148
|
+
snapshot = self._base.collect()
|
|
149
|
+
t = self.elapsed()
|
|
150
|
+
signals: dict[str, Value] = dict(snapshot.signals)
|
|
151
|
+
for name, value in snapshot.signals.items():
|
|
152
|
+
if isinstance(value, Missing):
|
|
153
|
+
continue
|
|
154
|
+
for glob, curve in self._scenario.curves.items():
|
|
155
|
+
if fnmatchcase(name, glob):
|
|
156
|
+
signals[name] = value_at(curve, t)
|
|
157
|
+
for pulse in self._scenario.pulses:
|
|
158
|
+
if t >= pulse.at and pulse not in self._pulsed:
|
|
159
|
+
self._pulsed.add(pulse)
|
|
160
|
+
for name, value in snapshot.signals.items():
|
|
161
|
+
if fnmatchcase(name, pulse.glob) and not isinstance(value, Missing):
|
|
162
|
+
signals[name] = pulse.value
|
|
163
|
+
return Snapshot(snapshot.at, signals, snapshot.metrics, snapshot.apps, snapshot.units)
|
|
164
|
+
|
|
165
|
+
def reset_baselines(self) -> None:
|
|
166
|
+
self._base.reset_baselines()
|
|
167
|
+
|
|
168
|
+
def due_events(self) -> list[EventKind]:
|
|
169
|
+
"""Scripted suspend/resume events whose time has come, each returned once."""
|
|
170
|
+
t = self.elapsed()
|
|
171
|
+
due: list[EventKind] = []
|
|
172
|
+
while self._events_done < len(self._scenario.events):
|
|
173
|
+
at, kind = self._scenario.events[self._events_done]
|
|
174
|
+
if t < at:
|
|
175
|
+
break
|
|
176
|
+
due.append(kind)
|
|
177
|
+
self._events_done += 1
|
|
178
|
+
return due
|
|
179
|
+
|
|
180
|
+
def loop_hook(
|
|
181
|
+
self, on_suspend: Callable[[], None], on_resume: Callable[[], None]
|
|
182
|
+
) -> Callable[[], None]:
|
|
183
|
+
"""For ``Daemon(on_loop=...)``: fires the scenario's suspend/resume like logind would."""
|
|
184
|
+
|
|
185
|
+
def hook() -> None:
|
|
186
|
+
for kind in self.due_events():
|
|
187
|
+
(on_suspend if kind == "suspend" else on_resume)()
|
|
188
|
+
|
|
189
|
+
return hook
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def scenario_named(name: str) -> Scenario:
|
|
193
|
+
try:
|
|
194
|
+
return SCENARIOS[name]
|
|
195
|
+
except KeyError:
|
|
196
|
+
raise SimulationError(
|
|
197
|
+
f"unknown scenario {name!r}; choose one of: {', '.join(SCENARIOS)}"
|
|
198
|
+
) from None
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def resolve_fixture(name: str) -> MachineRoot:
|
|
202
|
+
"""Installed demo data, or an explicitly supplied unified machine root."""
|
|
203
|
+
try:
|
|
204
|
+
if name == "proart-p16":
|
|
205
|
+
root = demo_root()
|
|
206
|
+
elif Path(name).is_dir():
|
|
207
|
+
root = MachineRoot.load(Path(name))
|
|
208
|
+
else:
|
|
209
|
+
raise SimulationError(f"no fixture {name!r}; available: proart-p16")
|
|
210
|
+
except FixtureError as exc:
|
|
211
|
+
raise SimulationError(str(exc)) from exc
|
|
212
|
+
return root
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def fixture_opener(path: Path) -> str:
|
|
216
|
+
"""Read a fixture file the way the kernel would: a file holding ``<ENODATA>`` fails."""
|
|
217
|
+
text = path.read_text(encoding="utf-8")
|
|
218
|
+
if text.strip() == ENODATA_MARKER:
|
|
219
|
+
raise OSError(errno.ENODATA, os.strerror(errno.ENODATA), str(path))
|
|
220
|
+
return text
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""System sources beyond hwmon: memory, pressure, CPU, network, Wi-Fi and Bluetooth. Read-only.
|
|
2
|
+
|
|
3
|
+
File readers take ``proc_root``/``sysfs_root`` so tests run against fixtures. A source the box
|
|
4
|
+
doesn't have returns ``None`` or an empty collection; it never raises.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from sensitivebox.sources.apps import (
|
|
8
|
+
AppMemory,
|
|
9
|
+
app_name,
|
|
10
|
+
app_slice_dir,
|
|
11
|
+
read_app_memory,
|
|
12
|
+
should_sample_apps,
|
|
13
|
+
)
|
|
14
|
+
from sensitivebox.sources.bluez import BluetoothStatus, BtAdapter, BtDevice, read_bluetooth
|
|
15
|
+
from sensitivebox.sources.bluez_watch import BluezWatcher
|
|
16
|
+
from sensitivebox.sources.cpu import (
|
|
17
|
+
CoreFreq,
|
|
18
|
+
CpuTimes,
|
|
19
|
+
CpuUtil,
|
|
20
|
+
read_cpu_freqs,
|
|
21
|
+
read_cpu_times,
|
|
22
|
+
utilisation,
|
|
23
|
+
)
|
|
24
|
+
from sensitivebox.sources.memory import MemInfo, VmStat, Zram, read_meminfo, read_vmstat, read_zram
|
|
25
|
+
from sensitivebox.sources.net import (
|
|
26
|
+
DEFAULT_SKIP,
|
|
27
|
+
DayTotal,
|
|
28
|
+
NetCounters,
|
|
29
|
+
NetMeter,
|
|
30
|
+
NetRate,
|
|
31
|
+
read_net_counters,
|
|
32
|
+
)
|
|
33
|
+
from sensitivebox.sources.power_supply import PowerSupply, read_power_supplies
|
|
34
|
+
from sensitivebox.sources.psi import Pressure, PsiLine, read_all_pressure, read_pressure
|
|
35
|
+
from sensitivebox.sources.report import SourcesReport, gather, system_bus_snapshot, with_dbus
|
|
36
|
+
from sensitivebox.sources.wifi import WifiSignal, WifiStatus, read_proc_wireless
|
|
37
|
+
from sensitivebox.sources.wifi_nm import NmWifiWatcher, read_nm_wifi_once
|
|
38
|
+
|
|
39
|
+
__all__ = [
|
|
40
|
+
"DEFAULT_SKIP",
|
|
41
|
+
"AppMemory",
|
|
42
|
+
"BluetoothStatus",
|
|
43
|
+
"BluezWatcher",
|
|
44
|
+
"BtAdapter",
|
|
45
|
+
"BtDevice",
|
|
46
|
+
"CoreFreq",
|
|
47
|
+
"CpuTimes",
|
|
48
|
+
"CpuUtil",
|
|
49
|
+
"DayTotal",
|
|
50
|
+
"MemInfo",
|
|
51
|
+
"NetCounters",
|
|
52
|
+
"NetMeter",
|
|
53
|
+
"NetRate",
|
|
54
|
+
"NmWifiWatcher",
|
|
55
|
+
"PowerSupply",
|
|
56
|
+
"Pressure",
|
|
57
|
+
"PsiLine",
|
|
58
|
+
"SourcesReport",
|
|
59
|
+
"VmStat",
|
|
60
|
+
"WifiSignal",
|
|
61
|
+
"WifiStatus",
|
|
62
|
+
"Zram",
|
|
63
|
+
"app_name",
|
|
64
|
+
"app_slice_dir",
|
|
65
|
+
"gather",
|
|
66
|
+
"read_all_pressure",
|
|
67
|
+
"read_app_memory",
|
|
68
|
+
"read_bluetooth",
|
|
69
|
+
"read_cpu_freqs",
|
|
70
|
+
"read_cpu_times",
|
|
71
|
+
"read_meminfo",
|
|
72
|
+
"read_net_counters",
|
|
73
|
+
"read_nm_wifi_once",
|
|
74
|
+
"read_power_supplies",
|
|
75
|
+
"read_pressure",
|
|
76
|
+
"read_proc_wireless",
|
|
77
|
+
"read_vmstat",
|
|
78
|
+
"read_zram",
|
|
79
|
+
"should_sample_apps",
|
|
80
|
+
"system_bus_snapshot",
|
|
81
|
+
"utilisation",
|
|
82
|
+
"with_dbus",
|
|
83
|
+
]
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""Memory per app, from the user's cgroup v2 ``app.slice``.
|
|
2
|
+
|
|
3
|
+
GNOME (and any desktop using systemd's XDG integration) launches each app in its own scope
|
|
4
|
+
or service under ``user@UID.service/app.slice``, so one ``memory.current`` read per app gives
|
|
5
|
+
its memory, child processes included. That still means dozens of reads, so it happens only
|
|
6
|
+
when memory is tight (see ``should_sample_apps``), never as a per-process scan.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from sensitivebox.hwmon.reader import Opener, default_opener, read_attr, read_int
|
|
15
|
+
from sensitivebox.sources.memory import MemInfo
|
|
16
|
+
from sensitivebox.sources.psi import Pressure
|
|
17
|
+
|
|
18
|
+
USED_THRESHOLD = 0.80 # sample when more than this share of memory is in use
|
|
19
|
+
PSI_HIGH = 10.0 # ... or memory "some" avg10 is at least this (%), or it is rising
|
|
20
|
+
|
|
21
|
+
_USER_SLICE_RE = re.compile(r"/user-(\d+)\.slice(?:/|$)")
|
|
22
|
+
_ESCAPE_RE = re.compile(r"\\x([0-9a-fA-F]{2})")
|
|
23
|
+
_SPAWN_RE = re.compile(r"^(?P<terminal>[^-]+)-spawn-[0-9a-fA-F-]+$")
|
|
24
|
+
# snapd tracks each app instance as snap.<snap>.<app>-<uuid>.scope (services drop the uuid).
|
|
25
|
+
_UUID = r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"
|
|
26
|
+
_SNAP_RE = re.compile(rf"^snap\.(?P<snap>[^.]+)\.(?P<app>.+?)(?:-{_UUID})?$")
|
|
27
|
+
_UNIT_SUFFIXES = (".scope", ".service", ".slice")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True, slots=True)
|
|
31
|
+
class AppMemory:
|
|
32
|
+
name: str
|
|
33
|
+
bytes: int
|
|
34
|
+
units: int = 1 # cgroups summed into this entry (same app name)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def app_slice_dir(
|
|
38
|
+
proc_root: Path,
|
|
39
|
+
sysfs_root: Path,
|
|
40
|
+
opener: Opener = default_opener,
|
|
41
|
+
*,
|
|
42
|
+
fallback_uid: int | None = None,
|
|
43
|
+
) -> Path | None:
|
|
44
|
+
"""The calling user's ``app.slice`` directory, or ``None`` without cgroup v2 / systemd.
|
|
45
|
+
|
|
46
|
+
The uid comes from ``<proc_root>/self/cgroup`` (so fixtures carry their own), falling back
|
|
47
|
+
to ``fallback_uid`` and then the real uid.
|
|
48
|
+
"""
|
|
49
|
+
uid: int | None = None
|
|
50
|
+
text = read_attr(proc_root / "self" / "cgroup", opener) or ""
|
|
51
|
+
for line in text.splitlines():
|
|
52
|
+
if line.startswith("0::") and (m := _USER_SLICE_RE.search(line[3:])):
|
|
53
|
+
uid = int(m[1])
|
|
54
|
+
break
|
|
55
|
+
if uid is None:
|
|
56
|
+
uid = fallback_uid if fallback_uid is not None else os.getuid()
|
|
57
|
+
path = (
|
|
58
|
+
sysfs_root
|
|
59
|
+
/ "fs"
|
|
60
|
+
/ "cgroup"
|
|
61
|
+
/ "user.slice"
|
|
62
|
+
/ f"user-{uid}.slice"
|
|
63
|
+
/ f"user@{uid}.service"
|
|
64
|
+
/ "app.slice"
|
|
65
|
+
)
|
|
66
|
+
return path if path.is_dir() else None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _unescape(text: str) -> str:
|
|
70
|
+
return _ESCAPE_RE.sub(lambda m: chr(int(m[1], 16)), text)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def app_name(unit: str) -> str:
|
|
74
|
+
"""A readable app name from a systemd unit name.
|
|
75
|
+
|
|
76
|
+
Follows the XDG naming scheme ``app[-<launcher>]-<app id>[-<random>].scope`` and
|
|
77
|
+
``app[-<launcher>]-<app id>[@<random>].service``, and snapd's
|
|
78
|
+
``snap.<snap>.<app>[-<uuid>].scope``. A literal ``-`` inside a part is
|
|
79
|
+
escaped as ``\\x2d``, so splitting on raw ``-`` *before* unescaping is unambiguous.
|
|
80
|
+
"""
|
|
81
|
+
stem, kind = unit, ""
|
|
82
|
+
for suffix in _UNIT_SUFFIXES:
|
|
83
|
+
if unit.endswith(suffix):
|
|
84
|
+
stem, kind = unit[: -len(suffix)], suffix
|
|
85
|
+
break
|
|
86
|
+
if kind == ".service":
|
|
87
|
+
stem = stem.split("@", 1)[0]
|
|
88
|
+
parts = stem.split("-")
|
|
89
|
+
if parts[0] == "app" and len(parts) >= 2:
|
|
90
|
+
rest = parts[1:]
|
|
91
|
+
if kind == ".scope" and len(rest) >= 2:
|
|
92
|
+
rest = rest[:-1] # the random/PID suffix
|
|
93
|
+
if len(rest) >= 2:
|
|
94
|
+
rest = rest[1:] # the launcher, e.g. "gnome" or "flatpak"
|
|
95
|
+
return _unescape("-".join(rest))
|
|
96
|
+
if m := _SPAWN_RE.match(stem):
|
|
97
|
+
return f"terminal ({_unescape(m['terminal'])})"
|
|
98
|
+
if m := _SNAP_RE.match(stem): # one name for every instance of a snap app (ADV-019)
|
|
99
|
+
snap, app = _unescape(m["snap"]), _unescape(m["app"])
|
|
100
|
+
return snap if app == snap else f"{snap} ({app})"
|
|
101
|
+
return _unescape(stem)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def read_app_memory(
|
|
105
|
+
slice_dir: Path, *, top: int = 5, opener: Opener = default_opener
|
|
106
|
+
) -> tuple[AppMemory, ...]:
|
|
107
|
+
"""The ``top`` apps by ``memory.current``, largest first. Same-named units are summed."""
|
|
108
|
+
try:
|
|
109
|
+
children = sorted(p for p in slice_dir.iterdir() if p.is_dir())
|
|
110
|
+
except OSError:
|
|
111
|
+
return ()
|
|
112
|
+
totals: dict[str, AppMemory] = {}
|
|
113
|
+
for child in children:
|
|
114
|
+
current = read_int(child / "memory.current", opener)
|
|
115
|
+
if current is None:
|
|
116
|
+
continue
|
|
117
|
+
name = app_name(child.name)
|
|
118
|
+
prev = totals.get(name)
|
|
119
|
+
totals[name] = (
|
|
120
|
+
AppMemory(name, current)
|
|
121
|
+
if prev is None
|
|
122
|
+
else AppMemory(name, prev.bytes + current, prev.units + 1)
|
|
123
|
+
)
|
|
124
|
+
ranked = sorted(totals.values(), key=lambda a: (-a.bytes, a.name))
|
|
125
|
+
return tuple(ranked[:top])
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def should_sample_apps(mem: MemInfo | None, memory_pressure: Pressure | None) -> bool:
|
|
129
|
+
"""Whether memory is tight enough to be worth listing the top apps."""
|
|
130
|
+
if mem is not None and mem.used_fraction > USED_THRESHOLD:
|
|
131
|
+
return True
|
|
132
|
+
if memory_pressure is None:
|
|
133
|
+
return False
|
|
134
|
+
some = memory_pressure.some
|
|
135
|
+
return some.avg10 >= PSI_HIGH or some.rising
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Bluetooth status from BlueZ over the system D-Bus. Read-only in v0.1.
|
|
2
|
+
|
|
3
|
+
One ``ObjectManager.GetManagedObjects`` call returns every adapter and device. We report each
|
|
4
|
+
adapter's ``Powered`` state and the devices that are connected, with their ``Battery1`` level.
|
|
5
|
+
The toggle (a write) is v0.3 and lives elsewhere.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from sensitivebox.sources.dbus import NO_BUS, Bus, DBusCallError, call, reason_for
|
|
13
|
+
|
|
14
|
+
BLUEZ = "org.bluez"
|
|
15
|
+
OBJECT_MANAGER = "org.freedesktop.DBus.ObjectManager"
|
|
16
|
+
ADAPTER = "org.bluez.Adapter1"
|
|
17
|
+
DEVICE = "org.bluez.Device1"
|
|
18
|
+
BATTERY = "org.bluez.Battery1"
|
|
19
|
+
NO_ADAPTER = "no Bluetooth adapter"
|
|
20
|
+
MANAGED_OBJECTS = "a{oa{sa{sv}}}" # GetManagedObjects' reply signature
|
|
21
|
+
|
|
22
|
+
type ManagedObjects = Mapping[str, Mapping[str, Mapping[str, Any]]]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True, slots=True)
|
|
26
|
+
class BtAdapter:
|
|
27
|
+
name: str # e.g. "hci0"
|
|
28
|
+
alias: str
|
|
29
|
+
powered: bool
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True, slots=True)
|
|
33
|
+
class BtDevice:
|
|
34
|
+
alias: str
|
|
35
|
+
icon: str | None # freedesktop icon name, e.g. "audio-headset"
|
|
36
|
+
battery: int | None # percent
|
|
37
|
+
adapter: str # adapter name, e.g. "hci0"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True, slots=True)
|
|
41
|
+
class BluetoothStatus:
|
|
42
|
+
adapters: tuple[BtAdapter, ...] = ()
|
|
43
|
+
devices: tuple[BtDevice, ...] = () # connected devices only
|
|
44
|
+
reason: str | None = None # set when unavailable
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def available(self) -> bool:
|
|
48
|
+
return self.reason is None
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def powered(self) -> bool:
|
|
52
|
+
return any(a.powered for a in self.adapters)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _basename(path: str) -> str:
|
|
56
|
+
return path.rstrip("/").rsplit("/", 1)[-1]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def parse_managed_objects(objects: ManagedObjects) -> BluetoothStatus:
|
|
60
|
+
adapters: list[BtAdapter] = []
|
|
61
|
+
devices: list[BtDevice] = []
|
|
62
|
+
for path in sorted(objects):
|
|
63
|
+
interfaces = objects[path]
|
|
64
|
+
if (adapter := interfaces.get(ADAPTER)) is not None:
|
|
65
|
+
name = _basename(path)
|
|
66
|
+
adapters.append(
|
|
67
|
+
BtAdapter(name, str(adapter.get("Alias", name)), bool(adapter.get("Powered")))
|
|
68
|
+
)
|
|
69
|
+
device = interfaces.get(DEVICE)
|
|
70
|
+
if device is None or not device.get("Connected"):
|
|
71
|
+
continue
|
|
72
|
+
battery = interfaces.get(BATTERY, {}).get("Percentage")
|
|
73
|
+
icon = device.get("Icon")
|
|
74
|
+
devices.append(
|
|
75
|
+
BtDevice(
|
|
76
|
+
alias=str(device.get("Alias", _basename(path))),
|
|
77
|
+
icon=str(icon) if icon is not None else None,
|
|
78
|
+
battery=int(battery) if battery is not None else None,
|
|
79
|
+
adapter=_basename(str(device.get("Adapter", path.rsplit("/", 1)[0]))),
|
|
80
|
+
)
|
|
81
|
+
)
|
|
82
|
+
if not adapters:
|
|
83
|
+
return BluetoothStatus(reason=NO_ADAPTER)
|
|
84
|
+
return BluetoothStatus(tuple(adapters), tuple(devices))
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
async def read_bluetooth(bus: Bus | None) -> BluetoothStatus:
|
|
88
|
+
if bus is None:
|
|
89
|
+
return BluetoothStatus(reason=NO_BUS)
|
|
90
|
+
try:
|
|
91
|
+
(objects,) = await call(
|
|
92
|
+
bus, BLUEZ, "/", OBJECT_MANAGER, "GetManagedObjects", expected=MANAGED_OBJECTS
|
|
93
|
+
)
|
|
94
|
+
except DBusCallError as exc:
|
|
95
|
+
return BluetoothStatus(reason=reason_for(exc, "BlueZ"))
|
|
96
|
+
return parse_managed_objects(objects)
|