Fix desktop update lifecycle and retain readable transaction progress
This commit is contained in:
parent
16f7a67494
commit
90e69c25b5
10 changed files with 258 additions and 26 deletions
|
|
@ -18,6 +18,7 @@ cp "$root/usr/lib/archipelago/packages.txt" "$generation/base-packages"
|
|||
cp "$generation/requested" "$generation/transaction-targets"
|
||||
(cd "$root/usr/lib/archipelago/package-db/sync"; sha256sum *.db) > "$generation/sync.sha256"
|
||||
# The immutable base supplies sync DBs, repository order and transport URLs. No -y.
|
||||
printf 'ARCHIPELAGO_PHASE\tpackages\n'
|
||||
systemd-nspawn --settings=no --register=no --resolv-conf=replace-host \
|
||||
-D "$root" --bind="$generation/inputs:/inputs" --bind="$generation/transaction-targets:/requested" \
|
||||
/bin/bash -euo pipefail -c '
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@
|
|||
#include <QJsonDocument>
|
||||
#include <QProcess>
|
||||
#include <QRegularExpression>
|
||||
#include <QSharedPointer>
|
||||
#include <QTimer>
|
||||
|
||||
class OSResource final : public AbstractResource
|
||||
|
|
@ -40,6 +41,8 @@ public:
|
|||
QString longDescription() override {
|
||||
QString text = comment().toHtmlEscaped();
|
||||
if (record["state"] == "pending") text += tr("<p>A deployment is staged. Restart when ready.</p>");
|
||||
if (record["state"] == "applying") text += tr("<p>The operating system update is being prepared. Detailed progress is recorded in the system log.</p>");
|
||||
if (record["state"] == "downloading") text += tr("<p>The verified operating system image is being downloaded.</p>");
|
||||
if (record["state"] == "error") text += "<p>" + record["error"].toString().toHtmlEscaped() + "</p>";
|
||||
text += "<pre>" + record["support_description"].toString().toHtmlEscaped() + "</pre>";
|
||||
text += "<ul>";
|
||||
|
|
@ -58,6 +61,7 @@ public:
|
|||
QJsonObject next;
|
||||
if (file.open(QIODevice::ReadOnly)) next = QJsonDocument::fromJson(file.readAll()).object();
|
||||
if (next["version"].toInt() != 1) next = {{"state", "error"}, {"error", tr("Update status unavailable; refresh to retrieve a verified plan.")}};
|
||||
if (record == next) return;
|
||||
record = next;
|
||||
Q_EMIT stateChanged();
|
||||
Q_EMIT versionsChanged();
|
||||
|
|
@ -114,6 +118,16 @@ public:
|
|||
updater->setNeedsReboot(resource->record["state"] == "pending");
|
||||
Q_EMIT updatesCountChanged();
|
||||
Q_EMIT resourcesChanged(resource, {"state", "installedVersion", "availableVersion", "longDescription"});
|
||||
const QString state = resource->record["state"].toString();
|
||||
QSharedPointer<InlineMessage> message;
|
||||
if (state == "error") {
|
||||
message.reset(new InlineMessage(InlineMessage::Error, QStringLiteral("dialog-error"), resource->record["error"].toString()));
|
||||
} else if (state == "pending") {
|
||||
message.reset(new InlineMessage(InlineMessage::Information, QStringLiteral("system-reboot"), tr("Archipelago is ready. Restart when you choose to activate the new deployment.")));
|
||||
} else if (state == "applying" || state == "downloading") {
|
||||
message.reset(new InlineMessage(InlineMessage::Information, QStringLiteral("system-software-update"), tr("An Archipelago transaction is running. Please wait for its result.")));
|
||||
}
|
||||
Q_EMIT inlineMessageChanged(message);
|
||||
});
|
||||
resource->reload();
|
||||
auto timer = new QTimer(this);
|
||||
|
|
|
|||
|
|
@ -36,16 +36,23 @@ source/binary checksums are retained with the run.
|
|||
- The native Software plugin exposes one whole-image operation and related package
|
||||
changes. It conflicts with the PackageKit plugin; stock ALPM remains disabled.
|
||||
|
||||
The daily pipeline compiles the module with `pkg-config gnome-software` against
|
||||
The release pipeline compiles the module with `pkg-config gnome-software` against
|
||||
the Arch 51.1 headers; an upstream source-tree build can instead include its
|
||||
`meson.build` under `plugins/`. Keep existing Flatpak/fwupd plugins enabled.
|
||||
Deliver changes through a new image rather than replacing the running desktop module.
|
||||
|
||||
Remaining acceptance: validate query/schema handling and authorization; 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.
|
||||
The follow-up source fix handles Software's `NO_APPLY` download request through
|
||||
`update download --plan`, then stages on apply. Informational related package
|
||||
objects have zero independent download bytes: the parent owns the image download.
|
||||
Cached app objects retain transaction state; staging disables cancellation and
|
||||
reports errors. A pending deployment offers an explicit restart action whose helper
|
||||
revalidates its exact checksum; GNOME owns the restart itself.
|
||||
|
||||
Desktop cache writes are serialized with refresh and transaction requests. Detailed
|
||||
operation output is retained in the CLI log and failures include journal context.
|
||||
The pipeline adapter includes a fake-helper download/apply/failure regression check.
|
||||
These newest changes still need compilation and real graphical update/restart
|
||||
acceptance; the source fix and fake helper do not demonstrate that acceptance.
|
||||
|
||||
Study references (51.1): GNOME Software `plugins/rpm-ostree` (transaction and related
|
||||
package principles), `plugins/dummy` (plugin API signatures). No RPM transaction
|
||||
|
|
|
|||
|
|
@ -8,10 +8,22 @@
|
|||
|
||||
#define STATUS_FILE "/var/lib/archipelago/software/status.json"
|
||||
#define HELPER "/usr/lib/archipelago/software-helper"
|
||||
#ifndef ARCHIPELAGO_PKEXEC
|
||||
#define ARCHIPELAGO_PKEXEC "/usr/bin/pkexec"
|
||||
#endif
|
||||
typedef struct { GsPlugin parent; GFileMonitor *monitor; } GsPluginArchipelago;
|
||||
typedef struct { GsPluginClass parent_class; } GsPluginArchipelagoClass;
|
||||
G_DEFINE_TYPE (GsPluginArchipelago, gs_plugin_archipelago, GS_TYPE_PLUGIN)
|
||||
|
||||
typedef struct { gchar *id; gboolean download; gboolean pending; GsApp *app; } UpdateData;
|
||||
static void update_data_free (gpointer pointer)
|
||||
{
|
||||
UpdateData *data = pointer;
|
||||
g_free (data->id);
|
||||
g_clear_object (&data->app);
|
||||
g_free (data);
|
||||
}
|
||||
|
||||
static gboolean
|
||||
is_ru (void)
|
||||
{
|
||||
|
|
@ -72,12 +84,22 @@ list_apps_async (GsPlugin *plugin, GsAppQuery *query, GsPluginListAppsFlags flag
|
|||
json_object_get_string_member_with_default (record, "error", "Update check failed"));
|
||||
return;
|
||||
}
|
||||
if (g_str_equal (state, "available")) {
|
||||
if (g_str_equal (state, "available") || g_str_equal (state, "downloading") || g_str_equal (state, "applying")) {
|
||||
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(GsApp) app = gs_plugin_cache_lookup (plugin, id);
|
||||
if (app) {
|
||||
gs_app_set_state (app, g_str_equal (state, "applying") ? GS_APP_STATE_INSTALLING :
|
||||
g_str_equal (state, "downloading") ? GS_APP_STATE_DOWNLOADING : GS_APP_STATE_UPDATABLE_LIVE);
|
||||
if (json_object_get_boolean_member_with_default (record, "downloaded", FALSE))
|
||||
gs_app_set_size_download (app, GS_SIZE_TYPE_VALID, 0);
|
||||
gs_app_list_add (list, app);
|
||||
g_task_return_pointer (task, g_steal_pointer (&list), g_object_unref);
|
||||
return;
|
||||
}
|
||||
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);
|
||||
|
|
@ -93,7 +115,9 @@ list_apps_async (GsPlugin *plugin, GsAppQuery *query, GsPluginListAppsFlags flag
|
|||
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);
|
||||
gs_app_set_state (app, g_str_equal (state, "applying") ? GS_APP_STATE_INSTALLING :
|
||||
g_str_equal (state, "downloading") ? GS_APP_STATE_DOWNLOADING : GS_APP_STATE_UPDATABLE_LIVE);
|
||||
gs_app_set_size_download (app, json_object_get_boolean_member_with_default (record, "downloaded", FALSE) ? GS_SIZE_TYPE_VALID : GS_SIZE_TYPE_UNKNOWN, 0);
|
||||
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);
|
||||
|
|
@ -108,6 +132,8 @@ list_apps_async (GsPlugin *plugin, GsAppQuery *query, GsPluginListAppsFlags flag
|
|||
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);
|
||||
/* Informational package diff; its bytes belong to the parent OSTree image. */
|
||||
gs_app_set_size_download (package, GS_SIZE_TYPE_VALID, 0);
|
||||
gs_app_set_version (package, old);
|
||||
gs_app_set_update_version (package, new ? new : (is_ru () ? "будет удалён" : "will be removed"));
|
||||
gs_app_add_related (app, package);
|
||||
|
|
@ -116,8 +142,36 @@ list_apps_async (GsPlugin *plugin, GsAppQuery *query, GsPluginListAppsFlags flag
|
|||
new ? new : (is_ru () ? "будет удалён" : "will be removed"));
|
||||
}
|
||||
gs_app_set_update_details_text (app, details->str);
|
||||
gs_plugin_cache_add (plugin, id, app);
|
||||
gs_app_list_add (list, app);
|
||||
} else if (!g_str_equal (state, "current") && !g_str_equal (state, "pending")) {
|
||||
} else if (g_str_equal (state, "pending")) {
|
||||
JsonObject *deployments = json_object_get_object_member (record, "deployments");
|
||||
JsonArray *entries = deployments ? json_object_get_array_member (deployments, "deployments") : NULL;
|
||||
for (guint i = 0; entries && i < json_array_get_length (entries); i++) {
|
||||
JsonObject *entry = json_array_get_object_element (entries, i);
|
||||
if (g_strcmp0 (json_object_get_string_member_with_default (entry, "stateroot", ""), "archipelago") != 0 ||
|
||||
!(json_object_get_boolean_member_with_default (entry, "pending", FALSE) ||
|
||||
json_object_get_boolean_member_with_default (entry, "staged", FALSE))) continue;
|
||||
const gchar *checksum = json_object_get_string_member (entry, "checksum");
|
||||
g_autoptr(GsApp) app = gs_app_new ("org.archipelago.System");
|
||||
g_autoptr(GIcon) icon = g_themed_icon_new ("distributor-logo");
|
||||
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 () ? "Установлено — готово к перезагрузке" : "Installed — ready to restart");
|
||||
gs_app_set_update_version (app, checksum);
|
||||
gs_app_set_metadata (app, "Archipelago::Pending", checksum);
|
||||
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);
|
||||
gs_app_set_size_download (app, GS_SIZE_TYPE_VALID, 0);
|
||||
gs_app_set_state (app, GS_APP_STATE_UPDATABLE);
|
||||
gs_app_list_add (list, app);
|
||||
break;
|
||||
}
|
||||
} else if (!g_str_equal (state, "current")) {
|
||||
g_task_return_new_error (task, GS_PLUGIN_ERROR, GS_PLUGIN_ERROR_FAILED, "Invalid Archipelago update state");
|
||||
return;
|
||||
}
|
||||
|
|
@ -130,12 +184,14 @@ static GsAppList *list_apps_finish (GsPlugin *plugin, GAsyncResult *result, GErr
|
|||
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 };
|
||||
UpdateData *data = task_data;
|
||||
const gchar *args[] = { ARCHIPELAGO_PKEXEC, HELPER,
|
||||
data ? (data->pending ? "confirm-pending" : data->download ? "download" : "apply") : "refresh",
|
||||
data ? data->id : NULL, 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 (!child || !g_subprocess_communicate_utf8 (child, NULL, data ? 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)) {
|
||||
|
|
@ -160,6 +216,21 @@ refresh_async (GsPlugin *plugin, guint64 age, GsPluginRefreshMetadataFlags flags
|
|||
static gboolean boolean_finish (GsPlugin *plugin, GAsyncResult *result, GError **error)
|
||||
{ return g_task_propagate_boolean (G_TASK (result), error); }
|
||||
|
||||
static gboolean update_finish (GsPlugin *plugin, GAsyncResult *result, GError **error)
|
||||
{
|
||||
UpdateData *data = g_task_get_task_data (G_TASK (result));
|
||||
gboolean success = g_task_propagate_boolean (G_TASK (result), error);
|
||||
if (data) {
|
||||
gs_app_set_progress (data->app, success ? 100 : 0);
|
||||
if (success) gs_app_set_size_download (data->app, GS_SIZE_TYPE_VALID, 0);
|
||||
gs_app_set_state (data->app, success && !data->download ? GS_APP_STATE_INSTALLED :
|
||||
data->pending ? GS_APP_STATE_UPDATABLE : GS_APP_STATE_UPDATABLE_LIVE);
|
||||
gs_app_set_allow_cancel (data->app, TRUE);
|
||||
if (success && !data->download) gs_plugin_updates_changed (plugin);
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
static void
|
||||
update_async (GsPlugin *plugin, GsAppList *apps, GsPluginUpdateAppsFlags flags,
|
||||
GsPluginProgressCallback progress, gpointer progress_data,
|
||||
|
|
@ -168,17 +239,34 @@ update_async (GsPlugin *plugin, GsAppList *apps, GsPluginUpdateAppsFlags flags,
|
|||
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 = NULL;
|
||||
for (guint i = 0; i < gs_app_list_length (apps); i++) {
|
||||
GsApp *candidate = gs_app_list_index (apps, i);
|
||||
if (!gs_app_has_management_plugin (candidate, plugin)) continue;
|
||||
if (app && app != candidate) {
|
||||
g_task_return_new_error (task, GS_PLUGIN_ERROR, GS_PLUGIN_ERROR_FAILED, "Multiple OS plans in one transaction");
|
||||
return;
|
||||
}
|
||||
app = candidate;
|
||||
}
|
||||
GsApp *app = gs_app_list_index (apps, 0);
|
||||
if (!app) { g_task_return_boolean (task, TRUE); return; }
|
||||
const gchar *id = gs_app_get_metadata_item (app, "Archipelago::Plan");
|
||||
const gchar *pending = gs_app_get_metadata_item (app, "Archipelago::Pending");
|
||||
if (pending) id = pending;
|
||||
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);
|
||||
UpdateData *data = g_new0 (UpdateData, 1);
|
||||
data->id = g_strdup (id);
|
||||
data->download = (flags & GS_PLUGIN_UPDATE_APPS_FLAGS_NO_APPLY) != 0;
|
||||
data->pending = pending != NULL;
|
||||
data->app = g_object_ref (app);
|
||||
g_task_set_task_data (task, data, update_data_free);
|
||||
g_task_set_check_cancellable (task, FALSE);
|
||||
gs_app_set_allow_cancel (app, FALSE);
|
||||
gs_app_set_progress (app, GS_APP_PROGRESS_UNKNOWN);
|
||||
gs_app_set_state (app, data->download ? GS_APP_STATE_DOWNLOADING : GS_APP_STATE_INSTALLING);
|
||||
g_task_run_in_thread (task, helper_thread);
|
||||
}
|
||||
|
||||
|
|
@ -191,7 +279,7 @@ static void gs_plugin_archipelago_class_init (GsPluginArchipelagoClass *klass)
|
|||
plugin->refresh_metadata_async = refresh_async;
|
||||
plugin->refresh_metadata_finish = boolean_finish;
|
||||
plugin->update_apps_async = update_async;
|
||||
plugin->update_apps_finish = boolean_finish;
|
||||
plugin->update_apps_finish = update_finish;
|
||||
}
|
||||
|
||||
G_MODULE_EXPORT GType gs_plugin_query_type (void)
|
||||
|
|
|
|||
|
|
@ -1,9 +1,17 @@
|
|||
/* Run only inside a disposable Arch build/test root. */
|
||||
#define ARCHIPELAGO_PKEXEC "/tmp/archipelago-plugin-helper"
|
||||
#include "gs-plugin-archipelago.c"
|
||||
#include <glib/gstdio.h>
|
||||
|
||||
static GMainLoop *loop;
|
||||
static GsAppList *result_list;
|
||||
static GError *result_error;
|
||||
static gboolean update_result;
|
||||
static void updated (GObject *source, GAsyncResult *result, gpointer data)
|
||||
{
|
||||
update_result = update_finish (GS_PLUGIN (source), result, &result_error);
|
||||
g_main_loop_quit (loop);
|
||||
}
|
||||
static void completed (GObject *source, GAsyncResult *result, gpointer data)
|
||||
{
|
||||
result_list = list_apps_finish (GS_PLUGIN (source), result, &result_error);
|
||||
|
|
@ -32,6 +40,32 @@ int main (void)
|
|||
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_assert_true (g_file_set_contents (ARCHIPELAGO_PKEXEC,
|
||||
"#!/bin/sh\nprintf '%s\\n' \"$2\" > /tmp/archipelago-plugin-operation\n"
|
||||
"if test -f /tmp/archipelago-plugin-fail; then echo 'fixture transaction rejected' >&2; exit 1; fi\n", -1, NULL));
|
||||
g_assert_cmpint (g_chmod (ARCHIPELAGO_PKEXEC, 0700), ==, 0);
|
||||
update_async (plugin, result_list, GS_PLUGIN_UPDATE_APPS_FLAGS_NO_APPLY, NULL, NULL, NULL, NULL, NULL, NULL, NULL, updated, NULL);
|
||||
g_main_loop_run (loop);
|
||||
g_assert_no_error (result_error);
|
||||
g_assert_true (update_result);
|
||||
g_assert_cmpint (gs_app_get_state (app), ==, GS_APP_STATE_UPDATABLE_LIVE);
|
||||
g_assert_true (gs_app_is_downloaded (app));
|
||||
g_autofree gchar *operation = NULL;
|
||||
g_assert_true (g_file_get_contents ("/tmp/archipelago-plugin-operation", &operation, NULL, NULL));
|
||||
g_assert_cmpstr (operation, ==, "download\n");
|
||||
g_assert_true (g_file_set_contents ("/tmp/archipelago-plugin-fail", "fail", -1, NULL));
|
||||
update_async (plugin, result_list, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, updated, NULL);
|
||||
g_main_loop_run (loop);
|
||||
g_assert_false (update_result);
|
||||
g_assert_error (result_error, GS_PLUGIN_ERROR, GS_PLUGIN_ERROR_FAILED);
|
||||
g_assert_cmpint (gs_app_get_state (app), ==, GS_APP_STATE_UPDATABLE_LIVE);
|
||||
g_clear_error (&result_error);
|
||||
g_unlink ("/tmp/archipelago-plugin-fail");
|
||||
update_async (plugin, result_list, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, updated, NULL);
|
||||
g_main_loop_run (loop);
|
||||
g_assert_no_error (result_error);
|
||||
g_assert_true (update_result);
|
||||
g_assert_cmpint (gs_app_get_state (app), ==, GS_APP_STATE_INSTALLED);
|
||||
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);
|
||||
|
|
@ -43,6 +77,6 @@ int main (void)
|
|||
g_clear_object (&plugin);
|
||||
g_clear_object (&bus);
|
||||
g_test_dbus_down (test_bus);
|
||||
g_print ("PLUGIN_PACKAGE_DIFF_AND_ERROR_PRESENTATION_PASS\n");
|
||||
g_print ("PLUGIN_DIFF_DOWNLOAD_APPLY_ERROR_STATES_PASS\n");
|
||||
return 0;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -133,6 +133,7 @@ pub fn remove(packages: &[String]) -> Result<(), String> {
|
|||
}
|
||||
|
||||
fn change(packages: &[String], remove: bool) -> Result<(), String> {
|
||||
crate::progress::phase("Resolving requested package changes", "Определение изменений пакетов");
|
||||
let additions = names(packages)?;
|
||||
if output("id", &["-u"])?.trim() != "0" { return Err("Run as root".into()); }
|
||||
if !Path::new("/run/ostree-booted").exists() || !Path::new("/etc/archipelago/provisioned").exists() {
|
||||
|
|
@ -171,6 +172,7 @@ fn change(packages: &[String], remove: bool) -> Result<(), String> {
|
|||
}
|
||||
|
||||
pub(crate) fn reapply(base: &str, requested: &Requests, initial: &Value) -> Result<(), String> {
|
||||
crate::progress::phase("Reapplying Host Extensions", "Повторное применение локальных пакетов");
|
||||
// Caller holds the same host mutation lock as extension add.
|
||||
let id = format!("update-{}-{}", SystemTime::now().duration_since(UNIX_EPOCH)
|
||||
.map_err(|e| e.to_string())?.as_nanos(), std::process::id());
|
||||
|
|
@ -200,6 +202,7 @@ fn compose(generation: &Path, id: &str, base: &str, snapshot: &str,
|
|||
return Ok(());
|
||||
}
|
||||
let root = generation.join("root");
|
||||
crate::progress::phase("Checking out the managed base", "Подготовка дерева базовой системы");
|
||||
let rootstr = root.to_str().ok_or("invalid workspace path")?;
|
||||
run("ostree", &[REPO, "refs", &format!("--create=extensions/bases/{id}"), base])?;
|
||||
run("ostree", &[REPO, "checkout", "--force-copy", base, rootstr])?;
|
||||
|
|
@ -209,6 +212,7 @@ fn compose(generation: &Path, id: &str, base: &str, snapshot: &str,
|
|||
include_str!("../adapters/extensions.sh"), "archipelago-extension"])
|
||||
.arg(generation).status().map_err(|e| e.to_string())?;
|
||||
if !transaction.success() { return Err(format!("package transaction/finalization failed: {transaction}")); }
|
||||
crate::progress::phase("Committing the composed image", "Сохранение собранного образа");
|
||||
write(root.join("usr/lib/archipelago/extensions.json"), serde_json::to_vec_pretty(&json!({
|
||||
"version": 2, "base": base, "snapshot": snapshot.trim(), "generation": id,
|
||||
"requested": requested.keys().collect::<Vec<_>>(), "request_sources": requested,
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ pub mod desktop;
|
|||
pub mod updates;
|
||||
pub mod package_diff;
|
||||
pub mod software;
|
||||
mod progress;
|
||||
|
||||
pub const HOST: &str = include_str!("../adapters/host.sh");
|
||||
pub const FIRSTBOOT: &str = include_str!("../adapters/firstboot.sh");
|
||||
|
|
|
|||
8
src/progress.rs
Normal file
8
src/progress.rs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
pub(crate) fn phase(english: &str, russian: &str) {
|
||||
let locale = std::env::var("LC_ALL").ok().filter(|v| !v.is_empty())
|
||||
.or_else(|| std::env::var("LC_MESSAGES").ok()).or_else(|| std::env::var("LANG").ok()).unwrap_or_default();
|
||||
let message = if locale.starts_with("ru") { russian } else { english };
|
||||
if std::env::var_os("ARCHIPELAGO_OUTPUT_CHILD").is_some() {
|
||||
eprintln!("ARCHIPELAGO_PHASE\t{message}");
|
||||
}
|
||||
}
|
||||
|
|
@ -16,6 +16,10 @@ fn save(value: &Value) -> Result<(), String> {
|
|||
}
|
||||
pub fn refresh() -> Result<(), String> {
|
||||
if run(&["id", "-u"])?.trim() != "0" { return Err("Run through the authorized Software helper".into()); }
|
||||
if run(&["systemctl", "show", "archipelago-software-apply.service", "-p", "ActiveState", "--value"])
|
||||
.is_ok_and(|state| matches!(state.trim(), "active" | "activating" | "reloading")) {
|
||||
return Ok(());
|
||||
}
|
||||
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}"))?;
|
||||
|
|
@ -31,6 +35,13 @@ pub fn refresh() -> Result<(), String> {
|
|||
let mut record: Value = serde_json::from_str(&text).map_err(|e| e.to_string())?;
|
||||
record["version"] = json!(1);
|
||||
record["support_description"] = json!(support);
|
||||
if let Ok(bytes) = fs::read(Path::new(CACHE).join("status.json")) {
|
||||
if let Ok(previous) = serde_json::from_slice::<Value>(&bytes) {
|
||||
if previous["plan_id"] == record["plan_id"] && previous["downloaded"] == true {
|
||||
record["downloaded"] = json!(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
record["state"] = json!(if record["plan"]["base"] == record["plan"]["target"] { "current" } else { "available" });
|
||||
save(&record)
|
||||
}
|
||||
|
|
@ -42,18 +53,51 @@ pub fn request(operation: &str, plan: Option<&str>) -> Result<(), String> {
|
|||
if operation == "refresh" && plan.is_none() {
|
||||
return run(&["systemctl", "start", "--wait", "archipelago-software-refresh.service"]).map(|_| ());
|
||||
}
|
||||
if operation == "confirm-pending" {
|
||||
let expected = plan.ok_or("Missing pending deployment identity")?;
|
||||
let state = crate::extensions::status()?;
|
||||
if !state["deployments"].as_array().ok_or("missing deployments")?.iter().any(|d|
|
||||
d["stateroot"] == "archipelago" && (d["pending"] == true || d["staged"] == true) && d["checksum"] == expected) {
|
||||
return Err("Pending deployment changed; refresh before requesting restart".into());
|
||||
}
|
||||
// GNOME owns the explicit user-requested reboot. This helper never reboots.
|
||||
return Ok(());
|
||||
}
|
||||
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]),
|
||||
("apply" | "download", 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", operation, "--plan", id]),
|
||||
_ => return Err("Unsupported Software operation".into()),
|
||||
}
|
||||
let request_lock = fs::File::options().create(true).truncate(false).write(true)
|
||||
.open("/run/archipelago-software-request.lock").map_err(|e| e.to_string())?;
|
||||
request_lock.try_lock().map_err(|e| format!("Another desktop transaction is running: {e}"))?;
|
||||
let cache_lock = fs::File::options().create(true).truncate(false).write(true)
|
||||
.open("/run/archipelago-software.lock").map_err(|e| e.to_string())?;
|
||||
cache_lock.try_lock().map_err(|e| format!("Software refresh busy: {e}"))?;
|
||||
let mut previous: Value = serde_json::from_slice(&fs::read(Path::new(CACHE).join("status.json")).map_err(|e| e.to_string())?)
|
||||
.map_err(|e| e.to_string())?;
|
||||
if previous["plan_id"].as_str() != plan || previous["state"] != "available" {
|
||||
return Err("Desktop update plan changed; refresh first".into());
|
||||
}
|
||||
let mut active = previous.clone();
|
||||
active["state"] = json!(if operation == "download" { "downloading" } else { "applying" });
|
||||
save(&active)?;
|
||||
let result = run(&command);
|
||||
if operation == "download" {
|
||||
if result.is_ok() { previous["downloaded"] = json!(true); }
|
||||
save(&previous)?;
|
||||
}
|
||||
drop(cache_lock);
|
||||
if operation == "apply" {
|
||||
// Always reconcile the real deployment, including failures after staging.
|
||||
if let Err(error) = refresh() { eprintln!("Software state refresh: {error}"); }
|
||||
}
|
||||
result.map(|_| ())
|
||||
result.map(|_| ()).map_err(|error| {
|
||||
let detail = run(&["journalctl", "-u", "archipelago-software-apply.service", "-n", "25", "--no-pager", "-o", "cat"])
|
||||
.unwrap_or_default();
|
||||
format!("{error}\n{detail}")
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -143,6 +143,7 @@ fn require_newer(base: &str, target: &str) -> Result<(), String> {
|
|||
Ok(())
|
||||
}
|
||||
pub(crate) fn stage_deployment(commit: &str) -> Result<(), String> {
|
||||
crate::progress::phase("Staging deployment and boot entry", "Подготовка deployment и загрузочной записи");
|
||||
let mut args = vec!["admin", "deploy", "--stage", "--retain", "--os=archipelago"];
|
||||
if matches!(variant()?, "gnome" | "kde") {
|
||||
args.extend(["--karg=quiet", "--karg=splash", "--karg=plymouth.ignore-serial-consoles"]);
|
||||
|
|
@ -175,6 +176,7 @@ pub fn plan(save: bool) -> Result<(), String> {
|
|||
pub fn plan_json(save: bool) -> Result<(), String> {
|
||||
plan_output(save, true, true)
|
||||
}
|
||||
pub fn diff() -> Result<(), String> { plan_output(false, false, true) }
|
||||
fn plan_output(save: bool, json_output: bool, include_diff: bool) -> Result<(), String> {
|
||||
let _lock = lock()?;
|
||||
reconcile_operations()?;
|
||||
|
|
@ -200,7 +202,21 @@ fn plan_output(save: bool, json_output: bool, include_diff: bool) -> Result<(),
|
|||
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(()); }
|
||||
if !save {
|
||||
if json_output { println!("{}", serde_json::to_string_pretty(&plan).unwrap()); }
|
||||
else {
|
||||
println!("Track: {reference}\nCurrent: {base}\nTarget: {target}");
|
||||
println!("State: {}", if base == target { "up to date" } else { "update available" });
|
||||
if let Some(changes) = plan["package_changes"].as_array() {
|
||||
println!("\n{:<32} {:<24} {}", "Package", "Installed", "Target");
|
||||
for change in changes {
|
||||
println!("{:<32} {:<24} {}", change["name"].as_str().unwrap_or("?"),
|
||||
change["old_version"].as_str().unwrap_or("—"), change["new_version"].as_str().unwrap_or("removed"));
|
||||
}
|
||||
}
|
||||
}
|
||||
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();
|
||||
|
|
@ -213,6 +229,13 @@ fn plan_output(save: bool, json_output: bool, include_diff: bool) -> Result<(),
|
|||
Ok(())
|
||||
}
|
||||
pub fn apply(id: &str) -> Result<(), String> {
|
||||
execute_plan(id, false)
|
||||
}
|
||||
pub fn download(id: &str) -> Result<(), String> {
|
||||
execute_plan(id, true)
|
||||
}
|
||||
fn execute_plan(id: &str, download_only: bool) -> Result<(), String> {
|
||||
crate::progress::phase("Checking saved plan and current deployment", "Проверка плана и текущего deployment");
|
||||
let _lock = lock()?;
|
||||
reconcile_operations()?;
|
||||
let path = plan_path(id)?;
|
||||
|
|
@ -222,14 +245,14 @@ pub fn apply(id: &str) -> Result<(), String> {
|
|||
let plan: Value = serde_json::from_slice(&fs::read(&path).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
|
||||
let operation = Path::new(STATE).join(format!("operation-{}.json", SystemTime::now().duration_since(UNIX_EPOCH).map_err(|e| e.to_string())?.as_nanos()));
|
||||
write(&operation, &json!({"plan":id,"state":"executing"}))?;
|
||||
let result = apply_plan(&plan);
|
||||
let result = apply_plan(&plan, download_only);
|
||||
let terminal = match &result { Ok(()) => json!({"plan":id,"state":"completed"}), Err(e) => json!({"plan":id,"state":"failed","error":e}) };
|
||||
if let Err(error) = write(&operation, &terminal) {
|
||||
eprintln!("Could not record terminal operation state: {error}; inspect deployment status");
|
||||
}
|
||||
result
|
||||
}
|
||||
fn apply_plan(plan: &Value) -> Result<(), String> {
|
||||
fn apply_plan(plan: &Value, download_only: bool) -> Result<(), String> {
|
||||
let binding = binding()?;
|
||||
if plan["version"] != 3 || plan["binding"] != binding || plan["variant"] != variant()? { return Err("unsupported plan or infrastructure binding changed; create a new plan".into()); }
|
||||
let initial = crate::extensions::status()?;
|
||||
|
|
@ -239,10 +262,12 @@ fn apply_plan(plan: &Value) -> Result<(), String> {
|
|||
if plan["base"] == target { println!("Already on the selected base; no deployment created."); return Ok(()); }
|
||||
configure(&binding)?;
|
||||
require_newer(plan["base"].as_str().filter(|s| digest(s)).ok_or("invalid base")?, target)?;
|
||||
crate::progress::phase("Downloading and verifying the image", "Загрузка и проверка подписанного образа");
|
||||
// The signed summary selects the checksum during planning; exact-checksum pull
|
||||
// verifies its commit signature without reinterpreting old build-local ref bindings.
|
||||
repo(&["pull", "--depth=0", REMOTE, target])?;
|
||||
let files = repo(&["ls", target, "/usr/lib/archipelago"])?;
|
||||
crate::progress::phase("Checking Purpose and architecture", "Проверка Purpose и архитектуры");
|
||||
let candidate = if files.lines().any(|l| l.ends_with("/purpose")) {
|
||||
purpose_variant(&repo(&["cat", target, "/usr/lib/archipelago/purpose"])?)?
|
||||
} else if files.lines().any(|l| l.ends_with("/gnome-firstboot")) {
|
||||
|
|
@ -251,7 +276,13 @@ fn apply_plan(plan: &Value) -> Result<(), String> {
|
|||
if candidate != variant()? { return Err("candidate Purpose differs from booted Purpose".into()); }
|
||||
if output("uname", &["-m"])?.trim() != "x86_64" { return Err("only x86_64 is implemented".into()); }
|
||||
repo(&["cat", target, "/usr/lib/archipelago/snapshot"])?;
|
||||
if download_only {
|
||||
if crate::extensions::status()? != initial { return Err("deployment state changed during download".into()); }
|
||||
println!("Verified image downloaded; no deployment staged.");
|
||||
return Ok(());
|
||||
}
|
||||
output("ostree", &["--repo=/sysroot/ostree/repo", "pull-local", &format!("{STATE}/repo"), target])?;
|
||||
crate::progress::phase("Preparing the new system", "Подготовка новой системы");
|
||||
let requested: crate::extensions::Requests = serde_json::from_value(plan["requested"].clone()).map_err(|e| e.to_string())?;
|
||||
if crate::extensions::status()? != initial { return Err("deployment state changed during download".into()); }
|
||||
if requested.is_empty() {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue