system/integrations/discover/ArchipelagoBackend.cpp
Archipelago 790a4dd2b0 Report real update progress and ship the distributor icon (D-112)
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.
2026-11-14 13:14:42 +03:00

354 lines
19 KiB
C++

// SPDX-License-Identifier: GPL-2.0-or-later
// One immutable OS transaction; package/runtime applications belong to other backends.
#include <resources/AbstractResourcesBackend.h>
#include <resources/StandardBackendUpdater.h>
#include <Transaction/Transaction.h>
#include <QDate>
#include <QFile>
#include <QJsonDocument>
#include <QDBusConnection>
#include <QDBusMessage>
#include <QDBusPendingCallWatcher>
#include <QDBusPendingReply>
#include <QDBusArgument>
#include <QDBusVariant>
#include <QDBusServiceWatcher>
#include <QElapsedTimer>
#include <QUuid>
#include <functional>
#include <QRegularExpression>
#include <QSharedPointer>
#include <QPointer>
#include <QTimer>
using namespace Qt::StringLiterals;
static const QString busName = QStringLiteral("org.archipelago.System1");
static const QString managerPath = QStringLiteral("/org/archipelago/System1");
static const QString managerInterface = busName + QStringLiteral(".Manager");
static QVariant decode(const QVariant &value)
{
if (value.metaType() == QMetaType::fromType<QDBusVariant>()) return decode(value.value<QDBusVariant>().variant());
if (value.metaType() == QMetaType::fromType<QDBusArgument>()) {
const auto arg = value.value<QDBusArgument>();
if (arg.currentType() == QDBusArgument::MapType) {
QVariantMap result;
arg.beginMap();
while (!arg.atEnd()) {
QString key; QDBusVariant field;
arg.beginMapEntry(); arg >> key >> field; arg.endMapEntry();
result.insert(key, decode(field.variant()));
}
arg.endMap(); return result;
}
if (arg.currentType() == QDBusArgument::ArrayType) {
QVariantList result;
arg.beginArray();
while (!arg.atEnd()) result.append(decode(arg.asVariant()));
arg.endArray(); return result;
}
}
return value;
}
using BusReply = std::function<void(const QDBusMessage &)>;
static void busCall(QObject *owner, const QString &path, const QString &interface,
const QString &method, const QVariantList &args, bool interactive, BusReply callback)
{
auto message = QDBusMessage::createMethodCall(busName, path, interface, method);
message.setArguments(args);
message.setInteractiveAuthorizationAllowed(interactive);
auto watcher = new QDBusPendingCallWatcher(QDBusConnection::systemBus().asyncCall(message, 120000), owner);
QObject::connect(watcher, &QDBusPendingCallWatcher::finished, owner, [watcher, callback] {
callback(watcher->reply()); watcher->deleteLater();
});
}
static QVariantMap replyMap(const QDBusMessage &reply)
{
return reply.arguments().isEmpty() ? QVariantMap{} : decode(reply.arguments().first()).toMap();
}
class SystemOperation final : public QObject
{
Q_OBJECT
public:
explicit SystemOperation(QObject *parent) : QObject(parent) { deadline.start(); }
QString path;
bool canCancel = false;
void start(const QString &method, const QString &target = {}) {
QVariantMap options{{QStringLiteral("request_id"), QUuid::createUuid().toString(QUuid::WithoutBraces)},
{QStringLiteral("interactive"), true}};
QVariantList args;
if (!target.isEmpty()) args.append(target);
args.append(options);
busCall(this, managerPath, managerInterface, method, args, true, [this](const QDBusMessage &reply) {
if (reply.type() == QDBusMessage::ErrorMessage) { finish({}, reply.errorMessage()); return; }
if (reply.arguments().isEmpty()) { finish({}, tr("Missing operation reply")); return; }
path = qvariant_cast<QDBusObjectPath>(reply.arguments().first()).path();
if (!path.startsWith(managerPath + "/transactions/op_"_L1)) { finish({}, tr("Invalid transaction path")); return; }
poll();
});
}
void cancel() {
if (!canCancel || path.isEmpty()) return;
busCall(this, path, busName + ".Transaction"_L1, QStringLiteral("Cancel"),
{QVariantMap{{QStringLiteral("interactive"), true}}}, true, [this](const QDBusMessage &reply) {
if (reply.type() == QDBusMessage::ErrorMessage) Q_EMIT cancellationError(reply.errorMessage());
});
}
Q_SIGNALS:
void finished(const QVariantMap &result, const QString &error);
void progress(const QVariantMap &snapshot);
void cancellationError(const QString &error);
private:
QElapsedTimer deadline;
int failures = 0;
void finish(const QVariantMap &result, const QString &error) { Q_EMIT finished(result, error); deleteLater(); }
void poll() {
busCall(this, path, busName + ".Transaction"_L1, QStringLiteral("GetSnapshot"), {}, false,
[this](const QDBusMessage &reply) {
if (reply.type() == QDBusMessage::ErrorMessage) {
if (++failures > 20) { finish({}, tr("Cannot observe retained operation %1: %2").arg(path, reply.errorMessage())); return; }
busCall(this, managerPath, managerInterface, QStringLiteral("GetTransaction"),
{path.section('/'_L1, -1).mid(3)}, false, [this](const QDBusMessage &) {
QTimer::singleShot(500, this, [this] { poll(); });
});
return;
}
failures = 0;
const auto state = replyMap(reply);
canCancel = state.value(QStringLiteral("CanCancel")).toBool();
Q_EMIT progress(state);
const auto status = state.value(QStringLiteral("State")).toString();
if (status == "succeeded"_L1) { finish(state.value(QStringLiteral("Result")).toMap(), {}); return; }
if (status == "failed"_L1 || status == "cancelled"_L1 || status == "interrupted"_L1) {
finish({}, state.value(QStringLiteral("Error")).toMap().value(QStringLiteral("message")).toString()); return;
}
if (deadline.elapsed() > 4*60*60*1000) { finish({}, tr("Stopped waiting for retained operation %1").arg(path)); return; }
QTimer::singleShot(500, this, [this] { poll(); });
});
}
};
class OSResource final : public AbstractResource
{
Q_OBJECT
public:
explicit OSResource(AbstractResourcesBackend *backend) : AbstractResource(backend) {
QDBusConnection::systemBus().connect(busName, managerPath,
QStringLiteral("org.freedesktop.DBus.Properties"), QStringLiteral("PropertiesChanged"),
this, SLOT(invalidated(QString,QVariantMap,QStringList)));
}
QJsonObject record;
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("archipelago"); }
bool canExecute() const override { return false; }
void invokeApplication() const override {}
bool isRemovable() const override { return false; }
State state() override { return record["state"_L1] == "available"_L1 ? Upgradeable : Installed; }
bool hasCategory(const QString &category) const override { return category == "System"_L1; }
Type type() const override { return System; }
quint64 size() override { return 0; } // The transport has not reported download size.
QString sizeDescription() override { return tr("Download size is determined by OSTree"); }
QJsonArray licenses() override { return {}; }
QString installedVersion() const override { return record["plan"_L1].toObject()["base"_L1].toString(); }
QString availableVersion() const override { return record["plan"_L1].toObject()["target"_L1].toString(); }
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("archipelago-symbolic"); }
QDate releaseDate() const override { return {}; }
QList<PackageState> addonsInformation() override { return {}; }
QString longDescription() override {
QString text = comment().toHtmlEscaped();
if (record["state"_L1] == "pending"_L1) text += tr("<p>A deployment is staged. Restart when ready.</p>");
if (record["state"_L1] == "applying"_L1) text += tr("<p>The operating system update is being prepared. The active transaction reports its progress.</p>");
if (record["state"_L1] == "downloading"_L1) text += tr("<p>The verified operating system image is being downloaded.</p>");
if (record["state"_L1] == "error"_L1) text += "<p>"_L1 + record["error"_L1].toString().toHtmlEscaped() + "</p>"_L1;
text += "<pre>"_L1 + record["support_description"_L1].toString().toHtmlEscaped() + "</pre>"_L1;
text += "<ul>"_L1;
for (const auto &entry : record["plan"_L1].toObject()["package_changes"_L1].toArray()) {
const auto change = entry.toObject();
const QString before = change["old_version"_L1].isString() ? change["old_version"_L1].toString() : tr("not installed");
const QString after = change["new_version"_L1].isString() ? change["new_version"_L1].toString() : tr("will be removed");
text += "<li>"_L1 + change["name"_L1].toString().toHtmlEscaped() + ": "_L1
+ before.toHtmlEscaped() + QStringLiteral(" → ") + after.toHtmlEscaped() + "</li>"_L1;
}
return text + "</ul>"_L1;
}
void fetchChangelog() override { Q_EMIT changelogFetched(longDescription()); }
void reload() {
if (loading) return;
loading = true;
busCall(this, managerPath, managerInterface, QStringLiteral("GetStatus"), {}, false, [this](const QDBusMessage &reply) {
loading = false;
if (reply.type() == QDBusMessage::ErrorMessage) {
// 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;
}
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;
};
class OSTransaction final : public Transaction
{
Q_OBJECT
public:
explicit OSTransaction(OSResource *resource)
: Transaction(resource->backend(), resource, InstallRole, {}) {
setCancellable(false);
const QString id = resource->record["target"_L1].toString();
QTimer::singleShot(0, this, [this, resource, id] {
if (resource->state() != AbstractResource::Upgradeable ||
!QRegularExpression(QStringLiteral("^[a-f0-9]{64}$")).match(id).hasMatch()) {
Q_EMIT passiveMessage(tr("No valid update plan; refresh updates first."));
setStatus(DoneWithErrorStatus);
deleteLater();
return;
}
setStatus(CommittingStatus);
run(resource, QStringLiteral("PrepareUpdate"), id, true);
});
}
void cancel() override { if (operation) operation->cancel(); }
private:
QPointer<SystemOperation> 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"))) 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) {
if (error.isEmpty() && planning) {
run(resource, QStringLiteral("Stage"), result.value(QStringLiteral("plan_id")).toString(), false);
return;
}
resource->reload();
if (!error.isEmpty()) Q_EMIT passiveMessage(error);
else setProgress(100);
setStatus(error.isEmpty() ? DoneStatus : DoneWithErrorStatus);
deleteLater();
});
operation->start(method, id);
}
};
class ArchipelagoBackend final : public AbstractResourcesBackend
{
Q_OBJECT
public:
explicit ArchipelagoBackend(QObject *parent = nullptr) : AbstractResourcesBackend(parent) {
resource = new OSResource(this);
updater = new StandardBackendUpdater(this);
connect(resource, &AbstractResource::stateChanged, this, [this] {
updater->setNeedsReboot(resource->record["state"_L1] == "pending"_L1);
Q_EMIT updatesCountChanged();
Q_EMIT resourcesChanged(resource, {"state", "installedVersion", "availableVersion", "longDescription"});
const QString state = resource->record["state"_L1].toString();
QSharedPointer<InlineMessage> message;
if (state == "error"_L1) {
message.reset(new InlineMessage(InlineMessage::Error, QStringLiteral("dialog-error"), resource->record["error"_L1].toString()));
} else if (state == "pending"_L1) {
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"_L1 || state == "downloading"_L1) {
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);
connect(timer, &QTimer::timeout, resource, &OSResource::reload);
timer->start(30000);
auto watcher = new QDBusServiceWatcher(busName, QDBusConnection::systemBus(),
QDBusServiceWatcher::WatchForOwnerChange, this);
connect(watcher, &QDBusServiceWatcher::serviceOwnerChanged, resource, [this] { resource->reload(); });
// ResourcesModel connects progress signals only after construction and
// initializes its aggregate at zero. Start asynchronously so startup
// cannot remain at "fetching" without any actual refresh in flight.
QTimer::singleShot(0, this, [this] { checkForUpdates(); });
}
bool isValid() const override {
QFile purpose(QStringLiteral("/usr/lib/archipelago/purpose"));
return QFile::exists(QStringLiteral("/run/ostree-booted")) && purpose.open(QIODevice::ReadOnly)
&& purpose.readAll().trimmed() == "purpose/desktop/kde";
}
QString displayName() const override { return QStringLiteral("Archipelago"); }
int updatesCount() const override { return resource->state() == AbstractResource::Upgradeable ? 1 : 0; }
AbstractBackendUpdater *backendUpdater() const override { return updater; }
AbstractReviewsBackend *reviewsBackend() const override { return nullptr; }
int fetchingUpdatesProgress() const override { return refreshing ? 0 : 100; }
ResultsStream *search(const Filters &filters) override {
QVector<StreamResult> found{StreamResult(resource)};
filters.filterJustInCase(found);
return new ResultsStream(QStringLiteral("Archipelago"), found);
}
Transaction *installApplication(AbstractResource *app, const AddonList &) override {
return app == resource ? new OSTransaction(resource) : nullptr;
}
Transaction *removeApplication(AbstractResource *) override {
Q_EMIT passiveMessage(tr("The operating system cannot be removed."));
return nullptr;
}
void checkForUpdates() override {
if (refreshing) return;
refreshing = true;
Q_EMIT fetchingUpdatesProgressChanged();
auto operation = new SystemOperation(this);
const auto finished = [this](const QString &error) {
refreshing = false;
resource->reload();
if (!error.isEmpty()) Q_EMIT passiveMessage(error);
Q_EMIT fetchingUpdatesProgressChanged();
};
connect(operation, &SystemOperation::finished, this, [this, finished](const QVariantMap &result, const QString &error) {
if (!error.isEmpty() || result.value(QStringLiteral("outcome")).toString() != "available"_L1) { finished(error); return; }
auto details = new SystemOperation(this);
connect(details, &SystemOperation::finished, this, [finished](const QVariantMap &, const QString &error) { finished(error); });
details->start(QStringLiteral("GetUpdateDetails"), result.value(QStringLiteral("target")).toString());
});
operation->start(QStringLiteral("Refresh"));
}
private:
OSResource *resource;
StandardBackendUpdater *updater;
bool refreshing = false;
};
DISCOVER_BACKEND_PLUGIN(ArchipelagoBackend)
#include "ArchipelagoBackend.moc"