// SPDX-License-Identifier: GPL-2.0-or-later // One immutable OS transaction; package/runtime applications belong to other backends. #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include 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()) return decode(value.value().variant()); if (value.metaType() == QMetaType::fromType()) { const auto arg = value.value(); 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; 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(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("distributor-logo"); } 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("drive-harddisk"); } 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] == "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; text += "
    "_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 += "
  • "_L1 + change["name"_L1].toString().toHtmlEscaped() + ": "_L1 + before.toHtmlEscaped() + QStringLiteral(" → ") + after.toHtmlEscaped() + "
  • "_L1; } return text + "
"_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; 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."); } } if (record == next) return; record = next; Q_EMIT stateChanged(); Q_EMIT versionsChanged(); Q_EMIT longDescriptionChanged(); }); } public Q_SLOTS: void invalidated(const QString &, const QVariantMap &, const QStringList &) { reload(); } private: 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 operation; 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()); }); 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 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 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"