diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml deleted file mode 100644 index b2b7cbe..0000000 --- a/.gitea/workflows/release.yml +++ /dev/null @@ -1,145 +0,0 @@ -# Gitea Actions — Release -# -# Triggered whenever the `version` file at the repository root is bumped. -# Creates a Gitea release tagged with the new version — but ONLY if the -# version in `version` differs from the latest released tag. -# -# The release also uploads a prebuilt binary archive -# (PacManager--x86_64.tar.gz with the binary, version file and -# plugins) so installed apps without a build toolchain can self-update -# WITHOUT recompiling. UpdateManager uses it as a fallback when git/cmake/a -# compiler are unavailable; otherwise it clones the repo and rebuilds. The -# upload is best-effort, so a failed build never blocks the release itself. -# -# No secret is required: `secrets.GITEA_TOKEN` is the built-in automatic -# token provided by Gitea on every run. The `permissions: contents: write` -# block below asks for write access to contents and releases, so the release -# can be created without configuring any secret in the repository settings. -# Tests are deliberately not run here; they live in the separate `tests` -# workflow and do not gate releases. - -name: release - -on: - push: - branches: - - main - paths: - - version - workflow_dispatch: - -permissions: - contents: write - -jobs: - # Reads the new version and publishes a release + git tag when the version - # genuinely changed. Runs without any test step. - release: - runs-on: linux - steps: - - name: Checkout with full history and tags - uses: actions/checkout@v4 - with: - fetch-depth: 0 - fetch-tags: true - - - name: Read version - id: version - run: | - VERSION=$(tr -d ' \n' < version) - echo "value=${VERSION}" >> "$GITHUB_OUTPUT" - - - name: Check whether the version already has a release - id: check - run: | - VERSION="${{ steps.version.outputs.value }}" - TAG="v${VERSION}" - if git tag --list | grep -qx "${TAG}"; then - echo "Tag ${TAG} already exists — nothing to release" - echo "new=false" >> "$GITHUB_OUTPUT" - else - echo "new=true" >> "$GITHUB_OUTPUT" - fi - - - name: Create release - if: steps.check.outputs.new == 'true' - id: create - env: - # Built-in automatic token, no secret to configure. The - # `permissions` block at the top grants it write access to - # contents/releases for this run. - GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} - run: | - VERSION="${{ steps.version.outputs.value }}" - TAG="v${VERSION}" - BODY=$(cat <<'EOF' - Release automatically generated by the `release` workflow when the - `version` file was bumped. - EOF - ) - RESP=$(curl -sS -X POST "$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/releases" \ - -H "Authorization: token ${GITEA_TOKEN}" \ - -H "Content-Type: application/json" \ - -d @- <> "$GITHUB_OUTPUT" - - - name: Build prebuilt binary archive - if: steps.check.outputs.new == 'true' - id: build - run: | - VERSION="${{ steps.version.outputs.value }}" - if command -v pacman >/dev/null 2>&1; then - sudo pacman -S --noconfirm --needed git cmake gcc make qt6-base - elif command -v apt-get >/dev/null 2>&1; then - sudo apt-get update - sudo apt-get install -y git cmake g++ make qt6-base-dev - elif command -v dnf >/dev/null 2>&1; then - sudo dnf install -y git cmake gcc-c++ make qt6-qtbase-devel - else - echo "Unsupported package manager — skipping prebuilt archive" - echo "ok=false" >> "$GITHUB_OUTPUT" - exit 0 - fi - cmake -B build -DCMAKE_BUILD_TYPE=Release - cmake --build build -j$(nproc) - STAGE="pacmanager-dist" - rm -rf "${STAGE}" && mkdir -p "${STAGE}/bin" "${STAGE}/plugins" - cp build/PacManager "${STAGE}/bin/" - cp version "${STAGE}/bin/" - if ls build/plugins/*.so >/dev/null 2>&1; then - cp build/plugins/*.so "${STAGE}/plugins/" - fi - # Layout consumed by UpdateManager's prebuilt path: bin/PacManager, - # bin/version and plugins/ (unpacked next to the running executable, - # wherever it lives). - ARCHIVE="PacManager-${VERSION}-x86_64.tar.gz" - tar czf "${ARCHIVE}" -C "${STAGE}" bin plugins - echo "archive=${ARCHIVE}" >> "$GITHUB_OUTPUT" - echo "ok=true" >> "$GITHUB_OUTPUT" - - - name: Upload prebuilt archive to release - if: steps.check.outputs.new == 'true' && steps.build.outputs.ok == 'true' - env: - GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} - run: | - ARCHIVE="${{ steps.build.outputs.archive }}" - RELEASE_ID="${{ steps.create.outputs.release_id }}" - if [ -z "${RELEASE_ID}" ]; then - echo "No release id — skipping upload" - exit 0 - fi - curl -sS -X POST \ - "$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/releases/${RELEASE_ID}/assets?name=$(basename ${ARCHIVE})" \ - -H "Authorization: token ${GITEA_TOKEN}" \ - -H "Content-Type: application/gzip" \ - --data-binary "@${ARCHIVE}" || echo "Asset upload failed — release still valid without prebuilt binary" diff --git a/.gitea/workflows/test.yml b/.gitea/workflows/test.yml deleted file mode 100644 index 911aad1..0000000 --- a/.gitea/workflows/test.yml +++ /dev/null @@ -1,84 +0,0 @@ -# Gitea Actions — Tests -# -# Dedicated test workflow: builds the application and runs the full test suite -# (ctest) on every push and pull request. Kept separate from the release -# workflow so a failing test never blocks a release. Also guards the -# `version` file: it must match the latest git tag (if any), otherwise the -# self-update check would report a phantom update. - -name: tests - -on: - push: - pull_request: - workflow_dispatch: - -jobs: - version-guard: - runs-on: linux - steps: - - name: Checkout with full history and tags - uses: actions/checkout@v4 - with: - fetch-depth: 0 - fetch-tags: true - - - name: Check version file matches latest tag (when tags exist) - run: | - VERSION=$(tr -d ' \n' < version) - echo "version file: ${VERSION}" - LATEST=$(git describe --tags --abbrev=0 2>/dev/null || true) - if [ -z "${LATEST}" ]; then - echo "No tags yet — skipping version guard" - exit 0 - fi - # Tags are like v1.3.1 / V1.3.1 ; the file holds 1.3.1 - NORMALIZED=$(echo "${LATEST}" | sed -E 's/^[vV]//') - echo "latest tag: ${LATEST} (normalized: ${NORMALIZED})" - if [ "${VERSION}" != "${NORMALIZED}" ]; then - echo "::error::version file (${VERSION}) does not match latest tag ${LATEST} (expected ${NORMALIZED}). Bump the version file before tagging." - exit 1 - fi - echo "version file matches latest tag" - - build-test: - runs-on: linux - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Install dependencies - run: | - # Host-mode runners execute jobs directly on the runner machine, so - # detect its package manager instead of hardcoding apt (which only - # exists on Debian/Ubuntu hosts). - if command -v pacman >/dev/null 2>&1; then - sudo pacman -S --noconfirm --needed \ - git cmake gcc make qt6-base - elif command -v apt-get >/dev/null 2>&1; then - sudo apt-get update - sudo apt-get install -y \ - git cmake g++ make qt6-base-dev - elif command -v dnf >/dev/null 2>&1; then - sudo dnf install -y \ - git cmake gcc-c++ make qt6-qtbase-devel - else - echo "Unsupported package manager: install git, cmake, a C++ compiler, make and Qt6 manually" >&2 - exit 1 - fi - - - name: Configure - run: | - cmake -B build \ - -DFWS_BUILD_EXAMPLE_PLUGIN=ON \ - -DFWS_BUILD_EXAMPLE_ADDON=ON \ - -DCMAKE_BUILD_TYPE=Release - - - name: Build - run: | - cmake --build build -j$(nproc) - - - name: Run all tests - run: | - cd build - ctest --output-on-failure diff --git a/CMakeLists.txt b/CMakeLists.txt index ef99ab4..6dc88ee 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,12 +8,17 @@ set(CMAKE_AUTORCC ON) set(CMAKE_AUTOUIC ON) # The repo-root `version` file is the single source of truth for release -# versioning. It is compiled into the binaries as well as installed next to -# them, so a running app always reports the release it was built from instead -# of trusting a `version` file that an update may have left stale. +# versioning. It is read at configure time and compiled into the binaries, so a +# running app knows which release it was built from. file(READ ${CMAKE_CURRENT_SOURCE_DIR}/version PACMANAGER_VERSION) string(STRIP "${PACMANAGER_VERSION}" PACMANAGER_VERSION) +# Reading it above only happens during configuration, and bumping the file is +# not otherwise a reason to configure again: without this, `cmake --build` after +# a version bump kept building the previous version into the binary. +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS + ${CMAKE_CURRENT_SOURCE_DIR}/version) + # Find Qt6 find_package(Qt6 REQUIRED COMPONENTS Widgets Network) diff --git a/README.en.md b/README.en.md index 4a02ff6..c1a3f15 100644 --- a/README.en.md +++ b/README.en.md @@ -131,17 +131,24 @@ The method is picked automatically (no configuration): | --- | --- | --- | | **Checkout** | a source checkout surrounds the binary (dev) | `git pull`, rebuild, install into the binary's directory | | **Clone** | installed app with no checkout, and `git` + `cmake` + a compiler | the repo is cloned/updated in `~/.local/share/PacManager/src`, rebuilt and installed in place | -| **Prebuilt** | no build toolchain available | the release's prebuilt archive is downloaded and unpacked | +| **Prebuilt** | no build toolchain available, and the release has a prebuilt archive attached | that archive is downloaded and unpacked | | **Tarball** | no `git`, but `cmake` + a compiler | the release sources are built and installed | Everything builds in a temporary directory: only the final replacement of the binary (and plugins) needs `sudo`, and only when the target directory is owned by root. PacManager then restarts automatically on the new version. +Nothing produces a prebuilt archive automatically: without one attached to the +release, **Clone** or **Tarball** applies instead (so `git`, `cmake` and a +compiler are needed on the machine). + All four methods install to the same place — the running binary's directory — -and rewrite the `version` file there. On top of that, the app reports the -version **compiled into the binary** (from the repo's `version` file) first, so -the same update is never offered again once it has been applied. +and rewrite the `version` file there. To know which release is really installed, +PacManager keeps the **newest** of two sources: the version compiled into the +binary (read from the repo's `version` file at configure time) and the one in the +`version` file next to the executable. An applied update is therefore never +offered again, even when one of the two lags behind (a binary rebuilt without +configuring again, an install older than the binary). ## Graphical interface @@ -155,6 +162,7 @@ The interface uses **Qt6** with a dark theme, a **navigation sidebar** and stack - 📜 **Logs**: built-in `/var/log/pacman.log` viewer with an instant filter - 🧩 **Plugins**: lists every plugin (package providers and extensions), enable / disable and plugin rescan - ⌨️ **Convenience**: system tray icon and keyboard shortcuts (Ctrl+F search, Ctrl+R / F5 refresh, Ctrl+U updates, Ctrl+E export, Ctrl+Q quit) +- 🔒 **pacman lock**: when another manager (pamac, octopi, yay…) holds the database, PacManager names it (process + PID) and offers to close it and resume the operation, instead of waiting for it to finish; a leftover lock is removed the same way - 🎨 **Legibility**: a sidebar split into sections, showing the installed version and the pending update count; quick actions (refresh, update all) in the header, reachable from any page; empty lists that say what to do next - 📤 **Export**: the displayed package list and the history can be exported as CSV diff --git a/README.md b/README.md index 2065441..5c63c94 100644 --- a/README.md +++ b/README.md @@ -131,7 +131,7 @@ La méthode est choisie automatiquement (aucune configuration) : | --- | --- | --- | | **Checkout** | un dépôt source entoure le binaire (dev) | `git pull`, recompilation puis installation dans le dossier du binaire | | **Clone** | app installée sans dépôt, avec `git` + `cmake` + compilateur | le dépôt est cloné puis mis à jour dans `~/.local/share/PacManager/src`, recompilé et installé en place | -| **Prebuilt** | pas d'outillage de compilation | l'archive précompilée de la release est téléchargée et décompressée | +| **Prebuilt** | pas d'outillage de compilation et une archive précompilée est attachée à la release | l'archive est téléchargée et décompressée | | **Tarball** | `git` absent mais `cmake` + compilateur présents | les sources de la release sont compilées puis installées | Tout se compile dans un dossier temporaire : seul le remplacement final du @@ -139,10 +139,18 @@ binaire (et des plugins) demande `sudo`, et uniquement si le dossier cible appartient à root. PacManager redémarre ensuite automatiquement sur la nouvelle version. +Rien ne produit d'archive précompilée automatiquement : sans archive attachée à +la release, ce sont **Clone** ou **Tarball** qui s'appliquent (donc `git`, `cmake` +et un compilateur sur la machine). + Les quatre méthodes installent au même endroit — le dossier du binaire en cours -— et y réécrivent le fichier `version`. L'application lit de plus en priorité la -version **compilée dans le binaire** (à partir du fichier `version` du dépôt) : -une mise à jour déjà appliquée n'est donc jamais reproposée au lancement. +— et y réécrivent le fichier `version`. Pour savoir quelle version est réellement +installée, PacManager retient la **plus récente** des deux sources : la version +compilée dans le binaire (lue dans le fichier `version` du dépôt au moment de la +configuration) et celle du fichier `version` posé à côté de l'exécutable. Une mise +à jour déjà appliquée n'est donc jamais reproposée, même quand l'une des deux +retarde (binaire recompilé sans reconfiguration, installation plus ancienne que +le binaire). ## Interface graphique @@ -156,6 +164,7 @@ L'interface utilise **Qt6** avec un thème sombre, une **sidebar de navigation** - 📜 **Logs** : journal `/var/log/pacman.log` intégré, avec filtre instantané - 🧩 **Plugins** : liste de tous les plugins (fournisseurs de paquets et extensions), activation / désactivation et rechargement - ⌨️ **Confort** : icône de notification (tray) et raccourcis clavier (Ctrl+F rechercher, Ctrl+R / F5 rafraîchir, Ctrl+U mises à jour, Ctrl+E exporter, Ctrl+Q quitter) +- 🔒 **Verrou pacman** : si un autre gestionnaire (pamac, octopi, yay…) tient la base, PacManager l'identifie (nom + PID) et propose de le fermer puis de reprendre l'opération automatiquement — au lieu d'attendre qu'il ait fini ; un verrou résiduel est supprimé de la même façon - 🎨 **Lisibilité** : barre latérale en sections, avec la version installée et le nombre de mises à jour en attente ; actions rapides (rafraîchir, tout mettre à jour) dans l'en-tête, disponibles depuis n'importe quelle page ; listes vides qui expliquent quoi faire - 📤 **Export** : liste de paquets affichée et historique exportables en CSV diff --git a/include/main-window.h b/include/main-window.h index 93ac1f0..0f7e4f7 100644 --- a/include/main-window.h +++ b/include/main-window.h @@ -71,12 +71,25 @@ private: class InstallWorker : public QThread { Q_OBJECT public: - enum class Op { Install, Remove, Update, UpdateAll, Refresh, RemovePackages, CleanCache }; + enum class Op { + Install, + Remove, + Update, + UpdateAll, + Refresh, + RemovePackages, + CleanCache, + ReleaseLock, + }; InstallWorker(IPackageManager* pm, Op op, const std::string& package); // Bulk variant: removes several packages in one provider call (cleanup // page) instead of one call per package. InstallWorker(IPackageManager* pm, Op op, const std::vector& packages); InstallWorker(const std::vector& providers, Op op); + // Pacman database-lock recovery: stops whatever holds the lock, or drops a + // stale lock file. Runs off the UI thread because waiting for the other + // manager to exit takes seconds. + InstallWorker(PacmanManager* pacman, const PacmanManager::LockHolder& holder); void run() override; signals: void progress(const QString& message); @@ -89,6 +102,8 @@ private: Op m_op; std::string m_package; std::vector m_packages; + PacmanManager* m_pacman = nullptr; // lock recovery only + PacmanManager::LockHolder m_lockHolder; }; class MainWindow : public QMainWindow { @@ -181,6 +196,14 @@ private: // a retry once the lock is gone). bool showProviderError(const QString& title, IPackageManager* provider); + // Names the process holding pacman's database and offers to close it — or to + // drop a stale lock — before re-running the pending action. Returns true when + // it handled the failure, so the caller skips its own reporting. + bool handleDatabaseLock(const QString& title); + void startLockRecovery(const PacmanManager::LockHolder& holder); + // Re-runs the action that failed, when it can still run. + void retryPendingAction(); + // Re-runs the given privileged action. Used by the "Réessayer" button // on db-lock errors: the lock (other manager / stale db.lck) is often // gone by the time the user retries. diff --git a/include/pacman-manager.h b/include/pacman-manager.h index 5939095..99925fc 100644 --- a/include/pacman-manager.h +++ b/include/pacman-manager.h @@ -73,6 +73,50 @@ public: // Exposed as static so it can be unit-tested without invoking pacman. static bool dbLocked(const std::string& output); + // What currently keeps pacman's database locked. The UI uses it to name the + // process in its dialog and offer to close it, instead of telling the user + // to wait for a manager it cannot identify. + struct LockHolder { + bool lockFilePresent = false; // /var/lib/pacman/db.lck exists + int pid = 0; // process holding it (0 when none found) + std::string name; // process name, when known + bool stale = false; // lock file present, but nobody holds it + }; + + // Pid of the process currently keeping `path` open, or 0 when nobody does. + // Detection walks /proc, which names the process even when it is not one of + // the managers we know about. Exposed so it can be unit-tested against a + // temporary file instead of pacman's real lock. + static int lockHolderPid(const std::string& path); + + // Inspect pacman's lock file and its holder. lockHolderPid() answers for a + // manager run by the user; the known managers are looked up with pgrep as a + // fallback, since /proc//fd is not readable when they run as root. + static LockHolder detectLockHolder(); + + // Human-readable description of what holds the database ("pamac-manager + // (PID 4321)", "un verrou résiduel..."), empty when nothing does. + static std::string describeLockHolder(const LockHolder& holder); + + // True when pacman's database is free, i.e. no lock file is present. + static bool databaseIsFree(); + + // Waits up to timeoutMs for the database to become free, so a manager that + // is finishing right now does not turn into an error dialog. + static bool waitForDatabase(int timeoutMs); + + // True when the last failed operation failed on a locked database, so the UI + // can offer the recovery without matching the (translated) message. + bool lastErrorWasLock() const { return m_lastErrorWasLock; } + + // Stops the process holding the lock — or removes a stale lock file — and + // waits for the database to become free. SIGTERM comes first so pacman can + // abort its transaction and release the lock itself; SIGKILL follows when it + // does not react. Returns false, with lastError() filled, when the lock + // outlives the attempt. + bool releaseDatabaseLock(const LockHolder& holder, + ProgressCallback progressCallback = nullptr); + // User-facing hint explaining the lock and how to recover. Checks the // lock file and other running managers on the live system. static std::string dbLockHint(); @@ -112,6 +156,13 @@ public: private: bool isPackageInstalled(const std::string& name); + // Run a one-off command (kill, rm) and return its exit status, through sudo + // with the session password when asked. Used by the lock recovery, which + // needs the status rather than the output. + int runCommand(const std::string& command, bool withSudo) const; + bool terminateProcess(int pid, const char* signal) const; + bool removeLockFile() const; + // Cache for the read-only queries several views ask for in a row: a search // runs `pacman -Q`, the Installed page runs `-Q`, `-Qi` and `-Sl`, and the // dashboard re-runs them on every visit. Without it that is a dozen @@ -134,4 +185,6 @@ private: std::string m_password; std::string m_lastError; + // Set with m_lastError when the failure was a locked database. + bool m_lastErrorWasLock = false; }; diff --git a/include/update-manager.h b/include/update-manager.h index e859c1b..c8146e9 100644 --- a/include/update-manager.h +++ b/include/update-manager.h @@ -26,11 +26,17 @@ class UpdateManager : public QObject { public: explicit UpdateManager(QObject* parent = nullptr); - // Current app version, compiled in from the repo-root `version` file (see - // CMakeLists.txt), falling back to the `version` file installed next to the - // executable when the build bypassed CMake. + // Current app version: the newest of the version compiled in from the + // repo-root `version` file (see CMakeLists.txt) and the one recorded in the + // `version` file installed next to the executable. static QString currentVersion(); + // Highest of two dotted versions. Used to reconcile the two places that know + // the version: either can lag behind (a build made without configuring + // again, or a marker left by an older install), and reporting the lower one + // would offer an already installed release for ever. + static QString newestVersion(const QString& a, const QString& b); + // Path of the state file storing the last check date and the latest // known remote version (e.g. ~/.local/share/PacManager/update-state.json). static QString stateFilePath(); diff --git a/src/main-window.cpp b/src/main-window.cpp index 905bd85..29fd01c 100644 --- a/src/main-window.cpp +++ b/src/main-window.cpp @@ -125,7 +125,20 @@ InstallWorker::InstallWorker(IPackageManager* pm, Op op, InstallWorker::InstallWorker(const std::vector& providers, Op op) : m_providers(providers), m_op(op) {} +InstallWorker::InstallWorker(PacmanManager* pacman, const PacmanManager::LockHolder& holder) + : m_op(Op::ReleaseLock), m_pacman(pacman), m_lockHolder(holder) {} + void InstallWorker::run() { + // Lock recovery bypasses the provider loop: it is one pacman-side operation + // whose progress comes back through the same signal as an install. + if (m_op == Op::ReleaseLock) { + auto cb = [this](const std::string& message, int) { + emit progress(QString::fromStdString(message)); + }; + emit finished(m_pacman && m_pacman->releaseDatabaseLock(m_lockHolder, cb)); + return; + } + bool success = true; for (IPackageManager* pm : m_providers) { // Prefix progress lines with the provider when several run at once. @@ -152,6 +165,7 @@ void InstallWorker::run() { success = pm->removePackages(m_packages, cb) && success; break; case Op::CleanCache: success = pm->cleanCache(cb) && success; break; + case Op::ReleaseLock: break; // handled before the provider loop } } emit finished(success); @@ -1469,36 +1483,121 @@ IPackageManager* MainWindow::providerFor(const std::string& id) const { bool MainWindow::showProviderError(const QString& title, IPackageManager* provider) { if (!provider) return false; - std::string err = provider->lastError(); + const std::string err = provider->lastError(); if (err.empty()) return false; - const bool dbLock = err.find("verrouillée") != std::string::npos - || err.find("db.lck") != std::string::npos; - if (!dbLock) { - QMessageBox::warning(this, title, QString::fromStdString(err)); - return false; + + // A locked database is the one failure the app can resolve on its own, so it + // gets its own dialog instead of a message the user has to act on by hand. + const bool lockFailure = + (provider == m_pacman && m_pacman && m_pacman->lastErrorWasLock()) + || PacmanManager::dbLocked(err); + if (lockFailure) return handleDatabaseLock(title); + + QMessageBox::warning(this, title, QString::fromStdString(err)); + return false; +} + +bool MainWindow::handleDatabaseLock(const QString& title) { + if (!m_pacman) return false; + + // The other manager frequently finishes while the failed operation was + // unwinding: retry straight away rather than announcing a lock that is gone. + if (PacmanManager::databaseIsFree()) { + statusBar()->showMessage("Base pacman libérée, nouvelle tentative..."); + QTimer::singleShot(0, this, [this] { retryPendingAction(); }); + return true; } - // Locked DB: explain + offer a retry, since the other manager (or stale - // lock) is often gone by the time the user clicks again. + + const PacmanManager::LockHolder holder = PacmanManager::detectLockHolder(); + const QString holderName = + QString::fromStdString(PacmanManager::describeLockHolder(holder)); + QMessageBox box(this); box.setWindowTitle(title); box.setIcon(QMessageBox::Warning); - box.setText(QString::fromStdString(err)); - box.setInformativeText("Fermez l'autre gestionnaire (ou supprimez le " - "fichier résiduel indiqué), puis réessayez."); - QPushButton* retryBtn = box.addButton("Réessayer", QMessageBox::AcceptRole); - box.addButton("Fermer", QMessageBox::RejectRole); - box.exec(); - if (box.clickedButton() == retryBtn && !m_pendingRetryAction.isEmpty()) { - const QString action = m_pendingRetryAction; - m_pendingRetryAction.clear(); - // Defer so the dialog closes before the worker touches the UI. - QTimer::singleShot(0, this, [this, action] { retryPrivilegedAction(action); }); + box.setTextFormat(Qt::RichText); + // The action only promises a resume when there is one to replay: a lock hit + // by an operation with no pending retry just needs the database freed. + const bool canRetry = !m_pendingRetryAction.isEmpty(); + const QString resume = canRetry + ? QStringLiteral(" PacManager reprendra ensuite l'opération automatiquement.") + : QString(); + + if (holder.pid > 0) { + box.setText(QString("%1 utilise déjà la base pacman.").arg(holderName)); + box.setInformativeText( + "Le fermer libère la base ; une transaction en cours sera " + "interrompue." + resume); } else { - m_pendingRetryAction.clear(); + box.setText(QString("La base pacman est verrouillée par %1.").arg(holderName)); + box.setInformativeText( + "Aucun gestionnaire ne tourne : le verrou peut être supprimé sans " + "risque." + resume); } + + QPushButton* resolveBtn = box.addButton( + holder.pid > 0 ? (canRetry ? QStringLiteral("Fermer et réessayer") + : QStringLiteral("Fermer le gestionnaire")) + : (canRetry ? QStringLiteral("Supprimer et réessayer") + : QStringLiteral("Supprimer le verrou")), + QMessageBox::AcceptRole); + QPushButton* retryBtn = + box.addButton(QStringLiteral("Réessayer"), QMessageBox::ActionRole); + box.addButton(QStringLiteral("Plus tard"), QMessageBox::RejectRole); + box.exec(); + + if (box.clickedButton() == retryBtn) { + QTimer::singleShot(0, this, [this] { retryPendingAction(); }); + return true; + } + if (box.clickedButton() != resolveBtn) { + m_pendingRetryAction.clear(); + return true; + } + + // Stopping another user's manager (or removing a root-owned lock file) needs + // the sudo password, which the session may not hold yet. + if (!ensureCredentials({m_pacman})) return true; + + // Deferred so the dialog closes before the worker touches the UI. + QTimer::singleShot(0, this, [this, holder] { startLockRecovery(holder); }); return true; } +void MainWindow::startLockRecovery(const PacmanManager::LockHolder& holder) { + if (!m_pacman) return; + + setBusy(true); + statusBar()->showMessage("Libération de la base de données pacman..."); + + auto* worker = new InstallWorker(m_pacman, holder); + connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { + statusBar()->showMessage(msg); + }); + connect(worker, &InstallWorker::finished, this, [this](bool released) { + setBusy(false); + if (!released) { + statusBar()->showMessage("Base pacman toujours verrouillée"); + QMessageBox::warning(this, "Base de données verrouillée", + QString::fromStdString(m_pacman ? m_pacman->lastError() : std::string())); + m_pendingRetryAction.clear(); + return; + } + statusBar()->showMessage("Base libérée, reprise de l'opération..."); + retryPendingAction(); + }); + connect(worker, &InstallWorker::finished, this, + [worker] { worker->wait(); worker->deleteLater(); }); + worker->start(); +} + +void MainWindow::retryPendingAction() { + if (m_pendingRetryAction.isEmpty()) return; + const QString action = m_pendingRetryAction; + m_pendingRetryAction.clear(); + retryPrivilegedAction(action); +} + void MainWindow::retryPrivilegedAction(const QString& action) { if (action == "install" && !m_selectedPackage.name.empty()) { m_pendingSelect = m_selectedPackage.name; @@ -1512,6 +1611,21 @@ void MainWindow::retryPrivilegedAction(const QString& action) { onRefresh(); } else if (action == "update" && !m_selectedPackage.name.empty()) { onUpdate(); + } else if (action == "cleanup") { + // The groups still queued are replayed; the one that failed on the lock + // is gone, and the recovery already freed the database. + std::vector providers; + for (const auto& entry : m_pendingRemovals) providers.push_back(entry.first); + if (!tryAcquireOp()) return; + if (!ensureCredentials(providers)) { + setBusy(false); + return; + } + startNextCleanupRemoval(); + } else if (action == "clean-caches") { + onCleanCaches(); + } else if (action == "install-plugin-tool") { + onInstallPluginTool(); } } @@ -2301,6 +2415,8 @@ void MainWindow::removeCleanupPackages(const std::vector& packages, return; } + // Lets a database-lock recovery re-run the removal it interrupted. + m_pendingRetryAction = "cleanup"; startNextCleanupRemoval(); } @@ -2332,18 +2448,25 @@ void MainWindow::startNextCleanupRemoval() { connect(worker, &InstallWorker::progressValue, this, &MainWindow::onInstallProgress); connect(worker, &InstallWorker::finished, this, [this, provider, packages](bool success) { - if (success) { - statusBar()->showMessage( - QString("%1 paquet(s) supprimé(s)").arg(packages.size())); - } else { - statusBar()->showMessage("Échec du nettoyage"); - showProviderError("Échec du nettoyage", provider); - } // One history row per removed package keeps the install/remove filters // of the History page meaningful. for (const auto& name : packages) { m_historyManager->record({"", "remove", name, provider->getName(), success}); } + + if (!success) { + // Stop the chain and keep the group queued, so the failure handler + // can resume the whole cleanup once the cause is gone (typically a + // locked database, freed through retryPendingAction()). + setBusy(false); + m_pendingRemovals.insert(m_pendingRemovals.begin(), {provider, packages}); + statusBar()->showMessage("Échec du nettoyage"); + showProviderError("Échec du nettoyage", provider); + return; + } + + statusBar()->showMessage( + QString("%1 paquet(s) supprimé(s)").arg(packages.size())); startNextCleanupRemoval(); }); connect(worker, &InstallWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); @@ -2377,6 +2500,7 @@ void MainWindow::onCleanCaches() { return; } + m_pendingRetryAction = "clean-caches"; statusBar()->showMessage("Nettoyage des caches..."); auto* worker = new InstallWorker(providers, InstallWorker::Op::CleanCache); @@ -2838,6 +2962,8 @@ void MainWindow::onInstallPluginTool() { if (installHint.empty()) return; if (!ensureCredentials({m_pacman})) return; + // Lets a database-lock recovery re-run the tool installation. + m_pendingRetryAction = "install-plugin-tool"; setBusy(true); statusBar()->showMessage( QString("Installation de l'outil %1...").arg(QString::fromStdString(installHint))); diff --git a/src/pacman-manager.cpp b/src/pacman-manager.cpp index 3ab41e5..8fb8797 100644 --- a/src/pacman-manager.cpp +++ b/src/pacman-manager.cpp @@ -1,5 +1,8 @@ #include "pacman-manager.h" #include +#include +#include +#include #include #include #include @@ -7,9 +10,11 @@ #include #include #include +#include #include #include #include +#include // Helper to run shell commands and capture output static std::string exec(const char* cmd) { @@ -112,6 +117,23 @@ static int percentFromLine(const std::string& line) { } } +// pacman's database lock file. Every manager that goes through libalpm (pacman, +// pamac, octopi, the AUR helpers) takes it for the duration of a transaction. +static const char* kLockFilePath = "/var/lib/pacman/db.lck"; + +// Processes that take that lock, used as a fallback when /proc cannot tell us +// who does (the fd table of a root-owned process is not readable by a normal +// user, which is exactly the "sudo pacman in another terminal" case). +static const char* kKnownLockUsers[] = { + "pacman", "pamac", "pamac-manager", "yay", "paru", "pikaur", + "octopi", "octopi-helper", "discover", +}; + +// How long the recovery waits for a SIGTERM-ed manager to release the lock +// before forcing it, then for the forced stop to take effect. +static constexpr int kTerminateGraceMs = 8000; +static constexpr int kKillGraceMs = 3000; + // Read-only pacman output is reused by several views within a few seconds, so // it is cached for this long. Short enough that a package installed outside the // app still appears almost immediately, and every mutating operation drops the @@ -228,6 +250,7 @@ bool PacmanManager::install(const std::string& packageName, return false; } if (dbLocked(output)) { + m_lastErrorWasLock = true; m_lastError = dbLockHint(); return false; } @@ -244,12 +267,14 @@ bool PacmanManager::remove(const std::string& packageName, execPrivileged("pacman -R --noconfirm " + packageName, m_password, progressCallback); m_lastError.clear(); + m_lastErrorWasLock = false; if (authFailed(output)) { clearPassword(); m_lastError = "Échec d'authentification sudo."; return false; } if (dbLocked(output)) { + m_lastErrorWasLock = true; m_lastError = dbLockHint(); return false; } @@ -271,12 +296,14 @@ bool PacmanManager::update(const std::string& packageName, } m_lastError.clear(); + m_lastErrorWasLock = false; if (authFailed(output)) { clearPassword(); m_lastError = "Échec d'authentification sudo."; return false; } if (dbLocked(output)) { + m_lastErrorWasLock = true; m_lastError = dbLockHint(); return false; } @@ -365,12 +392,14 @@ bool PacmanManager::removePackages(const std::vector& packages, std::string output = execPrivileged(command, m_password, progressCallback); m_lastError.clear(); + m_lastErrorWasLock = false; if (authFailed(output)) { clearPassword(); m_lastError = "Échec d'authentification sudo."; return false; } if (dbLocked(output)) { + m_lastErrorWasLock = true; m_lastError = dbLockHint(); return false; } @@ -395,12 +424,14 @@ bool PacmanManager::cleanCache(ProgressCallback progressCallback) { execPrivileged(cleanCacheCommand(paccache), m_password, progressCallback); m_lastError.clear(); + m_lastErrorWasLock = false; if (authFailed(output)) { clearPassword(); m_lastError = "Échec d'authentification sudo."; return false; } if (dbLocked(output)) { + m_lastErrorWasLock = true; m_lastError = dbLockHint(); return false; } @@ -422,12 +453,14 @@ bool PacmanManager::refresh(ProgressCallback progressCallback) { execPrivileged("pacman -Sy --noconfirm", m_password, progressCallback); m_lastError.clear(); + m_lastErrorWasLock = false; if (authFailed(output)) { clearPassword(); m_lastError = "Échec d'authentification sudo."; return false; } if (dbLocked(output)) { + m_lastErrorWasLock = true; m_lastError = dbLockHint(); return false; } @@ -613,6 +646,193 @@ bool PacmanManager::authFailed(const std::string& output) { // True when pacman refused to run because its database is locked // (/var/lib/pacman/db.lck): another pacman/pamac/yay run is in progress, or // a previous run crashed without releasing the lock. +// Name of a process as the user recognizes it (/proc//comm). +static std::string processName(int pid) { + std::ifstream comm("/proc/" + std::to_string(pid) + "/comm"); + std::string name; + std::getline(comm, name); + while (!name.empty() && (name.back() == '\n' || name.back() == ' ')) { + name.pop_back(); + } + return name; +} + +// Parent of a process (/proc//stat, 4th field); 0 when unknown. +static int parentPid(int pid) { + std::ifstream stat("/proc/" + std::to_string(pid) + "/stat"); + std::string line; + if (!std::getline(stat, line)) return 0; + + // The command name is parenthesised and may itself contain spaces, so the + // fields after it are read from the last closing parenthesis. + const size_t close = line.rfind(')'); + if (close == std::string::npos) return 0; + std::istringstream rest(line.substr(close + 1)); + std::string state; + int ppid = 0; + rest >> state >> ppid; + return ppid; +} + +// True when this process is keeping `path` open. Nothing takes a lock without +// opening it, so the fd table answers the question directly — and it names the +// exact process, even one we do not know about (a wrapper script, `sh -c`). +static bool processHoldsFile(int pid, const std::string& path) { + std::error_code listingError; + auto it = std::filesystem::directory_iterator( + "/proc/" + std::to_string(pid) + "/fd", listingError); + const auto end = std::filesystem::directory_iterator(); + for (; it != end; it.increment(listingError)) { + std::error_code linkError; + const std::filesystem::path target = + std::filesystem::read_symlink(it->path(), linkError); + if (!linkError && target == path) return true; + if (listingError) break; + } + return false; +} + +// First pid running `name`, excluding this process and its direct children: a +// pacman we launched ourselves is not "another manager". +static int pgrepPid(const std::string& name) { + const std::string output = + exec(("pgrep -x " + shellQuote(name) + " 2>/dev/null").c_str()); + const int self = static_cast(getpid()); + + std::istringstream iss(output); + std::string line; + while (std::getline(iss, line)) { + if (line.empty()) continue; + const int pid = std::atoi(line.c_str()); + if (pid <= 0 || pid == self) continue; + if (parentPid(pid) == self) continue; + return pid; + } + return 0; +} + +int PacmanManager::lockHolderPid(const std::string& path) { + std::error_code error; + for (const auto& entry : std::filesystem::directory_iterator("/proc", error)) { + const std::string name = entry.path().filename().string(); + if (name.empty() || !std::isdigit(static_cast(name[0]))) continue; + const int pid = std::atoi(name.c_str()); + if (pid <= 0 || pid == static_cast(getpid())) continue; + if (processHoldsFile(pid, path)) return pid; + } + return 0; +} + +PacmanManager::LockHolder PacmanManager::detectLockHolder() { + LockHolder holder; + std::error_code error; + holder.lockFilePresent = std::filesystem::exists(kLockFilePath, error); + if (!holder.lockFilePresent) return holder; + + holder.pid = lockHolderPid(kLockFilePath); + if (holder.pid > 0) { + holder.name = processName(holder.pid); + return holder; + } + + for (const char* tool : kKnownLockUsers) { + const int pid = pgrepPid(tool); + if (pid <= 0) continue; + holder.pid = pid; + holder.name = tool; + return holder; + } + + // Nobody holds it: the file is left over from a run that never finished. + holder.stale = true; + return holder; +} + +std::string PacmanManager::describeLockHolder(const LockHolder& holder) { + if (holder.pid > 0) { + const std::string name = holder.name.empty() ? "processus inconnu" : holder.name; + return name + " (PID " + std::to_string(holder.pid) + ")"; + } + if (holder.stale) { + return "un verrou résiduel laissé par un gestionnaire interrompu"; + } + return {}; +} + +bool PacmanManager::databaseIsFree() { + std::error_code error; + return !std::filesystem::exists(kLockFilePath, error); +} + +bool PacmanManager::waitForDatabase(int timeoutMs) { + constexpr int kStepMs = 250; + for (int waited = 0; waited <= timeoutMs; waited += kStepMs) { + if (databaseIsFree()) return true; + std::this_thread::sleep_for(std::chrono::milliseconds(kStepMs)); + } + return databaseIsFree(); +} + +int PacmanManager::runCommand(const std::string& command, bool withSudo) const { + std::string full = command; + if (withSudo) { + full = "printf '%s\\n' " + shellQuote(m_password) + " | sudo -S " + command; + } + return system((full + " > /dev/null 2>&1").c_str()); +} + +bool PacmanManager::terminateProcess(int pid, const char* signal) const { + const std::string command = + "kill -" + std::string(signal) + " " + std::to_string(pid); + if (runCommand(command, /*withSudo=*/false) == 0) return true; + // The holder belongs to another user (a manager started with sudo in a + // terminal): only the session password can reach it. + return hasPassword() && runCommand(command, /*withSudo=*/true) == 0; +} + +bool PacmanManager::removeLockFile() const { + const std::string command = std::string("rm -f ") + kLockFilePath; + if (runCommand(command, /*withSudo=*/false) == 0 && databaseIsFree()) return true; + return hasPassword() && runCommand(command, /*withSudo=*/true) == 0 + && databaseIsFree(); +} + +bool PacmanManager::releaseDatabaseLock(const LockHolder& holder, + ProgressCallback progressCallback) { + m_lastError.clear(); + m_lastErrorWasLock = false; + + if (holder.pid > 0) { + const std::string who = describeLockHolder(holder); + if (progressCallback) progressCallback("Arrêt de " + who + "...", -1); + + if (!terminateProcess(holder.pid, "TERM")) { + m_lastError = "Impossible d'arrêter " + who + + " : droits insuffisants pour le faire depuis " + "PacManager."; + return false; + } + + if (!waitForDatabase(kTerminateGraceMs)) { + if (progressCallback) { + progressCallback(who + " ne répond pas, arrêt forcé...", -1); + } + terminateProcess(holder.pid, "KILL"); + waitForDatabase(kKillGraceMs); + } + if (databaseIsFree()) return true; + } + + // No process left to stop (or it would not die): the lock file itself is + // what keeps the database closed. + if (progressCallback) progressCallback("Suppression du verrou résiduel...", -1); + if (removeLockFile()) return true; + + m_lastError = "La base pacman est toujours verrouillée : droits insuffisants " + "pour supprimer le verrou."; + return false; +} + bool PacmanManager::dbLocked(const std::string& output) { return output.find("could not lock database") != std::string::npos || output.find("unable to lock database") != std::string::npos diff --git a/src/update-manager.cpp b/src/update-manager.cpp index a698e78..9353bbc 100644 --- a/src/update-manager.cpp +++ b/src/update-manager.cpp @@ -51,21 +51,28 @@ UpdateManager::UpdateManager(QObject* parent) : QObject(parent) { }); } -QString UpdateManager::currentVersion() { - // The compiled-in version wins: it describes the code that is actually - // running, so a `version` file left behind (or never refreshed) by an - // update cannot make the app re-offer a release it already installed. - QString version = QStringLiteral(FWSPACMANAGE_VERSION).trimmed(); +QString UpdateManager::newestVersion(const QString& a, const QString& b) { + // isNewerVersion() also normalises a leading "v", so "v1.4.1" wins over + // "1.3.1" and an empty side always loses. + return isNewerVersion(b, a) ? b : a; +} - // Fallback for builds that bypass CMake: the `version` file installed next - // to the executable. - if (version.isEmpty()) { - QFile f(QCoreApplication::applicationDirPath() + "/version"); - if (f.open(QIODevice::ReadOnly | QIODevice::Text)) { - version = QString::fromUtf8(f.readAll()).trimmed(); - } +QString UpdateManager::currentVersion() { + // Two places know the version, and either can lag behind: the version + // compiled into the binary (a build made without configuring again keeps the + // previous one) and the marker installed next to the executable (an install + // made before an update left the old one behind). Reporting the lower of the + // two would offer an already installed release again at every launch, so the + // newest one known wins. + const QString compiled = QStringLiteral(FWSPACMANAGE_VERSION).trimmed(); + + QString installed; + QFile file(QCoreApplication::applicationDirPath() + "/version"); + if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { + installed = QString::fromUtf8(file.readAll()).trimmed(); } + const QString version = newestVersion(compiled, installed); return version.isEmpty() ? QStringLiteral("1.0.0") : version; } diff --git a/tests/pacman-manager.test.cpp b/tests/pacman-manager.test.cpp index d145542..5b1762e 100644 --- a/tests/pacman-manager.test.cpp +++ b/tests/pacman-manager.test.cpp @@ -1,6 +1,13 @@ #include "pacman-manager.h" #include +#include #include +#include +#include + +#include +#include +#include static void testParseInstalledOutput_parsesSimpleLines() { std::string output = "firefox 128.0\nvim 9.1.0000\n"; @@ -183,6 +190,61 @@ static void testAuthFailed_ignoresPacmanErrors() { assert(!PacmanManager::authFailed("warning: firefox is up to date")); } +// The lock dialog names the process that holds pacman's database, so the +// description has to cover the three states the detection can report. +static void testDescribeLockHolder() { + PacmanManager::LockHolder holder; + assert(PacmanManager::describeLockHolder(holder).empty()); + + holder.lockFilePresent = true; + holder.stale = true; + assert(PacmanManager::describeLockHolder(holder).find("résiduel") + != std::string::npos); + + holder.stale = false; + holder.pid = 4321; + holder.name = "pamac-manager"; + assert(PacmanManager::describeLockHolder(holder) == "pamac-manager (PID 4321)"); + + // A process whose name could not be read is still worth reporting. + holder.name.clear(); + assert(PacmanManager::describeLockHolder(holder).find("4321") != std::string::npos); +} + +// Detection must name the process actually holding the file open, the way +// pacman keeps db.lck during a transaction. +static void testLockHolderPid_findsTheHolder() { + char pathTemplate[] = "/tmp/pacmanager-lock-test-XXXXXX"; + const int fd = mkstemp(pathTemplate); + assert(fd >= 0); + close(fd); + const std::string lockPath = pathTemplate; + + const pid_t pid = fork(); + if (pid == 0) { + // Child: hold the file open, exactly like a running transaction does. + const std::string script = "exec 9<'" + lockPath + "'; sleep 30"; + execl("/bin/sh", "sh", "-c", script.c_str(), static_cast(nullptr)); + _exit(127); + } + assert(pid > 0); + + // The child needs a moment to reach the redirection. + int found = 0; + for (int attempt = 0; attempt < 50 && found != static_cast(pid); ++attempt) { + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + found = PacmanManager::lockHolderPid(lockPath); + } + assert(found == static_cast(pid)); + + kill(pid, SIGTERM); + waitpid(pid, nullptr, 0); + + // Nobody holds it any more: that is what makes the lock look stale. + assert(PacmanManager::lockHolderPid(lockPath) == 0); + unlink(lockPath.c_str()); +} + static void testDbLocked_detectsEnglishLock() { assert(PacmanManager::dbLocked( "error: failed to synchronize all databases (unable to lock database)")); @@ -238,6 +300,9 @@ int main() { testAuthFailed_detectsMissingPassword(); testAuthFailed_ignoresPacmanErrors(); + testDescribeLockHolder(); + testLockHolderPid_findsTheHolder(); + testDbLocked_detectsEnglishLock(); testDbLocked_detectsFrenchLock(); testDbLocked_detectsLockFile(); diff --git a/tests/update-manager.test.cpp b/tests/update-manager.test.cpp index f61182c..ccc468d 100644 --- a/tests/update-manager.test.cpp +++ b/tests/update-manager.test.cpp @@ -119,12 +119,30 @@ static void testChooseMethod_noneWhenNothingAvailable() { "method_none_without_anything"); } -// The version the app reports is the one compiled into it, so a stale `version` -// file next to the executable can never make it re-offer an installed update. -static void testCurrentVersion_isCompiledIn() { - check(UpdateManager::currentVersion() == QStringLiteral(FWSPACMANAGE_VERSION), - "current_version_compiled_in"); - check(!UpdateManager::currentVersion().isEmpty(), "current_version_not_empty"); +// Reconciliation of the two sources of truth: whichever is ahead wins, an empty +// side never does. This is what stops a release from being offered again when the +// binary and the installed marker disagree. +static void testNewestVersion() { + check(UpdateManager::newestVersion("1.3.1", "1.4.1") == "1.4.1", + "newest_installed_ahead"); + check(UpdateManager::newestVersion("1.4.1", "1.3.1") == "1.4.1", + "newest_compiled_ahead"); + check(UpdateManager::newestVersion("1.4.1", "1.4.1") == "1.4.1", "newest_equal"); + check(UpdateManager::newestVersion("v1.4.1", "1.3.1") == "v1.4.1", + "newest_tag_prefix"); + check(UpdateManager::newestVersion("", "1.3.1") == "1.3.1", "newest_empty_compiled"); + check(UpdateManager::newestVersion("1.3.1", "") == "1.3.1", "newest_empty_installed"); + check(UpdateManager::newestVersion("1.10.0", "1.9.9") == "1.10.0", + "newest_minor_beats_patch"); +} + +// Whatever sits next to the test binary, the reported version never goes +// backwards relative to the one compiled into it. +static void testCurrentVersion_neverOlderThanCompiled() { + const QString reported = UpdateManager::currentVersion(); + check(!reported.isEmpty(), "current_version_not_empty"); + check(!UpdateManager::isNewerVersion(QStringLiteral(FWSPACMANAGE_VERSION), reported), + "current_version_not_older_than_compiled"); } // The staged install must replace an executable that is currently running, @@ -296,7 +314,8 @@ int main() { check(UpdateManager::isNewerVersion("", "1.3.1") == false, "empty_remote"); // Reported version - testCurrentVersion_isCompiledIn(); + testNewestVersion(); + testCurrentVersion_neverOlderThanCompiled(); // Update-strategy choice testChooseMethod_checkoutWinsOverEverything(); diff --git a/version b/version index 6261a05..347f583 100644 --- a/version +++ b/version @@ -1 +1 @@ -1.3.1 \ No newline at end of file +1.4.1