builder/adapters/container-runner-package.sh

298 lines
13 KiB
Bash
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Container Runner integration assets. Server Purpose; no desktop stack.
# Runs inside the isolated builder with $pkg pointing at the purpose assets.
sed 's/Archipelago Core/Archipelago Container Runner/g' \
"$pkg/runtime/usr/lib/archipelago/defaults/os-release" > "$pkg/runtime/usr/lib/archipelago/defaults/os-release-container-runner"
# Server initramfs: keep the Core profile, add keyboard/vconsole for rescue consoles.
sed -e 's/modconf block/modconf kms keyboard sd-vconsole block/' \
"$pkg/runtime/usr/lib/archipelago/mkinitcpio-core.conf" > "$pkg/runtime/usr/lib/archipelago/mkinitcpio-container-runner.conf"
printf 'Container Runner; operator-managed container host\n' > "$pkg/runtime/usr/lib/archipelago/container-runner"
printf 'purpose/server/container-runner\n' > "$pkg/runtime/usr/lib/archipelago/purpose"
mkdir -p "$pkg/runtime/usr/lib/systemd/system" "$pkg/runtime/usr/lib/systemd/system-preset" \
"$pkg/runtime/usr/etc/containers/registries.conf.d" "$pkg/runtime/usr/share/archipelago/container-runner"
# D-118: Toolbx is part of this Purpose too, with the same upstream Arch image as
# Core and Desktop Purposes. The Purpose carries the default so it does not depend
# on a Core rebuild to add it.
cat > "$pkg/runtime/usr/etc/containers/toolbox.conf" <<'TOOLBOX'
@@TOOLBOX_CONFIG@@
TOOLBOX
cat > "$pkg/runtime/usr/etc/containers/registries.conf.d/60-archipelago-toolbox.conf" <<'TOOLBOX_REGISTRIES'
@@TOOLBOX_REGISTRIES@@
TOOLBOX_REGISTRIES
cat > "$pkg/runtime/usr/lib/systemd/system-preset/10-archipelago-container-runner.preset" <<'PRESET'
enable cockpit.socket
enable libvirtd.service
enable systemd-binfmt.service
disable tailscaled.service
disable firewalld.service
PRESET
cat > "$pkg/runtime/usr/share/archipelago/container-runner/README" <<'EOF'
Container Runner defaults
- Cockpit is enabled on 9090 with its self-signed certificate.
- Tailscale is installed but intentionally disabled; connect it manually:
systemctl enable --now tailscaled && tailscale up
- firewalld is installed but intentionally disabled and carries no rules.
The operator decides which zones, services and ports to open.
- qemu-user-static binfmt registrations are enabled for foreign-architecture images.
- Toolbx is installed with the same upstream Arch default as Desktop Purposes
(quay.io/toolbx/arch-toolbox:latest). Create a mutable development environment
with `toolbox create`; `toolbox enter` opens it. Users may override the image in
~/.config/containers/toolbox.conf, and containers persist in the user's home.
- QEMU/KVM and libvirt are installed for Cockpit Machines: qemu-system-x86,
qemu-img, libvirt (+ libvirt-dbus), dnsmasq for the default NAT network,
edk2-ovmf for UEFI guests, swtpm for emulated TPM 2.0 and virt-install for
creating new machines from Cockpit. libvirtd.service and libvirt's default NAT
network are enabled.
- Hardware virtualisation must be available: check for /dev/kvm. Operators who
manage machines from Cockpit need membership in the kvm group
(usermod -aG kvm <user>); without it only root can start guests.
- Container data is workload state in /var; OS updates and rollback do not remove it.
EOF
# Cockpit update page (D-100). It is a D-Bus client of archipelagod: no
# PackageKit, no pacman, no shell command and no second deployment writer.
updates="$pkg/runtime/usr/share/cockpit/archipelago-updates"
mkdir -p "$updates"
cat > "$updates/manifest.json" <<'EOF'
{
"version": 0,
"tools": {
"archipelago-updates": {
"label": "Обновления ОС",
"path": "index.html"
}
}
}
EOF
cat > "$updates/index.html" <<'EOF'
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<title>Archipelago · Обновления ОС</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<h1>Archipelago · Обновления ОС</h1>
<p id="daemon" class="muted">Проверка службы…</p>
</header>
<section id="state" class="card">
<dl>
<dt>Загруженная система</dt><dd id="booted">—</dd>
<dt>Следующая загрузка</dt><dd id="pending">—</dd>
<dt>Обновление</dt><dd id="update">—</dd>
</dl>
</section>
<section class="card">
<div class="actions">
<button id="refresh">Проверить обновления</button>
<button id="prepare" disabled>Подготовить план</button>
<button id="download" disabled>Загрузить</button>
<button id="stage" disabled>Применить</button>
</div>
<p id="progress" class="muted" aria-live="polite"></p>
<p id="error" class="error" hidden></p>
<p id="result" hidden></p>
</section>
<section class="card">
<h2>Изменения</h2>
<pre id="details" class="muted">Проверьте обновления, чтобы увидеть состав.</pre>
</section>
<script src="../base1/cockpit.js"></script>
<script src="updates.js"></script>
</body>
</html>
EOF
cat > "$updates/style.css" <<'EOF'
:root { color-scheme: light dark; }
body { font-family: system-ui, sans-serif; margin: 0 auto; max-width: 56rem; padding: 1.5rem; }
h1 { font-size: 1.35rem; margin: 0 0 .35rem; }
h2 { font-size: 1rem; margin: 0 0 .5rem; }
.card { border: 1px solid color-mix(in srgb, currentColor 20%, transparent); border-radius: .6rem; padding: 1rem; margin: 1rem 0; }
dl { display: grid; grid-template-columns: max-content 1fr; gap: .25rem 1rem; margin: 0; }
dt { font-weight: 600; }
.muted { opacity: .75; }
.error { color: #c0392b; white-space: pre-wrap; }
.actions { display: flex; flex-wrap: wrap; gap: .5rem; }
button { padding: .45rem .9rem; border-radius: .45rem; cursor: pointer; }
button:disabled { cursor: not-allowed; opacity: .5; }
pre { white-space: pre-wrap; max-height: 22rem; overflow: auto; margin: 0; }
EOF
cat > "$updates/updates.js" <<'EOF'
"use strict";
// The page is a typed D-Bus client only. It never shells out and never claims an
// update is installed before the daemon reports a staged deployment.
const MANAGER = "/org/archipelago/System1";
const MANAGER_IFACE = "org.archipelago.System1.Manager";
const TRANSACTION_IFACE = "org.archipelago.System1.Transaction";
const bus = cockpit.dbus("org.archipelago.System1", { bus: "system", superuser: "try" });
const $ = id => document.getElementById(id);
let busy = false;
let planId = null;
let target = null;
function uuid() {
if (window.crypto && crypto.randomUUID) { return crypto.randomUUID(); }
const bytes = crypto.getRandomValues(new Uint8Array(16));
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const hex = Array.from(bytes, b => b.toString(16).padStart(2, "0")).join("");
return hex.slice(0, 8) + "-" + hex.slice(8, 12) + "-" + hex.slice(12, 16) + "-" +
hex.slice(16, 20) + "-" + hex.slice(20);
}
function options(extra) {
const result = { interactive: cockpit.variant("b", true), request_id: cockpit.variant("s", uuid()) };
for (const [key, value] of Object.entries(extra || {})) {
if (typeof value === "boolean") { result[key] = cockpit.variant("b", value); }
else if (typeof value === "string") { result[key] = cockpit.variant("s", value); }
else { throw new Error("Unsupported D-Bus option type: " + key); }
}
return result;
}
function unbox(value) {
if (value && typeof value === "object" && typeof value.t === "string" && Object.prototype.hasOwnProperty.call(value, "v")) {
return unbox(value.v);
}
if (Array.isArray(value)) { return value.map(unbox); }
if (value && typeof value === "object") {
const result = {};
for (const [key, child] of Object.entries(value)) { result[key] = unbox(child); }
return result;
}
return value;
}
async function call(method, args) {
const reply = await bus.call(MANAGER, MANAGER_IFACE, method, args || []);
return unbox(reply[0]);
}
function showError(text) {
$("error").hidden = !text;
$("error").textContent = text || "";
}
function setBusy(value) {
busy = value;
for (const id of ["refresh", "prepare", "download", "stage"]) {
$(id).disabled = value || ($(id).dataset.ready !== "yes");
}
}
function label(state) {
return ({ current: "Система актуальна", available: "Доступно обновление",
downloaded: "Файлы загружены", staged: "Готово к перезагрузке",
"no-change": "Изменений нет", reconciled: "Проверка результата" })[state] || state || "—";
}
async function refreshStatus() {
try {
const status = await call("GetStatus");
$("daemon").textContent = "Служба archipelagod доступна (D-Bus, system bus)";
$("booted").textContent = (status.booted && status.booted.deployment_id) || "—";
$("pending").textContent = (status.pending && status.pending.deployment_id) || "нет";
$("update").textContent = label(status.update && status.update.state);
} catch (error) {
$("daemon").textContent = "Служба archipelagod недоступна; состояние системы неизвестно";
showError("D-Bus: " + error);
}
}
async function waitTransaction(path, caption) {
for (;;) {
const [rawSnapshot] = await bus.call(path, TRANSACTION_IFACE, "GetSnapshot", []);
const snapshot = unbox(rawSnapshot);
const progress = snapshot.Progress || {};
const percent = typeof progress.percent === "number" ? progress.percent + "% · " : "";
$("progress").textContent = caption + ": " + percent + (progress.message || snapshot.Phase || "");
const state = snapshot.State;
if (state === "succeeded") { $("progress").textContent = caption + ": готово"; return snapshot.Result || {}; }
if (state === "failed" || state === "cancelled" || state === "interrupted") {
const description = snapshot.Error && (snapshot.Error.message || snapshot.Error.code);
throw new Error(caption + ": " + (description || state));
}
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
async function run(method, args, caption) {
const path = await call(method, args);
return waitTransaction(path, caption);
}
async function check() {
showError("");
setBusy(true);
$("result").hidden = true;
try {
const refreshed = await run("Refresh", [options({ force: true })], "Проверка обновлений");
target = refreshed.target || null;
const availability = refreshed.outcome;
$("update").textContent = label(availability);
planId = null;
$("prepare").dataset.ready = target && availability === "available" ? "yes" : "no";
$("download").dataset.ready = "no";
$("stage").dataset.ready = "no";
if (target && availability === "available") {
// GetUpdateDetails returns a transaction object path, not the details
// payload. Observe the durable operation before rendering its result.
const details = await run("GetUpdateDetails", [target, options()], "Состав обновления");
$("details").textContent = JSON.stringify(details.plan || details, null, 2);
} else if (availability === "current") {
$("details").textContent = "Система актуальна: новых образов нет.";
} else {
throw new Error("Неожиданный ответ Refresh: " + String(availability));
}
} catch (error) {
showError(String(error.message || error));
} finally { setBusy(false); }
}
async function prepare() {
showError("");
setBusy(true);
try {
const plan = await run("PrepareUpdate", [target, options()], "Подготовка плана");
planId = plan.plan_id || null;
$("details").textContent = JSON.stringify(plan.plan || plan, null, 2);
$("download").dataset.ready = planId ? "yes" : "no";
$("stage").dataset.ready = planId ? "yes" : "no";
$("prepare").dataset.ready = "no";
} catch (error) {
showError(String(error.message || error));
} finally { setBusy(false); }
}
async function download() {
showError("");
setBusy(true);
try {
await run("Download", [planId, options()], "Загрузка");
$("download").dataset.ready = "no";
$("stage").dataset.ready = "yes";
} catch (error) {
showError(String(error.message || error));
} finally { setBusy(false); }
}
async function stage() {
showError("");
setBusy(true);
try {
const staged = await run("Stage", [planId, options()], "Применение");
$("result").hidden = false;
$("result").textContent = staged.outcome === "no-change"
? "Изменений нет."
: "Изменения подготовлены. Они вступят в силу после перезагрузки; перезагрузка выполняется вручную.";
$("stage").dataset.ready = "no";
await refreshStatus();
} catch (error) {
showError(String(error.message || error));
} finally { setBusy(false); }
}
$("refresh").dataset.ready = "yes";
$("refresh").addEventListener("click", check);
$("prepare").addEventListener("click", prepare);
$("download").addEventListener("click", download);
$("stage").addEventListener("click", stage);
setBusy(false);
refreshStatus();
EOF
cat > "$pkg/runtime/usr/share/archipelago/container-runner/cockpit-updates" <<'EOF'
The Cockpit page /usr/share/cockpit/archipelago-updates is a typed client of
org.archipelago.System1 on the system bus (GetStatus, Refresh, GetUpdateDetails,
PrepareUpdate, Download, Stage, Transaction.GetSnapshot). It never uses
PackageKit, pacman, shell commands or a second deployment writer. Stage only
prepares the next boot; the operator reboots explicitly.
EOF