Initialize cli experimental implementation and documentation
This commit is contained in:
commit
d0d083098a
9 changed files with 1344 additions and 0 deletions
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
/target/
|
||||
1009
Cargo.lock
generated
Normal file
1009
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
14
Cargo.toml
Normal file
14
Cargo.toml
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
[package]
|
||||
name = "archipelago"
|
||||
version = "0.0.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.90"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
serde_json = "1"
|
||||
archipelago-builder = { path = "../builder" }
|
||||
archipelago-installer = { path = "../installer" }
|
||||
archipelago-system = { path = "../system" }
|
||||
archipelago-registry = { path = "../registry" }
|
||||
archipelago-contracts = { path = "../contracts" }
|
||||
75
README.md
Normal file
75
README.md
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
# archipelago — experimental Core vertical slice
|
||||
|
||||
Единый Rust executable связывает `builder`, `installer`, `system`; snapshot-specific
|
||||
адаптеры штатных инструментов встроены в binary. Это экспериментальный фиксированный
|
||||
Core профиль из `../manifests/CORE-EXPERIMENT.md`, не полноценная реализация всех RFC.
|
||||
|
||||
Сборка на superserv1, репозитории расположены рядом:
|
||||
|
||||
```sh
|
||||
export RUSTUP_HOME=/hdd/archipelago/cache/rustup
|
||||
export CARGO_HOME=/hdd/archipelago/cache/cargo
|
||||
export CARGO_TARGET_DIR=/hdd/archipelago/cache/target
|
||||
export TMPDIR=/hdd/archipelago/tmp
|
||||
export PATH="$CARGO_HOME/bin:$PATH"
|
||||
cargo build --offline --locked --release
|
||||
sudo "$CARGO_TARGET_DIR/release/archipelago" build iso \
|
||||
/hdd/archipelago/runs/core-iso-new \
|
||||
/hdd/archipelago/cache/bootstrap/archlinux-bootstrap-2026.11.01-x86_64.tar.zst
|
||||
```
|
||||
|
||||
Bootstrap принимается только с проверенным SHA-256 из E01; сборщик не исполняет
|
||||
произвольный архив под этим именем. Результат — `WORKDIR/output/archipelago-core-latest.iso`.
|
||||
Для новой сборки использовать новый WORKDIR. Работа с live rootfs хоста через pacman
|
||||
не выполняется: package/image operations находятся в nspawn.
|
||||
|
||||
На ZFS сборщик создаёт в WORKDIR разреженный ext4-образ 32 GiB для рабочего дерева:
|
||||
это обходит обнаруженное ожидание ZFS txg при OSTree O_TMPFILE/linkat и обеспечивает
|
||||
обычные ACL/xattrs. Все данные по-прежнему находятся на `/hdd`. ISO и evidence
|
||||
копируются наружу перед размонтированием. Требуются host `mkfs.ext4`, loop и mount.
|
||||
`ARCHIPELAGO_PACKAGE_CACHE` позволяет явно переиспользовать каталог пакетов между
|
||||
прогонами; подписи/контрольные суммы всё равно проверяет pacman.
|
||||
|
||||
### Пакет в экспериментальном образе
|
||||
|
||||
`packaging/PKGBUILD` упаковывает бинарник и runtime-инфраструктуру: systemd units,
|
||||
presets, ALPM guard, tmpfiles, конфигурацию initramfs и шаблоны defaults.
|
||||
Builder запускает makepkg от непривилегированного пользователя в Arch nspawn,
|
||||
подписывает пакет и локальный репозиторий лабораторным ключом и устанавливает
|
||||
`archipelago` через pacstrap/pacman в Core и live. Рецепт с checksums и публичный
|
||||
ключ сохраняются в evidence; пакет и подписи — в `output/packages`.
|
||||
Лабораторный ключ не определяет будущую публичную trust/signing policy.
|
||||
|
||||
`archipelago self-check` проверяет владельца бинарника через pacman, `pacman -Qkk`
|
||||
и manifest прав каждого регулярного файла пакета: бинарник `0755 root:root`,
|
||||
данные `0644 root:root`. Проверка обязательна при сборке обоих rootfs и в VM
|
||||
до установки, после первого входа и после активации каждого расширения.
|
||||
Само наличие этих проверок не означает прохождения VM-приёмки.
|
||||
|
||||
### Repository-backed Host Extensions
|
||||
|
||||
```sh
|
||||
sudo archipelago extension add nano
|
||||
sudo archipelago extension add mc htop
|
||||
sudo archipelago status
|
||||
sudo systemctl reboot
|
||||
sudo archipelago extension add tree
|
||||
```
|
||||
|
||||
Имена разрешаются через pacman из закреплённой базы репозиториев выбранного image;
|
||||
зависимости устанавливаются автоматически. Повторные вызовы дополняют pending-набор,
|
||||
а после загрузки — набор загруженного deployment. Уже запрошенный пакет — no-op.
|
||||
Каждая новая композиция начинается с исходной managed-базы и полного явного набора,
|
||||
а не с изменённой package DB предыдущего Host Extension. `status` отдельно показывает
|
||||
booted/pending и их запросы. Активация — только после явной перезагрузки.
|
||||
|
||||
Транзакции выполняются в nspawn через `pacman -S --needed`; `-Sy/-Syu` не выполняется.
|
||||
Недоступность закреплённого пакета — ошибка. Для другого транспорта можно задать
|
||||
`/etc/archipelago/extensions-mirrorlist` в обычном формате mirrorlist; это не меняет
|
||||
версии/checksums выбранного snapshot. История, точные пакеты, зависимости и журналы
|
||||
сохраняются в `/var/lib/archipelago/host-extensions/generations/`.
|
||||
|
||||
Неадаптированные hooks/scriptlets, kernel/DKMS и payload на persistent-путях
|
||||
отклоняются с диагностикой, а не пропускаются молча. Замена пакетов базы через `add`
|
||||
запрещена. Локальные файлы, remove/update/rebase workflows требуют отдельных команд.
|
||||
Контракт прототипа: `../system/EXTENSIONS.md`; результаты проверок — в `test-lab`.
|
||||
31
packaging/PKGBUILD
Normal file
31
packaging/PKGBUILD
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
# Experimental binary package. The Rust executable is built on the designated
|
||||
# host; both inputs are pinned below by the builder before makepkg is invoked.
|
||||
pkgname=archipelago
|
||||
pkgver=0.0.0.@BUILD_ID@
|
||||
pkgrel=1
|
||||
pkgdesc='Archipelago Core build, installation and deployment control'
|
||||
arch=('x86_64')
|
||||
depends=('bash' 'coreutils' 'util-linux' 'ostree' 'pacman' 'shadow' 'sudo'
|
||||
'openssh' 'systemd' 'gptfdisk' 'parted' 'dosfstools' 'e2fsprogs'
|
||||
'arch-install-scripts' 'diffutils')
|
||||
options=('!strip' '!debug')
|
||||
source=('archipelago' 'runtime.tar')
|
||||
sha256sums=('@BINARY_SHA256@' '@RUNTIME_SHA256@')
|
||||
|
||||
package() {
|
||||
cp -a "$srcdir/runtime/usr" "$pkgdir/"
|
||||
find "$pkgdir" -type d -exec chmod 0755 '{}' +
|
||||
find "$pkgdir" -type f -exec chmod 0644 '{}' +
|
||||
install -Dm0755 "$srcdir/archipelago" "$pkgdir/usr/bin/archipelago"
|
||||
chown -R 0:0 "$pkgdir"
|
||||
install -d "$pkgdir/usr/share/archipelago"
|
||||
# Manifest covers every packaged regular file, including itself. No setuid,
|
||||
# setgid or writable-by-group/world files are required by this package.
|
||||
touch "$pkgdir/usr/share/archipelago/permissions.tsv"
|
||||
chmod 0644 "$pkgdir/usr/share/archipelago/permissions.tsv"
|
||||
(cd "$pkgdir" && find usr -type f -printf '%m %U %G %p\n' | LC_ALL=C sort) \
|
||||
> "$pkgdir/usr/share/archipelago/permissions.tsv"
|
||||
# OSTree materializes regular files with epoch mtimes. Match the package's
|
||||
# mtree to that representation so strict ALPM checks also pass after deploy.
|
||||
find "$pkgdir" -exec touch -h -d @0 '{}' +
|
||||
}
|
||||
3
rust-toolchain.toml
Normal file
3
rust-toolchain.toml
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
[toolchain]
|
||||
channel = "1.90.0"
|
||||
profile = "minimal"
|
||||
111
src/infrastructure.rs
Normal file
111
src/infrastructure.rs
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
//! Interim infrastructure control, configured on the coordinator only.
|
||||
use serde_json::{json, Value};
|
||||
use std::{env, fs, path::{Path, PathBuf}, process::Command, time::{SystemTime, UNIX_EPOCH}};
|
||||
|
||||
fn text<'a>(v: &'a Value, key: &str) -> Result<&'a str, String> {
|
||||
v[key].as_str().filter(|s| !s.is_empty()).ok_or_else(|| format!("missing infrastructure setting: {key}"))
|
||||
}
|
||||
fn reason(s: &str) -> Result<&str, String> {
|
||||
if s.trim().is_empty() || s.len() > 2048 || s.chars().any(char::is_control) {
|
||||
Err("provide a nonempty, single-line release reason (up to 2048 bytes)".into())
|
||||
} else { Ok(s) }
|
||||
}
|
||||
fn command(config: &Value, key: &str, candidates: Option<&Path>) -> Result<Vec<String>, String> {
|
||||
let values = config[key].as_array().filter(|v| !v.is_empty()).ok_or("missing configured command")?;
|
||||
values.iter().map(|v| {
|
||||
let s = v.as_str().ok_or("invalid command argument")?;
|
||||
if s == "{candidates}" {
|
||||
Ok(candidates.ok_or("candidate path required")?.to_str().ok_or("invalid path")?.into())
|
||||
} else { Ok(s.into()) }
|
||||
}).collect()
|
||||
}
|
||||
fn output(args: &[&str]) -> Result<String, String> {
|
||||
let out = Command::new(args[0]).args(&args[1..]).output().map_err(|e| e.to_string())?;
|
||||
if !out.status.success() { return Err(String::from_utf8_lossy(&out.stderr).into()); }
|
||||
Ok(String::from_utf8_lossy(&out.stdout).into())
|
||||
}
|
||||
fn start(config: &Value, operation: &str, why: &str, args: &[String]) -> Result<(), String> {
|
||||
reason(why)?;
|
||||
if output(&["id", "-u"])?.trim() != "0" { return Err("Run as root on the coordinator".into()); }
|
||||
let root = Path::new(text(config, "control_root")?);
|
||||
fs::create_dir_all(root).map_err(|e| e.to_string())?;
|
||||
let lock = fs::File::options().create(true).truncate(false).write(true).open(root.join("control.lock")).map_err(|e| e.to_string())?;
|
||||
lock.try_lock().map_err(|e| format!("infrastructure operation busy: {e}"))?;
|
||||
let unit = text(config, "unit")?;
|
||||
let active = output(&["systemctl", "show", unit, "-p", "ActiveState", "--value"])?;
|
||||
if matches!(active.trim(), "active" | "activating" | "deactivating") { return Err("infrastructure operation already running".into()); }
|
||||
let id = SystemTime::now().duration_since(UNIX_EPOCH).map_err(|e| e.to_string())?.as_nanos().to_string();
|
||||
let log = root.join(format!("{id}.log"));
|
||||
let record = root.join(format!("{id}.json"));
|
||||
let mut request = json!({"id":id,"operation":operation,"reason":why,"unit":unit,
|
||||
"state":"submitted","log":log,"command":args});
|
||||
fs::write(&record, serde_json::to_vec_pretty(&request).unwrap()).map_err(|e| e.to_string())?;
|
||||
let status = Command::new("systemd-run").args(["--collect", &format!("--unit={unit}"),
|
||||
"--property=RuntimeMaxSec=12h", &format!("--property=StandardOutput=append:{}", log.display()),
|
||||
&format!("--property=StandardError=append:{}", log.display()),
|
||||
&format!("--setenv=ARCHIPELAGO_RELEASE_REASON={why}")])
|
||||
.args(["python3", text(config, "job_runner")?]).arg(&record).status().map_err(|e| e.to_string())?;
|
||||
if !status.success() {
|
||||
request["state"] = json!("launch-failed");
|
||||
fs::write(&record, serde_json::to_vec_pretty(&request).unwrap()).map_err(|e| e.to_string())?;
|
||||
return Err(format!("systemd-run: {status}"));
|
||||
}
|
||||
println!("{}", serde_json::to_string_pretty(&request).unwrap());
|
||||
Ok(())
|
||||
}
|
||||
pub fn dispatch(args: &[String]) -> Result<(), String> {
|
||||
let path = env::var_os("ARCHIPELAGO_INFRA_CONFIG").map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from("/etc/archipelago/infrastructure.json"));
|
||||
let config: Value = serde_json::from_slice(&fs::read(&path).map_err(|e| format!("infrastructure is not configured at {}: {e}", path.display()))?).map_err(|e| e.to_string())?;
|
||||
if config["version"] != 1 { return Err("unsupported infrastructure configuration".into()); }
|
||||
match args.iter().map(String::as_str).collect::<Vec<_>>().as_slice() {
|
||||
["pipeline", "run", "--reason", why] => start(&config, "pipeline-run", why, &command(&config, "run_command", None)?),
|
||||
["pipeline", "status"] => {
|
||||
let status = output(&["systemctl", "show", text(&config, "unit")?, "-p", "ActiveState", "-p", "SubState", "-p", "Result"])?;
|
||||
let root = Path::new(text(&config, "control_root")?);
|
||||
let mut requests = Vec::new();
|
||||
if root.exists() {
|
||||
for entry in fs::read_dir(root).map_err(|e| e.to_string())? {
|
||||
let p = entry.map_err(|e| e.to_string())?.path();
|
||||
if p.extension().is_some_and(|e| e == "json") {
|
||||
requests.push(serde_json::from_slice::<Value>(&fs::read(p).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?);
|
||||
}
|
||||
}
|
||||
}
|
||||
requests.sort_by(|a,b| a["id"].as_str().cmp(&b["id"].as_str()));
|
||||
println!("{}", serde_json::to_string_pretty(&json!({"unit_status":status,"requests":requests})).unwrap());
|
||||
Ok(())
|
||||
}
|
||||
["pipeline", "logs", id] if id.bytes().all(|c| c.is_ascii_digit()) && !id.is_empty() => {
|
||||
let p = Path::new(text(&config, "control_root")?).join(format!("{id}.log"));
|
||||
let status = Command::new("tail").args(["-n", "200"]).arg(p).status().map_err(|e| e.to_string())?;
|
||||
if status.success() { Ok(()) } else { Err("log unavailable".into()) }
|
||||
}
|
||||
["release", operation, candidate, "--reason", why] if matches!(*operation, "plan" | "publish") => {
|
||||
reason(why)?;
|
||||
let candidate = fs::canonicalize(candidate).map_err(|e| e.to_string())?;
|
||||
let allowed = fs::canonicalize(text(&config, "candidate_root")?).map_err(|e| e.to_string())?;
|
||||
if !candidate.starts_with(allowed) { return Err("candidate must be in the configured private artifact root".into()); }
|
||||
let mut cmd = command(&config, "publish_command", Some(&candidate))?;
|
||||
if *operation == "plan" {
|
||||
cmd.push("--check-only".into());
|
||||
let status = Command::new(&cmd[0]).args(&cmd[1..]).status().map_err(|e| e.to_string())?;
|
||||
if status.success() { Ok(()) } else { Err(format!("candidate verification: {status}")) }
|
||||
} else { start(&config, "release-publish", why, &cmd) }
|
||||
}
|
||||
_ => Err("Supported: pipeline status | logs ID | run --reason TEXT; release plan|publish CANDIDATES.json --reason TEXT".into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn reason_and_arguments_are_not_shell_commands() {
|
||||
assert!(reason(" ").is_err());
|
||||
assert!(reason("fix\nreboot").is_err());
|
||||
let c = json!({"run_command":["python3", "a; reboot"]});
|
||||
assert_eq!(command(&c, "run_command", None).unwrap(), ["python3", "a; reboot"]);
|
||||
assert!(command(&json!({"run_command":["{candidates}"]}), "run_command", None).is_err());
|
||||
}
|
||||
}
|
||||
68
src/main.rs
Normal file
68
src/main.rs
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
use std::{env, process::{Command, ExitCode}};
|
||||
mod self_check;
|
||||
mod infrastructure;
|
||||
|
||||
fn run(script: &str, args: &[String]) -> Result<(), String> {
|
||||
let status = Command::new("/usr/bin/bash")
|
||||
.args(["-euo", "pipefail", "-c", script, "archipelago-adapter"])
|
||||
.args(args).status().map_err(|e| e.to_string())?;
|
||||
if status.success() { Ok(()) } else { Err(format!("operation failed: {status}")) }
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let args: Vec<String> = env::args().skip(1).collect();
|
||||
let result = match args.iter().map(String::as_str).collect::<Vec<_>>().as_slice() {
|
||||
["pipeline", ..] | ["release", "plan", ..] | ["release", "publish", ..] => infrastructure::dispatch(&args),
|
||||
["build", "gnome-probe", work, bootstrap] => archipelago_builder::build_gnome_probe_script()
|
||||
.and_then(|script| env::current_exe().map_err(|e| e.to_string()).and_then(|binary|
|
||||
run(&script, &[work.to_string(), bootstrap.to_string(), binary.display().to_string(), "gnome-probe".into()]))),
|
||||
["desktop", "reconcile"] => archipelago_system::desktop::reconcile(),
|
||||
["desktop", "seed-flatpaks"] => archipelago_system::desktop::seed_flatpaks(),
|
||||
["layer", "validate", path] => std::fs::read_to_string(path).map_err(|e| e.to_string())
|
||||
.and_then(|text| archipelago_contracts::layer::validate(&text))
|
||||
.map(|_| println!("Layer v1 syntax, schema and source-local checks passed; resolution/build checks still required")),
|
||||
["registry", "init", path] => archipelago_registry::init(path),
|
||||
["registry", "verify", path] => archipelago_registry::verify(path),
|
||||
["build", "iso", work, bootstrap] => {
|
||||
match env::current_exe() {
|
||||
Ok(binary) => run(&archipelago_builder::build_iso_script(),
|
||||
&[work.to_string(), bootstrap.to_string(), binary.display().to_string()]),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
["install", device, "--erase"] => run(archipelago_installer::INSTALL, &[device.to_string()]),
|
||||
["firstboot"] => run(archipelago_system::FIRSTBOOT, &[]),
|
||||
["self-check"] => self_check::check(),
|
||||
["status"] => run(archipelago_system::HOST, &args).and_then(|_| archipelago_system::extensions::describe()),
|
||||
["boot-sync"] => run(archipelago_system::HOST, &args),
|
||||
["extension", "add", ..] => archipelago_system::extensions::add(&args[2..]),
|
||||
["update", "check"] => archipelago_system::updates::plan(false),
|
||||
["update", "plan"] => archipelago_system::updates::plan(true),
|
||||
["update", "apply", "--plan", id] => archipelago_system::updates::apply(id),
|
||||
["overlay", "apply", "test-marker"] => {
|
||||
run(archipelago_system::HOST, &args)
|
||||
}
|
||||
_ => {
|
||||
eprintln!("Experimental Core profile\n\
|
||||
archipelago build iso WORKDIR BOOTSTRAP.tar.zst\n\
|
||||
archipelago build gnome-probe WORKDIR BOOTSTRAP.tar.zst (private integration probe)\n\
|
||||
archipelago registry init|verify REPOSITORY\n\
|
||||
archipelago layer validate MANIFEST.yaml\n\
|
||||
archipelago desktop reconcile|seed-flatpaks\n\
|
||||
archipelago install /dev/DEVICE --erase\n\
|
||||
archipelago firstboot | status | self-check\n\
|
||||
archipelago overlay apply test-marker\n\
|
||||
archipelago extension add PACKAGE...\n\
|
||||
archipelago update check|plan\n\
|
||||
archipelago update apply --plan PLAN_SHA256\n\
|
||||
archipelago pipeline status|logs|run --reason TEXT (configured infrastructure host)\n\
|
||||
archipelago release plan|publish CANDIDATES.json --reason TEXT (infrastructure host)\n\
|
||||
Activation happens on the next explicit reboot.");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
match result {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(error) => { eprintln!("archipelago: {error}"); ExitCode::FAILURE }
|
||||
}
|
||||
}
|
||||
32
src/self_check.rs
Normal file
32
src/self_check.rs
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
use std::{fs, os::unix::fs::MetadataExt, process::Command};
|
||||
|
||||
pub fn check() -> Result<(), String> {
|
||||
let owner = Command::new("pacman").args(["-Qoq", "/usr/bin/archipelago"])
|
||||
.output().map_err(|e| e.to_string())?;
|
||||
if !owner.status.success() || owner.stdout != b"archipelago\n" {
|
||||
return Err("binary is not owned by the archipelago package".into());
|
||||
}
|
||||
let status = Command::new("pacman").args(["-Qkk", "archipelago"])
|
||||
.status().map_err(|e| e.to_string())?;
|
||||
if !status.success() { return Err("package integrity check failed".into()); }
|
||||
let manifest = fs::read_to_string("/usr/share/archipelago/permissions.tsv")
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut binary_seen = false;
|
||||
for line in manifest.lines() {
|
||||
let fields: Vec<_> = line.split_whitespace().collect();
|
||||
if fields.len() != 4 || !fields[3].starts_with("usr/") || fields[3].split('/').any(|p| p == "..") {
|
||||
return Err(format!("invalid permissions entry: {line}"));
|
||||
}
|
||||
let path = format!("/{}", fields[3]);
|
||||
let metadata = fs::symlink_metadata(&path).map_err(|e| format!("{path}: {e}"))?;
|
||||
let expected = if path == "/usr/bin/archipelago" { binary_seen = true; "755" } else { "644" };
|
||||
if fields[0] != expected || fields[1] != "0" || fields[2] != "0"
|
||||
|| !metadata.is_file() || metadata.uid() != 0 || metadata.gid() != 0
|
||||
|| format!("{:o}", metadata.mode() & 0o7777) != expected {
|
||||
return Err(format!("incorrect type, ownership or permissions: {path}"));
|
||||
}
|
||||
}
|
||||
if !binary_seen { return Err("permissions manifest omits binary".into()); }
|
||||
println!("ARCHIPELAGO_SELF_CHECK_OK: package integrity, root:root ownership and permissions");
|
||||
Ok(())
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue