Record native desktop delivery, update integration and validation work in progress

This commit is contained in:
Pavel Isaev 2026-11-06 00:09:27 +03:00
parent b2e77f6c56
commit 51bc6ff237
13 changed files with 455 additions and 3 deletions

View file

@ -45,7 +45,13 @@ systemd-nspawn --settings=no --register=no --resolv-conf=replace-host \
mapfile -t requested < /requested
pacman -Sp --needed --print-format "%n %v %r %l" -- "${requested[@]}" > /inputs/plan
fi
pacman -Sw --needed --noconfirm --cachedir /inputs -- "${requested[@]}"
# Keep pacman signature/checksum validation, using a bounded external
# downloader to avoid the observed HTTP/2 reset on large mirror objects.
cp /etc/pacman.conf /run/archipelago-download.conf
sed -i "/^[[:space:]]*XferCommand[[:space:]]*=/d" /run/archipelago-download.conf
sed -i "/^\\[options\\]/a XferCommand = /usr/bin/curl --http1.1 --fail --location --retry 3 --connect-timeout 30 --max-time 1200 --output %o %u" /run/archipelago-download.conf
cp /run/archipelago-download.conf /inputs/download-pacman.conf
pacman --config /run/archipelago-download.conf -Sw --needed --noconfirm --cachedir /inputs -- "${requested[@]}"
' 2>&1 | tee "$generation/logs/download.log"
cp "$generation/inputs/plan" "$generation/plan"
(cd "$root/usr/lib/archipelago/package-db/sync"; sha256sum -c "$generation/sync.sha256")

View file

@ -0,0 +1,31 @@
# GNOME Software adapter — implementation in progress
Targets GNOME Software **51.1**, using its native plugin API. This source is not yet
installed into public images and must not be advertised as working GUI updates.
- The Rust CLI produces digest-bound JSON plans and package-version differences
read from signed OSTree image content. No package metadata is taken from an
unsigned portal response.
- A short-lived root refresh service writes a read-only presentation cache. The
timer checks automatically; interactive refresh/apply uses the exact Polkit
helper executable. No custom resident daemon is introduced.
- Applying starts a bounded systemd job invoking the existing `update apply` path,
sharing its lock, signature verification, state checks and extension reapplication.
- The native Software plugin exposes one whole-image operation and related package
changes. It conflicts with the PackageKit plugin; stock ALPM remains disabled.
Build the module inside the pinned GNOME Software 51.1 source build, adding this
directory under `plugins/` and including its `meson.build`. Keep the existing
Flatpak/fwupd plugins enabled. Never install an untested module into the user's
running desktop.
Remaining before packaging: compile against the exact Arch dependencies; validate
query/schema handling, authorization and headless tests; complete pending/reboot
presentation and cancellation handling; run the real Software update/failure path.
Download-only requests currently return unsupported rather than silently staging.
The GUI must use the supported whole-image online-staging path; this needs actual
Software validation before accepting the interaction contract.
Study references (51.1): GNOME Software `plugins/rpm-ostree` (transaction and related
package principles), `plugins/dummy` (plugin API signatures). No RPM transaction
implementation is copied into the Archipelago engine.

View file

@ -0,0 +1,12 @@
[Unit]
Description=Refresh signed Archipelago OS update metadata
ConditionPathExists=/run/ostree-booted
ConditionPathExists=/etc/archipelago/provisioned
Wants=network-online.target time-set.target
After=network-online.target time-set.target
[Service]
Type=oneshot
ExecStart=/usr/bin/archipelago desktop refresh-updates
TimeoutStartSec=10min
UMask=0022

View file

@ -0,0 +1,10 @@
[Unit]
Description=Check for signed Archipelago OS updates
[Timer]
OnBootSec=2min
OnUnitInactiveSec=1h
RandomizedDelaySec=30
[Install]
WantedBy=timers.target

View file

