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,87 @@
|
|
|
1
|
+
"""Input events: everything the alert engine sees, in the order it sees it.
|
|
2
|
+
|
|
3
|
+
What's recorded is what gets replayed (docs/BIBLE.md, "Alerting"; review ADV-005). The engine
|
|
4
|
+
reports each of these to its ``journal`` as it happens, the store keeps them in the 1 h raw ring,
|
|
5
|
+
and :func:`sensitivebox.alerts.replay.replay` feeds them back through a fresh engine, so a replay
|
|
6
|
+
gives exactly what the live daemon did. ``at`` is the engine's (monotonic) clock.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from collections.abc import Callable, Mapping
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
from sensitivebox.alerts.model import Rule, Value
|
|
13
|
+
from sensitivebox.hwmon import Limits
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True, slots=True)
|
|
17
|
+
class Tick:
|
|
18
|
+
"""One poll: every signal's value or MISSING, guard signals included."""
|
|
19
|
+
|
|
20
|
+
at: float
|
|
21
|
+
signals: Mapping[str, Value]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True, slots=True)
|
|
25
|
+
class Suspend:
|
|
26
|
+
at: float
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True, slots=True)
|
|
30
|
+
class Resume:
|
|
31
|
+
at: float
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True, slots=True)
|
|
35
|
+
class LimitsChanged:
|
|
36
|
+
"""The chip limits relative thresholds resolve against (at start, and after rediscovery)."""
|
|
37
|
+
|
|
38
|
+
at: float
|
|
39
|
+
limits: Mapping[str, Limits]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True, slots=True)
|
|
43
|
+
class RulesLoaded:
|
|
44
|
+
"""The rule set in force (at start, and whenever rules are loaded or edited)."""
|
|
45
|
+
|
|
46
|
+
at: float
|
|
47
|
+
rules: tuple[Rule, ...]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True, slots=True)
|
|
51
|
+
class EngineSettings:
|
|
52
|
+
"""How the engine treats time: a gap between real readings longer than ``max_gap`` seconds
|
|
53
|
+
is MISSING for that span (``None``: no limit)."""
|
|
54
|
+
|
|
55
|
+
at: float
|
|
56
|
+
max_gap: float | None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(frozen=True, slots=True)
|
|
60
|
+
class Restart:
|
|
61
|
+
at: float
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True, slots=True)
|
|
65
|
+
class OpenAlerts:
|
|
66
|
+
at: float
|
|
67
|
+
payload: str
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass(frozen=True, slots=True)
|
|
71
|
+
class Checkpoint:
|
|
72
|
+
at: float
|
|
73
|
+
payload: str
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
type InputEvent = (
|
|
77
|
+
OpenAlerts
|
|
78
|
+
| Restart
|
|
79
|
+
| Checkpoint
|
|
80
|
+
| Tick
|
|
81
|
+
| Suspend
|
|
82
|
+
| Resume
|
|
83
|
+
| LimitsChanged
|
|
84
|
+
| RulesLoaded
|
|
85
|
+
| EngineSettings
|
|
86
|
+
)
|
|
87
|
+
type Journal = Callable[[InputEvent], None]
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Signal globs: ``fnmatch`` syntax plus named wildcards.
|
|
2
|
+
|
|
3
|
+
``*``, ``?`` and ``[...]`` mean what they mean to :func:`fnmatch.fnmatchcase` (``*`` may cross a
|
|
4
|
+
``/``). A named wildcard such as ``{battery}`` matches exactly one path segment and *binds* it, so a
|
|
5
|
+
rule's guard can name the same device as its sensor (docs/BIBLE.md, "Alerting"; review ADV-002)::
|
|
6
|
+
|
|
7
|
+
sensor = "power_supply/{battery}/capacity"
|
|
8
|
+
only_if = { signal = "power_supply/{battery}/status", equals = "Discharging" }
|
|
9
|
+
|
|
10
|
+
The translation to a regular expression is written out here rather than taken from
|
|
11
|
+
``fnmatch.translate``, whose output format changes between Python versions.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import re
|
|
15
|
+
from functools import cache
|
|
16
|
+
|
|
17
|
+
_NAME_RE = re.compile(r"\{([A-Za-z_][A-Za-z0-9_]*)\}")
|
|
18
|
+
_GLOB_META_RE = re.compile(r"([*?\[])")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def names(glob: str) -> frozenset[str]:
|
|
22
|
+
"""The named wildcards in ``glob``."""
|
|
23
|
+
return frozenset(_NAME_RE.findall(glob))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _bracket(glob: str, start: int) -> tuple[str, int] | None:
|
|
27
|
+
"""The regex for a ``[...]`` set starting at ``start``, and the index after it."""
|
|
28
|
+
end = start + 1
|
|
29
|
+
if end < len(glob) and glob[end] == "!":
|
|
30
|
+
end += 1
|
|
31
|
+
if end < len(glob) and glob[end] == "]":
|
|
32
|
+
end += 1
|
|
33
|
+
end = glob.find("]", end)
|
|
34
|
+
if end < 0:
|
|
35
|
+
return None
|
|
36
|
+
body = glob[start + 1 : end].replace("\\", "\\\\")
|
|
37
|
+
if body.startswith("!"):
|
|
38
|
+
body = "^" + body[1:]
|
|
39
|
+
elif body.startswith(("^", "[")):
|
|
40
|
+
body = "\\" + body
|
|
41
|
+
return f"[{body}]", end + 1
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@cache
|
|
45
|
+
def compile_glob(glob: str) -> re.Pattern[str]:
|
|
46
|
+
parts: list[str] = []
|
|
47
|
+
seen: set[str] = set()
|
|
48
|
+
i = 0
|
|
49
|
+
while i < len(glob):
|
|
50
|
+
char = glob[i]
|
|
51
|
+
if char == "{" and (m := _NAME_RE.match(glob, i)):
|
|
52
|
+
name = m[1]
|
|
53
|
+
parts.append(f"(?P={name})" if name in seen else f"(?P<{name}>[^/]+)")
|
|
54
|
+
seen.add(name)
|
|
55
|
+
i = m.end()
|
|
56
|
+
elif char == "*":
|
|
57
|
+
parts.append(".*")
|
|
58
|
+
i += 1
|
|
59
|
+
elif char == "?":
|
|
60
|
+
parts.append(".")
|
|
61
|
+
i += 1
|
|
62
|
+
elif char == "[" and (bracket := _bracket(glob, i)):
|
|
63
|
+
parts.append(bracket[0])
|
|
64
|
+
i = bracket[1]
|
|
65
|
+
else:
|
|
66
|
+
parts.append(re.escape(char))
|
|
67
|
+
i += 1
|
|
68
|
+
return re.compile("(?s:" + "".join(parts) + r")\Z")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def match(glob: str, signal: str) -> dict[str, str] | None:
|
|
72
|
+
"""The bindings of ``glob``'s named wildcards if ``signal`` matches it, else ``None``."""
|
|
73
|
+
m = compile_glob(glob).match(signal)
|
|
74
|
+
return None if m is None else m.groupdict()
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def fill(glob: str, bindings: dict[str, str]) -> str:
|
|
78
|
+
"""``glob`` with its named wildcards replaced by their bound (literal) segments."""
|
|
79
|
+
|
|
80
|
+
def literal(m: re.Match[str]) -> str:
|
|
81
|
+
value = bindings.get(m[1])
|
|
82
|
+
return m[0] if value is None else _GLOB_META_RE.sub(r"[\1]", value)
|
|
83
|
+
|
|
84
|
+
return _NAME_RE.sub(literal, glob)
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"""Rule model: what ``rules.toml`` may say, validated with msgspec.
|
|
2
|
+
|
|
3
|
+
A rule's schema is deliberately small (see docs/BIBLE.md, "Alerting"). Only ``id``, ``sensor``,
|
|
4
|
+
``when``, ``value`` and ``severity`` are required; everything else has a default.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import math
|
|
8
|
+
import re
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from enum import StrEnum
|
|
11
|
+
from typing import Literal
|
|
12
|
+
|
|
13
|
+
import msgspec
|
|
14
|
+
|
|
15
|
+
from sensitivebox.alerts import globs
|
|
16
|
+
from sensitivebox.hwmon import Limits
|
|
17
|
+
|
|
18
|
+
type Severity = Literal["info", "warning", "critical"]
|
|
19
|
+
type When = Literal["above", "below", "equals"]
|
|
20
|
+
type Mode = Literal["sustained", "any"]
|
|
21
|
+
type OnMissing = Literal["ignore", "alert", "close"]
|
|
22
|
+
|
|
23
|
+
_DURATION_RE = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|min|h)?\s*$")
|
|
24
|
+
_UNIT_SECONDS = {"ms": 0.001, "s": 1.0, None: 1.0, "m": 60.0, "min": 60.0, "h": 3600.0}
|
|
25
|
+
_RELATIVE_RE = re.compile(r"^\s*(min|max|crit)\s*(?:([+-])\s*(\d+(?:\.\d+)?))?\s*$")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True, slots=True)
|
|
29
|
+
class Missing:
|
|
30
|
+
"""No reading this poll, and why (``ENODATA``, ``signal gone``, …). Never a number."""
|
|
31
|
+
|
|
32
|
+
reason: str
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
type Value = float | str | Missing
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class State(StrEnum):
|
|
39
|
+
WARMING = "warming"
|
|
40
|
+
OK = "ok"
|
|
41
|
+
PENDING = "pending"
|
|
42
|
+
FIRING = "firing"
|
|
43
|
+
RESOLVED = "resolved"
|
|
44
|
+
UNKNOWN = "unknown"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def parse_duration(text: str) -> float:
|
|
48
|
+
"""``"10s"``, ``"5m"``, ``"1h"``, ``"500ms"`` or a bare number of seconds."""
|
|
49
|
+
m = _DURATION_RE.match(text)
|
|
50
|
+
if not m:
|
|
51
|
+
raise ValueError(f"not a duration: {text!r} (use e.g. 10s, 5m, 1h)")
|
|
52
|
+
seconds = float(m[1]) * _UNIT_SECONDS[m[2]]
|
|
53
|
+
if not math.isfinite(seconds):
|
|
54
|
+
raise ValueError(f"duration too long: {text[:20]!r}…")
|
|
55
|
+
return seconds
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _finite(number: float, what: str) -> float:
|
|
59
|
+
if not math.isfinite(number):
|
|
60
|
+
raise ValueError(f"{what} must be a finite number, not {number}")
|
|
61
|
+
return number
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True, slots=True)
|
|
65
|
+
class Threshold:
|
|
66
|
+
"""A fixed number, or a chip limit plus an offset (``crit-5``)."""
|
|
67
|
+
|
|
68
|
+
fixed: float | None = None
|
|
69
|
+
limit: Literal["min", "max", "crit"] | None = None
|
|
70
|
+
offset: float = 0.0
|
|
71
|
+
|
|
72
|
+
@classmethod
|
|
73
|
+
def parse(cls, value: float | str) -> "Threshold":
|
|
74
|
+
if not isinstance(value, str):
|
|
75
|
+
return cls(fixed=_finite(float(value), "a threshold"))
|
|
76
|
+
m = _RELATIVE_RE.match(value)
|
|
77
|
+
if not m:
|
|
78
|
+
raise ValueError(f"not a threshold: {value!r} (use a number, or e.g. crit-5, max-5)")
|
|
79
|
+
sign = -1.0 if m[2] == "-" else 1.0
|
|
80
|
+
limit: Literal["min", "max", "crit"] = m[1] # pyright: ignore[reportAssignmentType]
|
|
81
|
+
return cls(limit=limit, offset=sign * _finite(float(m[3] or 0), "an offset"))
|
|
82
|
+
|
|
83
|
+
def resolve(self, limits: Limits | None) -> float | None:
|
|
84
|
+
"""The number to compare against, or ``None`` if the chip lacks that limit."""
|
|
85
|
+
if self.fixed is not None:
|
|
86
|
+
return self.fixed
|
|
87
|
+
base = getattr(limits, self.limit or "", None) if limits is not None else None
|
|
88
|
+
return None if base is None else float(base) + self.offset
|
|
89
|
+
|
|
90
|
+
def describe(self) -> str:
|
|
91
|
+
if self.fixed is not None:
|
|
92
|
+
return f"{self.fixed:g}"
|
|
93
|
+
sign = "-" if self.offset < 0 else "+"
|
|
94
|
+
return f"{self.limit}{sign}{abs(self.offset):g}" if self.offset else str(self.limit)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
_RECOVERY_SIDE = {"above": "below", "below": "above"}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def clear_on_breaching_side(when: When, value: float, clear: float) -> bool:
|
|
101
|
+
"""True when ``clear`` would count as recovered while ``value`` still breaches, so the
|
|
102
|
+
alert could close and reopen at a constant reading (docs/BIBLE.md, "Boundaries")."""
|
|
103
|
+
return clear > value if when == "above" else clear < value if when == "below" else False
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def wrong_side_of(when: When, value: Threshold, clear: Threshold) -> bool:
|
|
107
|
+
"""The load-time check: decidable when both are fixed, or both relative to the same limit.
|
|
108
|
+
A mix of the two is checked once the chip's limits are known."""
|
|
109
|
+
if value.fixed is not None and clear.fixed is not None:
|
|
110
|
+
return clear_on_breaching_side(when, value.fixed, clear.fixed)
|
|
111
|
+
if value.limit is not None and value.limit == clear.limit:
|
|
112
|
+
return clear_on_breaching_side(when, value.offset, clear.offset)
|
|
113
|
+
return False
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class OnlyIf(msgspec.Struct, forbid_unknown_fields=True, frozen=True):
|
|
117
|
+
"""Guard: the rule applies only while ``signal`` equals ``equals``. Named wildcards in
|
|
118
|
+
``signal`` (``{battery}``) take the value the rule's sensor glob bound them to, so the guard
|
|
119
|
+
reads the same device as the sensor."""
|
|
120
|
+
|
|
121
|
+
signal: str
|
|
122
|
+
equals: float | str
|
|
123
|
+
|
|
124
|
+
def __post_init__(self) -> None:
|
|
125
|
+
if isinstance(self.equals, float):
|
|
126
|
+
_finite(self.equals, "only_if.equals")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class Rule(msgspec.Struct, forbid_unknown_fields=True, frozen=True, kw_only=True):
|
|
130
|
+
id: str
|
|
131
|
+
sensor: str | tuple[str, ...] # a TOML list becomes a tuple: rules are immutable (ADV-022)
|
|
132
|
+
when: When
|
|
133
|
+
value: float | str
|
|
134
|
+
severity: Severity
|
|
135
|
+
name: str = ""
|
|
136
|
+
for_: str = msgspec.field(default="0s", name="for")
|
|
137
|
+
mode: Mode = "sustained"
|
|
138
|
+
clear: float | str | None = None
|
|
139
|
+
clear_for: str | None = None
|
|
140
|
+
on_missing: OnMissing = "ignore"
|
|
141
|
+
missing_for: str = "30s"
|
|
142
|
+
missing_severity: Severity = "info"
|
|
143
|
+
cooldown: str = "5m"
|
|
144
|
+
only_if: OnlyIf | None = None
|
|
145
|
+
|
|
146
|
+
def __post_init__(self) -> None:
|
|
147
|
+
if not self.id.strip():
|
|
148
|
+
raise ValueError("id must not be empty")
|
|
149
|
+
if not self.globs:
|
|
150
|
+
raise ValueError("sensor must name at least one signal glob")
|
|
151
|
+
if self.only_if is not None:
|
|
152
|
+
for name in sorted(globs.names(self.only_if.signal)):
|
|
153
|
+
for glob in self.globs:
|
|
154
|
+
if name not in globs.names(glob):
|
|
155
|
+
raise ValueError(
|
|
156
|
+
f"only_if uses {{{name}}}, which sensor {glob!r} doesn't bind"
|
|
157
|
+
)
|
|
158
|
+
for duration in (self.for_, self.clear_for, self.missing_for, self.cooldown):
|
|
159
|
+
if duration is not None:
|
|
160
|
+
parse_duration(duration)
|
|
161
|
+
if self.when == "equals" and isinstance(self.value, float):
|
|
162
|
+
_finite(self.value, "value")
|
|
163
|
+
if self.when != "equals": # equals compares any value, e.g. "Discharging"
|
|
164
|
+
value = Threshold.parse(self.value)
|
|
165
|
+
clear = Threshold.parse(self.clear) if self.clear is not None else value
|
|
166
|
+
if wrong_side_of(self.when, value, clear):
|
|
167
|
+
raise ValueError(
|
|
168
|
+
f"clear {clear.describe()} is on the breaching side of {value.describe()}:"
|
|
169
|
+
f" a {self.when!r} rule must clear at or {_RECOVERY_SIDE[self.when]} its value"
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
def matches(self, signal: str) -> bool:
|
|
173
|
+
return self.bindings(signal) is not None
|
|
174
|
+
|
|
175
|
+
def bindings(self, signal: str) -> dict[str, str] | None:
|
|
176
|
+
"""The named wildcards bound by the first sensor glob ``signal`` matches, or ``None``
|
|
177
|
+
when it matches none."""
|
|
178
|
+
for glob in self.globs:
|
|
179
|
+
bound = globs.match(glob, signal)
|
|
180
|
+
if bound is not None:
|
|
181
|
+
return bound
|
|
182
|
+
return None
|
|
183
|
+
|
|
184
|
+
@property
|
|
185
|
+
def title(self) -> str:
|
|
186
|
+
return self.name or self.id
|
|
187
|
+
|
|
188
|
+
@property
|
|
189
|
+
def globs(self) -> tuple[str, ...]:
|
|
190
|
+
globs = [self.sensor] if isinstance(self.sensor, str) else self.sensor
|
|
191
|
+
return tuple(g for g in globs if g.strip())
|
|
192
|
+
|
|
193
|
+
@property
|
|
194
|
+
def for_s(self) -> float:
|
|
195
|
+
return parse_duration(self.for_)
|
|
196
|
+
|
|
197
|
+
@property
|
|
198
|
+
def clear_for_s(self) -> float:
|
|
199
|
+
return parse_duration(self.clear_for) if self.clear_for is not None else self.for_s
|
|
200
|
+
|
|
201
|
+
@property
|
|
202
|
+
def missing_for_s(self) -> float:
|
|
203
|
+
return parse_duration(self.missing_for)
|
|
204
|
+
|
|
205
|
+
@property
|
|
206
|
+
def cooldown_s(self) -> float:
|
|
207
|
+
return parse_duration(self.cooldown)
|
|
208
|
+
|
|
209
|
+
@property
|
|
210
|
+
def threshold(self) -> Threshold:
|
|
211
|
+
return Threshold.parse(self.value)
|
|
212
|
+
|
|
213
|
+
@property
|
|
214
|
+
def clear_threshold(self) -> Threshold:
|
|
215
|
+
return Threshold.parse(self.clear) if self.clear is not None else self.threshold
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Civil-time quiet hours and boot-scoped monotonic rule mutes."""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from sensitivebox.alerts.engine import Clock
|
|
7
|
+
from sensitivebox.alerts.routing import MuteDecision, Notification
|
|
8
|
+
from sensitivebox.store.mutes import Mutes
|
|
9
|
+
from sensitivebox.store.quality import local_zone
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def boot_id(proc_root: Path) -> str:
|
|
13
|
+
try:
|
|
14
|
+
value = (proc_root / "sys/kernel/random/boot_id").read_text().strip()
|
|
15
|
+
except OSError:
|
|
16
|
+
raise OSError("boot ID unavailable in selected proc root") from None
|
|
17
|
+
if not value:
|
|
18
|
+
raise OSError("empty boot ID in selected proc root")
|
|
19
|
+
return value
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def quiet_now(schedule: str, wall: float) -> bool:
|
|
23
|
+
current = datetime.fromtimestamp(wall, local_zone()).strftime("%H:%M")
|
|
24
|
+
for part in schedule.split(","):
|
|
25
|
+
if not part:
|
|
26
|
+
continue
|
|
27
|
+
start, end = part.split("-")
|
|
28
|
+
if (start <= current < end) if start < end else (current >= start or current < end):
|
|
29
|
+
return True
|
|
30
|
+
return False
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class PersistentMute:
|
|
34
|
+
def __init__(self, store: Mutes, boot: str, clock: Clock, wall: Clock) -> None:
|
|
35
|
+
self.store, self.boot, self.clock, self.wall = store, boot, clock, wall
|
|
36
|
+
self._now = clock()
|
|
37
|
+
|
|
38
|
+
def decide(self, notification: Notification) -> MuteDecision:
|
|
39
|
+
self._now = max(self._now, self.clock())
|
|
40
|
+
row = self.store.db.execute(
|
|
41
|
+
"SELECT expiry,renotify,released FROM mutes WHERE rule_id=? AND boot=?",
|
|
42
|
+
(notification.rule_id, self.boot),
|
|
43
|
+
).fetchone()
|
|
44
|
+
manual = "muted" if row and row[2] else None
|
|
45
|
+
if row and not row[2] and (row[0] is None or row[0] > self._now):
|
|
46
|
+
return MuteDecision(False, "muted", bool(row[1]))
|
|
47
|
+
quiet = self.store.db.execute(
|
|
48
|
+
"SELECT schedule,renotify,released FROM quiet_hours"
|
|
49
|
+
).fetchone()
|
|
50
|
+
if quiet and notification.severity != "critical":
|
|
51
|
+
if quiet_now(quiet[0], self.wall()):
|
|
52
|
+
return MuteDecision(False, "quiet hours", bool(quiet[1]))
|
|
53
|
+
if quiet[2] and manual is None:
|
|
54
|
+
manual = "quiet hours"
|
|
55
|
+
return MuteDecision(True, manual_release=manual)
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Replay recorded input events through the real engine.
|
|
2
|
+
|
|
3
|
+
There is one evaluation path. ``sbox rule <id>`` and the rule editor's preview replay the input
|
|
4
|
+
events the store recorded (``Store.inputs``) with this function instead of re-implementing the
|
|
5
|
+
rules, so "why didn't it fire?" is always answered by the code that decides whether it fires.
|
|
6
|
+
The events carry everything the live engine saw, rule and limit changes included (ADV-005).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
import msgspec
|
|
13
|
+
|
|
14
|
+
from sensitivebox.alerts.engine import Engine, Evaluation, ManualClock, Step, Transition
|
|
15
|
+
from sensitivebox.alerts.events import (
|
|
16
|
+
Checkpoint,
|
|
17
|
+
EngineSettings,
|
|
18
|
+
InputEvent,
|
|
19
|
+
LimitsChanged,
|
|
20
|
+
OpenAlerts,
|
|
21
|
+
Restart,
|
|
22
|
+
Resume,
|
|
23
|
+
RulesLoaded,
|
|
24
|
+
Suspend,
|
|
25
|
+
Tick,
|
|
26
|
+
)
|
|
27
|
+
from sensitivebox.alerts.model import Rule
|
|
28
|
+
from sensitivebox.hwmon import Limits
|
|
29
|
+
|
|
30
|
+
type Event = InputEvent
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"EngineSettings",
|
|
34
|
+
"Event",
|
|
35
|
+
"LimitsChanged",
|
|
36
|
+
"ReplayResult",
|
|
37
|
+
"Resume",
|
|
38
|
+
"RulesLoaded",
|
|
39
|
+
"Suspend",
|
|
40
|
+
"Tick",
|
|
41
|
+
"replay",
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True, slots=True)
|
|
46
|
+
class ReplayResult:
|
|
47
|
+
evaluations: tuple[Evaluation, ...]
|
|
48
|
+
transitions: tuple[Transition, ...]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def replay(
|
|
52
|
+
rules: Sequence[Rule],
|
|
53
|
+
events: Iterable[InputEvent],
|
|
54
|
+
limits: Mapping[str, Limits] | None = None,
|
|
55
|
+
) -> ReplayResult:
|
|
56
|
+
"""Run ``events`` (in the order recorded) through a fresh engine and collect what it did.
|
|
57
|
+
|
|
58
|
+
``rules`` and ``limits`` are the starting configuration; ``RulesLoaded`` and ``LimitsChanged``
|
|
59
|
+
events change it exactly as ``Engine.load`` and ``Engine.set_limits`` did live.
|
|
60
|
+
"""
|
|
61
|
+
runner = ReplayRunner(rules, limits)
|
|
62
|
+
evaluations: list[Evaluation] = []
|
|
63
|
+
transitions: list[Transition] = []
|
|
64
|
+
for event in events:
|
|
65
|
+
step = runner.feed(event)
|
|
66
|
+
evaluations.extend(step.evaluations)
|
|
67
|
+
transitions.extend(step.transitions)
|
|
68
|
+
return ReplayResult(tuple(evaluations), tuple(transitions))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class ReplayRunner:
|
|
72
|
+
"""Incremental replay also advances the single ring-boundary checkpoint."""
|
|
73
|
+
|
|
74
|
+
def __init__(self, rules: Sequence[Rule] = (), limits: Mapping[str, Limits] | None = None):
|
|
75
|
+
self.clock = ManualClock()
|
|
76
|
+
self.engine = Engine(rules, clock=self.clock, limits=limits)
|
|
77
|
+
|
|
78
|
+
def feed(self, event: InputEvent) -> Step:
|
|
79
|
+
self.clock.now = event.at
|
|
80
|
+
match event:
|
|
81
|
+
case Restart():
|
|
82
|
+
self.engine = Engine((), clock=self.clock)
|
|
83
|
+
case Checkpoint(payload=payload):
|
|
84
|
+
self.engine.restore(payload)
|
|
85
|
+
case Tick(signals=signals):
|
|
86
|
+
return self.engine.evaluate(signals)
|
|
87
|
+
case OpenAlerts(payload=payload):
|
|
88
|
+
self.engine.restore_alerts(msgspec.json.decode(payload, type=list[Transition]))
|
|
89
|
+
case Suspend():
|
|
90
|
+
self.engine.suspend()
|
|
91
|
+
case Resume():
|
|
92
|
+
self.engine.resume()
|
|
93
|
+
case LimitsChanged(limits=changed):
|
|
94
|
+
self.engine.set_limits(changed)
|
|
95
|
+
case RulesLoaded(rules=loaded):
|
|
96
|
+
return Step(transitions=self.engine.load(loaded))
|
|
97
|
+
case EngineSettings(max_gap=max_gap):
|
|
98
|
+
self.engine.configure(max_gap)
|
|
99
|
+
return Step()
|