diff --git a/STATUS.md b/STATUS.md index 5d79d9d..afcd0fd 100644 --- a/STATUS.md +++ b/STATUS.md @@ -1,6 +1,36 @@ # Infrastructure implementation status -Updated 2026-11-14. Architectural acceptance is separate from implementation. +Updated 2026-11-15. Architectural acceptance is separate from implementation. + +## Manual builds pinned to an immutable snapshot, desktop Zen kernel (2026-11-15) + +The portal can now start a build itself and pin the repository it compiles from. +`POST /api/control` carries `mode` (`iso`/`ostree`) and `snapshot` (`latest`, `new` +or a date); the portal resolves the choice to one date **before** the unit starts and +writes `data/private/release-cycle/cycle-request.json`. `release-cycle.py` gained +`--snapshot` and `--request`: it consumes the request once (stale after 900 s, never +on `--resume`), records `snapshot`/`request` in the run state and refuses a date +without `core/os/x86_64/core.db`. A scheduled run therefore cannot inherit manual +inputs. `new` captures through a transient `systemd-run` unit so the read-only bind +view is created in the host mount namespace that serves HTTP; the portal lists and +validates snapshots from the ZFS dataset (`tank/archipelago/archlinux`), because its +own namespace never sees a view created afterwards. `deploy/mirror-snapshot.sh` and +`deploy/mirror-snapshot-mount.sh` now live in the repository: creation is immutable +per UTC date, retention keeps three, and views whose snapshot was destroyed are +pruned instead of left as stale empty directories. + +Desktop Purposes run `linux-zen`. `purposes/proposals/{gnome,kde}.yaml` install it and +declare `spec.packages.replacements` (`target: linux`, `expected_owner: core/arch`); +Core, Container Runner and the live ISO keep `linux`. `builder/src/lib.rs` renders a +`replace_core_package ` call only from that declaration, and +`composer/layer_delta.py` now permits a removal only for payload listed in the +replaced package's own `files` index plus its database entry — any other vanished +Core path still aborts the capture. Verified: `composer/tests/layer_delta_test.py` +(11 tests, including the allowed replacement, the undeclared removal, an unrelated +deleted path and inconsistent compose metadata) and the builder test +`only_declared_desktop_purposes_replace_the_kernel`. Real-image behaviour (does +`pacman -R linux` leave exactly the expected paths; does the finalizer see one +kernel) is only proven by the next published cycle. ## ISO cycle 20261114T133314Z with OS version 1.0.1. (in progress, 2026-11-14) diff --git a/control/README.md b/control/README.md index bd59ac1..b3d91d5 100644 --- a/control/README.md +++ b/control/README.md @@ -9,7 +9,9 @@ private networks; it is a personal control surface, not an Internet-facing app. Terra deployment: `192.168.88.104:8099`, `100.64.0.11:8099`, `127.0.0.1:8099`. Allowed peers: `192.168.88.0/24`, `100.64.0.0/10`, `127.0.0.0/8`. Config `/etc/archipelago/control.json` includes `listen`, `hosts` (with port), -`allowed_networks`, `port`, `coordinator_root`, `worker_root`, `worker_source_root`. +`allowed_networks`, `port`, `coordinator_root`, `worker_root`, `worker_source_root` +and optionally `snapshot_dataset` (default `tank/archipelago/archlinux`) plus +`snapshot_command` (default `/usr/local/sbin/archipelago-mirror-snapshot`). Unit: `deploy/archipelago-control.service`. Source: `/opt/archipelago/control-source`, which must contain `control/` and the imported `pipeline/monitor.py` and `pipeline/release-schedule.py` (deploy the `pipeline/` directory with `control/`). @@ -17,7 +19,8 @@ LAN address changes require updating bind/Host config and restarting this servic ## Monitoring contract -- `/api/status`: actual systemd service/timer state, next trigger, history, source SHAs. +- `/api/status`: actual systemd service/timer state, next trigger, history, source SHAs + and the immutable repository snapshots (`snapshots`), read from the ZFS dataset. - `/api/run?run=ID`: ordered phase events, all invoked actions, complete argv, start/end times, elapsed time, exit code/error, and inventory of nested logs. - `/api/log?run=ID&id=LOG&offset=BYTE`: 256-KiB pages from any byte offset; @@ -39,9 +42,28 @@ format; monitoring does not substitute human CLI output for private detailed log Stopping the driver stops owned worker units, retains logs, and leaves unfinished build artifacts for diagnosis rather than starting a lengthy archive. D-098 removed the VM phases, so the portal no longer stops VM units. No command shell or arbitrary -service name is accepted over HTTP. Schedule buttons enable or disable the D-098 -daily dispatcher timer; the cadence itself (three-day OSTree interval, day-30 ISO) -is fixed by the code and is not editable from the portal. +service name is accepted over HTTP. + +## Manual build request + +`POST /api/control` accepts `{action, mode, snapshot}`: `mode` is `iso` or `ostree`, +`snapshot` is `latest`, `new` or an existing `YYYY-MM-DD` date. Before the unit +starts, the portal resolves the choice to one immutable date and writes +`/opt/archipelago/data/private/release-cycle/cycle-request.json`; the driver consumes +that file exactly once (ignoring a request older than 900 s) and binds the run to +that snapshot URL. A scheduled or resumed run therefore never inherits a manual +build's inputs. + +`new` creates a snapshot through a transient `systemd-run` unit, because the +read-only view it bind-mounts must land in the host mount namespace to be published +over HTTP; a mount made inside this unit's own namespace would be invisible to the +web server. Snapshot listing and validation read the ZFS dataset directly, so a view +created moments ago is visible here as well. Retention keeps at most three monthly +snapshots and prunes the orphaned views (`deploy/mirror-snapshot*.sh`). + +Schedule buttons enable or disable the monthly dispatcher timer; the cadence itself +(1st of the month, ISO + OSTree) is fixed by the code and is not editable from the +portal. Runtime API tests: `python3 tests/control_portal.py` on terra. They use a temporary fixture and fake systemd responses; they never start or stop a real build. diff --git a/control/app.js b/control/app.js index ae54e16..0cab202 100644 --- a/control/app.js +++ b/control/app.js @@ -22,7 +22,7 @@ const phases = [ ['cleaning-worker','Очистка worker'] ]; let run = '', log = '', offset = 0, next = 0, size = 0, text = '', data = null, status = null, busy = false, logBusy = false; -let logsKey = '', runsKey = ''; +let logsKey = '', runsKey = '', snapshotsKey = ''; const date = value => value ? new Date(value).toLocaleString('ru-RU') : '—'; const bytes = value => value < 1024 ? value+' Б' : value < 1048576 ? (value/1024).toFixed(1)+' КиБ' : (value/1048576).toFixed(1)+' МиБ'; const elapsed = (start,end) => {const s=Math.max(0,Math.floor(((end?new Date(end):new Date())-new Date(start))/1000));return s<60?s+' с':Math.floor(s/60)+' мин '+s%60+' с';}; @@ -31,12 +31,21 @@ function node(tag, cls, content) {const n=document.createElement(tag);if(cls)n.c async function api(url, options) {const r=await fetch(url, options);const body=await r.json();if(!r.ok)throw Error(body.error || r.statusText);return body;} function showError(error) {$('error').hidden=false;$('error').textContent=error.message;} function selectRun(id) {run=id;log='';offset=0;logsKey='';runsKey='';data=null;$('log-content').textContent='Выберите лог';$('download').hidden=true;refresh();} -async function control(action) { +async function control(action, parameters) { document.querySelectorAll('.controls button').forEach(b=>b.disabled=true); - try {await api('/api/control',{method:'POST',headers:{'Content-Type':'application/json','X-Archipelago-Control':'1'},body:JSON.stringify({action})});$('action-result').textContent=({start:'Запуск передан systemd',stop:'Остановка передана systemd','schedule-on':'Расписание включено','schedule-off':'Расписание отключено'})[action];if(action==='start'){run='';runsKey='';}} + try { + const result=await api('/api/control',{method:'POST',headers:{'Content-Type':'application/json','X-Archipelago-Control':'1'},body:JSON.stringify(Object.assign({action},parameters||{}))}); + if(action==='start'){ + const req=result.request||{}; + $('action-result').textContent=`Принято: ${req.mode==='ostree'?'только OSTree':'ISO + OSTree'} · снимок ${req.snapshot}`; + run='';runsKey=''; + } else { + $('action-result').textContent=({stop:'Остановка передана systemd','schedule-on':'Расписание включено','schedule-off':'Расписание отключено'})[action]||'Принято'; + } + } catch(e){showError(e);}finally{refresh();} } -$('start').onclick=()=>control('start');$('stop').onclick=()=>control('stop'); +$('start').onclick=()=>control('start',{mode:$('build-mode').value,snapshot:$('build-snapshot').value});$('stop').onclick=()=>control('stop'); $('toggle-schedule').onclick=()=>control(status?.timer.ActiveState==='active'?'schedule-off':'schedule-on'); function drawStatus(s) { status=s;const active=['active','activating'].includes(s.service.ActiveState);const stopping=s.service.ActiveState==='deactivating'; @@ -45,6 +54,18 @@ function drawStatus(s) { $('schedule').textContent=s.timer.ActiveState==='active'?'ISO+OSTree · 1-е число':'Приостановлено'; $('next').textContent='Следующий: '+(s.timer.ActiveState==='active' && s.next_release ? `${s.next_release.date} · ${s.next_release.mode} · ${s.next_release.time}` : '—'); $('start').disabled=active||stopping;$('stop').disabled=!active;$('toggle-schedule').disabled=false; + $('build-mode').disabled=active||stopping;$('build-snapshot').disabled=active||stopping; + const snapshots=s.snapshots||[]; + $('snapshot').textContent=snapshots.length?snapshots[0].date:'Нет снимков'; + $('snapshot-detail').textContent=snapshots.length?`Доступно: ${snapshots.length} · хранится не более трёх`:'Выберите «Новый снимок сейчас»'; + const snapshotKey=snapshots.map(item=>item.date).join(','); + if(snapshotKey!==snapshotsKey){ + snapshotsKey=snapshotKey;const select=$('build-snapshot');const current=select.value; + select.replaceChildren();const latest=node('option','','Последний снимок');latest.value='latest';select.append(latest); + const fresh=node('option','','Новый снимок сейчас');fresh.value='new';select.append(fresh); + for(const item of snapshots){const option=node('option','',item.date);option.value=item.date;select.append(option);} + select.value=[...select.options].some(item=>item.value===current)?current:'latest'; + } $('toggle-schedule').textContent=s.timer.ActiveState==='active'?'Ⅱ Приостановить расписание':'↻ Включить расписание'; const published=s.runs.find(r=>r.published);$('published').textContent=published?'Опубликовано':'Нет данных';$('published-detail').textContent=published?.run || 'Публикация не подтверждена'; if(!run && s.runs.length){run=s.runs[0].run;logsKey='';} @@ -85,7 +106,7 @@ function drawRun(d) { data=d;const s=d.state;const terminal=['failed','complete'].includes(s.state);const plan=phasePlan(s,d,terminal); $('run-name').textContent=s.run;$('run-state').textContent=label(s.state); $('run-state').className='badge'+(s.state==='failed'?' error':''); - $('run-meta').textContent=`${date(s.started)} · ${elapsed(s.started,terminal?(s.finished||s.updated):null)} · ${s.worker} · ${s.channel} · ${s.output_mode||'—'}`; + $('run-meta').textContent=`${date(s.started)} · ${elapsed(s.started,terminal?(s.finished||s.updated):null)} · ${s.worker} · ${s.channel} · ${s.output_mode||'—'} · снимок ${s.snapshot||(s.snapshot_url||'').split('/arch-repo-snapshot/')[1]?.split('/')[0]||'—'}`; $('run-error').hidden=!s.error;$('run-error').textContent=s.error_details||s.error||''; const p=progressOf(s,d,plan);const track=$('run-progress-track'); track.setAttribute('aria-valuenow',String(p.percent)); diff --git a/control/index.html b/control/index.html index 0e0cb23..1afa306 100644 --- a/control/index.html +++ b/control/index.html @@ -30,16 +30,29 @@
Pipeline—Чтение systemd
Schedule——
+
Repository—Неизменяемый снимок зеркала
Publication—Только по результату конвейера
+ +
- Лимит каждого действия: 4 часа + Снимок фиксируется до старта; хранится не более трёх
diff --git a/control/server.py b/control/server.py index d7ca6fd..a8f0623 100644 --- a/control/server.py +++ b/control/server.py @@ -21,8 +21,14 @@ SCHEDULE_SPEC = importlib.util.spec_from_file_location('release_schedule', Path( schedule = importlib.util.module_from_spec(SCHEDULE_SPEC) SCHEDULE_SPEC.loader.exec_module(schedule) RUN = re.compile(r'[0-9]{8}T[0-9]{6}Z') +SNAPSHOT = re.compile(r'[0-9]{4}-[0-9]{2}-[0-9]{2}') SERVICE = 'archipelago-release-cycle.service' TIMER = 'archipelago-release-cycle.timer' +# Immutable mirror snapshots live on ZFS; the read-only bind views below are +# published by HTTP from the host mount namespace. +SNAPSHOT_DATASET = Path('/tank/archipelago/archlinux') +SNAPSHOT_PREFIX = 'monthly-' +SNAPSHOT_VIEW = 'data/public/arch-repo-snapshot' def read_json(path, default=None): @@ -39,6 +45,7 @@ class App: self.archive = self.base / 'data/private/release-cycle' self.history = self.base / 'data/private/pipeline-monitor' self.worker = Path(config['worker_root']) / 'build/release-cycle' + self.snapshot_dataset = Path(config.get('snapshot_dataset', str(SNAPSHOT_DATASET))) self.lock = threading.Lock() self.networks = [ipaddress.ip_network(n) for n in config['allowed_networks']] @@ -61,6 +68,55 @@ class App: # older identity but is the one actually progressing. return sorted(states, key=lambda s: (s.get("updated") or s.get("started") or "", s.get("run") or ""), reverse=True) + def snapshots(self): + """Immutable repository views, read from the dataset itself. + + A bind view created moments ago exists only in the host mount namespace, + so listing the published directory would hide it from this unit. The ZFS + snapshot list is the source of truth; every listed entry is validated by + its Core database, which is what the cycle resolves packages from. + """ + root = self.snapshot_dataset / '.zfs/snapshot' + result = [] + if root.is_dir(): + for entry in root.glob(SNAPSHOT_PREFIX + '*'): + date = entry.name.removeprefix(SNAPSHOT_PREFIX) + if SNAPSHOT.fullmatch(date) and (entry / 'core/os/x86_64/core.db').is_file(): + result.append({'date': date, + 'url': '/archipelago/arch-repo-snapshot/' + date + '/$repo/os/$arch'}) + return sorted(result, key=lambda item: item['date'], reverse=True) + + def snapshot_date(self, choice): + """Resolve a portal snapshot choice to one immutable view date.""" + if choice == 'latest': + available = self.snapshots() + if not available: + raise ValueError('Нет доступных снимков: выберите «Новый снимок»') + return available[0]['date'] + if choice == 'new': + # The creation script bind-mounts the read-only view for HTTP, and a + # mount made inside this unit's private namespace would be invisible + # to the web server, so it runs as a transient host unit. + unit = 'archipelago-snapshot-' + datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S') + command = self.config.get('snapshot_command', '/usr/local/sbin/archipelago-mirror-snapshot') + process = subprocess.run(['systemd-run', '--wait', '--pipe', '--collect', '--unit=' + unit, + '--property=Type=oneshot', + '--property=TimeoutStartSec=600', command], + capture_output=True, text=True, timeout=660) + output = process.stdout + process.stderr + if process.returncode: + raise ValueError('Снимок не создан: ' + output.strip()[-800:]) + views = [line.split('arch-repo-snapshot/')[1].split('/')[0] + for line in output.splitlines() if 'arch-repo-snapshot/' in line] + if not views or not SNAPSHOT.fullmatch(views[-1]): + raise ValueError('Снимок создан без пригодного URL: ' + output.strip()[-400:]) + return views[-1] + if not SNAPSHOT.fullmatch(choice): + raise ValueError('Некорректная дата снимка') + if not any(item['date'] == choice for item in self.snapshots()): + raise ValueError('Снимок ' + choice + ' не найден') + return choice + def logs(self, run): if not self.state(run): raise FileNotFoundError('Run not found') @@ -91,19 +147,35 @@ class App: found[label + '/' + str(path.relative_to(root))] = path return found - def control(self, action): + def control(self, action, parameters=None): commands = {'start': ['start', '--no-block', SERVICE], 'stop': ['stop', '--no-block', SERVICE], 'schedule-on': ['enable', '--now', TIMER], 'schedule-off': ['disable', '--now', TIMER]} if action not in commands: raise ValueError('Unknown action') + parameters = parameters or {} with self.lock: if action == 'start' and self.unit(SERVICE)['ActiveState'] in ('active', 'activating', 'deactivating'): raise ValueError('Pipeline is already running or stopping') + if action == 'start': + mode = parameters.get('mode', 'iso') + if mode not in ('iso', 'ostree'): + raise ValueError('Неизвестный режим сборки') + # Pin the exact immutable repository before the cycle starts: a + # manual build must never silently reuse a different snapshot. + pinned = self.snapshot_date(parameters.get('snapshot', 'latest')) + parameters = {'mode': mode, 'snapshot': pinned, + 'requested_at': datetime.now(timezone.utc).isoformat()} + path = self.archive / 'cycle-request.json' + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix('.tmp') + temporary.write_text(json.dumps(parameters) + '\n') + temporary.replace(path) subprocess.run(['systemctl', *commands[action]], check=True, capture_output=True, timeout=15) self.history.mkdir(parents=True, exist_ok=True) with (self.history / 'control.jsonl').open('a') as stream: - stream.write(json.dumps({'time': datetime.now(timezone.utc).isoformat(), 'action': action}) + '\n') - return {'accepted': True, 'action': action} + stream.write(json.dumps({'time': datetime.now(timezone.utc).isoformat(), + 'action': action, 'request': parameters}) + '\n') + return {'accepted': True, 'action': action, 'request': parameters if action == 'start' else None} class Handler(BaseHTTPRequestHandler): @@ -150,7 +222,8 @@ class Handler(BaseHTTPRequestHandler): if url.path == '/api/status': return self.result({'service': app.unit(SERVICE), 'timer': app.unit(TIMER), 'next_release': schedule.next_release(datetime.now(timezone.utc)), - 'runs': app.runs(), 'time': datetime.now(timezone.utc).isoformat(), + 'runs': app.runs(), 'snapshots': app.snapshots(), + 'time': datetime.now(timezone.utc).isoformat(), 'sources': read_json(Path(app.config['worker_source_root']) / 'src/source-revisions.json', {})}) if url.path == '/api/run': run = query['run'][0] @@ -222,7 +295,7 @@ class Handler(BaseHTTPRequestHandler): if not 0 < length <= 1024: raise ValueError('Invalid request size') body = json.loads(self.rfile.read(length)) - self.result(self.server.app.control(body['action']), 202) + self.result(self.server.app.control(body['action'], body), 202) except Exception as error: self.result({'error': str(error)}, 409) diff --git a/control/style.css b/control/style.css index 68a4ad4..20f4361 100644 --- a/control/style.css +++ b/control/style.css @@ -123,7 +123,7 @@ main{max-width:1440px;margin:0 auto;padding:24px 24px 48px} .connection i.online{background:var(--md-primary);box-shadow:0 0 0 4px var(--md-primary-container)} /* cards */ -.overview{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px} +.overview{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:12px} .overview article{ background:var(--md-surface-container-low); border-radius:var(--md-shape-lg); @@ -151,6 +151,13 @@ button:focus-visible,a:focus-visible,input:focus-visible,summary:focus-visible,p .primary:hover{box-shadow:var(--md-shadow-2)} .danger{background:var(--md-error-container);color:var(--md-on-error-container)} .tonal{background:var(--md-secondary-container);color:var(--md-on-secondary-container)} +.field{display:flex;flex-direction:column;gap:4px;font-size:11px;color:var(--md-on-surface-variant)} +.field select{ + font:inherit;font-size:13px;height:40px;padding:0 12px; + background:var(--md-surface-container-high);color:var(--md-on-surface); + border:1px solid var(--md-outline-variant);border-radius:var(--md-shape-md); +} +.field select:disabled{opacity:.38} #action-result{font-size:12px;color:var(--md-on-surface-variant)} /* workspace */ diff --git a/deploy/archipelago-control.service b/deploy/archipelago-control.service index 081cb49..ab95dab 100644 --- a/deploy/archipelago-control.service +++ b/deploy/archipelago-control.service @@ -14,6 +14,7 @@ PrivateTmp=true ProtectSystem=strict ProtectHome=true ReadWritePaths=/opt/archipelago/data/private/pipeline-monitor +ReadWritePaths=/opt/archipelago/data/private/release-cycle RestrictAddressFamilies=AF_INET AF_UNIX [Install] diff --git a/deploy/mirror-snapshot-mount.sh b/deploy/mirror-snapshot-mount.sh new file mode 100644 index 0000000..cdced04 --- /dev/null +++ b/deploy/mirror-snapshot-mount.sh @@ -0,0 +1,31 @@ +#!/bin/bash +# Bind-mount each monthly mirror snapshot read-only under the public artifact +# root, and prune views whose snapshot was destroyed by retention. +set -euo pipefail +mountroot=/tank/archipelago/archlinux +view=/opt/archipelago/data/public/arch-repo-snapshot +mkdir -p "$view" +# Unmount every existing view first: recreating them is idempotent, and a view +# must never be pruned while its snapshot is still bind-mounted. +while read -r m; do + umount "$m" 2>/dev/null || true +done < <(awk -v v="$view/" '$3 ~ "^" v {print $3}' /proc/mounts) +declare -A keep=() +for d in "$mountroot"/.zfs/snapshot/monthly-*; do + [ -d "$d" ] || continue + name=${d##*/} + date=${name#monthly-} + keep[$date]=1 + target="$view/$date" + mkdir -p "$target" + mount --bind -o ro "$d" "$target" + echo "mounted $date" +done +for target in "$view"/*; do + [ -d "$target" ] || continue + date=${target##*/} + [[ $date =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || continue + [ -n "${keep[$date]:-}" ] && continue + echo "pruning view $date" + rm -rf "$target" +done diff --git a/deploy/mirror-snapshot.sh b/deploy/mirror-snapshot.sh new file mode 100644 index 0000000..d6e47fd --- /dev/null +++ b/deploy/mirror-snapshot.sh @@ -0,0 +1,28 @@ +#!/bin/bash +# D-108: immutable Arch mirror snapshot. Create, retain at most three, publish +# the read-only views. A snapshot for the same UTC date is never replaced, so a +# pinned build can never be silently rewritten underneath itself. +set -euo pipefail +dataset=tank/archipelago/archlinux +today=$(date -u +%Y-%m-%d) +tag="monthly-${today}" +snap="${dataset}@${tag}" + +if zfs list -H -t snapshot -o name "$snap" >/dev/null 2>&1; then + echo "snapshot $snap already exists; immutable captures are not replaced" >&2 +else + zfs snapshot "$snap" + echo "created $snap" +fi + +# Retain at most three monthly snapshots (contract). Names sort by UTC date. +mapfile -t snaps < <(zfs list -H -o name -t snapshot -r "$dataset" | grep -E '@monthly-' | sort) +while ((${#snaps[@]} > 3)); do + echo "destroying oldest ${snaps[0]}" + zfs destroy "${snaps[0]}" + snaps=("${snaps[@]:1}") +done +echo "retained ${#snaps[@]} monthly snapshot(s)" + +/usr/local/sbin/archipelago-mirror-snapshot-mount +echo "url=https://mirror.nw-sys.ru/archipelago/arch-repo-snapshot/${today}/\$repo/os/\$arch" diff --git a/pipeline/release-cycle.py b/pipeline/release-cycle.py index 8b50a8e..e999a64 100644 --- a/pipeline/release-cycle.py +++ b/pipeline/release-cycle.py @@ -57,11 +57,43 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--config', default=os.environ.get('ARCHIPELAGO_CYCLE_CONFIG', '/etc/archipelago/release-cycle.json')) parser.add_argument('--mode', choices=('auto', 'ostree', 'iso'), default='auto') + parser.add_argument('--snapshot', default=None, + help='Repository view date, "latest", or "new" to capture one now') + parser.add_argument('--request', default=None, + help='Portal build request consumed once before the cycle starts') parser.add_argument('--resume', action='store_true', help='Continue the last failed run from its first incomplete phase') args = parser.parse_args() - mode = args.mode if args.mode != 'auto' else ('iso' if datetime.now(timezone.utc).day == 1 else 'ostree') config = json.loads(Path(args.config).read_text()) + # A portal request pins the mode and the immutable repository view. It is + # consumed exactly once and ignored if stale, so a scheduled run can never + # inherit a manual build's inputs. + request = None + request_path = Path(args.request) if args.request else Path(config['coordinator_root']) / 'data/private/release-cycle/cycle-request.json' + if request_path.exists(): + try: + candidate = json.loads(request_path.read_text()) + except (OSError, json.JSONDecodeError): + candidate = None + request_path.unlink(missing_ok=True) + if args.resume: + candidate = None + try: + age = (datetime.now(timezone.utc) - datetime.fromisoformat(candidate['requested_at'])).total_seconds() + except (TypeError, KeyError, ValueError): + age = None + if (candidate and candidate.get('mode') in ('iso', 'ostree') + and re.fullmatch(r'[0-9]{4}-[0-9]{2}-[0-9]{2}', candidate.get('snapshot', '')) + and age is not None and 0 <= age <= 900): + request = candidate + elif candidate is not None: + print('ignored stale or invalid portal request', flush=True) + if args.mode != 'auto': + mode = args.mode + elif request: + mode = request['mode'] + else: + mode = 'iso' if datetime.now(timezone.utc).day == 1 else 'ostree' variants = tuple(config.get('variants', ['core', 'gnome'])) if variants not in (('core', 'gnome'), ('core', 'gnome', 'kde')): raise ValueError('Supported cycle order: core, gnome, optionally kde') @@ -115,9 +147,12 @@ def main(): state = dict(version=1, run=stamp, started=datetime.now(timezone.utc).isoformat(), state='starting', published=False, channel='stable', output_mode=mode, invocation_id=os.environ.get('INVOCATION_ID'), worker=worker, - reason=os.environ.get('ARCHIPELAGO_RELEASE_REASON', 'D-098 Rust/manual release cycle')) + reason=os.environ.get('ARCHIPELAGO_RELEASE_REASON', 'D-098 Rust/manual release cycle'), + request=request) if resumed_state: state['snapshot_url'] = resumed_state.get('snapshot_url', '') + if resumed_state.get('snapshot'): + state['snapshot'] = resumed_state['snapshot'] state['resumed_from_phase'] = resumed_state.get('failed_phase') or resumed_state.get('state') step = 0 worker_units = [] @@ -205,20 +240,31 @@ def main(): # rolling mirror and lose a package that the mirror later prunes. phase('selecting-repository') snapshots = Path('/opt/archipelago/data/public/arch-repo-snapshot') - if datetime.now(timezone.utc).day == 1: + choice = args.snapshot or (request or {}).get('snapshot') or 'latest' + def capture_snapshot(): snapshot_proc = subprocess.run(['/usr/local/sbin/archipelago-mirror-snapshot'], capture_output=True, text=True) if snapshot_proc.returncode != 0: raise RuntimeError('mirror snapshot failed: ' + snapshot_proc.stderr.strip()) - snapshot_url = next(line.removeprefix('url=') for line - in reversed(snapshot_proc.stdout.splitlines()) if line.startswith('url=')) - else: + return next(line.removeprefix('url=') for line + in reversed(snapshot_proc.stdout.splitlines()) if line.startswith('url=')) + if choice == 'new' or (choice == 'latest' and datetime.now(timezone.utc).day == 1): + snapshot_url = capture_snapshot() + elif choice == 'latest': views = sorted(p.name for p in snapshots.iterdir() if p.is_dir()) if snapshots.is_dir() else [] if not views: raise RuntimeError('No repository snapshot available; run the cycle on the 1st to capture one') snapshot_url = (config['public_url'].rstrip('/') + '/arch-repo-snapshot/' + views[-1] + '/$repo/os/$arch') + else: + if not re.fullmatch(r'[0-9]{4}-[0-9]{2}-[0-9]{2}', choice): + raise ValueError('Invalid repository snapshot date: ' + choice) + if not (snapshots / choice / 'core/os/x86_64/core.db').is_file(): + raise RuntimeError('Requested repository snapshot is missing: ' + choice) + snapshot_url = config['public_url'].rstrip('/') + '/arch-repo-snapshot/' + choice + '/$repo/os/$arch' + state['snapshot'] = snapshot_url.split('/arch-repo-snapshot/')[1].split('/')[0] state['snapshot_url'] = snapshot_url + write_status(base, state) # Compile from the frozen source tree, not a possibly stale deployed CLI. previous_binary = '' if resume: diff --git a/tests/control_portal.py b/tests/control_portal.py index ecef3c7..52e2928 100644 --- a/tests/control_portal.py +++ b/tests/control_portal.py @@ -31,7 +31,7 @@ class Portal(unittest.TestCase): (root / 'escape.log').symlink_to('/etc/passwd') app.unit = lambda name: {'ActiveState': 'inactive'} called = [] - app.control = lambda action: called.append(action) or {'accepted': True} + app.control = lambda action, parameters=None: called.append((action, parameters)) or {'accepted': True} server = control.ThreadingHTTPServer(('127.0.0.1', 0), control.Handler) server.app = app host = f'127.0.0.1:{server.server_port}' @@ -62,13 +62,59 @@ class Portal(unittest.TestCase): headers['Origin'] = url with urlopen(Request(url+'/api/control', data=b'{"action":"start"}', headers=headers)) as response: self.assertEqual(response.status, 202) - self.assertEqual(called, ['start']) + self.assertEqual(called, [('start', {'action': 'start'})]) with self.assertRaises(HTTPError): urlopen(Request(url+'/', headers={'Host':'attacker.example'})) finally: server.shutdown() server.server_close() + def test_start_pins_mode_and_snapshot_before_the_unit_starts(self): + with tempfile.TemporaryDirectory() as directory: + base = Path(directory) + app = control.App(dict(coordinator_root=directory, worker_root=str(base / 'worker'), + worker_source_root=str(base / 'source'), + allowed_networks=['127.0.0.0/8'], hosts=[])) + app.unit = lambda name: {'ActiveState': 'inactive'} + asked = [] + app.snapshot_date = lambda choice: asked.append(choice) or '2026-11-12' + calls = [] + original = control.subprocess.run + control.subprocess.run = lambda argv, **kwargs: (calls.append(argv) + or subprocess.CompletedProcess(argv, 0, b'', b'')) + try: + result = app.control('start', {'action': 'start', 'mode': 'ostree', 'snapshot': 'latest'}) + finally: + control.subprocess.run = original + request = json.loads((app.archive / 'cycle-request.json').read_text()) + self.assertEqual((request['mode'], request['snapshot']), ('ostree', '2026-11-12')) + self.assertIn('requested_at', request) + self.assertEqual(result['request']['snapshot'], '2026-11-12') + self.assertEqual(calls, [['systemctl', 'start', '--no-block', control.SERVICE]]) + self.assertEqual(asked, ['latest']) + # Unknown modes are rejected before anything is pinned or started. + (app.archive / 'cycle-request.json').unlink() + with self.assertRaises(ValueError): + app.control('start', {'mode': 'reboot'}) + self.assertFalse((app.archive / 'cycle-request.json').exists()) + + def test_snapshot_listing_requires_a_complete_core_database(self): + with tempfile.TemporaryDirectory() as directory: + dataset = Path(directory) / 'archlinux' + complete = dataset / '.zfs/snapshot/monthly-2026-11-12/core/os/x86_64' + complete.mkdir(parents=True) + (complete / 'core.db').write_bytes(b'database') + (dataset / '.zfs/snapshot/monthly-2026-11-01').mkdir(parents=True) + app = control.App(dict(coordinator_root=directory, worker_root=directory, + worker_source_root=directory, snapshot_dataset=str(dataset), + allowed_networks=['127.0.0.0/8'], hosts=[])) + self.assertEqual([item['date'] for item in app.snapshots()], ['2026-11-12']) + self.assertEqual(app.snapshot_date('latest'), '2026-11-12') + self.assertEqual(app.snapshot_date('2026-11-12'), '2026-11-12') + for choice in ('2026-11-01', '../../etc', ''): + with self.assertRaises(ValueError): + app.snapshot_date(choice) + def test_progress_markup_and_percentage_rules(self): root = Path(__file__).parents[1] / 'control' html = (root / 'index.html').read_text() @@ -76,8 +122,11 @@ class Portal(unittest.TestCase): self.assertIn('id="run-progress-track"', html) self.assertIn('role="progressbar"', html) self.assertIn('aria-valuenow', html) + self.assertIn('id="build-mode"', html) + self.assertIn('id="build-snapshot"', html) self.assertIn('function progressOf(', script) self.assertIn("track.setAttribute('aria-valuenow'", script) + self.assertIn("control('start',{mode:$('build-mode').value,snapshot:$('build-snapshot').value})", script) def test_failed_action_is_durable(self): with tempfile.TemporaryDirectory() as directory: diff --git a/tests/release-schedule.py b/tests/release-schedule.py index f40002d..7ddd9e3 100644 --- a/tests/release-schedule.py +++ b/tests/release-schedule.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""D-098 cadence: anchored three-day OSTree grid and calendar-day-30 ISO.""" +"""D-108 cadence: one monthly ISO+OSTree cycle on the 1st at 00:00 UTC.""" import importlib.util from datetime import date, datetime, timezone from pathlib import Path @@ -8,26 +8,22 @@ spec = importlib.util.spec_from_file_location('schedule', Path(__file__).parents s = importlib.util.module_from_spec(spec) spec.loader.exec_module(s) -assert s.mode(date(2026, 11, 9)) == 'ostree' -for day in (12, 15, 18, 21, 24, 27): - assert s.mode(date(2026, 11, day)) == 'ostree', day -assert s.mode(date(2026, 11, 30)) == 'iso' -assert s.mode(date(2026, 11, 10)) is None and s.mode(date(2026, 11, 29)) is None -# The grid is an interval, not a day-of-month rule: it continues across the -# month and year boundary and never substitutes a missing calendar day. -for day in (date(2026, 12, 3), date(2026, 12, 6), date(2027, 1, 2)): - assert s.mode(day) == 'ostree', day -assert s.mode(date(2026, 12, 30)) == 'iso' -assert s.mode(date(2027, 2, 28)) == 'ostree' -assert s.mode(date(2026, 11, 8)) is None +assert s.mode(date(2026, 11, 1)) == 'iso' +assert s.mode(date(2026, 12, 1)) == 'iso' +assert s.mode(date(2027, 1, 1)) == 'iso' +# Calendar dates, not an interval: every other day is unscheduled. +for day in (date(2026, 11, 2), date(2026, 11, 15), date(2026, 11, 30)): + assert s.mode(day) is None, day +# February has no 30th; the rule must not substitute another date. +assert s.mode(date(2027, 2, 28)) is None and s.mode(date(2027, 3, 1)) == 'iso' -assert s.next_release(datetime(2026, 11, 9, 12, tzinfo=timezone.utc)) == { - 'date': '2026-11-12', 'mode': 'ostree', 'time': '00:00 UTC'} -assert s.next_release(datetime(2026, 11, 29, 23, tzinfo=timezone.utc))['mode'] == 'iso' -assert s.next_release(datetime(2026, 11, 30, 1, tzinfo=timezone.utc))['date'] == '2026-12-03' -assert s.next_release(datetime(2027, 2, 27, tzinfo=timezone.utc))['date'] == '2027-02-28' -for start in (datetime(2026, 11, 9, tzinfo=timezone.utc), datetime(2027, 3, 29, tzinfo=timezone.utc)): +assert s.next_release(datetime(2026, 11, 15, 12, tzinfo=timezone.utc)) == { + 'date': '2026-12-01', 'mode': 'iso', 'time': '00:00 UTC'} +assert s.next_release(datetime(2026, 11, 30, 23, tzinfo=timezone.utc))['date'] == '2026-12-01' +assert s.next_release(datetime(2026, 12, 1, 0, 1, tzinfo=timezone.utc))['date'] == '2027-01-01' +assert s.next_release(datetime(2027, 2, 1, tzinfo=timezone.utc))['date'] == '2027-03-01' +for start in (datetime(2026, 11, 15, tzinfo=timezone.utc), datetime(2027, 1, 31, tzinfo=timezone.utc)): nxt = s.next_release(start) day = date.fromisoformat(nxt['date']) - assert day > start.date() and s.mode(day) == nxt['mode'] + assert day > start.date() and day.day == 1 and s.mode(day) == nxt['mode'] print('RELEASE_SCHEDULE_PASS')