@ -0,0 +1,196 @@
/* SPDX-License-Identifier: GPL-2.0-or-later
* GNOME Software 51 adapter. OS transactions remain in the Rust CLI.
*/
#define I_KNOW_THE_GNOME_SOFTWARE_API_IS_SUBJECT_TO_CHANGE
#include <gnome-software.h>
#include <json-glib/json-glib.h>
#include <string.h>
#define STATUS_FILE "/var/lib/archipelago/software/status.json"
#define HELPER "/usr/lib/archipelago/software-helper"
typedef struct { GsPlugin parent; GFileMonitor *monitor; } GsPluginArchipelago;
typedef struct { GsPluginClass parent_class; } GsPluginArchipelagoClass;
G_DEFINE_TYPE (GsPluginArchipelago, gs_plugin_archipelago, GS_TYPE_PLUGIN)
static gboolean
is_ru (void)
{
const gchar * const *languages = g_get_language_names ();
return languages && languages[0] && g_str_has_prefix (languages[0], "ru");
}
static void
changed (GFileMonitor *monitor, GFile *file, GFile *other, GFileMonitorEvent event, gpointer data)
{
gs_plugin_updates_changed (GS_PLUGIN (data));
}
static void
gs_plugin_archipelago_init (GsPluginArchipelago *self)
{
g_autoptr(GFile) directory = g_file_new_for_path ("/var/lib/archipelago/software");
if (!g_file_test ("/run/ostree-booted", G_FILE_TEST_EXISTS) ||
!g_file_test ("/usr/lib/archipelago/gnome-firstboot", G_FILE_TEST_EXISTS)) {
gs_plugin_set_enabled (GS_PLUGIN (self), FALSE);
return;
}
gs_plugin_add_rule (GS_PLUGIN (self), GS_PLUGIN_RULE_CONFLICTS, "packagekit");
gs_plugin_add_rule (GS_PLUGIN (self), GS_PLUGIN_RULE_RUN_BEFORE, "generic-updates");
self->monitor = g_file_monitor_directory (directory, G_FILE_MONITOR_NONE, NULL, NULL);
if (self->monitor) g_signal_connect (self->monitor, "changed", G_CALLBACK (changed), self);
}
static void
dispose (GObject *object)
{
GsPluginArchipelago *self = (GsPluginArchipelago *) object;
g_clear_object (&self->monitor);
G_OBJECT_CLASS (gs_plugin_archipelago_parent_class)->dispose (object);
}
static void
list_apps_async (GsPlugin *plugin, GsAppQuery *query, GsPluginListAppsFlags flags,
GsPluginEventCallback event_callback, void *event_data,
GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data)
{
g_autoptr(GTask) task = g_task_new (plugin, cancellable, callback, user_data);
g_autoptr(GsAppList) list = gs_app_list_new ();
g_autoptr(JsonParser) parser = json_parser_new ();
g_autoptr(GError) error = NULL;
if (!query || gs_app_query_get_is_for_update (query) != GS_APP_QUERY_TRISTATE_TRUE) {
g_task_return_new_error (task, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Unsupported query");
return;
}
if (!json_parser_load_from_file (parser, STATUS_FILE, &error)) {
g_task_return_error (task, g_steal_pointer (&error));
return;
}
JsonObject *record = json_node_get_object (json_parser_get_root (parser));
const gchar *state = record ? json_object_get_string_member_with_default (record, "state", "invalid") : "invalid";
if (g_str_equal (state, "error")) {
g_task_return_new_error (task, GS_PLUGIN_ERROR, GS_PLUGIN_ERROR_FAILED, "%s",
json_object_get_string_member_with_default (record, "error", "Update check failed"));
return;
}
if (g_str_equal (state, "available")) {
JsonObject *plan = json_object_get_object_member (record, "plan");
const gchar *id = json_object_get_string_member (record, "plan_id");
const gchar *target = json_object_get_string_member (plan, "target");
const gchar *base = json_object_get_string_member (plan, "base");
g_autoptr(GsApp) app = gs_app_new ("org.archipelago.System");
g_autoptr(GIcon) icon = g_themed_icon_new ("distributor-logo");
g_autoptr(GString) details = g_string_new (is_ru () ? "Изменения пакетов базового образа:\n" : "Base image package changes:\n");
gs_app_set_kind (app, AS_COMPONENT_KIND_OPERATING_SYSTEM);
gs_app_set_scope (app, AS_COMPONENT_SCOPE_SYSTEM);
gs_app_set_bundle_kind (app, AS_BUNDLE_KIND_PACKAGE);
gs_app_set_name (app, GS_APP_QUALITY_HIGHEST, "Archipelago");
gs_app_set_summary (app, GS_APP_QUALITY_HIGHEST, is_ru () ? "Обновление системы" : "System update");
gs_app_set_version (app, base);
gs_app_set_update_version (app, target);
gs_app_set_metadata (app, "Archipelago::Plan", id);
gs_app_set_management_plugin (app, plugin);
gs_app_add_quirk (app, GS_APP_QUIRK_NEEDS_REBOOT);
gs_app_add_quirk (app, GS_APP_QUIRK_NOT_REVIEWABLE);
gs_app_add_icon (app, icon);
/* Staging runs online; reboot only activates the completed deployment. */
gs_app_set_state (app, GS_APP_STATE_UPDATABLE_LIVE);
JsonArray *changes = json_object_get_array_member (plan, "package_changes");
for (guint i = 0; changes && i < json_array_get_length (changes); i++) {
JsonObject *change = json_array_get_object_element (changes, i);
const gchar *name = json_object_get_string_member (change, "name");
JsonNode *old_node = json_object_get_member (change, "old_version");
JsonNode *new_node = json_object_get_member (change, "new_version");
const gchar *old = JSON_NODE_HOLDS_NULL (old_node) ? NULL : json_node_get_string (old_node);
const gchar *new = JSON_NODE_HOLDS_NULL (new_node) ? NULL : json_node_get_string (new_node);
g_autoptr(GsApp) package = gs_app_new (NULL);
gs_app_add_source (package, name);
gs_app_set_name (package, GS_APP_QUALITY_NORMAL, name);
gs_app_set_kind (package, AS_COMPONENT_KIND_GENERIC);
gs_app_set_bundle_kind (package, AS_BUNDLE_KIND_PACKAGE);
gs_app_set_scope (package, AS_COMPONENT_SCOPE_SYSTEM);
gs_app_set_version (package, old);
gs_app_set_update_version (package, new);
gs_app_add_related (app, package);
g_string_append_printf (details, "%s: %s → %s\n", name, old ? old : "—", new ? new : "—");
}
gs_app_set_update_details_text (app, details->str);
gs_app_list_add (list, app);
} else if (!g_str_equal (state, "current") && !g_str_equal (state, "pending")) {
g_task_return_new_error (task, GS_PLUGIN_ERROR, GS_PLUGIN_ERROR_FAILED, "Invalid Archipelago update state");
return;
}
g_task_return_pointer (task, g_steal_pointer (&list), g_object_unref);
}
static GsAppList *list_apps_finish (GsPlugin *plugin, GAsyncResult *result, GError **error)
{ return g_task_propagate_pointer (G_TASK (result), error); }
static void
helper_thread (GTask *task, gpointer source, gpointer task_data, GCancellable *cancellable)
{
const gchar *id = task_data;
const gchar *args[] = { "/usr/bin/pkexec", HELPER, id ? "apply" : "refresh", id, NULL };
g_autoptr(GError) error = NULL;
g_autoptr(GSubprocess) child = g_subprocess_newv (args, G_SUBPROCESS_FLAGS_STDOUT_PIPE | G_SUBPROCESS_FLAGS_STDERR_PIPE, &error);
g_autofree gchar *out = NULL, *err = NULL;
if (!child || !g_subprocess_communicate_utf8 (child, NULL, cancellable, &out, &err, &error)) {
if (!error) g_set_error_literal (&error, GS_PLUGIN_ERROR, GS_PLUGIN_ERROR_FAILED, "Helper communication failed; inspect operation status");
g_task_return_error (task, g_steal_pointer (&error));
} else if (!g_subprocess_get_successful (child)) {
g_task_return_new_error (task, GS_PLUGIN_ERROR, GS_PLUGIN_ERROR_FAILED, "%s", err ? err : "Update failed");
} else g_task_return_boolean (task, TRUE);
}
static void
refresh_async (GsPlugin *plugin, guint64 age, GsPluginRefreshMetadataFlags flags,
GsPluginEventCallback event_callback, void *event_data,
GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data)
{
g_autoptr(GTask) task = g_task_new (plugin, cancellable, callback, user_data);
if (!(flags & GS_PLUGIN_REFRESH_METADATA_FLAGS_INTERACTIVE)) {
/* The system timer performs unattended checks without authorization dialogs. */
g_task_return_boolean (task, TRUE);
return;
}
g_task_run_in_thread (task, helper_thread);
}
static gboolean boolean_finish (GsPlugin *plugin, GAsyncResult *result, GError **error)
{ return g_task_propagate_boolean (G_TASK (result), error); }
static void
update_async (GsPlugin *plugin, GsAppList *apps, GsPluginUpdateAppsFlags flags,
GsPluginProgressCallback progress, gpointer progress_data,
GsPluginEventCallback event_callback, void *event_data,
GsPluginAppNeedsUserActionCallback action, gpointer action_data,
GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data)
{
g_autoptr(GTask) task = g_task_new (plugin, cancellable, callback, user_data);
if ((flags & GS_PLUGIN_UPDATE_APPS_FLAGS_NO_APPLY) || gs_app_list_length (apps) != 1) {
g_task_return_new_error (task, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Use a single whole-image online staging operation");
return;
}
GsApp *app = gs_app_list_index (apps, 0);
const gchar *id = gs_app_get_metadata_item (app, "Archipelago::Plan");
if (!gs_app_has_management_plugin (app, plugin) || !id || strlen (id) != 64 || strspn (id, "0123456789abcdef") != 64) {
g_task_return_new_error (task, GS_PLUGIN_ERROR, GS_PLUGIN_ERROR_FAILED, "Invalid update plan");
return;
}
g_task_set_task_data (task, g_strdup (id), g_free);
g_task_run_in_thread (task, helper_thread);
}
static void gs_plugin_archipelago_class_init (GsPluginArchipelagoClass *klass)
{
GsPluginClass *plugin = GS_PLUGIN_CLASS (klass);
G_OBJECT_CLASS (klass)->dispose = dispose;
plugin->list_apps_async = list_apps_async;
plugin->list_apps_finish = list_apps_finish;
plugin->refresh_metadata_async = refresh_async;
plugin->refresh_metadata_finish = boolean_finish;
plugin->update_apps_async = update_async;
plugin->update_apps_finish = boolean_finish;
}
G_MODULE_EXPORT GType gs_plugin_query_type (void)
{ return gs_plugin_archipelago_get_type (); }

View file

@ -0,0 +1,6 @@
shared_module('gs_plugin_archipelago',
sources: ['gs-plugin-archipelago.c'],
install: true,
install_dir: plugin_dir,
dependencies: [plugin_libs, dependency('json-glib-1.0')],
c_args: ['-DG_LOG_DOMAIN="GsPluginArchipelago"'])

View file

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN" "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
<policyconfig>
<vendor>Archipelago</vendor>
<action id="org.archipelago.software.update">
<description>Manage Archipelago system updates</description>
<description xml:lang="ru">Управление обновлениями Archipelago</description>
<message>Authentication is required to manage system updates</message>
<message xml:lang="ru">Для управления обновлениями системы требуется авторизация</message>
<defaults><allow_any>no</allow_any><allow_inactive>no</allow_inactive><allow_active>auth_admin_keep</allow_active></defaults>
<annotate key="org.freedesktop.policykit.exec.path">/usr/lib/archipelago/software-helper</annotate>
</action>
</policyconfig>

View file

@ -0,0 +1,3 @@
#!/bin/sh
# Installed root-owned; pkexec authorizes this exact executable.
exec /usr/bin/archipelago desktop software-request "$@"

View file

@ -0,0 +1,48 @@
/* Run only inside a disposable Arch build/test root. */
#include "gs-plugin-archipelago.c"
static GMainLoop *loop;
static GsAppList *result_list;
static GError *result_error;
static void completed (GObject *source, GAsyncResult *result, gpointer data)
{
result_list = list_apps_finish (GS_PLUGIN (source), result, &result_error);
g_main_loop_quit (loop);
}
int main (void)
{
g_autoptr(GTestDBus) test_bus = g_test_dbus_new (G_TEST_DBUS_NONE);
g_test_dbus_up (test_bus);
g_autoptr(GDBusConnection) bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
g_assert_nonnull (bus);
g_autoptr(GsPlugin) plugin = g_object_new (gs_plugin_archipelago_get_type (),
"session-bus-connection", bus, "system-bus-connection", bus, NULL);
g_autoptr(GsAppQuery) query = gs_app_query_new ("is-for-update", GS_APP_QUERY_TRISTATE_TRUE, NULL);
g_mkdir_with_parents ("/var/lib/archipelago/software", 0755);
const gchar *fixture = "{\"version\":1,\"state\":\"available\",\"plan_id\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"plan\":{\"base\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"target\":\"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\",\"package_changes\":[{\"name\":\"linux\",\"old_version\":\"1\",\"new_version\":\"2\"},{\"name\":\"added\",\"old_version\":null,\"new_version\":\"3\"},{\"name\":\"removed\",\"old_version\":\"4\",\"new_version\":null}]}}";
g_assert_true (g_file_set_contents (STATUS_FILE, fixture, -1, NULL));
loop = g_main_loop_new (NULL, FALSE);
list_apps_async (plugin, query, 0, NULL, NULL, NULL, completed, NULL);
g_main_loop_run (loop);
g_assert_no_error (result_error);
g_assert_cmpuint (gs_app_list_length (result_list), ==, 1);
GsApp *app = gs_app_list_index (result_list, 0);
g_assert_true (gs_app_has_management_plugin (app, plugin));
g_assert_true (gs_app_has_quirk (app, GS_APP_QUIRK_NEEDS_REBOOT));
g_assert_cmpuint (gs_app_list_length (gs_app_get_related (app)), ==, 3);
g_assert_nonnull (strstr (gs_app_get_update_details_markup (app), "linux"));
g_clear_object (&result_list);
g_assert_true (g_file_set_contents (STATUS_FILE, "{\"version\":1,\"state\":\"error\",\"error\":\"signature rejected\"}", -1, NULL));
list_apps_async (plugin, query, 0, NULL, NULL, NULL, completed, NULL);
g_main_loop_run (loop);
g_assert_null (result_list);
g_assert_error (result_error, GS_PLUGIN_ERROR, GS_PLUGIN_ERROR_FAILED);
g_clear_error (&result_error);
g_main_loop_unref (loop);
g_clear_object (&plugin);
g_clear_object (&bus);
g_test_dbus_down (test_bus);
g_print ("PLUGIN_PACKAGE_DIFF_AND_ERROR_PRESENTATION_PASS\n");
return 0;
}

View file

@ -3,6 +3,8 @@ pub mod onboarding;
pub mod extensions;
pub mod desktop;
pub mod updates;
pub mod package_diff;
pub mod software;
pub const HOST: &str = include_str!("../adapters/host.sh");
pub const FIRSTBOOT: &str = include_str!("../adapters/firstboot.sh");

51
src/package_diff.rs Normal file
View file

@ -0,0 +1,51 @@
//! Version differences from package inventories stored inside verified image commits.
use std::collections::{BTreeMap, BTreeSet};
use serde_json::{json, Value};
fn inventory(text: &str) -> Result<BTreeMap<String, String>, String> {
let mut packages = BTreeMap::new();
for line in text.lines().filter(|line| !line.trim().is_empty()) {
let fields: Vec<_> = line.split_whitespace().collect();
if fields.len() != 2 || fields[0].starts_with('-') ||
!fields[0].bytes().all(|c| c.is_ascii_alphanumeric() || b"@._+-".contains(&c)) {
return Err("invalid image package inventory".into());
}
if packages.insert(fields[0].into(), fields[1].into()).is_some() {
return Err("duplicate package in image inventory".into());
}
}
if packages.is_empty() { return Err("empty image package inventory".into()); }
Ok(packages)
}
pub fn between(before: &str, after: &str) -> Result<Vec<Value>, String> {
let before = inventory(before)?;
let after = inventory(after)?;
let names: BTreeSet<_> = before.keys().chain(after.keys()).collect();
Ok(names.into_iter().filter_map(|name| {
let old = before.get(name); let new = after.get(name);
if old == new { return None; }
Some(json!({"name":name,"old_version":old,"new_version":new,
"change": if old.is_none() { "added" } else if new.is_none() { "removed" } else { "changed" }}))
}).collect())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn additions_removals_epoch_changes_and_unchanged_packages() {
let diff = between("linux 6.1-1\nremoved 1-1\nsame 2-1\n", "added 3-1\nlinux 1:6.1-1\nsame 2-1\n").unwrap();
assert_eq!(diff.len(), 3);
assert_eq!(diff[0]["change"], "added");
assert_eq!(diff[1]["old_version"], "6.1-1");
assert_eq!(diff[1]["new_version"], "1:6.1-1");
assert_eq!(diff[2]["change"], "removed");
}
#[test]
fn ambiguous_or_missing_inventory_is_not_an_empty_update() {
for invalid in ["", "pkg 1\npkg 2", "pkg", "pkg 1 extra"] {
assert!(between("pkg 1", invalid).is_err());
}
}
}

56
src/software.rs Normal file
View file

@ -0,0 +1,56 @@
//! Privileged, short-lived GNOME Software bridge to the shared update engine.
use serde_json::{json, Value};
use std::{fs, path::Path, process::Command};
const CACHE: &str = "/var/lib/archipelago/software";
fn run(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()); }
String::from_utf8(out.stdout).map_err(|e| e.to_string())
}
fn save(value: &Value) -> Result<(), String> {
fs::create_dir_all(CACHE).map_err(|e| e.to_string())?;
let temp = Path::new(CACHE).join("status.tmp");
fs::write(&temp, serde_json::to_vec_pretty(value).unwrap()).map_err(|e| e.to_string())?;
fs::rename(temp, Path::new(CACHE).join("status.json")).map_err(|e| e.to_string())
}
pub fn refresh() -> Result<(), String> {
if run(&["id", "-u"])?.trim() != "0" { return Err("Run through the authorized Software helper".into()); }
let lock = fs::File::options().create(true).truncate(false).write(true)
.open("/run/archipelago-software.lock").map_err(|e| e.to_string())?;
lock.try_lock().map_err(|e| format!("Software refresh busy: {e}"))?;
let state = crate::extensions::status()?;
if state["deployments"].as_array().ok_or("missing deployments")?.iter()
.any(|d| d["pending"] == true || d["staged"] == true) {
return save(&json!({"version":1,"state":"pending","deployments":state}));
}
match run(&["/usr/bin/archipelago", "update", "plan", "--json"]) {
Ok(text) => {
let mut record: Value = serde_json::from_str(&text).map_err(|e| e.to_string())?;
record["version"] = json!(1);
record["state"] = json!(if record["plan"]["base"] == record["plan"]["target"] { "current" } else { "available" });
save(&record)
}
Err(error) => { save(&json!({"version":1,"state":"error","error":error}))?; Err(error) }
}
}
pub fn request(operation: &str, plan: Option<&str>) -> Result<(), String> {
if run(&["id", "-u"])?.trim() != "0" { return Err("Authorization required".into()); }
if operation == "refresh" && plan.is_none() {
return run(&["systemctl", "start", "--wait", "archipelago-software-refresh.service"]).map(|_| ());
}
let mut command = vec!["systemd-run", "--collect", "--wait", "--quiet",
"--property=RuntimeMaxSec=2h", "--property=StandardOutput=journal",
"--property=StandardError=journal"];
match (operation, plan) {
("apply", Some(id)) if id.len() == 64 && id.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) =>
command.extend(["--unit=archipelago-software-apply", "/usr/bin/archipelago", "update", "apply", "--plan", id]),
_ => return Err("Unsupported Software operation".into()),
}
let result = run(&command);
if operation == "apply" {
// Always reconcile the real deployment, including failures after staging.
if let Err(error) = refresh() { eprintln!("Software state refresh: {error}"); }
}
result.map(|_| ())
}

