Native libostree kernel arguments; fail-safe OSTree object collection
This commit is contained in:
parent
10bbfa7de9
commit
35b6ef50d1
13 changed files with 602 additions and 370 deletions
2
Cargo.lock
generated
2
Cargo.lock
generated
|
|
@ -30,6 +30,7 @@ name = "archipelago-builder"
|
|||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"archipelago-contracts",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -61,6 +62,7 @@ dependencies = [
|
|||
"archipelago-builder",
|
||||
"archipelago-composer",
|
||||
"archipelago-contracts",
|
||||
"libc",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
|
|
|
|||
|
|
@ -15,3 +15,4 @@ zbus = { version = "=5.12.0", default-features = false, features = ["async-io",
|
|||
# Macro releases use private zbus dispatch APIs; pin the matching family too.
|
||||
zbus_macros = "=5.12.0"
|
||||
sha2 = "=0.10.9"
|
||||
libc = "=0.2.191"
|
||||
|
|
|
|||
74
SERVICE.md
74
SERVICE.md
|
|
@ -1,34 +1,46 @@
|
|||
# archipelagod implementation checkpoint
|
||||
|
||||
## 2026-11-16 checkpoint: native libostree kernel arguments
|
||||
|
||||
`system/src/service/kargs.rs` no longer runs `python3 adapters/kernel-arguments.py`.
|
||||
The same libostree calls (parse, append, append-if-missing, delete,
|
||||
delete-if-present, new-replace, `to_strv`, sysroot/deployment/bootconfig reads) are
|
||||
resolved with `dlopen`/`dlsym` and called through a typed FFI surface. Dynamic
|
||||
loading is deliberate: the release build image has no libostree, so linking would
|
||||
break the Cargo stage; the installed host has the library and gets a clear
|
||||
"libostree-1.so.1 is not available" error otherwise. The Python adapter and its
|
||||
fixture are deleted; validation and deployment-argument construction remain covered
|
||||
by Rust tests.
|
||||
|
||||
## 2026-11-16 checkpoint: guarded OSTree object collection
|
||||
|
||||
Installed hosts accumulated image objects forever. `ostree prune` without
|
||||
Installed hosts accumulated unreachable objects. `ostree prune` without
|
||||
`--refs-only` traverses *every* commit in the repository, so it only removes objects
|
||||
that were written but never committed; old image commits stay alive. `--refs-only`
|
||||
does collect them, but then the deployed systems must be reachable from refs. The new
|
||||
`system/src/gc.rs` makes that explicit:
|
||||
that were written but never committed; `--refs-only` collects objects no ref can
|
||||
reach. The first GC implementation was too aggressive: it ran `admin cleanup` before
|
||||
boot-readiness evidence existed, removed service refs without following overlay
|
||||
intent, and leaked its own old keep refs. Audit found this could retire recovery roots
|
||||
and, paradoxically, could keep old objects pinned forever.
|
||||
|
||||
- `archipelago cleanup plan [--json]` is a read-only inventory: deployments with
|
||||
roles, protected commits (deployment checksums plus their `archipelago.base`,
|
||||
`archipelago.layer-core` and `archipelago.layer-purpose` metadata), keep refs to
|
||||
create, unreferenced `service/*` composition refs, repository size and the guard
|
||||
result.
|
||||
- `archipelago cleanup apply` takes the same host mutation lock as updates and
|
||||
extensions, refuses to run in the live environment, without a booted deployment or
|
||||
while a pending/staged deployment exists, runs `ostree admin cleanup`, mirrors every
|
||||
retained deployment into `archipelago/keep/<checksum>` refs, drops `service/bases`,
|
||||
`service/overlays` and `service/overlay-builds` refs that no retained deployment
|
||||
names, verifies every protected commit resolves, then runs
|
||||
`ostree prune --refs-only`. Each protected deployment is re-read afterwards; a
|
||||
vanished commit is reported as a critical failure. The record (protected commits,
|
||||
prune output, bytes before/after) is written to `/var/lib/archipelago/cleanup/`.
|
||||
- `archipelago cleanup plan [--json]` is read-only and inventories deployment
|
||||
roots, overlay-selected/source layer commits, Host Extension bases and active-context
|
||||
plan targets. It lists service refs that look unreferenced but explicitly marks
|
||||
them **retained** until a history/readiness policy exists.
|
||||
- `archipelago cleanup apply` takes the shared host mutation lock, refuses live/no-booted/
|
||||
pending states, establishes keep refs for the complete protected commit graph and
|
||||
invokes only `ostree prune --refs-only`. It does **not** run `admin cleanup`, delete
|
||||
deployments or remove any old keep/service/history refs. The record stores protected
|
||||
commit identities and the before/after repo size in `/var/lib/archipelago/cleanup/`.
|
||||
This safely removes objects already unreachable from every ref; it cannot yet
|
||||
reclaim commits kept alive by obsolete deployment/history refs.
|
||||
- The `archipelago-ostree-gc.timer` unit (30 minutes after boot, then weekly) runs the
|
||||
guarded apply on installed hosts; the live ISO is excluded by condition.
|
||||
|
||||
Unit tests cover deployment parsing, the pending/unbooted guards, keep-ref mirroring
|
||||
and stale composition refs. The engine compiles and those tests pass; actual pruning
|
||||
on real hardware remains a user-verified scenario, and `cleanup plan` is the
|
||||
read-only way to inspect a host before it runs.
|
||||
Unit tests cover deployment parsing, pending/unbooted guards, keep-root calculation,
|
||||
overlay source/layer roots and the non-retirement of stale refs. This is deliberately
|
||||
not full D-046 cleanup: D-047/D-048 boot checks and durable success records must exist
|
||||
before automatically retiring unpinned deployments or expiring service/history refs.
|
||||
Actual pruning on hardware remains user-verified; first inspect with `cleanup plan`.
|
||||
|
||||
## 2026-11-16 checkpoint: quoted release code name
|
||||
|
||||
|
|
@ -69,11 +81,10 @@ The hardware import failure had one cause: the identity cross-check ran
|
|||
`pacman --config /dev/null -Qp`, which opens the default `/var/lib/pacman` that an
|
||||
installed OSTree host does not have. Every pacman call in the service now names
|
||||
`/usr/lib/archipelago/package-db` (`inputs::PACKAGE_DB`, shared argument builder),
|
||||
and `system/tests/local_package_import.py` fails the build if any service pacman
|
||||
invocation loses the explicit database path. The same script checks that import
|
||||
precedes planning in the CLI, that one plan covers a mixed request, that the
|
||||
capability identifiers match the implemented interfaces, and that the disposable
|
||||
package workspace is removed whole.
|
||||
Native Rust tests assert that the import identity query uses the explicit image
|
||||
DBPath and that CLI parsing keeps local paths separate from package names. The
|
||||
Cockpit updater contract also has a native Rust test; the release build no longer
|
||||
executes Python test fixtures for these checks.
|
||||
|
||||
`Sandbox::release` now deletes the entire per-operation directory (request files,
|
||||
copied archives, adapter, checkout) instead of only the checkout, is not skipped by
|
||||
|
|
@ -83,11 +94,10 @@ prevents the private copies of processed packages that accumulated in
|
|||
`/var/lib/archipelago/service/package-work`.
|
||||
|
||||
Verification: `cargo test` for `archipelago`, `archipelago-system`,
|
||||
`archipelago-builder`, `archipelago-composer` (system suite 40 tests, including the
|
||||
new database-path and argument-splitting cases) and
|
||||
`python3 system/tests/local_package_import.py` (6 checks). Hardware acceptance of
|
||||
the corrected import is a user manual check on an installed image that carries
|
||||
this source.
|
||||
`archipelago-builder`, `archipelago-composer` (system suite 43 tests, including the
|
||||
database-path, argument-splitting and GC-root cases; builder checks the Cockpit
|
||||
assets and typed D-Bus operations). Hardware acceptance of the corrected import is
|
||||
a user manual check on an installed image that carries this source.
|
||||
|
||||
## 2026-11-14 checkpoint: observable progress and distributor identity
|
||||
|
||||
|
|
|
|||
|
|
@ -1,116 +0,0 @@
|
|||
"""Private read/transform adapter using libostree; never edits boot entries.
|
||||
|
||||
The Rust service owns authorization, locking, durable intent and staged deployment.
|
||||
"""
|
||||
import ctypes as C
|
||||
import json
|
||||
import sys
|
||||
|
||||
ostree = C.CDLL('libostree-1.so.1')
|
||||
glib = C.CDLL('libglib-2.0.so.0')
|
||||
gobject = C.CDLL('libgobject-2.0.so.0')
|
||||
P = C.c_void_p
|
||||
S = C.c_char_p
|
||||
|
||||
|
||||
def bind(lib, name, result, *args):
|
||||
f = getattr(lib, name)
|
||||
f.restype, f.argtypes = result, list(args)
|
||||
return f
|
||||
|
||||
|
||||
class Error(C.Structure):
|
||||
_fields_ = [('domain', C.c_uint), ('code', C.c_int), ('message', S)]
|
||||
|
||||
|
||||
class Array(C.Structure):
|
||||
_fields_ = [('pdata', C.POINTER(P)), ('len', C.c_uint)]
|
||||
|
||||
|
||||
def checked(f, *args):
|
||||
error = C.POINTER(Error)()
|
||||
if not f(*args, C.byref(error)):
|
||||
message = error.contents.message.decode() if error else 'libostree operation failed'
|
||||
if error:
|
||||
bind(glib, 'g_error_free', None, P)(error)
|
||||
raise ValueError(message)
|
||||
|
||||
|
||||
def arguments(options, changes):
|
||||
kargs = bind(ostree, 'ostree_kernel_args_from_string', P, S)(options)
|
||||
try:
|
||||
for change in changes:
|
||||
op, arg = change['op'], change['argument']
|
||||
if not arg or len(arg) > 4096 or any(c in arg for c in '\x00\r\n') or arg.split('=', 1)[0] == 'ostree':
|
||||
raise ValueError('Invalid kernel argument or protected ostree selector')
|
||||
# Native operations split their input again. Validate the complete
|
||||
# token, not only its first key, before passing it to libostree.
|
||||
if arg.count('"') % 2 or arguments(arg.encode(), []) != [arg]:
|
||||
raise ValueError('Expected exactly one kernel argument with balanced quotes')
|
||||
if op in ('append', 'append-if-missing'):
|
||||
name = 'ostree_kernel_args_' + op.replace('-', '_')
|
||||
bind(ostree, name, None, P, S)(kargs, arg.encode())
|
||||
elif op in ('delete', 'delete-if-present', 'replace'):
|
||||
name = 'ostree_kernel_args_' + ('new_replace' if op == 'replace' else op.replace('-', '_'))
|
||||
checked(bind(ostree, name, C.c_int, P, S, C.POINTER(C.POINTER(Error))), kargs, arg.encode())
|
||||
else:
|
||||
raise ValueError('Unknown kernel argument operation')
|
||||
vector = bind(ostree, 'ostree_kernel_args_to_strv', C.POINTER(S), P)(kargs)
|
||||
try:
|
||||
result, i = [], 0
|
||||
while vector[i] is not None:
|
||||
token = vector[i].decode()
|
||||
if token.split('=', 1)[0] != 'ostree':
|
||||
result.append(token)
|
||||
i += 1
|
||||
return result
|
||||
finally:
|
||||
bind(glib, 'g_strfreev', None, C.POINTER(S))(vector)
|
||||
finally:
|
||||
bind(ostree, 'ostree_kernel_args_free', None, P)(kargs)
|
||||
|
||||
|
||||
def snapshot(changes):
|
||||
root = bind(ostree, 'ostree_sysroot_new_default', P)()
|
||||
try:
|
||||
checked(bind(ostree, 'ostree_sysroot_load', C.c_int, P, P, C.POINTER(C.POINTER(Error))), root, None)
|
||||
booted = bind(ostree, 'ostree_sysroot_get_booted_deployment', P, P)(root)
|
||||
deployments = bind(ostree, 'ostree_sysroot_get_deployments', C.POINTER(Array), P)(root)
|
||||
try:
|
||||
result = []
|
||||
options_by_id = {}
|
||||
for index in range(deployments.contents.len):
|
||||
d = deployments.contents.pdata[index]
|
||||
osname = bind(ostree, 'ostree_deployment_get_osname', S, P)(d).decode()
|
||||
if osname != 'archipelago':
|
||||
continue
|
||||
checksum = bind(ostree, 'ostree_deployment_get_csum', S, P)(d).decode()
|
||||
serial = bind(ostree, 'ostree_deployment_get_deployserial', C.c_int, P)(d)
|
||||
config = bind(ostree, 'ostree_deployment_get_bootconfig', P, P)(d)
|
||||
if not config:
|
||||
raise ValueError('Deployment boot configuration unavailable')
|
||||
options = bind(ostree, 'ostree_bootconfig_parser_get', S, P, S)(config, b'options')
|
||||
if options is None:
|
||||
raise ValueError('Deployment kernel arguments unavailable')
|
||||
result.append(dict(deployment_id=f'{osname}/{checksum}.{serial}', checksum=checksum,
|
||||
booted=d == booted, staged=bool(bind(ostree, 'ostree_deployment_is_staged', C.c_int, P)(d)),
|
||||
arguments=arguments(options, [])))
|
||||
options_by_id[result[-1]['deployment_id']] = options
|
||||
if changes is not None:
|
||||
selected = next((d for d in result if d['staged']), None) or next((d for d in result if d['booted']), None)
|
||||
if selected is None:
|
||||
raise ValueError('No booted deployment')
|
||||
selected['edited'] = arguments(options_by_id[selected['deployment_id']], changes)
|
||||
return result
|
||||
finally:
|
||||
bind(glib, 'g_ptr_array_unref', None, C.POINTER(Array))(deployments)
|
||||
finally:
|
||||
bind(gobject, 'g_object_unref', None, P)(root)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
print(json.dumps(snapshot(json.loads(sys.argv[1]) if len(sys.argv) > 1 else None)))
|
||||
except Exception as error:
|
||||
print(str(error), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
17
integrations/plymouth/README.md
Normal file
17
integrations/plymouth/README.md
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
# Archipelago Plymouth BGRT theme
|
||||
|
||||
`archipelago-bgrt.plymouth` is based on the BGRT/two-step theme shipped by the
|
||||
OSTree build snapshot. The Purpose adapter copies the snapshot's Spinner animation
|
||||
assets into a separately owned theme directory, then replaces only `watermark.png`
|
||||
with the rasterized Archipelago icon. The upstream Spinner directory and package
|
||||
ownership remain untouched.
|
||||
|
||||
The theme preserves BGRT/two-step progress and uses `UseFirmwareBackground=false`
|
||||
for boot-up, reboot and shutdown. This suppresses the firmware-provided logo (which
|
||||
may itself be an Arch Linux logo), while the custom watermark supplies the
|
||||
distribution identity. The GNOME/KDE initramfs checks assert that both the custom
|
||||
theme descriptor and its watermark are included.
|
||||
|
||||
The PNG is generated deterministically from `../icons/archipelago.svg` using the
|
||||
pinned build-tools image's ImageMagick `convert` (`-resize 128x128 -background
|
||||
none`). Regenerate it only when the source icon changes and review the output.
|
||||
66
integrations/plymouth/archipelago-bgrt.plymouth
Normal file
66
integrations/plymouth/archipelago-bgrt.plymouth
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
[Plymouth Theme]
|
||||
Name=Archipelago BGRT
|
||||
Description=BGRT-style two-step boot splash with Archipelago branding and no firmware logo
|
||||
ModuleName=two-step
|
||||
|
||||
[two-step]
|
||||
Font=Adwaita Sans 12
|
||||
TitleFont=Adwaita Sans Light 30
|
||||
MonospaceFont=Adwaita Mono 12
|
||||
ImageDir=/usr/share/plymouth/themes/archipelago-bgrt
|
||||
DialogHorizontalAlignment=.5
|
||||
DialogVerticalAlignment=.382
|
||||
TitleHorizontalAlignment=.5
|
||||
TitleVerticalAlignment=.382
|
||||
HorizontalAlignment=.5
|
||||
VerticalAlignment=.7
|
||||
WatermarkHorizontalAlignment=.5
|
||||
WatermarkVerticalAlignment=.92
|
||||
Transition=none
|
||||
TransitionDuration=0.0
|
||||
BackgroundStartColor=0x0d161c
|
||||
BackgroundEndColor=0x0d161c
|
||||
ProgressBarBackgroundColor=0x267c88
|
||||
ProgressBarForegroundColor=0x35d2d0
|
||||
DialogClearsFirmwareBackground=false
|
||||
MessageBelowAnimation=true
|
||||
|
||||
[boot-up]
|
||||
UseEndAnimation=false
|
||||
UseFirmwareBackground=false
|
||||
|
||||
[shutdown]
|
||||
UseEndAnimation=false
|
||||
UseFirmwareBackground=false
|
||||
|
||||
[reboot]
|
||||
UseEndAnimation=false
|
||||
UseFirmwareBackground=false
|
||||
|
||||
[updates]
|
||||
SuppressMessages=true
|
||||
ProgressBarShowPercentComplete=true
|
||||
UseProgressBar=true
|
||||
Title=Installing Updates...
|
||||
SubTitle=Do not turn off your computer
|
||||
|
||||
[system-upgrade]
|
||||
SuppressMessages=true
|
||||
ProgressBarShowPercentComplete=true
|
||||
UseProgressBar=true
|
||||
Title=Upgrading System...
|
||||
SubTitle=Do not turn off your computer
|
||||
|
||||
[firmware-upgrade]
|
||||
SuppressMessages=true
|
||||
ProgressBarShowPercentComplete=true
|
||||
UseProgressBar=true
|
||||
Title=Upgrading Firmware...
|
||||
SubTitle=Do not turn off your computer
|
||||
|
||||
[system-reset]
|
||||
SuppressMessages=true
|
||||
ProgressBarShowPercentComplete=true
|
||||
UseProgressBar=true
|
||||
Title=Resetting System...
|
||||
SubTitle=Do not turn off your computer
|
||||
BIN
integrations/plymouth/watermark.png
Normal file
BIN
integrations/plymouth/watermark.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 7.5 KiB |
294
src/gc.rs
294
src/gc.rs
|
|
@ -1,16 +1,17 @@
|
|||
//! Guarded OSTree object collection.
|
||||
//!
|
||||
//! `ostree prune` without `--refs-only` traverses *every* commit in the repository,
|
||||
//! so it only removes objects that were written but never committed. Old image
|
||||
//! commits therefore stay alive forever and the object store grows with each
|
||||
//! update. `--refs-only` does collect those commits, but then the commits of the
|
||||
//! deployed systems must be reachable from refs. This module makes that reachability
|
||||
//! explicit with `archipelago/keep/<checksum>` refs before pruning, keeps the
|
||||
//! service refs still referenced by a retained deployment, and refuses to run in
|
||||
//! states where the protected set cannot be established. It never walks the object
|
||||
//! store itself.
|
||||
//! so it only removes objects that were written but never committed. `--refs-only`
|
||||
//! collects objects unreachable from refs. This module makes deployments and the
|
||||
//! commits they reference explicit GC roots with `archipelago/keep/<checksum>`
|
||||
//! refs. It deliberately does not run `ostree admin cleanup` or delete service,
|
||||
//! plan, generation or old keep refs: destructive retention requires the
|
||||
//! deployment-bound readiness records mandated by D-046/D-047, which are not yet
|
||||
//! implemented. The timer therefore only collects objects already unreachable from
|
||||
//! every retained ref.
|
||||
use serde_json::Value;
|
||||
use std::{collections::BTreeSet, fs, io::Write, os::unix::fs::OpenOptionsExt, path::Path, process::Command, time::{SystemTime, UNIX_EPOCH}};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{collections::BTreeSet, fs, io::Write, os::unix::fs::{MetadataExt, OpenOptionsExt}, path::Path, process::Command, time::{SystemTime, UNIX_EPOCH}};
|
||||
|
||||
const REPO: &str = "/sysroot/ostree/repo";
|
||||
const STATE: &str = "/var/lib/archipelago/cleanup";
|
||||
|
|
@ -26,6 +27,7 @@ const PROTECTED_KEYS: [&str; 3] = ["archipelago.base", "archipelago.layer-core",
|
|||
pub(crate) struct Deployment {
|
||||
pub checksum: String,
|
||||
pub serial: u64,
|
||||
pub archipelago: bool,
|
||||
pub booted: bool,
|
||||
pub pending: bool,
|
||||
pub pinned: bool,
|
||||
|
|
@ -36,7 +38,10 @@ fn digest(value: &str) -> bool {
|
|||
}
|
||||
|
||||
fn command(program: &str, args: &[&str]) -> Result<String, String> {
|
||||
let output = Command::new(program).args(args).env("LC_ALL", "C").output()
|
||||
// A full object walk must not leave the weekly maintenance job indefinitely
|
||||
// alive. OSTree prune is bounded to the release worker's four-hour action SLA.
|
||||
let output = Command::new("timeout").args(["--kill-after=15", "14400", program]).args(args)
|
||||
.env("LC_ALL", "C").output()
|
||||
.map_err(|e| format!("{program}: {e}"))?;
|
||||
if !output.status.success() {
|
||||
return Err(format!("{program} {}: {}", args.join(" "), String::from_utf8_lossy(&output.stderr).trim()));
|
||||
|
|
@ -66,6 +71,7 @@ pub(crate) fn parse_deployments(status: &Value) -> Result<Vec<Deployment>, Strin
|
|||
result.push(Deployment {
|
||||
checksum: checksum.to_owned(),
|
||||
serial,
|
||||
archipelago: entry["stateroot"] == "archipelago",
|
||||
booted: entry["booted"] == true,
|
||||
pending: entry["pending"] == true || entry["staged"] == true,
|
||||
pinned: entry["pinned"] == true,
|
||||
|
|
@ -89,34 +95,168 @@ pub(crate) fn preconditions(deployments: &[Deployment]) -> Result<(), String> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Keep refs mirror the current deployment set. Creates protect a commit before
|
||||
/// pruning; removals only drop protection for deployments that no longer exist.
|
||||
pub(crate) fn keep_ref_sync(existing: &[String], deployments: &[Deployment])
|
||||
-> (Vec<(String, String)>, Vec<String>) {
|
||||
let desired: BTreeSet<&str> = deployments.iter().map(|deployment| deployment.checksum.as_str()).collect();
|
||||
/// Create missing keep refs for the complete protected commit graph. Existing
|
||||
/// refs are never removed here; their retirement must use readiness-bound policy.
|
||||
pub(crate) fn keep_ref_sync(existing: &[String], protected: &BTreeSet<String>)
|
||||
-> Vec<(String, String)> {
|
||||
let mut create = Vec::new();
|
||||
for commit in &desired {
|
||||
for commit in protected {
|
||||
let name = format!("{KEEP}/{commit}");
|
||||
if !existing.iter().any(|ref_name| ref_name == &name) {
|
||||
create.push((name, (*commit).to_owned()));
|
||||
}
|
||||
}
|
||||
let remove = existing.iter().filter(|ref_name| ref_name.starts_with(&format!("{KEEP}/")))
|
||||
.filter(|ref_name| {
|
||||
let commit = ref_name.rsplit('/').next().unwrap_or("");
|
||||
!desired.contains(commit)
|
||||
}).cloned().collect();
|
||||
(create, remove)
|
||||
create
|
||||
}
|
||||
|
||||
/// Service refs built by planning belong to one composition. Anything not named by
|
||||
/// a retained deployment is a build artifact and may be dropped.
|
||||
fn stale_keep_refs(refs: &[(String, String)], protected: &BTreeSet<String>) -> Vec<(String, String)> {
|
||||
refs.iter().filter(|(name, _)| name.starts_with(&format!("{KEEP}/")))
|
||||
.filter(|(_, commit)| !protected.contains(commit))
|
||||
.cloned().collect()
|
||||
}
|
||||
|
||||
/// Candidate service refs not directly referenced by a deployment. This is an
|
||||
/// informational list only: plans/history may still refer to them, so GC must not
|
||||
/// delete these refs until their durable retention policy exists.
|
||||
pub(crate) fn stale_service_refs(refs: &[(String, String)], desired: &BTreeSet<String>) -> Vec<(String, String)> {
|
||||
refs.iter().filter(|(name, _)| SERVICE_PREFIXES.iter().any(|prefix| name.starts_with(prefix)))
|
||||
.filter(|(_, target)| !desired.contains(target))
|
||||
.cloned().collect()
|
||||
}
|
||||
|
||||
/// Compute every commit needed to interpret the retained deployments. Overlay
|
||||
/// layer commits are nested in managed-overlays.json and are not all named by
|
||||
/// OSTree commit metadata; dropping their service refs would break future rebase.
|
||||
fn protected_commits(deployments: &[Deployment]) -> Result<BTreeSet<String>, String> {
|
||||
let mut protected = BTreeSet::new();
|
||||
for deployment in deployments {
|
||||
let image = deployment.checksum.as_str();
|
||||
repository(&["ls", image, "/"])?;
|
||||
protected.insert(deployment.checksum.clone());
|
||||
for key in PROTECTED_KEYS {
|
||||
if let Some(commit) = metadata_commit(image, key)? { protected.insert(commit); }
|
||||
}
|
||||
let directory = repository(&["ls", image, "/usr/lib/archipelago"])?;
|
||||
if directory.lines().any(|line| line.ends_with("/managed-overlays.json")) {
|
||||
let raw = repository(&["cat", image, "/usr/lib/archipelago/managed-overlays.json"])?;
|
||||
let intent: Value = serde_json::from_str(&raw)
|
||||
.map_err(|_| format!("malformed managed overlay intent in {image}"))?;
|
||||
if intent["version"].as_u64() != Some(0) {
|
||||
return Err(format!("unsupported managed overlay intent in {image}"));
|
||||
}
|
||||
insert_digest(&mut protected, &intent["clean_base"], "overlay clean base")?;
|
||||
for overlay in intent["selection"].as_array().ok_or("missing overlay selection")? {
|
||||
insert_digest(&mut protected, &overlay["commit"], "selected overlay commit")?;
|
||||
}
|
||||
let inputs = &intent["inputs"];
|
||||
if let Some(layers) = inputs["layers"].as_array() {
|
||||
for layer in layers { insert_digest(&mut protected, &layer["commit"], "resolved overlay layer")?; }
|
||||
}
|
||||
if let Some(declarations) = inputs["declarations"].as_array() {
|
||||
for declaration in declarations {
|
||||
insert_digest(&mut protected, &declaration["source_commit"], "overlay source layer")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
if directory.lines().any(|line| line.ends_with("/extensions.json")) {
|
||||
let raw = repository(&["cat", image, "/usr/lib/archipelago/extensions.json"])?;
|
||||
let intent: Value = serde_json::from_str(&raw)
|
||||
.map_err(|_| format!("malformed Host Extension intent in {image}"))?;
|
||||
if let Some(base) = intent.get("base") { insert_digest(&mut protected, base, "Host Extension base")?; }
|
||||
}
|
||||
}
|
||||
protected.extend(active_plan_commits(deployments)?);
|
||||
// Fail closed before ref changes if any manifest-protected commit is absent.
|
||||
for commit in &protected {
|
||||
repository(&["ls", commit, "/"])
|
||||
.map_err(|error| format!("protected commit {commit} is unavailable: {error}"))?;
|
||||
}
|
||||
Ok(protected)
|
||||
}
|
||||
|
||||
/// A persisted plan can still be staged while its deployment context is current.
|
||||
/// Protect its exact targets and overlay layer inputs; plans for another booted
|
||||
/// identity are already PlanStale and do not pin old OSTree history forever.
|
||||
fn active_plan_commits(deployments: &[Deployment]) -> Result<BTreeSet<String>, String> {
|
||||
const PLANS: &str = "/var/lib/archipelago/service/plans";
|
||||
let Some(booted) = deployments.iter().find(|deployment| deployment.archipelago && deployment.booted) else {
|
||||
return Err("missing booted Archipelago deployment for plan retention".into());
|
||||
};
|
||||
let booted_id = format!("archipelago/{}.{}", booted.checksum, booted.serial);
|
||||
let pending_id = deployments.iter().find(|deployment| deployment.archipelago && deployment.pending)
|
||||
.map(|deployment| format!("archipelago/{}.{}", deployment.checksum, deployment.serial));
|
||||
let root = Path::new(PLANS);
|
||||
if let Ok(metadata) = fs::symlink_metadata(root) {
|
||||
if !metadata.is_dir() || metadata.file_type().is_symlink() || metadata.uid() != 0 || metadata.mode() & 0o077 != 0 {
|
||||
return Err("plan store must be a private root-owned directory".into());
|
||||
}
|
||||
}
|
||||
let entries = match fs::read_dir(root) {
|
||||
Ok(entries) => entries,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeSet::new()),
|
||||
Err(error) => return Err(format!("cannot inventory retained plans: {error}")),
|
||||
};
|
||||
let root_metadata = fs::symlink_metadata(root).map_err(|error| format!("invalid plan store: {error}"))?;
|
||||
if !root_metadata.is_dir() || root_metadata.uid() != 0 || root_metadata.mode() & 0o077 != 0 {
|
||||
return Err("plan store must be a private root-owned directory".into());
|
||||
}
|
||||
let mut commits = BTreeSet::new();
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|error| format!("cannot inventory retained plans: {error}"))?;
|
||||
let path = entry.path();
|
||||
if path.extension().and_then(|value| value.to_str()) != Some("json") { continue; }
|
||||
let name = path.file_stem().and_then(|value| value.to_str()).ok_or("invalid plan filename")?;
|
||||
if !digest(name) { continue; }
|
||||
let metadata = fs::symlink_metadata(&path).map_err(|error| format!("invalid retained plan: {error}"))?;
|
||||
if !metadata.is_file() || metadata.uid() != 0 || metadata.mode() & 0o077 != 0 || metadata.len() > 32 * 1024 * 1024 {
|
||||
return Err(format!("unsafe retained plan record {}", path.display()));
|
||||
}
|
||||
let raw = fs::read(&path).map_err(|error| format!("cannot read retained plan: {error}"))?;
|
||||
let hash = format!("{:x}", Sha256::digest(&raw));
|
||||
if hash != name { return Err(format!("retained plan identity mismatch: {}", path.display())); }
|
||||
let plan: Value = serde_json::from_slice(&raw).map_err(|_| format!("malformed retained plan {}", path.display()))?;
|
||||
if plan["version"].as_u64() != Some(1) { return Err(format!("unsupported retained plan {}", path.display())); }
|
||||
let context = &plan["context"];
|
||||
if context["booted"].as_str() != Some(&booted_id) ||
|
||||
context["pending"].as_str() != pending_id.as_deref() {
|
||||
continue;
|
||||
}
|
||||
collect_plan_commits(&plan, &mut commits)?;
|
||||
}
|
||||
for commit in &commits {
|
||||
repository(&["ls", commit, "/"])
|
||||
.map_err(|error| format!("retained plan references unavailable commit {commit}: {error}"))?;
|
||||
}
|
||||
Ok(commits)
|
||||
}
|
||||
|
||||
fn collect_plan_commits(value: &Value, output: &mut BTreeSet<String>) -> Result<(), String> {
|
||||
const COMMIT_KEYS: [&str; 9] = ["target", "managed_base", "clean_base", "upstream_target",
|
||||
"commit", "source_commit", "catalog_commit", "base", "image"];
|
||||
match value {
|
||||
Value::Object(object) => {
|
||||
for (key, child) in object {
|
||||
if COMMIT_KEYS.contains(&key.as_str()) {
|
||||
if let Some(text) = child.as_str() {
|
||||
if digest(text) { output.insert(text.to_owned()); }
|
||||
}
|
||||
}
|
||||
collect_plan_commits(child, output)?;
|
||||
}
|
||||
}
|
||||
Value::Array(rows) => for row in rows { collect_plan_commits(row, output)?; },
|
||||
_ => (),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn insert_digest(set: &mut BTreeSet<String>, value: &Value, label: &str) -> Result<(), String> {
|
||||
let commit = value.as_str().filter(|commit| digest(commit))
|
||||
.ok_or_else(|| format!("invalid {label} in retained deployment"))?;
|
||||
set.insert(commit.to_owned());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Human/JSON inventory. Read-only: it reports what apply would consider and
|
||||
/// refuses to pretend it can predict the exact byte count without pruning.
|
||||
pub fn plan(as_json: bool) -> Result<(), String> {
|
||||
|
|
@ -124,16 +264,18 @@ pub fn plan(as_json: bool) -> Result<(), String> {
|
|||
let status: Value = serde_json::from_str(&ostree(&["admin", "status", "--json"])?)
|
||||
.map_err(|_| "invalid OSTree deployment status".to_string())?;
|
||||
let deployments = parse_deployments(&status)?;
|
||||
let guard = preconditions(&deployments);
|
||||
let mut guard = preconditions(&deployments);
|
||||
let refs = list_refs()?;
|
||||
let mut protected: BTreeSet<String> = deployments.iter().map(|deployment| deployment.checksum.clone()).collect();
|
||||
for deployment in &deployments {
|
||||
for key in PROTECTED_KEYS {
|
||||
if let Some(commit) = metadata_commit(&deployment.checksum, key) { protected.insert(commit); }
|
||||
let protected = match protected_commits(&deployments) {
|
||||
Ok(protected) => protected,
|
||||
Err(error) => {
|
||||
guard = Err(format!("cannot establish protected object roots: {error}"));
|
||||
deployments.iter().map(|deployment| deployment.checksum.clone()).collect()
|
||||
}
|
||||
}
|
||||
};
|
||||
let stale = stale_service_refs(&refs, &protected);
|
||||
let (create, remove) = keep_ref_sync(&ref_names(&refs), &deployments);
|
||||
let stale_keep = stale_keep_refs(&refs, &protected);
|
||||
let create = keep_ref_sync(&ref_names(&refs), &protected);
|
||||
if as_json {
|
||||
println!("{}", serde_json::json!({
|
||||
"deployments": deployments.iter().map(|deployment| serde_json::json!({
|
||||
|
|
@ -142,8 +284,9 @@ pub fn plan(as_json: bool) -> Result<(), String> {
|
|||
"pinned": deployment.pinned})).collect::<Vec<_>>(),
|
||||
"protected_commits": protected,
|
||||
"keep_refs_to_create": create.iter().map(|(name, _)| name).collect::<Vec<_>>(),
|
||||
"keep_refs_to_remove": remove,
|
||||
"stale_service_refs": stale.iter().map(|(name, target)| serde_json::json!({
|
||||
"old_keep_refs_retained_pending_readiness": stale_keep.iter().map(|(name, target)| serde_json::json!({
|
||||
"ref": name, "commit": target})).collect::<Vec<_>>(),
|
||||
"service_refs_retained_pending_history_policy": stale.iter().map(|(name, target)| serde_json::json!({
|
||||
"ref": name, "commit": target})).collect::<Vec<_>>(),
|
||||
"repository_bytes": repository_bytes(),
|
||||
"guard": match &guard { Err(error) => Some(error.clone()), Ok(_) => None },
|
||||
|
|
@ -160,9 +303,11 @@ pub fn plan(as_json: bool) -> Result<(), String> {
|
|||
}
|
||||
println!("Protected commits: {}", protected.len());
|
||||
println!("Keep refs to create: {}", create.len());
|
||||
if !remove.is_empty() { println!("Keep refs for removed deployments: {}", remove.len()); }
|
||||
if !stale_keep.is_empty() {
|
||||
println!("Old keep refs retained until readiness-bound cleanup: {}", stale_keep.len());
|
||||
}
|
||||
if !stale.is_empty() {
|
||||
println!("Unreferenced composition refs:");
|
||||
println!("Composition refs retained until history/readiness policy is available:");
|
||||
for (name, target) in &stale { println!(" {name} {target}"); }
|
||||
}
|
||||
if let Err(error) = guard {
|
||||
|
|
@ -173,38 +318,26 @@ pub fn plan(as_json: bool) -> Result<(), String> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Apply the guarded collection: OSTree deployment retention, explicit keep refs
|
||||
/// for every retained deployment, removal of unreferenced composition refs, then
|
||||
/// `ostree prune --refs-only`. Protected commits are re-resolved afterwards.
|
||||
/// Apply guarded collection of objects already unreachable from any ref. Deployment
|
||||
/// retirement is success-gated by D-046/D-047, and that readiness record producer
|
||||
/// is not implemented yet; therefore this command never calls `admin cleanup` or
|
||||
/// removes keep/service/history refs.
|
||||
pub fn apply() -> Result<(), String> {
|
||||
require_host()?;
|
||||
let _lock = lock()?;
|
||||
let before = repository_bytes();
|
||||
let status: Value = serde_json::from_str(&ostree(&["admin", "status", "--json"])?)
|
||||
.map_err(|_| "invalid OSTree deployment status".to_string())?;
|
||||
let mut deployments = parse_deployments(&status)?;
|
||||
let deployments = parse_deployments(&status)?;
|
||||
preconditions(&deployments)?;
|
||||
// OSTree's own retention: booted, previous, pending and pinned deployments.
|
||||
// Failure is not fatal for object collection, which protects what still exists.
|
||||
let cleanup = ostree(&["admin", "cleanup"]);
|
||||
let status: Value = serde_json::from_str(&ostree(&["admin", "status", "--json"])?)
|
||||
.map_err(|_| "invalid OSTree deployment status".to_string())?;
|
||||
deployments = parse_deployments(&status)?;
|
||||
preconditions(&deployments)?;
|
||||
let mut protected: BTreeSet<String> = deployments.iter().map(|deployment| deployment.checksum.clone()).collect();
|
||||
for deployment in &deployments {
|
||||
for key in PROTECTED_KEYS {
|
||||
if let Some(commit) = metadata_commit(&deployment.checksum, key) { protected.insert(commit); }
|
||||
}
|
||||
}
|
||||
let protected = protected_commits(&deployments)?;
|
||||
let refs = list_refs()?;
|
||||
for (name, commit) in keep_ref_sync(&ref_names(&refs), &deployments).0 {
|
||||
for (name, commit) in keep_ref_sync(&ref_names(&refs), &protected) {
|
||||
repository(&["refs", "--force", &format!("--create={name}"), &commit])?;
|
||||
}
|
||||
for (name, _) in stale_service_refs(&refs, &protected) {
|
||||
repository(&["refs", "--delete", &name])?;
|
||||
}
|
||||
// Every protected commit must resolve through a ref before anything is deleted.
|
||||
// Never expire old keep/service/history refs here. An extra ref is a leak;
|
||||
// removing a recovery root is destructive. D-047 readiness-bound retention
|
||||
// must own that step.
|
||||
for commit in &protected {
|
||||
repository(&["ls", commit, "/"])?;
|
||||
}
|
||||
|
|
@ -214,14 +347,9 @@ pub fn apply() -> Result<(), String> {
|
|||
.map_err(|error| format!("protected deployment became unreadable after prune: {error}"))?;
|
||||
}
|
||||
let after = repository_bytes();
|
||||
let cleanup_status = match &cleanup {
|
||||
Ok(_) => "ok".to_string(),
|
||||
Err(error) => error.clone(),
|
||||
};
|
||||
let record = serde_json::json!({
|
||||
"version": 1, "finished_unix": now()?, "deployments": deployments.len(),
|
||||
"protected_commits": protected, "keep_refs_checked": true,
|
||||
"admin_cleanup": cleanup_status,
|
||||
"prune": prune.trim(), "bytes_before": before, "bytes_after": after,
|
||||
});
|
||||
record_journal(&record)?;
|
||||
|
|
@ -282,10 +410,12 @@ fn ref_names(refs: &[(String, String)]) -> Vec<String> {
|
|||
refs.iter().map(|(name, _)| name.clone()).collect()
|
||||
}
|
||||
|
||||
fn metadata_commit(commit: &str, key: &str) -> Option<String> {
|
||||
let raw = ostree(&["show", &format!("--print-metadata-key={key}"), commit]).ok()?;
|
||||
fn metadata_commit(commit: &str, key: &str) -> Result<Option<String>, String> {
|
||||
let raw = ostree(&["show", &format!("--print-metadata-key={key}"), commit])?;
|
||||
let value = raw.trim().trim_matches('\'');
|
||||
digest(value).then(|| value.to_owned())
|
||||
if value.is_empty() { return Ok(None); }
|
||||
if !digest(value) { return Err(format!("invalid {key} commit metadata in {commit}")); }
|
||||
Ok(Some(value.to_owned()))
|
||||
}
|
||||
|
||||
fn repository_bytes() -> Option<u64> {
|
||||
|
|
@ -343,23 +473,26 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn keep_refs_track_exactly_the_current_deployments() {
|
||||
fn keep_refs_add_protected_roots_but_do_not_retire_old_roots() {
|
||||
let deployments = parse_deployments(&status()).unwrap();
|
||||
let protected: BTreeSet<String> = deployments.iter().map(|deployment| deployment.checksum.clone()).collect();
|
||||
let existing = vec![
|
||||
format!("{KEEP}/{}", "a".repeat(64)),
|
||||
format!("{KEEP}/{}", "c".repeat(64)),
|
||||
"stable/core".to_string(),
|
||||
];
|
||||
let (create, remove) = keep_ref_sync(&existing, &deployments);
|
||||
let create = keep_ref_sync(&existing, &protected);
|
||||
assert_eq!(create, vec![(format!("{KEEP}/{}", "b".repeat(64)), "b".repeat(64))]);
|
||||
assert_eq!(remove, vec![format!("{KEEP}/{}", "c".repeat(64))]);
|
||||
// A second run is a no-op for protection.
|
||||
let created = keep_ref_sync(&[format!("{KEEP}/{}", "a".repeat(64)), format!("{KEEP}/{}", "b".repeat(64))], &deployments);
|
||||
assert!(created.0.is_empty() && created.1.is_empty());
|
||||
let mut with_old_root = protected.clone();
|
||||
with_old_root.insert("c".repeat(64));
|
||||
let all_refs = ["a".repeat(64), "b".repeat(64), "c".repeat(64)].into_iter()
|
||||
.map(|sum| format!("{KEEP}/{sum}")).collect::<Vec<_>>();
|
||||
assert!(keep_ref_sync(&all_refs, &with_old_root).is_empty());
|
||||
assert_eq!(stale_keep_refs(&[(format!("{KEEP}/{}", "c".repeat(64)), "c".repeat(64))], &protected).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_unreferenced_composition_refs_are_stale() {
|
||||
fn service_refs_are_only_candidates_until_history_policy_exists() {
|
||||
let target = "d".repeat(64);
|
||||
let refs = vec![
|
||||
("service/bases/".to_owned() + &target, target.clone()),
|
||||
|
|
@ -374,4 +507,21 @@ mod tests {
|
|||
assert!(stale.iter().all(|(name, _)| name != "stable/core"));
|
||||
assert!(stale.iter().all(|(name, _)| !name.starts_with(&format!("{KEEP}/"))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retained_overlay_plan_roots_include_all_layer_identities() {
|
||||
let base = "a".repeat(64);
|
||||
let layer = "b".repeat(64);
|
||||
let source = "c".repeat(64);
|
||||
let target = "d".repeat(64);
|
||||
let plan = json!({"target":target,"context":{"managed_base":base},"inputs":{"overlay":{
|
||||
"clean_base":base,"catalog_commit":"e".repeat(64),
|
||||
"layers":[{"commit":layer}],"declarations":[{"source_commit":source}]}}});
|
||||
let mut roots = BTreeSet::new();
|
||||
collect_plan_commits(&plan, &mut roots).unwrap();
|
||||
for commit in [&base, &layer, &source, &target] { assert!(roots.contains(commit)); }
|
||||
// This is an archive checksum, not an OSTree commit, and must not be
|
||||
// mistaken for a repository root from an arbitrary `checksum` field.
|
||||
assert!(!roots.contains(&"f".repeat(64)));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,11 +2,248 @@
|
|||
use super::{storage, worker::{Failure, Result, Worker}};
|
||||
use archipelago_contracts::system_bus::{ErrorCode, Phase};
|
||||
use serde_json::{json, Value};
|
||||
use std::{process::{Command, Stdio}, time::Duration};
|
||||
use std::{ffi::{CStr, CString}, os::raw::{c_char, c_int, c_uint, c_void}, process::Command, ptr, time::Duration};
|
||||
|
||||
const ADAPTER: &str = include_str!("../../adapters/kernel-arguments.py");
|
||||
fn fail(message: &str) -> Failure { Failure::new(ErrorCode::InvalidArgument, message) }
|
||||
|
||||
#[repr(C)]
|
||||
struct GError { domain: c_uint, code: c_int, message: *mut c_char }
|
||||
#[repr(C)]
|
||||
struct GPtrArray { pdata: *mut *mut c_void, len: c_uint }
|
||||
|
||||
type KernelArgsFromString = unsafe extern "C" fn(*const c_char) -> *mut c_void;
|
||||
type KernelArgsMut = unsafe extern "C" fn(*mut c_void, *const c_char);
|
||||
type KernelArgsEdit = unsafe extern "C" fn(*mut c_void, *const c_char, *mut *mut GError) -> c_int;
|
||||
type KernelArgsToStrv = unsafe extern "C" fn(*mut c_void) -> *mut *mut c_char;
|
||||
type KernelArgsFree = unsafe extern "C" fn(*mut c_void);
|
||||
type SysrootNew = unsafe extern "C" fn() -> *mut c_void;
|
||||
type SysrootLoad = unsafe extern "C" fn(*mut c_void, *mut c_void, *mut *mut GError) -> c_int;
|
||||
type SysrootGet = unsafe extern "C" fn(*mut c_void) -> *mut c_void;
|
||||
type SysrootDeployments = unsafe extern "C" fn(*mut c_void) -> *mut GPtrArray;
|
||||
type DeploymentText = unsafe extern "C" fn(*mut c_void) -> *const c_char;
|
||||
type DeploymentSerial = unsafe extern "C" fn(*mut c_void) -> c_int;
|
||||
type DeploymentStaged = unsafe extern "C" fn(*mut c_void) -> c_int;
|
||||
type BootconfigGet = unsafe extern "C" fn(*mut c_void, *const c_char) -> *const c_char;
|
||||
type FreeError = unsafe extern "C" fn(*mut GError);
|
||||
type FreeStrv = unsafe extern "C" fn(*mut *mut c_char);
|
||||
type FreeArray = unsafe extern "C" fn(*mut GPtrArray);
|
||||
type FreeObject = unsafe extern "C" fn(*mut c_void);
|
||||
|
||||
/// libostree is a runtime system library: the release build image must not need
|
||||
/// it at link time. Resolve the exact ctypes surface the old Python adapter used.
|
||||
struct Api {
|
||||
_ostree: *mut c_void,
|
||||
_glib: *mut c_void,
|
||||
_gobject: *mut c_void,
|
||||
kernel_args_from_string: KernelArgsFromString,
|
||||
kernel_args_append: KernelArgsMut,
|
||||
kernel_args_append_if_missing: KernelArgsMut,
|
||||
kernel_args_delete: KernelArgsEdit,
|
||||
kernel_args_delete_if_present: KernelArgsEdit,
|
||||
kernel_args_new_replace: KernelArgsEdit,
|
||||
kernel_args_to_strv: KernelArgsToStrv,
|
||||
kernel_args_free: KernelArgsFree,
|
||||
sysroot_new_default: SysrootNew,
|
||||
sysroot_load: SysrootLoad,
|
||||
sysroot_get_booted: SysrootGet,
|
||||
sysroot_get_deployments: SysrootDeployments,
|
||||
deployment_osname: DeploymentText,
|
||||
deployment_csum: DeploymentText,
|
||||
deployment_serial: DeploymentSerial,
|
||||
deployment_bootconfig: SysrootGet,
|
||||
deployment_staged: DeploymentStaged,
|
||||
bootconfig_get: BootconfigGet,
|
||||
error_free: FreeError,
|
||||
strv_free: FreeStrv,
|
||||
array_unref: FreeArray,
|
||||
object_unref: FreeObject,
|
||||
}
|
||||
|
||||
fn dlopen(name: &str) -> std::result::Result<*mut c_void, String> {
|
||||
let name = CString::new(name).map_err(|_| "Invalid library name".to_string())?;
|
||||
let handle = unsafe { libc::dlopen(name.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) };
|
||||
if handle.is_null() { return Err(format!("{name:?} is not available: {}", dl_error())); }
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
fn dl_error() -> String {
|
||||
let pointer = unsafe { libc::dlerror() };
|
||||
if pointer.is_null() { return "unknown dynamic loader error".into(); }
|
||||
unsafe { CStr::from_ptr(pointer) }.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn symbol<T: Copy>(handle: *mut c_void, name: &str) -> std::result::Result<T, String> {
|
||||
let key = CString::new(name).map_err(|_| "Invalid symbol name".to_string())?;
|
||||
let pointer = unsafe { libc::dlsym(handle, key.as_ptr()) };
|
||||
if pointer.is_null() { return Err(format!("libostree symbol {name} is missing")); }
|
||||
// dlsym returns a generic function pointer; the caller supplies the exact ABI.
|
||||
Ok(unsafe { std::mem::transmute_copy(&pointer) })
|
||||
}
|
||||
|
||||
impl Api {
|
||||
fn load() -> std::result::Result<Self, String> {
|
||||
let ostree = dlopen("libostree-1.so.1")?;
|
||||
let glib = dlopen("libglib-2.0.so.0")?;
|
||||
let gobject = dlopen("libgobject-2.0.so.0")?;
|
||||
Ok(Self {
|
||||
_ostree: ostree, _glib: glib, _gobject: gobject,
|
||||
kernel_args_from_string: symbol(ostree, "ostree_kernel_args_from_string")?,
|
||||
kernel_args_append: symbol(ostree, "ostree_kernel_args_append")?,
|
||||
kernel_args_append_if_missing: symbol(ostree, "ostree_kernel_args_append_if_missing")?,
|
||||
kernel_args_delete: symbol(ostree, "ostree_kernel_args_delete")?,
|
||||
kernel_args_delete_if_present: symbol(ostree, "ostree_kernel_args_delete_if_present")?,
|
||||
kernel_args_new_replace: symbol(ostree, "ostree_kernel_args_new_replace")?,
|
||||
kernel_args_to_strv: symbol(ostree, "ostree_kernel_args_to_strv")?,
|
||||
kernel_args_free: symbol(ostree, "ostree_kernel_args_free")?,
|
||||
sysroot_new_default: symbol(ostree, "ostree_sysroot_new_default")?,
|
||||
sysroot_load: symbol(ostree, "ostree_sysroot_load")?,
|
||||
sysroot_get_booted: symbol(ostree, "ostree_sysroot_get_booted_deployment")?,
|
||||
sysroot_get_deployments: symbol(ostree, "ostree_sysroot_get_deployments")?,
|
||||
deployment_osname: symbol(ostree, "ostree_deployment_get_osname")?,
|
||||
deployment_csum: symbol(ostree, "ostree_deployment_get_csum")?,
|
||||
deployment_serial: symbol(ostree, "ostree_deployment_get_deployserial")?,
|
||||
deployment_bootconfig: symbol(ostree, "ostree_deployment_get_bootconfig")?,
|
||||
deployment_staged: symbol(ostree, "ostree_deployment_is_staged")?,
|
||||
bootconfig_get: symbol(ostree, "ostree_bootconfig_parser_get")?,
|
||||
error_free: symbol(glib, "g_error_free")?,
|
||||
strv_free: symbol(glib, "g_strfreev")?,
|
||||
array_unref: symbol(glib, "g_ptr_array_unref")?,
|
||||
object_unref: symbol(gobject, "g_object_unref")?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn error_text(api: &Api, error: *mut GError, fallback: &str) -> String {
|
||||
if error.is_null() { return fallback.into(); }
|
||||
let message = unsafe { CStr::from_ptr((*error).message) }.to_string_lossy().into_owned();
|
||||
unsafe { (api.error_free)(error); }
|
||||
message
|
||||
}
|
||||
|
||||
fn kernel_args(api: &Api, options: &str, changes: &[Value]) -> std::result::Result<Vec<String>, String> {
|
||||
let options = CString::new(options).map_err(|_| "Invalid boot options".to_string())?;
|
||||
let pointer = unsafe { (api.kernel_args_from_string)(options.as_ptr()) };
|
||||
if pointer.is_null() { return Err("libostree could not parse boot options".into()); }
|
||||
let result = (|| {
|
||||
for change in changes {
|
||||
let op = change["op"].as_str().ok_or("Invalid kernel argument operation")?;
|
||||
let value = change["argument"].as_str().ok_or("Invalid kernel argument")?;
|
||||
if value.matches('"').count() % 2 != 0 { return Err("Unbalanced quotes in kernel argument".into()); }
|
||||
// libostree parses the argument again internally; require the complete
|
||||
// input to round-trip as exactly one token before passing it to mutators.
|
||||
if parse_one(api, value)? != value { return Err("Expected exactly one kernel argument".into()); }
|
||||
let argument = CString::new(value).map_err(|_| "NUL in kernel argument".to_string())?;
|
||||
match op {
|
||||
"append" => unsafe { (api.kernel_args_append)(pointer, argument.as_ptr()) },
|
||||
"append-if-missing" => unsafe { (api.kernel_args_append_if_missing)(pointer, argument.as_ptr()) },
|
||||
"delete" | "delete-if-present" | "replace" => {
|
||||
let mut error = ptr::null_mut();
|
||||
let ok = unsafe { match op {
|
||||
"delete" => (api.kernel_args_delete)(pointer, argument.as_ptr(), &mut error),
|
||||
"delete-if-present" => (api.kernel_args_delete_if_present)(pointer, argument.as_ptr(), &mut error),
|
||||
_ => (api.kernel_args_new_replace)(pointer, argument.as_ptr(), &mut error),
|
||||
}};
|
||||
if ok == 0 { return Err(error_text(api, error, "libostree kernel argument edit failed")); }
|
||||
}
|
||||
_ => return Err(format!("Unknown kernel argument operation: {op}")),
|
||||
}
|
||||
}
|
||||
let vector = unsafe { (api.kernel_args_to_strv)(pointer) };
|
||||
if vector.is_null() { return Err("libostree returned no kernel argument vector".into()); }
|
||||
let mut output = Vec::new();
|
||||
let mut index = 0usize;
|
||||
loop {
|
||||
let item = unsafe { *vector.add(index) };
|
||||
if item.is_null() { break; }
|
||||
if index >= 4096 {
|
||||
unsafe { (api.strv_free)(vector); }
|
||||
return Err("Kernel argument vector exceeds limit".into());
|
||||
}
|
||||
let text = unsafe { CStr::from_ptr(item) }.to_str().map_err(|_| "Invalid UTF-8 kernel argument".to_string())?;
|
||||
if text.split('=').next() != Some("ostree") { output.push(text.to_owned()); }
|
||||
index += 1;
|
||||
}
|
||||
unsafe { (api.strv_free)(vector); }
|
||||
Ok(output)
|
||||
})();
|
||||
unsafe { (api.kernel_args_free)(pointer); }
|
||||
result
|
||||
}
|
||||
|
||||
fn parse_one(api: &Api, value: &str) -> std::result::Result<String, String> {
|
||||
let options = CString::new(value).map_err(|_| "NUL in kernel argument".to_string())?;
|
||||
let pointer = unsafe { (api.kernel_args_from_string)(options.as_ptr()) };
|
||||
if pointer.is_null() { return Err("libostree could not parse kernel argument".into()); }
|
||||
let vector = unsafe { (api.kernel_args_to_strv)(pointer) };
|
||||
let result = if vector.is_null() {
|
||||
Err("libostree returned no kernel argument vector".into())
|
||||
} else {
|
||||
let first = unsafe { *vector };
|
||||
let count = (0..).take_while(|index| !unsafe { *vector.add(*index) }.is_null()).count();
|
||||
let result = if first.is_null() || count != 1 {
|
||||
Err("Expected exactly one kernel argument".into())
|
||||
} else {
|
||||
unsafe { CStr::from_ptr(first) }.to_str().map(str::to_owned).map_err(|_| "Invalid UTF-8 kernel argument".into())
|
||||
};
|
||||
unsafe { (api.strv_free)(vector); }
|
||||
result
|
||||
};
|
||||
unsafe { (api.kernel_args_free)(pointer); }
|
||||
result
|
||||
}
|
||||
|
||||
fn ostree_snapshot(changes: Option<&Value>) -> std::result::Result<Value, String> {
|
||||
let api = Api::load()?;
|
||||
let pointer = unsafe { (api.sysroot_new_default)() };
|
||||
if pointer.is_null() { return Err("libostree could not allocate sysroot".into()); }
|
||||
let result = (|| {
|
||||
let mut error = ptr::null_mut();
|
||||
if unsafe { (api.sysroot_load)(pointer, ptr::null_mut(), &mut error) } == 0 {
|
||||
return Err(error_text(&api, error, "libostree could not load sysroot"));
|
||||
}
|
||||
let booted = unsafe { (api.sysroot_get_booted)(pointer) };
|
||||
let array = unsafe { (api.sysroot_get_deployments)(pointer) };
|
||||
if array.is_null() { return Err("libostree returned no deployment list".into()); }
|
||||
let mut rows = Vec::new();
|
||||
let mut raw_options = Vec::new();
|
||||
for index in 0..unsafe { (*array).len } as usize {
|
||||
let deployment = unsafe { *(*array).pdata.add(index) };
|
||||
if deployment.is_null() { unsafe { (api.array_unref)(array); } return Err("libostree returned a null deployment".into()); }
|
||||
let osname = unsafe { (api.deployment_osname)(deployment) };
|
||||
if osname.is_null() || unsafe { CStr::from_ptr(osname) }.to_bytes() != b"archipelago" { continue; }
|
||||
let checksum = unsafe { (api.deployment_csum)(deployment) };
|
||||
if checksum.is_null() { unsafe { (api.array_unref)(array); } return Err("Missing deployment checksum".into()); }
|
||||
let checksum = unsafe { CStr::from_ptr(checksum) }.to_str().map_err(|_| "Invalid deployment checksum")?.to_owned();
|
||||
let serial = unsafe { (api.deployment_serial)(deployment) };
|
||||
if serial < 0 { unsafe { (api.array_unref)(array); } return Err("Invalid deployment serial".into()); }
|
||||
let config = unsafe { (api.deployment_bootconfig)(deployment) };
|
||||
if config.is_null() { unsafe { (api.array_unref)(array); } return Err("Deployment boot configuration unavailable".into()); }
|
||||
let key = CString::new("options").map_err(|_| "Invalid boot configuration key")?;
|
||||
let options = unsafe { (api.bootconfig_get)(config, key.as_ptr()) };
|
||||
if options.is_null() { unsafe { (api.array_unref)(array); } return Err("Deployment kernel arguments unavailable".into()); }
|
||||
let options = unsafe { CStr::from_ptr(options) }.to_str().map_err(|_| "Invalid boot options")?;
|
||||
let arguments = kernel_args(&api, options, &[])?;
|
||||
raw_options.push(options.to_owned());
|
||||
rows.push(json!({"deployment_id":format!("archipelago/{checksum}.{serial}"),"checksum":checksum,
|
||||
"booted":deployment == booted,"staged":unsafe { (api.deployment_staged)(deployment) } != 0,
|
||||
"arguments":arguments}));
|
||||
}
|
||||
unsafe { (api.array_unref)(array); }
|
||||
if let Some(changes) = changes {
|
||||
validate(changes).map_err(|error| error.message)?;
|
||||
let selected = rows.iter().position(|row| row["staged"] == true)
|
||||
.or_else(|| rows.iter().position(|row| row["booted"] == true))
|
||||
.ok_or_else(|| "No booted deployment".to_string())?;
|
||||
let options = raw_options.get(selected).ok_or("Missing selected boot options")?;
|
||||
let edited = kernel_args(&api, options, changes.as_array().ok_or("Expected kernel argument edits")?)?;
|
||||
rows[selected]["edited"] = json!(edited);
|
||||
}
|
||||
Ok(Value::Array(rows))
|
||||
})();
|
||||
unsafe { (api.object_unref)(pointer); }
|
||||
result
|
||||
}
|
||||
|
||||
pub fn validate(changes: &Value) -> Result<()> {
|
||||
let rows = changes.as_array().ok_or_else(|| fail("Expected kernel argument edits"))?;
|
||||
if rows.is_empty() || rows.len() > 256 || changes.to_string().len() > 65536 { return Err(fail("Invalid kernel argument edit count/size")); }
|
||||
|
|
@ -52,12 +289,8 @@ mod tests {
|
|||
}
|
||||
|
||||
pub fn inspect() -> Result<Value> {
|
||||
let output = Command::new("/usr/bin/timeout").args(["--kill-after=2", "15", "/usr/bin/python3", "-c", ADAPTER])
|
||||
.stdin(Stdio::null()).output().map_err(storage::io_error)?;
|
||||
if !output.status.success() || output.stdout.len() > 1024*1024 {
|
||||
return Err(Failure::new(ErrorCode::Unavailable, "Cannot read deployment kernel arguments"));
|
||||
}
|
||||
let deployments: Value = serde_json::from_slice(&output.stdout).map_err(|_| fail("Invalid kernel arguments observation"))?;
|
||||
let deployments = ostree_snapshot(None)
|
||||
.map_err(|_| Failure::new(ErrorCode::Unavailable, "Cannot read deployment kernel arguments"))?;
|
||||
let context = storage::hash(&serde_json::to_vec(&deployments).map_err(|_| fail("Invalid kargs context"))?);
|
||||
let selected = selected(&deployments)?.clone();
|
||||
Ok(json!({"context_id":context,"selected":selected,"deployments":deployments}))
|
||||
|
|
@ -98,8 +331,7 @@ pub fn execute(worker: &Worker, changes: &Value, context: &str) -> Result<Value>
|
|||
let before = inspect()?;
|
||||
if before["context_id"] != context { return Err(Failure::new(ErrorCode::PlanStale, "Kernel arguments changed; read the current deployment and retry")); }
|
||||
worker.events.checkpoint(Phase::Planning, true, "Preparing kernel arguments")?;
|
||||
let output = worker.command("/usr/bin/python3", &["-c", ADAPTER, &changes.to_string()], Duration::from_secs(15), true)?;
|
||||
let rows: Value = serde_json::from_str(&output).map_err(|_| fail("Invalid edited kernel arguments"))?;
|
||||
let rows = ostree_snapshot(Some(changes)).map_err(|_| fail("Cannot edit kernel arguments with libostree"))?;
|
||||
let source = selected(&rows)?;
|
||||
let after = &source["edited"];
|
||||
if after == &before["selected"]["arguments"] { return Ok(json!({"outcome":"no-change","changed":false,"arguments":after})); }
|
||||
|
|
@ -123,12 +355,7 @@ pub fn execute(worker: &Worker, changes: &Value, context: &str) -> Result<Value>
|
|||
pub fn apply_local(changes: &Value) -> Result<Value> {
|
||||
validate(changes)?;
|
||||
let before = inspect()?;
|
||||
let output = Command::new("/usr/bin/python3").args(["-c", ADAPTER, &changes.to_string()])
|
||||
.stdin(Stdio::null()).output().map_err(storage::io_error)?;
|
||||
if !output.status.success() {
|
||||
return Err(Failure::new(ErrorCode::Unavailable, "Cannot edit kernel arguments"));
|
||||
}
|
||||
let rows: Value = serde_json::from_slice(&output.stdout).map_err(|_| fail("Invalid edited kernel arguments"))?;
|
||||
let rows = ostree_snapshot(Some(changes)).map_err(|_| fail("Cannot edit kernel arguments with libostree"))?;
|
||||
let source = selected(&rows)?;
|
||||
let after = &source["edited"];
|
||||
if after == &before["selected"]["arguments"] {
|
||||
|
|
|
|||
|
|
@ -329,22 +329,11 @@ pub(crate) fn load_base(worker: &Worker, commit: &str, offline: bool) -> Result<
|
|||
};
|
||||
let purpose_root = work.join("base-purpose");
|
||||
if let Some(commit) = &purpose { managed(worker, commit, &purpose_root, offline)?; }
|
||||
for (name, contents) in [("base.py", archipelago_composer::base::SCANNER),
|
||||
("artifact.py", artifact::CHECKER), ("materialize.py", archipelago_composer::MATERIALIZER)] {
|
||||
fs::write(work.join(name), contents).map_err(storage::io_error)?;
|
||||
}
|
||||
let script = work.join("base.py");
|
||||
let text = |p: &Path| p.to_str().map(str::to_owned).ok_or_else(|| failure("Invalid base path"));
|
||||
let output_path = work.join("base-index.json");
|
||||
let mut args = vec!["-I".into(), "-B".into(), text(&script)?, "--output".into(),
|
||||
text(&output_path)?, text(&root)?, text(&core)?];
|
||||
if purpose.is_some() { args.push(text(&purpose_root)?); }
|
||||
worker.command("/usr/bin/python3", &args.iter().map(String::as_str).collect::<Vec<_>>(),
|
||||
Duration::from_secs(1800), true)?;
|
||||
// Full Desktop indexes can exceed the worker's bounded diagnostic output.
|
||||
// Read protected evidence directly instead of transporting it through logs.
|
||||
let checked = serde_json::from_reader(fs::File::open(&output_path).map_err(storage::io_error)?)
|
||||
.map_err(|_| failure("Invalid base scanner output"))?;
|
||||
// Native scanner replaces base.py and returns the exact typed index consumed
|
||||
// by the composer. It reads only authenticated checkouts and has no subprocess
|
||||
// or JSON hand-off to trust.
|
||||
let checked = archipelago_composer::base::scan_legacy(&root, &core,
|
||||
purpose.as_ref().map(|_| purpose_root.as_path())).map_err(failure)?;
|
||||
let base = archipelago_composer::base::read_checked(&root, checked).map_err(failure)?;
|
||||
worker.events.effect("overlay_base", json!({"image":commit,"core":core_commit,"purpose":purpose,
|
||||
"snapshot":base.snapshot}))?;
|
||||
|
|
|
|||
|
|
@ -201,11 +201,10 @@ pub(crate) fn stage_deployment(commit: &str) -> Result<(), String> {
|
|||
args.extend(["--karg=quiet", "--karg=splash", "--karg=plymouth.ignore-serial-consoles"]);
|
||||
}
|
||||
args.push(commit);
|
||||
let result = output("ostree", &args).map(|_| ());
|
||||
// Best effort: remove unpinned deployments after a successful stage so the
|
||||
// boot filesystem cannot accumulate one initramfs per historical update.
|
||||
if result.is_ok() { let _ = output("ostree", &["admin", "cleanup"]); }
|
||||
result
|
||||
// Do not run `ostree admin cleanup` here: a successful Stage has not booted the
|
||||
// candidate and is not D-047 readiness evidence. `finalize-staged` applies the
|
||||
// native minimum retention; success-gated GC is a separate boot lifecycle.
|
||||
output("ostree", &args).map(|_| ())
|
||||
}
|
||||
fn reconcile_operations() -> Result<(), String> {
|
||||
// Caller owns the shared host-operation lock: no prior CLI operation can run.
|
||||
|
|
|
|||
|
|
@ -1,27 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Native libostree argument semantics, run in the normal build-tools stage."""
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
|
||||
arguments = runpy.run_path(str(Path(__file__).resolve().parents[1] / 'adapters/kernel-arguments.py'))['arguments']
|
||||
base = b'root=UUID=fixture rw quiet console=tty0 console=ttyS0 ostree=/managed'
|
||||
assert arguments(base, []) == ['root=UUID=fixture', 'rw', 'quiet', 'console=tty0', 'console=ttyS0']
|
||||
edits = [{'op':'append-if-missing','argument':'quiet'},
|
||||
{'op':'delete','argument':'quiet'},
|
||||
{'op':'replace','argument':'console=ttyS0=ttyS1'},
|
||||
{'op':'append','argument':'archipelago.test=yes'}]
|
||||
result = arguments(base, edits)
|
||||
assert 'quiet' not in result and 'console=ttyS0' not in result
|
||||
assert 'console=tty0' in result and 'console=ttyS1' in result and 'archipelago.test=yes' in result
|
||||
assert arguments(base, [{'op':'delete-if-present','argument':'absent'}]) == arguments(base, [])
|
||||
for change in [{'op':'delete','argument':'absent'}, {'op':'append','argument':'ostree=/bad'},
|
||||
{'op':'append','argument':'test=yes ostree=/bad'},
|
||||
{'op':'append','argument':'test="unterminated'},
|
||||
{'op':'replace','argument':'absent=new'}]:
|
||||
try:
|
||||
arguments(base, [change])
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError(change)
|
||||
print('Native kernel argument edit/duplicate/protected-selector checks passed')
|
||||
|
|
@ -1,86 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Contract checks for local package import (D-094, RFC-0013 §4.3).
|
||||
|
||||
These are source-level assertions on purpose: the hardware failure this test
|
||||
guards against was a pacman invocation that silently used the absent default
|
||||
`/var/lib/pacman` instead of the image database, which no type system catches.
|
||||
"""
|
||||
import re
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
SYSTEM = Path(__file__).resolve().parents[1]
|
||||
SOURCE = SYSTEM / 'src'
|
||||
IMAGE_DB = '/usr/lib/archipelago/package-db'
|
||||
|
||||
|
||||
def read(name):
|
||||
return (SOURCE / name).read_text()
|
||||
|
||||
|
||||
class LocalPackageImport(unittest.TestCase):
|
||||
def test_import_queries_pacman_with_the_image_database(self):
|
||||
text = read('service/inputs.rs')
|
||||
self.assertIn(f'pub const PACKAGE_DB: &str = "{IMAGE_DB}"', text)
|
||||
self.assertIn('fn query_arguments', text)
|
||||
self.assertIn('"--dbpath", PACKAGE_DB', text)
|
||||
# The failing hardware path: `--config /dev/null` without a dbpath makes
|
||||
# pacman open the absent default database.
|
||||
self.assertNotIn('&["--config", "/dev/null", "-Qp"', text)
|
||||
self.assertIn('"-Qp"', text)
|
||||
|
||||
def test_every_pacman_invocation_names_a_database(self):
|
||||
offenders = []
|
||||
for path in SOURCE.rglob('*.rs'):
|
||||
text = path.read_text()
|
||||
for match in re.finditer(r'"/usr/bin/pacman"', text):
|
||||
call = text[match.start():match.start() + 300]
|
||||
# Either the call site names the database itself, or it delegates to
|
||||
# the shared argument builder that does.
|
||||
if '--dbpath' not in call and 'query_arguments(' not in call:
|
||||
offenders.append(f'{path.relative_to(SOURCE)}:{text[:match.start()].count(chr(10)) + 1}')
|
||||
self.assertEqual(offenders, [], 'pacman invoked without an explicit database path')
|
||||
|
||||
def test_extension_add_imports_before_it_plans(self):
|
||||
text = read('service/client.rs')
|
||||
self.assertIn('fn extension_add', text)
|
||||
self.assertIn('fn split_add_args', text)
|
||||
self.assertIn('"ImportPackage"', text)
|
||||
self.assertIn('"add-local"', text)
|
||||
self.assertIn('"--file"', text)
|
||||
# One plan for the whole request: the import result feeds PrepareChange and
|
||||
# a single Stage applies it, rather than staging per archive.
|
||||
method = text[text.index('fn extension_add'):]
|
||||
method = method[:method.index('\n }')]
|
||||
self.assertLess(method.index('self.import('), method.index('"PrepareChange"'))
|
||||
self.assertEqual(method.count('self.stage('), 1)
|
||||
|
||||
def test_local_import_capability_is_advertised(self):
|
||||
text = read('service/mod.rs')
|
||||
for feature in ('host-extensions-v1', 'local-package-import-v1'):
|
||||
self.assertIn(f'"{feature}"', text)
|
||||
for unimplemented in ('managed-overlays-v1', 'packagekit-broker-v1'):
|
||||
self.assertNotIn(f'"{unimplemented}"', text)
|
||||
|
||||
def test_disposable_package_workspace_is_removed_whole(self):
|
||||
text = read('service/packages.rs')
|
||||
self.assertNotIn('release_checkout', text)
|
||||
release = text[text.index('fn release(&self'):]
|
||||
release = release[:release.index('\n }')]
|
||||
self.assertIn('self.path', release)
|
||||
self.assertIn('"--one-file-system"', release)
|
||||
# Cleanup must not be skipped by a cancellation request.
|
||||
self.assertIn('false)?;', release)
|
||||
self.assertIn('fn purge_stale', text)
|
||||
|
||||
def test_plan_entries_are_created_for_local_and_repository_requests(self):
|
||||
text = read('service/packages.rs')
|
||||
self.assertIn('Change::AddLocal { input_id }', text)
|
||||
self.assertIn('"source":"local"', text)
|
||||
# A local request keeps its retained archive name and checksum; nothing is
|
||||
# re-resolved from the filesystem or from a rolling mirror.
|
||||
self.assertIn('"filename":format!("{}.pkg.tar.zst",input.checksum)', text)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Loading…
Add table
Reference in a new issue