#include "Server.h" #include #include // Initialize the static instance pointer Server* Server::instance = nullptr; Server::Server() : reloadConfigFlag(false) { instance = this; // Set the instance pointer signal(SIGUSR1, Server::handleSignal); if (!config.loadFromFile("config.json")) { std::cerr << "Failed to load config.json" << std::endl; } loadPlugins(); for (int i = 0; i < 4; ++i) { threadPool.emplace_back(std::make_unique(&Server::handleIPC, this)); } } Server::~Server() { for (auto& handle : pluginHandles) { dlclose(handle); } } Server& Server::getInstance() { return *instance; } void Server::run() { mainLoop(); } void Server::reloadConfig() { if (config.loadFromFile("config.json")) { std::cout << "Configuration reloaded." << std::endl; for (auto& plugin : plugins) { plugin->updateConfig(config.getConfig()); } } else { std::cerr << "Failed to reload configuration." << std::endl; } } void Server::loadPlugins() { const char* pluginPath = "./plugins/libSamplePlugin.so"; void* handle = dlopen(pluginPath, RTLD_LAZY); if (!handle) { std::cerr << "Cannot open library: " << dlerror() << '\n'; return; } pluginHandles.push_back(handle); typedef IPlugin* (*create_t)(); create_t create_plugin = (create_t)dlsym(handle, "create"); const char* dlsym_error = dlerror(); if (dlsym_error) { std::cerr << "Cannot load symbol create: " << dlsym_error << '\n'; return; } std::shared_ptr plugin(create_plugin()); plugins.push_back(plugin); ipc.registerHandler(plugin); plugin->updateConfig(config.getConfig()); // Forward the config to the plugin } void Server::mainLoop() { while (true) { if (reloadConfigFlag.load()) { reloadConfig(); reloadConfigFlag.store(false); } std::this_thread::sleep_for(std::chrono::seconds(1)); } } void Server::handleIPC() { while (true) { auto message = ipc.receiveMessage(); if (message.has_value()) { for (auto& plugin : plugins) { plugin->handleMessage(message.value()); } } } } void Server::handleSignal(int signal) { if (signal == SIGUSR1) { std::cout << "Received signal to reload configuration." << std::endl; Server::getInstance().reloadConfigFlag.store(true); } }