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,90 @@
|
|
|
1
|
+
"""Route-specific, typed wire models. No CLI envelope and no raw hardware paths."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
import msgspec
|
|
6
|
+
|
|
7
|
+
from sensitivebox.alerts.model import Severity, State, When
|
|
8
|
+
from sensitivebox.hwmon.model import Limits
|
|
9
|
+
from sensitivebox.sources.wifi import WifiStatus
|
|
10
|
+
from sensitivebox.store.events import Incident
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True, slots=True)
|
|
14
|
+
class EvaluationView:
|
|
15
|
+
rule_id: str
|
|
16
|
+
state: State
|
|
17
|
+
when: When
|
|
18
|
+
value: float | None
|
|
19
|
+
clear: float | None
|
|
20
|
+
severity: Severity
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True, slots=True)
|
|
24
|
+
class SignalView:
|
|
25
|
+
id: str
|
|
26
|
+
label: str
|
|
27
|
+
unit: str
|
|
28
|
+
limits: Limits
|
|
29
|
+
value: float | str | None
|
|
30
|
+
missing: str | None
|
|
31
|
+
evaluations: tuple[EvaluationView, ...]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True, slots=True)
|
|
35
|
+
class AppView:
|
|
36
|
+
name: str
|
|
37
|
+
bytes: int
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True, slots=True)
|
|
41
|
+
class BluetoothView:
|
|
42
|
+
powered: bool | None
|
|
43
|
+
devices: tuple[str, ...]
|
|
44
|
+
missing: str | None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True, slots=True)
|
|
48
|
+
class SensorsView:
|
|
49
|
+
timestamp: float
|
|
50
|
+
fresh: bool
|
|
51
|
+
groups: dict[str, tuple[SignalView, ...]]
|
|
52
|
+
apps: tuple[AppView, ...]
|
|
53
|
+
bluetooth: BluetoothView
|
|
54
|
+
wifi: WifiStatus
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(frozen=True, slots=True)
|
|
58
|
+
class HostView:
|
|
59
|
+
hostname: str | None
|
|
60
|
+
ubuntu_release: str | None
|
|
61
|
+
kernel: str | None
|
|
62
|
+
version: str
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True, slots=True)
|
|
66
|
+
class IncidentView(Incident):
|
|
67
|
+
name: str | None
|
|
68
|
+
severity: str | None
|
|
69
|
+
peak: float | None
|
|
70
|
+
unit: str | None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True, slots=True)
|
|
74
|
+
class AlertsView:
|
|
75
|
+
incidents: tuple[IncidentView, ...]
|
|
76
|
+
truncated: bool
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass(frozen=True, slots=True)
|
|
80
|
+
class ErrorView:
|
|
81
|
+
error: str
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class AckBody(msgspec.Struct, forbid_unknown_fields=True):
|
|
85
|
+
pass
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class MuteBody(msgspec.Struct, forbid_unknown_fields=True):
|
|
89
|
+
duration: str
|
|
90
|
+
renotify: bool = True
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Loopback Host, same-origin Origin, and daemon-session CSRF for API mutations."""
|
|
2
|
+
|
|
3
|
+
import ipaddress
|
|
4
|
+
import secrets
|
|
5
|
+
from urllib.parse import urlsplit
|
|
6
|
+
|
|
7
|
+
from starlette.datastructures import MutableHeaders
|
|
8
|
+
from starlette.requests import Request
|
|
9
|
+
from starlette.responses import Response
|
|
10
|
+
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
|
11
|
+
|
|
12
|
+
from sensitivebox.api.model import ErrorView
|
|
13
|
+
from sensitivebox.api.state import ApiState
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def loopback(host: str) -> bool:
|
|
17
|
+
try:
|
|
18
|
+
parsed = urlsplit("//" + host)
|
|
19
|
+
if parsed.username is not None or parsed.password is not None or parsed.path:
|
|
20
|
+
return False
|
|
21
|
+
if parsed.query or parsed.fragment or not parsed.hostname:
|
|
22
|
+
return False
|
|
23
|
+
_ = parsed.port # reject malformed ports
|
|
24
|
+
return parsed.hostname == "localhost" or ipaddress.ip_address(parsed.hostname).is_loopback
|
|
25
|
+
except ValueError:
|
|
26
|
+
return False
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ApiSecurity:
|
|
30
|
+
def __init__(self, app: ASGIApp, *, state: ApiState) -> None:
|
|
31
|
+
self.app, self.state = app, state
|
|
32
|
+
self.token = secrets.token_urlsafe(32)
|
|
33
|
+
|
|
34
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
35
|
+
if scope["type"] != "http":
|
|
36
|
+
await self.app(scope, receive, send)
|
|
37
|
+
return
|
|
38
|
+
request = Request(scope)
|
|
39
|
+
started = False
|
|
40
|
+
api = scope["path"] == "/api" or scope["path"].startswith("/api/")
|
|
41
|
+
if api and request.method == "POST" and not self.allowed(request):
|
|
42
|
+
response = Response(
|
|
43
|
+
self.state.encode(ErrorView("loopback origin and CSRF required")),
|
|
44
|
+
status_code=403,
|
|
45
|
+
media_type="application/json",
|
|
46
|
+
headers={"Cache-Control": "no-store"},
|
|
47
|
+
)
|
|
48
|
+
await response(scope, receive, send)
|
|
49
|
+
return
|
|
50
|
+
|
|
51
|
+
async def guarded(message: Message) -> None:
|
|
52
|
+
nonlocal started
|
|
53
|
+
if message["type"] == "http.response.start":
|
|
54
|
+
started = True
|
|
55
|
+
if api and message["type"] == "http.response.start":
|
|
56
|
+
headers = MutableHeaders(scope=message)
|
|
57
|
+
headers["cache-control"] = "no-store"
|
|
58
|
+
headers["x-content-type-options"] = "nosniff"
|
|
59
|
+
if request.method == "GET":
|
|
60
|
+
cookie = Response()
|
|
61
|
+
cookie.set_cookie("sbox_csrf", self.token, samesite="strict", path="/")
|
|
62
|
+
headers.append("set-cookie", cookie.headers["set-cookie"])
|
|
63
|
+
await send(message)
|
|
64
|
+
|
|
65
|
+
try:
|
|
66
|
+
await self.app(scope, receive, guarded)
|
|
67
|
+
except Exception:
|
|
68
|
+
if started:
|
|
69
|
+
raise
|
|
70
|
+
response = Response(
|
|
71
|
+
self.state.encode(ErrorView("API unavailable; monitoring continues")),
|
|
72
|
+
status_code=500,
|
|
73
|
+
media_type="application/json",
|
|
74
|
+
)
|
|
75
|
+
await response(scope, receive, guarded)
|
|
76
|
+
|
|
77
|
+
def allowed(self, request: Request) -> bool:
|
|
78
|
+
headers = request.headers
|
|
79
|
+
if any(len(headers.getlist(name)) != 1 for name in ("host", "origin", "x-csrf-token")):
|
|
80
|
+
return False
|
|
81
|
+
host = headers["host"]
|
|
82
|
+
return (
|
|
83
|
+
loopback(host)
|
|
84
|
+
and headers["origin"] == f"{request.scope['scheme']}://{host}"
|
|
85
|
+
and secrets.compare_digest(
|
|
86
|
+
request.cookies.get("sbox_csrf", "").encode(), self.token.encode()
|
|
87
|
+
)
|
|
88
|
+
and secrets.compare_digest(headers["x-csrf-token"].encode(), self.token.encode())
|
|
89
|
+
)
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Embedded uvicorn listener: pre-bind IPv4 loopback, leave daemon signal handling alone."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import errno
|
|
5
|
+
import logging
|
|
6
|
+
import socket
|
|
7
|
+
from collections.abc import AsyncGenerator, Callable, Generator
|
|
8
|
+
from contextlib import asynccontextmanager, contextmanager
|
|
9
|
+
from typing import Protocol
|
|
10
|
+
|
|
11
|
+
import uvicorn
|
|
12
|
+
from starlette.types import ASGIApp
|
|
13
|
+
|
|
14
|
+
from sensitivebox.redact import redact
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Server(Protocol):
|
|
18
|
+
should_exit: bool
|
|
19
|
+
|
|
20
|
+
async def serve(self, sockets: list[socket.socket] | None = None) -> None: ...
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class EmbeddedServer(uvicorn.Server):
|
|
24
|
+
@contextmanager
|
|
25
|
+
def capture_signals(self) -> Generator[None]:
|
|
26
|
+
"""The CLI owns SIGINT/SIGTERM; never replace or re-raise those handlers."""
|
|
27
|
+
yield
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class RedactedLog(logging.Handler):
|
|
31
|
+
def __init__(self, out: Callable[[str], None]) -> None:
|
|
32
|
+
super().__init__()
|
|
33
|
+
self.out = out
|
|
34
|
+
|
|
35
|
+
def emit(self, record: logging.LogRecord) -> None:
|
|
36
|
+
self.out(redact(self.format(record)))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@asynccontextmanager
|
|
40
|
+
async def serve_api(
|
|
41
|
+
app: ASGIApp,
|
|
42
|
+
out: Callable[[str], None],
|
|
43
|
+
*,
|
|
44
|
+
socket_factory: Callable[[], socket.socket] = socket.socket,
|
|
45
|
+
server_factory: Callable[[uvicorn.Config], Server] = EmbeddedServer,
|
|
46
|
+
) -> AsyncGenerator[None]:
|
|
47
|
+
listener = socket_factory()
|
|
48
|
+
try:
|
|
49
|
+
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
50
|
+
listener.bind(("127.0.0.1", 7878))
|
|
51
|
+
listener.listen(128)
|
|
52
|
+
listener.setblocking(False)
|
|
53
|
+
except OSError as exc:
|
|
54
|
+
listener.close()
|
|
55
|
+
if exc.errno != errno.EADDRINUSE:
|
|
56
|
+
raise
|
|
57
|
+
out(redact("API unavailable: 127.0.0.1:7878 is already in use; monitoring continues"))
|
|
58
|
+
yield
|
|
59
|
+
return
|
|
60
|
+
|
|
61
|
+
logger = logging.getLogger("uvicorn.error")
|
|
62
|
+
previous, propagate = logger.handlers[:], logger.propagate
|
|
63
|
+
handler = RedactedLog(out)
|
|
64
|
+
logger.handlers, logger.propagate = [handler], False
|
|
65
|
+
task: asyncio.Task[None] | None = None
|
|
66
|
+
try:
|
|
67
|
+
config = uvicorn.Config(
|
|
68
|
+
app,
|
|
69
|
+
host="127.0.0.1",
|
|
70
|
+
port=7878,
|
|
71
|
+
loop="asyncio",
|
|
72
|
+
http="h11",
|
|
73
|
+
ws="none",
|
|
74
|
+
lifespan="on",
|
|
75
|
+
log_config=None,
|
|
76
|
+
access_log=False,
|
|
77
|
+
proxy_headers=False,
|
|
78
|
+
server_header=False,
|
|
79
|
+
timeout_graceful_shutdown=1,
|
|
80
|
+
)
|
|
81
|
+
server = server_factory(config)
|
|
82
|
+
task = asyncio.create_task(server.serve(sockets=[listener]), name="sbox-api")
|
|
83
|
+
|
|
84
|
+
def finished(done: asyncio.Task[None]) -> None:
|
|
85
|
+
if not done.cancelled() and done.exception() is not None:
|
|
86
|
+
out(redact("API unavailable: server stopped; monitoring continues"))
|
|
87
|
+
|
|
88
|
+
task.add_done_callback(finished)
|
|
89
|
+
try:
|
|
90
|
+
yield
|
|
91
|
+
finally:
|
|
92
|
+
server.should_exit = True
|
|
93
|
+
# A stuck client must never keep monitoring's shutdown alive indefinitely.
|
|
94
|
+
try:
|
|
95
|
+
async with asyncio.timeout(2):
|
|
96
|
+
await asyncio.shield(task)
|
|
97
|
+
except TimeoutError:
|
|
98
|
+
task.cancel()
|
|
99
|
+
await asyncio.gather(task, return_exceptions=True)
|
|
100
|
+
except Exception: # noqa: S110 - already reported through the redacted callback
|
|
101
|
+
pass # already reported through the redacted callback
|
|
102
|
+
finally:
|
|
103
|
+
if task is not None and not task.done():
|
|
104
|
+
task.cancel()
|
|
105
|
+
await asyncio.gather(task, return_exceptions=True)
|
|
106
|
+
listener.close()
|
|
107
|
+
logger.handlers, logger.propagate = previous, propagate
|
|
108
|
+
handler.close()
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""Latest poll and bounded live subscriptions, owned by the daemon's asyncio loop."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from collections.abc import AsyncGenerator, Callable
|
|
5
|
+
from dataclasses import dataclass, field, replace
|
|
6
|
+
|
|
7
|
+
from sensitivebox.alerts.engine import Clock, Engine
|
|
8
|
+
from sensitivebox.alerts.model import Missing
|
|
9
|
+
from sensitivebox.api.data import incident
|
|
10
|
+
from sensitivebox.api.model import (
|
|
11
|
+
AppView,
|
|
12
|
+
BluetoothView,
|
|
13
|
+
EvaluationView,
|
|
14
|
+
IncidentView,
|
|
15
|
+
SensorsView,
|
|
16
|
+
SignalView,
|
|
17
|
+
)
|
|
18
|
+
from sensitivebox.collector import Collector
|
|
19
|
+
from sensitivebox.daemon import TickResult
|
|
20
|
+
from sensitivebox.hwmon.model import Group, Limits
|
|
21
|
+
from sensitivebox.redact import device_label, redacted_json
|
|
22
|
+
from sensitivebox.sources.bluez import BluetoothStatus
|
|
23
|
+
from sensitivebox.sources.wifi import WifiStatus
|
|
24
|
+
from sensitivebox.store import Store
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True, slots=True)
|
|
28
|
+
class AlertUpdate:
|
|
29
|
+
incident: IncidentView
|
|
30
|
+
kind: str
|
|
31
|
+
reason: str | None = None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(eq=False, slots=True)
|
|
35
|
+
class Subscription:
|
|
36
|
+
queue: asyncio.Queue[str | None]
|
|
37
|
+
closed: asyncio.Event = field(default_factory=asyncio.Event)
|
|
38
|
+
|
|
39
|
+
def close(self) -> None:
|
|
40
|
+
self.closed.set()
|
|
41
|
+
while not self.queue.empty():
|
|
42
|
+
self.queue.get_nowait()
|
|
43
|
+
self.queue.put_nowait(None)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class ApiState:
|
|
47
|
+
queue_size = 64
|
|
48
|
+
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
store: Store,
|
|
52
|
+
collector: Collector,
|
|
53
|
+
*,
|
|
54
|
+
engine: Engine,
|
|
55
|
+
clock: Clock,
|
|
56
|
+
wall: Clock,
|
|
57
|
+
boot: str,
|
|
58
|
+
interval: float,
|
|
59
|
+
bluetooth: Callable[[], BluetoothStatus] = lambda: BluetoothStatus(reason="not available"),
|
|
60
|
+
wifi: Callable[[], WifiStatus] = lambda: WifiStatus.unavailable("not available"),
|
|
61
|
+
) -> None:
|
|
62
|
+
self.store, self.collector = store, collector
|
|
63
|
+
self.engine = engine
|
|
64
|
+
self.clock, self.wall, self.boot, self.interval = clock, wall, boot, interval
|
|
65
|
+
self._bluetooth, self._wifi = bluetooth, wifi
|
|
66
|
+
self._snapshot: SensorsView | None = None
|
|
67
|
+
self._at: float | None = None
|
|
68
|
+
self._serial = 0
|
|
69
|
+
self._subscriptions: set[Subscription] = set()
|
|
70
|
+
self._private: set[str] = set()
|
|
71
|
+
self._stable = {s.id for s in collector.sensors}
|
|
72
|
+
self._event_cursor = int(
|
|
73
|
+
store.mutes.db.execute("SELECT coalesce(max(id),0) FROM alert_events").fetchone()[0]
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def subscriber_count(self) -> int:
|
|
78
|
+
return len(self._subscriptions)
|
|
79
|
+
|
|
80
|
+
def encode(self, value: object) -> str:
|
|
81
|
+
return redacted_json(
|
|
82
|
+
value,
|
|
83
|
+
private=tuple(sorted(self._private, key=len, reverse=True)),
|
|
84
|
+
stable_ids=frozenset(self._stable),
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
def snapshot(self) -> SensorsView | None:
|
|
88
|
+
if self._snapshot is None or self._at is None:
|
|
89
|
+
return None
|
|
90
|
+
return replace(self._snapshot, fresh=0 <= self.clock() - self._at <= 3 * self.interval)
|
|
91
|
+
|
|
92
|
+
def tick(self, result: TickResult) -> None:
|
|
93
|
+
snap = result.snapshot
|
|
94
|
+
self._at = snap.at
|
|
95
|
+
sensors = {sensor.id: sensor for sensor in self.collector.sensors}
|
|
96
|
+
self._stable.update(snap.signals)
|
|
97
|
+
self._stable.update(snap.metrics)
|
|
98
|
+
self._stable.update(snap.display)
|
|
99
|
+
self._private.update(app.name for app in snap.apps)
|
|
100
|
+
bluetooth = self._bluetooth()
|
|
101
|
+
self._private.update(d.alias for d in bluetooth.devices)
|
|
102
|
+
self._private.update(a.alias for a in bluetooth.adapters)
|
|
103
|
+
groups: dict[str, list[SignalView]] = {group.value: [] for group in Group}
|
|
104
|
+
values = dict(snap.display)
|
|
105
|
+
values.update(snap.metrics)
|
|
106
|
+
values.update(snap.signals)
|
|
107
|
+
rules = {rule.id: rule for rule in self.engine.rules}
|
|
108
|
+
evaluations: dict[str, list[EvaluationView]] = {}
|
|
109
|
+
for evaluation in result.step.evaluations:
|
|
110
|
+
rule = rules[evaluation.rule_id]
|
|
111
|
+
threshold = evaluation.threshold
|
|
112
|
+
if rule.when == "equals":
|
|
113
|
+
threshold = float(rule.value) if isinstance(rule.value, (int, float)) else None
|
|
114
|
+
evaluations.setdefault(evaluation.signal, []).append(
|
|
115
|
+
EvaluationView(
|
|
116
|
+
rule.id,
|
|
117
|
+
evaluation.state,
|
|
118
|
+
rule.when,
|
|
119
|
+
threshold,
|
|
120
|
+
self.engine.resolved_clear(rule.id, evaluation.signal),
|
|
121
|
+
rule.severity,
|
|
122
|
+
)
|
|
123
|
+
)
|
|
124
|
+
for identity, value in sorted(values.items()):
|
|
125
|
+
sensor = sensors.get(identity)
|
|
126
|
+
group = sensor.group.value if sensor is not None else _group(identity)
|
|
127
|
+
groups[group].append(
|
|
128
|
+
SignalView(
|
|
129
|
+
identity,
|
|
130
|
+
sensor.label if sensor is not None else _label(identity),
|
|
131
|
+
sensor.unit if sensor is not None else snap.units.get(identity, ""),
|
|
132
|
+
sensor.limits
|
|
133
|
+
if sensor is not None
|
|
134
|
+
else self.collector.limits.get(identity, Limits()),
|
|
135
|
+
None if isinstance(value, Missing) else value,
|
|
136
|
+
value.reason if isinstance(value, Missing) else None,
|
|
137
|
+
tuple(evaluations.get(identity, ())),
|
|
138
|
+
)
|
|
139
|
+
)
|
|
140
|
+
self._snapshot = SensorsView(
|
|
141
|
+
self.wall(),
|
|
142
|
+
True,
|
|
143
|
+
{g: tuple(v) for g, v in groups.items()},
|
|
144
|
+
tuple(AppView("<redacted>", app.bytes) for app in snap.apps),
|
|
145
|
+
BluetoothView(
|
|
146
|
+
bluetooth.powered if bluetooth.available else None,
|
|
147
|
+
tuple(device_label(d) for d in bluetooth.devices),
|
|
148
|
+
bluetooth.reason,
|
|
149
|
+
),
|
|
150
|
+
self._wifi(),
|
|
151
|
+
)
|
|
152
|
+
self._publish("snapshot", self._snapshot)
|
|
153
|
+
for event in reversed(self.store.events.history(after=self._event_cursor, limit=10000)):
|
|
154
|
+
self._event_cursor = event.id
|
|
155
|
+
current = incident(self.store.mutes.db, event.incident_id)
|
|
156
|
+
if current is not None:
|
|
157
|
+
self._publish("alert", AlertUpdate(current, event.kind, event.reason))
|
|
158
|
+
|
|
159
|
+
def changed(self, current: IncidentView, kind: str) -> None:
|
|
160
|
+
self._publish("alert", AlertUpdate(current, kind))
|
|
161
|
+
|
|
162
|
+
def _event(self, name: str, payload: object) -> str:
|
|
163
|
+
self._serial += 1
|
|
164
|
+
return f"id: {self._serial}\nevent: {name}\ndata: {self.encode(payload)}\n\n"
|
|
165
|
+
|
|
166
|
+
def _publish(self, name: str, payload: object) -> None:
|
|
167
|
+
event = self._event(name, payload)
|
|
168
|
+
for sub in tuple(self._subscriptions):
|
|
169
|
+
try:
|
|
170
|
+
sub.queue.put_nowait(event)
|
|
171
|
+
except asyncio.QueueFull:
|
|
172
|
+
sub.close()
|
|
173
|
+
self._subscriptions.discard(sub)
|
|
174
|
+
|
|
175
|
+
def subscribe(self) -> Subscription:
|
|
176
|
+
sub = Subscription(asyncio.Queue(self.queue_size))
|
|
177
|
+
self._subscriptions.add(sub)
|
|
178
|
+
current = self.snapshot()
|
|
179
|
+
if current is not None:
|
|
180
|
+
sub.queue.put_nowait(self._event("snapshot", current))
|
|
181
|
+
return sub
|
|
182
|
+
|
|
183
|
+
async def stream(self, sub: Subscription | None = None) -> AsyncGenerator[str]:
|
|
184
|
+
sub = sub or self.subscribe()
|
|
185
|
+
try:
|
|
186
|
+
while not sub.closed.is_set():
|
|
187
|
+
event = await sub.queue.get()
|
|
188
|
+
if event is None or sub.closed.is_set():
|
|
189
|
+
break
|
|
190
|
+
yield event
|
|
191
|
+
finally:
|
|
192
|
+
self.unsubscribe(sub)
|
|
193
|
+
|
|
194
|
+
def unsubscribe(self, sub: Subscription) -> None:
|
|
195
|
+
self._subscriptions.discard(sub)
|
|
196
|
+
sub.close()
|
|
197
|
+
|
|
198
|
+
def close(self) -> None:
|
|
199
|
+
for sub in tuple(self._subscriptions):
|
|
200
|
+
self.unsubscribe(sub)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _group(identity: str) -> str:
|
|
204
|
+
if identity.startswith(("cpu/", "psi/cpu/")):
|
|
205
|
+
return "CPU"
|
|
206
|
+
if identity.startswith(("memory/", "zram/", "vmstat/", "psi/memory/")):
|
|
207
|
+
return "Memory"
|
|
208
|
+
if identity.startswith("gpu/"):
|
|
209
|
+
return "GPU"
|
|
210
|
+
if identity.startswith("psi/io/"):
|
|
211
|
+
return "Storage"
|
|
212
|
+
if identity.startswith(("net/", "wifi/")):
|
|
213
|
+
return "Network"
|
|
214
|
+
if identity.startswith("power_supply/"):
|
|
215
|
+
return "Power"
|
|
216
|
+
return "System"
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _label(identity: str) -> str:
|
|
220
|
+
return identity.replace("_", " ").replace("/", " · ")
|
|
Binary file
|
|
Binary file
|