diff --git a/README.en.md b/README.en.md index 4563f1a..ce2132c 100644 --- a/README.en.md +++ b/README.en.md @@ -135,7 +135,7 @@ The method is picked automatically (no configuration): 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. Restart the application to activate the new version. +by root. PacManager then restarts automatically on the new version. ## Graphical interface diff --git a/README.md b/README.md index bb8d328..63cbf9e 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,8 @@ La méthode est choisie automatiquement (aucune configuration) : Tout se compile dans un dossier temporaire : seul le remplacement final du binaire (et des plugins) demande `sudo`, et uniquement si le dossier cible -appartient à root. Redémarrez l'application pour activer la nouvelle version. +appartient à root. PacManager redémarre ensuite automatiquement sur la nouvelle +version. ## Interface graphique diff --git a/include/update-manager.h b/include/update-manager.h index 7724c30..f2c879a 100644 --- a/include/update-manager.h +++ b/include/update-manager.h @@ -18,7 +18,8 @@ // into ~/.local/share/PacManager/src, built, and installed in place; // - Prebuilt: the release's prebuilt archive is unpacked (no compiler); // - Tarball: the release sources are built and installed in place. -// The running binary stays untouched until the next launch. +// The running binary stays untouched (it keeps the inode that was replaced on +// disk); the UI hands over to the freshly installed build by relaunching it. class UpdateManager : public QObject { Q_OBJECT public: @@ -66,6 +67,14 @@ public: // new binary here (in place), so it works whatever the layout on disk. QString binDir() const; + // Path of the freshly installed binary to hand over to after a successful + // update, or empty when `binDir` holds no runnable binary (the caller then + // falls back to asking for a manual restart). The running process still + // maps the replaced inode, so starting this file is the only way to pick up + // the new build without a manual restart. Static and parameterised so it + // can be unit-tested without performing an update. + static QString restartProgram(const QString& binDir); + // Persistent source clone used to update an installed app that has no // local checkout (~/.local/share/PacManager/src). The first update clones, // later ones fast-forward to the latest main. @@ -94,6 +103,16 @@ public: // the "update available" dialog. static QString methodDescription(UpdateMethod method, const QString& targetDir); + // Shell script that installs a staged tree (`$STAGE/bin`, plugins under + // `$STAGE/bin/plugins` or `$STAGE/plugins`) into the running binary's + // directory (`$BIN_DIR`), both taken from the environment. Each file is + // copied to a sibling temp file and renamed into place, so the install + // also works when the target is the executable (or plugin) currently in + // use, where a plain `cp` fails with ETXTBSY ("Text file busy"). + // Exposed so the unit test can drive it against a genuinely running + // binary. + static QString stagedInstallScript(); + // Whether a self-update is possible with the current state. bool canSelfUpdate() const; diff --git a/src/main-window.cpp b/src/main-window.cpp index 70cb968..76ed3f9 100644 --- a/src/main-window.cpp +++ b/src/main-window.cpp @@ -32,6 +32,8 @@ #include #include #include +#include +#include #include "app-logging.h" @@ -2555,8 +2557,8 @@ void MainWindow::onUpdateCheckFinished(bool hasUpdate, const QString& latestVers // Ask the user whether to update now or skip. The update runs in the // background (git pull from a checkout, clone + rebuild, prebuilt unpack, - // or tarball rebuild); the running binary stays untouched until the next - // launch. + // or tarball rebuild); the running binary stays untouched and the app + // hands over to the new build once the update succeeds. const UpdateManager::UpdateMethod method = m_updateManager->updateMethod(); const QString targetDir = m_updateManager->binDir(); @@ -2613,21 +2615,41 @@ void MainWindow::onUpdateCheckFinished(bool hasUpdate, const QString& latestVers m_updateManager->performSelfUpdate(sudoPassword); } -// Called when the background git pull + build finishes. Reports the result in -// a dialog so the user knows whether to restart the app. +// Called when the background git pull + build finishes. A success hands over to +// the freshly installed binary right away; a failure is reported in a dialog. void MainWindow::onSelfUpdateFinished(bool success, const QString& message) { disconnect(m_updateManager, &UpdateManager::selfUpdateFinished, this, &MainWindow::onSelfUpdateFinished); - if (success) { - QMessageBox::information(this, "Mise à jour terminée", - QString("

