From 790a4dd2b07d8b5b67c63aa0c10e51cbb2e080c3 Mon Sep 17 00:00:00 2001 From: Archipelago Date: Sat, 14 Nov 2026 13:14:42 +0300 Subject: [PATCH] Report real update progress and ship the distributor icon (D-112) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Progress.percent becomes a monotonic completion estimate: phase checkpoints keep their bands and fetching OSTree commands refine the value inside the band from libostree's terminal output. libostree draws progress only on a TTY, so Worker::command_progress runs the command under `script -qec`, strips ANSI and carriage-return redrawing, and parses receiving/writing/completion records. OperationEvents::progress clamps to 99, never rewinds and skips no-op fsyncs. Applied to layer pull, image pull in prepare/execute, both pull-local imports and retain_clean_base. Discover keeps a monotonic floor across PrepareUpdate→Stage, preserves the last observation when GetStatus fails, and stops reporting the transient `reconciling` window as an update error. GNOME Software polls snapshots from its worker thread, marshals percentages to the caller's GMainContext, mirrors them onto related package rows and applies the same reconciliation policy. The package installs archipelago.svg and archipelago-symbolic.svg into hicolor so both clients can show the distributor identity. --- SERVICE.md | 34 +++ integrations/discover/ArchipelagoBackend.cpp | 58 ++--- .../gnome-software/gs-plugin-archipelago.c | 55 ++++- integrations/gnome-software/system-bus.h | 28 ++- integrations/icons/archipelago-symbolic.svg | 4 + integrations/icons/archipelago.svg | 16 ++ src/service/events.rs | 32 ++- src/service/worker.rs | 203 +++++++++++++++++- src/updates/managed.rs | 33 ++- 9 files changed, 406 insertions(+), 57 deletions(-) create mode 100644 integrations/icons/archipelago-symbolic.svg create mode 100644 integrations/icons/archipelago.svg diff --git a/SERVICE.md b/SERVICE.md index ebf5399..7131114 100644 --- a/SERVICE.md +++ b/SERVICE.md @@ -1,5 +1,39 @@ # archipelagod implementation checkpoint +## 2026-11-14 checkpoint: observable progress and distributor identity + +`Progress.percent` is now a monotonic completion estimate for the whole +transaction. Phase checkpoints keep their fixed bands, and every fetching OSTree +command additionally refines the value inside the current band from the tool's +own console records. libostree prints transfer progress only to a terminal, so +`Worker::command_progress` runs the command under `script -qec` (a PTY), strips +ANSI/CR redrawing, and maps the newest `Receiving objects:`, `Receiving delta +parts:`, `Receiving metadata objects:`, `Writing objects:` or completion record +onto the band. Unrecognized output leaves the phase percentage untouched. +`OperationEvents::progress` clamps to 99 and never decreases; repeated values do +not fsync the journal. Call sites: layer pull, image pull in `prepare`/`execute`, +both `pull-local` imports and `retain_clean_base`. + +Clients: the Discover backend keeps one monotonic floor across +`PrepareUpdate`→`Stage`, treats a failed `GetStatus` as "keep the last +observation", and no longer renders `reconciling` as an update error. The GNOME +Software plugin polls transaction snapshots on its worker thread, marshals +percentage updates to the caller's `GMainContext`, mirrors them onto related +package rows (the updates list averages watched apps and hides the bar if any is +unknown), and ships the same policy for `reconciling`. + +The `archipelago` package now installs `archipelago.svg` and +`archipelago-symbolic.svg` into `hicolor/scalable/apps`; both adapters use the +colored icon for the OS resource and the symbolic one for the source badge, and +the GNOME/KDE finalizers refresh the hicolor cache. + +Verification: the `archipelago-system` and `archipelago-builder` release test suites +pass, including new unit tests for the console parser and terminal-control +stripping, plus a real GNOME Software plugin contract test and a Discover adapter +build against the `2026-11-12` snapshot. The daemon/adapter behaviour on installed +hardware (progress animation, no reconciliation banner, icon rendering) is still +user-verified only. + ## 2026-11-09 checkpoint (supersedes the historical status below) The D-Bus images from run `20261109T113636Z` were published with an explicit diff --git a/integrations/discover/ArchipelagoBackend.cpp b/integrations/discover/ArchipelagoBackend.cpp index 64fee55..5dd3e1e 100644 --- a/integrations/discover/ArchipelagoBackend.cpp +++ b/integrations/discover/ArchipelagoBackend.cpp @@ -142,7 +142,7 @@ public: QString packageName() const override { return QStringLiteral("archipelago-os"); } QString name() const override { return QStringLiteral("Archipelago KDE"); } QString comment() override { return tr("Verified operating system image; activation requires a restart"); } - QVariant icon() const override { return QStringLiteral("distributor-logo"); } + QVariant icon() const override { return QStringLiteral("archipelago"); } bool canExecute() const override { return false; } void invokeApplication() const override {} bool isRemovable() const override { return false; } @@ -157,13 +157,13 @@ public: QString origin() const override { return QStringLiteral("Archipelago"); } QString section() override { return QStringLiteral("System"); } QString author() const override { return QStringLiteral("Archipelago"); } - QString sourceIcon() const override { return QStringLiteral("drive-harddisk"); } + QString sourceIcon() const override { return QStringLiteral("archipelago-symbolic"); } QDate releaseDate() const override { return {}; } QList addonsInformation() override { return {}; } QString longDescription() override { QString text = comment().toHtmlEscaped(); if (record["state"_L1] == "pending"_L1) text += tr("

