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.
Files changed (95) hide show
  1. sensitivebox/__init__.py +10 -0
  2. sensitivebox/alerts/__init__.py +94 -0
  3. sensitivebox/alerts/config.py +85 -0
  4. sensitivebox/alerts/defaults.toml +126 -0
  5. sensitivebox/alerts/engine.py +624 -0
  6. sensitivebox/alerts/events.py +87 -0
  7. sensitivebox/alerts/globs.py +84 -0
  8. sensitivebox/alerts/model.py +215 -0
  9. sensitivebox/alerts/mute.py +55 -0
  10. sensitivebox/alerts/replay.py +99 -0
  11. sensitivebox/alerts/routing.py +247 -0
  12. sensitivebox/api/__init__.py +6 -0
  13. sensitivebox/api/app.py +225 -0
  14. sensitivebox/api/data.py +109 -0
  15. sensitivebox/api/host.py +27 -0
  16. sensitivebox/api/model.py +90 -0
  17. sensitivebox/api/security.py +89 -0
  18. sensitivebox/api/server.py +108 -0
  19. sensitivebox/api/state.py +220 -0
  20. sensitivebox/api/static/assets/archivo-latin-wdth-normal-DY7AcnAa.woff2 +0 -0
  21. sensitivebox/api/static/assets/ibm-plex-mono-medium-BpyVxOr_.woff2 +0 -0
  22. sensitivebox/api/static/assets/index-BH9EydfS.js +10 -0
  23. sensitivebox/api/static/assets/index-RMruxW54.css +1 -0
  24. sensitivebox/api/static/assets/mark-on-dark-CpSxozdM.png +0 -0
  25. sensitivebox/api/static/assets/mark-on-light-DgUAeHTp.png +0 -0
  26. sensitivebox/api/static/assets/mark-raised-Bg5z6PGs.png +0 -0
  27. sensitivebox/api/static/index.html +14 -0
  28. sensitivebox/browser.py +106 -0
  29. sensitivebox/cli.py +467 -0
  30. sensitivebox/collector.py +319 -0
  31. sensitivebox/completion.py +117 -0
  32. sensitivebox/daemon.py +181 -0
  33. sensitivebox/data/icons/128.png +0 -0
  34. sensitivebox/data/icons/256.png +0 -0
  35. sensitivebox/data/icons/512.png +0 -0
  36. sensitivebox/data/proart-p16.tar.gz +0 -0
  37. sensitivebox/data/sensitivebox.desktop.in +8 -0
  38. sensitivebox/data/sensitivebox.service.in +11 -0
  39. sensitivebox/doctor.py +322 -0
  40. sensitivebox/fixtures.py +177 -0
  41. sensitivebox/history.py +298 -0
  42. sensitivebox/hwmon/__init__.py +20 -0
  43. sensitivebox/hwmon/classify.py +74 -0
  44. sensitivebox/hwmon/discovery.py +139 -0
  45. sensitivebox/hwmon/ids.py +35 -0
  46. sensitivebox/hwmon/model.py +78 -0
  47. sensitivebox/hwmon/normalise.py +42 -0
  48. sensitivebox/hwmon/reader.py +65 -0
  49. sensitivebox/inspect.py +175 -0
  50. sensitivebox/live.py +56 -0
  51. sensitivebox/notify/__init__.py +7 -0
  52. sensitivebox/notify/base.py +60 -0
  53. sensitivebox/notify/desktop.py +84 -0
  54. sensitivebox/notify/log.py +30 -0
  55. sensitivebox/operations.py +44 -0
  56. sensitivebox/output.py +76 -0
  57. sensitivebox/process.py +25 -0
  58. sensitivebox/py.typed +0 -0
  59. sensitivebox/redact.py +85 -0
  60. sensitivebox/report.py +357 -0
  61. sensitivebox/runtime.py +313 -0
  62. sensitivebox/sample.py +84 -0
  63. sensitivebox/service.py +112 -0
  64. sensitivebox/simulate.py +220 -0
  65. sensitivebox/sources/__init__.py +83 -0
  66. sensitivebox/sources/apps.py +135 -0
  67. sensitivebox/sources/bluez.py +96 -0
  68. sensitivebox/sources/bluez_watch.py +214 -0
  69. sensitivebox/sources/changes.py +121 -0
  70. sensitivebox/sources/cpu.py +152 -0
  71. sensitivebox/sources/dbus.py +174 -0
  72. sensitivebox/sources/logind.py +88 -0
  73. sensitivebox/sources/memory.py +127 -0
  74. sensitivebox/sources/net.py +128 -0
  75. sensitivebox/sources/power_profiles.py +116 -0
  76. sensitivebox/sources/power_supply.py +70 -0
  77. sensitivebox/sources/psi.py +78 -0
  78. sensitivebox/sources/report.py +85 -0
  79. sensitivebox/sources/wifi.py +90 -0
  80. sensitivebox/sources/wifi_nm.py +269 -0
  81. sensitivebox/status.py +205 -0
  82. sensitivebox/store/__init__.py +5 -0
  83. sensitivebox/store/changes.py +58 -0
  84. sensitivebox/store/db.py +423 -0
  85. sensitivebox/store/events.py +337 -0
  86. sensitivebox/store/mutes.py +58 -0
  87. sensitivebox/store/quality.py +51 -0
  88. sensitivebox/store/read.py +40 -0
  89. sensitivebox/store/schema.py +194 -0
  90. sensitivebox/store/status.py +105 -0
  91. sensitivebox-0.1.0.dist-info/METADATA +424 -0
  92. sensitivebox-0.1.0.dist-info/RECORD +95 -0
  93. sensitivebox-0.1.0.dist-info/WHEEL +4 -0
  94. sensitivebox-0.1.0.dist-info/entry_points.txt +4 -0
  95. sensitivebox-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,88 @@