PacManager a été mis à jour

" - "

La nouvelle version sera active au prochain démarrage.

" - "
%1
") - .arg(message.toHtmlEscaped())); - } else { + if (!success) { QMessageBox::warning(this, "Échec de la mise à jour", QString("

La mise à jour a échoué :

%1
") .arg(message.toHtmlEscaped())); + return; } + + // The build log is no longer shown to the user, so keep it in the app log + // for troubleshooting. + qCInfo(pacmgrUpdate) << "self-update output:" << message; + + // Restarting is the only way to run the new build: this process still maps + // the inode that was replaced on disk. Ask for a manual restart only when + // no runnable binary is there to hand over to. + const QString program = UpdateManager::restartProgram(m_updateManager->binDir()); + if (!program.isEmpty() + && QProcess::startDetached(program, QCoreApplication::arguments().mid(1))) { + qCInfo(pacmgrUpdate) << "update installed, relaunching" << program; + statusBar()->showMessage("Mise à jour terminée, redémarrage de PacManager..."); + // Quit on the next event-loop pass so the message paints first. The new + // process is detached and outlives this one. + QTimer::singleShot(0, qApp, &QCoreApplication::quit); + return; + } + + qCWarning(pacmgrUpdate) << "could not relaunch" << program; + QMessageBox::information(this, "Mise à jour terminée", + QString("

PacManager a été mis à jour

" + "

La nouvelle version sera active au prochain démarrage.