A deployment is staged. Restart when ready.

"); - if (record["state"_L1] == "applying"_L1) text += tr("

The operating system update is being prepared. Detailed progress is recorded in the system log.

"); + if (record["state"_L1] == "applying"_L1) text += tr("

The operating system update is being prepared. The active transaction reports its progress.

"); if (record["state"_L1] == "downloading"_L1) text += tr("

The verified operating system image is being downloaded.

"); if (record["state"_L1] == "error"_L1) text += "

"_L1 + record["error"_L1].toString().toHtmlEscaped() + "

"_L1; text += "
"_L1 + record["support_description"_L1].toString().toHtmlEscaped() + "
"_L1; @@ -183,33 +183,38 @@ public: loading = true; busCall(this, managerPath, managerInterface, QStringLiteral("GetStatus"), {}, false, [this](const QDBusMessage &reply) { loading = false; - QJsonObject next; if (reply.type() == QDBusMessage::ErrorMessage) { - next = {{"state"_L1, "error"_L1}, {"error"_L1, reply.errorMessage()}}; - } else { - const auto status = QJsonObject::fromVariantMap(replyMap(reply)); - const auto update = status["update"_L1].toObject(); - const auto pending = status["pending"_L1].toObject(); - auto plan = update["details"_L1].toObject(); - plan["base"_L1] = status["booted"_L1].toObject()["checksum"_L1]; - plan["target"_L1] = update["target"_L1]; - next = {{"state"_L1, update["state"_L1]}, {"target"_L1, update["target"_L1]}, {"plan"_L1, plan}}; - if (!pending["deployment_id"_L1].toString().isEmpty()) next["state"_L1] = "pending"_L1; - if (status["reconciling"_L1].toBool()) { - next["state"_L1] = "error"_L1; - next["error"_L1] = tr("System state is being reconciled. Retry when ready."); - } + // A daemon restart or a held host lock momentarily hides the status. + // Keep the last observation instead of surfacing a transient banner; + // the service watcher and the periodic reload recover the state. + if (record.isEmpty()) setRecord(QJsonObject{{"state"_L1, "current"_L1}}); + return; } - if (record == next) return; - record = next; - Q_EMIT stateChanged(); - Q_EMIT versionsChanged(); - Q_EMIT longDescriptionChanged(); + const auto status = QJsonObject::fromVariantMap(replyMap(reply)); + const auto update = status["update"_L1].toObject(); + const auto pending = status["pending"_L1].toObject(); + auto plan = update["details"_L1].toObject(); + plan["base"_L1] = status["booted"_L1].toObject()["checksum"_L1]; + plan["target"_L1] = update["target"_L1]; + QString state = update["state"_L1].toString(); + if (state.isEmpty()) state = QStringLiteral("current"); + if (!pending["deployment_id"_L1].toString().isEmpty()) state = QStringLiteral("pending"); + // `reconciling` marks a transient observation window while a host writer + // holds the composition lock. The journal-derived update state already + // describes an in-flight transaction, so this is not an update error. + setRecord({{"state"_L1, state}, {"target"_L1, update["target"_L1]}, {"plan"_L1, plan}}); }); } public Q_SLOTS: void invalidated(const QString &, const QVariantMap &, const QStringList &) { reload(); } private: + void setRecord(const QJsonObject &next) { + if (record == next) return; + record = next; + Q_EMIT stateChanged(); + Q_EMIT versionsChanged(); + Q_EMIT longDescriptionChanged(); + } bool loading = false; }; @@ -236,12 +241,17 @@ public: void cancel() override { if (operation) operation->cancel(); } private: QPointer operation; + int progressFloor = 0; void run(OSResource *resource, const QString &method, const QString &id, bool planning) { operation = new SystemOperation(this); connect(operation, &SystemOperation::progress, this, [this](const QVariantMap &snapshot) { setCancellable(snapshot.value(QStringLiteral("CanCancel")).toBool()); const auto progress = snapshot.value(QStringLiteral("Progress")).toMap(); - if (progress.contains(QStringLiteral("percent"))) setProgress(progress.value(QStringLiteral("percent")).toUInt()); + if (!progress.contains(QStringLiteral("percent"))) return; + // PrepareUpdate and Stage are separate durable transactions; keep one + // monotonic bar across both instead of rewinding at the handover. + progressFloor = qMax(progressFloor, progress.value(QStringLiteral("percent")).toInt()); + setProgress(progressFloor); }); connect(operation, &SystemOperation::cancellationError, this, &OSTransaction::passiveMessage); connect(operation, &SystemOperation::finished, this, [this, resource, planning](const QVariantMap &result, const QString &error) { diff --git a/integrations/gnome-software/gs-plugin-archipelago.c b/integrations/gnome-software/gs-plugin-archipelago.c index 9f4ddd9..4891527 100644 --- a/integrations/gnome-software/gs-plugin-archipelago.c +++ b/integrations/gnome-software/gs-plugin-archipelago.c @@ -11,15 +11,56 @@ typedef struct { GsPlugin parent; GDBusConnection *bus; guint subscription; guin typedef struct { GsPluginClass parent_class; } GsPluginArchipelagoClass; G_DEFINE_TYPE (GsPluginArchipelago, gs_plugin_archipelago, GS_TYPE_PLUGIN) -typedef struct { gchar *id; gboolean download; gboolean pending; gboolean interactive; GsApp *app; } UpdateData; +typedef struct { gchar *id; gboolean download; gboolean pending; gboolean interactive; GsApp *app; GMainContext *context; guint last_progress; } UpdateData; static void update_data_free (gpointer pointer) { UpdateData *data = pointer; g_free (data->id); g_clear_object (&data->app); + g_clear_pointer (&data->context, g_main_context_unref); g_free (data); } +/* GNOME Software renders themed icons; keep the generic distributor logo as a + * fallback for systems without the Archipelago icon cache. */ +static GIcon *distributor_icon (void) +{ + const gchar *names[] = { "archipelago", "distributor-logo", NULL }; + return G_ICON (g_themed_icon_new_from_names ((gchar **) names, -1)); +} + +typedef struct { GsApp *app; GMainContext *context; guint percent; } AppProgress; +static gboolean apply_progress (gpointer pointer) +{ + AppProgress *entry = pointer; + gs_app_set_progress (entry->app, entry->percent); + /* The updates list watches related apps too; an unknown percentage on a + * package diff row would otherwise hide the aggregate progress bar. */ + GsAppList *related = gs_app_get_related (entry->app); + for (guint i = 0; related != NULL && i < gs_app_list_length (related); i++) + gs_app_set_progress (gs_app_list_index (related, i), entry->percent); + return G_SOURCE_REMOVE; +} +static void free_progress (gpointer pointer) +{ + AppProgress *entry = pointer; + g_clear_object (&entry->app); + g_clear_pointer (&entry->context, g_main_context_unref); + g_free (entry); +} +/* Polling runs on a worker thread; GsApp must be updated on the main context. */ +static void report_progress (guint percent, gpointer pointer) +{ + UpdateData *data = pointer; + if (percent > 100 || percent <= data->last_progress) return; + data->last_progress = percent; + AppProgress *entry = g_new0 (AppProgress, 1); + entry->app = g_object_ref (data->app); + entry->context = g_main_context_ref (data->context); + entry->percent = percent; + g_main_context_invoke_full (data->context, G_PRIORITY_DEFAULT, apply_progress, entry, free_progress); +} + static gboolean is_ru (void) { @@ -97,7 +138,7 @@ list_thread (GTask *task, gpointer source, gpointer task_data, GCancellable *can 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(GIcon) icon = distributor_icon (); 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); @@ -145,7 +186,7 @@ list_thread (GTask *task, gpointer source, gpointer task_data, GCancellable *can { const gchar *checksum = json_object_get_string_member (record, "pending_checksum"); g_autoptr(GsApp) app = gs_app_new ("org.archipelago.System"); - g_autoptr(GIcon) icon = g_themed_icon_new ("distributor-logo"); + g_autoptr(GIcon) icon = distributor_icon (); 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); @@ -193,9 +234,10 @@ operation_thread (GTask *task, gpointer source, gpointer task_data, GCancellable if (bus && data->pending) { result = bus_call(bus, ARCH_PATH, ARCH_MANAGER, "ValidatePending", g_variant_new("(s)", data->id), FALSE, &error); } else if (bus && data->id) { - g_autoptr(GVariant) plan = bus_operation(bus, "PrepareUpdate", data->id, data->interactive, cancellable, &error); - if (plan) result = bus_operation(bus, data->download ? "Download" : "Stage", - bus_string(plan, "plan_id"), data->interactive, cancellable, &error); + g_autoptr(GVariant) plan = bus_operation_full(bus, "PrepareUpdate", data->id, data->interactive, + cancellable, report_progress, data, &error); + if (plan) result = bus_operation_full(bus, data->download ? "Download" : "Stage", + bus_string(plan, "plan_id"), data->interactive, cancellable, report_progress, data, &error); } else if (bus) { result = bus_operation(bus, "Refresh", NULL, data->interactive, cancellable, &error); if (result && g_str_equal(bus_string(result, "outcome"), "available")) { @@ -272,6 +314,7 @@ update_async (GsPlugin *plugin, GsAppList *apps, GsPluginUpdateAppsFlags flags, data->pending = pending != NULL; data->interactive = (flags & GS_PLUGIN_UPDATE_APPS_FLAGS_INTERACTIVE) != 0; data->app = g_object_ref (app); + data->context = g_main_context_ref_thread_default (); g_task_set_task_data (task, data, update_data_free); g_task_set_check_cancellable (task, FALSE); gs_app_set_allow_cancel (app, TRUE); diff --git a/integrations/gnome-software/system-bus.h b/integrations/gnome-software/system-bus.h index 0285c6d..bdb831a 100644 --- a/integrations/gnome-software/system-bus.h +++ b/integrations/gnome-software/system-bus.h @@ -28,8 +28,12 @@ static GVariant *bus_call(GDBusConnection *bus, const gchar *path, const gchar * interactive ? G_DBUS_CALL_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION : G_DBUS_CALL_FLAGS_NONE, 120000, NULL, error); } -static GVariant *bus_operation(GDBusConnection *bus, const gchar *method, const gchar *target, - gboolean interactive, GCancellable *cancellable, GError **error) +/* Called on the polling thread; implementations must marshal to their own + * main context before touching GsApp. */ +typedef void (*BusProgressFunc)(guint percent, gpointer user_data); +static GVariant *bus_operation_full(GDBusConnection *bus, const gchar *method, const gchar *target, + gboolean interactive, GCancellable *cancellable, + BusProgressFunc progress, gpointer progress_data, GError **error) { g_autoptr(GVariant) admitted = bus_call(bus, ARCH_PATH, ARCH_MANAGER, method, target ? g_variant_new("(s@a{sv})", target, bus_options(interactive)) @@ -54,6 +58,11 @@ static GVariant *bus_operation(GDBusConnection *bus, const gchar *method, const } failures = 0; g_autoptr(GVariant) fields = g_variant_get_child_value(snapshot, 0); + if (progress) { + g_autoptr(GVariant) record = g_variant_lookup_value(fields, "Progress", G_VARIANT_TYPE_VARDICT); + guint percent = 0; + if (record && g_variant_lookup(record, "percent", "u", &percent)) progress(percent, progress_data); + } const gchar *state = bus_string(fields, "State"); if (g_str_equal(state, "succeeded")) return g_variant_lookup_value(fields, "Result", G_VARIANT_TYPE_VARDICT); @@ -80,6 +89,11 @@ static GVariant *bus_operation(GDBusConnection *bus, const gchar *method, const g_usleep(250000); } } +static GVariant *bus_operation(GDBusConnection *bus, const gchar *method, const gchar *target, + gboolean interactive, GCancellable *cancellable, GError **error) +{ + return bus_operation_full(bus, method, target, interactive, cancellable, NULL, NULL, error); +} static JsonObject *bus_status(GError **error) { g_autoptr(GDBusConnection) bus = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, error); @@ -91,12 +105,10 @@ static JsonObject *bus_status(GError **error) g_autoptr(GVariant) booted = g_variant_lookup_value(status, "booted", G_VARIANT_TYPE_VARDICT); g_autoptr(GVariant) update = g_variant_lookup_value(status, "update", G_VARIANT_TYPE_VARDICT); JsonObject *record = json_object_new(); - gboolean reconciling = FALSE; - g_variant_lookup(status, "reconciling", "b", &reconciling); - if (reconciling) { - json_object_set_string_member(record, "state", "error"); - json_object_set_string_member(record, "error", "System state is being reconciled; retry when ready."); - } else if (*bus_string(pending, "deployment_id")) { + /* A host writer briefly holds the observation lock while it mutates the + * deployment; the journal-derived update state still describes the active + * transaction, so this window is not an update error. */ + if (*bus_string(pending, "deployment_id")) { json_object_set_string_member(record, "state", "pending"); json_object_set_string_member(record, "pending_id", bus_string(pending, "deployment_id")); json_object_set_string_member(record, "pending_checksum", bus_string(pending, "checksum")); diff --git a/integrations/icons/archipelago-symbolic.svg b/integrations/icons/archipelago-symbolic.svg new file mode 100644 index 0000000..50b4013 --- /dev/null +++ b/integrations/icons/archipelago-symbolic.svg @@ -0,0 +1,4 @@ + + + + diff --git a/integrations/icons/archipelago.svg b/integrations/icons/archipelago.svg new file mode 100644 index 0000000..73fd586 --- /dev/null +++ b/integrations/icons/archipelago.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/src/service/events.rs b/src/service/events.rs index 3df9995..6b961ad 100644 --- a/src/service/events.rs +++ b/src/service/events.rs @@ -5,8 +5,8 @@ use serde_json::{json, Value}; use std::sync::{Arc, Mutex}; /// Coarse, monotonic progress percentage derived from the operation phase. -/// Discover renders this as its transaction progress bar; the daemon does not -/// currently report a byte-accurate percentage, so the phase is the durable cue. +/// Transfers refine this value inside their phase band through `progress()`; +/// the phase remains the durable cue when a command prints no terminal progress. fn phase_percent(phase: Phase) -> u64 { match phase { Phase::Admission => 2, @@ -51,12 +51,38 @@ impl Events for OperationEvents { journal.update(&self.id, |record| { record.phase = phase; record.can_cancel = can_cancel; - record.progress = json!({"message": message, "unit": "steps", "completed": 0, "percent": phase_percent(phase)}); + // A finer-grained transfer report may already have advanced past the + // new phase floor (for example a Host Extension pull during planning); + // the label is refreshed but the displayed value never rewinds. + let floor = record.progress.get("percent").and_then(Value::as_u64).unwrap_or(0).max(phase_percent(phase)); + record.progress = json!({"message": message, "unit": "steps", "completed": 0, "percent": floor}); Ok(()) }).map_err(unavailable)?; Ok(()) } + fn progress(&self, percent: u64, message: &str) -> Result<()> { + let mut journal = self.journal.lock().map_err(unavailable)?; + let current = journal.get(&self.id).ok_or_else(|| unavailable("missing operation"))?; + if current.cancel_requested { return Err(Failure::cancelled()); } + let before = current.progress.get("percent").and_then(Value::as_u64).unwrap_or(0); + // Terminal records must not advance past 99; total completion belongs to + // the terminal transition. No-op reports avoid an unnecessary fsync. + let percent = percent.min(99).max(before); + if percent == before { return Ok(()); } + journal.update(&self.id, |record| { + record.progress = json!({"message": message, "unit": "steps", "completed": 0, "percent": percent}); + Ok(()) + }).map_err(unavailable)?; + Ok(()) + } + + fn percent(&self) -> Result { + let journal = self.journal.lock().map_err(unavailable)?; + let record = journal.get(&self.id).ok_or_else(|| unavailable("missing operation"))?; + Ok(record.progress.get("percent").and_then(Value::as_u64).unwrap_or(0)) + } + fn effect(&self, key: &str, value: Value) -> Result<()> { self.journal.lock().map_err(unavailable)?.update(&self.id, |record| { record.effects.as_object_mut().ok_or("invalid effects")?.insert(key.into(), value); diff --git a/src/service/worker.rs b/src/service/worker.rs index 4fe560e..53cf2ce 100644 --- a/src/service/worker.rs +++ b/src/service/worker.rs @@ -2,9 +2,12 @@ //! Each command belongs to a recorded transient unit bound to archipelagod. use archipelago_contracts::system_bus::{ErrorCode, Phase}; use serde_json::Value; -use std::{io::Read, process::{Command, Stdio}, sync::{Arc, mpsc, atomic::{AtomicU64, Ordering}}, time::{Duration, Instant}}; +use std::{io::Read, process::{Command, Stdio}, sync::{Arc, Mutex, mpsc, atomic::{AtomicU64, Ordering}}, time::{Duration, Instant}}; const MAX_OUTPUT: usize = 32 * 1024 * 1024; +/// Parse console output into an absolute percentage and a short message. +/// Implementations scan a rolling window and return the newest record. +pub type ProgressParser = Box Option<(u64, String)> + Send>; #[derive(Clone, Debug)] pub struct Failure { @@ -23,6 +26,12 @@ pub trait Events: Send + Sync { /// Atomically check requested cancellation before changing CanCancel/phase. /// Persist the phase before any corresponding external side effect. fn checkpoint(&self, phase: Phase, can_cancel: bool, message: &str) -> Result<()>; + /// Advance the durable percentage without changing the phase. Values never + /// decrease, so a coarse phase checkpoint and a byte-scaled report can + /// interleave safely. + fn progress(&self, percent: u64, message: &str) -> Result<()>; + /// Current durable percentage; zero until the first checkpoint. + fn percent(&self) -> Result; fn effect(&self, key: &str, value: Value) -> Result<()>; fn worker_unit(&self, name: &str) -> Result<()>; fn cancelled(&self) -> bool; @@ -57,18 +66,71 @@ pub fn stop_owned(operation: &str, unit: &str) -> Result<()> { Ok(()) } -fn collect(mut pipe: impl Read + Send + 'static) -> mpsc::Receiver>> { +/// Serialized console observer shared by both pipe readers. Parsers deduplicate +/// on the last reported percentage so a redrawn terminal line is not persisted +/// twice; the journal update itself also clamps to a monotonic value. +struct ProgressChannel { + events: Arc, + parser: Mutex, + reported: Mutex>, +} + +impl ProgressChannel { + fn observe(&self, window: &[u8]) { + let parsed = { + let Ok(mut parser) = self.parser.lock() else { return }; + parser(&String::from_utf8_lossy(window)) + }; + let Some((percent, message)) = parsed else { return }; + let Ok(mut reported) = self.reported.lock() else { return }; + if *reported == Some(percent) { return; } + if self.events.progress(percent, &message).is_ok() { *reported = Some(percent); } + } +} + +/// Strip terminal controls and flatten carriage returns. libostree redraws its +/// progress line in place, so records are separated by `\r`, `\n` or cursor +/// save/restore sequences rather than by portable newlines. +fn console_bytes(input: &[u8]) -> Vec { + let mut text = Vec::with_capacity(input.len()); + let mut index = 0; + while index < input.len() { + let byte = input[index]; + if byte == 0x1b { + index += 1; + if index < input.len() && input[index] == b'[' { + index += 1; + while index < input.len() && !(0x40..=0x7e).contains(&input[index]) { index += 1; } + index = (index + 1).min(input.len()); + } else if index < input.len() { index += 1; } + } else { + if byte == b'\r' || byte == b'\n' { text.push(b' '); } + else if byte == b'\t' || (0x20..0x7f).contains(&byte) { text.push(byte); } + index += 1; + } + } + text +} + +fn collect(mut pipe: impl Read + Send + 'static, progress: Option>) + -> mpsc::Receiver>> { let (tx, rx) = mpsc::sync_channel(1); std::thread::spawn(move || { let result = (|| { let mut output = Vec::new(); let mut chunk = [0_u8; 8192]; + let mut window = Vec::new(); let mut too_large = false; loop { let n = pipe.read(&mut chunk)?; if n == 0 { break; } if output.len() + n <= MAX_OUTPUT { output.extend_from_slice(&chunk[..n]); } else { too_large = true; } // keep draining to avoid pipe deadlock + if let Some(progress) = &progress { + window.extend_from_slice(&console_bytes(&chunk[..n])); + if window.len() > 8192 { window.drain(..window.len() - 4096); } + progress.observe(&window); + } } if too_large { Err(std::io::Error::other("command output exceeds limit")) } else { Ok(output) } })(); @@ -77,9 +139,71 @@ fn collect(mut pipe: impl Read + Send + 'static) -> mpsc::Receiver String { + format!("'{}'", argument.replace('\'', "'\\''")) +} + +/// Map the newest console record printed by `ostree pull` onto an absolute +/// percentage band. libostree only prints transfer progress with a terminal, so +/// callers of `command_progress` allocate a PTY for the duration of the command. +/// Unknown formats leave the durable phase percentage untouched. +pub(crate) fn console_progress(text: &str, band: (u64, u64), label: &str) -> Option<(u64, String)> { + let scaled = |fraction: f64| -> u64 { + let span = band.1.saturating_sub(band.0) as f64; + (band.0 as f64 + span * fraction.clamp(0.0, 1.0)).round() as u64 + }; + let digits = |value: &str| -> Option { + let value: String = value.trim_start().chars().take_while(char::is_ascii_digit).collect(); + if value.is_empty() { None } else { value.parse().ok() } + }; + let pair = |value: &str| -> Option<(u32, Option)> { + let token = value.trim_start().split_whitespace().next()?; + let (done, total) = token.split_once('/')?; + Some((done.parse().ok()?, total.parse().ok())) + }; + enum Record { Receiving(u32), Parts(u32, Option), Writing(u32), Complete } + let mut newest: Option<(usize, Record)> = None; + let mut consider = |needle: &str, make: &dyn Fn(&str) -> Option| { + if let Some(at) = text.rfind(needle) { + if newest.as_ref().map_or(true, |(position, _)| at > *position) { + if let Some(record) = make(&text[at + needle.len()..]) { newest = Some((at, record)); } + } + } + }; + consider("Receiving objects: ", &|rest| digits(rest).map(Record::Receiving)); + consider("Receiving delta parts: ", &|rest| pair(rest).map(|(done, total)| Record::Parts(done, total))); + consider("Receiving metadata objects: ", &|rest| pair(rest).map(|(done, total)| Record::Parts(done, total))); + consider("Writing objects: ", &|rest| digits(rest).map(Record::Writing)); + consider(" objects fetched", &|_| Some(Record::Complete)); + consider(" transferred in ", &|_| Some(Record::Complete)); + match newest?.1 { + Record::Receiving(percent) => Some((scaled(percent as f64 / 100.0), format!("{label} ({percent}%)"))), + Record::Parts(done, Some(total)) if total > 0 => { + let percent = (done.saturating_mul(100) / total).min(100); + Some((scaled(done as f64 / total as f64), format!("{label} ({percent}%)"))) + } + Record::Parts(done, _) => Some((scaled(0.05), format!("{label} ({done} objects)"))), + Record::Writing(objects) => Some((scaled(0.99), format!("{label} (writing {objects} objects)"))), + Record::Complete => Some((band.1, format!("{label} (complete)"))), + } +} + impl Worker { pub fn new(events: Arc) -> Self { Self { events, sequence: AtomicU64::new(0) } } pub fn command(&self, program: &str, args: &[&str], deadline: Duration, cancellable: bool) -> Result { + self.run(program, args, deadline, cancellable, None) + } + /// Run a command under a pseudo-terminal so that libostree prints its + /// in-place transfer progress, and translate the newest record into the + /// operation's durable percentage. + pub fn command_progress(&self, program: &str, args: &[&str], deadline: Duration, + cancellable: bool, parser: ProgressParser) -> Result { + let channel = Arc::new(ProgressChannel { events: self.events.clone(), parser: Mutex::new(parser), + reported: Mutex::new(None) }); + self.run(program, args, deadline, cancellable, Some(channel)) + } + fn run(&self, program: &str, args: &[&str], deadline: Duration, cancellable: bool, + progress: Option>) -> Result { if cancellable && self.events.cancelled() { return Err(Failure::cancelled()); } let sequence = self.sequence.fetch_add(1, Ordering::Relaxed); let unit = format!("archipelago-op-{}-{sequence}.service", self.events.id()); @@ -90,14 +214,22 @@ impl Worker { .args(["--property=KillMode=control-group", "--property=BindsTo=archipelagod.service", "--property=After=archipelagod.service", "--property=TimeoutStopSec=10s", "--property=UMask=0077", "--setenv=LC_ALL=C", "--setenv=TZ=UTC", - "--setenv=PATH=/usr/sbin:/usr/bin:/sbin:/bin"]) - .arg(format!("--property=RuntimeMaxSec={}s", deadline.as_secs().max(1))) - .arg("--").arg(program).args(args) + "--setenv=PATH=/usr/sbin:/usr/bin:/sbin:/bin"]); + if progress.is_some() { command.arg("--setenv=TERM=xterm"); } + command.arg(format!("--property=RuntimeMaxSec={}s", deadline.as_secs().max(1))); + if progress.is_some() { + let mut line = shell_quote(program); + for argument in args { line.push(' '); line.push_str(&shell_quote(argument)); } + command.args(["--", "/usr/bin/script", "-q", "-e", "-c"]).arg(line).arg("/dev/null"); + } else { + command.arg("--").arg(program).args(args); + } + command .env_clear().env("PATH", "/usr/sbin:/usr/bin:/sbin:/bin").env("LC_ALL", "C") .stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); let mut child = command.spawn().map_err(|_| Failure::new(ErrorCode::Unavailable, "Could not start owned engine worker"))?; - let stdout = collect(child.stdout.take().expect("piped stdout")); - let stderr = collect(child.stderr.take().expect("piped stderr")); + let stdout = collect(child.stdout.take().expect("piped stdout"), progress.clone()); + let stderr = collect(child.stderr.take().expect("piped stderr"), progress); let started = Instant::now(); let mut stopped = None; let mut stopped_at = None; @@ -151,7 +283,8 @@ impl Worker { } if let Some(failure) = stopped { return Err(failure); } if !status.success() { - let diagnostic = String::from_utf8_lossy(&err).to_lowercase(); + // A PTY merges diagnostics onto stdout; classify both streams. + let diagnostic = format!("{}\n{}", String::from_utf8_lossy(&out), String::from_utf8_lossy(&err)).to_lowercase(); let code = if diagnostic.contains("no space left on device") { ErrorCode::NoSpace } else if diagnostic.contains("signature") || diagnostic.contains("gpg") { ErrorCode::TrustFailed } else if diagnostic.contains("timed out") { ErrorCode::Timeout } @@ -162,3 +295,57 @@ impl Worker { String::from_utf8(out).map_err(|_| Failure::new(ErrorCode::ExecutionFailed, "Engine returned non-UTF8 metadata")) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn receiving_progress_is_scaled_into_the_phase_band() { + let band = (40, 54); + assert_eq!(console_progress("Receiving objects: 42% (42/100) 1.2 MB/s 5s remaining", band, "Download"), + Some((46, "Download (42%)".into()))); + assert_eq!(console_progress("Receiving objects: 100% (10/10) 2 MB/s", band, "Download"), + Some((54, "Download (100%)".into()))); + } + + #[test] + fn static_delta_parts_report_their_ratio() { + let band = (40, 54); + assert_eq!(console_progress("Receiving delta parts: 3/10 1.2/4.5 MB 300 kB/s 11s remaining", band, "Download"), + Some((44, "Download (30%)".into()))); + assert_eq!(console_progress("Receiving metadata objects: 7/(estimating) 1 kB/s", band, "Download"), + Some((41, "Download (7 objects)".into()))); + } + + #[test] + fn the_newest_record_wins_and_completion_saturates_the_band() { + let band = (40, 54); + let text = "Receiving objects: 60% (60/100) 1 MB/s Writing objects: 12"; + assert_eq!(console_progress(text, band, "Download"), Some((54, "Download (writing 12 objects)".into()))); + let done = "Receiving objects: 100% (10/10) 4 metadata, 1 content objects fetched; 117223 KiB transferred in 11 seconds"; + assert_eq!(console_progress(done, band, "Download"), Some((54, "Download (complete)".into()))); + } + + #[test] + fn unrecognized_output_keeps_the_phase_percentage() { + assert_eq!(console_progress("error: Invalid refspec", (40, 54), "Download"), None); + assert_eq!(console_progress("", (40, 54), "Download"), None); + } + + #[test] + fn terminal_controls_and_carriage_returns_are_flattened() { + let data = b"\x1b7Receiving objects: 12% (1/8)\r\x1b8\x1b[KWriting objects: 1"; + let text = String::from_utf8(console_bytes(data)).unwrap(); + assert!(!text.contains('\u{1b}')); + assert!(text.contains("Receiving objects: 12%")); + assert!(text.contains("Writing objects: 1")); + assert_eq!(console_progress(&text, (40, 54), "Download"), Some((54, "Download (writing 1 objects)".into()))); + } + + #[test] + fn shell_arguments_are_quoted_for_the_pty_shell() { + assert_eq!(shell_quote("--depth=0"), "'--depth=0'"); + assert_eq!(shell_quote("a'b"), "'a'\\''b'"); + } +} diff --git a/src/updates/managed.rs b/src/updates/managed.rs index a8e71fb..6ae941c 100644 --- a/src/updates/managed.rs +++ b/src/updates/managed.rs @@ -1,6 +1,7 @@ //! Typed service execution of the shared signed-image update policy. use super::{binding, digest, lock, purpose_variant, summary_commit, variant, REMOTE, STATE}; -use crate::service::{journal, plans::{Context, Intent, Plan}, storage, worker::{Failure, Result, Worker}}; +use crate::service::{journal, plans::{Context, Intent, Plan}, storage, + worker::{console_progress, Failure, Result, Worker}}; use archipelago_contracts::system_bus::{ErrorCode, Phase}; use serde_json::{json, Value}; use std::{fs, path::Path, time::Duration}; @@ -16,6 +17,16 @@ fn cmd(worker: &Worker, args: &[&str], network: bool, offline: bool) -> Result Result { cmd(worker, &[&[format!("--repo={STATE}/repo").as_str()], args].concat(), network, offline) } +/// Run a fetching OSTree command and map its terminal transfer progress onto +/// the next `span` percentage points. libostree only draws progress for a +/// terminal, so the worker allocates a PTY around the command. +fn fetching(worker: &Worker, args: &[&str], span: u64, message: &str, network: bool) -> Result { + let start = worker.events.percent()?; + let band = (start, start.saturating_add(span).min(99)); + let label = message.to_owned(); + worker.command_progress("/usr/bin/ostree", args, Duration::from_secs(if network { 3600 } else { 600 }), + true, Box::new(move |text: &str| console_progress(text, band, &label))) +} pub(crate) fn status(worker: &Worker) -> Result { serde_json::from_str(&cmd(worker, &["admin", "status", "--json"], false, true)?).map_err(|_| fail("Invalid OSTree deployment status")) } @@ -53,7 +64,8 @@ pub(crate) fn checkout_layer(worker: &Worker, commit: &str, destination: &Path, let binding = binding().map_err(|_| Failure::new(ErrorCode::NoTrack, "Configured layer trust unavailable"))?; worker.events.checkpoint(Phase::Metadata, true, "Verifying the selected layer against configured trust")?; configure(worker, &binding)?; - if !offline { repo(worker, &["pull", "--depth=0", REMOTE, commit], true, false)?; } + if !offline { fetching(worker, &[&format!("--repo={STATE}/repo"), "pull", "--depth=0", REMOTE, commit], + 10, "Downloading the checked layer", true)?; } // Reverify cached commits too: presence in a local repository is not proof // that the current configured key authorized this layer. let verification = repo(worker, &["show", &format!("--gpg-verify-remote={REMOTE}"), commit], false, true)?; @@ -85,8 +97,8 @@ pub(crate) fn retain_clean_base(worker: &Worker, image: &str) -> Result<()> { return Err(Failure::new(ErrorCode::TrustFailed, "Clean base signature unavailable")); } worker.events.effect("retained_clean_base", json!(image))?; - worker.command("/usr/bin/ostree", &["--repo=/sysroot/ostree/repo", "pull-local", - &format!("{STATE}/repo"), image], Duration::from_secs(600), true)?; + fetching(worker, &["--repo=/sysroot/ostree/repo", "pull-local", &format!("{STATE}/repo"), image], + 8, "Importing the verified base into the sysroot", false)?; cmd(worker, &["--repo=/sysroot/ostree/repo", "refs", "--force", &format!("--create=service/bases/{image}"), image], false, true)?; Ok(()) @@ -280,7 +292,9 @@ pub(crate) fn prepare(worker: &Worker, target: &str, offline: bool, details: boo let receipt: Value = storage::json(&Path::new(SERVICE).join("downloads").join(format!("{target}.json")))?; if receipt["trust"] != context.trust { return Err(Failure::new(ErrorCode::PlanStale,"Cached target trust changed")); } } else { - repo(worker,&["pull","--depth=0",REMOTE,target],true,false)?; + worker.events.checkpoint(Phase::Downloading, true, "Downloading the verified image for Host Extension reapplication")?; + fetching(worker, &[&format!("--repo={STATE}/repo"), "pull", "--depth=0", REMOTE, target], + 15, "Downloading the verified image", true)?; storage::directory(&Path::new(SERVICE).join("downloads"))?; storage::atomic(&Path::new(SERVICE).join("downloads").join(format!("{target}.json")),&json!({"version":1,"trust":context.trust}))?; } @@ -315,7 +329,8 @@ pub(crate) fn execute(worker: &Worker, plan: &Plan, download_only: bool, offline let receipt: Value = storage::json(&Path::new(SERVICE).join("downloads").join(format!("{}.json", plan.target)))?; if receipt["trust"] != plan.context.trust { return Err(Failure::new(ErrorCode::PlanStale, "Download trust binding changed")); } } else { - repo(worker, &["pull", "--depth=0", REMOTE, &plan.target], true, false)?; + fetching(worker, &[&format!("--repo={STATE}/repo"), "pull", "--depth=0", REMOTE, &plan.target], + 15, "Downloading the verified image", true)?; } repo(worker, &["show", &format!("--gpg-verify-remote={REMOTE}"), &plan.target], false, true)?; let listing = repo(worker, &["ls", &plan.target, "/usr/lib/archipelago"], false, true)?; @@ -328,13 +343,15 @@ pub(crate) fn execute(worker: &Worker, plan: &Plan, download_only: bool, offline storage::atomic(&Path::new(SERVICE).join("downloads").join(format!("{}.json", plan.target)), &json!({"version":1,"trust":plan.context.trust}))?; if status(worker)? != initial { return Err(Failure::new(ErrorCode::PlanStale, "Deployment changed while downloading")); } if plan.inputs.get("requests").is_some() { - cmd(worker,&["--repo=/sysroot/ostree/repo","pull-local",&format!("{STATE}/repo"),&plan.target],false,true)?; + fetching(worker, &["--repo=/sysroot/ostree/repo", "pull-local", &format!("{STATE}/repo"), &plan.target], + 5, "Importing the verified image into the sysroot", false)?; return crate::service::packages::execute_locked(worker,plan,download_only,offline); } if download_only { return Ok(json!({"outcome":"downloaded","changed":false})); } if plan.target == plan.context.managed_base { return Ok(json!({"outcome":"no-change","changed":false})); } worker.events.checkpoint(Phase::Validating, true, "Importing verified image into sysroot")?; - cmd(worker, &["--repo=/sysroot/ostree/repo", "pull-local", &format!("{STATE}/repo"), &plan.target], false, true)?; + fetching(worker, &["--repo=/sysroot/ostree/repo", "pull-local", &format!("{STATE}/repo"), &plan.target], + 8, "Importing the verified image into the sysroot", false)?; if status(worker)? != initial { return Err(Failure::new(ErrorCode::PlanStale, "Deployment changed before staging")); } worker.events.checkpoint(Phase::Staging, false, "Staging deployment for the next boot")?; let (args, arguments) = crate::service::kargs::deployment_args(&plan.target)?;