Files
Library/src/Plugin/Manager.cpp

639 lines
18 KiB
C++

#include <Void/Plugin/Manager.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Plugin/Loader.hpp>
#if defined(__unix__) || defined(__APPLE__)
#include <dlfcn.h>
#define VOID_HAS_DLOPEN 1
#endif
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <string>
#include <system_error>
#include <utility>
namespace Void::Plugin
{
namespace detail
{
struct Instance {
void* handle{nullptr};
IPlugin* plugin{nullptr};
destroy_fn destroy{nullptr};
transfer_fn transfer{nullptr};
configure_fn configure{nullptr};
ready_fn ready{nullptr};
state_version_fn state_version{nullptr};
serialize_fn serialize{nullptr};
free_string_fn free_string{nullptr};
deserialize_fn deserialize{nullptr};
PluginInfo info{};
bool dlclose_on_destroy{false};
Instance() = default;
Instance(const Instance&) = delete;
Instance& operator=(const Instance&) = delete;
~Instance()
{
#ifdef VOID_HAS_DLOPEN
if (plugin != nullptr) {
plugin->on_unload();
if (destroy != nullptr) {
destroy(plugin);
}
}
if (handle != nullptr && dlclose_on_destroy) {
dlclose(handle);
}
#endif
}
};
} // namespace detail
// ── PluginHandle ──────────────────────────────────────────────────────
IPlugin* PluginHandle::operator->() const noexcept
{
return m_pin ? m_pin->plugin : nullptr;
}
IPlugin& PluginHandle::operator*() const noexcept { return *m_pin->plugin; }
IPlugin* PluginHandle::get() const noexcept
{
return m_pin ? m_pin->plugin : nullptr;
}
PluginHandle::operator bool() const noexcept
{
return m_pin != nullptr && m_pin->plugin != nullptr;
}
const PluginInfo& PluginHandle::info() const noexcept
{
return m_pin->info;
}
void* PluginHandle::raw_symbol(const char* symbol) const noexcept
{
#ifdef VOID_HAS_DLOPEN
if (!m_pin || m_pin->handle == nullptr || symbol == nullptr) {
return nullptr;
}
return dlsym(m_pin->handle, symbol);
#else
(void)symbol;
return nullptr;
#endif
}
// ── loading helpers ───────────────────────────────────────────────────
namespace
{
// dlopen a (fresh-inode) copy of `path` and resolve all symbols.
std::expected<std::shared_ptr<detail::Instance>, LoadError>
open_instance(const std::filesystem::path& load_path,
bool dlclose_on_destroy)
{
#ifdef VOID_HAS_DLOPEN
void* h = dlopen(load_path.c_str(), RTLD_NOW | RTLD_LOCAL);
if (h == nullptr) {
return std::unexpected{LoadError::DlopenFailed};
}
const auto info_sym =
reinterpret_cast<info_fn>(dlsym(h, kInfoSymbol));
const auto create_sym =
reinterpret_cast<create_fn>(dlsym(h, kCreateSymbol));
const auto destroy_sym =
reinterpret_cast<destroy_fn>(dlsym(h, kDestroySymbol));
if (info_sym == nullptr || create_sym == nullptr ||
destroy_sym == nullptr) {
dlclose(h);
return std::unexpected{LoadError::SymbolMissing};
}
const PluginInfo info = info_sym();
if (info.abi_version != ABI_VERSION) {
dlclose(h);
return std::unexpected{LoadError::AbiMismatch};
}
void* raw = create_sym();
if (raw == nullptr) {
dlclose(h);
return std::unexpected{LoadError::CreateFailed};
}
auto inst = std::make_shared<detail::Instance>();
inst->handle = h;
inst->plugin = static_cast<IPlugin*>(raw);
inst->destroy = destroy_sym;
inst->transfer =
reinterpret_cast<transfer_fn>(dlsym(h, kTransferSymbol));
inst->configure =
reinterpret_cast<configure_fn>(dlsym(h, kConfigureSymbol));
inst->ready = reinterpret_cast<ready_fn>(dlsym(h, kReadySymbol));
inst->state_version = reinterpret_cast<state_version_fn>(
dlsym(h, kStateVersionSymbol));
inst->serialize =
reinterpret_cast<serialize_fn>(dlsym(h, kSerializeSymbol));
inst->free_string =
reinterpret_cast<free_string_fn>(dlsym(h, kFreeStringSymbol));
inst->deserialize =
reinterpret_cast<deserialize_fn>(dlsym(h, kDeserializeSymbol));
inst->info = info;
inst->dlclose_on_destroy = dlclose_on_destroy;
return inst;
#else
(void)load_path;
(void)dlclose_on_destroy;
return std::unexpected{LoadError::NotSupported};
#endif
}
// Move state old -> new (v2 serialize/deserialize, else transfer).
// Returns false only if the new instance rejects the state.
bool transfer_state(const detail::Instance& from, detail::Instance& to)
{
if (from.plugin == nullptr || to.plugin == nullptr) {
return true;
}
if (from.serialize != nullptr && to.deserialize != nullptr) {
const std::uint32_t version =
from.state_version != nullptr ? from.state_version() : 0;
const char* json = from.serialize(from.plugin);
if (json != nullptr) {
const int rc = to.deserialize(to.plugin, json, version);
if (from.free_string != nullptr) {
from.free_string(json);
}
if (rc != 0) {
Void::Log::warn(
"Plugin.Manager",
"deserialize rejected state (v{}, rc={})", version,
rc);
return false;
}
return true;
}
}
if (to.transfer != nullptr) {
to.transfer(from.plugin, to.plugin);
}
return true;
}
// Copy to a fresh-inode temp path so dlopen does not return the
// already-mapped image when the file is replaced in place.
std::expected<std::filesystem::path, LoadError>
hotswap_copy(const std::filesystem::path& path)
{
static std::atomic<std::uint64_t> counter{0};
const auto tmp = path.parent_path() /
(path.filename().string() + ".void_hotswap." +
std::to_string(counter.fetch_add(
1, std::memory_order_relaxed)));
std::error_code ec;
std::filesystem::copy_file(
path, tmp, std::filesystem::copy_options::overwrite_existing,
ec);
if (ec) {
return std::unexpected{LoadError::FileNotFound};
}
return tmp;
}
} // namespace
// ── PluginManager ─────────────────────────────────────────────────────
PluginManager::PluginManager(Options options)
: m_options(std::move(options)),
m_watcher(FileSystem::FileWatcherOptions{
.poll_interval = m_options.poll_interval,
.debounce_polls = m_options.debounce_polls})
{
}
PluginManager::~PluginManager() = default;
PluginManager::Entry* PluginManager::find(std::string_view name) const
{
const auto it = m_plugins.find(std::string{name});
return it == m_plugins.end() ? nullptr : it->second.get();
}
std::shared_ptr<PluginManager::Entry>
PluginManager::find_shared(std::string_view name) const
{
const auto it = m_plugins.find(std::string{name});
return it == m_plugins.end() ? nullptr : it->second;
}
std::expected<std::string, LoadError>
PluginManager::load(const std::filesystem::path& path)
{
std::error_code ec;
if (!std::filesystem::exists(path, ec)) {
return std::unexpected{LoadError::FileNotFound};
}
std::filesystem::path load_path = path;
if (m_options.copy_on_load) {
auto tmp = hotswap_copy(path);
if (!tmp.has_value()) {
return std::unexpected{tmp.error()};
}
load_path = *tmp;
}
auto inst = open_instance(load_path, m_options.dlclose_on_swap);
if (m_options.copy_on_load) {
std::filesystem::remove(load_path, ec);
}
if (!inst.has_value()) {
Void::Log::warn("Plugin.Manager", "load '{}' failed: {}",
path.string(), to_string(inst.error()));
return std::unexpected{inst.error()};
}
std::string name{(*inst)->plugin->name()};
if (m_options.candidate_validator &&
!m_options.candidate_validator(PluginHandle{*inst})) {
Void::Log::warn("Plugin.Manager",
"load '{}' aborted: binary validation failed",
name);
return std::unexpected{LoadError::ActivationFailed};
}
if (m_options.config_provider && (*inst)->configure != nullptr) {
const std::string config = m_options.config_provider(name);
(*inst)->configure((*inst)->plugin, config.c_str());
}
try {
(*inst)->plugin->on_load();
} catch (...) {
return std::unexpected{LoadError::ActivationFailed};
}
if ((*inst)->ready != nullptr && (*inst)->ready((*inst)->plugin) != 0) {
return std::unexpected{LoadError::ActivationFailed};
}
if (m_options.instance_validator &&
!m_options.instance_validator(*(*inst)->plugin, (*inst)->info)) {
return std::unexpected{LoadError::ActivationFailed};
}
std::shared_ptr<Entry> replaced_entry;
{
std::lock_guard lock(m_mutex);
auto entry = std::make_shared<Entry>();
entry->path = path;
entry->current.store(std::move(*inst), std::memory_order_release);
Void::Log::info("Plugin.Manager", "loaded '{}' as '{}' (v{})",
path.string(), name,
entry->current.load(std::memory_order_relaxed)
->info.plugin_version);
auto it = m_plugins.find(name);
if (it != m_plugins.end()) {
replaced_entry = std::move(it->second);
it->second = std::move(entry);
} else {
m_plugins.emplace(name, std::move(entry));
}
}
return name;
}
std::vector<
std::pair<std::filesystem::path, std::expected<std::string, LoadError>>>
PluginManager::load_directory(const std::filesystem::path& dir)
{
#if defined(_WIN32)
constexpr std::string_view ext = ".dll";
#elif defined(__APPLE__)
constexpr std::string_view ext = ".dylib";
#else
constexpr std::string_view ext = ".so";
#endif
std::vector<std::filesystem::path> candidates;
std::error_code ec;
for (const auto& entry : std::filesystem::directory_iterator{dir, ec}) {
if (entry.is_regular_file(ec) && entry.path().extension() == ext) {
candidates.push_back(entry.path());
}
}
std::sort(candidates.begin(), candidates.end());
std::vector<std::pair<std::filesystem::path,
std::expected<std::string, LoadError>>>
out;
out.reserve(candidates.size());
for (auto& path : candidates) {
auto result = load(path);
out.emplace_back(std::move(path), std::move(result));
}
return out;
}
std::expected<void, LoadError> PluginManager::unload(std::string_view name)
{
std::shared_ptr<Entry> removed;
{
std::lock_guard lock(m_mutex);
auto it = m_plugins.find(std::string{name});
if (it == m_plugins.end()) {
return std::unexpected{LoadError::UnknownPlugin};
}
m_watcher.unwatch(it->second->path);
removed = std::move(it->second);
m_plugins.erase(it);
}
Void::Log::info("Plugin.Manager", "unloaded '{}'", name);
return {};
}
PluginHandle PluginManager::acquire(std::string_view name) const
{
std::shared_ptr<Entry> entry;
{
std::lock_guard lock(m_mutex);
entry = find_shared(name);
}
if (!entry) {
return PluginHandle{};
}
return PluginHandle{entry->current.load(std::memory_order_acquire)};
}
std::expected<void, LoadError> PluginManager::reload(std::string_view name)
{
std::shared_ptr<Entry> entry;
{
std::lock_guard lock(m_mutex);
entry = find_shared(name);
}
if (!entry) {
return std::unexpected{LoadError::UnknownPlugin};
}
return reload_entry_unlocked(entry, name, std::nullopt);
}
std::expected<void, LoadError>
PluginManager::replace(std::string_view name,
const std::filesystem::path& newPath)
{
std::shared_ptr<Entry> entry;
{
std::lock_guard lock(m_mutex);
entry = find_shared(name);
}
if (!entry) {
return std::unexpected{LoadError::UnknownPlugin};
}
std::error_code error;
if (!std::filesystem::is_regular_file(newPath, error)) {
return std::unexpected{LoadError::FileNotFound};
}
return reload_entry_unlocked(entry, name, newPath);
}
std::expected<void, LoadError> PluginManager::reload_entry_unlocked(
const std::shared_ptr<Entry>& entry, std::string_view name,
const std::optional<std::filesystem::path>& newPath)
{
std::vector<std::function<void(std::string_view)>> callbacks;
bool restartWatcher = false;
std::shared_ptr<detail::Instance> retired_old;
{
// Serialize reloads per plugin entry WITHOUT holding m_mutex, so
// validators, config providers, and concurrent acquire() callers can
// reenter PluginManager without deadlocking.
std::lock_guard reload_lk{entry->reload_mutex};
std::filesystem::path sourcePath;
{
std::lock_guard lock(m_mutex);
if (find(name) != entry.get()) {
return std::unexpected{LoadError::UnknownPlugin};
}
sourcePath = newPath.has_value() ? *newPath : entry->path;
}
auto tmp = hotswap_copy(sourcePath);
if (!tmp.has_value()) {
return std::unexpected{tmp.error()};
}
auto next = open_instance(*tmp, m_options.dlclose_on_swap);
std::error_code ec;
std::filesystem::remove(*tmp, ec);
if (!next.has_value()) {
Void::Log::warn("Plugin.Manager",
"reload '{}' failed: {}; keeping old", name,
to_string(next.error()));
return std::unexpected{next.error()};
}
if ((*next)->plugin->name() != name) {
Void::Log::warn("Plugin.Manager",
"replace '{}' rejected: candidate reports '{}'",
name, (*next)->plugin->name());
return std::unexpected{LoadError::NameMismatch};
}
if (m_options.candidate_validator &&
!m_options.candidate_validator(PluginHandle{*next})) {
Void::Log::warn("Plugin.Manager",
"reload '{}' aborted: binary validation failed",
name);
return std::unexpected{LoadError::ActivationFailed};
}
if (m_options.config_provider && (*next)->configure != nullptr) {
const std::string config = m_options.config_provider(name);
(*next)->configure((*next)->plugin, config.c_str());
}
auto old = entry->current.load(std::memory_order_acquire);
if (old) {
if (!transfer_state(*old, **next)) {
Void::Log::warn("Plugin.Manager",
"reload '{}' aborted: state rejected", name);
return std::unexpected{LoadError::StateRejected};
}
}
try {
(*next)->plugin->on_load();
} catch (...) {
return std::unexpected{LoadError::ActivationFailed};
}
if ((*next)->ready != nullptr &&
(*next)->ready((*next)->plugin) != 0) {
Void::Log::warn("Plugin.Manager",
"reload '{}' aborted: activation failed", name);
return std::unexpected{LoadError::ActivationFailed};
}
if (m_options.instance_validator &&
!m_options.instance_validator(*(*next)->plugin, (*next)->info)) {
Void::Log::warn("Plugin.Manager",
"reload '{}' aborted: host validation failed",
name);
return std::unexpected{LoadError::ActivationFailed};
}
{
std::lock_guard lock(m_mutex);
if (find(name) != entry.get()) {
return std::unexpected{LoadError::UnknownPlugin};
}
retired_old = entry->current.exchange(
std::move(*next), std::memory_order_acq_rel);
if (newPath.has_value()) {
restartWatcher = entry->watched;
if (restartWatcher) {
m_watcher.unwatch(entry->path);
}
entry->path = *newPath;
}
callbacks = reload_callbacks_locked();
}
}
// Drop old instance and invoke observers strictly outside all locks.
retired_old.reset();
if (restartWatcher) {
watch(name);
}
Void::Log::info("Plugin.Manager", "reloaded '{}'", name);
for (const auto& cb : callbacks) {
cb(name);
}
return {};
}
void PluginManager::watch(std::string_view name)
{
std::shared_ptr<Entry> entry;
std::filesystem::path path;
{
std::lock_guard lock(m_mutex);
entry = find_shared(name);
if (!entry) {
return;
}
path = entry->path;
entry->watched = true;
}
const std::string name_str{name};
m_watcher.watch(path, [this, entry, name_str](
const FileSystem::FileWatcher::Event& e) {
if (!e.exists) {
return;
}
(void)reload_entry_unlocked(entry, name_str, std::nullopt);
});
}
void PluginManager::unwatch(std::string_view name)
{
std::lock_guard lock(m_mutex);
auto* entry = find(name);
if (entry != nullptr) {
m_watcher.unwatch(entry->path);
entry->watched = false;
}
}
ReloadCallbackId PluginManager::on_reloaded(
std::function<void(std::string_view name)> cb)
{
std::lock_guard lock(m_mutex);
const ReloadCallbackId id = m_next_reload_id++;
m_on_reloaded.emplace_back(id, std::move(cb));
return id;
}
void PluginManager::remove_on_reloaded(ReloadCallbackId id)
{
std::lock_guard lock(m_mutex);
std::erase_if(m_on_reloaded,
[id](const auto& pair) { return pair.first == id; });
}
std::vector<std::function<void(std::string_view)>>
PluginManager::reload_callbacks_locked() const
{
std::vector<std::function<void(std::string_view)>> out;
out.reserve(m_on_reloaded.size());
for (const auto& [_, cb] : m_on_reloaded) {
out.push_back(cb);
}
return out;
}
std::optional<PluginManager::StateSnapshot>
PluginManager::serialize_state(std::string_view name) const
{
std::shared_ptr<detail::Instance> inst;
{
std::lock_guard lock(m_mutex);
auto* entry = find(name);
if (entry == nullptr) {
return std::nullopt;
}
inst = entry->current.load(std::memory_order_acquire);
}
if (!inst || inst->serialize == nullptr) {
return std::nullopt;
}
const char* json = inst->serialize(inst->plugin);
if (json == nullptr) {
return std::nullopt;
}
StateSnapshot snapshot{.json = std::string{json},
.version = inst->state_version != nullptr
? inst->state_version()
: 0};
if (inst->free_string != nullptr) {
inst->free_string(json);
}
return snapshot;
}
bool PluginManager::deserialize_state(std::string_view name,
std::string_view json,
std::uint32_t from_version)
{
std::shared_ptr<detail::Instance> inst;
{
std::lock_guard lock(m_mutex);
auto* entry = find(name);
if (entry == nullptr) {
return false;
}
inst = entry->current.load(std::memory_order_acquire);
}
if (!inst || inst->deserialize == nullptr) {
return false;
}
const std::string terminated{json};
return inst->deserialize(inst->plugin, terminated.c_str(),
from_version) == 0;
}
std::vector<std::string> PluginManager::names() const
{
std::lock_guard lock(m_mutex);
std::vector<std::string> out;
out.reserve(m_plugins.size());
for (const auto& [name, _] : m_plugins) {
out.push_back(name);
}
return out;
}
void* PluginManager::raw_symbol(std::string_view name,
const char* symbol) const
{
return acquire(name).raw_symbol(symbol);
}
} // namespace Void::Plugin