sitemon 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.
- sitemon/__init__.py +22 -0
- sitemon/_cli.py +279 -0
- sitemon/_duration.py +34 -0
- sitemon/_events.py +230 -0
- sitemon/_systemd.py +35 -0
- sitemon/agent/__init__.py +1 -0
- sitemon/agent/ami.py +266 -0
- sitemon/agent/aredn.py +49 -0
- sitemon/agent/runtime.py +504 -0
- sitemon/agent/sensors/__init__.py +1 -0
- sitemon/agent/sensors/base.py +22 -0
- sitemon/agent/sensors/bme280.py +197 -0
- sitemon/agent/sensors/factory.py +129 -0
- sitemon/agent/sensors/gpio.py +80 -0
- sitemon/agent/sensors/i2c.py +117 -0
- sitemon/agent/sensors/ina.py +118 -0
- sitemon/agent/sensors/sim.py +105 -0
- sitemon/agent/store.py +195 -0
- sitemon/config.py +429 -0
- sitemon/hub/__init__.py +1 -0
- sitemon/hub/alerts.py +135 -0
- sitemon/hub/channels.py +94 -0
- sitemon/hub/db.py +276 -0
- sitemon/hub/ingest.py +252 -0
- sitemon/hub/rules.py +266 -0
- sitemon/hub/server.py +494 -0
- sitemon/hub/static/app.js +214 -0
- sitemon/hub/static/index.html +19 -0
- sitemon/hub/static/style.css +77 -0
- sitemon/hub/summary.py +55 -0
- sitemon/py.typed +0 -0
- sitemon-0.1.0.dist-info/METADATA +244 -0
- sitemon-0.1.0.dist-info/RECORD +36 -0
- sitemon-0.1.0.dist-info/WHEEL +4 -0
- sitemon-0.1.0.dist-info/entry_points.txt +2 -0
- sitemon-0.1.0.dist-info/licenses/LICENSE +21 -0
sitemon/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Repeater site monitoring: an agent at each site, one hub watching them all::
|
|
2
|
+
|
|
3
|
+
from sitemon import Event, SigningKey
|
|
4
|
+
|
|
5
|
+
key = SigningKey.generate()
|
|
6
|
+
ev = Event.create(site="hilltop", seq=1, boot="b1", kind="reading",
|
|
7
|
+
source="batt", data={"v": 13.4}).signed(key)
|
|
8
|
+
assert ev.verify(key.public_key())
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
14
|
+
|
|
15
|
+
from ._events import Event, PublicKey, SigningKey, canonical_json
|
|
16
|
+
|
|
17
|
+
try:
|
|
18
|
+
__version__ = version("sitemon")
|
|
19
|
+
except PackageNotFoundError: # running from a source tree without an install
|
|
20
|
+
__version__ = "0.0.0+unknown"
|
|
21
|
+
|
|
22
|
+
__all__ = ["Event", "PublicKey", "SigningKey", "canonical_json", "__version__"]
|
sitemon/_cli.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"""Command line: ``sitemon keygen|pubkey|agent|hub|check|summary|demo``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import asyncio
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
import signal
|
|
10
|
+
import sys
|
|
11
|
+
import tempfile
|
|
12
|
+
import time
|
|
13
|
+
from collections.abc import Awaitable, Callable
|
|
14
|
+
|
|
15
|
+
from . import __version__
|
|
16
|
+
from ._events import SigningKey
|
|
17
|
+
from .config import (
|
|
18
|
+
AgentConfig,
|
|
19
|
+
ChannelConfig,
|
|
20
|
+
ConfigError,
|
|
21
|
+
HubConfig,
|
|
22
|
+
RuleConfig,
|
|
23
|
+
SiteConfig,
|
|
24
|
+
load_agent_config,
|
|
25
|
+
load_hub_config,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _write_key(path: str, key: SigningKey) -> None:
|
|
30
|
+
if os.path.exists(path):
|
|
31
|
+
raise SystemExit(f"{path} already exists; refusing to overwrite a site key")
|
|
32
|
+
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
|
|
33
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
34
|
+
with os.fdopen(fd, "w", encoding="ascii") as f:
|
|
35
|
+
f.write(key.to_hex() + "\n")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def cmd_keygen(a: argparse.Namespace) -> int:
|
|
39
|
+
key = SigningKey.generate()
|
|
40
|
+
_write_key(a.out, key)
|
|
41
|
+
print(f"Wrote {a.out}. Add this site's public key to the hub config:\n")
|
|
42
|
+
print(f'key = "{key.public_key().to_b64()}"')
|
|
43
|
+
return 0
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def cmd_pubkey(a: argparse.Namespace) -> int:
|
|
47
|
+
print(SigningKey.load(a.key).public_key().to_b64())
|
|
48
|
+
return 0
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _run(coro_factory: Callable[[], Awaitable[None]], stopper: Callable[[], None]) -> None:
|
|
52
|
+
async def main() -> None:
|
|
53
|
+
loop = asyncio.get_running_loop()
|
|
54
|
+
for sig in (signal.SIGINT, signal.SIGTERM):
|
|
55
|
+
try:
|
|
56
|
+
loop.add_signal_handler(sig, stopper)
|
|
57
|
+
except (NotImplementedError, RuntimeError): # Windows
|
|
58
|
+
pass
|
|
59
|
+
await coro_factory()
|
|
60
|
+
|
|
61
|
+
try:
|
|
62
|
+
asyncio.run(main())
|
|
63
|
+
except KeyboardInterrupt:
|
|
64
|
+
pass
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def cmd_agent(a: argparse.Namespace) -> int:
|
|
68
|
+
from .agent.runtime import Agent
|
|
69
|
+
from .agent.sensors.factory import build_sensors
|
|
70
|
+
|
|
71
|
+
cfg = load_agent_config(a.config)
|
|
72
|
+
agent = Agent(cfg, SigningKey.load(cfg.key_path), build_sensors(cfg.sensors))
|
|
73
|
+
_run(agent.run, agent.stop)
|
|
74
|
+
return 0
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def cmd_hub(a: argparse.Namespace) -> int:
|
|
78
|
+
from .hub.server import Hub
|
|
79
|
+
|
|
80
|
+
hub = Hub(load_hub_config(a.config))
|
|
81
|
+
_run(hub.run, hub.stop)
|
|
82
|
+
return 0
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _is_agent_config(path: str) -> bool:
|
|
86
|
+
"""An agent config has a [site] table; a hub config doesn't."""
|
|
87
|
+
import tomllib
|
|
88
|
+
|
|
89
|
+
try:
|
|
90
|
+
with open(path, "rb") as f:
|
|
91
|
+
return "site" in tomllib.load(f)
|
|
92
|
+
except (OSError, tomllib.TOMLDecodeError):
|
|
93
|
+
return False # let the loader report it properly
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def cmd_check(a: argparse.Namespace) -> int:
|
|
97
|
+
for path in a.configs:
|
|
98
|
+
try:
|
|
99
|
+
if _is_agent_config(path):
|
|
100
|
+
from .agent.sensors.factory import build_sensors
|
|
101
|
+
|
|
102
|
+
ag = load_agent_config(path)
|
|
103
|
+
build_sensors(ag.sensors) # validates sensor entries without touching hardware
|
|
104
|
+
print(
|
|
105
|
+
f"{path}: agent config OK (site {ag.site}, {len(ag.sensors)} sensors, "
|
|
106
|
+
f"AMI {'on' if ag.ami else 'off'}, AREDN {'on' if ag.aredn else 'off'})"
|
|
107
|
+
)
|
|
108
|
+
else:
|
|
109
|
+
from .hub.server import load_keys
|
|
110
|
+
|
|
111
|
+
h = load_hub_config(path)
|
|
112
|
+
load_keys(h)
|
|
113
|
+
print(
|
|
114
|
+
f"{path}: hub config OK ({len(h.sites)} sites, {len(h.rules)} rules, "
|
|
115
|
+
f"{len(h.channels)} channels)"
|
|
116
|
+
)
|
|
117
|
+
except ConfigError as e:
|
|
118
|
+
print(f"{path}: {e}", file=sys.stderr)
|
|
119
|
+
return 1
|
|
120
|
+
return 0
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def cmd_summary(a: argparse.Namespace) -> int:
|
|
124
|
+
from .hub.db import HubDB
|
|
125
|
+
from .hub.summary import weekly_summary
|
|
126
|
+
|
|
127
|
+
cfg = load_hub_config(a.config)
|
|
128
|
+
db = HubDB(cfg.db_path)
|
|
129
|
+
for group in cfg.groups:
|
|
130
|
+
print(weekly_summary(cfg, db, group, time.time()))
|
|
131
|
+
print()
|
|
132
|
+
return 0
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def cmd_demo(a: argparse.Namespace) -> int:
|
|
136
|
+
"""A hub and three simulated sites on this machine, for a look around."""
|
|
137
|
+
from .agent.runtime import Agent
|
|
138
|
+
from .agent.sensors import sim
|
|
139
|
+
from .agent.sensors.base import Sensor
|
|
140
|
+
from .hub.server import Hub
|
|
141
|
+
|
|
142
|
+
tmp = tempfile.mkdtemp(prefix="sitemon-demo-")
|
|
143
|
+
hub_url = f"http://127.0.0.1:{a.port}"
|
|
144
|
+
specs = [
|
|
145
|
+
("shack", "Shack", 13.4, 0.0, False),
|
|
146
|
+
("hilltop", "Hilltop", 12.6, 0.0, True), # door open
|
|
147
|
+
("ridge", "North Ridge", 12.05, 0.0, False), # battery low
|
|
148
|
+
]
|
|
149
|
+
keys = {sid: SigningKey.generate() for sid, *_ in specs}
|
|
150
|
+
hub_cfg = HubConfig(
|
|
151
|
+
listen=f"127.0.0.1:{a.port}",
|
|
152
|
+
db_path=os.path.join(tmp, "hub.db"),
|
|
153
|
+
public_url=hub_url,
|
|
154
|
+
sites=[
|
|
155
|
+
SiteConfig(id=sid, name=name, group="demo", keys=[keys[sid].public_key().to_b64()])
|
|
156
|
+
for sid, name, *_ in specs
|
|
157
|
+
],
|
|
158
|
+
rules=[
|
|
159
|
+
RuleConfig(
|
|
160
|
+
name="Battery low",
|
|
161
|
+
type="threshold",
|
|
162
|
+
metric="batt.v",
|
|
163
|
+
sites=["*"],
|
|
164
|
+
below=12.2,
|
|
165
|
+
critical_below=11.8,
|
|
166
|
+
hysteresis=0.1,
|
|
167
|
+
unit="V",
|
|
168
|
+
),
|
|
169
|
+
RuleConfig(name="Door open", type="state", metric="door.open", sites=["*"], bad=True),
|
|
170
|
+
RuleConfig(
|
|
171
|
+
name="Shack hot",
|
|
172
|
+
type="threshold",
|
|
173
|
+
metric="env.temp_c",
|
|
174
|
+
sites=["*"],
|
|
175
|
+
above=40,
|
|
176
|
+
critical_above=50,
|
|
177
|
+
unit="°C",
|
|
178
|
+
),
|
|
179
|
+
],
|
|
180
|
+
channels=[]
|
|
181
|
+
if not a.ntfy_topic
|
|
182
|
+
else [
|
|
183
|
+
ChannelConfig(
|
|
184
|
+
type="ntfy",
|
|
185
|
+
name="ntfy",
|
|
186
|
+
min_severity="warn",
|
|
187
|
+
url="https://ntfy.sh",
|
|
188
|
+
topic=a.ntfy_topic,
|
|
189
|
+
)
|
|
190
|
+
],
|
|
191
|
+
groups={"demo": "Demo sites"},
|
|
192
|
+
silence_warn=60,
|
|
193
|
+
silence_critical=120,
|
|
194
|
+
summary_enabled=False,
|
|
195
|
+
)
|
|
196
|
+
hub = Hub(hub_cfg)
|
|
197
|
+
agents = []
|
|
198
|
+
for sid, _name, volts, drift, door in specs:
|
|
199
|
+
cfg = AgentConfig(
|
|
200
|
+
site=sid,
|
|
201
|
+
key_path="",
|
|
202
|
+
data_dir=os.path.join(tmp, sid),
|
|
203
|
+
hubs=[hub_url],
|
|
204
|
+
sample_interval=5,
|
|
205
|
+
heartbeat_interval=10,
|
|
206
|
+
flush_interval=5,
|
|
207
|
+
sync_interval=5,
|
|
208
|
+
local_ui="",
|
|
209
|
+
)
|
|
210
|
+
sensors: list[Sensor] = [
|
|
211
|
+
sim.battery("batt", float_v=volts, drift_v_per_day=drift, seed=hash(sid) & 0xFFFF),
|
|
212
|
+
sim.environment("env", base_c=24.0),
|
|
213
|
+
sim.switch("door", "open", active=door),
|
|
214
|
+
]
|
|
215
|
+
agents.append(Agent(cfg, keys[sid], sensors))
|
|
216
|
+
|
|
217
|
+
async def main() -> None:
|
|
218
|
+
tasks = [asyncio.create_task(hub.run())]
|
|
219
|
+
await asyncio.sleep(0.5)
|
|
220
|
+
# The third site stops after a minute, to show the silence alarm.
|
|
221
|
+
tasks += [asyncio.create_task(ag.run()) for ag in agents]
|
|
222
|
+
print(f"Dashboard: {hub_url} (data in {tmp}; Ctrl+C to stop)")
|
|
223
|
+
await asyncio.sleep(60)
|
|
224
|
+
agents[-1].stop()
|
|
225
|
+
await asyncio.gather(*tasks)
|
|
226
|
+
|
|
227
|
+
def stop() -> None:
|
|
228
|
+
for ag in agents:
|
|
229
|
+
ag.stop()
|
|
230
|
+
hub.stop()
|
|
231
|
+
|
|
232
|
+
_run(main, stop)
|
|
233
|
+
return 0
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def main(argv: list[str] | None = None) -> int:
|
|
237
|
+
p = argparse.ArgumentParser(prog="sitemon", description=__doc__)
|
|
238
|
+
p.add_argument("--version", action="version", version=f"sitemon {__version__}")
|
|
239
|
+
p.add_argument("-v", "--verbose", action="store_true")
|
|
240
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
241
|
+
|
|
242
|
+
s = sub.add_parser("keygen", help="create a site signing key and print its public key")
|
|
243
|
+
s.add_argument("--out", required=True)
|
|
244
|
+
s.set_defaults(fn=cmd_keygen)
|
|
245
|
+
s = sub.add_parser("pubkey", help="print the public key for a site key file")
|
|
246
|
+
s.add_argument("--key", required=True)
|
|
247
|
+
s.set_defaults(fn=cmd_pubkey)
|
|
248
|
+
s = sub.add_parser("agent", help="run the site agent")
|
|
249
|
+
s.add_argument("--config", default="/etc/sitemon/agent.toml")
|
|
250
|
+
s.set_defaults(fn=cmd_agent)
|
|
251
|
+
s = sub.add_parser("hub", help="run the hub")
|
|
252
|
+
s.add_argument("--config", default="/etc/sitemon/hub.toml")
|
|
253
|
+
s.set_defaults(fn=cmd_hub)
|
|
254
|
+
s = sub.add_parser("check", help="validate agent or hub config files")
|
|
255
|
+
s.add_argument("configs", nargs="+")
|
|
256
|
+
s.set_defaults(fn=cmd_check)
|
|
257
|
+
s = sub.add_parser("summary", help="print the weekly summary now")
|
|
258
|
+
s.add_argument("--config", default="/etc/sitemon/hub.toml")
|
|
259
|
+
s.set_defaults(fn=cmd_summary)
|
|
260
|
+
s = sub.add_parser("demo", help="run a hub with three simulated sites on this machine")
|
|
261
|
+
s.add_argument("--port", type=int, default=8470)
|
|
262
|
+
s.add_argument("--ntfy-topic", help="also push demo alerts to this ntfy.sh topic")
|
|
263
|
+
s.set_defaults(fn=cmd_demo)
|
|
264
|
+
|
|
265
|
+
a = p.parse_args(argv)
|
|
266
|
+
logging.basicConfig(
|
|
267
|
+
level=logging.DEBUG if a.verbose else logging.INFO,
|
|
268
|
+
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
|
269
|
+
)
|
|
270
|
+
try:
|
|
271
|
+
rc: int = a.fn(a)
|
|
272
|
+
return rc
|
|
273
|
+
except ConfigError as e:
|
|
274
|
+
print(f"config error: {e}", file=sys.stderr)
|
|
275
|
+
return 2
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
if __name__ == "__main__":
|
|
279
|
+
sys.exit(main())
|
sitemon/_duration.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Duration parsing for config and wording for alert text."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
_DURATION = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d|w)?\s*$")
|
|
8
|
+
_UNITS = {"ms": 0.001, "s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800, None: 1}
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def parse_duration(value: str | int | float) -> float:
|
|
12
|
+
"""``"30s"``, ``"5m"``, ``"7d"`` or a bare number of seconds -> seconds."""
|
|
13
|
+
if isinstance(value, bool):
|
|
14
|
+
raise ValueError(f"not a duration: {value!r}")
|
|
15
|
+
if isinstance(value, (int, float)):
|
|
16
|
+
if value < 0:
|
|
17
|
+
raise ValueError(f"negative duration: {value!r}")
|
|
18
|
+
return float(value)
|
|
19
|
+
m = _DURATION.match(value)
|
|
20
|
+
if not m:
|
|
21
|
+
raise ValueError(f"not a duration: {value!r} (use e.g. 30s, 5m, 2h, 7d)")
|
|
22
|
+
return float(m.group(1)) * _UNITS[m.group(2)]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def human_duration(seconds: float) -> str:
|
|
26
|
+
"""Plain-language duration for alert text: ``"20 min"``, ``"3 h"``, ``"2 days"``."""
|
|
27
|
+
s = int(seconds)
|
|
28
|
+
if s < 120:
|
|
29
|
+
return f"{s} s"
|
|
30
|
+
if s < 7200:
|
|
31
|
+
return f"{s // 60} min"
|
|
32
|
+
if s < 172800:
|
|
33
|
+
return f"{s // 3600} h"
|
|
34
|
+
return f"{s // 86400} days"
|
sitemon/_events.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
"""Events and their Ed25519 signatures.
|
|
2
|
+
|
|
3
|
+
Each event carries a per-site ``seq`` that never repeats and the agent's
|
|
4
|
+
monotonic clock (``boot`` + ``mono_ns``), so the hub can de-duplicate and place
|
|
5
|
+
it in time without trusting the site's wall clock. Signed, never encrypted:
|
|
6
|
+
data over AREDN must stay readable (Part 97).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import base64
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import math
|
|
15
|
+
import time
|
|
16
|
+
from dataclasses import asdict, dataclass, field, replace
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from cryptography.exceptions import InvalidSignature
|
|
20
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import (
|
|
21
|
+
Ed25519PrivateKey,
|
|
22
|
+
Ed25519PublicKey,
|
|
23
|
+
)
|
|
24
|
+
from cryptography.hazmat.primitives.serialization import (
|
|
25
|
+
Encoding,
|
|
26
|
+
NoEncryption,
|
|
27
|
+
PrivateFormat,
|
|
28
|
+
PublicFormat,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
KINDS = ("reading", "state", "fault", "heartbeat")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def canonical_json(obj: Any) -> bytes:
|
|
35
|
+
"""The exact bytes that get signed: sorted keys, no whitespace, UTF-8."""
|
|
36
|
+
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _b64(b: bytes) -> str:
|
|
40
|
+
return base64.b64encode(b).decode("ascii")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _unb64(s: str) -> bytes:
|
|
44
|
+
return base64.b64decode(s.encode("ascii"), validate=True)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def envelope_body(env: dict[str, Any]) -> dict[str, Any]:
|
|
48
|
+
"""What an upload's signature covers, including a digest of every event:
|
|
49
|
+
without it, a swapped event would be set aside and acked, and the real
|
|
50
|
+
one deleted by the site."""
|
|
51
|
+
evs = env.get("events", [])
|
|
52
|
+
return {
|
|
53
|
+
"site": env["site"],
|
|
54
|
+
"boot": env["boot"],
|
|
55
|
+
"mono_ns": env["mono_ns"],
|
|
56
|
+
"wall": env["wall"],
|
|
57
|
+
"count": len(evs),
|
|
58
|
+
"first": evs[0]["seq"] if evs else None,
|
|
59
|
+
"last": evs[-1]["seq"] if evs else None,
|
|
60
|
+
"events_sha256": hashlib.sha256(canonical_json(evs)).hexdigest(),
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class PublicKey:
|
|
65
|
+
"""An Ed25519 public key, written as base64 in hub config."""
|
|
66
|
+
|
|
67
|
+
def __init__(self, key: Ed25519PublicKey) -> None:
|
|
68
|
+
self._key = key
|
|
69
|
+
|
|
70
|
+
@classmethod
|
|
71
|
+
def from_b64(cls, s: str) -> PublicKey:
|
|
72
|
+
raw = _unb64(s.strip())
|
|
73
|
+
if len(raw) != 32:
|
|
74
|
+
raise ValueError("an Ed25519 public key is 32 bytes")
|
|
75
|
+
return cls(Ed25519PublicKey.from_public_bytes(raw))
|
|
76
|
+
|
|
77
|
+
def to_b64(self) -> str:
|
|
78
|
+
return _b64(self._key.public_bytes(Encoding.Raw, PublicFormat.Raw))
|
|
79
|
+
|
|
80
|
+
def verify(self, sig_b64: str, message: bytes) -> bool:
|
|
81
|
+
try:
|
|
82
|
+
self._key.verify(_unb64(sig_b64), message)
|
|
83
|
+
except (InvalidSignature, ValueError):
|
|
84
|
+
return False
|
|
85
|
+
return True
|
|
86
|
+
|
|
87
|
+
def __eq__(self, other: object) -> bool:
|
|
88
|
+
return isinstance(other, PublicKey) and other.to_b64() == self.to_b64()
|
|
89
|
+
|
|
90
|
+
def __hash__(self) -> int:
|
|
91
|
+
return hash(self.to_b64())
|
|
92
|
+
|
|
93
|
+
def __repr__(self) -> str:
|
|
94
|
+
return f"PublicKey({self.to_b64()!r})"
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class SigningKey:
|
|
98
|
+
"""A site's Ed25519 private key. Stored as 64 hex characters in a 0600 file."""
|
|
99
|
+
|
|
100
|
+
def __init__(self, key: Ed25519PrivateKey) -> None:
|
|
101
|
+
self._key = key
|
|
102
|
+
|
|
103
|
+
@classmethod
|
|
104
|
+
def generate(cls) -> SigningKey:
|
|
105
|
+
return cls(Ed25519PrivateKey.generate())
|
|
106
|
+
|
|
107
|
+
@classmethod
|
|
108
|
+
def from_hex(cls, s: str) -> SigningKey:
|
|
109
|
+
raw = bytes.fromhex(s.strip())
|
|
110
|
+
if len(raw) != 32:
|
|
111
|
+
raise ValueError("an Ed25519 private key is 32 bytes (64 hex characters)")
|
|
112
|
+
return cls(Ed25519PrivateKey.from_private_bytes(raw))
|
|
113
|
+
|
|
114
|
+
@classmethod
|
|
115
|
+
def load(cls, path: str) -> SigningKey:
|
|
116
|
+
with open(path, encoding="ascii") as f:
|
|
117
|
+
return cls.from_hex(f.read())
|
|
118
|
+
|
|
119
|
+
def to_hex(self) -> str:
|
|
120
|
+
return self._key.private_bytes(Encoding.Raw, PrivateFormat.Raw, NoEncryption()).hex()
|
|
121
|
+
|
|
122
|
+
def public_key(self) -> PublicKey:
|
|
123
|
+
return PublicKey(self._key.public_key())
|
|
124
|
+
|
|
125
|
+
def sign(self, message: bytes) -> str:
|
|
126
|
+
return _b64(self._key.sign(message))
|
|
127
|
+
|
|
128
|
+
def __repr__(self) -> str: # never print key material
|
|
129
|
+
return f"SigningKey(public={self.public_key().to_b64()!r})"
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@dataclass(frozen=True)
|
|
133
|
+
class Event:
|
|
134
|
+
site: str
|
|
135
|
+
seq: int
|
|
136
|
+
boot: str
|
|
137
|
+
mono_ns: int
|
|
138
|
+
wall: float
|
|
139
|
+
kind: str
|
|
140
|
+
source: str
|
|
141
|
+
data: dict[str, Any] = field(default_factory=dict)
|
|
142
|
+
sig: str = ""
|
|
143
|
+
|
|
144
|
+
@classmethod
|
|
145
|
+
def create(
|
|
146
|
+
cls,
|
|
147
|
+
*,
|
|
148
|
+
site: str,
|
|
149
|
+
seq: int,
|
|
150
|
+
boot: str,
|
|
151
|
+
kind: str,
|
|
152
|
+
source: str,
|
|
153
|
+
data: dict[str, Any],
|
|
154
|
+
mono_ns: int | None = None,
|
|
155
|
+
wall: float | None = None,
|
|
156
|
+
) -> Event:
|
|
157
|
+
if kind not in KINDS:
|
|
158
|
+
raise ValueError(f"unknown event kind {kind!r}")
|
|
159
|
+
return cls(
|
|
160
|
+
site=site,
|
|
161
|
+
seq=seq,
|
|
162
|
+
boot=boot,
|
|
163
|
+
mono_ns=time.monotonic_ns() if mono_ns is None else mono_ns,
|
|
164
|
+
wall=round(time.time() if wall is None else wall, 3),
|
|
165
|
+
kind=kind,
|
|
166
|
+
source=source,
|
|
167
|
+
data=data,
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
def body(self) -> dict[str, Any]:
|
|
171
|
+
d = asdict(self)
|
|
172
|
+
del d["sig"]
|
|
173
|
+
return d
|
|
174
|
+
|
|
175
|
+
def signing_bytes(self) -> bytes:
|
|
176
|
+
return canonical_json(self.body())
|
|
177
|
+
|
|
178
|
+
def signed(self, key: SigningKey) -> Event:
|
|
179
|
+
return replace(self, sig=key.sign(self.signing_bytes()))
|
|
180
|
+
|
|
181
|
+
def verify(self, key: PublicKey) -> bool:
|
|
182
|
+
return bool(self.sig) and key.verify(self.sig, self.signing_bytes())
|
|
183
|
+
|
|
184
|
+
def to_dict(self) -> dict[str, Any]:
|
|
185
|
+
return asdict(self)
|
|
186
|
+
|
|
187
|
+
def to_json(self) -> str:
|
|
188
|
+
return canonical_json(self.to_dict()).decode()
|
|
189
|
+
|
|
190
|
+
@classmethod
|
|
191
|
+
def from_dict(cls, d: dict[str, Any]) -> Event:
|
|
192
|
+
try:
|
|
193
|
+
ev = cls(
|
|
194
|
+
site=str(d["site"]),
|
|
195
|
+
seq=int(d["seq"]),
|
|
196
|
+
boot=str(d["boot"]),
|
|
197
|
+
mono_ns=int(d["mono_ns"]),
|
|
198
|
+
wall=float(d["wall"]),
|
|
199
|
+
kind=str(d["kind"]),
|
|
200
|
+
source=str(d["source"]),
|
|
201
|
+
data=dict(d["data"]),
|
|
202
|
+
sig=str(d.get("sig", "")),
|
|
203
|
+
)
|
|
204
|
+
except (KeyError, TypeError, ValueError, OverflowError) as e:
|
|
205
|
+
raise ValueError(f"malformed event: {e}") from e
|
|
206
|
+
if ev.kind not in KINDS:
|
|
207
|
+
raise ValueError(f"unknown event kind {ev.kind!r}")
|
|
208
|
+
# The signature covers the parsed body, so "5" must not pass for 5.
|
|
209
|
+
if any(not isinstance(d[k], t) or isinstance(d[k], bool) for k, t in _WIRE_TYPES.items()):
|
|
210
|
+
raise ValueError("malformed event: field has the wrong type")
|
|
211
|
+
# SQLite integers are signed 64-bit.
|
|
212
|
+
if not (0 <= ev.seq < 2**63 and 0 <= ev.mono_ns < 2**63) or not math.isfinite(ev.wall):
|
|
213
|
+
raise ValueError("malformed event: seq, mono_ns or wall out of range")
|
|
214
|
+
return ev
|
|
215
|
+
|
|
216
|
+
@classmethod
|
|
217
|
+
def from_json(cls, s: str) -> Event:
|
|
218
|
+
return cls.from_dict(json.loads(s))
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
_WIRE_TYPES: dict[str, type | tuple[type, ...]] = {
|
|
222
|
+
"site": str,
|
|
223
|
+
"seq": int,
|
|
224
|
+
"boot": str,
|
|
225
|
+
"mono_ns": int,
|
|
226
|
+
"wall": (int, float),
|
|
227
|
+
"kind": str,
|
|
228
|
+
"source": str,
|
|
229
|
+
"data": dict,
|
|
230
|
+
}
|
sitemon/_systemd.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""sd_notify without a dependency: READY=1 and watchdog pings."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import socket
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def notify(state: str) -> bool:
|
|
10
|
+
addr = os.environ.get("NOTIFY_SOCKET")
|
|
11
|
+
if not addr or not hasattr(socket, "AF_UNIX"):
|
|
12
|
+
return False
|
|
13
|
+
if addr.startswith("@"): # abstract namespace
|
|
14
|
+
addr = "\0" + addr[1:]
|
|
15
|
+
try:
|
|
16
|
+
with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as s:
|
|
17
|
+
s.connect(addr)
|
|
18
|
+
s.sendall(state.encode())
|
|
19
|
+
return True
|
|
20
|
+
except OSError:
|
|
21
|
+
return False
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def watchdog_interval() -> float | None:
|
|
25
|
+
"""Half of WatchdogSec, in seconds, or None when no watchdog is configured."""
|
|
26
|
+
usec = os.environ.get("WATCHDOG_USEC")
|
|
27
|
+
if not usec:
|
|
28
|
+
return None
|
|
29
|
+
pid = os.environ.get("WATCHDOG_PID")
|
|
30
|
+
if pid and pid != str(os.getpid()):
|
|
31
|
+
return None
|
|
32
|
+
try:
|
|
33
|
+
return int(usec) / 2_000_000
|
|
34
|
+
except ValueError:
|
|
35
|
+
return None
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""The site agent: sensors, AllStar and AREDN readers, event log and sync."""
|