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,65 @@
|
|
|
1
|
+
"""Read single sysfs attribute files, turning every kind of read failure into a reason.
|
|
2
|
+
|
|
3
|
+
hwmon attributes fail in many ways: ``-ENODATA`` when the firmware has no value, ``-EIO`` when a
|
|
4
|
+
bus transaction fails, ``-EACCES`` for root-only attributes, or a file that vanishes when a device
|
|
5
|
+
is unplugged mid-scan. None of these may crash the daemon, so all of them mean "unavailable", and
|
|
6
|
+
the reason is kept so ``sensitivebox doctor`` can say why.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import errno
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
type Opener = Callable[[Path], str]
|
|
15
|
+
|
|
16
|
+
_MAX_SHOWN = 20 # characters of a non-numeric value quoted in a reason
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def default_opener(path: Path) -> str:
|
|
20
|
+
return path.read_text(encoding="utf-8", errors="replace")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True, slots=True)
|
|
24
|
+
class RawRead:
|
|
25
|
+
"""An attribute read as an integer: exactly one of ``value`` and ``reason`` is set."""
|
|
26
|
+
|
|
27
|
+
value: int | None
|
|
28
|
+
reason: str | None = None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _error_name(exc: OSError) -> str:
|
|
32
|
+
if exc.errno is not None and exc.errno in errno.errorcode:
|
|
33
|
+
return errno.errorcode[exc.errno] # e.g. "ENODATA", "EACCES", "ENOENT"
|
|
34
|
+
return type(exc).__name__
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _read_text(path: Path, opener: Opener) -> tuple[str | None, str | None]:
|
|
38
|
+
try:
|
|
39
|
+
return opener(path).strip(), None
|
|
40
|
+
except OSError as exc:
|
|
41
|
+
return None, _error_name(exc)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def read_attr(path: Path, opener: Opener = default_opener) -> str | None:
|
|
45
|
+
"""Return the stripped contents of an attribute file, or ``None`` if it can't be read."""
|
|
46
|
+
return _read_text(path, opener)[0]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def read_raw(path: Path, opener: Opener = default_opener) -> RawRead:
|
|
50
|
+
"""Read an attribute as an integer, keeping the reason when that isn't possible."""
|
|
51
|
+
text, error = _read_text(path, opener)
|
|
52
|
+
if text is None:
|
|
53
|
+
return RawRead(None, error)
|
|
54
|
+
if not text:
|
|
55
|
+
return RawRead(None, "empty")
|
|
56
|
+
try:
|
|
57
|
+
return RawRead(int(text))
|
|
58
|
+
except ValueError:
|
|
59
|
+
shown = text if len(text) <= _MAX_SHOWN else text[:_MAX_SHOWN] + "…"
|
|
60
|
+
return RawRead(None, f"not a number: {shown!r}")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def read_int(path: Path, opener: Opener = default_opener) -> int | None:
|
|
64
|
+
"""Return an attribute as an integer, or ``None`` if unreadable, empty or non-numeric."""
|
|
65
|
+
return read_raw(path, opener).value
|
sensitivebox/inspect.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Public diagnostic models omit Bluetooth aliases before serialization."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from sensitivebox import __version__, alerts, doctor
|
|
7
|
+
from sensitivebox.hwmon import Group, Kind, Limits, Reading
|
|
8
|
+
from sensitivebox.sample import Sample
|
|
9
|
+
from sensitivebox.sources import SourcesReport
|
|
10
|
+
from sensitivebox.sources.apps import AppMemory
|
|
11
|
+
from sensitivebox.sources.cpu import CoreFreq, CpuTimes
|
|
12
|
+
from sensitivebox.sources.memory import VmStat, Zram
|
|
13
|
+
from sensitivebox.sources.net import NetCounters
|
|
14
|
+
from sensitivebox.sources.psi import Pressure
|
|
15
|
+
from sensitivebox.sources.wifi import WifiStatus
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True, slots=True)
|
|
19
|
+
class MemoryView:
|
|
20
|
+
total: int
|
|
21
|
+
available: int
|
|
22
|
+
used: int
|
|
23
|
+
used_pct: float
|
|
24
|
+
cached: int
|
|
25
|
+
dirty: int
|
|
26
|
+
swap_total: int
|
|
27
|
+
swap_used: int
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True, slots=True)
|
|
31
|
+
class AdapterView:
|
|
32
|
+
name: str
|
|
33
|
+
powered: bool
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True, slots=True)
|
|
37
|
+
class DeviceView:
|
|
38
|
+
kind: str
|
|
39
|
+
battery: int | None
|
|
40
|
+
adapter: str
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True, slots=True)
|
|
44
|
+
class BluetoothView:
|
|
45
|
+
adapters: tuple[AdapterView, ...]
|
|
46
|
+
devices: tuple[DeviceView, ...]
|
|
47
|
+
reason: str | None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True, slots=True)
|
|
51
|
+
class SourcesView:
|
|
52
|
+
memory: MemoryView | None
|
|
53
|
+
pressure: dict[str, Pressure]
|
|
54
|
+
apps: tuple[AppMemory, ...] | None
|
|
55
|
+
apps_reason: str | None
|
|
56
|
+
zram: tuple[Zram, ...]
|
|
57
|
+
vmstat: VmStat | None
|
|
58
|
+
cpu_times: CpuTimes | None
|
|
59
|
+
cpu_freqs: tuple[CoreFreq, ...]
|
|
60
|
+
network: dict[str, NetCounters]
|
|
61
|
+
wifi: WifiStatus
|
|
62
|
+
bluetooth: BluetoothView
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def public_sources(report: SourcesReport) -> SourcesView:
|
|
66
|
+
mem = report.meminfo
|
|
67
|
+
memory = (
|
|
68
|
+
MemoryView(
|
|
69
|
+
mem.total,
|
|
70
|
+
mem.available,
|
|
71
|
+
mem.used,
|
|
72
|
+
mem.used_fraction * 100,
|
|
73
|
+
mem.cached,
|
|
74
|
+
mem.dirty,
|
|
75
|
+
mem.swap_total,
|
|
76
|
+
mem.swap_used,
|
|
77
|
+
)
|
|
78
|
+
if mem
|
|
79
|
+
else None
|
|
80
|
+
)
|
|
81
|
+
bt = report.bluetooth
|
|
82
|
+
bluetooth = BluetoothView(
|
|
83
|
+
tuple(AdapterView(a.name, a.powered) for a in bt.adapters) if bt else (),
|
|
84
|
+
tuple(DeviceView(d.icon or "device", d.battery, d.adapter) for d in bt.devices)
|
|
85
|
+
if bt
|
|
86
|
+
else (),
|
|
87
|
+
bt.reason if bt else "not queried",
|
|
88
|
+
)
|
|
89
|
+
return SourcesView(
|
|
90
|
+
memory,
|
|
91
|
+
report.pressure,
|
|
92
|
+
report.apps,
|
|
93
|
+
report.apps_reason,
|
|
94
|
+
report.zram,
|
|
95
|
+
report.vmstat,
|
|
96
|
+
report.cpu_times,
|
|
97
|
+
report.cpu_freqs,
|
|
98
|
+
report.net,
|
|
99
|
+
report.wifi,
|
|
100
|
+
bluetooth,
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@dataclass(frozen=True, slots=True)
|
|
105
|
+
class DoctorSensor:
|
|
106
|
+
id: str
|
|
107
|
+
label: str
|
|
108
|
+
group: Group
|
|
109
|
+
kind: Kind
|
|
110
|
+
unit: str
|
|
111
|
+
limits: Limits
|
|
112
|
+
dropped_limits: tuple[tuple[str, float], ...]
|
|
113
|
+
reading: Reading
|
|
114
|
+
default_rules: tuple[str, ...]
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass(frozen=True, slots=True)
|
|
118
|
+
class EmptyChip:
|
|
119
|
+
name: str
|
|
120
|
+
bus_id: str
|
|
121
|
+
path: str
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass(frozen=True, slots=True)
|
|
125
|
+
class DoctorView:
|
|
126
|
+
package_version: str
|
|
127
|
+
sensors: tuple[DoctorSensor, ...]
|
|
128
|
+
empty_chips: tuple[EmptyChip, ...]
|
|
129
|
+
sources: SourcesView
|
|
130
|
+
text: str
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def doctor_view(sample: Sample, sysfs_root: Path, proc_root: Path, verbose: bool) -> DoctorView:
|
|
134
|
+
rules = alerts.load_defaults()
|
|
135
|
+
sensors = tuple(
|
|
136
|
+
DoctorSensor(
|
|
137
|
+
s.id,
|
|
138
|
+
s.label,
|
|
139
|
+
s.group,
|
|
140
|
+
s.kind,
|
|
141
|
+
s.unit,
|
|
142
|
+
s.limits,
|
|
143
|
+
s.dropped_limits,
|
|
144
|
+
sample.readings[s.id],
|
|
145
|
+
tuple(r.id for r in rules if r.matches(s.id)),
|
|
146
|
+
)
|
|
147
|
+
for c in sample.chips
|
|
148
|
+
for s in c.sensors
|
|
149
|
+
)
|
|
150
|
+
empty = tuple(EmptyChip(c.name, c.bus_id, str(c.path)) for c in sample.chips if not c.sensors)
|
|
151
|
+
text = (
|
|
152
|
+
f"Sensitive Box {__version__} · sysfs root {sysfs_root} · proc root {proc_root}\n\n"
|
|
153
|
+
+ doctor.render(sample.chips, sample.readings, verbose=verbose, rules=rules)
|
|
154
|
+
+ "\n\n"
|
|
155
|
+
+ doctor.render_sources(sample.sources)
|
|
156
|
+
)
|
|
157
|
+
return DoctorView(__version__, sensors, empty, public_sources(sample.sources), text)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
@dataclass(frozen=True, slots=True)
|
|
161
|
+
class AppsView:
|
|
162
|
+
sources: SourcesView
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def render_apps(report: SourcesReport) -> str:
|
|
166
|
+
pressure = report.pressure.get("memory")
|
|
167
|
+
psi = f"{pressure.some.avg10:.2f} % some" if pressure else "unavailable"
|
|
168
|
+
lines = [f"Memory PSI {psi}"]
|
|
169
|
+
if report.apps is None:
|
|
170
|
+
lines.append("Apps not sampled: memory is healthy and pressure is steady")
|
|
171
|
+
elif not report.apps:
|
|
172
|
+
lines.append(report.apps_reason or "No apps found in this user's cgroup app.slice")
|
|
173
|
+
else:
|
|
174
|
+
lines.extend(f"{app.name} {doctor.format_bytes(app.bytes)}" for app in report.apps)
|
|
175
|
+
return "\n".join(lines)
|
sensitivebox/live.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""A heartbeat summary from the poll just collected; no additional reads or processes."""
|
|
2
|
+
|
|
3
|
+
from collections import Counter
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
from sensitivebox.alerts import State, format_duration
|
|
7
|
+
from sensitivebox.daemon import TickResult
|
|
8
|
+
from sensitivebox.store.mutes import ActiveMute
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True, slots=True)
|
|
12
|
+
class LiveStatus:
|
|
13
|
+
at: float
|
|
14
|
+
memory_used_pct: float | None
|
|
15
|
+
memory_pressure: float | None
|
|
16
|
+
open_alerts: dict[str, int]
|
|
17
|
+
states: dict[str, int]
|
|
18
|
+
muted: tuple[ActiveMute, ...] | None = None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def live_status(result: TickResult) -> LiveStatus:
|
|
22
|
+
counts = Counter(e.alert_severity for e in result.step.evaluations if e.alert_severity)
|
|
23
|
+
available = result.snapshot.signals.get("memory/available_pct")
|
|
24
|
+
pressure = result.snapshot.signals.get("psi/memory/some_avg10")
|
|
25
|
+
return LiveStatus(
|
|
26
|
+
result.snapshot.at,
|
|
27
|
+
100 - available if isinstance(available, (int, float)) else None,
|
|
28
|
+
pressure if isinstance(pressure, (int, float)) else None,
|
|
29
|
+
{s: counts[s] for s in ("info", "warning", "critical")},
|
|
30
|
+
{s.value: sum(e.state == s for e in result.step.evaluations) for s in State},
|
|
31
|
+
result.muted,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def render_live(view: LiveStatus) -> str:
|
|
36
|
+
memory = f"{view.memory_used_pct:.0f} %" if view.memory_used_pct is not None else "unavailable"
|
|
37
|
+
pressure = f"{view.memory_pressure:.1f}" if view.memory_pressure is not None else "unavailable"
|
|
38
|
+
alerts = " · ".join(f"{n} {s}" for s, n in view.open_alerts.items() if n) or "Nothing firing"
|
|
39
|
+
states = " · ".join(f"{view.states[s]} {s}" for s in ("unknown", "warming", "pending"))
|
|
40
|
+
muted = "muted unavailable" if view.muted is None else f"{len(view.muted)} muted"
|
|
41
|
+
if view.muted:
|
|
42
|
+
muted += (
|
|
43
|
+
" ("
|
|
44
|
+
+ ", ".join(
|
|
45
|
+
m.rule_id
|
|
46
|
+
+ ": "
|
|
47
|
+
+ (
|
|
48
|
+
"until reboot"
|
|
49
|
+
if m.remaining_s is None
|
|
50
|
+
else format_duration(m.remaining_s) + " left"
|
|
51
|
+
)
|
|
52
|
+
for m in view.muted
|
|
53
|
+
)
|
|
54
|
+
+ ")"
|
|
55
|
+
)
|
|
56
|
+
return f"Status · Memory {memory} · PSI {pressure} · {alerts} · {muted} · {states}"
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Notifiers sit behind one small interface: desktop (D-Bus) and a terminal log line."""
|
|
2
|
+
|
|
3
|
+
from sensitivebox.notify.base import Notifier, NotifierHub
|
|
4
|
+
from sensitivebox.notify.desktop import DesktopNotifier
|
|
5
|
+
from sensitivebox.notify.log import LogNotifier
|
|
6
|
+
|
|
7
|
+
__all__ = ["DesktopNotifier", "LogNotifier", "Notifier", "NotifierHub"]
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""The notifier interface and the hub that fans a notification out to every channel."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from collections.abc import Iterable, Sequence
|
|
5
|
+
from typing import Protocol
|
|
6
|
+
|
|
7
|
+
from sensitivebox.alerts.engine import Transition
|
|
8
|
+
from sensitivebox.alerts.routing import Notification
|
|
9
|
+
|
|
10
|
+
log = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Notifier(Protocol):
|
|
14
|
+
"""One delivery channel (desktop, webhook, sound…). Notifiers only ever see notifications
|
|
15
|
+
that already passed the mute layer and cooldown."""
|
|
16
|
+
|
|
17
|
+
async def notify(self, notification: Notification) -> bool | None:
|
|
18
|
+
"""False means delivery failed; None preserves simple successful notifiers."""
|
|
19
|
+
...
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class NotifierHub:
|
|
23
|
+
"""Sends each notification to every notifier. One failing channel never stops the others,
|
|
24
|
+
and never raises into the daemon loop. Return only notifications accepted by every enabled
|
|
25
|
+
channel; retain successful channel receipts while a failed firing is retried."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, notifiers: Sequence[Notifier]) -> None:
|
|
28
|
+
self._notifiers = tuple(notifiers)
|
|
29
|
+
self._receipts: dict[tuple[str, str, float, bool], set[int]] = {}
|
|
30
|
+
|
|
31
|
+
def discard_closed(self, alerts: Iterable[Transition]) -> None:
|
|
32
|
+
"""Keep partial channel receipts only while their firing is still open."""
|
|
33
|
+
opened = {(t.rule_id, t.signal, t.opened_at, t.no_data) for t in alerts}
|
|
34
|
+
for key in self._receipts.keys() - opened:
|
|
35
|
+
del self._receipts[key]
|
|
36
|
+
|
|
37
|
+
async def send(self, notifications: Iterable[Notification]) -> tuple[Notification, ...]:
|
|
38
|
+
delivered: list[Notification] = []
|
|
39
|
+
for notification in notifications:
|
|
40
|
+
key = (
|
|
41
|
+
notification.rule_id,
|
|
42
|
+
notification.signal,
|
|
43
|
+
notification.opened_at,
|
|
44
|
+
notification.no_data,
|
|
45
|
+
)
|
|
46
|
+
receipts: set[int] = (
|
|
47
|
+
self._receipts.setdefault(key, set()) if notification.kind == "firing" else set()
|
|
48
|
+
)
|
|
49
|
+
for index, notifier in enumerate(self._notifiers):
|
|
50
|
+
if index in receipts:
|
|
51
|
+
continue
|
|
52
|
+
try:
|
|
53
|
+
if await notifier.notify(notification) is not False:
|
|
54
|
+
receipts.add(index)
|
|
55
|
+
except Exception:
|
|
56
|
+
log.exception("notifier %s failed", type(notifier).__name__)
|
|
57
|
+
if len(receipts) == len(self._notifiers):
|
|
58
|
+
delivered.append(notification)
|
|
59
|
+
self._receipts.pop(key, None)
|
|
60
|
+
return tuple(delivered)
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Desktop notifications over ``org.freedesktop.Notifications`` on the session bus.
|
|
2
|
+
|
|
3
|
+
Never ``notify-send`` and never a subprocess: one D-Bus method call per notification. Urgency
|
|
4
|
+
follows the spec's hint (0 low, 1 normal, 2 critical): a critical alert that fires is 2, a
|
|
5
|
+
resolved alert is low, and anything else that fires is normal.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from typing import Final
|
|
11
|
+
|
|
12
|
+
from dbus_fast import Variant
|
|
13
|
+
from dbus_fast.errors import DBusFastError
|
|
14
|
+
|
|
15
|
+
from sensitivebox.alerts.engine import TransitionKind
|
|
16
|
+
from sensitivebox.alerts.routing import Notification
|
|
17
|
+
from sensitivebox.sources.dbus import Bus, DBusCallError, call
|
|
18
|
+
|
|
19
|
+
log = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
SERVICE: Final = "org.freedesktop.Notifications"
|
|
22
|
+
PATH: Final = "/org/freedesktop/Notifications"
|
|
23
|
+
APP_NAME: Final = "Sensitive Box"
|
|
24
|
+
|
|
25
|
+
URGENCY_LOW: Final = 0
|
|
26
|
+
URGENCY_NORMAL: Final = 1
|
|
27
|
+
URGENCY_CRITICAL: Final = 2
|
|
28
|
+
EXPIRE_DEFAULT: Final = -1 # let the notification server decide
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def urgency(notification: Notification) -> int:
|
|
32
|
+
if notification.kind is TransitionKind.RESOLVED:
|
|
33
|
+
return URGENCY_LOW
|
|
34
|
+
return URGENCY_CRITICAL if notification.severity == "critical" else URGENCY_NORMAL
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class DesktopNotifier:
|
|
38
|
+
"""Sends notifications on ``bus``. With no bus (no desktop session) it does nothing.
|
|
39
|
+
|
|
40
|
+
A failed call is logged once per distinct error and returns False so the daemon can retry.
|
|
41
|
+
A missing notification daemon must not stop alerting, the dashboard or the log.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
def __init__(self, bus: Bus | None, *, warn: Callable[[str], None] = log.warning) -> None:
|
|
45
|
+
self._bus = bus
|
|
46
|
+
self._warn = warn
|
|
47
|
+
self._warned: set[str] = set()
|
|
48
|
+
if bus is None:
|
|
49
|
+
self._warn_once("no-session", "desktop notifications off: no session bus")
|
|
50
|
+
|
|
51
|
+
async def notify(self, notification: Notification) -> bool | None:
|
|
52
|
+
if self._bus is None:
|
|
53
|
+
return
|
|
54
|
+
try:
|
|
55
|
+
await call(
|
|
56
|
+
self._bus,
|
|
57
|
+
SERVICE,
|
|
58
|
+
PATH,
|
|
59
|
+
SERVICE,
|
|
60
|
+
"Notify",
|
|
61
|
+
"susssasa{sv}i",
|
|
62
|
+
[
|
|
63
|
+
APP_NAME,
|
|
64
|
+
0, # replaces_id: a new notification each time
|
|
65
|
+
"", # app_icon
|
|
66
|
+
notification.title,
|
|
67
|
+
notification.body,
|
|
68
|
+
[], # actions
|
|
69
|
+
{"urgency": Variant("y", urgency(notification))},
|
|
70
|
+
EXPIRE_DEFAULT,
|
|
71
|
+
],
|
|
72
|
+
)
|
|
73
|
+
except DBusCallError as exc:
|
|
74
|
+
self._warn_once(exc.name, f"desktop notification failed: {exc}")
|
|
75
|
+
return False
|
|
76
|
+
except (OSError, EOFError, DBusFastError) as exc: # the bus went away
|
|
77
|
+
self._warn_once(type(exc).__name__, f"desktop notification failed: {exc!r}")
|
|
78
|
+
return False
|
|
79
|
+
return True
|
|
80
|
+
|
|
81
|
+
def _warn_once(self, key: str, message: str) -> None:
|
|
82
|
+
if key not in self._warned:
|
|
83
|
+
self._warned.add(key)
|
|
84
|
+
self._warn(message)
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""A notifier that prints one line per alert to the terminal: what ``sbox watch`` shows."""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
|
|
6
|
+
from sensitivebox.alerts.engine import TransitionKind
|
|
7
|
+
from sensitivebox.alerts.routing import Notification
|
|
8
|
+
from sensitivebox.redact import redact
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class LogNotifier:
|
|
12
|
+
def __init__(
|
|
13
|
+
self,
|
|
14
|
+
write: Callable[[str], None] = print,
|
|
15
|
+
*,
|
|
16
|
+
now: Callable[[], float] = time.time,
|
|
17
|
+
event: Callable[[Notification, str], None] | None = None,
|
|
18
|
+
) -> None:
|
|
19
|
+
self._write = write
|
|
20
|
+
self._now = now
|
|
21
|
+
self._event = event
|
|
22
|
+
|
|
23
|
+
async def notify(self, notification: Notification) -> None:
|
|
24
|
+
stamp = time.strftime("%H:%M:%S", time.localtime(self._now()))
|
|
25
|
+
word = "FIRING " if notification.kind is TransitionKind.FIRING else "RESOLVED"
|
|
26
|
+
text = f"{stamp} {word} {notification.title} — {notification.body}"
|
|
27
|
+
if self._event is not None:
|
|
28
|
+
self._event(notification, text)
|
|
29
|
+
else:
|
|
30
|
+
self._write(redact(text))
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""CLI writes for the SQLite mute control plane."""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from sensitivebox.alerts.engine import Clock
|
|
8
|
+
from sensitivebox.alerts.model import parse_duration
|
|
9
|
+
from sensitivebox.alerts.mute import boot_id
|
|
10
|
+
from sensitivebox.store import Store
|
|
11
|
+
from sensitivebox.store.mutes import ActiveMute
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True, slots=True)
|
|
15
|
+
class MuteView:
|
|
16
|
+
mutes: tuple[ActiveMute, ...]
|
|
17
|
+
message: str
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def control(
|
|
21
|
+
path: Path,
|
|
22
|
+
proc_root: Path,
|
|
23
|
+
command: str,
|
|
24
|
+
rule: str,
|
|
25
|
+
duration: str,
|
|
26
|
+
renotify: bool,
|
|
27
|
+
*,
|
|
28
|
+
clock: Clock = time.monotonic,
|
|
29
|
+
) -> MuteView:
|
|
30
|
+
expiry: float | None = None
|
|
31
|
+
if command == "mute" and duration != "until-reboot":
|
|
32
|
+
seconds = parse_duration(duration)
|
|
33
|
+
if seconds <= 0:
|
|
34
|
+
raise ValueError("mute duration must be positive; use e.g. 30m or until-reboot")
|
|
35
|
+
expiry = clock() + seconds
|
|
36
|
+
boot = boot_id(proc_root) if command != "quiet" else ""
|
|
37
|
+
with Store(path, clock=time.time, start_session=False) as store:
|
|
38
|
+
if command == "mute":
|
|
39
|
+
store.mutes.set(rule, boot, expiry, renotify)
|
|
40
|
+
elif command == "unmute":
|
|
41
|
+
store.mutes.remove(rule, boot)
|
|
42
|
+
else:
|
|
43
|
+
store.mutes.quiet(duration, renotify)
|
|
44
|
+
return MuteView(store.mutes.active(boot, clock()), f"{command}: {rule or duration}")
|
sensitivebox/output.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""One redacted boundary for terminal documents, events and errors."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import sys
|
|
5
|
+
from collections.abc import Callable, Generator
|
|
6
|
+
from contextlib import contextmanager
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Any, cast
|
|
9
|
+
|
|
10
|
+
import msgspec
|
|
11
|
+
|
|
12
|
+
from sensitivebox.redact import redact
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Document(msgspec.Struct, frozen=True):
|
|
16
|
+
kind: str
|
|
17
|
+
data: Any
|
|
18
|
+
version: int = 1
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _private(value: Any, redactor: Callable[[str], str]) -> Any:
|
|
22
|
+
if isinstance(value, str):
|
|
23
|
+
return redactor(value)
|
|
24
|
+
if isinstance(value, dict):
|
|
25
|
+
return {redactor(k): _private(v, redactor) for k, v in cast(dict[str, Any], value).items()}
|
|
26
|
+
if isinstance(value, list):
|
|
27
|
+
return [_private(v, redactor) for v in cast(list[Any], value)]
|
|
28
|
+
return value
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def encode(value: object, *, redactor: Callable[[str], str] = redact) -> str:
|
|
32
|
+
"""Redact fields before encoding, preserving JSON escapes and numeric types."""
|
|
33
|
+
return msgspec.json.encode(_private(msgspec.to_builtins(value), redactor)).decode()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True, slots=True)
|
|
37
|
+
class Output:
|
|
38
|
+
json: bool = False
|
|
39
|
+
|
|
40
|
+
def emit(self, kind: str, data: object, text: str, *, error: bool = False) -> None:
|
|
41
|
+
line = encode(Document(kind, data)) if self.json else redact(text)
|
|
42
|
+
print(line, file=sys.stderr if error else sys.stdout, flush=True)
|
|
43
|
+
|
|
44
|
+
def line(self, text: str) -> None:
|
|
45
|
+
self.emit("message", text, text)
|
|
46
|
+
|
|
47
|
+
def error(self, text: str) -> None:
|
|
48
|
+
self.emit("error", text, f"sbox: {text}", error=True)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# CLI-owned logging uses the same boundary, including exception tracebacks.
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class _Handler(logging.Handler):
|
|
55
|
+
def __init__(self, output: Output) -> None:
|
|
56
|
+
super().__init__()
|
|
57
|
+
self.output = output
|
|
58
|
+
|
|
59
|
+
def emit(self, record: logging.LogRecord) -> None:
|
|
60
|
+
text = self.format(record)
|
|
61
|
+
self.output.emit("log", text, text, error=True)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@contextmanager
|
|
65
|
+
def logging_output(output: Output) -> Generator[None]:
|
|
66
|
+
logger = logging.getLogger("sensitivebox")
|
|
67
|
+
handlers, propagate = logger.handlers[:], logger.propagate
|
|
68
|
+
handler = _Handler(output)
|
|
69
|
+
logger.handlers = [handler]
|
|
70
|
+
logger.propagate = False
|
|
71
|
+
try:
|
|
72
|
+
yield
|
|
73
|
+
finally:
|
|
74
|
+
logger.handlers = handlers
|
|
75
|
+
logger.propagate = propagate
|
|
76
|
+
handler.close()
|
sensitivebox/process.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Bounded child processes with captured, redacted output and no shell."""
|
|
2
|
+
|
|
3
|
+
import subprocess
|
|
4
|
+
from collections.abc import Sequence
|
|
5
|
+
|
|
6
|
+
from sensitivebox.redact import redact
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def run(args: Sequence[str]) -> str:
|
|
10
|
+
try:
|
|
11
|
+
result = subprocess.run( # noqa: S603 - argument vectors only, no shell
|
|
12
|
+
list(args),
|
|
13
|
+
capture_output=True,
|
|
14
|
+
text=True,
|
|
15
|
+
stdin=subprocess.DEVNULL,
|
|
16
|
+
timeout=10,
|
|
17
|
+
check=False,
|
|
18
|
+
)
|
|
19
|
+
except subprocess.TimeoutExpired:
|
|
20
|
+
raise OSError(redact(f"{args[0]} timed out after 10 s")) from None
|
|
21
|
+
if result.returncode:
|
|
22
|
+
raise OSError(
|
|
23
|
+
redact(result.stderr or result.stdout or f"{args[0]} failed ({result.returncode})")
|
|
24
|
+
)
|
|
25
|
+
return redact(result.stdout)
|
sensitivebox/py.typed
ADDED
|
File without changes
|