@vibelord/lanes 1.7.3 → 1.7.5
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.
- package/README.md +9 -0
- package/package.json +1 -1
- package/payload/lanes/VERSION +1 -1
- package/payload/lanes/bin/lanes +128 -24
- package/payload/lanes/bin/lanes-site-serve +15 -0
- package/payload/lanes/bin-rs/BINARIES.json +5 -0
- package/payload/lanes/container/lane-mcp +108 -5
- package/payload/lanes/container/lane_core.py +116 -0
- package/payload/lanes/container/throttle-pulse +159 -14
- package/payload/lanes/docs/ARCHITECTURE.md +132 -13
- package/payload/lanes/docs/DESIGN.md +10 -8
- package/payload/lanes/docs/INSTALL.md +1 -1
- package/payload/lanes/docs/RUNBOOK.md +436 -8
- package/payload/lanes/docs/USERGUIDE.md +82 -9
- package/payload/lanes/install/host-install.sh +35 -4
- package/payload/lanes/libexec/adopt.py +364 -0
- package/payload/lanes/libexec/attach.py +35 -5
- package/payload/lanes/libexec/cutover.py +656 -0
- package/payload/lanes/libexec/docsd.py +12 -8
- package/payload/lanes/libexec/doctor_lanes2.py +284 -0
- package/payload/lanes/libexec/economy_poll.py +87 -2
- package/payload/lanes/libexec/gc_unregistered.py +407 -0
- package/payload/lanes/libexec/lanes_lib.py +474 -2
- package/payload/lanes/libexec/native.sh +38 -0
- package/payload/lanes/libexec/native_bin.py +670 -0
- package/payload/lanes/libexec/session_actions.py +85 -7
- package/payload/lanes/libexec/shadow.py +1311 -0
- package/payload/lanes/libexec/sidebar.py +252 -30
- package/payload/lanes/libexec/sidebar_status.py +373 -25
- package/payload/lanes/libexec/statusd.py +67 -3
- package/payload/lanes/libexec/tokens.py +99 -131
- package/payload/lanes/libexec/tokens.sh +1 -1
- package/payload/lanes/libexec/update.py +78 -8
- package/payload/lanes/libexec/users.py +282 -0
- package/payload/lanes/site/README.md +9 -0
- package/payload/lanes/site/conformance.py +280 -0
- package/payload/lanes/site/protocol.py +368 -0
- package/payload/lanes/site/server.py +314 -0
- package/payload/lanes/systemd/lanes-gc.service +1 -1
- package/payload/lanes/systemd/lanes-gc.timer +14 -3
- package/payload/lanes/tokens/README.md +156 -0
- package/payload/lanes/tokens/generate.py +930 -0
- package/payload/lanes/tokens/generated/parity.v1.tsv +489 -0
- package/payload/lanes/tokens/generated/tokens.resolved.json +835 -0
- package/payload/lanes/tokens/tokens.v1.json +763 -0
- package/payload/lanes/tokens/tokens.v1.schema.json +143 -0
- package/payload/lanes/web/Caddyfile +11 -0
- package/payload/lanes/web/README.md +253 -4
- package/payload/lanes/web/directory.css +95 -0
- package/payload/lanes/web/directory.js +951 -0
- package/payload/lanes/web/generated/README.md +107 -0
- package/payload/lanes/web/generated/lanes2_protocol.d.mts +1162 -0
- package/payload/lanes/web/generated/lanes2_protocol.mjs +2333 -0
- package/payload/lanes/web/inbox.js +1140 -0
- package/payload/lanes/web/mobile.js +35 -45
- package/payload/lanes/web/tokens.css +137 -0
- package/payload/manifest.json +7 -4
|
@@ -0,0 +1,656 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""cutover.py — the Python half of the Lanes 2.0 per-domain cutover (Rust runtime specification §17.1; lanes2 Round 1
|
|
3
|
+
H3, BEY-6988). Nothing calls it yet: no domain has cut over, every `LANES_RS_*` flag is off, and the Python host keeps
|
|
4
|
+
owning everything exactly as before.
|
|
5
|
+
|
|
6
|
+
cutover.py status [DOMAIN…] [--json] every domain's record under $LANES_STATE/cutover/
|
|
7
|
+
cutover.py check DOMAIN --holder H --schema N [--admit] [--legacy L]
|
|
8
|
+
may this binary own DOMAIN (with --admit: admit new work
|
|
9
|
+
or start a new effect in it now)? exit 0 yes, 3 no
|
|
10
|
+
cutover.py rollback DOMAIN --to H --schema N abort a fence that has not committed its epoch, handing
|
|
11
|
+
the domain back to its fenced owner H; exit 3 otherwise
|
|
12
|
+
cutover.py forward SPOOL INTAKE --endpoint ID [--limit N] [--json]
|
|
13
|
+
durable forwarding of committed legacy envelopes
|
|
14
|
+
cutover.py retire ENDPOINT --census FILE [--json] a retirement proof; exit 3 while a producer names ENDPOINT
|
|
15
|
+
|
|
16
|
+
THE RECORD, AND THE ONE JOURNAL OF RECORD. One state domain's ownership, `lanes.cutover/1`, one line of canonical
|
|
17
|
+
JSON at $LANES_STATE/cutover/<domain>.json, byte for byte what the Rust fence renders
|
|
18
|
+
(`crates/lanes-runtime/src/cutover/record.rs`; golden line `crates/lanes-runtime/src/cutover/fence-record.v1.golden.json`):
|
|
19
|
+
|
|
20
|
+
{"v":1,"kind":"lanes.cutover/1","domain":"attention","phase":"active","epoch":2,"owner":"lanes-rs",
|
|
21
|
+
"previous":"lanes-py","schema":3,"fenced_through":17}
|
|
22
|
+
|
|
23
|
+
Keys in exactly that order, no whitespace, one final newline. `owner` owns the domain at `epoch` (it only increases,
|
|
24
|
+
and increases when ownership moves); `schema` is the schema epoch a runtime must read to own the domain; the phase is
|
|
25
|
+
shadow, prepared, quiesced, drained, cut_verified, epoch_committed, active or rolled_back; `fenced_through` is the old
|
|
26
|
+
owner's sealed watermark (at most 2^53-1). A record that is not in the canonical form is refused (`record_malformed`)
|
|
27
|
+
and never read as absent: an old binary that cannot read the record does not own the domain. This file is the single
|
|
28
|
+
journal of record: the Rust fence (`cutover/journal.rs` FileJournal) and this script read it and compare-and-swap it
|
|
29
|
+
with the same protocol, and no store keeps a second copy that decides ownership. A writer holds an exclusive flock on
|
|
30
|
+
<domain>.lock, compares the stored record with the one it read, writes a fresh temporary, fsyncs it, renames it over
|
|
31
|
+
the record and fsyncs the directory; a directory it creates is fsynced into its parent first.
|
|
32
|
+
|
|
33
|
+
THE REFUSING OLD BINARY. `may_own` refuses `schema_ahead` when this binary reads a lower schema than the active one
|
|
34
|
+
(first, whoever the record names), then `owned_elsewhere`; `may_admit` adds `fenced` for every phase between the fence
|
|
35
|
+
and activation (quiesced, drained, cut_verified, epoch_committed): the recorded owner admits only in shadow and prepared
|
|
36
|
+
(the old owner before the fence), active (the owner that took the domain through a fence: the candidate, or a rollback
|
|
37
|
+
target through the reverse fence) and rolled_back (a fence aborted before its epoch commit; its owner owns again). No
|
|
38
|
+
record means no cutover has started: the legacy owner (`--legacy`, default `lanes-py`) owns the domain as it always
|
|
39
|
+
has, and every other holder is `owned_elsewhere`.
|
|
40
|
+
|
|
41
|
+
ROLLBACK. `rollback` aborts a fence that has not committed its epoch (quiesced, drained, cut_verified): the fenced owner
|
|
42
|
+
never stopped owning and its custody is complete, so the record hands the domain back to it (`--to` must name it,
|
|
43
|
+
`rollback_not_owner` otherwise) at the next epoch as rolled_back, with no seal; the owner resumes when it reads that.
|
|
44
|
+
An owner that committed its epoch (epoch_committed, active) may have accepted and executed work: only the Rust reverse
|
|
45
|
+
fence (`rollback_plan` + `DomainFence`) takes the domain from it, quiescing, draining and sealing it and making its
|
|
46
|
+
final cut durable in the target's store first, so this script refuses (`rollback_needs_fence`), and a stale snapshot is
|
|
47
|
+
never the recovery source. A release that cannot read the active schema is refused (`no_compatible_runtime`).
|
|
48
|
+
|
|
49
|
+
LEGACY ENDPOINTS. Native sessions and their hook configuration survive the cutover on purpose, so a lane started
|
|
50
|
+
before it keeps publishing where its configuration says. `plan_endpoints` retires an endpoint only with proof, keeps a
|
|
51
|
+
socket or state file (the candidate serves it in place) and forwards a spool, and refuses a census producer whose
|
|
52
|
+
endpoint is not inventoried (`endpoint_live_not_planned`); `check_activation` re-proves the plan against the census.
|
|
53
|
+
`forward` is the durable forwarding protocol for a legacy no-replace spool: every committed envelope (never a `.`
|
|
54
|
+
temporary, never a link, fifo or other special file) is linked into INTAKE/<endpoint>/<name> under a fresh temporary
|
|
55
|
+
— a hard link never replaces a name, and a filesystem without hard links refuses instead of falling back to
|
|
56
|
+
check-then-rename — the intake directory is fsynced, and only then is the legacy file removed. An envelope already in
|
|
57
|
+
the intake with the same bytes is a duplicate (also released); different bytes are a conflict (both kept, reported); a
|
|
58
|
+
release that fails is `release_failed:<errno>` (kept, retried next pass) and the pass goes on. Every result carries
|
|
59
|
+
`across_cutover`: its causal order relative to the final cut is unknown. The candidate's SourceEventId deduplication
|
|
60
|
+
makes every retry one custody result (an envelope without an event id is keyed `legacy:<endpoint>/<name>:<digest of
|
|
61
|
+
its bytes>`). `forward` runs on every pass of the rollback window, not once at activation; `pump` forwards every
|
|
62
|
+
forwarded endpoint of the plan and never reads or releases a kept one. `forward` exits 1 on any `conflict`,
|
|
63
|
+
`refused:*` or `release_failed:*`; `skipped:not_regular` is reported and does not fail the pass.
|
|
64
|
+
|
|
65
|
+
`retire` proves an endpoint unused from the producer census only — every live native generation and every installed
|
|
66
|
+
hook configuration that names it (`[{"kind": "generation"|"configuration", "endpoint": ID, ...}]`). An empty endpoint
|
|
67
|
+
directory is not evidence: a publisher paused just before its envelope commit has no committed file yet.
|
|
68
|
+
"""
|
|
69
|
+
import argparse
|
|
70
|
+
import errno
|
|
71
|
+
import fcntl
|
|
72
|
+
import json
|
|
73
|
+
import os
|
|
74
|
+
import re
|
|
75
|
+
import secrets
|
|
76
|
+
import stat
|
|
77
|
+
import sys
|
|
78
|
+
from pathlib import Path
|
|
79
|
+
|
|
80
|
+
STATE = Path(os.environ.get('LANES_STATE', Path.home() / '.local/state/lanes'))
|
|
81
|
+
KIND = 'lanes.cutover/1'
|
|
82
|
+
RETIREMENT_KIND = 'lanes.cutover.retirement/1'
|
|
83
|
+
FIELDS = ('v', 'kind', 'domain', 'phase', 'epoch', 'owner', 'previous', 'schema', 'fenced_through')
|
|
84
|
+
PHASES = ('shadow', 'prepared', 'quiesced', 'drained', 'cut_verified', 'epoch_committed', 'active', 'rolled_back')
|
|
85
|
+
ADMITTING = frozenset({'shadow', 'prepared', 'active', 'rolled_back'})
|
|
86
|
+
ROLLBACK_FROM = frozenset({'quiesced', 'drained', 'cut_verified'}) # rollback.rs ABORTABLE: fenced, epoch uncommitted
|
|
87
|
+
COMMITTED = frozenset({'epoch_committed', 'active'}) # only the reverse fence takes these back
|
|
88
|
+
LEGACY_OWNER = 'lanes-py' # who owns a domain with no record
|
|
89
|
+
DOMAIN_RE = re.compile(r'[a-z][a-z0-9-]{0,31}\Z') # domain.rs StateDomain
|
|
90
|
+
TOKEN_RE = re.compile(r'[A-Za-z0-9_][A-Za-z0-9_.:-]{0,127}\Z') # lanes_core Token (HostInstanceId)
|
|
91
|
+
ENDPOINT_RE = re.compile(r'[a-z0-9][a-z0-9._-]{0,63}\Z') # legacy.rs EndpointId
|
|
92
|
+
COUNTER_MAX = (1 << 53) - 1 # lanes_core COUNTER_MAX
|
|
93
|
+
SCHEMA_MAX = (1 << 32) - 1 # SchemaEpoch is a u32
|
|
94
|
+
WATERMARK_MAX = COUNTER_MAX # record.rs FENCED_THROUGH_MAX
|
|
95
|
+
RECORD_MAX = 1024 # record.rs RECORD_MAX_BYTES
|
|
96
|
+
ENVELOPE_MAX = 256 * 1024
|
|
97
|
+
FORWARD_BATCH = 64 # legacy.rs FORWARD_BATCH
|
|
98
|
+
PRODUCER_KINDS = frozenset({'generation', 'configuration'})
|
|
99
|
+
EXIT_REFUSED = 3
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class Refused(Exception):
|
|
103
|
+
"""A refusal with a stable code (the same words the Rust side uses)."""
|
|
104
|
+
|
|
105
|
+
def __init__(self, code, detail=''):
|
|
106
|
+
super().__init__(f'{code}: {detail}' if detail else code)
|
|
107
|
+
self.code = code
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# ---------------------------------------------------------------- the record
|
|
111
|
+
|
|
112
|
+
def _is_int(value, low, high):
|
|
113
|
+
return isinstance(value, int) and not isinstance(value, bool) and low <= value <= high
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def render(record):
|
|
117
|
+
"""The canonical record line, newline-terminated."""
|
|
118
|
+
return json.dumps({field: record[field] for field in FIELDS}, separators=(',', ':'), ensure_ascii=True) + '\n'
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _no_duplicates(pairs):
|
|
122
|
+
keys = [key for key, _ in pairs]
|
|
123
|
+
if len(set(keys)) != len(keys):
|
|
124
|
+
raise Refused('record_malformed', 'a key repeats')
|
|
125
|
+
return dict(pairs)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def parse(text):
|
|
129
|
+
"""One canonical record line (the final newline optional) as a dict; anything else raises
|
|
130
|
+
Refused('record_malformed')."""
|
|
131
|
+
if len(text.encode('utf-8', 'surrogatepass')) > RECORD_MAX:
|
|
132
|
+
raise Refused('record_malformed', f'longer than {RECORD_MAX} bytes')
|
|
133
|
+
line = text[:-1] if text.endswith('\n') else text
|
|
134
|
+
try:
|
|
135
|
+
record = json.loads(line, object_pairs_hook=_no_duplicates)
|
|
136
|
+
except ValueError as error:
|
|
137
|
+
raise Refused('record_malformed', str(error)) from None
|
|
138
|
+
if not isinstance(record, dict) or tuple(record) != FIELDS:
|
|
139
|
+
raise Refused('record_malformed', 'the keys are not the canonical ones in order')
|
|
140
|
+
checks = (
|
|
141
|
+
('v', _is_int(record['v'], 1, 1)),
|
|
142
|
+
('kind', record['kind'] == KIND),
|
|
143
|
+
('domain', isinstance(record['domain'], str) and DOMAIN_RE.match(record['domain'])),
|
|
144
|
+
('phase', record['phase'] in PHASES),
|
|
145
|
+
('epoch', _is_int(record['epoch'], 1, COUNTER_MAX)),
|
|
146
|
+
('owner', isinstance(record['owner'], str) and TOKEN_RE.match(record['owner'])),
|
|
147
|
+
('previous', record['previous'] is None
|
|
148
|
+
or (isinstance(record['previous'], str) and TOKEN_RE.match(record['previous']))),
|
|
149
|
+
('schema', _is_int(record['schema'], 1, SCHEMA_MAX)),
|
|
150
|
+
('fenced_through', record['fenced_through'] is None or _is_int(record['fenced_through'], 0, WATERMARK_MAX)),
|
|
151
|
+
)
|
|
152
|
+
for field, valid in checks:
|
|
153
|
+
if not valid:
|
|
154
|
+
raise Refused('record_malformed', f'invalid {field}')
|
|
155
|
+
if render(record) != line + '\n':
|
|
156
|
+
raise Refused('record_malformed', 'not the canonical form')
|
|
157
|
+
return record
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def record_path(state, domain):
|
|
161
|
+
if not DOMAIN_RE.match(domain or ''):
|
|
162
|
+
raise Refused('domain_invalid', repr(domain))
|
|
163
|
+
return Path(state) / 'cutover' / f'{domain}.json'
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _read_text(path):
|
|
167
|
+
"""A regular file's text, never through a symbolic link, bounded; None when it does not exist."""
|
|
168
|
+
try:
|
|
169
|
+
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC)
|
|
170
|
+
except FileNotFoundError:
|
|
171
|
+
return None
|
|
172
|
+
except OSError as error:
|
|
173
|
+
raise Refused('record_unreadable', f'{path}: {error.strerror}') from None
|
|
174
|
+
try:
|
|
175
|
+
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
|
176
|
+
raise Refused('record_unreadable', f'{path} is not a regular file')
|
|
177
|
+
data = os.read(fd, RECORD_MAX + 1)
|
|
178
|
+
finally:
|
|
179
|
+
os.close(fd)
|
|
180
|
+
try:
|
|
181
|
+
return data.decode('utf-8')
|
|
182
|
+
except UnicodeDecodeError:
|
|
183
|
+
raise Refused('record_malformed', 'not UTF-8') from None
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def read_record(state, domain):
|
|
187
|
+
"""The domain's record, or None when no cutover has started. Unreadable or malformed raises Refused: never
|
|
188
|
+
treated as absent."""
|
|
189
|
+
text = _read_text(record_path(state, domain))
|
|
190
|
+
if text is None:
|
|
191
|
+
return None
|
|
192
|
+
record = parse(text)
|
|
193
|
+
# BEY-7053: match FileJournal::load_now; another domain's record is never ownership evidence for this one.
|
|
194
|
+
if record['domain'] != domain:
|
|
195
|
+
raise Refused('record_malformed', f"{domain}: record names domain {record['domain']}")
|
|
196
|
+
return record
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _fsync_dir(path):
|
|
200
|
+
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC)
|
|
201
|
+
try:
|
|
202
|
+
os.fsync(fd)
|
|
203
|
+
finally:
|
|
204
|
+
os.close(fd)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _private_dir(path):
|
|
208
|
+
"""Create (0700) or reuse `path` as a real directory, never through a symbolic link; a directory it creates is
|
|
209
|
+
fsynced into its parent before anything is written there."""
|
|
210
|
+
path = Path(path)
|
|
211
|
+
try:
|
|
212
|
+
os.mkdir(path, 0o700)
|
|
213
|
+
except FileExistsError:
|
|
214
|
+
pass
|
|
215
|
+
else:
|
|
216
|
+
_fsync_dir(path.parent)
|
|
217
|
+
if not stat.S_ISDIR(os.lstat(path).st_mode):
|
|
218
|
+
raise Refused('not_a_directory', str(path))
|
|
219
|
+
return path
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _make_dirs(path):
|
|
223
|
+
"""`path` and every missing ancestor as private directories, each made durable in its parent."""
|
|
224
|
+
path = Path(path)
|
|
225
|
+
missing = []
|
|
226
|
+
while not os.path.lexists(path):
|
|
227
|
+
missing.append(path)
|
|
228
|
+
if path.parent == path:
|
|
229
|
+
break
|
|
230
|
+
path = path.parent
|
|
231
|
+
for directory in reversed(missing):
|
|
232
|
+
_private_dir(directory)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def write_record(state, record, expected):
|
|
236
|
+
"""Compare-and-swap one domain's record: written only while the stored record equals `expected` (None: no record
|
|
237
|
+
yet) and the epoch does not go back. Raises Refused('journal_conflict') otherwise."""
|
|
238
|
+
record = parse(render(record))
|
|
239
|
+
path = record_path(state, record['domain'])
|
|
240
|
+
_make_dirs(state)
|
|
241
|
+
directory = _private_dir(path.parent)
|
|
242
|
+
lock_fd = os.open(directory / f"{record['domain']}.lock", os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC,
|
|
243
|
+
0o600)
|
|
244
|
+
try:
|
|
245
|
+
fcntl.flock(lock_fd, fcntl.LOCK_EX)
|
|
246
|
+
current = read_record(state, record['domain'])
|
|
247
|
+
if current != expected or (current is not None and record['epoch'] < current['epoch']):
|
|
248
|
+
raise Refused('journal_conflict', f"{record['domain']}: the stored record moved")
|
|
249
|
+
temp = directory / f".{record['domain']}.json.{os.getpid()}.{secrets.token_hex(4)}.tmp"
|
|
250
|
+
fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600)
|
|
251
|
+
try:
|
|
252
|
+
try:
|
|
253
|
+
remaining = memoryview(render(record).encode('ascii'))
|
|
254
|
+
while remaining:
|
|
255
|
+
written = os.write(fd, remaining)
|
|
256
|
+
if written == 0:
|
|
257
|
+
raise Refused('record_unwritable', 'record write made no progress')
|
|
258
|
+
remaining = remaining[written:]
|
|
259
|
+
os.fsync(fd)
|
|
260
|
+
finally:
|
|
261
|
+
os.close(fd)
|
|
262
|
+
os.replace(temp, path)
|
|
263
|
+
except BaseException:
|
|
264
|
+
try:
|
|
265
|
+
os.unlink(temp)
|
|
266
|
+
except OSError:
|
|
267
|
+
pass
|
|
268
|
+
raise
|
|
269
|
+
_fsync_dir(directory)
|
|
270
|
+
finally:
|
|
271
|
+
os.close(lock_fd)
|
|
272
|
+
return record
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def records(state, domains=()):
|
|
276
|
+
"""Every domain's record (or the named ones), sorted: {domain: record or Refused}."""
|
|
277
|
+
names = list(domains)
|
|
278
|
+
if not names:
|
|
279
|
+
try:
|
|
280
|
+
names = sorted(entry[:-5] for entry in os.listdir(Path(state) / 'cutover')
|
|
281
|
+
if entry.endswith('.json') and not entry.startswith('.'))
|
|
282
|
+
except FileNotFoundError:
|
|
283
|
+
names = []
|
|
284
|
+
out = {}
|
|
285
|
+
for name in names:
|
|
286
|
+
try:
|
|
287
|
+
out[name] = read_record(state, name)
|
|
288
|
+
except Refused as refused:
|
|
289
|
+
out[name] = refused
|
|
290
|
+
return out
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
# ---------------------------------------------------------------- ownership and rollback
|
|
294
|
+
|
|
295
|
+
def may_own(record, holder, readable, legacy=LEGACY_OWNER):
|
|
296
|
+
"""(True, 'ok' | 'no_cutover') or (False, 'schema_ahead' | 'owned_elsewhere'). With no record only the legacy
|
|
297
|
+
owner owns the domain."""
|
|
298
|
+
if record is None:
|
|
299
|
+
return (True, 'no_cutover') if holder == legacy else (False, 'owned_elsewhere')
|
|
300
|
+
if readable < record['schema']:
|
|
301
|
+
return False, 'schema_ahead'
|
|
302
|
+
if record['owner'] != holder:
|
|
303
|
+
return False, 'owned_elsewhere'
|
|
304
|
+
return True, 'ok'
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def may_admit(record, holder, readable, legacy=LEGACY_OWNER):
|
|
308
|
+
"""may_own, then (False, 'fenced') in every phase that admits nothing."""
|
|
309
|
+
allowed, code = may_own(record, holder, readable, legacy)
|
|
310
|
+
if not allowed or record is None:
|
|
311
|
+
return allowed, code
|
|
312
|
+
if record['phase'] not in ADMITTING:
|
|
313
|
+
return False, 'fenced'
|
|
314
|
+
return True, 'ok'
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def rollback_record(record, holder, readable):
|
|
318
|
+
"""The record that aborts a fence that has not committed its epoch, back to its fenced owner `holder` (reading
|
|
319
|
+
schemas up to `readable`): rolled_back at the next epoch, no seal (rollback.rs `rollback_record`)."""
|
|
320
|
+
if record is None:
|
|
321
|
+
raise Refused('rollback_not_fenced', 'no record')
|
|
322
|
+
if record['phase'] in COMMITTED:
|
|
323
|
+
raise Refused('rollback_needs_fence', f"{record['phase']}: only the reverse fence takes the domain back")
|
|
324
|
+
if record['phase'] not in ROLLBACK_FROM:
|
|
325
|
+
raise Refused('rollback_not_fenced', record['phase'])
|
|
326
|
+
if record['owner'] != holder:
|
|
327
|
+
raise Refused('rollback_not_owner', f"the fenced owner is {record['owner']}")
|
|
328
|
+
if record['schema'] > readable:
|
|
329
|
+
raise Refused('no_compatible_runtime', f"schema {record['schema']} is above {readable}")
|
|
330
|
+
if record['epoch'] >= COUNTER_MAX:
|
|
331
|
+
raise Refused('epoch_exhausted')
|
|
332
|
+
return dict(record, phase='rolled_back', epoch=record['epoch'] + 1, fenced_through=None)
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def rollback(state, domain, holder, readable):
|
|
336
|
+
if not TOKEN_RE.match(holder or ''):
|
|
337
|
+
raise Refused('holder_invalid', repr(holder))
|
|
338
|
+
current = read_record(state, domain)
|
|
339
|
+
return write_record(state, rollback_record(current, holder, readable), current)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
# ---------------------------------------------------------------- legacy endpoints
|
|
343
|
+
|
|
344
|
+
def _check_endpoint(endpoint):
|
|
345
|
+
if not isinstance(endpoint, str) or not ENDPOINT_RE.match(endpoint):
|
|
346
|
+
raise Refused('endpoint_invalid', repr(endpoint))
|
|
347
|
+
return endpoint
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def check_census(census):
|
|
351
|
+
"""A producer census: a list of {"kind": "generation"|"configuration", "endpoint": ID, ...}."""
|
|
352
|
+
if not isinstance(census, list):
|
|
353
|
+
raise Refused('census_malformed', 'not a list')
|
|
354
|
+
for producer in census:
|
|
355
|
+
if not isinstance(producer, dict) or producer.get('kind') not in PRODUCER_KINDS:
|
|
356
|
+
raise Refused('census_malformed', repr(producer))
|
|
357
|
+
try:
|
|
358
|
+
_check_endpoint(producer.get('endpoint'))
|
|
359
|
+
except Refused:
|
|
360
|
+
raise Refused('census_malformed', repr(producer)) from None
|
|
361
|
+
return census
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def prove_retirement(endpoint, census):
|
|
365
|
+
"""A retirement proof for `endpoint`, refused while any producer in the census names it. The endpoint's contents
|
|
366
|
+
are deliberately not an input."""
|
|
367
|
+
_check_endpoint(endpoint)
|
|
368
|
+
census = check_census(census)
|
|
369
|
+
naming = [producer for producer in census if producer['endpoint'] == endpoint]
|
|
370
|
+
if naming:
|
|
371
|
+
raise Refused('endpoint_has_live_producers', f'{endpoint}: {len(naming)}')
|
|
372
|
+
return {'v': 1, 'kind': RETIREMENT_KIND, 'endpoint': endpoint, 'census_size': len(census)}
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def plan_endpoints(inventory, census):
|
|
376
|
+
"""{endpoint id: 'kept' | 'forwarded' | 'retired'}: retired only with proof, else a socket or state file is kept
|
|
377
|
+
and a spool is forwarded (legacy.rs EndpointPlan::plan). A census producer naming an endpoint the inventory lacks
|
|
378
|
+
is refused (`endpoint_live_not_planned`): no plan abandons it."""
|
|
379
|
+
plan = {}
|
|
380
|
+
for endpoint in inventory:
|
|
381
|
+
ident = _check_endpoint(endpoint['id'])
|
|
382
|
+
try:
|
|
383
|
+
prove_retirement(ident, census)
|
|
384
|
+
plan[ident] = 'retired'
|
|
385
|
+
except Refused as refused:
|
|
386
|
+
if refused.code != 'endpoint_has_live_producers':
|
|
387
|
+
raise
|
|
388
|
+
plan[ident] = 'forwarded' if endpoint['kind'] == 'spool' else 'kept'
|
|
389
|
+
check_activation(plan, census)
|
|
390
|
+
return plan
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def check_activation(plan, census):
|
|
394
|
+
"""Refused unless every retirement still holds against the census now and every endpoint a census producer names
|
|
395
|
+
is planned with a disposition that takes custody (legacy.rs EndpointPlan::check_activation)."""
|
|
396
|
+
census = check_census(census)
|
|
397
|
+
for endpoint, disposition in sorted(plan.items()):
|
|
398
|
+
if disposition not in ('kept', 'forwarded', 'retired'):
|
|
399
|
+
raise Refused('endpoint_undisposed', endpoint)
|
|
400
|
+
if disposition == 'retired':
|
|
401
|
+
try:
|
|
402
|
+
prove_retirement(endpoint, census)
|
|
403
|
+
except Refused as refused:
|
|
404
|
+
raise Refused('endpoint_retirement_stale', str(refused)) from None
|
|
405
|
+
for producer in census:
|
|
406
|
+
if producer['endpoint'] not in plan:
|
|
407
|
+
raise Refused('endpoint_live_not_planned', producer['endpoint'])
|
|
408
|
+
return plan
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def _read_envelope(dir_fd, name):
|
|
412
|
+
"""(bytes, (st_dev, st_ino), problem) of one committed envelope — problem None, or 'too_large' with no bytes —
|
|
413
|
+
and None for anything that is not a regular file (opened without following a link and without waiting on a
|
|
414
|
+
fifo)."""
|
|
415
|
+
try:
|
|
416
|
+
fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, dir_fd=dir_fd)
|
|
417
|
+
except OSError:
|
|
418
|
+
return None
|
|
419
|
+
try:
|
|
420
|
+
info = os.fstat(fd)
|
|
421
|
+
if not stat.S_ISREG(info.st_mode):
|
|
422
|
+
return None
|
|
423
|
+
if info.st_size > ENVELOPE_MAX:
|
|
424
|
+
return b'', (info.st_dev, info.st_ino), 'too_large'
|
|
425
|
+
chunks, size = [], 0
|
|
426
|
+
while size <= ENVELOPE_MAX:
|
|
427
|
+
chunk = os.read(fd, 65536)
|
|
428
|
+
if not chunk:
|
|
429
|
+
break
|
|
430
|
+
chunks.append(chunk)
|
|
431
|
+
size += len(chunk)
|
|
432
|
+
if size > ENVELOPE_MAX:
|
|
433
|
+
return b'', (info.st_dev, info.st_ino), 'too_large'
|
|
434
|
+
return b''.join(chunks), (info.st_dev, info.st_ino), None
|
|
435
|
+
finally:
|
|
436
|
+
os.close(fd)
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def _errname(error):
|
|
440
|
+
return errno.errorcode.get(error.errno, str(error.errno))
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def _link_into(target_dir, name, data):
|
|
444
|
+
"""'forwarded' | 'duplicate' | 'conflict' | 'refused:<why>': `data` linked to target_dir/name without ever
|
|
445
|
+
replacing a name."""
|
|
446
|
+
temp = f'.{name}.{os.getpid()}.{secrets.token_hex(4)}.tmp'
|
|
447
|
+
dir_fd = os.open(target_dir, os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC)
|
|
448
|
+
try:
|
|
449
|
+
try:
|
|
450
|
+
fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600,
|
|
451
|
+
dir_fd=dir_fd)
|
|
452
|
+
except OSError as error:
|
|
453
|
+
return f'refused:{_errname(error)}'
|
|
454
|
+
try:
|
|
455
|
+
try:
|
|
456
|
+
view = memoryview(data)
|
|
457
|
+
while view:
|
|
458
|
+
view = view[os.write(fd, view):]
|
|
459
|
+
os.fsync(fd)
|
|
460
|
+
except OSError as error:
|
|
461
|
+
return f'refused:{_errname(error)}'
|
|
462
|
+
finally:
|
|
463
|
+
os.close(fd)
|
|
464
|
+
try:
|
|
465
|
+
os.link(temp, name, src_dir_fd=dir_fd, dst_dir_fd=dir_fd, follow_symlinks=False)
|
|
466
|
+
outcome = 'forwarded'
|
|
467
|
+
except FileExistsError:
|
|
468
|
+
existing = _read_envelope(dir_fd, name)
|
|
469
|
+
outcome = 'duplicate' if existing is not None and existing[2] is None and existing[0] == data \
|
|
470
|
+
else 'conflict'
|
|
471
|
+
except OSError as error:
|
|
472
|
+
# No check-absence-then-rename fallback: that could replace a concurrent publisher's file.
|
|
473
|
+
outcome = f'refused:{_errname(error)}'
|
|
474
|
+
finally:
|
|
475
|
+
try:
|
|
476
|
+
os.unlink(temp, dir_fd=dir_fd)
|
|
477
|
+
except OSError:
|
|
478
|
+
pass
|
|
479
|
+
os.fsync(dir_fd)
|
|
480
|
+
return outcome
|
|
481
|
+
finally:
|
|
482
|
+
os.close(dir_fd)
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def forward(spool, intake, endpoint, limit=FORWARD_BATCH):
|
|
486
|
+
"""One forwarding pass over a legacy spool, oldest name first, until `limit` envelopes are released. An entry that
|
|
487
|
+
cannot move (a special file, an oversize envelope, a conflict, a refusal) is reported on every pass and never uses
|
|
488
|
+
the batch, so it cannot starve the envelopes behind it; a release that fails is `release_failed:<errno>` and the
|
|
489
|
+
pass goes on. Whatever was released is made durable in the spool directory even when the pass is interrupted.
|
|
490
|
+
Returns one result per entry looked at: {'name', 'custody', 'released', 'limitations'}."""
|
|
491
|
+
_check_endpoint(endpoint)
|
|
492
|
+
spool = Path(spool)
|
|
493
|
+
try:
|
|
494
|
+
if not stat.S_ISDIR(os.lstat(spool).st_mode):
|
|
495
|
+
raise Refused('not_a_directory', str(spool))
|
|
496
|
+
except FileNotFoundError:
|
|
497
|
+
return []
|
|
498
|
+
_make_dirs(intake)
|
|
499
|
+
target = _private_dir(_private_dir(Path(intake)) / endpoint)
|
|
500
|
+
results = []
|
|
501
|
+
released = 0
|
|
502
|
+
dir_fd = os.open(spool, os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC)
|
|
503
|
+
try:
|
|
504
|
+
names = sorted(name for name in os.listdir(dir_fd) if not name.startswith('.'))
|
|
505
|
+
for name in names:
|
|
506
|
+
if released >= limit:
|
|
507
|
+
break
|
|
508
|
+
result = {'name': name, 'custody': None, 'released': False, 'limitations': ['across_cutover']}
|
|
509
|
+
results.append(result)
|
|
510
|
+
try:
|
|
511
|
+
envelope = _read_envelope(dir_fd, name)
|
|
512
|
+
except OSError as error:
|
|
513
|
+
result['custody'] = f'refused:{_errname(error)}'
|
|
514
|
+
continue
|
|
515
|
+
if envelope is None:
|
|
516
|
+
result['custody'] = 'skipped:not_regular'
|
|
517
|
+
continue
|
|
518
|
+
if envelope[2] is not None:
|
|
519
|
+
result['custody'] = f'refused:{envelope[2]}'
|
|
520
|
+
continue
|
|
521
|
+
data, identity, _ = envelope
|
|
522
|
+
result['custody'] = _link_into(target, name, data)
|
|
523
|
+
if result['custody'] not in ('forwarded', 'duplicate'):
|
|
524
|
+
continue
|
|
525
|
+
# Release only the file that was forwarded: the legacy publisher only ever adds names.
|
|
526
|
+
try:
|
|
527
|
+
info = os.stat(name, dir_fd=dir_fd, follow_symlinks=False)
|
|
528
|
+
if (info.st_dev, info.st_ino) == identity:
|
|
529
|
+
os.unlink(name, dir_fd=dir_fd)
|
|
530
|
+
result['released'] = True
|
|
531
|
+
released += 1
|
|
532
|
+
except FileNotFoundError:
|
|
533
|
+
pass
|
|
534
|
+
except OSError as error:
|
|
535
|
+
# Kept in the spool and retried next pass: the intake copy makes the retry a duplicate.
|
|
536
|
+
result['custody'] = f'release_failed:{_errname(error)}'
|
|
537
|
+
finally:
|
|
538
|
+
try:
|
|
539
|
+
if released:
|
|
540
|
+
os.fsync(dir_fd)
|
|
541
|
+
finally:
|
|
542
|
+
os.close(dir_fd)
|
|
543
|
+
return results
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def pump(plan, spools, intake, census, limit=FORWARD_BATCH):
|
|
547
|
+
"""One pass of the rollback window, after re-checking the plan against the census: forward every forwarded
|
|
548
|
+
endpoint's spool. {endpoint: results}; a kept endpoint (served in place by the candidate) and a retired one map to
|
|
549
|
+
None and are never read or released. A forwarded endpoint without a spool is refused (`endpoint_not_pumped`)."""
|
|
550
|
+
check_activation(plan, census)
|
|
551
|
+
for endpoint in sorted(spools):
|
|
552
|
+
if endpoint not in plan:
|
|
553
|
+
raise Refused('endpoint_undisposed', endpoint)
|
|
554
|
+
unpumped = sorted(endpoint for endpoint, disposition in plan.items()
|
|
555
|
+
if disposition == 'forwarded' and endpoint not in spools)
|
|
556
|
+
if unpumped:
|
|
557
|
+
raise Refused('endpoint_not_pumped', ', '.join(unpumped))
|
|
558
|
+
return {endpoint: forward(spool, intake, endpoint, limit) if plan[endpoint] == 'forwarded' else None
|
|
559
|
+
for endpoint, spool in sorted(spools.items())}
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
# ---------------------------------------------------------------- command line
|
|
563
|
+
|
|
564
|
+
def _positive(text):
|
|
565
|
+
value = int(text)
|
|
566
|
+
if value < 1:
|
|
567
|
+
raise argparse.ArgumentTypeError('must be at least 1')
|
|
568
|
+
return value
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
def _parser():
|
|
572
|
+
parser = argparse.ArgumentParser(prog='cutover.py', description='The Python half of the Lanes 2.0 cutover.')
|
|
573
|
+
commands = parser.add_subparsers(dest='command', required=True)
|
|
574
|
+
status = commands.add_parser('status')
|
|
575
|
+
status.add_argument('domains', nargs='*')
|
|
576
|
+
status.add_argument('--json', action='store_true')
|
|
577
|
+
check = commands.add_parser('check')
|
|
578
|
+
check.add_argument('domain')
|
|
579
|
+
check.add_argument('--holder', required=True)
|
|
580
|
+
check.add_argument('--schema', required=True, type=_positive)
|
|
581
|
+
check.add_argument('--admit', action='store_true')
|
|
582
|
+
check.add_argument('--legacy', default=LEGACY_OWNER, help='who owns a domain with no record')
|
|
583
|
+
back = commands.add_parser('rollback')
|
|
584
|
+
back.add_argument('domain')
|
|
585
|
+
back.add_argument('--to', required=True)
|
|
586
|
+
back.add_argument('--schema', required=True, type=_positive)
|
|
587
|
+
fwd = commands.add_parser('forward')
|
|
588
|
+
fwd.add_argument('spool')
|
|
589
|
+
fwd.add_argument('intake')
|
|
590
|
+
fwd.add_argument('--endpoint', required=True)
|
|
591
|
+
fwd.add_argument('--limit', type=_positive, default=FORWARD_BATCH)
|
|
592
|
+
fwd.add_argument('--json', action='store_true')
|
|
593
|
+
retire = commands.add_parser('retire')
|
|
594
|
+
retire.add_argument('endpoint')
|
|
595
|
+
retire.add_argument('--census', required=True)
|
|
596
|
+
retire.add_argument('--json', action='store_true')
|
|
597
|
+
return parser
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
def main(argv, state=None, out=None):
|
|
601
|
+
out = out or sys.stdout
|
|
602
|
+
state = Path(state) if state is not None else STATE
|
|
603
|
+
args = _parser().parse_args(argv)
|
|
604
|
+
try:
|
|
605
|
+
if args.command == 'status':
|
|
606
|
+
found = records(state, args.domains)
|
|
607
|
+
if args.json:
|
|
608
|
+
print(json.dumps({name: ({'error': value.code} if isinstance(value, Refused) else value)
|
|
609
|
+
for name, value in found.items()}, sort_keys=True), file=out)
|
|
610
|
+
else:
|
|
611
|
+
for name, value in found.items():
|
|
612
|
+
if isinstance(value, Refused):
|
|
613
|
+
print(f'{name}: {value}', file=out)
|
|
614
|
+
elif value is None:
|
|
615
|
+
print(f'{name}: no cutover', file=out)
|
|
616
|
+
else:
|
|
617
|
+
print(f"{name}: {value['phase']} epoch {value['epoch']} owner {value['owner']}"
|
|
618
|
+
f" schema {value['schema']}", file=out)
|
|
619
|
+
return 1 if any(isinstance(value, Refused) for value in found.values()) else 0
|
|
620
|
+
if args.command == 'check':
|
|
621
|
+
record = read_record(state, args.domain)
|
|
622
|
+
allowed, code = (may_admit if args.admit else may_own)(record, args.holder, args.schema, args.legacy)
|
|
623
|
+
print(code, file=out)
|
|
624
|
+
return 0 if allowed else EXIT_REFUSED
|
|
625
|
+
if args.command == 'rollback':
|
|
626
|
+
record = rollback(state, args.domain, args.to, args.schema)
|
|
627
|
+
print(render(record), end='', file=out)
|
|
628
|
+
return 0
|
|
629
|
+
if args.command == 'forward':
|
|
630
|
+
results = forward(args.spool, args.intake, args.endpoint, args.limit)
|
|
631
|
+
if args.json:
|
|
632
|
+
print(json.dumps(results), file=out)
|
|
633
|
+
else:
|
|
634
|
+
for result in results:
|
|
635
|
+
print(f"{result['name']}: {result['custody']}{' released' if result['released'] else ''}",
|
|
636
|
+
file=out)
|
|
637
|
+
failed = [result for result in results
|
|
638
|
+
if result['custody'] not in ('forwarded', 'duplicate', 'skipped:not_regular')]
|
|
639
|
+
return 1 if failed else 0
|
|
640
|
+
if args.command == 'retire':
|
|
641
|
+
try:
|
|
642
|
+
census = json.loads(Path(args.census).read_text())
|
|
643
|
+
except (OSError, ValueError) as error:
|
|
644
|
+
raise Refused('census_malformed', str(error)) from None
|
|
645
|
+
proof = prove_retirement(args.endpoint, census)
|
|
646
|
+
print(json.dumps(proof) if args.json else f"{proof['endpoint']}: retired "
|
|
647
|
+
f"(census of {proof['census_size']})", file=out)
|
|
648
|
+
return 0
|
|
649
|
+
except Refused as refused:
|
|
650
|
+
print(str(refused), file=out)
|
|
651
|
+
return EXIT_REFUSED
|
|
652
|
+
return 2
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
if __name__ == '__main__':
|
|
656
|
+
sys.exit(main(sys.argv[1:]))
|