" + "
%1
") + .arg(message.toHtmlEscaped())); } diff --git a/src/update-manager.cpp b/src/update-manager.cpp index 38576bc..14ae819 100644 --- a/src/update-manager.cpp +++ b/src/update-manager.cpp @@ -131,6 +131,20 @@ QString UpdateManager::binDir() const { return QCoreApplication::applicationDirPath(); } +// The install step always writes /PacManager (CMake appends .exe on +// Windows), whatever name the running copy was launched under. +QString UpdateManager::restartProgram(const QString& binDir) { + if (binDir.isEmpty()) return {}; +#ifdef Q_OS_WIN + const QString name = QStringLiteral("PacManager.exe"); +#else + const QString name = QStringLiteral("PacManager"); +#endif + const QFileInfo info(QDir(binDir).filePath(name)); + if (!info.exists() || !info.isExecutable()) return {}; + return info.absoluteFilePath(); +} + // ~/.local/share/PacManager/src (honouring XDG_DATA_HOME): the same user data // directory as the drop-in plugins, so it is writable and independent of where // the binary itself lives. @@ -189,23 +203,23 @@ QString UpdateManager::methodDescription(UpdateMethod method, const QString& tar case UpdateMethod::Checkout: return QStringLiteral( "La mise à jour va récupérer le code (git pull), recompiler et " - "réinstaller.\nRedémarrez PacManager ensuite pour utiliser la " - "nouvelle version."); + "réinstaller.\nPacManager redémarrera automatiquement pour " + "utiliser la nouvelle version."); case UpdateMethod::Clone: return QStringLiteral( "La mise à jour va cloner (puis mettre à jour) le dépôt source " - "et recompiler l'application dans %1.\nRedémarrez PacManager " - "ensuite pour utiliser la nouvelle version.").arg(targetDir); + "et recompiler l'application dans %1.\nPacManager redémarrera " + "automatiquement pour utiliser la nouvelle version.").arg(targetDir); case UpdateMethod::Prebuilt: return QStringLiteral( "La mise à jour va télécharger la version précompilée et " - "l'installer dans %1 (sans compilation).\nRedémarrez PacManager " - "ensuite pour utiliser la nouvelle version.").arg(targetDir); + "l'installer dans %1 (sans compilation).\nPacManager redémarrera " + "automatiquement pour utiliser la nouvelle version.").arg(targetDir); case UpdateMethod::Tarball: return QStringLiteral( "La mise à jour va télécharger les sources, les compiler et " - "installer l'application dans %1.\nRedémarrez PacManager " - "ensuite pour utiliser la nouvelle version.").arg(targetDir); + "installer l'application dans %1.\nPacManager redémarrera " + "automatiquement pour utiliser la nouvelle version.").arg(targetDir); case UpdateMethod::None: return QStringLiteral( "Le dépôt source n'est pas disponible sur ce système. " @@ -367,9 +381,9 @@ bool UpdateManager::isNewerVersion(const QString& remote, const QString& local) } // Rebuilds + reinstalls the app in the background, using the strategy picked -// by updateMethod(). The new binary takes effect at the next launch; the -// running process is untouched. Exits non-zero on failure so the caller can -// report it. +// by updateMethod(). The running process is untouched (it keeps the replaced +// inode); the caller relaunches into the new build. Exits non-zero on failure +// so the caller can report it. void UpdateManager::performSelfUpdate(const QString& sudoPassword) { const UpdateMethod method = updateMethod(); qCInfo(pacmgrUpdate) << "starting self-update, method" @@ -409,7 +423,7 @@ void UpdateManager::performCheckoutUpdate() { " cmake --build build -j$(nproc) 2>&1\n" "fi\n" "cmake --install build 2>&1\n" - "echo 'Mise a jour terminee. Redemarrez PacManager pour utiliser la nouvelle version.'"); + "echo 'Mise a jour terminee.'"); runShell(script, m_repoPath); } @@ -431,18 +445,38 @@ QString UpdateManager::installedScriptPrologue() const { // Copies a staged install tree ($STAGE/bin, plugins under bin/plugins or // plugins/ depending on the source) into the running binary's directory. -static QString stagedCopyAction() { +// +// Every file goes through a sibling temp file + rename instead of a direct +// `cp`: the update replaces the very binary (and the plugins) the running +// process has open, and Linux refuses to open a file being executed for +// writing (ETXTBSY, "Text file busy"). rename(2) only swaps the directory +// entry, so the running process keeps its old inode and the next launch picks +// up the new build. The temp name is fixed, so a failed copy is overwritten by +// the next attempt instead of piling up in the target directory. +QString UpdateManager::stagedInstallScript() { return QStringLiteral( "set -e\n" + "umask 022\n" // installed files keep their source mode (binary stays executable) + "install_file() {\n" + " TMP=\"$2.new\"\n" + " rm -f \"$TMP\"\n" + " cp \"$1\" \"$TMP\"\n" + " mv -f \"$TMP\" \"$2\"\n" + "}\n" "mkdir -p \"$BIN_DIR\"\n" - "cp \"$STAGE/bin/PacManager\" \"$BIN_DIR/PacManager\"\n" - "if [ -f \"$STAGE/bin/version\" ]; then cp \"$STAGE/bin/version\" \"$BIN_DIR/version\"; fi\n" + "install_file \"$STAGE/bin/PacManager\" \"$BIN_DIR/PacManager\"\n" + "if [ -f \"$STAGE/bin/version\" ]; then\n" + " install_file \"$STAGE/bin/version\" \"$BIN_DIR/version\"\n" + "fi\n" "if [ -d \"$STAGE/bin/plugins\" ]; then SRC_PLUGINS=\"$STAGE/bin/plugins\";\n" "elif [ -d \"$STAGE/plugins\" ]; then SRC_PLUGINS=\"$STAGE/plugins\";\n" "else SRC_PLUGINS=\"\"; fi\n" "if [ -n \"$SRC_PLUGINS\" ]; then\n" " mkdir -p \"$BIN_DIR/plugins\"\n" - " cp \"$SRC_PLUGINS/\"*.so \"$BIN_DIR/plugins/\" 2>/dev/null || true\n" + " for SO in \"$SRC_PLUGINS\"/*.so; do\n" + " [ -e \"$SO\" ] || continue\n" + " install_file \"$SO\" \"$BIN_DIR/plugins/$(basename \"$SO\")\"\n" + " done\n" "fi\n"); } @@ -505,9 +539,9 @@ void UpdateManager::performCloneUpdate(const QString& sudoPassword) { "cmake --build \"$SRC/build\" -j$(nproc) 2>&1\n" "cmake --install \"$SRC/build\" --prefix \"$STAGE\" 2>&1\n") .arg(quoteShell(sourceClonePath()), quoteShell(QString::fromLatin1(kRepoUrl))); - script += installCommand(quotedPassword(sudoPassword), stagedCopyAction()); + script += installCommand(quotedPassword(sudoPassword), stagedInstallScript()); script += QStringLiteral( - "echo 'Mise a jour terminee. Redemarrez PacManager pour utiliser la nouvelle version.'"); + "echo 'Mise a jour terminee.'"); runShell(script, QDir::homePath()); } @@ -527,9 +561,9 @@ void UpdateManager::performPrebuiltUpdate(const QString& sudoPassword) { "export STAGE\n" "[ -x \"$STAGE/bin/PacManager\" ] || { echo 'Archive invalide'; exit 1; }\n") .arg(quoteShell(m_prebuiltUrl)); - script += installCommand(quotedPassword(sudoPassword), stagedCopyAction()); + script += installCommand(quotedPassword(sudoPassword), stagedInstallScript()); script += QStringLiteral( - "echo 'Mise a jour terminee. Redemarrez PacManager pour utiliser la nouvelle version.'"); + "echo 'Mise a jour terminee.'"); runShell(script, QDir::homePath()); } @@ -558,8 +592,8 @@ void UpdateManager::performTarballUpdate(const QString& sudoPassword) { "cmake --build \"$WORK/build\" -j$(nproc) 2>&1\n" "cmake --install \"$WORK/build\" --prefix \"$STAGE\" 2>&1\n") .arg(quoteShell(m_tarballUrl)); - script += installCommand(quotedPassword(sudoPassword), stagedCopyAction()); + script += installCommand(quotedPassword(sudoPassword), stagedInstallScript()); script += QStringLiteral( - "echo 'Mise a jour terminee. Redemarrez PacManager pour utiliser la nouvelle version.'"); + "echo 'Mise a jour terminee.'"); runShell(script, QDir::homePath()); } \ No newline at end of file diff --git a/tests/update-manager.test.cpp b/tests/update-manager.test.cpp index a87f902..d760574 100644 --- a/tests/update-manager.test.cpp +++ b/tests/update-manager.test.cpp @@ -1,9 +1,17 @@ -// Unit tests for the pure parts of UpdateManager: version comparison and the -// update-strategy choice (no network, toolchain or filesystem needed). +// Unit tests for UpdateManager: version comparison, the update-strategy choice +// (pure logic), and the staged install script (run for real against a running +// binary, no network or toolchain needed). #include #include +#include +#include +#include +#include +#include #include +#include +#include #include "update-manager.h" @@ -18,6 +26,20 @@ static void check(bool cond, const char* name) { } } +static bool writeFile(const QString& path, const QByteArray& content) { + QFile f(path); + if (!f.open(QIODevice::WriteOnly)) return false; + return f.write(content) == content.size(); +} + +// Byte-for-byte comparison: enough to tell a replaced file from the original. +static bool sameFileContent(const QString& a, const QString& b) { + QFile fa(a); + QFile fb(b); + if (!fa.open(QIODevice::ReadOnly) || !fb.open(QIODevice::ReadOnly)) return false; + return fa.readAll() == fb.readAll(); +} + using Caps = UpdateManager::UpdateCapabilities; using Method = UpdateManager::UpdateMethod; @@ -91,6 +113,113 @@ static void testChooseMethod_noneWhenNothingAvailable() { "method_none_without_anything"); } +// The staged install must replace an executable that is currently running, +// which is exactly the situation of the app updating itself: opening the busy +// file for writing fails with ETXTBSY ("Text file busy"), so the script copies +// to a sibling temp file and renames it over the target instead. +// Unix-only: it needs /bin/sh and exec semantics, and /bin/sleep as a known +// long-lived program. +#if !defined(Q_OS_WIN) +static void testStagedInstall_replacesRunningExecutable() { + QTemporaryDir tmp; + check(tmp.isValid(), "staged_install_tmpdir"); + if (!tmp.isValid()) return; + + const QString binDir = tmp.path() + "/bin"; + const QString stage = tmp.path() + "/stage"; + QDir().mkpath(binDir + "/plugins"); + QDir().mkpath(stage + "/bin/plugins"); + + // Seed the target with a long-lived executable and start it, so the + // destination really is "text busy" for the whole duration of the test. + const QString target = binDir + "/PacManager"; + check(QFile::copy("/bin/sleep", target), "staged_install_seed_binary"); + + QProcess running; + running.start(target, {"30"}); + check(running.waitForStarted(5000), "staged_install_binary_running"); + + // Staged tree: a different binary, a plugin and the version file. + check(QFile::copy("/bin/echo", stage + "/bin/PacManager"), + "staged_install_stage_binary"); + check(writeFile(stage + "/bin/version", "9.9.9"), + "staged_install_stage_version"); + check(writeFile(stage + "/bin/plugins/fake-provider.so", "plugin-bytes"), + "staged_install_stage_plugin"); + + QProcess sh; + QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); + env.insert("BIN_DIR", binDir); + env.insert("STAGE", stage); + sh.setProcessEnvironment(env); + sh.start("/bin/sh", {"-c", UpdateManager::stagedInstallScript()}); + const bool finished = sh.waitForFinished(15000); + const int exitCode = sh.exitCode(); + if (!finished || exitCode != 0) { + std::cout << " sh output: " << sh.readAllStandardOutput().constData() + << sh.readAllStandardError().constData() << std::endl; + } + check(finished && sh.exitStatus() == QProcess::NormalExit && exitCode == 0, + "staged_install_exit_zero"); + + check(sameFileContent(target, stage + "/bin/PacManager"), + "staged_install_binary_replaced"); + check(sameFileContent(binDir + "/version", stage + "/bin/version"), + "staged_install_version_replaced"); + check(sameFileContent(binDir + "/plugins/fake-provider.so", + stage + "/bin/plugins/fake-provider.so"), + "staged_install_plugin_replaced"); + + // The temporary copy must not survive in the target directory. + check(QDir(binDir).entryList(QStringList() << "*.new", QDir::Files).isEmpty(), + "staged_install_no_leftover_temp"); + + // The process started before the install still runs on its old inode, which + // is what makes the replacement safe for the running app. + check(running.state() == QProcess::Running, "staged_install_old_process_alive"); + + running.kill(); + running.waitForFinished(2000); +} +#endif // !Q_OS_WIN + +// The restart after a successful update must point at the binary the update +// just installed, and must refuse to launch anything that is missing or not +// runnable (the caller then asks for a manual restart instead). +static void testRestartProgram_findsInstalledBinary() { + QTemporaryDir tmp; + check(tmp.isValid(), "restart_program_tmpdir"); + if (!tmp.isValid()) return; + + // Nothing installed yet, or no directory at all: nowhere to hand over to. + check(UpdateManager::restartProgram(tmp.path()).isEmpty(), + "restart_program_absent"); + check(UpdateManager::restartProgram(QString()).isEmpty(), + "restart_program_empty_bindir"); + +#ifdef Q_OS_WIN + const QString name = QStringLiteral("PacManager.exe"); +#else + const QString name = QStringLiteral("PacManager"); +#endif + const QString target = tmp.path() + "/" + name; + check(writeFile(target, "#!/bin/sh\nexit 0\n"), "restart_program_write"); + + // Present but not runnable: still not something to launch. Windows derives + // executability from the .exe suffix, hence the guard. +#if !defined(Q_OS_WIN) + QFile::setPermissions(target, QFileDevice::ReadOwner | QFileDevice::WriteOwner); + check(UpdateManager::restartProgram(tmp.path()).isEmpty(), + "restart_program_not_executable"); +#endif + + QFile::setPermissions(target, QFileDevice::ReadOwner | QFileDevice::WriteOwner + | QFileDevice::ExeOwner); + check(UpdateManager::restartProgram(tmp.path()) + == QFileInfo(target).absoluteFilePath(), + "restart_program_found"); +} + int main() { // Basic ordering check(UpdateManager::isNewerVersion("1.3.2", "1.3.1") == true, "newer_patch"); @@ -122,6 +251,11 @@ int main() { testChooseMethod_tarballRequiresCompiler(); testChooseMethod_noneWhenNothingAvailable(); +#if !defined(Q_OS_WIN) + testStagedInstall_replacesRunningExecutable(); +#endif + testRestartProgram_findsInstalledBinary(); + if (failures == 0) std::cout << "All update-manager tests passed" << std::endl; return failures == 0 ? 0 : 1; }