moat-link-save 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.
- moat/link/save/__init__.py +49 -0
- moat/link/save/_cfg.yaml +39 -0
- moat/link/save/_main.py +361 -0
- moat/link/save/_schema.yaml +46 -0
- moat/link/save/_server_if.py +25 -0
- moat/link/save/cfg.py +151 -0
- moat/link/save/file.py +216 -0
- moat/link/save/keep.py +207 -0
- moat/link/save/saver.py +624 -0
- moat/link/save/source.py +947 -0
- moat/link/save/writer.py +198 -0
- moat_link_save-0.1.0.dist-info/METADATA +170 -0
- moat_link_save-0.1.0.dist-info/RECORD +16 -0
- moat_link_save-0.1.0.dist-info/WHEEL +5 -0
- moat_link_save-0.1.0.dist-info/licenses/LICENSE.txt +14 -0
- moat_link_save-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Saving MoaT-Link state to files.
|
|
3
|
+
|
|
4
|
+
This package implements writing, rotating, and cleaning up the state
|
|
5
|
+
files that a MoaT-Link server — or a separate recorder process
|
|
6
|
+
(``moat link save run``) — persists.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
|
|
12
|
+
|
|
13
|
+
try:
|
|
14
|
+
from importlib.metadata import version
|
|
15
|
+
|
|
16
|
+
_version = version("moat.link.save")
|
|
17
|
+
_version_tuple = tuple(int(x) for x in _version.split("."))
|
|
18
|
+
|
|
19
|
+
except Exception: # pragma: no cover
|
|
20
|
+
_version = "0.0.1"
|
|
21
|
+
_version_tuple = (0, 0, 1)
|
|
22
|
+
|
|
23
|
+
from moat.lib.config import register as _register
|
|
24
|
+
|
|
25
|
+
from .cfg import SaveCfg as SaveCfg
|
|
26
|
+
from .file import BadFile as BadFile
|
|
27
|
+
from .file import StateFileInfo as StateFileInfo
|
|
28
|
+
from .file import name_for_file as name_for_file
|
|
29
|
+
from .file import read_state_header as read_state_header
|
|
30
|
+
from .file import read_state_trailer as read_state_trailer
|
|
31
|
+
from .file import tag_check as tag_check
|
|
32
|
+
from .keep import cleanup_state_files as cleanup_state_files
|
|
33
|
+
from .keep import collect_state_files as collect_state_files
|
|
34
|
+
from .keep import unlink_state_file as unlink_state_file
|
|
35
|
+
|
|
36
|
+
_register(__name__)
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
"BadFile",
|
|
40
|
+
"SaveCfg",
|
|
41
|
+
"StateFileInfo",
|
|
42
|
+
"cleanup_state_files",
|
|
43
|
+
"collect_state_files",
|
|
44
|
+
"name_for_file",
|
|
45
|
+
"read_state_header",
|
|
46
|
+
"read_state_trailer",
|
|
47
|
+
"tag_check",
|
|
48
|
+
"unlink_state_file",
|
|
49
|
+
]
|
moat/link/save/_cfg.yaml
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# The recorder's own defaults. The server overrides them with its own
|
|
2
|
+
# ``save.dir`` (the server needs its own directory — a recorder writing
|
|
3
|
+
# to the same directory would corrupt the files).
|
|
4
|
+
dir: "/var/lib/moat/link/record"
|
|
5
|
+
name: "%Y-%m/%d/%H-%M.moat"
|
|
6
|
+
interval: 1000
|
|
7
|
+
rewrite: 5
|
|
8
|
+
errors: 10 # unlink error files ZZ
|
|
9
|
+
use_local_time: false
|
|
10
|
+
incremental: true
|
|
11
|
+
# False: only save snapshots
|
|
12
|
+
keep:
|
|
13
|
+
- 10
|
|
14
|
+
- 1 day
|
|
15
|
+
- 10
|
|
16
|
+
run: false
|
|
17
|
+
# Also record run.* data — ephemeral by design (state, ping,
|
|
18
|
+
# registrations), though some of it may be retained
|
|
19
|
+
source: null
|
|
20
|
+
# Where a recorder takes its data from: "server" or "backend".
|
|
21
|
+
# Not used by the server (which reads its own state).
|
|
22
|
+
load_dir: null
|
|
23
|
+
# Directory to restore the server's startup state from; the default
|
|
24
|
+
# (null) restores from ``dir``. Server-only: the recorder never
|
|
25
|
+
# restores, and a running server ignores changes to it (it only
|
|
26
|
+
# applies at startup).
|
|
27
|
+
replay:
|
|
28
|
+
# Backend-recorder tunables for detecting the end of the retained-
|
|
29
|
+
# message replay: no recorded message for `quiet` seconds (the
|
|
30
|
+
# burst is over), or the rate dropped well below its peak for
|
|
31
|
+
# `quiet` seconds while the recent messages are live (fresh
|
|
32
|
+
# timestamps within `skew` of the wall clock, and/or not marked
|
|
33
|
+
# retained), or the `max` bound passed. `first` bounds the wait for
|
|
34
|
+
# the first message (an empty subtree costs `first`, not `max`).
|
|
35
|
+
first: 5
|
|
36
|
+
quiet: 0.5
|
|
37
|
+
frac: 0.1
|
|
38
|
+
skew: 1.0
|
|
39
|
+
max: 30
|
moat/link/save/_main.py
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Command-line interface for moat.link.save: the remote state recorder.
|
|
3
|
+
|
|
4
|
+
``moat link save run`` records MoaT-Link state to rotating files, from
|
|
5
|
+
a server or from the MQTT backend directly. ``moat link save snap``
|
|
6
|
+
writes a one-shot full snapshot — for a backup, or triggered from a
|
|
7
|
+
systemd timer unit.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import anyio
|
|
13
|
+
import logging
|
|
14
|
+
import sys
|
|
15
|
+
from contextlib import nullcontext
|
|
16
|
+
from datetime import UTC, datetime
|
|
17
|
+
from pathlib import Path as FSPath
|
|
18
|
+
|
|
19
|
+
import asyncclick as click
|
|
20
|
+
|
|
21
|
+
from moat.util import NotGiven, gen_ident
|
|
22
|
+
from moat.util import time as mtime
|
|
23
|
+
from moat.lib.path import P, Path
|
|
24
|
+
from moat.lib.run import attr_args, process_args
|
|
25
|
+
|
|
26
|
+
from .cfg import SaveCfg, make_cfg
|
|
27
|
+
from .saver import Saver
|
|
28
|
+
from .source import BackendSource, ServerSource
|
|
29
|
+
|
|
30
|
+
from typing import TYPE_CHECKING
|
|
31
|
+
|
|
32
|
+
if TYPE_CHECKING:
|
|
33
|
+
from moat.util import CfgStore
|
|
34
|
+
|
|
35
|
+
from typing import Any
|
|
36
|
+
|
|
37
|
+
logger = logging.getLogger(__name__)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@click.group(short_help="Save MoaT-Link state to files.")
|
|
41
|
+
@click.pass_context
|
|
42
|
+
async def cli(ctx) -> None:
|
|
43
|
+
"""
|
|
44
|
+
Record MoaT-Link state to files, like a server's ``save`` setup,
|
|
45
|
+
but from a separate process.
|
|
46
|
+
|
|
47
|
+
The data source is a MoaT-Link server (default) or the MQTT
|
|
48
|
+
backend itself; the settings live in the ``link.save`` config
|
|
49
|
+
subtree, command-line options override them.
|
|
50
|
+
"""
|
|
51
|
+
ctx.obj.save_link_cfg = ctx.obj.cfg["link"]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _save_cfg(source: str | None, **kw: Any) -> SaveCfg:
|
|
55
|
+
"""Build the recorder's save config: ``link.save`` plus CLI overrides.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
source: ``"backend"`` to record from the backend; ``None`` uses
|
|
59
|
+
the config's ``link.save.source`` (default: a server).
|
|
60
|
+
kw: Config overrides; ``NotGiven`` and ``None`` values are
|
|
61
|
+
skipped — only options actually given override the config.
|
|
62
|
+
"""
|
|
63
|
+
if source is not None:
|
|
64
|
+
kw["source"] = source
|
|
65
|
+
item = {k: v for k, v in kw.items() if v is not NotGiven and v is not None}
|
|
66
|
+
return make_cfg(item)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _source_factory(scfg: SaveCfg, link_cfg: CfgStore, prefix: Path):
|
|
70
|
+
"""Return a source factory for the recorder's config.
|
|
71
|
+
|
|
72
|
+
Every call yields a fresh source — a new connection per full
|
|
73
|
+
rotation, so no state leaks between the files' streams. The
|
|
74
|
+
connections are uniquely named (random suffixes): two processes
|
|
75
|
+
recording simultaneously, or a ``run`` recorder plus the ``snap``
|
|
76
|
+
timer, must not kick each other off the broker.
|
|
77
|
+
"""
|
|
78
|
+
if scfg.source == "backend":
|
|
79
|
+
|
|
80
|
+
def factory() -> BackendSource:
|
|
81
|
+
from moat.link.backend import get_backend # noqa: PLC0415
|
|
82
|
+
|
|
83
|
+
return BackendSource(
|
|
84
|
+
lambda: get_backend(link_cfg, name=f"save_{gen_ident(8)}"),
|
|
85
|
+
prefix=prefix,
|
|
86
|
+
run=scfg.run,
|
|
87
|
+
replay=scfg.replay,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
else:
|
|
91
|
+
|
|
92
|
+
def factory() -> ServerSource:
|
|
93
|
+
from moat.link.client import Link # noqa: PLC0415
|
|
94
|
+
|
|
95
|
+
# No name: a plain client connection with a random ID —
|
|
96
|
+
# not a server, and unique without a counter that would
|
|
97
|
+
# collide between processes.
|
|
98
|
+
return ServerSource(
|
|
99
|
+
lambda: Link(link_cfg),
|
|
100
|
+
prefix=prefix,
|
|
101
|
+
run=scfg.run,
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
return factory
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@cli.command("run")
|
|
108
|
+
@click.option(
|
|
109
|
+
"-b",
|
|
110
|
+
"--backend",
|
|
111
|
+
is_flag=True,
|
|
112
|
+
help="Record from the MQTT backend, not a server. Only retained data is recorded.",
|
|
113
|
+
)
|
|
114
|
+
@click.option(
|
|
115
|
+
"-d", "--dir", "dir_", type=click.Path(file_okay=False, writable=True), help="Save directory"
|
|
116
|
+
)
|
|
117
|
+
@click.option(
|
|
118
|
+
"-n",
|
|
119
|
+
"--name",
|
|
120
|
+
help="strftime pattern for the file names (default: link.save.name)",
|
|
121
|
+
)
|
|
122
|
+
@click.option("-i", "--interval", type=float, help="Rotation interval, seconds")
|
|
123
|
+
@click.option("-r", "--rewrite", type=int, help="Every n-th file is a full snapshot")
|
|
124
|
+
@click.option(
|
|
125
|
+
"--incr/--no-incr",
|
|
126
|
+
"incr",
|
|
127
|
+
default=None,
|
|
128
|
+
help="Record incremental update tails between full snapshots",
|
|
129
|
+
)
|
|
130
|
+
@click.option("--run/--no-run", "run_", default=None, help="Also record run.* (ephemeral) data")
|
|
131
|
+
@click.option("-p", "--prefix", type=P, default=Path(), help="Only record this subtree")
|
|
132
|
+
@click.option(
|
|
133
|
+
"-t",
|
|
134
|
+
"--time",
|
|
135
|
+
"duration",
|
|
136
|
+
type=float,
|
|
137
|
+
help="Stop after this many seconds (for testing; systemd sends the signal)",
|
|
138
|
+
)
|
|
139
|
+
@click.pass_obj
|
|
140
|
+
async def run_(
|
|
141
|
+
obj,
|
|
142
|
+
backend: bool,
|
|
143
|
+
dir_: str | None,
|
|
144
|
+
name: str | None,
|
|
145
|
+
interval: float | None,
|
|
146
|
+
rewrite: int | None,
|
|
147
|
+
incr: bool | None,
|
|
148
|
+
run_: bool | None,
|
|
149
|
+
prefix: Path,
|
|
150
|
+
duration: float | None,
|
|
151
|
+
) -> None:
|
|
152
|
+
"""Record MoaT-Link state to rotating files, until stopped.
|
|
153
|
+
|
|
154
|
+
This command is meant to run as a systemd service; SIGTERM stops
|
|
155
|
+
it (all files get their trailer, no update is lost). See the
|
|
156
|
+
moat-link-save package for the service units.
|
|
157
|
+
|
|
158
|
+
The initial snapshot starts immediately; the first file is
|
|
159
|
+
complete once its rotation is due (``interval``). A failed
|
|
160
|
+
snapshot is retried after a short delay; the old file keeps
|
|
161
|
+
recording meanwhile.
|
|
162
|
+
"""
|
|
163
|
+
from moat.util.systemd import as_service # noqa: PLC0415
|
|
164
|
+
|
|
165
|
+
scfg = _save_cfg(
|
|
166
|
+
"backend" if backend else None,
|
|
167
|
+
dir=dir_,
|
|
168
|
+
name=name,
|
|
169
|
+
interval=interval,
|
|
170
|
+
rewrite=rewrite,
|
|
171
|
+
incremental=incr,
|
|
172
|
+
run=run_,
|
|
173
|
+
)
|
|
174
|
+
saver = Saver(scfg, _source_factory(scfg, obj.save_link_cfg, prefix))
|
|
175
|
+
|
|
176
|
+
async with as_service(obj) as evt:
|
|
177
|
+
# The saver runs in the service's task group; a duration
|
|
178
|
+
# bounds the run (its cancellation is shielded through the
|
|
179
|
+
# cleanup, so every file is flushed and closed first).
|
|
180
|
+
done = anyio.Event()
|
|
181
|
+
# Fires on the first handover or the saver's end, whichever
|
|
182
|
+
# comes first: the saver may end before its first handover
|
|
183
|
+
# (a duration shorter than the first snapshot, or a failing
|
|
184
|
+
# source). ``saver.ready`` keeps meaning "first handover";
|
|
185
|
+
# ``saver.fn`` tells the two apart.
|
|
186
|
+
first = anyio.Event()
|
|
187
|
+
|
|
188
|
+
async def run_saver(*, task_status=anyio.TASK_STATUS_IGNORED) -> None:
|
|
189
|
+
try:
|
|
190
|
+
with anyio.move_on_after(duration) if duration is not None else nullcontext():
|
|
191
|
+
await saver.run(task_status=task_status)
|
|
192
|
+
finally:
|
|
193
|
+
first.set()
|
|
194
|
+
done.set()
|
|
195
|
+
|
|
196
|
+
async def handover_watch() -> None:
|
|
197
|
+
await saver.ready.wait()
|
|
198
|
+
first.set()
|
|
199
|
+
|
|
200
|
+
await evt.tg.start(run_saver)
|
|
201
|
+
evt.tg.start_soon(handover_watch)
|
|
202
|
+
# Report ready only after the first snapshot completed: a
|
|
203
|
+
# failing first snapshot (retried in the background) must not
|
|
204
|
+
# look like a started recorder. TimeoutSec bounds the wait.
|
|
205
|
+
await first.wait()
|
|
206
|
+
if saver.fn is None:
|
|
207
|
+
# The saver ended before the first handover: no READY=1.
|
|
208
|
+
# The process exits; systemd reports a failed start
|
|
209
|
+
# (Type=notify) — a stopped-before-ready service is not
|
|
210
|
+
# "running". The warning names the reason in the journal.
|
|
211
|
+
logger.warning("The recorder ended before its first snapshot completed.")
|
|
212
|
+
return
|
|
213
|
+
evt.set()
|
|
214
|
+
await done.wait()
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
@cli.command("snap")
|
|
218
|
+
@click.option(
|
|
219
|
+
"-b",
|
|
220
|
+
"--backend",
|
|
221
|
+
is_flag=True,
|
|
222
|
+
help="Snapshot from the MQTT backend, not a server. Only retained data is recorded.",
|
|
223
|
+
)
|
|
224
|
+
@click.option(
|
|
225
|
+
"-d",
|
|
226
|
+
"--dir",
|
|
227
|
+
"dir_",
|
|
228
|
+
type=click.Path(file_okay=False, writable=True),
|
|
229
|
+
help="Snapshot into this directory (with --name)",
|
|
230
|
+
)
|
|
231
|
+
@click.option(
|
|
232
|
+
"-n",
|
|
233
|
+
"--name",
|
|
234
|
+
help="strftime pattern for the file name (with --dir), e.g. %Y-%m-%d.moat",
|
|
235
|
+
)
|
|
236
|
+
@click.option("-p", "--prefix", type=P, default=Path(), help="Only snapshot this subtree")
|
|
237
|
+
@click.option("--run/--no-run", "run_", default=None, help="Also snapshot run.* (ephemeral) data")
|
|
238
|
+
@click.option(
|
|
239
|
+
"-t",
|
|
240
|
+
"--time",
|
|
241
|
+
"duration",
|
|
242
|
+
type=float,
|
|
243
|
+
default=None,
|
|
244
|
+
help="Fail if the snapshot takes longer than this, seconds",
|
|
245
|
+
)
|
|
246
|
+
@click.argument("file", type=click.Path(writable=True, allow_dash=False), required=False)
|
|
247
|
+
@click.pass_obj
|
|
248
|
+
async def snap(
|
|
249
|
+
obj,
|
|
250
|
+
backend: bool,
|
|
251
|
+
dir_: str | None,
|
|
252
|
+
name: str | None,
|
|
253
|
+
prefix: Path,
|
|
254
|
+
run_: bool | None,
|
|
255
|
+
duration: float | None,
|
|
256
|
+
file: str | None,
|
|
257
|
+
) -> None:
|
|
258
|
+
"""Write a one-shot full snapshot of the current state to FILE.
|
|
259
|
+
|
|
260
|
+
The file has the same format as the recorder's full files; a
|
|
261
|
+
server can load it (``moat link server --load``). FILE may
|
|
262
|
+
contain strftime patterns (e.g. ``%Y-%m-%d.moat``), expanded with
|
|
263
|
+
the time (local or UTC, per ``link.save.use_local_time``) — so a
|
|
264
|
+
systemd timer can write dated snapshots
|
|
265
|
+
(``moat link save snap /var/lib/moat/link/snapshot/%%Y-%%m-%%d.moat``
|
|
266
|
+
— systemd needs doubled percent signs).
|
|
267
|
+
|
|
268
|
+
Alternatively, ``--dir DIR --name PATTERN`` names the target by
|
|
269
|
+
the same strftime rules — DIR/PATTERN expanded — so a timer's
|
|
270
|
+
unit reads like the recorder's configuration. Exactly one of
|
|
271
|
+
FILE or --name must be given.
|
|
272
|
+
|
|
273
|
+
The file is written to ``FILE.tmp`` and renamed on success: a
|
|
274
|
+
failed snapshot (timeout, connection loss) never leaves a
|
|
275
|
+
partial file at the target name, and a previous snapshot stays.
|
|
276
|
+
|
|
277
|
+
Use this for backups or as a systemd timer unit; for continuous
|
|
278
|
+
recording use ``moat link save run``.
|
|
279
|
+
"""
|
|
280
|
+
if name is not None:
|
|
281
|
+
if file is not None:
|
|
282
|
+
raise click.UsageError("Pass either a FILE argument or --name, not both")
|
|
283
|
+
if dir_ is None:
|
|
284
|
+
raise click.UsageError("--name needs --dir (or pass a FILE argument)")
|
|
285
|
+
file = str(FSPath(dir_) / name)
|
|
286
|
+
elif file is None:
|
|
287
|
+
raise click.UsageError("Pass a FILE argument (or --dir and --name)")
|
|
288
|
+
|
|
289
|
+
scfg = _save_cfg(
|
|
290
|
+
"backend" if backend else None,
|
|
291
|
+
run=run_,
|
|
292
|
+
)
|
|
293
|
+
# strftime patterns: expanded like the rotating files' names
|
|
294
|
+
if "%" in file:
|
|
295
|
+
now = datetime.fromtimestamp(mtime.time(), UTC)
|
|
296
|
+
if scfg.use_local_time:
|
|
297
|
+
now = now.astimezone()
|
|
298
|
+
file = now.strftime(file)
|
|
299
|
+
|
|
300
|
+
from .writer import StreamWriter # noqa: PLC0415
|
|
301
|
+
|
|
302
|
+
src = await _source_factory(scfg, obj.save_link_cfg, prefix)().start(updates=False)
|
|
303
|
+
|
|
304
|
+
# Write to a temporary file; rename only on success — a failed
|
|
305
|
+
# snapshot must not clobber a previous one.
|
|
306
|
+
p = FSPath(file)
|
|
307
|
+
tmp = p.with_name(p.name + ".tmp")
|
|
308
|
+
await anyio.Path(tmp.parent).mkdir(parents=True, exist_ok=True)
|
|
309
|
+
try:
|
|
310
|
+
# The stored name is the final one, not the temporary file's
|
|
311
|
+
w = StreamWriter(str(tmp), run=scfg.run, name=file)
|
|
312
|
+
async with w:
|
|
313
|
+
with anyio.fail_after(duration) if duration is not None else nullcontext():
|
|
314
|
+
await w.write_header(mode="full", state=None)
|
|
315
|
+
await w.write_snapshot(src)
|
|
316
|
+
# The change tag closes the snapshot phase; a loader
|
|
317
|
+
# expects it before the file's end.
|
|
318
|
+
await w.write_change()
|
|
319
|
+
await w.stop()
|
|
320
|
+
await anyio.Path(tmp).replace(p)
|
|
321
|
+
finally:
|
|
322
|
+
# Leave no partial file behind; a crash may leave ``FILE.tmp``
|
|
323
|
+
# (the next run overwrites it).
|
|
324
|
+
t = anyio.Path(tmp)
|
|
325
|
+
if await t.exists():
|
|
326
|
+
await t.unlink()
|
|
327
|
+
await src.aclose()
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
@cli.command("cfg")
|
|
331
|
+
@attr_args(par_name="Config item")
|
|
332
|
+
@click.pass_obj
|
|
333
|
+
async def cfg_(obj, **upd: Any) -> None:
|
|
334
|
+
"""Show or update a running server's save configuration.
|
|
335
|
+
|
|
336
|
+
Without options, the server's effective ``link.server.save``
|
|
337
|
+
configuration is printed. With ``-s key value`` arguments the
|
|
338
|
+
changes are sent to the server: it combines them with its current
|
|
339
|
+
configuration and rotates its saver onto the result — a full
|
|
340
|
+
rotation, so no update is lost. An empty ``dir`` stops saving.
|
|
341
|
+
|
|
342
|
+
The global ``moat link -s NAME`` picks the server; this command
|
|
343
|
+
needs a running one.
|
|
344
|
+
"""
|
|
345
|
+
from moat.util import yprint # noqa: PLC0415
|
|
346
|
+
from moat.link.client import Link # noqa: PLC0415
|
|
347
|
+
|
|
348
|
+
upd_ = any(upd.values())
|
|
349
|
+
async with Link(obj.save_link_cfg) as conn:
|
|
350
|
+
try:
|
|
351
|
+
if upd_:
|
|
352
|
+
# The `-s` (and friends) arguments form the changes mapping
|
|
353
|
+
changes = process_args({}, **upd)
|
|
354
|
+
res = await conn.cmd(P("s.cfg"), cfg=changes)
|
|
355
|
+
else:
|
|
356
|
+
res = await conn.cmd(P("s.cfg"))
|
|
357
|
+
except KeyError:
|
|
358
|
+
print("Command unknown. Pre-0.9 server?", file=sys.stderr)
|
|
359
|
+
sys.exit(1)
|
|
360
|
+
else:
|
|
361
|
+
yprint(res.kw, stream=obj.stdout)
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
_path: !P :n.moat.link.save
|
|
2
|
+
version: 1
|
|
3
|
+
---
|
|
4
|
+
_path: !P _.save.data
|
|
5
|
+
title: Save file entry, except for the first and last item
|
|
6
|
+
type: array
|
|
7
|
+
prefixItems:
|
|
8
|
+
- type: integer
|
|
9
|
+
title: Path prefix
|
|
10
|
+
description: The first n items in the previous entry's path atr prepended to this entry's path
|
|
11
|
+
- type: array
|
|
12
|
+
$ref: _.path
|
|
13
|
+
- title: Data
|
|
14
|
+
- type: array
|
|
15
|
+
$ref: _.meta
|
|
16
|
+
---
|
|
17
|
+
_path: !P _.save.header
|
|
18
|
+
type: object
|
|
19
|
+
title: Saved-file and Data dump transmission header+trailer
|
|
20
|
+
properties:
|
|
21
|
+
root:
|
|
22
|
+
title: base directory
|
|
23
|
+
$ref: _.path
|
|
24
|
+
timestamp:
|
|
25
|
+
type: number
|
|
26
|
+
title: the file contains changes logged after this time
|
|
27
|
+
prev:
|
|
28
|
+
type: string
|
|
29
|
+
title: Previous savefile
|
|
30
|
+
description: Written after switching to @next
|
|
31
|
+
next:
|
|
32
|
+
type: string
|
|
33
|
+
title: Next savefile
|
|
34
|
+
description: replaces
|
|
35
|
+
sup:
|
|
36
|
+
type: string
|
|
37
|
+
title: Name of the savefile this one supersedes
|
|
38
|
+
description: also read @sup if @prev is incomplete
|
|
39
|
+
level:
|
|
40
|
+
type: integer
|
|
41
|
+
title: Save level of this file
|
|
42
|
+
|
|
43
|
+
required:
|
|
44
|
+
- root
|
|
45
|
+
- timestamp
|
|
46
|
+
- level
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Structural interface for a server whose state is saved.
|
|
3
|
+
|
|
4
|
+
The save package must not import :mod:`moat.link.server` (which imports
|
|
5
|
+
the save package back), so :class:`LocalSource` uses this protocol to
|
|
6
|
+
describe what it needs from a server.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import TYPE_CHECKING, Protocol
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from moat.lib.broadcast import Broadcaster
|
|
15
|
+
from moat.link.node import Node
|
|
16
|
+
|
|
17
|
+
__all__ = ["ServerLike"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ServerLike(Protocol):
|
|
21
|
+
"""The parts of a :class:`~moat.link.server.Server` a source needs."""
|
|
22
|
+
|
|
23
|
+
write_monitor: Broadcaster
|
|
24
|
+
data: Node
|
|
25
|
+
rdata: Node
|
moat/link/save/cfg.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Configuration model for saving MoaT-Link state to files.
|
|
3
|
+
|
|
4
|
+
The model is built from the package defaults (``_cfg.yaml``, registered
|
|
5
|
+
as ``link.save``) combined with an override mapping — either the
|
|
6
|
+
server's ``link.server.save`` subtree or the recorder's command line /
|
|
7
|
+
config. Loading it from — and watching it in — MoaT-Link is follow-up
|
|
8
|
+
issue moat-cbwy.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from pathlib import PurePath
|
|
14
|
+
|
|
15
|
+
from pydantic import BeforeValidator, Field
|
|
16
|
+
|
|
17
|
+
from moat.util import NotGiven, attrdict, combine_dict
|
|
18
|
+
from moat.lib.config import CFG
|
|
19
|
+
from moat.lib.config.base import BaseModel
|
|
20
|
+
|
|
21
|
+
from collections.abc import Mapping
|
|
22
|
+
from typing import TYPE_CHECKING, Annotated, Literal
|
|
23
|
+
|
|
24
|
+
if TYPE_CHECKING:
|
|
25
|
+
from types import EllipsisType
|
|
26
|
+
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
__all__ = ["ReplayCfg", "SaveCfg", "defaults", "make_cfg"]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _to_str(value: object) -> object:
|
|
33
|
+
"""Accept path objects for string config fields."""
|
|
34
|
+
if isinstance(value, PurePath):
|
|
35
|
+
return str(value)
|
|
36
|
+
return value
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
_Str = Annotated[str, BeforeValidator(_to_str)]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class ReplayCfg(BaseModel):
|
|
43
|
+
"""Tunables for detecting the end of a retained-message replay.
|
|
44
|
+
|
|
45
|
+
The backend source's "snapshot" is the retained-message replay on its
|
|
46
|
+
MQTT subscription, which has no end-of-replay marker. These
|
|
47
|
+
heuristics decide when the replay is (believed to be) over: no
|
|
48
|
+
*recorded* message for *quiet* seconds (the burst is over), or
|
|
49
|
+
the message rate dropping well below its peak for *quiet* seconds
|
|
50
|
+
while the recent messages are live (metadata timestamps within
|
|
51
|
+
*skew* of wall clock, and/or not marked as retained — traffic
|
|
52
|
+
continues, but the flood is over), or *max* seconds passed.
|
|
53
|
+
|
|
54
|
+
Ending the snapshot early does not lose data: the subscription stays
|
|
55
|
+
open, late replay messages are written after the new file's change
|
|
56
|
+
tag.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
first: float = Field(
|
|
60
|
+
default=..., description="Bound for the first message (empty-subtree bound), seconds"
|
|
61
|
+
)
|
|
62
|
+
quiet: float = Field(default=..., description="Quiet seconds that end the replay")
|
|
63
|
+
frac: float = Field(default=..., description="Peak fraction below which traffic is low")
|
|
64
|
+
skew: float = Field(default=..., description="Timestamp tolerance, seconds")
|
|
65
|
+
max: float = Field(default=..., description="Hard upper bound of the replay, seconds")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class SaveCfg(BaseModel):
|
|
69
|
+
"""How MoaT-Link state is saved to files.
|
|
70
|
+
|
|
71
|
+
The default values live in ``_cfg.yaml`` (the ``link.save`` config
|
|
72
|
+
subtree); the field definitions here only declare types and
|
|
73
|
+
constraints, so there is exactly one source of default *values*.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
dir: Directory to store the state files in.
|
|
77
|
+
name: strftime pattern for the file names.
|
|
78
|
+
interval: Rotation interval, seconds.
|
|
79
|
+
rewrite: Every *n*-th file is a full snapshot.
|
|
80
|
+
errors: Number of consecutive error files to keep.
|
|
81
|
+
use_local_time: Use local time instead of UTC in file names.
|
|
82
|
+
incremental: If false, only write snapshots, no update tails.
|
|
83
|
+
keep: Retention policy; see the savefile documentation.
|
|
84
|
+
run: Also save ``run.*`` (non-retained, ephemeral) data.
|
|
85
|
+
source: Where a recorder takes its data from: ``server`` or
|
|
86
|
+
``backend``. Not used by the server (which reads its own state).
|
|
87
|
+
replay: Tunables for the backend recorder's replay-end heuristics.
|
|
88
|
+
load_dir: Directory to restore the state from at startup; the
|
|
89
|
+
default (``None``) restores from ``dir``. Server-only: the
|
|
90
|
+
recorder never restores.
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
dir: _Str = Field(default=..., description="Directory to store the state files in")
|
|
94
|
+
name: _Str = Field(default=..., description="strftime pattern for the file names")
|
|
95
|
+
interval: float = Field(default=..., description="Rotation interval, seconds")
|
|
96
|
+
rewrite: int = Field(default=..., description="Every n-th file is a full snapshot")
|
|
97
|
+
errors: int = Field(default=..., description="Number of consecutive error files to keep")
|
|
98
|
+
use_local_time: bool = Field(
|
|
99
|
+
default=..., description="Use local time instead of UTC in file names"
|
|
100
|
+
)
|
|
101
|
+
incremental: bool = Field(
|
|
102
|
+
default=..., description="If false, only write snapshots, no update tails"
|
|
103
|
+
)
|
|
104
|
+
keep: list[int | str] = Field(
|
|
105
|
+
default=..., description="Retention policy; see the savefile documentation"
|
|
106
|
+
)
|
|
107
|
+
run: bool = Field(default=..., description="Also save run.* data")
|
|
108
|
+
source: Literal["server", "backend"] | None = Field(
|
|
109
|
+
default=..., description="Where a recorder takes its data from"
|
|
110
|
+
)
|
|
111
|
+
replay: ReplayCfg = Field(default=..., description="Replay-end heuristics")
|
|
112
|
+
load_dir: _Str | None = Field(
|
|
113
|
+
default=...,
|
|
114
|
+
description="Directory to restore state from at startup; default: dir",
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def defaults() -> attrdict:
|
|
119
|
+
"""Return the effective defaults for ``link.save``.
|
|
120
|
+
|
|
121
|
+
The package's ``_cfg.yaml`` defaults are merged with the user's
|
|
122
|
+
``link.save`` subtree from the config store, user values winning.
|
|
123
|
+
"""
|
|
124
|
+
CFG.with_("moat.link.save")
|
|
125
|
+
return attrdict(CFG.moat.link.save)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def make_cfg(item: Any = NotGiven, *, base: Mapping | EllipsisType | None = NotGiven) -> SaveCfg:
|
|
129
|
+
"""
|
|
130
|
+
Build the save configuration from defaults plus an override mapping.
|
|
131
|
+
|
|
132
|
+
Args:
|
|
133
|
+
item: Overrides; a mapping (e.g. the server's ``link.server.save``
|
|
134
|
+
subtree), or ``NotGiven`` / ``None`` for defaults only.
|
|
135
|
+
base: The base defaults to combine over. The default is the
|
|
136
|
+
package's ``link.save`` subtree (recorder defaults); ``None``
|
|
137
|
+
uses the item as-is — for callers whose *item* already
|
|
138
|
+
carries its own defaults (e.g. the server's
|
|
139
|
+
``link.server.save``, whose base values come from the server
|
|
140
|
+
package's ``_cfg.yaml``).
|
|
141
|
+
"""
|
|
142
|
+
if base is NotGiven:
|
|
143
|
+
base = defaults()
|
|
144
|
+
if item is NotGiven or item is None:
|
|
145
|
+
data: Mapping | None = base
|
|
146
|
+
elif isinstance(item, Mapping):
|
|
147
|
+
data = combine_dict(item, base, cls=attrdict) if base is not None else dict(item)
|
|
148
|
+
else:
|
|
149
|
+
raise TypeError(f"Config item is not a mapping: {item!r}")
|
|
150
|
+
assert data is not None, "no config data"
|
|
151
|
+
return SaveCfg.model_validate(data)
|