1
+ """Sleep and shutdown notices from systemd-logind.
2
+
3
+ ``PrepareForSleep(true)`` is sent just before suspend or hibernate and ``PrepareForSleep(false)``
4
+ just after resume; ``PrepareForShutdown(true)`` precedes shutdown or reboot. While either is in
5
+ progress the daemon pauses evaluation and the missing-data timers, so closing the lid or shutting
6
+ down never fires an alert, and never a "no data" one. On resume the engine restarts every rule in
7
+ Warming (docs/BIBLE.md, "Sleep and shutdown").
8
+
9
+ Sleep and shutdown are tracked separately, so the pause lasts until neither is in progress.
10
+ """
11
+
12
+ from collections.abc import Callable
13
+
14
+ from dbus_fast import Message, MessageType
15
+
16
+ from sensitivebox.sources.dbus import Bus, DBusCallError, add_match, remove_matches, signal_rule
17
+
18
+ LOGIND = "org.freedesktop.login1"
19
+ LOGIND_PATH = "/org/freedesktop/login1"
20
+ MANAGER = "org.freedesktop.login1.Manager"
21
+ SIGNALS = ("PrepareForSleep", "PrepareForShutdown")
22
+ RULES = tuple(
23
+ signal_rule(sender=LOGIND, interface=MANAGER, member=member, path=LOGIND_PATH)
24
+ for member in SIGNALS
25
+ )
26
+
27
+
28
+ class LogindWatcher:
29
+ """Calls ``on_suspend`` when the first of sleep/shutdown begins and ``on_resume`` when the
30
+ last one ends. Both run inside the D-Bus message loop, so they must be quick."""
31
+
32
+ def __init__(self, on_suspend: Callable[[], None], on_resume: Callable[[], None]) -> None:
33
+ self._on_suspend = on_suspend
34
+ self._on_resume = on_resume
35
+ self._bus: Bus | None = None
36
+ self._rules: list[str] = []
37
+ self._preparing: set[str] = set()
38
+
39
+ @property
40
+ def preparing(self) -> bool:
41
+ """True between a ``Prepare…(true)`` and the matching ``(false)``."""
42
+ return bool(self._preparing)
43
+
44
+ async def start(self, bus: Bus | None) -> bool:
45
+ """Subscribe. ``False`` when there is no bus or logind refuses the subscription. Starting
46
+ again on the same bus changes nothing; on another bus, the old subscriptions are dropped
47
+ first (ADV-017)."""
48
+ if bus is not None and bus is self._bus:
49
+ return True
50
+ await self.close()
51
+ if bus is None:
52
+ return False
53
+ self._bus = bus
54
+ bus.add_message_handler(self._on_message)
55
+ try:
56
+ for rule in RULES:
57
+ await add_match(bus, rule)
58
+ self._rules.append(rule)
59
+ except DBusCallError:
60
+ await self.close()
61
+ return False
62
+ return True
63
+
64
+ async def close(self) -> None:
65
+ bus, self._bus = self._bus, None
66
+ if bus is None:
67
+ return
68
+ bus.remove_message_handler(self._on_message)
69
+ rules, self._rules = self._rules, []
70
+ await remove_matches(bus, rules)
71
+
72
+ def _on_message(self, msg: Message) -> None:
73
+ if (
74
+ msg.message_type != MessageType.SIGNAL
75
+ or msg.interface != MANAGER
76
+ or msg.member not in SIGNALS
77
+ or len(msg.body) != 1
78
+ ):
79
+ return
80
+ was_preparing = self.preparing
81
+ if msg.body[0]:
82
+ self._preparing.add(str(msg.member))
83
+ else:
84
+ self._preparing.discard(str(msg.member))
85
+ if self.preparing and not was_preparing:
86
+ self._on_suspend()
87
+ elif was_preparing and not self.preparing:
88
+ self._on_resume()
@@ -0,0 +1,127 @@
1
+ """Memory: ``/proc/meminfo``, zram ``mm_stat`` and the ``/proc/vmstat`` counters we care about.
2
+
3
+ Used memory is always ``MemTotal - MemAvailable``. "Free" memory leaves out reclaimable page
4
+ cache, so it makes every Linux box look full.
5
+ """
6
+
7
+ import re
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+
11
+ from sensitivebox.hwmon.reader import Opener, default_opener, read_attr
12
+
13
+ _KB = 1024
14
+ _ZRAM_RE = re.compile(r"^zram(\d+)$")
15
+
16
+
17
+ @dataclass(frozen=True, slots=True)
18
+ class MemInfo:
19
+ """``/proc/meminfo`` in bytes."""
20
+
21
+ total: int
22
+ available: int
23
+ cached: int = 0
24
+ dirty: int = 0
25
+ swap_total: int = 0
26
+ swap_free: int = 0
27
+
28
+ @property
29
+ def used(self) -> int:
30
+ return max(self.total - self.available, 0)
31
+
32
+ @property
33
+ def used_fraction(self) -> float:
34
+ return self.used / self.total if self.total else 0.0
35
+
36
+ @property
37
+ def swap_used(self) -> int:
38
+ return max(self.swap_total - self.swap_free, 0)
39
+
40
+
41
+ def parse_meminfo(text: str) -> MemInfo | None:
42
+ """``None`` without MemTotal or MemAvailable (kernels before 3.14 lack the latter)."""
43
+ fields: dict[str, int] = {}
44
+ for line in text.splitlines():
45
+ key, sep, rest = line.partition(":")
46
+ parts = rest.split()
47
+ if not sep or not parts or not parts[0].isdigit():
48
+ continue
49
+ scale = _KB if parts[1:2] == ["kB"] else 1
50
+ fields[key.strip()] = int(parts[0]) * scale
51
+ if "MemTotal" not in fields or "MemAvailable" not in fields:
52
+ return None
53
+ return MemInfo(
54
+ total=fields["MemTotal"],
55
+ available=fields["MemAvailable"],
56
+ cached=fields.get("Cached", 0),
57
+ dirty=fields.get("Dirty", 0),
58
+ swap_total=fields.get("SwapTotal", 0),
59
+ swap_free=fields.get("SwapFree", 0),
60
+ )
61
+
62
+
63
+ def read_meminfo(proc_root: Path, opener: Opener = default_opener) -> MemInfo | None:
64
+ text = read_attr(proc_root / "meminfo", opener)
65
+ return parse_meminfo(text) if text else None
66
+
67
+
68
+ @dataclass(frozen=True, slots=True)
69
+ class Zram:
70
+ """One zram device, from the first three ``mm_stat`` fields (bytes)."""
71
+
72
+ name: str
73
+ orig_bytes: int # uncompressed data stored
74
+ compr_bytes: int # compressed size of that data
75
+ mem_used_bytes: int # RAM actually used, including allocator overhead
76
+
77
+ @property
78
+ def ratio(self) -> float | None:
79
+ """Compression ratio, e.g. 3.1; ``None`` while the device holds nothing."""
80
+ return self.orig_bytes / self.compr_bytes if self.compr_bytes else None
81
+
82
+ @property
83
+ def saved_bytes(self) -> int:
84
+ return max(self.orig_bytes - self.mem_used_bytes, 0)
85
+
86
+
87
+ def read_zram(sysfs_root: Path, opener: Opener = default_opener) -> tuple[Zram, ...]:
88
+ """Every ``block/zramN`` with a readable ``mm_stat``, in device order. Empty without zram."""
89
+ block = sysfs_root / "block"
90
+ try:
91
+ entries = list(block.iterdir())
92
+ except OSError:
93
+ return ()
94
+ devices: list[tuple[int, Zram]] = []
95
+ for entry in entries:
96
+ m = _ZRAM_RE.match(entry.name)
97
+ if not m:
98
+ continue
99
+ text = read_attr(entry / "mm_stat", opener)
100
+ fields = text.split() if text else []
101
+ if len(fields) < 3 or not all(f.isdigit() for f in fields[:3]):
102
+ continue
103
+ orig, compr, used = (int(f) for f in fields[:3])
104
+ devices.append((int(m[1]), Zram(entry.name, orig, compr, used)))
105
+ return tuple(zram for _, zram in sorted(devices))
106
+
107
+
108
+ @dataclass(frozen=True, slots=True)
109
+ class VmStat:
110
+ """Cumulative since boot. ``None`` for a counter this kernel doesn't have."""
111
+
112
+ oom_kill: int | None
113
+ pswpin: int | None # pages swapped in
114
+ pswpout: int | None # pages swapped out
115
+
116
+
117
+ def read_vmstat(proc_root: Path, opener: Opener = default_opener) -> VmStat | None:
118
+ text = read_attr(proc_root / "vmstat", opener)
119
+ if text is None:
120
+ return None
121
+ wanted = {"oom_kill", "pswpin", "pswpout"}
122
+ values: dict[str, int] = {}
123
+ for line in text.splitlines():
124
+ parts = line.split()
125
+ if len(parts) == 2 and parts[0] in wanted and parts[1].isdigit():
126
+ values[parts[0]] = int(parts[1])
127
+ return VmStat(values.get("oom_kill"), values.get("pswpin"), values.get("pswpout"))
@@ -0,0 +1,128 @@
1
+ """Network throughput from ``/sys/class/net/*/statistics`` byte counters.
2
+
3
+ Speed is Δbytes / Δt between polls. A counter that goes *down* (driver reload, interface
4
+ reset) starts a new baseline: no rate for that poll and nothing added to the totals, never a
5
+ negative value. Totals are kept per interface per day; persisting them is the store's job, which
6
+ hands them back through ``NetMeter.seed`` after a restart.
7
+ """
8
+
9
+ from collections.abc import Iterable, Mapping
10
+ from dataclasses import dataclass
11
+ from datetime import date
12
+ from fnmatch import fnmatchcase
13
+ from pathlib import Path
14
+
15
+ from sensitivebox.hwmon.reader import Opener, default_opener, read_attr, read_int
16
+
17
+ DEFAULT_SKIP: tuple[str, ...] = ("lo", "veth*", "docker*", "br-*")
18
+
19
+
20
+ @dataclass(frozen=True, slots=True)
21
+ class NetCounters:
22
+ iface: str
23
+ rx_bytes: int
24
+ tx_bytes: int
25
+ virtual: bool = False # lives under devices/virtual (bridges, tunnels, VPNs)
26
+ operstate: str | None = None # "up", "down", "unknown", …
27
+
28
+
29
+ def read_net_counters(
30
+ sysfs_root: Path,
31
+ skip: Iterable[str] = DEFAULT_SKIP,
32
+ opener: Opener = default_opener,
33
+ ) -> dict[str, NetCounters]:
34
+ """Counters for every interface not matching a ``skip`` glob, by name."""
35
+ class_dir = sysfs_root / "class" / "net"
36
+ patterns = tuple(skip)
37
+ try:
38
+ entries = sorted(class_dir.iterdir())
39
+ except OSError:
40
+ return {}
41
+ out: dict[str, NetCounters] = {}
42
+ for entry in entries:
43
+ name = entry.name
44
+ if any(fnmatchcase(name, p) for p in patterns):
45
+ continue
46
+ stats = entry / "statistics"
47
+ rx = read_int(stats / "rx_bytes", opener)
48
+ tx = read_int(stats / "tx_bytes", opener)
49
+ if rx is None or tx is None:
50
+ continue
51
+ out[name] = NetCounters(
52
+ iface=name,
53
+ rx_bytes=rx,
54
+ tx_bytes=tx,
55
+ virtual="/devices/virtual/" in entry.resolve().as_posix(),
56
+ operstate=read_attr(entry / "operstate", opener),
57
+ )
58
+ return out
59
+
60
+
61
+ @dataclass(frozen=True, slots=True)
62
+ class NetRate:
63
+ """Bytes per second since the last poll; ``None`` on a new baseline."""
64
+
65
+ iface: str
66
+ rx_bps: float | None
67
+ tx_bps: float | None
68
+
69
+
70
+ @dataclass(frozen=True, slots=True)
71
+ class DayTotal:
72
+ rx_bytes: int = 0
73
+ tx_bytes: int = 0
74
+
75
+ def __add__(self, other: "DayTotal") -> "DayTotal":
76
+ return DayTotal(self.rx_bytes + other.rx_bytes, self.tx_bytes + other.tx_bytes)
77
+
78
+
79
+ @dataclass(frozen=True, slots=True)
80
+ class _Last:
81
+ at: float
82
+ rx: int
83
+ tx: int
84
+
85
+
86
+ class NetMeter:
87
+ """Turns successive counter samples into rates and per-day totals. Owns no clock: the caller
88
+ passes a monotonic time (for rates) and the local date (for totals)."""
89
+
90
+ def __init__(self) -> None:
91
+ self._last: dict[str, _Last] = {}
92
+ self._totals: dict[tuple[str, date], DayTotal] = {}
93
+
94
+ def seed(self, totals: Mapping[tuple[str, date], DayTotal]) -> None:
95
+ """Restore totals saved by the store; later deltas are added on top."""
96
+ for key, total in totals.items():
97
+ self._totals[key] = self._totals.get(key, DayTotal()) + total
98
+
99
+ @property
100
+ def totals(self) -> dict[tuple[str, date], DayTotal]:
101
+ return dict(self._totals)
102
+
103
+ def day_totals(self, day: date) -> dict[str, DayTotal]:
104
+ return {iface: t for (iface, d), t in sorted(self._totals.items()) if d == day}
105
+
106
+ def update(
107
+ self, counters: Mapping[str, NetCounters], *, monotonic: float, day: date
108
+ ) -> dict[str, NetRate]:
109
+ # An interface that disappears loses its baseline, so it starts fresh if it returns.
110
+ for gone in self._last.keys() - counters.keys():
111
+ del self._last[gone]
112
+ rates: dict[str, NetRate] = {}
113
+ for iface, c in counters.items():
114
+ last = self._last.get(iface)
115
+ if last is not None and monotonic <= last.at:
116
+ # No time has passed: keep the baseline and report nothing new.
117
+ rates[iface] = NetRate(iface, None, None)
118
+ continue
119
+ self._last[iface] = _Last(monotonic, c.rx_bytes, c.tx_bytes)
120
+ if last is None or c.rx_bytes < last.rx or c.tx_bytes < last.tx:
121
+ rates[iface] = NetRate(iface, None, None) # first sample or counter reset
122
+ continue
123
+ d_rx, d_tx = c.rx_bytes - last.rx, c.tx_bytes - last.tx
124
+ dt = monotonic - last.at
125
+ key = (iface, day)
126
+ self._totals[key] = self._totals.get(key, DayTotal()) + DayTotal(d_rx, d_tx)
127
+ rates[iface] = NetRate(iface, d_rx / dt, d_tx / dt)
128
+ return rates
@@ -0,0 +1,116 @@
1
+ """Read and subscribe to ActiveProfile, supporting current and legacy services."""
2
+
3
+ import asyncio
4
+ from collections.abc import Callable
5
+ from typing import Any, cast
6
+
7
+ from dbus_fast import Message, MessageType
8
+
9
+ from sensitivebox.sources.dbus import (
10
+ DBUS,
11
+ PROPERTIES,
12
+ Bus,
13
+ DBusCallError,
14
+ add_match,
15
+ get_property,
16
+ remove_matches,
17
+ signal_rule,
18
+ unwrap,
19
+ )
20
+
21
+ SERVICES = (
22
+ ("org.freedesktop.UPower.PowerProfiles", "/org/freedesktop/UPower/PowerProfiles"),
23
+ ("net.hadess.PowerProfiles", "/net/hadess/PowerProfiles"),
24
+ )
25
+
26
+
27
+ class PowerProfileWatcher:
28
+ def __init__(self, on_change: Callable[[str], None]) -> None:
29
+ self.on_change = on_change
30
+ self.bus: Bus | None = None
31
+ self.rules: list[str] = []
32
+ self.tasks: set[asyncio.Task[None]] = set()
33
+
34
+ async def start(self, bus: Bus | None) -> bool:
35
+ await self.close()
36
+ if bus is None:
37
+ return False
38
+ self.bus = bus
39
+ bus.add_message_handler(self._message)
40
+ try:
41
+ for service, path in SERVICES:
42
+ for rule in (
43
+ signal_rule(
44
+ sender=service,
45
+ interface=PROPERTIES,
46
+ member="PropertiesChanged",
47
+ path=path,
48
+ arg0=service,
49
+ ),
50
+ signal_rule(
51
+ sender=DBUS, interface=DBUS, member="NameOwnerChanged", arg0=service
52
+ ),
53
+ ):
54
+ await add_match(bus, rule)
55
+ self.rules.append(rule)
56
+ await self._read()
57
+ except DBusCallError:
58
+ await self.close()
59
+ return False
60
+ return True
61
+
62
+ async def _read(self) -> None:
63
+ if self.bus is None:
64
+ return
65
+ for service, path in SERVICES:
66
+ try:
67
+ value: Any = await get_property(self.bus, service, path, service, "ActiveProfile")
68
+ except DBusCallError:
69
+ continue
70
+ if isinstance(value, str):
71
+ self.on_change(value)
72
+ return
73
+
74
+ def _message(self, msg: Message) -> None:
75
+ if msg.message_type != MessageType.SIGNAL:
76
+ return
77
+ if (
78
+ msg.interface == PROPERTIES
79
+ and msg.member == "PropertiesChanged"
80
+ and any(msg.path == p for _, p in SERVICES)
81
+ and len(msg.body) == 3
82
+ and msg.body[0] in {s for s, _ in SERVICES}
83
+ ):
84
+ props: Any = unwrap(msg.body[1])
85
+ value: Any = (
86
+ cast(dict[str, Any], props).get("ActiveProfile")
87
+ if isinstance(props, dict)
88
+ else None
89
+ )
90
+ if isinstance(value, str):
91
+ self.on_change(value)
92
+ elif "ActiveProfile" in msg.body[2]:
93
+ self._refresh()
94
+ elif (
95
+ msg.interface == DBUS
96
+ and msg.member == "NameOwnerChanged"
97
+ and len(msg.body) == 3
98
+ and msg.body[0] in {s for s, _ in SERVICES}
99
+ and msg.body[2]
100
+ ):
101
+ self._refresh()
102
+
103
+ def _refresh(self) -> None:
104
+ task = asyncio.create_task(self._read())
105
+ self.tasks.add(task)
106
+ task.add_done_callback(self.tasks.discard)
107
+
108
+ async def close(self) -> None:
109
+ for task in self.tasks:
110
+ task.cancel()
111
+ await asyncio.gather(*self.tasks, return_exceptions=True)
112
+ bus, self.bus = self.bus, None
113
+ if bus is not None:
114
+ bus.remove_message_handler(self._message)
115
+ rules, self.rules = self.rules, []
116
+ await remove_matches(bus, rules)
@@ -0,0 +1,70 @@
1
+ """Batteries, mains adapters and USB-C source ports from ``/sys/class/power_supply``.
2
+
3
+ Directory names are what the kernel calls the supply (``BAT1``, ``ACAD``,
4
+ ``ucsi-source-psy-USBC000:001``), and the daemon publishes them unchanged. Voltage and current
5
+ are in micro-units. A USB-C port with nothing plugged in reads 0 V / 0 A and ``online`` = 0;
6
+ that is "no source", not a 0 W charger, so ``power_w`` is ``None`` unless the port is online.
7
+ """
8
+
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+
12
+ from sensitivebox.hwmon.reader import Opener, default_opener, read_attr, read_raw
13
+
14
+ _MICRO = 1_000_000.0
15
+
16
+
17
+ @dataclass(frozen=True, slots=True)
18
+ class PowerSupply:
19
+ name: str
20
+ kind: str | None # the ``type`` file: "Battery", "Mains", "USB", …
21
+ capacity: float | None # percent, batteries only
22
+ status: str | None # "Charging", "Discharging", "Full", …
23
+ online: bool | None # mains and USB-C ports
24
+ voltage_v: float | None
25
+ current_a: float | None
26
+
27
+ @property
28
+ def power_w(self) -> float | None:
29
+ """Negotiated power, only for an online supply that reports both voltage and current."""
30
+ if not self.online or self.voltage_v is None or self.current_a is None:
31
+ return None
32
+ return self.voltage_v * self.current_a
33
+
34
+ @property
35
+ def is_usb_source(self) -> bool:
36
+ return self.name.startswith("ucsi-source-psy-")
37
+
38
+
39
+ def _number(path: Path, opener: Opener) -> int | None:
40
+ return read_raw(path, opener).value
41
+
42
+
43
+ def _scaled(path: Path, opener: Opener) -> float | None:
44
+ raw = _number(path, opener)
45
+ return None if raw is None else raw / _MICRO
46
+
47
+
48
+ def read_power_supply(directory: Path, opener: Opener = default_opener) -> PowerSupply:
49
+ online = _number(directory / "online", opener)
50
+ capacity = _number(directory / "capacity", opener)
51
+ return PowerSupply(
52
+ name=directory.name,
53
+ kind=read_attr(directory / "type", opener),
54
+ capacity=None if capacity is None else float(capacity),
55
+ status=read_attr(directory / "status", opener),
56
+ online=None if online is None else online != 0,
57
+ voltage_v=_scaled(directory / "voltage_now", opener),
58
+ current_a=_scaled(directory / "current_now", opener),
59
+ )
60
+
61
+
62
+ def read_power_supplies(
63
+ sysfs_root: Path, opener: Opener = default_opener
64
+ ) -> tuple[PowerSupply, ...]:
65
+ """Every supply under ``class/power_supply``, sorted by name. Empty when there are none."""
66
+ try:
67
+ entries = sorted((sysfs_root / "class" / "power_supply").iterdir())
68
+ except OSError:
69
+ return ()
70
+ return tuple(read_power_supply(entry, opener) for entry in entries)
@@ -0,0 +1,78 @@
1
+ """Pressure stall information from ``/proc/pressure/{memory,cpu,io}``.
2
+
3
+ PSI is the share of time tasks were stalled waiting on a resource. ``some``: at least one task
4
+ waited; ``full``: every non-idle task waited at once. The ``total`` counters (microseconds) are
5
+ what Insights stores per interval; the averages are for the live view and alerts.
6
+ """
7
+
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+
11
+ from sensitivebox.hwmon.reader import Opener, default_opener, read_attr
12
+
13
+ RESOURCES = ("memory", "cpu", "io")
14
+ RISING_MIN = 1.0 # %: below this, avg10 > avg60 is noise, not a trend
15
+
16
+
17
+ @dataclass(frozen=True, slots=True)
18
+ class PsiLine:
19
+ avg10: float # percent of the last 10 s
20
+ avg60: float
21
+ avg300: float
22
+ total_us: int # cumulative stall time since boot
23
+
24
+ @property
25
+ def rising(self) -> bool:
26
+ return self.avg10 > self.avg60 and self.avg10 >= RISING_MIN
27
+
28
+
29
+ @dataclass(frozen=True, slots=True)
30
+ class Pressure:
31
+ resource: str
32
+ some: PsiLine
33
+ full: PsiLine | None # absent on older kernels for cpu
34
+
35
+
36
+ def _parse_line(rest: str) -> PsiLine | None:
37
+ values: dict[str, str] = {}
38
+ for item in rest.split():
39
+ key, sep, value = item.partition("=")
40
+ if sep:
41
+ values[key] = value
42
+ try:
43
+ return PsiLine(
44
+ avg10=float(values["avg10"]),
45
+ avg60=float(values["avg60"]),
46
+ avg300=float(values["avg300"]),
47
+ total_us=int(values["total"]),
48
+ )
49
+ except (KeyError, ValueError):
50
+ return None
51
+
52
+
53
+ def parse_pressure(resource: str, text: str) -> Pressure | None:
54
+ lines: dict[str, PsiLine] = {}
55
+ for line in text.splitlines():
56
+ kind, _, rest = line.partition(" ")
57
+ if kind in ("some", "full") and (parsed := _parse_line(rest)):
58
+ lines[kind] = parsed
59
+ if "some" not in lines:
60
+ return None
61
+ return Pressure(resource, lines["some"], lines.get("full"))
62
+
63
+
64
+ def read_pressure(
65
+ proc_root: Path, resource: str, opener: Opener = default_opener
66
+ ) -> Pressure | None:
67
+ """``None`` when PSI is off (``psi=0``, or EOPNOTSUPP) or the file can't be parsed."""
68
+ text = read_attr(proc_root / "pressure" / resource, opener)
69
+ return parse_pressure(resource, text) if text else None
70
+
71
+
72
+ def read_all_pressure(proc_root: Path, opener: Opener = default_opener) -> dict[str, Pressure]:
73
+ """Every resource that has PSI on this box, in ``RESOURCES`` order."""
74
+ out: dict[str, Pressure] = {}
75
+ for resource in RESOURCES:
76
+ if (pressure := read_pressure(proc_root, resource, opener)) is not None:
77
+ out[resource] = pressure
78
+ return out
@@ -0,0 +1,85 @@
1
+ """One read of every system source, for ``sensitivebox doctor``.
2
+
3
+ The daemon will poll the same readers but keep state (``NetMeter``, the previous ``CpuTimes``,
4
+ an ``NmWifiWatcher``); doctor is a one-shot, so it reports since-boot figures.
5
+ """
6
+
7
+ import asyncio
8
+ import dataclasses
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+
12
+ from sensitivebox.hwmon.reader import Opener, default_opener
13
+ from sensitivebox.sources import apps, cpu, memory, net, psi, wifi
14
+ from sensitivebox.sources.bluez import BluetoothStatus, read_bluetooth
15
+ from sensitivebox.sources.dbus import NO_BUS, connect_system_bus
16
+ from sensitivebox.sources.wifi_nm import read_nm_wifi_once
17
+
18
+
19
+ @dataclass(frozen=True, slots=True)
20
+ class SourcesReport:
21
+ meminfo: memory.MemInfo | None
22
+ zram: tuple[memory.Zram, ...]
23
+ vmstat: memory.VmStat | None
24
+ pressure: dict[str, psi.Pressure]
25
+ cpu_times: cpu.CpuTimes | None
26
+ cpu_freqs: tuple[cpu.CoreFreq, ...]
27
+ net: dict[str, net.NetCounters]
28
+ wifi: wifi.WifiStatus
29
+ apps: tuple[apps.AppMemory, ...] | None # None: not sampled (memory isn't tight)
30
+ apps_reason: str | None = None # why apps is empty although memory is tight
31
+ bluetooth: BluetoothStatus | None = None # None: D-Bus not queried
32
+
33
+
34
+ def gather(proc_root: Path, sysfs_root: Path, opener: Opener = default_opener) -> SourcesReport:
35
+ """Every file-based source. Wi-Fi comes from ``/proc/net/wireless`` only; see
36
+ ``with_dbus`` for the NetworkManager fallback and Bluetooth."""
37
+ meminfo = memory.read_meminfo(proc_root, opener)
38
+ pressure = psi.read_all_pressure(proc_root, opener)
39
+ top: tuple[apps.AppMemory, ...] | None = None
40
+ reason: str | None = None
41
+ if apps.should_sample_apps(meminfo, pressure.get("memory")):
42
+ slice_dir = apps.app_slice_dir(proc_root, sysfs_root, opener)
43
+ if slice_dir is None:
44
+ top, reason = (), "no cgroup v2 app.slice for this user"
45
+ else:
46
+ top = apps.read_app_memory(slice_dir, opener=opener)
47
+ return SourcesReport(
48
+ meminfo=meminfo,
49
+ zram=memory.read_zram(sysfs_root, opener),
50
+ vmstat=memory.read_vmstat(proc_root, opener),
51
+ pressure=pressure,
52
+ cpu_times=cpu.read_cpu_times(proc_root, opener),
53
+ cpu_freqs=cpu.read_cpu_freqs(sysfs_root, opener),
54
+ net=net.read_net_counters(sysfs_root, opener=opener),
55
+ wifi=wifi.choose(wifi.read_proc_wireless(proc_root, opener), None),
56
+ apps=top,
57
+ apps_reason=reason,
58
+ )
59
+
60
+
61
+ def with_dbus(
62
+ report: SourcesReport, bluetooth: BluetoothStatus, nm_wifi: wifi.WifiStatus
63
+ ) -> SourcesReport:
64
+ """Add Bluetooth, and NetworkManager's Wi-Fi signal unless ``/proc`` already had one."""
65
+ wifi_status = report.wifi if report.wifi.available else nm_wifi
66
+ return dataclasses.replace(report, bluetooth=bluetooth, wifi=wifi_status)
67
+
68
+
69
+ SNAPSHOT_TIMEOUT_S = 2.0
70
+
71
+
72
+ async def system_bus_snapshot() -> tuple[BluetoothStatus, wifi.WifiStatus]:
73
+ """Read BlueZ and NetworkManager once, over one connection that is always closed."""
74
+ bus = await connect_system_bus()
75
+ if bus is None:
76
+ return BluetoothStatus(reason=NO_BUS), wifi.WifiStatus.unavailable(NO_BUS)
77
+ try:
78
+ async with asyncio.timeout(SNAPSHOT_TIMEOUT_S):
79
+ bt, nm = await asyncio.gather(read_bluetooth(bus), read_nm_wifi_once(bus))
80
+ except TimeoutError:
81
+ reason = "D-Bus timed out"
82
+ return BluetoothStatus(reason=reason), wifi.WifiStatus.unavailable(reason)
83
+ finally:
84
+ bus.disconnect()
85
+ return bt, nm