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,247 @@
|
|
|
1
|
+
"""From transitions to notifications: engine → **mute** → cooldown → notifiers.
|
|
2
|
+
|
|
3
|
+
Muting sits after the engine, never inside it: a muted alert still evaluates, is logged and lights
|
|
4
|
+
the LED; only its notification is held back. Prompt 2 ships the ``Mute`` interface and a
|
|
5
|
+
pass-through stub; the real layer (dashboard mutes, quiet hours, re-notify when a mute ends) is
|
|
6
|
+
Prompt 3.
|
|
7
|
+
|
|
8
|
+
Cooldown is the minimum gap between repeat firing notifications of the same rule, signal and kind
|
|
9
|
+
of alert (a value alert, or a "no data" one). It never holds back a more severe alert than the last
|
|
10
|
+
one delivered, so an info "no data" notification can't mask a critical heat alert (ADV-001).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import socket
|
|
14
|
+
from collections.abc import Iterable, Mapping
|
|
15
|
+
from dataclasses import dataclass, field, replace
|
|
16
|
+
from typing import Protocol
|
|
17
|
+
|
|
18
|
+
import msgspec
|
|
19
|
+
|
|
20
|
+
from sensitivebox.alerts.engine import Transition, TransitionKind, format_duration
|
|
21
|
+
from sensitivebox.alerts.model import Rule, Severity
|
|
22
|
+
|
|
23
|
+
SEVERITY_RANK: dict[Severity, int] = {"info": 0, "warning": 1, "critical": 2}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True, slots=True)
|
|
27
|
+
class Notification:
|
|
28
|
+
at: float
|
|
29
|
+
rule_id: str
|
|
30
|
+
signal: str
|
|
31
|
+
kind: TransitionKind
|
|
32
|
+
severity: Severity
|
|
33
|
+
title: str # "CRITICAL · CPU hot · proart-p16"
|
|
34
|
+
body: str # "95 above 90 for 10 s (k10temp/0000:00:18.3/temp1)"
|
|
35
|
+
opened_at: float # identifies the alert this belongs to
|
|
36
|
+
no_data: bool = False
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True, slots=True)
|
|
40
|
+
class MuteDecision:
|
|
41
|
+
deliver: bool
|
|
42
|
+
reason: str | None = None # why it was held
|
|
43
|
+
renotify: bool = True
|
|
44
|
+
manual_release: str | None = None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Mute(Protocol):
|
|
48
|
+
"""Decides, per notification, whether it goes out now. Never sees or changes alert state."""
|
|
49
|
+
|
|
50
|
+
def decide(self, notification: Notification) -> MuteDecision: ...
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class PassThroughMute:
|
|
54
|
+
"""The Prompt 2 stub: every notification is delivered."""
|
|
55
|
+
|
|
56
|
+
def decide(self, notification: Notification) -> MuteDecision:
|
|
57
|
+
return MuteDecision(deliver=True)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True, slots=True)
|
|
61
|
+
class Held:
|
|
62
|
+
notification: Notification
|
|
63
|
+
reason: str
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True, slots=True)
|
|
67
|
+
class Routed:
|
|
68
|
+
delivered: tuple[Notification, ...] = ()
|
|
69
|
+
held: tuple[Held, ...] = ()
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def title(severity: Severity, rule_title: str, host: str) -> str:
|
|
73
|
+
return f"{severity.upper()} · {rule_title} · {host}"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def body(transition: Transition) -> str:
|
|
77
|
+
reason = transition.reason[:1].upper() + transition.reason[1:]
|
|
78
|
+
if transition.kind is TransitionKind.RESOLVED:
|
|
79
|
+
reason += f" after {format_duration(transition.at - transition.opened_at)}"
|
|
80
|
+
return f"{reason} ({transition.signal})"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass(frozen=True, slots=True)
|
|
84
|
+
class RouterMemory:
|
|
85
|
+
last: list[tuple[str, str, bool, float, Severity]]
|
|
86
|
+
cooled: list[tuple[str, str, float]]
|
|
87
|
+
alerts: list[tuple[Transition, MuteDecision | None, bool]]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass(slots=True)
|
|
91
|
+
class Router:
|
|
92
|
+
host: str = field(default_factory=socket.gethostname)
|
|
93
|
+
mute: Mute = field(default_factory=PassThroughMute)
|
|
94
|
+
# (rule id, signal, no-data?) → when and at what severity its last firing notification went out
|
|
95
|
+
_last_fired: dict[tuple[str, str, bool], tuple[float, Severity]] = field(
|
|
96
|
+
default_factory=lambda: {}
|
|
97
|
+
)
|
|
98
|
+
# alerts whose firing notification was held by cooldown, so their resolve is held too
|
|
99
|
+
_cooled: set[tuple[str, str, float]] = field(default_factory=lambda: set())
|
|
100
|
+
|
|
101
|
+
_open: dict[tuple[str, str, float, bool], Transition] = field(default_factory=lambda: {})
|
|
102
|
+
_blocked: dict[tuple[str, str, float, bool], MuteDecision] = field(default_factory=lambda: {})
|
|
103
|
+
_pending: set[tuple[str, str, float, bool]] = field(default_factory=lambda: set())
|
|
104
|
+
|
|
105
|
+
def open_alerts(self) -> tuple[Transition, ...]:
|
|
106
|
+
return tuple(self._open.values())
|
|
107
|
+
|
|
108
|
+
def checkpoint(self) -> str:
|
|
109
|
+
memory = RouterMemory(
|
|
110
|
+
[(r, s, n, at, severity) for (r, s, n), (at, severity) in self._last_fired.items()],
|
|
111
|
+
list(self._cooled),
|
|
112
|
+
[(t, self._blocked.get(key), key in self._pending) for key, t in self._open.items()],
|
|
113
|
+
)
|
|
114
|
+
return msgspec.json.encode(memory).decode()
|
|
115
|
+
|
|
116
|
+
def restore(self, payload: str) -> None:
|
|
117
|
+
memory = msgspec.json.decode(payload, type=RouterMemory)
|
|
118
|
+
self._last_fired = {(r, s, n): (at, severity) for r, s, n, at, severity in memory.last}
|
|
119
|
+
self._cooled = set(memory.cooled)
|
|
120
|
+
self._open.clear()
|
|
121
|
+
self._blocked.clear()
|
|
122
|
+
self._pending.clear()
|
|
123
|
+
for t, decision, pending in memory.alerts:
|
|
124
|
+
key = (t.rule_id, t.signal, t.opened_at, t.no_data)
|
|
125
|
+
self._open[key] = t
|
|
126
|
+
if decision is not None:
|
|
127
|
+
self._blocked[key] = decision
|
|
128
|
+
if pending:
|
|
129
|
+
self._pending.add(key)
|
|
130
|
+
|
|
131
|
+
def poll(
|
|
132
|
+
self,
|
|
133
|
+
at: float,
|
|
134
|
+
rules: Mapping[str, Rule],
|
|
135
|
+
*,
|
|
136
|
+
defer_delivery: bool = False,
|
|
137
|
+
skip: Iterable[Notification] = (),
|
|
138
|
+
) -> Routed:
|
|
139
|
+
delivered: list[Notification] = []
|
|
140
|
+
held: list[Held] = []
|
|
141
|
+
skipped = {(n.rule_id, n.signal, n.opened_at, n.no_data) for n in skip}
|
|
142
|
+
for key, original in list(self._open.items()):
|
|
143
|
+
if key in skipped:
|
|
144
|
+
continue
|
|
145
|
+
t = replace(original, at=at)
|
|
146
|
+
note = self._notification(t, rules.get(t.rule_id))
|
|
147
|
+
decision = self.mute.decide(note)
|
|
148
|
+
if not decision.deliver:
|
|
149
|
+
if key not in self._blocked:
|
|
150
|
+
held.append(Held(note, decision.reason or "muted"))
|
|
151
|
+
self._blocked[key] = decision
|
|
152
|
+
continue
|
|
153
|
+
previous = self._blocked.pop(key, None)
|
|
154
|
+
if previous is not None and (
|
|
155
|
+
previous.renotify or decision.manual_release == previous.reason
|
|
156
|
+
):
|
|
157
|
+
self._pending.add(key)
|
|
158
|
+
if key not in self._pending:
|
|
159
|
+
continue
|
|
160
|
+
reason = self._cooldown(t, rules.get(t.rule_id))
|
|
161
|
+
if reason is None:
|
|
162
|
+
delivered.append(note)
|
|
163
|
+
if not defer_delivery:
|
|
164
|
+
self.confirm_delivery(note)
|
|
165
|
+
elif previous is not None:
|
|
166
|
+
held.append(Held(note, reason))
|
|
167
|
+
return Routed(tuple(delivered), tuple(held))
|
|
168
|
+
|
|
169
|
+
def _notification(self, t: Transition, rule: Rule | None) -> Notification:
|
|
170
|
+
return Notification(
|
|
171
|
+
at=t.at,
|
|
172
|
+
rule_id=t.rule_id,
|
|
173
|
+
signal=t.signal,
|
|
174
|
+
kind=t.kind,
|
|
175
|
+
severity=t.severity,
|
|
176
|
+
title=title(t.severity, rule.title if rule else t.rule_id, self.host),
|
|
177
|
+
body=body(t),
|
|
178
|
+
opened_at=t.opened_at,
|
|
179
|
+
no_data=t.no_data,
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
def route(
|
|
183
|
+
self,
|
|
184
|
+
transitions: Iterable[Transition],
|
|
185
|
+
rules: Mapping[str, Rule],
|
|
186
|
+
*,
|
|
187
|
+
defer_delivery: bool = False,
|
|
188
|
+
) -> Routed:
|
|
189
|
+
delivered: list[Notification] = []
|
|
190
|
+
held: list[Held] = []
|
|
191
|
+
for t in transitions:
|
|
192
|
+
rule = rules.get(t.rule_id)
|
|
193
|
+
key = (t.rule_id, t.signal, t.opened_at, t.no_data)
|
|
194
|
+
if t.kind is TransitionKind.FIRING:
|
|
195
|
+
self._open[key] = t
|
|
196
|
+
else:
|
|
197
|
+
self._open.pop(key, None)
|
|
198
|
+
self._blocked.pop(key, None)
|
|
199
|
+
self._pending.discard(key)
|
|
200
|
+
note = self._notification(t, rule)
|
|
201
|
+
decision = self.mute.decide(note)
|
|
202
|
+
if not decision.deliver:
|
|
203
|
+
if t.kind is TransitionKind.FIRING:
|
|
204
|
+
self._blocked[key] = decision
|
|
205
|
+
held.append(Held(note, decision.reason or "muted"))
|
|
206
|
+
continue
|
|
207
|
+
reason = self._cooldown(t, rule)
|
|
208
|
+
if reason is not None:
|
|
209
|
+
if t.kind is TransitionKind.FIRING:
|
|
210
|
+
self._pending.add(key)
|
|
211
|
+
held.append(Held(note, reason))
|
|
212
|
+
continue
|
|
213
|
+
delivered.append(note)
|
|
214
|
+
if t.kind is TransitionKind.FIRING:
|
|
215
|
+
self._pending.add(key)
|
|
216
|
+
if not defer_delivery:
|
|
217
|
+
self.confirm_delivery(note)
|
|
218
|
+
return Routed(tuple(delivered), tuple(held))
|
|
219
|
+
|
|
220
|
+
def confirm_delivery(self, note: Notification, *, at: float | None = None) -> None:
|
|
221
|
+
"""Commit a successful firing send. Until then it remains eligible for retry."""
|
|
222
|
+
if note.kind is TransitionKind.FIRING:
|
|
223
|
+
self._last_fired[(note.rule_id, note.signal, note.no_data)] = (
|
|
224
|
+
note.at if at is None else at,
|
|
225
|
+
note.severity,
|
|
226
|
+
)
|
|
227
|
+
self._pending.discard((note.rule_id, note.signal, note.opened_at, note.no_data))
|
|
228
|
+
self._cooled.discard((note.rule_id, note.signal, note.opened_at))
|
|
229
|
+
|
|
230
|
+
def _cooldown(self, t: Transition, rule: Rule | None) -> str | None:
|
|
231
|
+
key = (t.rule_id, t.signal, t.no_data)
|
|
232
|
+
alert = (t.rule_id, t.signal, t.opened_at)
|
|
233
|
+
if t.kind is TransitionKind.RESOLVED:
|
|
234
|
+
if alert in self._cooled:
|
|
235
|
+
self._cooled.discard(alert)
|
|
236
|
+
return "cooldown"
|
|
237
|
+
return None
|
|
238
|
+
last = self._last_fired.get(key)
|
|
239
|
+
cooldown = rule.cooldown_s if rule is not None else 0.0
|
|
240
|
+
if last is not None:
|
|
241
|
+
last_at, last_severity = last
|
|
242
|
+
elapsed = max(t.at - last_at, 0.0) # a clock step backwards is no time passing
|
|
243
|
+
escalated = SEVERITY_RANK[t.severity] > SEVERITY_RANK[last_severity]
|
|
244
|
+
if elapsed < cooldown and not escalated:
|
|
245
|
+
self._cooled.add(alert)
|
|
246
|
+
return "cooldown"
|
|
247
|
+
return None
|
sensitivebox/api/app.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"""Local ASGI routes; all handlers execute on the daemon thread, including SQLite access."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from collections.abc import AsyncGenerator
|
|
5
|
+
from contextlib import asynccontextmanager
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import msgspec
|
|
9
|
+
from starlette.applications import Starlette
|
|
10
|
+
from starlette.datastructures import Headers
|
|
11
|
+
from starlette.exceptions import HTTPException
|
|
12
|
+
from starlette.middleware import Middleware
|
|
13
|
+
from starlette.requests import Request
|
|
14
|
+
from starlette.responses import FileResponse, Response, StreamingResponse
|
|
15
|
+
from starlette.routing import Route
|
|
16
|
+
from starlette.types import Message, Receive, Scope, Send
|
|
17
|
+
|
|
18
|
+
from sensitivebox.alerts.model import parse_duration
|
|
19
|
+
from sensitivebox.api.data import history, incident, incidents
|
|
20
|
+
from sensitivebox.api.host import host_view
|
|
21
|
+
from sensitivebox.api.model import AckBody, ErrorView, MuteBody
|
|
22
|
+
from sensitivebox.api.security import ApiSecurity
|
|
23
|
+
from sensitivebox.api.state import ApiState
|
|
24
|
+
|
|
25
|
+
MAX_BODY = 4096
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class BuiltFileResponse(FileResponse):
|
|
29
|
+
"""Keep successful assets unchanged; route library-generated errors through redaction."""
|
|
30
|
+
|
|
31
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
32
|
+
async def checked(message: Message) -> None:
|
|
33
|
+
if message["type"] == "http.response.start" and message["status"] >= 400:
|
|
34
|
+
content_range = Headers(raw=message["headers"]).get("content-range")
|
|
35
|
+
headers = {"Content-Range": content_range} if content_range else None
|
|
36
|
+
raise HTTPException(message["status"], "invalid static file range", headers=headers)
|
|
37
|
+
await send(message)
|
|
38
|
+
|
|
39
|
+
await super().__call__(scope, receive, checked)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class LiveResponse(StreamingResponse):
|
|
43
|
+
"""Cancel even a blocked socket send when a subscriber's queue overflows."""
|
|
44
|
+
|
|
45
|
+
def __init__(self, state: ApiState) -> None:
|
|
46
|
+
self.state = state
|
|
47
|
+
self.sub = state.subscribe()
|
|
48
|
+
super().__init__(
|
|
49
|
+
state.stream(self.sub),
|
|
50
|
+
media_type="text/event-stream",
|
|
51
|
+
headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"},
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
async def stream_response(self, send: Send) -> None:
|
|
55
|
+
sender = asyncio.create_task(super().stream_response(send))
|
|
56
|
+
closed = asyncio.create_task(self.sub.closed.wait())
|
|
57
|
+
try:
|
|
58
|
+
done, _ = await asyncio.wait((sender, closed), return_when=asyncio.FIRST_COMPLETED)
|
|
59
|
+
if sender in done:
|
|
60
|
+
await sender
|
|
61
|
+
else:
|
|
62
|
+
sender.cancel()
|
|
63
|
+
await asyncio.gather(sender, return_exceptions=True)
|
|
64
|
+
# If even the final frame is blocked, propagate a generic timeout so the
|
|
65
|
+
# ASGI server closes the transport instead of retaining a slow client.
|
|
66
|
+
async with asyncio.timeout(0.1):
|
|
67
|
+
await send({"type": "http.response.body", "body": b"", "more_body": False})
|
|
68
|
+
finally:
|
|
69
|
+
sender.cancel()
|
|
70
|
+
closed.cancel()
|
|
71
|
+
await asyncio.gather(sender, closed, return_exceptions=True)
|
|
72
|
+
self.state.unsubscribe(self.sub)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def create_app(
|
|
76
|
+
state: ApiState,
|
|
77
|
+
*,
|
|
78
|
+
proc_root: Path,
|
|
79
|
+
os_release: Path,
|
|
80
|
+
static_root: Path | None = None,
|
|
81
|
+
) -> Starlette:
|
|
82
|
+
static = (
|
|
83
|
+
static_root if static_root is not None else Path(__file__).parent / "static"
|
|
84
|
+
).resolve()
|
|
85
|
+
facts = host_view(proc_root, os_release)
|
|
86
|
+
|
|
87
|
+
def reply(value: object, code: int = 200) -> Response:
|
|
88
|
+
return Response(state.encode(value), status_code=code, media_type="application/json")
|
|
89
|
+
|
|
90
|
+
async def error(request: Request, exc: Exception) -> Response:
|
|
91
|
+
if isinstance(exc, HTTPException):
|
|
92
|
+
response = reply(ErrorView(str(exc.detail)), exc.status_code)
|
|
93
|
+
response.headers.update(exc.headers or {})
|
|
94
|
+
return response
|
|
95
|
+
return reply(ErrorView("API unavailable; monitoring continues"), 500)
|
|
96
|
+
|
|
97
|
+
async def sensors(request: Request) -> Response:
|
|
98
|
+
view = state.snapshot()
|
|
99
|
+
if view is None:
|
|
100
|
+
raise HTTPException(503, "waiting for the first poll")
|
|
101
|
+
return reply(view)
|
|
102
|
+
|
|
103
|
+
async def host(request: Request) -> Response:
|
|
104
|
+
return reply(facts)
|
|
105
|
+
|
|
106
|
+
async def read_history(request: Request) -> Response:
|
|
107
|
+
identity = request.query_params.get("id")
|
|
108
|
+
period = request.query_params.get("range")
|
|
109
|
+
if not identity or period not in {"1h", "6h", "24h"}:
|
|
110
|
+
raise HTTPException(400, "history requires id and range=1h|6h|24h")
|
|
111
|
+
state.store.flush()
|
|
112
|
+
return reply(history(state.store.mutes.db, identity, period, state.wall(), state.interval))
|
|
113
|
+
|
|
114
|
+
async def alerts(request: Request) -> Response:
|
|
115
|
+
try:
|
|
116
|
+
limit = int(request.query_params.get("limit", "100"))
|
|
117
|
+
except ValueError:
|
|
118
|
+
raise HTTPException(400, "limit must be 1-10000") from None
|
|
119
|
+
if not 1 <= limit <= 10000:
|
|
120
|
+
raise HTTPException(400, "limit must be 1-10000")
|
|
121
|
+
return reply(
|
|
122
|
+
incidents(
|
|
123
|
+
state.store.mutes.db,
|
|
124
|
+
state.wall(),
|
|
125
|
+
limit,
|
|
126
|
+
boot=state.boot,
|
|
127
|
+
monotonic_now=state.clock(),
|
|
128
|
+
)
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
async def mutate(request: Request) -> Response:
|
|
132
|
+
if (
|
|
133
|
+
request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
|
134
|
+
!= "application/json"
|
|
135
|
+
):
|
|
136
|
+
raise HTTPException(415, "use application/json")
|
|
137
|
+
body = bytearray()
|
|
138
|
+
async for chunk in request.stream():
|
|
139
|
+
body.extend(chunk)
|
|
140
|
+
if len(body) > MAX_BODY:
|
|
141
|
+
raise HTTPException(413, "JSON body too large")
|
|
142
|
+
muting = request.path_params["action"] == "mute"
|
|
143
|
+
try:
|
|
144
|
+
payload = (
|
|
145
|
+
msgspec.json.decode(body, type=MuteBody)
|
|
146
|
+
if muting
|
|
147
|
+
else msgspec.json.decode(body, type=AckBody)
|
|
148
|
+
)
|
|
149
|
+
expiry = None
|
|
150
|
+
if isinstance(payload, MuteBody) and payload.duration != "until-reboot":
|
|
151
|
+
seconds = parse_duration(payload.duration)
|
|
152
|
+
if seconds <= 0:
|
|
153
|
+
raise ValueError("duration must be positive")
|
|
154
|
+
expiry = state.clock() + seconds
|
|
155
|
+
except (msgspec.DecodeError, ValueError):
|
|
156
|
+
raise HTTPException(400, "invalid JSON or mutation fields") from None
|
|
157
|
+
db = state.store.mutes.db
|
|
158
|
+
current = incident(db, str(request.path_params["id"]))
|
|
159
|
+
if current is None:
|
|
160
|
+
raise HTTPException(404, "unknown incident")
|
|
161
|
+
if current.closed is not None:
|
|
162
|
+
raise HTTPException(409, "incident already closed")
|
|
163
|
+
with db:
|
|
164
|
+
if isinstance(payload, MuteBody):
|
|
165
|
+
# Same control plane and boot/monotonic scope as the CLI, no direct routing.
|
|
166
|
+
state.store.mutes.set(current.rule_id, state.boot, expiry, payload.renotify)
|
|
167
|
+
state.store.events.fact(current.id, "muted")
|
|
168
|
+
else:
|
|
169
|
+
state.store.events.fact(current.id, "acknowledged")
|
|
170
|
+
updated = incident(db, current.id)
|
|
171
|
+
if updated is None:
|
|
172
|
+
raise HTTPException(404, "unknown incident")
|
|
173
|
+
if muting or not current.acknowledged:
|
|
174
|
+
state.changed(updated, "muted" if muting else "acknowledged")
|
|
175
|
+
return reply(updated)
|
|
176
|
+
|
|
177
|
+
async def ack(request: Request) -> Response:
|
|
178
|
+
request.path_params["action"] = "ack"
|
|
179
|
+
return await mutate(request)
|
|
180
|
+
|
|
181
|
+
async def mute(request: Request) -> Response:
|
|
182
|
+
request.path_params["action"] = "mute"
|
|
183
|
+
return await mutate(request)
|
|
184
|
+
|
|
185
|
+
async def stream(request: Request) -> Response:
|
|
186
|
+
return LiveResponse(state)
|
|
187
|
+
|
|
188
|
+
async def fallback(request: Request) -> Response:
|
|
189
|
+
route = request.path_params.get("path", "")
|
|
190
|
+
if route == "api" or route.startswith("api/"):
|
|
191
|
+
raise HTTPException(404, "API route not found")
|
|
192
|
+
index = static / "index.html"
|
|
193
|
+
if not index.resolve().is_relative_to(static) or not index.is_file():
|
|
194
|
+
raise HTTPException(503, "The UI has not been built. Run cd ui && pnpm build.")
|
|
195
|
+
target = (static / route).resolve()
|
|
196
|
+
if not target.is_relative_to(static):
|
|
197
|
+
raise HTTPException(404, "file not found")
|
|
198
|
+
if target.is_file():
|
|
199
|
+
return BuiltFileResponse(target)
|
|
200
|
+
if Path(route).suffix:
|
|
201
|
+
raise HTTPException(404, "file not found")
|
|
202
|
+
return BuiltFileResponse(index)
|
|
203
|
+
|
|
204
|
+
@asynccontextmanager
|
|
205
|
+
async def lifespan(app: Starlette) -> AsyncGenerator[None]:
|
|
206
|
+
try:
|
|
207
|
+
yield
|
|
208
|
+
finally:
|
|
209
|
+
state.close()
|
|
210
|
+
|
|
211
|
+
return Starlette(
|
|
212
|
+
routes=[
|
|
213
|
+
Route("/api/sensors", sensors),
|
|
214
|
+
Route("/api/host", host),
|
|
215
|
+
Route("/api/history", read_history),
|
|
216
|
+
Route("/api/alerts", alerts),
|
|
217
|
+
Route("/api/alerts/{id}/ack", ack, methods=["POST"]),
|
|
218
|
+
Route("/api/alerts/{id}/mute", mute, methods=["POST"]),
|
|
219
|
+
Route("/api/stream", stream),
|
|
220
|
+
Route("/{path:path}", fallback),
|
|
221
|
+
],
|
|
222
|
+
middleware=[Middleware(ApiSecurity, state=state)],
|
|
223
|
+
exception_handlers={HTTPException: error, Exception: error},
|
|
224
|
+
lifespan=lifespan,
|
|
225
|
+
)
|
sensitivebox/api/data.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Bounded SQLite queries on the daemon thread, including pending raw/rollup data."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import sqlite3
|
|
5
|
+
from dataclasses import dataclass, replace
|
|
6
|
+
|
|
7
|
+
from sensitivebox.api.model import AlertsView, IncidentView
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True, slots=True)
|
|
11
|
+
class RawHistory:
|
|
12
|
+
t: tuple[float, ...]
|
|
13
|
+
avg: tuple[float | None, ...]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True, slots=True)
|
|
17
|
+
class MinuteHistory(RawHistory):
|
|
18
|
+
min: tuple[float | None, ...]
|
|
19
|
+
max: tuple[float | None, ...]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def history(
|
|
23
|
+
db: sqlite3.Connection, signal: str, period: str, now: float, interval: float
|
|
24
|
+
) -> RawHistory | MinuteHistory:
|
|
25
|
+
"""Caller flushes once before reading. Never combine rollups with raw samples."""
|
|
26
|
+
width = {"1h": 3600, "6h": 21600, "24h": 86400}[period]
|
|
27
|
+
if period != "1h":
|
|
28
|
+
start, end = math.floor((now - width) / 60) * 60, math.floor(now / 60) * 60
|
|
29
|
+
buckets: dict[int, tuple[float, float, float]] = {
|
|
30
|
+
int(t): (float(total) / n, float(lo), float(hi))
|
|
31
|
+
for t, n, total, lo, hi in db.execute(
|
|
32
|
+
"SELECT bucket,n,total,lo,hi FROM rollup_1m WHERE signal_id="
|
|
33
|
+
" (SELECT id FROM signals WHERE name=?) AND bucket BETWEEN ? AND ?",
|
|
34
|
+
(signal, start, end),
|
|
35
|
+
)
|
|
36
|
+
if n > 0
|
|
37
|
+
}
|
|
38
|
+
bucket_times = tuple(float(t) for t in range(start, end + 1, 60))
|
|
39
|
+
values = [buckets.get(int(t), (None, None, None)) for t in bucket_times]
|
|
40
|
+
return MinuteHistory(
|
|
41
|
+
bucket_times,
|
|
42
|
+
tuple(v[0] for v in values),
|
|
43
|
+
tuple(v[1] for v in values),
|
|
44
|
+
tuple(v[2] for v in values),
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
# Left-join poll frames: an absent value in a frame is missing too. Metric rows take
|
|
48
|
+
# precedence only when no signal value exists. UNIX wall timestamps, never engine mono.
|
|
49
|
+
rows: list[tuple[float, float | None]] = db.execute(
|
|
50
|
+
"SELECT tick.ts,coalesce(v.value,m.value) FROM inputs_raw tick"
|
|
51
|
+
" LEFT JOIN inputs_raw v ON v.frame=tick.frame AND v.kind='value'"
|
|
52
|
+
" AND v.signal_id=(SELECT id FROM signals WHERE name=?)"
|
|
53
|
+
" LEFT JOIN metrics_raw m ON m.ts=tick.ts"
|
|
54
|
+
" AND m.signal_id=(SELECT id FROM signals WHERE name=?)"
|
|
55
|
+
" WHERE tick.kind='tick' AND tick.ts BETWEEN ? AND ? ORDER BY tick.ts,tick.frame",
|
|
56
|
+
(signal, signal, now - width, now),
|
|
57
|
+
).fetchall()
|
|
58
|
+
times: list[float] = []
|
|
59
|
+
values_raw: list[float | None] = []
|
|
60
|
+
for at, value in rows:
|
|
61
|
+
if times:
|
|
62
|
+
gap = times[-1] + interval
|
|
63
|
+
while gap < at - interval / 2:
|
|
64
|
+
times.append(gap)
|
|
65
|
+
values_raw.append(None)
|
|
66
|
+
gap += interval
|
|
67
|
+
times.append(at)
|
|
68
|
+
values_raw.append(value)
|
|
69
|
+
return RawHistory(tuple(times), tuple(values_raw))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
_INCIDENT = (
|
|
73
|
+
"SELECT i.*,s.name,s.severity,s.peak,s.unit FROM alert_incidents i"
|
|
74
|
+
" LEFT JOIN incident_summaries s ON s.incident_id=i.id"
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def incidents(
|
|
79
|
+
db: sqlite3.Connection, now: float, limit: int, *, boot: str, monotonic_now: float
|
|
80
|
+
) -> AlertsView:
|
|
81
|
+
rows = db.execute(
|
|
82
|
+
_INCIDENT + " WHERE i.closed IS NULL OR i.closed>=?"
|
|
83
|
+
" ORDER BY i.opened DESC,i.id DESC LIMIT ?",
|
|
84
|
+
(now - 86400, limit + 1),
|
|
85
|
+
).fetchall()
|
|
86
|
+
muted_rules = _active_mutes(db, boot, monotonic_now)
|
|
87
|
+
shown: list[IncidentView] = []
|
|
88
|
+
for row in rows[:limit]:
|
|
89
|
+
incident = IncidentView(*row)
|
|
90
|
+
if incident.closed is None and incident.rule_id in muted_rules:
|
|
91
|
+
incident = replace(incident, muted=True)
|
|
92
|
+
shown.append(incident)
|
|
93
|
+
return AlertsView(tuple(shown), len(rows) > limit)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _active_mutes(db: sqlite3.Connection, boot: str, now: float) -> set[str]:
|
|
97
|
+
return {
|
|
98
|
+
str(rule)
|
|
99
|
+
for (rule,) in db.execute(
|
|
100
|
+
"SELECT rule_id FROM mutes WHERE boot=? AND released=0"
|
|
101
|
+
" AND (expiry IS NULL OR expiry>?)",
|
|
102
|
+
(boot, now),
|
|
103
|
+
)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def incident(db: sqlite3.Connection, identity: str) -> IncidentView | None:
|
|
108
|
+
row = db.execute(_INCIDENT + " WHERE i.id=?", (identity,)).fetchone()
|
|
109
|
+
return None if row is None else IncidentView(*row)
|
sensitivebox/api/host.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Host facts from selected files only; absent fixture inputs stay null."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from sensitivebox import __version__
|
|
6
|
+
from sensitivebox.api.model import HostView
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _read(path: Path) -> str | None:
|
|
10
|
+
try:
|
|
11
|
+
return path.read_text(encoding="utf-8").strip() or None
|
|
12
|
+
except (OSError, UnicodeError):
|
|
13
|
+
return None
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def host_view(proc_root: Path, os_release: Path) -> HostView:
|
|
17
|
+
release = None
|
|
18
|
+
for line in (_read(os_release) or "").splitlines():
|
|
19
|
+
key, sep, value = line.partition("=")
|
|
20
|
+
if sep and key == "PRETTY_NAME":
|
|
21
|
+
release = value.strip().strip('"').strip("'") or None
|
|
22
|
+
return HostView(
|
|
23
|
+
_read(proc_root / "sys/kernel/hostname"),
|
|
24
|
+
release,
|
|
25
|
+
_read(proc_root / "sys/kernel/osrelease"),
|
|
26
|
+
__version__,
|
|
27
|
+
)
|