View file

@ -81,6 +81,12 @@ fn plan_path(id: &str) -> Result<PathBuf, String> {
Ok(Path::new(STATE).join(format!("plan-{id}.json")))
}
pub fn plan(save: bool) -> Result<(), String> {
plan_output(save, false, false)
}
pub fn plan_json(save: bool) -> Result<(), String> {
plan_output(save, true, true)
}
fn plan_output(save: bool, json_output: bool, include_diff: bool) -> Result<(), String> {
let _lock = lock()?;
let binding = binding()?;
configure(&binding)?;
@ -93,14 +99,26 @@ pub fn plan(save: bool) -> Result<(), String> {
}
let reference = binding["reference"].as_str().ok_or("missing reference")?;
let target = summary_commit(&repo(&["remote", "summary", REMOTE])?, &reference)?;
let plan = json!({"version":2,"binding":binding,"variant":variant(),"reference":reference,
let mut plan = json!({"version":2,"binding":binding,"variant":variant(),"reference":reference,
"target":target,"base":base,"requested":requested,"initial":state});
if include_diff {
let inventory = "/usr/lib/archipelago/packages.txt";
repo(&["pull", "--depth=0", &format!("--subpath={inventory}"), REMOTE, &target])?;
let before = output("ostree", &["--repo=/sysroot/ostree/repo", "cat", &base, inventory])?;
let after = repo(&["cat", &target, inventory])?;
plan["package_changes"] = json!(crate::package_diff::between(&before, &after)?);
plan["package_changes_scope"] = json!("managed-base");
}
if !save { println!("{}", serde_json::to_string_pretty(&plan).unwrap()); return Ok(()); }
let temp = Path::new(STATE).join("plan.tmp");
write(&temp, &plan)?;
let hash = output("sha256sum", &[temp.to_str().unwrap()])?.split_whitespace().next().ok_or("missing digest")?.to_string();
fs::rename(&temp, plan_path(&hash)?).map_err(|e| e.to_string())?;
println!("Plan: {hash}\nTarget: {target}\nApply: sudo archipelago update apply --plan {hash}");
if json_output {
println!("{}", serde_json::to_string_pretty(&json!({"plan_id":hash,"plan":plan})).unwrap());
} else {
println!("Plan: {hash}\nTarget: {target}\nApply: sudo archipelago update apply --plan {hash}");
}
Ok(())
}
pub fn apply(id: &str) -> Result<(), String> {