Merge branch 'main' into feature/mcp

This commit is contained in:
SoftFever committed 2026-11-21 18:57:39 +08:00
commit 867ba9b005
300 files changed
+18531 -2298

No files matched your search

+544 -112
View File
@@ -7,6 +7,7 @@
#include <functional>
#include "libslic3r/Config.hpp"
#include "libslic3r/LifecycleEvents.hpp"
#include "libslic3r/Utils.hpp"
#include <memory>
#include <optional>
#include <pybind11/embed.h>
@@ -66,6 +67,8 @@ std::vector<std::string>* permission_bucket(PluginPermissions& permissions, Plug
switch (category) {
case PluginPermissionCategory::FsRead: return &permissions.fs_read;
case PluginPermissionCategory::FsReadWrite: return &permissions.fs_readwrite;
case PluginPermissionCategory::FsCreate: return &permissions.fs_create;
case PluginPermissionCategory::FsDelete: return &permissions.fs_delete;
case PluginPermissionCategory::NetworkHttp: return &permissions.network_http;
case PluginPermissionCategory::NetworkSocket: return &permissions.network_socket;
case PluginPermissionCategory::Process: return &permissions.process;
@@ -153,31 +156,18 @@ bool PluginManager::initialize()
// Uninstalled in shutdown() before the interpreter finalizes.
plugin_hooks::install();
// Persist auto-load / capability state to each plugin's .install_state.json sidecar.
// On load: write enabled=true plus the current capability flags. On unload: flip enabled=false.
// The on-unload callback is skipped during shutdown, so app exit does not wipe the auto-load list.
subscribe_on_load_callback([this](const std::string& key) { write_loaded_plugin_install_state(key); });
subscribe_on_unload_callback([this](const std::string& key) {
if (m_shutting_down.load(std::memory_order_acquire))
return;
std::lock_guard<std::mutex> state_lock(install_state_mutex());
PluginDescriptor descriptor;
if (!try_get_plugin_descriptor(key, descriptor) || descriptor.plugin_root.empty())
return;
const boost::filesystem::path root(descriptor.plugin_root);
PluginInstallState state;
if (read_install_state(root, state)) {
state.enabled = false;
write_install_state(root, state);
}
});
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": Plugin manager initialized";
return true;
}
void PluginManager::set_shutting_down() { m_shutting_down.store(true, std::memory_order_release); }
void PluginManager::set_shutting_down()
{
m_shutting_down.store(true, std::memory_order_release);
// The GUI may already be closing: drop audit prompts that have not been shown yet rather than
// letting a queued dialog open after shutdown has begun.
PluginAuditManager::discard_pending_permission_prompts();
}
void PluginManager::shutdown()
{
@@ -189,6 +179,11 @@ void PluginManager::shutdown()
return;
}
// Set the shutdown flag before releasing any blocked permission prompt: a worker that fails
// because of that release must see the cancellation and not record a spurious load error or
// disable the package.
set_shutting_down();
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": PluginManager shutdown enter";
// Detach the libslic3r hooks first so nothing dispatches into Python while (or after) plugins
@@ -196,9 +191,6 @@ void PluginManager::shutdown()
// the remaining hook seams retain their existing shutdown requirements.
plugin_hooks::uninstall();
// Reject new plugin loads before we drain.
set_shutting_down();
std::string wait_error;
if (!wait_for_discovery(std::chrono::milliseconds::max(), wait_error) && !wait_error.empty())
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Plugin discovery did not finish cleanly during shutdown: " << wait_error;
@@ -398,8 +390,8 @@ void PluginManager::merge_discovered_plugins(std::vector<PluginDescriptor> disco
// A package can be temporarily absent while an external side-loader replaces it. Keep the
// descriptor and its persisted enable state until the user explicitly removes the missing
// entry, or a later scan rediscovers it. In particular, do not unload here: the unload callback
// would turn a transient filesystem gap into enabled=false in the sidecar.
// entry, or a later scan rediscovers it. In particular, do not unload here: unloading would turn
// a transient filesystem gap into enabled=false in the sidecar.
{
std::lock_guard<std::mutex> lock(m_mutex);
for (const Plugin& plugin : m_plugins) {
@@ -466,6 +458,12 @@ void PluginManager::unload_and_erase_if(const std::function<bool(const Plugin&)>
if (loaded_entry_found)
continue;
// A removed package can no longer retry the load a queued prompt was waiting for.
// Loaded entries were unloaded above; not-loaded ones are erased here.
for (const Plugin& plugin : m_plugins)
if (should_remove(plugin))
m_failed_loads.erase(plugin.descriptor.plugin_key);
m_plugins.erase(std::remove_if(m_plugins.begin(), m_plugins.end(), should_remove), m_plugins.end());
if (after_erase_locked)
after_erase_locked();
@@ -738,6 +736,12 @@ bool PluginManager::is_plugin_load_in_progress(const std::string& plugin_key) co
return m_load_in_progress.count(plugin_key) > 0;
}
bool PluginManager::is_plugin_load_cancelled(const std::string& plugin_key) const
{
std::lock_guard<std::mutex> lock(m_mutex);
return is_plugin_load_cancelled_locked(plugin_key);
}
void PluginManager::wait_for_all_plugin_loads() const
{
std::unique_lock<std::mutex> lock(m_mutex);
@@ -763,6 +767,14 @@ bool PluginManager::wait_for_plugin_load(const std::string& plugin_key, std::chr
return false;
}
// An update owns the key while it replaces the package and refuses to start a load, so there
// is no slot to wait for. Report the reason here rather than recording it in m_load_errors,
// where it would outlive the claim and surface on a later load.
if (m_updates_in_progress.count(plugin_key) > 0) {
error = _u8L("Plugin update is in progress.");
return false;
}
const auto it = m_load_errors.find(plugin_key);
if (it != m_load_errors.end()) {
error = it->second;
@@ -779,6 +791,12 @@ std::string PluginManager::get_plugin_load_error(const std::string& plugin_key)
return it == m_load_errors.end() ? std::string{} : it->second;
}
bool PluginManager::is_plugin_load_failed(const std::string& plugin_key) const
{
std::lock_guard<std::mutex> lock(m_mutex);
return find_plugin_locked(plugin_key) != nullptr && m_failed_loads.count(plugin_key) > 0;
}
bool PluginManager::cancel_plugin_load(const std::string& plugin_key)
{
bool cancelled = false;
@@ -787,6 +805,13 @@ bool PluginManager::cancel_plugin_load(const std::string& plugin_key)
cancelled = cancel_plugin_load_locked(plugin_key);
}
// A queued or active audit prompt for this load would keep its worker blocked on an answer
// that can no longer authorize anything. Mark the load cancelled first, then discard outside
// m_mutex, matching unload_plugin(): a prompt whose answer has not begun committing loses to
// the cancellation, while an in-progress commit stays atomic.
if (cancelled)
PluginAuditManager::discard_pending_permission_prompts_for(plugin_key);
notify_plugin_load_state_changed(cancelled);
return cancelled;
}
@@ -798,6 +823,7 @@ bool PluginManager::cancel_plugin_load_locked(const std::string& plugin_key)
m_cancelled.insert(plugin_key);
m_load_errors.erase(plugin_key);
m_failed_loads.erase(plugin_key);
return true;
}
@@ -815,7 +841,17 @@ void PluginManager::release_load_slot(const std::string& plugin_key)
{
std::lock_guard<std::mutex> lock(m_mutex);
changed = m_load_in_progress.erase(plugin_key) > 0;
m_cancelled.erase(plugin_key);
const bool cancelled = m_cancelled.erase(plugin_key) > 0;
const Plugin* plugin = find_plugin_locked(plugin_key);
const bool loaded = plugin != nullptr && plugin->is_loaded();
// Record an ordinary failure, but never a cancelled or successful load, and never one for
// a package that was removed while the worker unwound. Only the ordinary failure leaves
// its queued runtime prompts actionable for approval and retry.
if (cancelled || loaded || plugin == nullptr || m_load_errors.count(plugin_key) == 0)
m_failed_loads.erase(plugin_key);
else
m_failed_loads.insert(plugin_key);
}
notify_plugin_load_state_changed(changed);
}
@@ -891,12 +927,13 @@ void PluginManager::load_plugin(const std::string& plugin_key, bool skip_deps, s
{
std::string plugin_id = plugin_key;
bool exists = false;
bool invalid = false;
bool already_loaded = false;
bool load_in_progress = false;
bool load_slot_claimed = false;
bool shutting_down = false;
bool exists = false;
bool invalid = false;
bool already_loaded = false;
bool load_in_progress = false;
bool load_slot_claimed = false;
bool shutting_down = false;
bool update_in_progress = false;
std::string invalid_error;
std::vector<std::string> loaded_capability_names;
@@ -917,15 +954,25 @@ void PluginManager::load_plugin(const std::string& plugin_key, bool skip_deps, s
}
}
load_in_progress = m_load_in_progress.count(plugin_id) > 0;
shutting_down = m_shutting_down.load(std::memory_order_acquire);
if (exists && !invalid && !already_loaded && !load_in_progress && !shutting_down) {
load_in_progress = m_load_in_progress.count(plugin_id) > 0;
shutting_down = m_shutting_down.load(std::memory_order_acquire);
update_in_progress = m_updates_in_progress.count(plugin_id) > 0;
if (exists && !invalid && !already_loaded && !load_in_progress && !update_in_progress && !shutting_down) {
m_load_in_progress.insert(plugin_id);
m_load_errors.erase(plugin_id);
m_failed_loads.erase(plugin_id);
load_slot_claimed = true;
}
}
// An update owns the key until it has finished replacing the package on disk and reloads the
// new one itself. Starting a load here would import the old package while it is being moved
// aside, so the request is refused rather than left to race the replacement.
if (update_in_progress) {
BOOST_LOG_TRIVIAL(info) << "Plugin load skipped — update in progress: " << plugin_id;
return;
}
if (already_loaded) {
// An empty request means "restore the persisted capability state". Only an explicit
// capability request may change an already-loaded capability, e.g. when resolving an
@@ -1066,8 +1113,18 @@ void PluginManager::load_plugin_impl(const std::string& plugin_key, bool skip_de
std::string error;
bool registration_failed = false;
if (!plugin_loader::load(descriptor, skip_deps, capabilities_to_enable, registry_precheck, plugin, error, &registration_failed)) {
if (error == LOAD_CANCELLED)
// A permission prompt denied because the load was cancelled (unload or shutdown) surfaces
// here as an ordinary registration/permission failure. Do not disable the package or record
// an error for that: a genuine denial still follows the normal failure path below.
bool load_cancelled = m_shutting_down.load(std::memory_order_acquire);
if (!load_cancelled) {
std::lock_guard<std::mutex> lock(m_mutex);
load_cancelled = is_plugin_load_cancelled_locked(plugin_key);
}
if (error == LOAD_CANCELLED || load_cancelled) {
BOOST_LOG_TRIVIAL(info) << "[load_plugin_impl] CANCELLED plugin=" << plugin_key;
return; // cancelled: nothing materialized survives, and no error is recorded
}
if (registration_failed)
mark_plugin_install_state_disabled(plugin_key);
fail(std::move(error));
@@ -1121,6 +1178,11 @@ void PluginManager::load_plugin_impl(const std::string& plugin_key, bool skip_de
clear_plugin_error(plugin_key);
// Persist only after the plugin is committed as loaded. Lifecycle callbacks are dispatched
// asynchronously from worker threads and must not own sidecar persistence.
if (!m_shutting_down.load(std::memory_order_acquire))
write_loaded_plugin_install_state(plugin_key);
{
std::lock_guard<std::mutex> lock(m_mutex);
m_load_errors.erase(plugin_key);
@@ -1147,6 +1209,9 @@ bool PluginManager::unload_plugin(const std::string& plugin_key)
// Cancel any in-progress load for this plugin so its worker discards the result.
cancelled = cancel_plugin_load_locked(plugin_key);
// An explicit unload also revokes the "ordinary failure" state, so a prompt admitted
// after the queue discard below can never be shown for the unloaded plugin.
m_failed_loads.erase(plugin_key);
Plugin* plugin = find_plugin_locked(plugin_key);
if (plugin != nullptr && plugin->is_loaded()) {
@@ -1162,11 +1227,24 @@ bool PluginManager::unload_plugin(const std::string& plugin_key)
}
}
// Queued audit prompts belong to a plugin that is going away: cancel any blocked load worker
// and keep a late answer from persisting. Do this after marking the load cancelled so a worker
// released by the cancellation cannot take it as approval.
PluginAuditManager::discard_pending_permission_prompts_for(plugin_key);
if (!found) {
notify_plugin_load_state_changed(cancelled);
return true;
}
// Flip the durable flag here rather than in a completion callback: the update path unloads on
// a worker and immediately replaces the package, so a deferred write must not race the new
// sidecar. Persisting before the unload completes also means callers that delete or replace
// the plugin directory next already see the disabled state. Shutdown skips this to preserve
// the auto-load list across app exit.
if (!m_shutting_down.load(std::memory_order_acquire))
mark_plugin_install_state_disabled(plugin_key);
notify_unload_complete();
cancel_and_wait_for_capabilities(removed.capabilities);
@@ -1176,8 +1254,6 @@ bool PluginManager::unload_plugin(const std::string& plugin_key)
// Teardown runs outside m_mutex: it calls into Python and must not hold the registry lock.
plugin_loader::unload(removed);
// The .install_state.json sidecar is flipped to enabled=false by the on-unload callback
// (skipped during shutdown), so the auto-load list survives app exit.
BOOST_LOG_TRIVIAL(info) << "Unloaded plugin: " << plugin_key;
return true;
@@ -1207,8 +1283,10 @@ void PluginManager::unload_all_plugins()
// Bulk shutdown intentionally skips the normal unload notification path, but resources owned
// by GUI subscribers still need to be torn down before the interpreter is finalized.
for (const std::string& key : removed_keys)
for (const std::string& key : removed_keys) {
PluginAuditManager::discard_pending_permission_prompts_for(key);
run_on_unload_callbacks(key);
}
// Broadcast cancellation to every plugin before waiting. This keeps bulk unload from
// starving a later plugin while an earlier plugin uses the full cancellation grace period.
@@ -1388,6 +1466,9 @@ bool PluginManager::mutate_plugin_permissions(const std::string& plugin_key, con
if (applied != nullptr)
*applied = state.permissions;
// Pending recursive-delete consents were granted against the previous permission state.
PluginAuditManager::instance().invalidate_recursive_delete_state(plugin_key);
BOOST_LOG_TRIVIAL(info) << "Applied permission changes for plugin " << plugin_key;
return true;
}
@@ -1410,6 +1491,9 @@ void PluginManager::revoke_plugin_permissions(const std::string& plugin_key)
state.permissions = {};
if (!write_install_state(root, state))
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Failed to revoke permissions for " << plugin_key;
// A revoke or reinstall invalidates transient recursive-delete consents and queued callbacks.
PluginAuditManager::instance().invalidate_recursive_delete_state(plugin_key);
}
// ── Callbacks ───────────────────────────────────────────────────────────────────────────────
@@ -1551,6 +1635,16 @@ void PluginManager::set_cloud_user(const std::string& user_id)
m_cloud_user_id = user_id;
}
void PluginManager::sync_cloud_user_from_agent()
{
// Ensure cloud plugins install to _subscribed/<user_id>/, matching the signed-in session.
if (auto agent = m_cloud_service.get_cloud_agent()) {
const std::string user_id = agent->get_user_id();
if (!user_id.empty())
set_cloud_user(user_id);
}
}
// ── Errors ──────────────────────────────────────────────────────────────────────────────────
bool PluginManager::set_plugin_error(const std::string& plugin_key, std::string error)
@@ -1598,20 +1692,30 @@ bool PluginManager::install_plugin(const boost::filesystem::path& filepath, std:
}
bool PluginManager::install_plugin(const boost::filesystem::path& filepath, PluginDescriptor& plugin_descriptor, std::string& error)
{
return install_plugin_impl(filepath, plugin_descriptor, nullptr, error, nullptr);
}
bool PluginManager::install_plugin_impl(const boost::filesystem::path& filepath, PluginDescriptor& plugin_descriptor,
const std::string* cloud_user_id_override, std::string& error,
bool* install_target_intact, const PluginInstallState* preserved_state,
bool mark_error_on_failure)
{
error.clear();
std::string wait_error;
if (!wait_for_discovery(std::chrono::milliseconds::max(), wait_error)) {
error = GUI::format(_u8L("Plugin installation failed: %1%"), wait_error.empty() ? _u8L("Plugin discovery is still running") : wait_error);
if (!plugin_descriptor.plugin_key.empty())
if (mark_error_on_failure && !plugin_descriptor.plugin_key.empty())
set_plugin_error(plugin_descriptor.plugin_key, error);
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ": Plugin installation failed while waiting for discovery: " << error;
return false;
}
std::string cloud_user_id;
{
if (cloud_user_id_override != nullptr) {
cloud_user_id = *cloud_user_id_override;
} else {
std::lock_guard<std::mutex> lock(m_mutex);
cloud_user_id = m_cloud_user_id;
}
@@ -1624,8 +1728,9 @@ bool PluginManager::install_plugin(const boost::filesystem::path& filepath, Plug
unload_plugin(local_plugin_key);
}
if (!plugin_loader::install_plugin(filepath, cloud_user_id, plugin_descriptor, error)) {
if (!plugin_descriptor.plugin_key.empty())
if (!plugin_loader::install_plugin(filepath, cloud_user_id, plugin_descriptor, error, install_target_intact,
preserved_state)) {
if (mark_error_on_failure && !plugin_descriptor.plugin_key.empty())
set_plugin_error(plugin_descriptor.plugin_key, error);
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ": " << error;
return false;
@@ -1633,11 +1738,18 @@ bool PluginManager::install_plugin(const boost::filesystem::path& filepath, Plug
// Every successful install may have replaced executable plugin code. Revoke any permissions
// associated with the previous package so the newly installed version must request them again.
if (!plugin_descriptor.plugin_key.empty())
if (!plugin_descriptor.plugin_key.empty()) { {
revoke_plugin_permissions(plugin_descriptor.plugin_key);
// A prompt queued by the replaced code must not grant a permission the new code never
// requested: an installed package starts its lifecycle from a clean failure state.
std::lock_guard<std::mutex> lock(m_mutex);
m_failed_loads.erase(plugin_descriptor.plugin_key);
}
if (!plugin_descriptor.plugin_key.empty())
clear_plugin_error(plugin_descriptor.plugin_key);
}
return true;
}
@@ -1930,6 +2042,85 @@ bool PluginManager::subscribe_and_install_cloud_plugin(const std::string& plugin
return download_and_install_cloud_plugin(descriptor.plugin_key, descriptor.version, error);
}
bool PluginManager::install_cloud_plugin_package(const std::string& plugin_key,
const std::string& requested_version,
const boost::filesystem::path& package_path,
const PluginDescriptor& descriptor,
const std::string* cloud_user_id,
std::string& error,
CloudUpdateFailure* failure,
const PluginInstallState* preserved_state)
{
error.clear();
// When `failure` is given, the caller owns the failed update: it restores the previous package
// when that is still usable, and only then decides whether the plugin is actually broken. Do
// not record the install error here, where it would mark a working restored plugin as failed.
const bool caller_owns_failure = failure != nullptr;
// Record the version fetched from the cloud so install_plugin persists it to the install-state
// sidecar (the source of truth for the installed cloud version) instead of the local
// manifest/PEP723 header version.
PluginDescriptor installed = descriptor;
installed.installed_version = requested_version;
// The executable identity belongs to the package being installed. A descriptor taken from the
// previous installation can still carry its old wheel import name; clearing it lets
// install_plugin() fill entry_package from the replacement's package metadata instead.
installed.entry_package.clear();
bool install_target_intact = true;
if (!install_plugin_impl(package_path, installed, cloud_user_id, error, &install_target_intact, preserved_state,
/*mark_error_on_failure=*/!caller_owns_failure)) {
if (failure != nullptr)
*failure = install_target_intact ? CloudUpdateFailure::PreviousPackageUsable
: CloudUpdateFailure::RollbackFailed;
if (error.empty())
error = _u8L("Failed to install cloud plugin.");
if (!caller_owns_failure)
set_plugin_error(plugin_key, error);
boost::system::error_code ec;
boost::filesystem::remove(package_path, ec);
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ": " << error;
return false;
}
if (!requested_version.empty())
installed.version = requested_version;
// The version just downloaded and installed is now the locally installed version.
installed.installed_version = requested_version.empty() ? installed.version : requested_version;
// The installer kept the pre-update activation intent in the sidecar; mirror it in memory.
installed.enabled = preserved_state != nullptr ? preserved_state->enabled : true;
if (installed.cloud.has_value()) {
installed.cloud->installed = true;
installed.cloud->update_available = false;
installed.cloud->unauthorized = false;
}
installed.clear_error();
installed.set_unauthorized(false);
{
std::lock_guard<std::mutex> lock(m_mutex);
Plugin* entry = find_plugin_locked(plugin_key);
if (entry == nullptr) {
error = _u8L("Plugin not found.");
if (failure != nullptr)
*failure = CloudUpdateFailure::ReplacementInstalled;
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Cloud plugin " << plugin_key
<< " downloaded successfully but failed to update plugin metadata. Plugin object not found.";
} else {
entry->descriptor = std::move(installed);
}
}
if (!error.empty()) {
if (!caller_owns_failure)
set_plugin_error(plugin_key, error);
return false;
}
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": Cloud plugin " << plugin_key << " installed successfully";
return true;
}
bool PluginManager::download_and_install_cloud_plugin(const std::string& plugin_key, const std::string& version, std::string& error)
{
error.clear();
@@ -1954,59 +2145,59 @@ bool PluginManager::download_and_install_cloud_plugin(const std::string& plugin_
}
// Ensure cloud plugins install to _subscribed/<user_id>/
if (auto agent = m_cloud_service.get_cloud_agent()) {
const std::string user_id = agent->get_user_id();
if (!user_id.empty())
set_cloud_user(user_id);
sync_cloud_user_from_agent();
return install_cloud_plugin_package(plugin_key, requested_version, download.package_path, descriptor, nullptr, error);
}
void PluginManager::restore_plugin_state_after_failed_update(const PluginDescriptor& previous,
const PluginInstallState& previous_state,
bool had_previous_state,
bool was_enabled)
{
namespace fs = boost::filesystem;
if (previous.plugin_root.empty())
return;
const fs::path root(previous.plugin_root);
boost::system::error_code ec;
if (!fs::exists(root, ec)) {
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Previous plugin folder is missing, cannot restore its state: "
<< previous.plugin_key;
return;
}
// Record the version we just fetched from the cloud so install_plugin persists it to the
// install-state sidecar (the source of truth for the installed cloud version) instead of the
// local manifest/PEP723 header version.
descriptor.installed_version = requested_version;
{
std::lock_guard<std::mutex> state_lock(install_state_mutex());
if (!install_plugin(download.package_path, descriptor, error)) {
if (error.empty())
error = _u8L("Failed to install cloud plugin.");
set_plugin_error(plugin_key, error);
boost::system::error_code ec;
boost::filesystem::remove(download.package_path, ec);
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ": " << error;
return false;
}
PluginInstallState state;
const InstallStateReadStatus status = read_install_state_status(root, state);
if (status == InstallStateReadStatus::Unreadable) {
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Cannot restore install state for "
<< previous.plugin_key << "; leaving the sidecar untouched";
return;
}
PluginDescriptor updated_descriptor = descriptor;
if (!requested_version.empty())
updated_descriptor.version = requested_version;
// The version just downloaded and installed is now the locally installed version.
updated_descriptor.installed_version = requested_version.empty() ? descriptor.version : requested_version;
updated_descriptor.enabled = true;
if (updated_descriptor.cloud.has_value()) {
updated_descriptor.cloud->installed = true;
updated_descriptor.cloud->update_available = false;
updated_descriptor.cloud->unauthorized = false;
if (had_previous_state) {
// The snapshot also restores permissions and capability choices, which belong to the
// old package and were never replaced.
state = previous_state;
} else if (status == InstallStateReadStatus::Absent) {
seed_install_metadata(state, previous);
}
// The unload before the failed replacement wrote enabled=false over the old intent.
state.enabled = was_enabled;
if (!write_install_state(root, state))
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Failed to restore install state for " << previous.plugin_key;
}
updated_descriptor.clear_error();
updated_descriptor.set_unauthorized(false);
{
std::lock_guard<std::mutex> lock(m_mutex);
Plugin* entry = find_plugin_locked(plugin_key);
if (entry == nullptr) {
error = _u8L("Plugin not found.");
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Cloud plugin " << plugin_key
<< " downloaded successfully but failed to update plugin metadata. Plugin object not found.";
} else {
entry->descriptor = std::move(updated_descriptor);
}
if (Plugin* plugin = find_plugin_locked(previous.plugin_key))
plugin->descriptor.enabled = was_enabled;
}
if (!error.empty()) {
set_plugin_error(plugin_key, error);
return false;
}
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": Cloud plugin " << plugin_key << " installed successfully";
return true;
}
bool PluginManager::update_cloud_plugin(const std::string& plugin_key, std::string& error, std::string version)
@@ -2025,6 +2216,46 @@ bool PluginManager::update_cloud_plugin(const std::string& plugin_key, std::stri
return false;
}
// Claim the key before any network or filesystem work. Both checks and the insert happen under
// m_mutex, and load_plugin() checks the same set under it, so an in-flight load cannot be
// cancelled halfway by the replacement and a new one cannot start while the package is being
// moved aside. The account the update started under is captured with the claim.
std::string update_cloud_user;
{
std::lock_guard<std::mutex> lock(m_mutex);
if (m_load_in_progress.count(plugin_key) > 0)
error = _u8L("Plugin load is still in progress");
else if (!m_updates_in_progress.insert(plugin_key).second)
error = _u8L("A plugin update is already in progress.");
else
update_cloud_user = m_cloud_user_id;
}
if (!error.empty()) {
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": " << error;
return false;
}
// Release the claim on every path. The reload of the replacement must run without it, so it
// is released explicitly first and the scope guard then has nothing left to do.
auto release_update = [this, &plugin_key]() {
std::lock_guard<std::mutex> lock(m_mutex);
m_updates_in_progress.erase(plugin_key);
};
ScopeGuard update_scope(release_update);
// Reloads whichever package is installed for the key. The claim is already released, so
// load_plugin() can start the replacement load itself. Returns false with the reason.
auto reload_plugin = [&](std::string& reason) {
release_update();
update_scope.reset();
load_plugin(plugin_key);
std::string load_error;
if (wait_for_plugin_load(plugin_key, std::chrono::minutes(5), load_error) && is_plugin_loaded(plugin_key))
return true;
reason = load_error.empty() ? _u8L("Plugin failed to load.") : load_error;
return false;
};
// An empty version means "update the current plugin". If there is no update available, the
// intention is unclear.
if (version.empty()) {
@@ -2037,39 +2268,236 @@ bool PluginManager::update_cloud_plugin(const std::string& plugin_key, std::stri
}
}
// Keep the plugin's current error before the clear below. It is only meant to drop a stale
// error from an earlier update attempt; if this update fails and the restored package is not
// reloaded, a plugin that was already broken must not end up looking healthy.
const std::string previous_error = descriptor.normalized_error();
clear_plugin_error(plugin_key);
if (descriptor.has_local_package()) {
boost::filesystem::path resolved_root;
bool resolved_allowed_plugin_root = false;
{
std::lock_guard<std::mutex> lock(m_mutex);
resolved_allowed_plugin_root = resolve_allowed_plugin_root(descriptor, get_plugin_directories(m_cloud_user_id),
_u8L("Refusing to delete a plugin outside the known plugin directories."),
resolved_root, error);
}
if (!resolved_allowed_plugin_root) {
set_plugin_error(plugin_key, error);
return false;
}
unload_plugin(plugin_key);
if (!delete_plugin_root(resolved_root, plugin_key, error)) {
set_plugin_error(plugin_key, error);
return false;
}
// Pin the account target before any network work. If the account was not set when the update
// started, the signed-in agent is authoritative (startup ordering); reject an update with no
// known account, so a sign-in during the download cannot silently retarget the install.
if (update_cloud_user.empty()) {
sync_cloud_user_from_agent();
std::lock_guard<std::mutex> lock(m_mutex);
update_cloud_user = m_cloud_user_id;
}
if (!download_and_install_cloud_plugin(plugin_key, version, error)) {
if (update_cloud_user.empty()) {
error = _u8L("Sign in to OrcaCloud to update this plugin.");
set_plugin_error(plugin_key, error);
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": " << error;
return false;
}
clear_plugin_error(plugin_key);
// Download before touching the installed package: a failed download must leave the old package
// and its sidecar exactly as they were.
CloudPluginDownload download;
if (!m_cloud_service.download_cloud_plugin(descriptor, version, download, error)) {
if (error.empty())
error = _u8L("Failed to download cloud plugin.");
set_plugin_error(plugin_key, error);
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ": " << error;
return false;
}
// Re-read after the download: a capability may have been toggled while it ran, and the plugin
// may have been removed or replaced. This snapshot is what the update preserves.
PluginDescriptor previous;
if (!try_get_plugin_descriptor(plugin_key, previous)) {
error = GUI::format(_u8L("Plugin not found: %1%"), plugin_key);
boost::system::error_code ec;
boost::filesystem::remove(download.package_path, ec);
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Failed to find plugin key " << plugin_key;
return false;
}
const bool had_local_package = previous.has_local_package();
const bool was_loaded = had_local_package && is_plugin_loaded(plugin_key);
const bool was_enabled = !had_local_package || was_loaded || previous.enabled;
PluginInstallState previous_state;
bool had_previous_state = false;
bool previous_state_unreadable = false;
if (had_local_package && !previous.plugin_root.empty()) {
std::lock_guard<std::mutex> state_lock(install_state_mutex());
const InstallStateReadStatus status =
read_install_state_status(boost::filesystem::path(previous.plugin_root), previous_state);
had_previous_state = status == InstallStateReadStatus::Readable;
previous_state_unreadable = status == InstallStateReadStatus::Unreadable;
}
// A sidecar that exists but cannot be read may still hold the user's capability choices and
// grants. Replacing the package would reset it with an empty capability list, so abort while
// the installed package and its sidecar are still untouched. Absent is a package without
// stored choices and keeps the normal replacement path.
if (previous_state_unreadable) {
const boost::filesystem::path previous_root(previous.plugin_root);
error = GUI::format(_u8L("Failed to read plugin install state: %1%"),
(previous_root / INSTALL_STATE_FILE).string());
boost::system::error_code ec;
boost::filesystem::remove(download.package_path, ec);
set_plugin_error(plugin_key, error);
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": " << error;
return false;
}
// Check the account before touching the installed package. It must still be the one captured
// before the download: a sign-in/sign-out or account switch while it ran would otherwise
// install the replacement into a different user's directory. The pinned id is passed to the
// installer, so a change after this check cannot redirect the install either.
bool account_changed = false;
{
std::lock_guard<std::mutex> lock(m_mutex);
account_changed = m_cloud_user_id != update_cloud_user;
}
if (account_changed) {
error = _u8L("The cloud account changed while the plugin was updating. Please try again.");
boost::system::error_code ec;
boost::filesystem::remove(download.package_path, ec);
set_plugin_error(plugin_key, error);
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": " << error << " (" << plugin_key << ")";
return false;
}
boost::filesystem::path resolved_root;
if (had_local_package) {
bool resolved_allowed_plugin_root = false;
{
std::lock_guard<std::mutex> lock(m_mutex);
resolved_allowed_plugin_root = resolve_allowed_plugin_root(previous, get_plugin_directories(update_cloud_user),
_u8L("Refusing to delete a plugin outside the known plugin directories."),
resolved_root, error);
}
if (!resolved_allowed_plugin_root) {
boost::system::error_code ec;
boost::filesystem::remove(download.package_path, ec);
set_plugin_error(plugin_key, error);
return false;
}
unload_plugin(plugin_key);
}
std::string install_error;
CloudUpdateFailure failure = CloudUpdateFailure::PreviousPackageUsable;
// The installer writes the sidecar for the new package before it removes the backup, so it
// needs the user's activation intent and capability choices up front. Permissions are not
// carried over: the replacement is new executable code and must request them again.
PluginInstallState preserved_state;
if (had_local_package) {
preserved_state.enabled = was_enabled;
if (had_previous_state)
preserved_state.capabilities = previous_state.capabilities;
}
if (!install_cloud_plugin_package(plugin_key, version, download.package_path, previous, &update_cloud_user, install_error,
&failure, had_local_package ? &preserved_state : nullptr)) {
// Restoring the old state and reloading the old package is only meaningful when the
// installer left that package in place. A committed replacement must not inherit the old
// package's grants.
bool previous_package_usable = failure == CloudUpdateFailure::PreviousPackageUsable;
// A failed rollback concerns only the directory the installer wrote to. When the package
// this update preserves lives at a different root, that rollback did not touch it. Allow
// the restore/reload only after proving the old package is still there; any path or
// lookup error keeps the conservative "not usable" result, so old grants can never be
// applied to a replacement package.
if (failure == CloudUpdateFailure::RollbackFailed && had_local_package && !resolved_root.empty() &&
!previous.cloud_uuid().empty()) {
const boost::filesystem::path install_target =
boost::filesystem::path(get_cloud_plugin_dir(update_cloud_user)) / previous.cloud_uuid();
boost::system::error_code target_ec;
const boost::filesystem::path target_root = boost::filesystem::weakly_canonical(install_target, target_ec);
if (!target_ec && resolved_root != target_root) {
boost::system::error_code exists_ec;
const bool old_package_present =
!previous.entry_path.empty()
? boost::filesystem::is_regular_file(boost::filesystem::path(previous.entry_path), exists_ec)
: boost::filesystem::is_directory(boost::filesystem::path(previous.plugin_root), exists_ec);
previous_package_usable = !exists_ec && old_package_present;
}
}
if (had_local_package && previous_package_usable)
restore_plugin_state_after_failed_update(previous, previous_state, had_previous_state, was_enabled);
bool previous_reloaded = true;
if (was_loaded && previous_package_usable) {
std::string reason;
if (!reload_plugin(reason)) {
previous_reloaded = false;
install_error += "\n" + GUI::format(_u8L("The previous version also failed to reload: %1%"), reason);
}
}
if (had_local_package && failure == CloudUpdateFailure::RollbackFailed && !previous_package_usable) {
install_error += "\n" + _u8L("The previous plugin files could not be restored.");
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Previous package of " << plugin_key
<< " could not be restored; its permissions were not reapplied";
}
error = std::move(install_error);
// The update failed, but a previous package that was restored and reloaded is still
// working. Report the update error without marking the plugin broken. An unrestored
// package or a failed reload leaves the plugin unusable, so it is marked.
const bool previous_plugin_working = had_local_package && previous_package_usable && previous_reloaded;
if (!previous_plugin_working) {
set_plugin_error(plugin_key, error);
} else if (!was_loaded && !previous_error.empty()) {
// Nothing was reloaded, so a plugin that was already broken stays broken. The clear
// above discarded its real error; put it back instead of leaving an unhealthy plugin
// looking fine.
set_plugin_error(plugin_key, previous_error);
}
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": " << error;
return false;
}
// The installer committed the replacement with the preserved activation and capability state
// and every permission cleared, so the new package is ready to load.
PluginDescriptor installed;
if (!try_get_plugin_descriptor(plugin_key, installed)) {
error = _u8L("Plugin not found.");
set_plugin_error(plugin_key, error);
return false;
}
// The installed descriptor may point at another allowed directory (for example a package
// retained from an earlier install location). The installer only replaces the directory it
// installs into. Keep that package until the new one is fully committed (sidecar written and,
// when applicable, reloaded) so any failure still leaves a fallback on disk.
auto remove_stale_old_package = [&]() {
if (!had_local_package || resolved_root.empty() || installed.plugin_root.empty())
return;
boost::system::error_code equivalent_ec;
const bool same_root = boost::filesystem::equivalent(resolved_root, installed.plugin_root, equivalent_ec);
if (!equivalent_ec && !same_root) {
std::string cleanup_error;
if (!delete_plugin_root(resolved_root, plugin_key, cleanup_error))
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": " << cleanup_error;
}
};
if (was_loaded) {
// The package is already installed and its state persisted, so a failure here is reported
// as a reload failure rather than hiding the successful update.
std::string reason;
if (!reload_plugin(reason)) {
error = GUI::format(_u8L("Updated the plugin, but failed to reload it: %1%"), reason);
set_plugin_error(plugin_key, error);
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": " << error;
return false;
}
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": Cloud plugin " << plugin_key
<< " updated and reloaded";
} else if (!was_enabled) {
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": Cloud plugin " << plugin_key
<< " updated and kept deactivated";
}
remove_stale_old_package();
return true;
}
@@ -2184,6 +2612,9 @@ bool PluginManager::keep_installed_plugin_as_local(const PluginDescriptor& plugi
entry->descriptor.plugin_key = new_key;
entry->descriptor.cloud.reset();
entry->descriptor.clear_error();
// The package identity changed, so neither key may keep an old failure's prompt alive.
m_failed_loads.erase(old_key);
m_failed_loads.erase(new_key);
for (const auto& capability : entry->capabilities) {
if (capability)
@@ -2228,6 +2659,7 @@ bool PluginManager::finalize_cloud_plugin_removal(const PluginDescriptor& plugin
{
std::lock_guard<std::mutex> lock(m_mutex);
m_failed_loads.erase(plugin.plugin_key);
m_plugins.erase(std::remove_if(m_plugins.begin(), m_plugins.end(),
[&plugin](const Plugin& entry) { return entry.descriptor.plugin_key == plugin.plugin_key; }),
m_plugins.end());