diff options
author | Matthias Schiffer <matthias@gamezock.de> | 2009-06-18 22:03:02 +0200 |
---|---|---|
committer | Matthias Schiffer <matthias@gamezock.de> | 2009-06-18 22:03:02 +0200 |
commit | 7234fe326d16d6bf9f4374a09ddc6ef790e6723f (patch) | |
tree | 437d4c40eeb1e9b34b369e4b82064a1572c7dac9 | |
parent | bf561f8226e97f4ace4f04bddf198175e91ee7f0 (diff) | |
download | mad-7234fe326d16d6bf9f4374a09ddc6ef790e6723f.tar mad-7234fe326d16d6bf9f4374a09ddc6ef790e6723f.zip |
Globale Variablen durch Application-Klasse ersetzt
123 files changed, 1475 insertions, 1090 deletions
diff --git a/src/Client/Application.cpp b/src/Client/Application.cpp new file mode 100644 index 0000000..34a26bb --- /dev/null +++ b/src/Client/Application.cpp @@ -0,0 +1,33 @@ +/* + * Application.cpp + * + * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de> + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "Application.h" +#include "InformationManager.h" + +namespace Mad { +namespace Client { + +Application::Application() : Common::Application(false), informationManager(new InformationManager(this)) {} + +Application::~Application() { + delete informationManager; +} + +} +} diff --git a/src/Core/Initializable.h b/src/Client/Application.h index e7d329d..db861c2 100644 --- a/src/Core/Initializable.h +++ b/src/Client/Application.h @@ -1,7 +1,7 @@ /* - * Initializable.h + * Application.h * - * Copyright (C) 2008 Matthias Schiffer <matthias@gamezock.de> + * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the @@ -17,38 +17,30 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ -#ifndef MAD_CORE_INITIALIZABLE_H_ -#define MAD_CORE_INITIALIZABLE_H_ +#ifndef MAD_CLIENT_APPLICATION_H_ +#define MAD_CLIENT_APPLICATION_H_ -#include <stack> +#include <Common/Application.h> namespace Mad { -namespace Core { +namespace Client { -class Initializable { - private: - static std::stack<Initializable*> initializedObjects; - - bool initializing; - bool initialized; +class InformationManager; - protected: - Initializable() : initializing(false), initialized(false) {} - virtual void doInit() {} - virtual void doDeinit() {} +class Application : public Common::Application { + private: + InformationManager *informationManager; public: - virtual ~Initializable() {} - - void init(); - - bool isInitialized() const {return initialized;} - bool isInitializing() const {return initializing;} + Application(); + virtual ~Application(); - static void deinit(); + InformationManager* getInformationManager() const { + return informationManager; + } }; } } -#endif /* MAD_CORE_INITIALIZABLE_H_ */ +#endif /* MAD_CLIENT_APPLICATION_H_ */ diff --git a/src/Client/CMakeLists.txt b/src/Client/CMakeLists.txt index e663602..6d7ba4c 100644 --- a/src/Client/CMakeLists.txt +++ b/src/Client/CMakeLists.txt @@ -3,6 +3,7 @@ add_subdirectory(Requests) include_directories(${INCLUDES}) add_library(Client + Application.cpp Application.h CommandParser.cpp CommandParser.h InformationManager.cpp InformationManager.h SystemCommands.cpp SystemCommands.h diff --git a/src/Client/CommandParser.cpp b/src/Client/CommandParser.cpp index be2383a..f231082 100644 --- a/src/Client/CommandParser.cpp +++ b/src/Client/CommandParser.cpp @@ -18,11 +18,11 @@ */ #include "CommandParser.h" +#include "Application.h" #include "InformationManager.h" #include "SystemCommands.h" #include "UserCommands.h" -#include <Core/Logger.h> #include <Core/Tokenizer.h> #include <Common/RequestManager.h> @@ -52,8 +52,6 @@ const CommandParser::Command CommandParser::commands[] = { {{0}, 0, 0, 0, 0} }; -CommandParser CommandParser::commandParser; - const CommandParser::Command* CommandParser::findCommand(const std::string& command) { for(int i = 0; commands[i].commands[0] != 0; ++i) { @@ -71,12 +69,12 @@ void CommandParser::printUsage(const std::string& command) { const CommandParser::Command *cmd = findCommand(command); if(cmd) - Core::Logger::logf("Usage: %s\n", cmd->cmdline); + std::cerr << "Usage: " << cmd->cmdline << std::endl; } std::map<std::string, Common::HostInfo> CommandParser::parseHostList(const std::vector<std::string> &args, bool mustBeActive) { - const std::map<std::string, Common::HostInfo>& hosts = InformationManager::get()->getDaemons(); + const std::map<std::string, Common::HostInfo>& hosts = application->getInformationManager()->getDaemons(); std::map<std::string, Common::HostInfo> ret; for(std::vector<std::string>::const_iterator arg = args.begin(); arg != args.end(); ++arg) { @@ -88,7 +86,7 @@ std::map<std::string, Common::HostInfo> CommandParser::parseHostList(const std:: } if(ret.empty()) - Core::Logger::log("No hosts active."); + std::cerr << "No hosts active." << std::endl; } else { ret = hosts; @@ -98,9 +96,9 @@ std::map<std::string, Common::HostInfo> CommandParser::parseHostList(const std:: std::map<std::string, Common::HostInfo>::const_iterator host = hosts.find(*arg); if(host == hosts.end()) - Core::Logger::logf(Core::Logger::ERROR, "Host '%s' doesn't exist.", arg->c_str()); + std::cerr << "Host '" << *arg << "' doesn't exist." << std::endl; else if(mustBeActive && host->second.getState() == Common::HostInfo::INACTIVE) - Core::Logger::logf(Core::Logger::WARNING, "Host '%s' is inactive.", arg->c_str()); + std::cerr << "Host '" << *arg << "' is inactive." << std::endl; else ret.insert(*host); } @@ -109,7 +107,7 @@ std::map<std::string, Common::HostInfo> CommandParser::parseHostList(const std:: return ret; } -void CommandParser::helpCommand(const std::vector<std::string> &args, Common::Connection *connection _UNUSED_PARAMETER_) { +void CommandParser::helpCommand(const std::vector<std::string> &args) { if(args.size() == 1) { std::cout << "Available commands:" << std::endl << std::endl; @@ -130,16 +128,16 @@ void CommandParser::helpCommand(const std::vector<std::string> &args, Common::Co std::cout << command->longdesc << std::endl << std::endl; } else - Core::Logger::logf(Core::Logger::WARNING, "%s: Command '%s' doesn't exist.", args[0].c_str(), args[1].c_str()); + std::cerr << args[0] << ": Command '" << args[1] << "' doesn't exist." << std::endl; } else { - Core::Logger::logf(Core::Logger::ERROR, "%s: Too many arguments.", args[0].c_str()); + std::cerr << args[0] << ": Too many arguments." << std::endl; printUsage("help"); } } -void CommandParser::listHostsCommand(const std::vector<std::string> &args, Common::Connection *connection _UNUSED_PARAMETER_) { - const std::map<std::string, Common::HostInfo>& hosts = InformationManager::get()->getDaemons(); +void CommandParser::listHostsCommand(const std::vector<std::string> &args) { + const std::map<std::string, Common::HostInfo>& hosts = application->getInformationManager()->getDaemons(); if(args.size() == 1) { if(hosts.empty()) { @@ -167,7 +165,7 @@ void CommandParser::listHostsCommand(const std::vector<std::string> &args, Commo std::cout << std::endl; } else if(args.size() > 2) { - Core::Logger::logf(Core::Logger::ERROR, "%s: Too many arguments.", args[0].c_str()); + std::cerr << args[0] << ": Too many arguments." << std::endl; printUsage("list_hosts"); } else if(args[1] == "-a") { @@ -185,23 +183,23 @@ void CommandParser::listHostsCommand(const std::vector<std::string> &args, Commo std::cout << std::endl; } else { - Core::Logger::logf(Core::Logger::ERROR, "%s: Don't understand argument '%s'.", args[0].c_str(), args[1].c_str()); + std::cerr << args[0] << ": Don't understand argument '" << args[1] << "'." << std::endl; printUsage("list_hosts"); } } -void CommandParser::exitCommand(const std::vector<std::string> &args _UNUSED_PARAMETER_, Common::Connection *connection) { - boost::shared_ptr<Common::Requests::DisconnectRequest> request(new Common::Requests::DisconnectRequest); +void CommandParser::exitCommand(const std::vector<std::string> &args _UNUSED_PARAMETER_) { + boost::shared_ptr<Common::Requests::DisconnectRequest> request(new Common::Requests::DisconnectRequest(application)); - Common::RequestManager::get()->sendRequest(connection, request); + application->getRequestManager()->sendRequest(connection, request); request->wait(); std::pair<boost::shared_ptr<const Common::XmlPacket>, Core::Exception> result = request->getResult(); if(result.second) - Core::Logger::logf(Core::Logger::ERROR, "An error occurred during your request: %s.", result.second.strerror().c_str()); + std::cerr << "An error occurred during your request: " << result.second.strerror() << "." << std::endl; else - commandParser.disconnect = true; + disconnect = true; } bool CommandParser::parse(const std::string &cmd) { @@ -215,12 +213,15 @@ bool CommandParser::parse(const std::string &cmd) { const Command* command = findCommand(splitCmd[0]); if(command) - command->function(splitCmd, connection); + command->function(this, splitCmd); else - Core::Logger::logf(Core::Logger::ERROR, "Unknown command '%s'.", splitCmd[0].c_str()); + std::cerr << "Unknown command '" << splitCmd[0] << "'." << std::endl; return true; } +CommandParser::CommandParser(Application *application0, Common::Connection *connection0) +: application(application0), connection(connection0), disconnect(false) {} + } } diff --git a/src/Client/CommandParser.h b/src/Client/CommandParser.h index a7157ed..64dab1f 100644 --- a/src/Client/CommandParser.h +++ b/src/Client/CommandParser.h @@ -38,6 +38,7 @@ class Connection; namespace Client { +class Application; class SystemCommands; class UserCommands; @@ -52,12 +53,12 @@ class CommandParser { const char* desc; const char* longdesc; - boost::function2<void, const std::vector<std::string>, Common::Connection*> function; + boost::function2<void, CommandParser*, const std::vector<std::string> > function; }; static const Command commands[]; - static CommandParser commandParser; + Application *application; Common::Connection *connection; @@ -65,32 +66,24 @@ class CommandParser { static const Command* findCommand(const std::string& command); - static void printUsage(const std::string& command); - static std::map<std::string, Common::HostInfo> parseHostList(const std::vector<std::string> &args, bool mustBeActive = false); + void printUsage(const std::string& command); + std::map<std::string, Common::HostInfo> parseHostList(const std::vector<std::string> &args, bool mustBeActive = false); - static void helpCommand(const std::vector<std::string> &args, Common::Connection *connection); - static void listHostsCommand(const std::vector<std::string> &args, Common::Connection *connection); - static void exitCommand(const std::vector<std::string> &args, Common::Connection *connection); - - CommandParser() : connection(0), disconnect(false) {} + void helpCommand(const std::vector<std::string> &args); + void listHostsCommand(const std::vector<std::string> &args); + void exitCommand(const std::vector<std::string> &args); public: - static CommandParser *get() { - return &commandParser; - } + CommandParser(Application *application0, Common::Connection *connection0); Common::Connection *getConnection() const { return connection; } - void setConnection(Common::Connection *con) { - connection = con; - } - bool parse(const std::string &cmd); void requestDisconnect() { - exitCommand(std::vector<std::string>(), connection); + exitCommand(std::vector<std::string>()); } bool willDisconnect() const { diff --git a/src/Client/InformationManager.cpp b/src/Client/InformationManager.cpp index c5ff9f8..a4a63fb 100644 --- a/src/Client/InformationManager.cpp +++ b/src/Client/InformationManager.cpp @@ -18,40 +18,40 @@ */ #include "InformationManager.h" +#include "Application.h" #include "Requests/DaemonListRequest.h" -#include <Core/Logger.h> + #include <Common/RequestManager.h> namespace Mad { namespace Client { -InformationManager InformationManager::informationManager; - - void InformationManager::DaemonStateUpdateRequestHandler::handleRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret) { // TODO Require authentication + InformationManager *informationManager = dynamic_cast<Application&>(*getApplication()).getInformationManager(); + { - boost::lock_guard<boost::mutex> lock(informationManager.mutex); + boost::lock_guard<boost::mutex> lock(informationManager->mutex); - std::map<std::string, Common::HostInfo>::iterator host = informationManager.daemons.find((*packet)["name"]); - if(host != informationManager.daemons.end()) + std::map<std::string, Common::HostInfo>::iterator host = informationManager->daemons.find((*packet)["name"]); + if(host != informationManager->daemons.end()) host->second.setState((*packet)["state"]); else - Core::Logger::log(Core::Logger::WARNING, "Received a state update for an unknown host."); + getApplication()->log(Core::LoggerBase::WARNING, "Received a state update for an unknown host."); } ret->setType("OK"); } -void InformationManager::doInit() { - Common::RequestManager::get()->registerPacketType<DaemonStateUpdateRequestHandler>("UpdateHostState"); +InformationManager::InformationManager(Application *application0) : application(application0), updating(false) { + application->getRequestManager()->registerPacketType<DaemonStateUpdateRequestHandler>("UpdateHostState"); } -void InformationManager::doDeinit() { - Common::RequestManager::get()->unregisterPacketType("UpdateHostState"); +InformationManager::~InformationManager() { + application->getRequestManager()->unregisterPacketType("UpdateHostState"); } void InformationManager::updateDaemonList(Common::Connection *con) { @@ -60,10 +60,10 @@ void InformationManager::updateDaemonList(Common::Connection *con) { if(updating) return; - updateRequest = boost::shared_ptr<Requests::DaemonListRequest>(new Requests::DaemonListRequest); + updateRequest = boost::shared_ptr<Requests::DaemonListRequest>(new Requests::DaemonListRequest(application)); updateRequest->connectSignalFinished(boost::bind(&InformationManager::daemonListRequestFinished, this, _1, _2)); - Common::RequestManager::get()->sendRequest(con, updateRequest); + application->getRequestManager()->sendRequest(con, updateRequest); updating = true; } @@ -72,7 +72,7 @@ void InformationManager::daemonListRequestFinished(boost::shared_ptr<const Commo boost::lock_guard<boost::mutex> lock(mutex); if(!packet || error) { - Core::Logger::logf(Core::Logger::CRITICAL, "Host list request failed: %s", error.strerror().c_str()); + application->logf(Core::LoggerBase::CRITICAL, "Host list request failed: %s", error.strerror().c_str()); } else { const Common::XmlPacket::Element &hostInfo = (*packet)["hosts"]; diff --git a/src/Client/InformationManager.h b/src/Client/InformationManager.h index ffc24cf..ab84e3c 100644 --- a/src/Client/InformationManager.h +++ b/src/Client/InformationManager.h @@ -23,10 +23,9 @@ #include <map> #include <memory> -#include <Core/Initializable.h> - #include <Common/HostInfo.h> #include <Common/Request.h> +#include <Common/RequestHandlerGroup.h> #include <Common/RequestHandlers/SimpleRequestHandler.h> #include <boost/thread/condition_variable.hpp> @@ -36,17 +35,23 @@ namespace Mad { namespace Client { -class InformationManager : public Core::Initializable, private boost::noncopyable { +class Application; + +class InformationManager : private boost::noncopyable { private: class DaemonStateUpdateRequestHandler : public Common::RequestHandlers::SimpleRequestHandler { private: - static void handleRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret); + void handleRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret); public: - DaemonStateUpdateRequestHandler() : Common::RequestHandlers::SimpleRequestHandler("UpdateHostState", &DaemonStateUpdateRequestHandler::handleRequest) {} + DaemonStateUpdateRequestHandler(Common::Application *application) + : Common::RequestHandlers::SimpleRequestHandler(application, "UpdateHostState", + boost::bind(&DaemonStateUpdateRequestHandler::handleRequest, this, _1, _2)) {} }; - static InformationManager informationManager; + friend class Application; + + Application *application; boost::mutex mutex; @@ -56,19 +61,12 @@ class InformationManager : public Core::Initializable, private boost::noncopyabl bool updating; - InformationManager() : updating(false) {} - void daemonListRequestFinished(boost::shared_ptr<const Common::XmlPacket> packet, Core::Exception error); - protected: - virtual void doInit(); - virtual void doDeinit(); + InformationManager(Application *application0); + ~InformationManager(); public: - static InformationManager *get() { - return &informationManager; - } - void updateDaemonList(Common::Connection *con); bool isUpdating() { diff --git a/src/Client/Requests/DaemonCommandRequest.h b/src/Client/Requests/DaemonCommandRequest.h index 8559f87..5f01e1f 100644 --- a/src/Client/Requests/DaemonCommandRequest.h +++ b/src/Client/Requests/DaemonCommandRequest.h @@ -36,8 +36,8 @@ class DaemonCommandRequest : public Common::Request { virtual void sendRequest(); public: - DaemonCommandRequest(const std::string &daemon0, bool reboot0) - : daemon(daemon0), reboot(reboot0) {} + DaemonCommandRequest(Common::Application *application, const std::string &daemon0, bool reboot0) + : Common::Request(application), daemon(daemon0), reboot(reboot0) {} }; } diff --git a/src/Client/Requests/DaemonFSInfoRequest.h b/src/Client/Requests/DaemonFSInfoRequest.h index 58ca9a6..5be504f 100644 --- a/src/Client/Requests/DaemonFSInfoRequest.h +++ b/src/Client/Requests/DaemonFSInfoRequest.h @@ -36,7 +36,7 @@ class DaemonFSInfoRequest : public Common::Request { virtual void sendRequest(); public: - DaemonFSInfoRequest(const std::string &daemon0) : daemon(daemon0) {} + DaemonFSInfoRequest(Common::Application *application, const std::string &daemon0) : Common::Request(application), daemon(daemon0) {} }; } diff --git a/src/Client/Requests/DaemonListRequest.h b/src/Client/Requests/DaemonListRequest.h index d10efab..566fee7 100644 --- a/src/Client/Requests/DaemonListRequest.h +++ b/src/Client/Requests/DaemonListRequest.h @@ -28,7 +28,7 @@ namespace Requests { class DaemonListRequest : public Common::Requests::SimpleRequest { public: - DaemonListRequest() : SimpleRequest("ListHosts") {} + DaemonListRequest(Common::Application *application) : SimpleRequest(application, "ListHosts") {} }; } diff --git a/src/Client/Requests/DaemonStatusRequest.h b/src/Client/Requests/DaemonStatusRequest.h index 0642187..4035276 100644 --- a/src/Client/Requests/DaemonStatusRequest.h +++ b/src/Client/Requests/DaemonStatusRequest.h @@ -36,7 +36,7 @@ class DaemonStatusRequest : public Common::Request { virtual void sendRequest(); public: - DaemonStatusRequest(const std::string &daemon0) : daemon(daemon0) {} + DaemonStatusRequest(Common::Application *application, const std::string &daemon0) : Common::Request(application), daemon(daemon0) {} }; } diff --git a/src/Client/SystemCommands.cpp b/src/Client/SystemCommands.cpp index 490f278..5b2d4e5 100644 --- a/src/Client/SystemCommands.cpp +++ b/src/Client/SystemCommands.cpp @@ -18,9 +18,9 @@ */ #include "SystemCommands.h" +#include "Application.h" #include "CommandParser.h" -#include <Core/Logger.h> #include <Common/RequestManager.h> #include "Requests/DaemonFSInfoRequest.h" @@ -138,26 +138,26 @@ void SystemCommands::printHostStatus(boost::shared_ptr<const Common::XmlPacket> } -void SystemCommands::fsinfoCommand(const std::vector<std::string> &args, Common::Connection *connection) { +void SystemCommands::fsinfoCommand(CommandParser *commandParser, const std::vector<std::string> &args) { boost::shared_ptr<Common::Request> request; if(args.size() == 1) - request = boost::shared_ptr<Common::Requests::FSInfoRequest>(new Common::Requests::FSInfoRequest); + request = boost::shared_ptr<Common::Requests::FSInfoRequest>(new Common::Requests::FSInfoRequest(commandParser->application)); else if(args.size() == 2) - request = boost::shared_ptr<Requests::DaemonFSInfoRequest>(new Requests::DaemonFSInfoRequest(args[1])); + request = boost::shared_ptr<Requests::DaemonFSInfoRequest>(new Requests::DaemonFSInfoRequest(commandParser->application, args[1])); else { - Core::Logger::logf(Core::Logger::ERROR, "%s: Too many arguments.", args[0].c_str()); - CommandParser::printUsage("fsinfo"); + std::cerr << args[0] << ": Too many arguments." << std::endl; + commandParser->printUsage("fsinfo"); return; } - Common::RequestManager::get()->sendRequest(connection, request); + commandParser->application->getRequestManager()->sendRequest(commandParser->connection, request); request->wait(); std::pair<boost::shared_ptr<const Common::XmlPacket>, Core::Exception> result = request->getResult(); if(!result.first || result.second) { - Core::Logger::logf(Core::Logger::ERROR, "An error occurred during your request: %s.", result.second.strerror().c_str()); + std::cerr << "An error occurred during your request: " << result.second.strerror() << "." << std::endl; } else { if(args.size() == 1) @@ -169,20 +169,20 @@ void SystemCommands::fsinfoCommand(const std::vector<std::string> &args, Common: } } -void SystemCommands::rebootCommand(const std::vector<std::string> &args, Common::Connection *connection) { +void SystemCommands::rebootCommand(CommandParser *commandParser, const std::vector<std::string> &args) { if(args.size() < 2) { - Core::Logger::logf(Core::Logger::ERROR, "%s: No host given.", args[0].c_str()); - CommandParser::printUsage("reboot"); + std::cerr << args[0] << ": No host given." << std::endl; + commandParser->printUsage("reboot"); return; } - std::map<std::string, Common::HostInfo> hosts = CommandParser::parseHostList(std::vector<std::string>(args.begin()+1, args.end()), true); + std::map<std::string, Common::HostInfo> hosts = commandParser->parseHostList(std::vector<std::string>(args.begin()+1, args.end()), true); std::vector<boost::shared_ptr<Requests::DaemonCommandRequest> > requests; for(std::map<std::string, Common::HostInfo>::iterator host = hosts.begin(); host != hosts.end(); ++host) { - boost::shared_ptr<Requests::DaemonCommandRequest> request(new Requests::DaemonCommandRequest(host->first, true)); - Common::RequestManager::get()->sendRequest(connection, request); + boost::shared_ptr<Requests::DaemonCommandRequest> request(new Requests::DaemonCommandRequest(commandParser->application, host->first, true)); + commandParser->application->getRequestManager()->sendRequest(commandParser->connection, request); requests.push_back(request); } @@ -194,24 +194,24 @@ void SystemCommands::rebootCommand(const std::vector<std::string> &args, Common: std::pair<boost::shared_ptr<const Common::XmlPacket>, Core::Exception> result = (*request)->getResult(); if(result.second) - Core::Logger::logf(Core::Logger::ERROR, "An error occurred during your request: %s.", result.second.strerror().c_str()); + std::cerr << "An error occurred during your request: " << result.second.strerror() << "." << std::endl; } } -void SystemCommands::shutdownCommand(const std::vector<std::string> &args, Common::Connection *connection) { +void SystemCommands::shutdownCommand(CommandParser *commandParser, const std::vector<std::string> &args) { if(args.size() < 2) { - Core::Logger::logf(Core::Logger::ERROR, "%s: No host given.", args[0].c_str()); - CommandParser::printUsage("shutdown"); + std::cerr << args[0] << ": No host given." << std::endl; + commandParser->printUsage("shutdown"); return; } - std::map<std::string, Common::HostInfo> hosts = CommandParser::parseHostList(std::vector<std::string>(args.begin()+1, args.end()), true); + std::map<std::string, Common::HostInfo> hosts = commandParser->parseHostList(std::vector<std::string>(args.begin()+1, args.end()), true); std::vector<boost::shared_ptr<Requests::DaemonCommandRequest> > requests; for(std::map<std::string, Common::HostInfo>::iterator host = hosts.begin(); host != hosts.end(); ++host) { - boost::shared_ptr<Requests::DaemonCommandRequest> request(new Requests::DaemonCommandRequest(host->first, false)); - Common::RequestManager::get()->sendRequest(connection, request); + boost::shared_ptr<Requests::DaemonCommandRequest> request(new Requests::DaemonCommandRequest(commandParser->application, host->first, false)); + commandParser->application->getRequestManager()->sendRequest(commandParser->connection, request); requests.push_back(request); } @@ -223,30 +223,30 @@ void SystemCommands::shutdownCommand(const std::vector<std::string> &args, Commo std::pair<boost::shared_ptr<const Common::XmlPacket>, Core::Exception> result = (*request)->getResult(); if(result.second) - Core::Logger::logf(Core::Logger::ERROR, "An error occurred during your request: %s.", result.second.strerror().c_str()); + std::cerr << "An error occurred during your request: " << result.second.strerror() << "." << std::endl; } } -void SystemCommands::statusCommand(const std::vector<std::string> &args, Common::Connection *connection) { +void SystemCommands::statusCommand(CommandParser *commandParser, const std::vector<std::string> &args) { boost::shared_ptr<Common::Request> request; if(args.size() == 1) - request = boost::shared_ptr<Common::Requests::StatusRequest>(new Common::Requests::StatusRequest); + request = boost::shared_ptr<Common::Requests::StatusRequest>(new Common::Requests::StatusRequest(commandParser->application)); else if(args.size() == 2) - request = boost::shared_ptr<Requests::DaemonStatusRequest>(new Requests::DaemonStatusRequest(args[1])); + request = boost::shared_ptr<Requests::DaemonStatusRequest>(new Requests::DaemonStatusRequest(commandParser->application, args[1])); else { - Core::Logger::logf(Core::Logger::ERROR, "%s: Too many arguments.", args[0].c_str()); - CommandParser::printUsage("status"); + std::cerr << args[0] << ": Too many arguments." << std::endl; + commandParser->printUsage("status"); return; } - Common::RequestManager::get()->sendRequest(connection, request); + commandParser->application->getRequestManager()->sendRequest(commandParser->connection, request); request->wait(); std::pair<boost::shared_ptr<const Common::XmlPacket>, Core::Exception> result = request->getResult(); if(!result.first || result.second) { - Core::Logger::logf(Core::Logger::ERROR, "An error occurred during your request: %s.", result.second.strerror().c_str()); + std::cerr << "An error occurred during your request: " << result.second.strerror() << "." << std::endl; } else { if(args.size() == 1) diff --git a/src/Client/SystemCommands.h b/src/Client/SystemCommands.h index 142ebdc..a647bed 100644 --- a/src/Client/SystemCommands.h +++ b/src/Client/SystemCommands.h @@ -20,15 +20,17 @@ #ifndef MAD_CLIENT_SYSTEMCOMMANDS_H_ #define MAD_CLIENT_SYSTEMCOMMANDS_H_ -#include <Common/Connection.h> +#include <Common/XmlPacket.h> -#include <string> #include <vector> +#include <boost/shared_ptr.hpp> namespace Mad { namespace Client { +class CommandParser; + class SystemCommands { private: SystemCommands(); @@ -37,10 +39,10 @@ class SystemCommands { static void printHostStatus(boost::shared_ptr<const Common::XmlPacket> &packet); public: - static void fsinfoCommand(const std::vector<std::string> &args, Common::Connection *connection); - static void rebootCommand(const std::vector<std::string> &args, Common::Connection *connection); - static void shutdownCommand(const std::vector<std::string> &args, Common::Connection *connection); - static void statusCommand(const std::vector<std::string> &args, Common::Connection *connection); + static void fsinfoCommand(CommandParser *commandParser, const std::vector<std::string> &args); + static void rebootCommand(CommandParser *commandParser, const std::vector<std::string> &args); + static void shutdownCommand(CommandParser *commandParser, const std::vector<std::string> &args); + static void statusCommand(CommandParser *commandParser, const std::vector<std::string> &args); }; } diff --git a/src/Client/UserCommands.cpp b/src/Client/UserCommands.cpp index 97ea27b..a1cfd0f 100644 --- a/src/Client/UserCommands.cpp +++ b/src/Client/UserCommands.cpp @@ -18,9 +18,9 @@ */ #include "UserCommands.h" +#include "Application.h" #include "CommandParser.h" -#include <Core/Logger.h> #include <Common/RequestManager.h> #include <Common/Requests/GroupListRequest.h> @@ -35,34 +35,34 @@ namespace Mad { namespace Client { -void UserCommands::userInfoCommand(const std::vector<std::string> &args, Common::Connection *connection) { +void UserCommands::userInfoCommand(CommandParser *commandParser, const std::vector<std::string> &args) { if(args.size() == 1) { - Core::Logger::logf(Core::Logger::ERROR, "%s: No user id given.", args[0].c_str()); - CommandParser::printUsage("user_info"); + std::cerr << args[0] << ": No user id given." << std::endl; + commandParser->printUsage("user_info"); return; } if(args.size() > 2) { - Core::Logger::logf(Core::Logger::ERROR, "%s: Too many arguments.", args[0].c_str()); - CommandParser::printUsage("user_info"); + std::cerr << args[0] << ": Too many arguments." << std::endl; + commandParser->printUsage("user_info"); return; } char *endptr; unsigned long uid = std::strtoul(args[1].c_str(), &endptr, 10); if(args[1].empty() || *endptr != '\0') { - Core::Logger::logf(Core::Logger::ERROR, "%s: Unable to parse user id.", args[0].c_str()); - CommandParser::printUsage("user_info"); + std::cerr << args[0] << ": Unable to parse user id." << std::endl; + commandParser->printUsage("user_info"); return; } - boost::shared_ptr<Common::Requests::UserInfoRequest> request(new Common::Requests::UserInfoRequest(uid)); - Common::RequestManager::get()->sendRequest(connection, request); + boost::shared_ptr<Common::Requests::UserInfoRequest> request(new Common::Requests::UserInfoRequest(commandParser->application, uid)); + commandParser->application->getRequestManager()->sendRequest(commandParser->connection, request); request->wait(); std::pair<boost::shared_ptr<const Common::XmlPacket>, Core::Exception> result = request->getResult(); if(!result.first || result.second) { - Core::Logger::logf(Core::Logger::ERROR, "An error occurred during your request: %s.", result.second.strerror().c_str()); + std::cerr << "An error occurred during your request: " << result.second.strerror() << "." << std::endl; } else { const Common::XmlPacket &packet = *result.first; @@ -72,16 +72,16 @@ void UserCommands::userInfoCommand(const std::vector<std::string> &args, Common: } } -void UserCommands::listUsersCommand(const std::vector<std::string> &args _UNUSED_PARAMETER_, Common::Connection *connection) { - boost::shared_ptr<Common::Requests::UserListRequest> request(new Common::Requests::UserListRequest); +void UserCommands::listUsersCommand(CommandParser *commandParser, const std::vector<std::string> &args _UNUSED_PARAMETER_) { + boost::shared_ptr<Common::Requests::UserListRequest> request(new Common::Requests::UserListRequest(commandParser->application)); - Common::RequestManager::get()->sendRequest(connection, request); + commandParser->application->getRequestManager()->sendRequest(commandParser->connection, request); request->wait(); std::pair<boost::shared_ptr<const Common::XmlPacket>, Core::Exception> result = request->getResult(); if(!result.first || result.second) { - Core::Logger::logf(Core::Logger::ERROR, "An error occurred during your request: %s.", result.second.strerror().c_str()); + std::cerr << "An error occurred during your request: " << result.second.strerror() << "." << std::endl; } else { const Common::XmlPacket::Element &users = (*result.first)["users"]; @@ -101,34 +101,34 @@ void UserCommands::listUsersCommand(const std::vector<std::string> &args _UNUSED } } -void UserCommands::listUserGroupsCommand(const std::vector<std::string> &args, Common::Connection *connection) { +void UserCommands::listUserGroupsCommand(CommandParser *commandParser, const std::vector<std::string> &args) { if(args.size() == 1) { - Core::Logger::logf(Core::Logger::ERROR, "%s: No user id given.", args[0].c_str()); - CommandParser::printUsage("list_user_groups"); + std::cerr << args[0] << ": No user id given." << std::endl; + commandParser->printUsage("list_user_groups"); return; } if(args.size() > 2) { - Core::Logger::logf(Core::Logger::ERROR, "%s: Too many arguments.", args[0].c_str()); - CommandParser::printUsage("list_user_groups"); + std::cerr << args[0] << ": Too many arguments." << std::endl; + commandParser->printUsage("list_user_groups"); return; } char *endptr; unsigned long uid = std::strtoul(args[1].c_str(), &endptr, 10); if(args[1].empty() || *endptr != '\0') { - Core::Logger::logf(Core::Logger::ERROR, "%s: Unable to parse user id.", args[0].c_str()); - CommandParser::printUsage("list_user_groups"); + std::cerr << args[0] << ": Unable to parse user id." << std::endl; + commandParser->printUsage("list_user_groups"); return; } - boost::shared_ptr<Common::Requests::UserGroupListRequest> request(new Common::Requests::UserGroupListRequest(uid)); - Common::RequestManager::get()->sendRequest(connection, request); + boost::shared_ptr<Common::Requests::UserGroupListRequest> request(new Common::Requests::UserGroupListRequest(commandParser->application, uid)); + commandParser->application->getRequestManager()->sendRequest(commandParser->connection, request); request->wait(); std::pair<boost::shared_ptr<const Common::XmlPacket>, Core::Exception> result = request->getResult(); if(!result.first || result.second) { - Core::Logger::logf(Core::Logger::ERROR, "An error occurred during your request: %s.", result.second.strerror().c_str()); + std::cerr << "An error occurred during your request: " << result.second.strerror() << "." << std::endl; } else { const Common::XmlPacket::Element &groups = (*result.first)["groups"]; @@ -149,16 +149,16 @@ void UserCommands::listUserGroupsCommand(const std::vector<std::string> &args, C } } -void UserCommands::listGroupsCommand(const std::vector<std::string> &args _UNUSED_PARAMETER_, Common::Connection *connection) { - boost::shared_ptr<Common::Requests::GroupListRequest> request(new Common::Requests::GroupListRequest); +void UserCommands::listGroupsCommand(CommandParser *commandParser, const std::vector<std::string> &args _UNUSED_PARAMETER_) { + boost::shared_ptr<Common::Requests::GroupListRequest> request(new Common::Requests::GroupListRequest(commandParser->application)); - Common::RequestManager::get()->sendRequest(connection, request); + commandParser->application->getRequestManager()->sendRequest(commandParser->connection, request); request->wait(); std::pair<boost::shared_ptr<const Common::XmlPacket>, Core::Exception> result = request->getResult(); if(!result.first || result.second) { - Core::Logger::logf(Core::Logger::ERROR, "An error occurred during your request: %s.", result.second.strerror().c_str()); + std::cerr << "An error occurred during your request: " << result.second.strerror() << "." << std::endl; } else { const Common::XmlPacket::Element &groups = (*result.first)["groups"]; @@ -178,34 +178,34 @@ void UserCommands::listGroupsCommand(const std::vector<std::string> &args _UNUSE } } -void UserCommands::listGroupUsersCommand(const std::vector<std::string> &args, Common::Connection *connection) { +void UserCommands::listGroupUsersCommand(CommandParser *commandParser, const std::vector<std::string> &args) { if(args.size() == 1) { - Core::Logger::logf(Core::Logger::ERROR, "%s: No group id given.", args[0].c_str()); - CommandParser::printUsage("list_group_users"); + std::cerr << args[0] << ": No group id given." << std::endl; + commandParser->printUsage("list_group_users"); return; } if(args.size() > 2) { - Core::Logger::logf(Core::Logger::ERROR, "%s: Too many arguments.", args[0].c_str()); - CommandParser::printUsage("list_group_users"); + std::cerr << args[0] << ": Too many arguments." << std::endl; + commandParser->printUsage("list_group_users"); return; } char *endptr; unsigned long gid = std::strtoul(args[1].c_str(), &endptr, 10); if(args[1].empty() || *endptr != '\0') { - Core::Logger::logf(Core::Logger::ERROR, "%s: Unable to parse group id.", args[0].c_str()); - CommandParser::printUsage("list_group_users"); + std::cerr << args[0] << ": Unable to parse group id." << std::endl; + commandParser->printUsage("list_group_users"); return; } - boost::shared_ptr<Common::Requests::GroupUserListRequest> request(new Common::Requests::GroupUserListRequest(gid)); - Common::RequestManager::get()->sendRequest(connection, request); + boost::shared_ptr<Common::Requests::GroupUserListRequest> request(new Common::Requests::GroupUserListRequest(commandParser->application, gid)); + commandParser->application->getRequestManager()->sendRequest(commandParser->connection, request); request->wait(); std::pair<boost::shared_ptr<const Common::XmlPacket>, Core::Exception> result = request->getResult(); if(!result.first || result.second) { - Core::Logger::logf(Core::Logger::ERROR, "An error occurred during your request: %s.", result.second.strerror().c_str()); + std::cerr << "An error occurred during your request: " << result.second.strerror() << "." << std::endl; } else { const Common::XmlPacket::Element &users = (*result.first)["users"]; diff --git a/src/Client/UserCommands.h b/src/Client/UserCommands.h index c4cd399..f3dd31c 100644 --- a/src/Client/UserCommands.h +++ b/src/Client/UserCommands.h @@ -20,25 +20,24 @@ #ifndef MAD_CLIENT_USERCOMMANDS_H_ #define MAD_CLIENT_USERCOMMANDS_H_ -#include <Common/Connection.h> - #include <string> #include <vector> - namespace Mad { namespace Client { +class CommandParser; + class UserCommands { private: UserCommands(); public: - static void userInfoCommand(const std::vector<std::string> &args, Common::Connection *connection); - static void listUsersCommand(const std::vector<std::string> &args, Common::Connection *connection); - static void listUserGroupsCommand(const std::vector<std::string> &args, Common::Connection *connection); - static void listGroupsCommand(const std::vector<std::string> &args, Common::Connection *connection); - static void listGroupUsersCommand(const std::vector<std::string> &args, Common::Connection *connection); + static void userInfoCommand(CommandParser *commandParser, const std::vector<std::string> &args); + static void listUsersCommand(CommandParser *commandParser, const std::vector<std::string> &args); + static void listUserGroupsCommand(CommandParser *commandParser, const std::vector<std::string> &args); + static void listGroupsCommand(CommandParser *commandParser, const std::vector<std::string> &args); + static void listGroupUsersCommand(CommandParser *commandParser, const std::vector<std::string> &args); }; } diff --git a/src/Common/Application.cpp b/src/Common/Application.cpp new file mode 100644 index 0000000..950e61b --- /dev/null +++ b/src/Common/Application.cpp @@ -0,0 +1,38 @@ +/* + * Application.cpp + * + * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de> + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "Application.h" +#include "ModuleManager.h" +#include "RequestManager.h" +#include "SystemManager.h" + +namespace Mad { +namespace Common { + +Application::Application(bool server) : moduleManager(new ModuleManager(this)), requestManager(new RequestManager(this, server)), +systemManager(new SystemManager) {} + +Application::~Application() { + delete systemManager; + delete requestManager; + delete moduleManager; +} + +} +} diff --git a/src/Common/Application.h b/src/Common/Application.h new file mode 100644 index 0000000..332e4c7 --- /dev/null +++ b/src/Common/Application.h @@ -0,0 +1,59 @@ +/* + * Application.h + * + * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de> + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef MAD_COMMON_APPLICATION_H_ +#define MAD_COMMON_APPLICATION_H_ + +#include <Core/Application.h> + +namespace Mad { +namespace Common { + +class ModuleManager; +class RequestManager; +class SystemManager; + +class Application : public Core::Application { + private: + ModuleManager *moduleManager; + RequestManager *requestManager; + SystemManager *systemManager; + + protected: + Application(bool server); + virtual ~Application(); + + public: + ModuleManager* getModuleManager() const { + return moduleManager; + } + + RequestManager* getRequestManager() const { + return requestManager; + } + + SystemManager* getSystemManager() const { + return systemManager; + } +}; + +} +} + +#endif /* MAD_COMMON_APPLICATION_H_ */ diff --git a/src/Common/CMakeLists.txt b/src/Common/CMakeLists.txt index 078df71..4a4eb8e 100644 --- a/src/Common/CMakeLists.txt +++ b/src/Common/CMakeLists.txt @@ -6,11 +6,13 @@ include_directories(${INCLUDES}) link_directories(${LTDL_LIBRARY_DIR}) add_library(Common + Application.cpp Application.h Base64Encoder.cpp Base64Encoder.h ClientConnection.cpp ClientConnection.h Connection.cpp Connection.h GroupInfo.h HostInfo.h + Module.h ModuleManager.cpp ModuleManager.h Request.cpp Request.h RequestHandler.cpp RequestHandler.h diff --git a/src/Common/ClientConnection.cpp b/src/Common/ClientConnection.cpp index ba558f4..4438c8f 100644 --- a/src/Common/ClientConnection.cpp +++ b/src/Common/ClientConnection.cpp @@ -24,7 +24,7 @@ namespace Mad { namespace Common { -ClientConnection::ClientConnection() : connection(new Net::ClientConnection) { +ClientConnection::ClientConnection(Core::Application *application) : Connection(application), connection(new Net::ClientConnection(application)) { connection->connectSignalReceive(boost::bind(&ClientConnection::receive, this, _1)); } diff --git a/src/Common/ClientConnection.h b/src/Common/ClientConnection.h index 305df44..ab0dbb8 100644 --- a/src/Common/ClientConnection.h +++ b/src/Common/ClientConnection.h @@ -41,7 +41,7 @@ class ClientConnection : public Connection { virtual bool send(const Net::Packet &packet); public: - ClientConnection(); + ClientConnection(Core::Application *application); virtual ~ClientConnection() {} void connect(const boost::asio::ip::tcp::endpoint &address) throw(Core::Exception); diff --git a/src/Common/Connection.h b/src/Common/Connection.h index 6700574..9680452 100644 --- a/src/Common/Connection.h +++ b/src/Common/Connection.h @@ -42,7 +42,7 @@ class Connection : private boost::noncopyable { Core::Signals::Signal2<boost::shared_ptr<const XmlPacket>, uint16_t> signalReceive; protected: - Connection() : authenticated(0) {} + Connection(Core::Application *application) : authenticated(0), signalReceive(application) {} void receive(boost::shared_ptr<Net::Packet> packet); diff --git a/src/Common/Module.h b/src/Common/Module.h new file mode 100644 index 0000000..877649c --- /dev/null +++ b/src/Common/Module.h @@ -0,0 +1,37 @@ +/* + * Module.h + * + * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de> + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef MAD_COMMON_MODULE_H_ +#define MAD_COMMON_MODULE_H_ + +namespace Mad { +namespace Common { + +class Module { + protected: + Module() {} + + public: + virtual ~Module() {} +}; + +} +} + +#endif /* MAD_COMMON_MODULE_H_ */ diff --git a/src/Common/ModuleManager.cpp b/src/Common/ModuleManager.cpp index bec3618..738532f 100644 --- a/src/Common/ModuleManager.cpp +++ b/src/Common/ModuleManager.cpp @@ -21,10 +21,10 @@ #include <config.h> #include "ModuleManager.h" +#include "Application.h" #include <Core/ConfigEntry.h> -#include <Core/Logger.h> - +#include <Core/ConfigManager.h> //extern const lt_dlsymlist lt_preloaded_symbols[]; @@ -32,24 +32,25 @@ namespace Mad { namespace Common { -ModuleManager ModuleManager::moduleManager; - - -int ModuleManager::preopenCallback(lt_dlhandle handle) { +/*int ModuleManager::preopenCallback(lt_dlhandle handle) { moduleManager.modules.insert(std::make_pair(lt_dlgetinfo(handle)->name, std::make_pair(handle, false))); return 0; -} +}*/ -void ModuleManager::doInit() { +ModuleManager::ModuleManager(Application *application0) : application(application0) { lt_dlinit(); //lt_dlpreload_default(lt_preloaded_symbols); - lt_dlpreload(0); - lt_dlpreload_open("@PROGRAM@", &ModuleManager::preopenCallback); + //lt_dlpreload(0); + //lt_dlpreload_open("@PROGRAM@", &ModuleManager::preopenCallback); + + application->getConfigManager()->registerConfigurable(this); } -void ModuleManager::doDeinit() { +ModuleManager::~ModuleManager() { + application->getConfigManager()->unregisterConfigurable(this); + while(!moduleOrder.empty()) { unloadModule(moduleOrder.top()); moduleOrder.pop(); @@ -64,7 +65,7 @@ bool ModuleManager::handleConfigEntry(const Core::ConfigEntry &entry, bool handl if(entry[0].getKey().matches("LoadModule")) { if(!loadModule(entry[0][0].c_str())) - Core::Logger::logf(Core::Logger::ERROR, "Can't load module '%s'.", entry[0][0].c_str()); + application->logf(Core::LoggerBase::ERROR, "Can't load module '%s'.", entry[0][0].c_str()); return true; } @@ -73,7 +74,7 @@ bool ModuleManager::handleConfigEntry(const Core::ConfigEntry &entry, bool handl } lt_dlhandle ModuleManager::loadModule(const std::string &name) { - std::map<std::string, std::pair<lt_dlhandle, bool> >::iterator mod = modules.find(name); + std::map<std::string, std::pair<lt_dlhandle, Module*> >::iterator mod = modules.find(name); if(mod == modules.end()) { lt_dlhandle handle = lt_dlopen((name + MODULE_SUFFIX).c_str()); @@ -81,28 +82,25 @@ lt_dlhandle ModuleManager::loadModule(const std::string &name) { if(!handle) return 0; - mod = modules.insert(std::make_pair(lt_dlgetinfo(handle)->name, std::make_pair(handle, false))).first; + mod = modules.insert(std::make_pair(lt_dlgetinfo(handle)->name, std::make_pair(handle, (Module*)0))).first; } if(!mod->second.second) { - void (*initFun)() = (void(*)())lt_dlsym(mod->second.first, (name + "_init").c_str()); + ModuleLoadFunc loader = (ModuleLoadFunc)lt_dlsym(mod->second.first, (name + "_create").c_str()); + + if(!loader) + return 0; - if(initFun) - (*initFun)(); + mod->second.second = loader(application); - mod->second.second = true; - moduleOrder.push(name); + if(mod->second.second) + moduleOrder.push(name); } return mod->second.first; } void ModuleManager::unloadModule(const std::string &name) { - void (*deinitFun)(); - deinitFun = (void(*)())lt_dlsym(modules[name].first, (name + "_deinit").c_str()); - - if(deinitFun) - (*deinitFun)(); - + delete modules[name].second; lt_dlclose(modules[name].first); modules.erase(name); diff --git a/src/Common/ModuleManager.h b/src/Common/ModuleManager.h index de5535f..eb8c800 100644 --- a/src/Common/ModuleManager.h +++ b/src/Common/ModuleManager.h @@ -20,8 +20,10 @@ #ifndef MAD_COMMON_MODULEMANAGER_H_ #define MAD_COMMON_MODULEMANAGER_H_ +#include "Module.h" #include <Core/Configurable.h> -#include <Core/Initializable.h> + +#include <boost/noncopyable.hpp> #include <map> #include <stack> @@ -32,32 +34,31 @@ namespace Mad { namespace Common { -class ModuleManager : public Core::Configurable, public Core::Initializable { +class Application; + +class ModuleManager : public Core::Configurable, private boost::noncopyable { private: - static ModuleManager moduleManager; + friend class Application; + + typedef Module* (*ModuleLoadFunc)(Application*); + + Application *application; - std::map<std::string, std::pair<lt_dlhandle, bool> > modules; + std::map<std::string, std::pair<lt_dlhandle, Module*> > modules; std::stack<std::string> moduleOrder; - static int preopenCallback(lt_dlhandle handle); + //static int preopenCallback(lt_dlhandle handle); + + ModuleManager(Application *application0); + ~ModuleManager(); void unloadModule(const std::string &name); protected: - virtual void doInit(); - virtual void doDeinit(); - virtual bool handleConfigEntry(const Core::ConfigEntry &entry, bool handled); public: lt_dlhandle loadModule(const std::string &name); - - static ModuleManager* get() { - if(!moduleManager.isInitialized()) - moduleManager.init(); - - return &moduleManager; - } }; } diff --git a/src/Common/Request.h b/src/Common/Request.h index ac59e45..d1b5851 100644 --- a/src/Common/Request.h +++ b/src/Common/Request.h @@ -47,7 +47,7 @@ class Request : public RequestHandler { Core::Signals::Signal2<boost::shared_ptr<const XmlPacket>, Core::Exception> finished; protected: - Request() : isFinished(false) {} + Request(Application *application) : RequestHandler(application), isFinished(false), finished(application) {} void signalFinished(boost::shared_ptr<const XmlPacket> pkt, Core::Exception exp) { { diff --git a/src/Common/RequestHandler.cpp b/src/Common/RequestHandler.cpp index 218155d..91ddce6 100644 --- a/src/Common/RequestHandler.cpp +++ b/src/Common/RequestHandler.cpp @@ -23,12 +23,14 @@ namespace Mad { namespace Common { +RequestHandler::RequestHandler(Application *application0) : application(application0), finished(application) {} + Connection* RequestHandler::getConnection() const { - return RequestManager::get()->requestMap.getRequestInfo(this).first; + return getRequestManager()->requestMap.getRequestInfo(this).first; } void RequestHandler::sendPacket(const XmlPacket &packet) { - std::pair<Connection*, boost::uint16_t> requestInfo = RequestManager::get()->requestMap.getRequestInfo(this); + std::pair<Connection*, boost::uint16_t> requestInfo = getRequestManager()->requestMap.getRequestInfo(this); if(!requestInfo.first) return; diff --git a/src/Common/RequestHandler.h b/src/Common/RequestHandler.h index 3deb8c0..096ff45 100644 --- a/src/Common/RequestHandler.h +++ b/src/Common/RequestHandler.h @@ -20,31 +20,32 @@ #ifndef MAD_COMMON_REQUESTHANDLER_H_ #define MAD_COMMON_REQUESTHANDLER_H_ +#include "Application.h" #include "Connection.h" #include "XmlPacket.h" #include <Core/Signals.h> #include <boost/cstdint.hpp> -#include <boost/thread/locks.hpp> -#include <boost/thread/mutex.hpp> namespace Mad { namespace Common { class Connection; -class RequestManager; class RequestHandler : private boost::noncopyable { private: friend class RequestManager; - boost::mutex mutex; + Application *application; Core::Signals::Signal0 finished; protected: - RequestHandler() {} + Application* getApplication() const {return application;} + RequestManager* getRequestManager() const {return application->getRequestManager();} + + RequestHandler(Application *application0); void signalFinished() { finished.emit(); diff --git a/src/Common/RequestHandlerGroup.h b/src/Common/RequestHandlerGroup.h index c9f57eb..135111a 100644 --- a/src/Common/RequestHandlerGroup.h +++ b/src/Common/RequestHandlerGroup.h @@ -35,7 +35,7 @@ class RequestHandlerGroup { public: virtual const std::set<std::string>& getPacketTypes() = 0; - virtual boost::shared_ptr<RequestHandler> createRequestHandler(const std::string &type) = 0; + virtual boost::shared_ptr<RequestHandler> createRequestHandler(Application *application, const std::string &type) = 0; virtual ~RequestHandlerGroup() {} }; diff --git a/src/Common/RequestHandlers/DisconnectRequestHandler.cpp b/src/Common/RequestHandlers/DisconnectRequestHandler.cpp index 6c89ab2..11256b1 100644 --- a/src/Common/RequestHandlers/DisconnectRequestHandler.cpp +++ b/src/Common/RequestHandlers/DisconnectRequestHandler.cpp @@ -19,7 +19,6 @@ #include "DisconnectRequestHandler.h" #include <Core/Exception.h> -#include <Core/Logger.h> namespace Mad { namespace Common { @@ -27,7 +26,7 @@ namespace RequestHandlers { void DisconnectRequestHandler::handlePacket(boost::shared_ptr<const XmlPacket> packet) { if(packet->getType() != "Disconnect") { - Core::Logger::log(Core::Logger::ERROR, "Received an unexpected packet."); + getApplication()->log(Core::LoggerBase::ERROR, "Received an unexpected packet."); XmlPacket ret; ret.setType("Error"); diff --git a/src/Common/RequestHandlers/DisconnectRequestHandler.h b/src/Common/RequestHandlers/DisconnectRequestHandler.h index 963f603..d94bc73 100644 --- a/src/Common/RequestHandlers/DisconnectRequestHandler.h +++ b/src/Common/RequestHandlers/DisconnectRequestHandler.h @@ -29,6 +29,9 @@ namespace RequestHandlers { class DisconnectRequestHandler : public RequestHandler { protected: virtual void handlePacket(boost::shared_ptr<const XmlPacket> packet); + + public: + DisconnectRequestHandler(Application *application) : RequestHandler(application) {} }; } diff --git a/src/Common/RequestHandlers/FSInfoRequestHandler.cpp b/src/Common/RequestHandlers/FSInfoRequestHandler.cpp index 7ac4644..c036f7b 100644 --- a/src/Common/RequestHandlers/FSInfoRequestHandler.cpp +++ b/src/Common/RequestHandlers/FSInfoRequestHandler.cpp @@ -28,7 +28,7 @@ void FSInfoRequestHandler::handleRequest(boost::shared_ptr<const Common::XmlPack // TODO Require authentication std::vector<SystemManager::FSInfo> fsInfo; - SystemManager::get()->getFSInfo(&fsInfo); + getApplication()->getSystemManager()->getFSInfo(&fsInfo); ret->setType("OK"); ret->addList("filesystems"); diff --git a/src/Common/RequestHandlers/FSInfoRequestHandler.h b/src/Common/RequestHandlers/FSInfoRequestHandler.h index 167e116..27a1af3 100644 --- a/src/Common/RequestHandlers/FSInfoRequestHandler.h +++ b/src/Common/RequestHandlers/FSInfoRequestHandler.h @@ -28,10 +28,10 @@ namespace RequestHandlers { class FSInfoRequestHandler : public SimpleRequestHandler { private: - static void handleRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret); + void handleRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret); public: - FSInfoRequestHandler() : SimpleRequestHandler("FSInfo", &FSInfoRequestHandler::handleRequest) {} + FSInfoRequestHandler(Application *application) : SimpleRequestHandler(application, "FSInfo", boost::bind(&FSInfoRequestHandler::handleRequest, this, _1, _2)) {} }; } diff --git a/src/Common/RequestHandlers/SimpleRequestHandler.cpp b/src/Common/RequestHandlers/SimpleRequestHandler.cpp index b6de0f4..b6a22bf 100644 --- a/src/Common/RequestHandlers/SimpleRequestHandler.cpp +++ b/src/Common/RequestHandlers/SimpleRequestHandler.cpp @@ -19,7 +19,6 @@ #include "SimpleRequestHandler.h" -#include <Core/Logger.h> #include <Core/Exception.h> namespace Mad { @@ -28,7 +27,7 @@ namespace RequestHandlers { void SimpleRequestHandler::handlePacket(boost::shared_ptr<const XmlPacket> packet) { if(packet->getType() != type) { - Core::Logger::log(Core::Logger::ERROR, "Received an unexpected packet."); + getApplication()->log(Core::LoggerBase::ERROR, "Received an unexpected packet."); XmlPacket ret; ret.setType("Error"); diff --git a/src/Common/RequestHandlers/SimpleRequestHandler.h b/src/Common/RequestHandlers/SimpleRequestHandler.h index 5d388d3..0c295b5 100644 --- a/src/Common/RequestHandlers/SimpleRequestHandler.h +++ b/src/Common/RequestHandlers/SimpleRequestHandler.h @@ -26,20 +26,16 @@ namespace Mad { namespace Common { namespace RequestHandlers { -class SimpleRequestHandlerGroup; - class SimpleRequestHandler : public RequestHandler { private: - friend class SimpleRequestHandlerGroup; - std::string type; boost::function2<void, boost::shared_ptr<const XmlPacket>, XmlPacket*> handler; protected: virtual void handlePacket(boost::shared_ptr<const XmlPacket> packet); - SimpleRequestHandler(const std::string &type0, const boost::function2<void, boost::shared_ptr<const XmlPacket>, XmlPacket*> &handler0) - : type(type0), handler(handler0) {} + SimpleRequestHandler(Application *application, const std::string &type0, const boost::function2<void, boost::shared_ptr<const XmlPacket>, XmlPacket*> &handler0) + : RequestHandler(application), type(type0), handler(handler0) {} }; } diff --git a/src/Common/RequestHandlers/SimpleRequestHandlerGroup.cpp b/src/Common/RequestHandlers/SimpleRequestHandlerGroup.cpp index 9c80e23..845021d 100644 --- a/src/Common/RequestHandlers/SimpleRequestHandlerGroup.cpp +++ b/src/Common/RequestHandlers/SimpleRequestHandlerGroup.cpp @@ -20,17 +20,52 @@ #include "SimpleRequestHandlerGroup.h" #include "SimpleRequestHandler.h" +#include <Core/Exception.h> + namespace Mad { namespace Common { namespace RequestHandlers { -boost::shared_ptr<RequestHandler> SimpleRequestHandlerGroup::createRequestHandler(const std::string &type) { - std::map<std::string, boost::function2<void, boost::shared_ptr<const XmlPacket>, XmlPacket*> >::iterator handler = handlers.find(type); +void SimpleRequestHandlerGroup::GroupRequestHandler::handlePacket(boost::shared_ptr<const XmlPacket> packet) { + if(packet->getType() != type) { + getApplication()->log(Core::LoggerBase::ERROR, "Received an unexpected packet."); + + XmlPacket ret; + ret.setType("Error"); + ret.add("ErrorCode", Core::Exception::UNEXPECTED_PACKET); + + sendPacket(ret); + + signalFinished(); + return; + } + + // TODO Require authentication + + XmlPacket ret; + + try { + handler(packet, &ret, getConnection()); + } + catch(Core::Exception e) { + ret.setType("Error"); + ret.add("ErrorCode", e.getErrorCode()); + ret.add("SubCode", e.getSubCode()); + ret.add("SubSubCode", e.getSubSubCode()); + ret.add("Where", e.getWhere()); + } + + sendPacket(ret); + signalFinished(); +} + +boost::shared_ptr<RequestHandler> SimpleRequestHandlerGroup::createRequestHandler(Application *application, const std::string &type) { + std::map<std::string, boost::function3<void, boost::shared_ptr<const XmlPacket>, XmlPacket*, Connection*> >::iterator handler = handlers.find(type); if(handler == handlers.end()) return boost::shared_ptr<RequestHandler>(); else - return boost::shared_ptr<SimpleRequestHandler>(new SimpleRequestHandler(type, handler->second)); + return boost::shared_ptr<GroupRequestHandler>(new GroupRequestHandler(application, type, handler->second)); } } diff --git a/src/Common/RequestHandlers/SimpleRequestHandlerGroup.h b/src/Common/RequestHandlers/SimpleRequestHandlerGroup.h index 86009f3..32e46ce 100644 --- a/src/Common/RequestHandlers/SimpleRequestHandlerGroup.h +++ b/src/Common/RequestHandlers/SimpleRequestHandlerGroup.h @@ -28,11 +28,24 @@ namespace RequestHandlers { class SimpleRequestHandlerGroup : public RequestHandlerGroup { private: + class GroupRequestHandler : public RequestHandler { + private: + std::string type; + boost::function3<void, boost::shared_ptr<const XmlPacket>, XmlPacket*, Connection*> handler; + + protected: + virtual void handlePacket(boost::shared_ptr<const XmlPacket> packet); + + public: + GroupRequestHandler(Application *application, const std::string &type0, const boost::function3<void, boost::shared_ptr<const XmlPacket>, XmlPacket*, Connection*> &handler0) + : RequestHandler(application), type(type0), handler(handler0) {} + }; + std::set<std::string> types; - std::map<std::string, boost::function2<void, boost::shared_ptr<const XmlPacket>, XmlPacket*> > handlers; + std::map<std::string, boost::function3<void, boost::shared_ptr<const XmlPacket>, XmlPacket*, Connection*> > handlers; protected: - void registerHandler(const std::string &type, const boost::function2<void, boost::shared_ptr<const XmlPacket>, XmlPacket*> &handler) { + void registerHandler(const std::string &type, const boost::function3<void, boost::shared_ptr<const XmlPacket>, XmlPacket*, Connection*> &handler) { types.insert(type); handlers.insert(std::make_pair(type, handler)); } @@ -44,7 +57,7 @@ class SimpleRequestHandlerGroup : public RequestHandlerGroup { return types; } - virtual boost::shared_ptr<RequestHandler> createRequestHandler(const std::string &type); + virtual boost::shared_ptr<RequestHandler> createRequestHandler(Application *application, const std::string &type); }; } diff --git a/src/Common/RequestHandlers/StatusRequestHandler.cpp b/src/Common/RequestHandlers/StatusRequestHandler.cpp index 7abcd7f..50dbe11 100644 --- a/src/Common/RequestHandlers/StatusRequestHandler.cpp +++ b/src/Common/RequestHandlers/StatusRequestHandler.cpp @@ -32,7 +32,7 @@ void StatusRequestHandler::handleRequest(boost::shared_ptr<const Common::XmlPack try { unsigned long uptime, idleTime; - SystemManager::get()->getUptimeInfo(&uptime, &idleTime); + getApplication()->getSystemManager()->getUptimeInfo(&uptime, &idleTime); ret->add("uptime", uptime); ret->add("idleTime", idleTime); @@ -42,7 +42,7 @@ void StatusRequestHandler::handleRequest(boost::shared_ptr<const Common::XmlPack try { unsigned long totalMem, freeMem, totalSwap, freeSwap; - SystemManager::get()->getMemoryInfo(&totalMem, &freeMem, &totalSwap, &freeSwap); + getApplication()->getSystemManager()->getMemoryInfo(&totalMem, &freeMem, &totalSwap, &freeSwap); ret->add("totalMem", totalMem); ret->add("freeMem", freeMem); @@ -55,7 +55,7 @@ void StatusRequestHandler::handleRequest(boost::shared_ptr<const Common::XmlPack unsigned long currentLoad, nProcesses; float loadAvg1, loadAvg5, loadAvg15; - SystemManager::get()->getLoadInfo(¤tLoad, &nProcesses, &loadAvg1, &loadAvg5, &loadAvg15); + getApplication()->getSystemManager()->getLoadInfo(¤tLoad, &nProcesses, &loadAvg1, &loadAvg5, &loadAvg15); ret->add("currentLoad", currentLoad); ret->add("nProcesses", nProcesses); diff --git a/src/Common/RequestHandlers/StatusRequestHandler.h b/src/Common/RequestHandlers/StatusRequestHandler.h index 5583733..24158c9 100644 --- a/src/Common/RequestHandlers/StatusRequestHandler.h +++ b/src/Common/RequestHandlers/StatusRequestHandler.h @@ -28,10 +28,10 @@ namespace RequestHandlers { class StatusRequestHandler : public SimpleRequestHandler { private: - static void handleRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret); + void handleRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret); public: - StatusRequestHandler() : SimpleRequestHandler("GetStatus", &StatusRequestHandler::handleRequest) {} + StatusRequestHandler(Application *application) : SimpleRequestHandler(application, "GetStatus", boost::bind(&StatusRequestHandler::handleRequest, this, _1, _2)) {} }; } diff --git a/src/Common/RequestManager.cpp b/src/Common/RequestManager.cpp index a8b817f..c8b27a2 100644 --- a/src/Common/RequestManager.cpp +++ b/src/Common/RequestManager.cpp @@ -19,16 +19,12 @@ #include "RequestManager.h" #include "RequestHandlers/DisconnectRequestHandler.h" -#include <Core/Logger.h> #include <boost/bind.hpp> namespace Mad { namespace Common { -RequestManager RequestManager::requestManager; - - void RequestManager::RequestMap::unregisterConnection(Connection *connection) { std::map<Connection*, IdMap>::iterator idMap = connectionMap.find(connection); if(idMap == connectionMap.end()) @@ -96,21 +92,21 @@ void RequestManager::receiveHandler(Connection *connection, boost::shared_ptr<co boost::shared_ptr<RequestHandler> request = requestMap.findRequest(connection, requestId); if(request) { lock.unlock(); - Core::ThreadManager::get()->pushWork(boost::bind(&RequestHandler::handlePacket, request, packet)); + application->getThreadManager()->pushWork(boost::bind(&RequestHandler::handlePacket, request, packet)); return; } if(!requestMap.isConnectionRegistered(connection)) { // TODO: Error - Core::Logger::log(Core::Logger::ERROR, "Received a packet from an unregistered connection."); + application->log(Core::LoggerBase::ERROR, "Received a packet from an unregistered connection."); return; } std::map<std::string, boost::shared_ptr<RequestHandlerGroup> >::iterator rgh = requestHandlerGroups.find(packet->getType()); if(rgh != requestHandlerGroups.end()) { - request = rgh->second->createRequestHandler(packet->getType()); + request = rgh->second->createRequestHandler(application, packet->getType()); if(request) { { @@ -122,7 +118,7 @@ void RequestManager::receiveHandler(Connection *connection, boost::shared_ptr<co } lock.unlock(); - Core::ThreadManager::get()->pushWork(boost::bind(&RequestHandler::handlePacket, request, packet)); + application->getThreadManager()->pushWork(boost::bind(&RequestHandler::handlePacket, request, packet)); return; } @@ -130,7 +126,7 @@ void RequestManager::receiveHandler(Connection *connection, boost::shared_ptr<co lock.unlock(); - Core::Logger::logf(Core::Logger::ERROR, "Received an unexpected packet with type '%s'.", packet->getType().c_str()); + application->logf(Core::LoggerBase::ERROR, "Received an unexpected packet with type '%s'.", packet->getType().c_str()); XmlPacket ret; ret.setType("Error"); @@ -143,20 +139,20 @@ bool RequestManager::sendRequest(Connection *connection, boost::shared_ptr<Reque boost::unique_lock<boost::shared_mutex> lock(mutex); if(!requestMap.isConnectionRegistered(connection)) { - Core::Logger::log(Core::Logger::CRITICAL, "Trying to send a request over an unregistered connecion."); + application->log(Core::LoggerBase::CRITICAL, "Trying to send a request over an unregistered connecion."); return false; } uint16_t requestId = _getUnusedRequestId(connection); if(request->isFinished || !requestMap.addRequest(connection, requestId, request)) { - Core::Logger::log(Core::Logger::CRITICAL, "Trying resend a request."); + application->log(Core::LoggerBase::CRITICAL, "Trying resend a request."); return false; } request->connectSignalFinished(boost::bind(&RequestManager::handleRequestFinished, this, connection, requestId)); lock.unlock(); - Core::ThreadManager::get()->pushWork(boost::bind(&Request::sendRequest, request)); + application->getThreadManager()->pushWork(boost::bind(&Request::sendRequest, request)); return true; } @@ -176,7 +172,7 @@ void RequestManager::registerConnection(Connection *connection) { connection->connectSignalReceive(boost::bind(&RequestManager::receiveHandler, this, connection, _1, _2)); } -RequestManager::RequestManager() : server(false), lastRequestId(-1) { +RequestManager::RequestManager(Application *application0, bool server) : application(application0), lastRequestId(server ? 0 : -1) { registerPacketType<RequestHandlers::DisconnectRequestHandler>("Disconnect"); } diff --git a/src/Common/RequestManager.h b/src/Common/RequestManager.h index 2dd892e..fb67748 100644 --- a/src/Common/RequestManager.h +++ b/src/Common/RequestManager.h @@ -33,8 +33,11 @@ namespace Mad { namespace Common { -class RequestManager : boost::noncopyable { +class Application; + +class RequestManager : private boost::noncopyable { private: + friend class Application; friend class RequestHandler; class RequestMap : private boost::noncopyable { @@ -78,18 +81,17 @@ class RequestManager : boost::noncopyable { return types; } - virtual boost::shared_ptr<RequestHandler> createRequestHandler(const std::string &type _UNUSED_PARAMETER_) { - return boost::shared_ptr<RequestHandler>(new T()); + virtual boost::shared_ptr<RequestHandler> createRequestHandler(Application *application, const std::string &type _UNUSED_PARAMETER_) { + return boost::shared_ptr<RequestHandler>(new T(application)); } }; - static RequestManager requestManager; + Application *application; boost::shared_mutex mutex; RequestMap requestMap; - bool server; boost::uint16_t lastRequestId; std::map<std::string, boost::shared_ptr<RequestHandlerGroup> > requestHandlerGroups; @@ -109,29 +111,9 @@ class RequestManager : boost::noncopyable { bool send(Request *request); - RequestManager(); + RequestManager(Application *application0, bool server); public: - static RequestManager* get() { - return &requestManager; - } - - bool isServer() { - boost::shared_lock<boost::shared_mutex> lock(mutex); - return server; - } - - void setServer(bool newServer) { - boost::lock_guard<boost::shared_mutex> lock(mutex); - - server = newServer; - - if(server) - lastRequestId &= ~0x01; - else - lastRequestId |= 0x01; - } - void registerConnection(Connection *connection); void unregisterConnection(Connection *connection) { diff --git a/src/Common/Requests/DisconnectRequest.h b/src/Common/Requests/DisconnectRequest.h index 6da0ac9..f8150bd 100644 --- a/src/Common/Requests/DisconnectRequest.h +++ b/src/Common/Requests/DisconnectRequest.h @@ -30,6 +30,9 @@ class DisconnectRequest : public Request { protected: virtual void sendRequest(); virtual void handlePacket(boost::shared_ptr<const XmlPacket> packet); + + public: + DisconnectRequest(Application *application) : Request(application) {} }; } diff --git a/src/Common/Requests/FSInfoRequest.h b/src/Common/Requests/FSInfoRequest.h index 250889a..2bd9eeb 100644 --- a/src/Common/Requests/FSInfoRequest.h +++ b/src/Common/Requests/FSInfoRequest.h @@ -28,7 +28,7 @@ namespace Requests { class FSInfoRequest : public SimpleRequest { public: - FSInfoRequest() : SimpleRequest("FSInfo") {} + FSInfoRequest(Application *application) : SimpleRequest(application, "FSInfo") {} }; } diff --git a/src/Common/Requests/GroupListRequest.h b/src/Common/Requests/GroupListRequest.h index b1e4115..f8760ca 100644 --- a/src/Common/Requests/GroupListRequest.h +++ b/src/Common/Requests/GroupListRequest.h @@ -28,7 +28,7 @@ namespace Requests { class GroupListRequest : public SimpleRequest { public: - GroupListRequest() : SimpleRequest("ListGroups") {} + GroupListRequest(Application *application) : SimpleRequest(application, "ListGroups") {} }; } diff --git a/src/Common/Requests/GroupUserListRequest.h b/src/Common/Requests/GroupUserListRequest.h index bb735f1..f95cd3b 100644 --- a/src/Common/Requests/GroupUserListRequest.h +++ b/src/Common/Requests/GroupUserListRequest.h @@ -34,7 +34,7 @@ class GroupUserListRequest : public Request { virtual void sendRequest(); public: - GroupUserListRequest(unsigned long gid0) : gid(gid0) {} + GroupUserListRequest(Application *application, unsigned long gid0) : Request(application), gid(gid0) {} }; } diff --git a/src/Common/Requests/IdentifyRequest.h b/src/Common/Requests/IdentifyRequest.h index 3084ce6..2ca9d8e 100644 --- a/src/Common/Requests/IdentifyRequest.h +++ b/src/Common/Requests/IdentifyRequest.h @@ -36,7 +36,7 @@ class IdentifyRequest : public Common::Request { virtual void sendRequest(); public: - IdentifyRequest(const std::string &hostname0 = std::string()) : hostname(hostname0) {} + IdentifyRequest(Application *application, const std::string &hostname0 = std::string()) : Request(application), hostname(hostname0) {} }; } diff --git a/src/Common/Requests/SimpleRequest.h b/src/Common/Requests/SimpleRequest.h index d381ecf..649f34c 100644 --- a/src/Common/Requests/SimpleRequest.h +++ b/src/Common/Requests/SimpleRequest.h @@ -34,7 +34,7 @@ class SimpleRequest : public Request { virtual void sendRequest(); - SimpleRequest(const std::string &type0) : type(type0) {} + SimpleRequest(Application *application, const std::string &type0) : Request(application), type(type0) {} }; } diff --git a/src/Common/Requests/StatusRequest.h b/src/Common/Requests/StatusRequest.h index b9b9f02..c30e0d5 100644 --- a/src/Common/Requests/StatusRequest.h +++ b/src/Common/Requests/StatusRequest.h @@ -28,7 +28,7 @@ namespace Requests { class StatusRequest : public SimpleRequest { public: - StatusRequest() : SimpleRequest("GetStatus") {} + StatusRequest(Application *application) : SimpleRequest(application, "GetStatus") {} }; } diff --git a/src/Common/Requests/UserGroupListRequest.h b/src/Common/Requests/UserGroupListRequest.h index 82db411..4cd27b6 100644 --- a/src/Common/Requests/UserGroupListRequest.h +++ b/src/Common/Requests/UserGroupListRequest.h @@ -34,7 +34,7 @@ class UserGroupListRequest : public Request { virtual void sendRequest(); public: - UserGroupListRequest(unsigned long uid0) : uid(uid0) {} + UserGroupListRequest(Application *application, unsigned long uid0) : Request(application), uid(uid0) {} }; } diff --git a/src/Common/Requests/UserInfoRequest.h b/src/Common/Requests/UserInfoRequest.h index c9ac89b..7b4b2fc 100644 --- a/src/Common/Requests/UserInfoRequest.h +++ b/src/Common/Requests/UserInfoRequest.h @@ -34,8 +34,7 @@ class UserInfoRequest : public Request { virtual void sendRequest(); public: - UserInfoRequest(unsigned long uid0) - : uid(uid0) {} + UserInfoRequest(Application *application, unsigned long uid0) : Request(application), uid(uid0) {} }; } diff --git a/src/Common/Requests/UserListRequest.h b/src/Common/Requests/UserListRequest.h index 9b69564..9196166 100644 --- a/src/Common/Requests/UserListRequest.h +++ b/src/Common/Requests/UserListRequest.h @@ -28,7 +28,7 @@ namespace Requests { class UserListRequest : public SimpleRequest { public: - UserListRequest() : SimpleRequest("ListUsers") {} + UserListRequest(Application *application) : SimpleRequest(application, "ListUsers") {} }; } diff --git a/src/Common/SystemManager.cpp b/src/Common/SystemManager.cpp index fac50d5..deb361a 100644 --- a/src/Common/SystemManager.cpp +++ b/src/Common/SystemManager.cpp @@ -23,9 +23,6 @@ namespace Mad { namespace Common { -SystemManager SystemManager::systemManager; - - bool SystemManager::Compare::operator() (boost::shared_ptr<SystemBackend> b1, boost::shared_ptr<SystemBackend> b2) { if(b1->getPriority() == b2->getPriority()) return (b1.get() > b2.get()); diff --git a/src/Common/SystemManager.h b/src/Common/SystemManager.h index 6870489..e8567c5 100644 --- a/src/Common/SystemManager.h +++ b/src/Common/SystemManager.h @@ -24,6 +24,7 @@ #include <string> #include <vector> +#include <boost/noncopyable.hpp> #include <boost/smart_ptr.hpp> #include <Core/Exception.h> @@ -31,16 +32,17 @@ namespace Mad { namespace Common { +class Application; class SystemBackend; -class SystemManager { +class SystemManager : private boost::noncopyable { private: + friend class Application; + struct Compare { bool operator() (boost::shared_ptr<SystemBackend> b1, boost::shared_ptr<SystemBackend> b2); }; - static SystemManager systemManager; - std::set<boost::shared_ptr<SystemBackend>, Compare> backends; SystemManager() {} @@ -70,10 +72,6 @@ class SystemManager { void shutdown() throw(Core::Exception); void reboot() throw(Core::Exception); - - static SystemManager *get() { - return &systemManager; - } }; } diff --git a/src/Core/Logger.cpp b/src/Core/Application.cpp index e4e0341..7c92ed6 100644 --- a/src/Core/Logger.cpp +++ b/src/Core/Application.cpp @@ -1,7 +1,7 @@ /* - * Logger.cpp + * Application.cpp * - * Copyright (C) 2008 Johannes Thorn <dante@g4t3.de> + * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the @@ -17,15 +17,26 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ -#include "Logger.h" +#include "Application.h" +#include "ConfigManager.h" #include "LogManager.h" +#include "ThreadManager.h" #include <cstdlib> namespace Mad { namespace Core { -void Logger::logfv(MessageCategory category, MessageLevel level, const char *format, va_list ap) { +Application::Application() : configManager(new ConfigManager(this)), logManager(new LogManager(this)), threadManager(new ThreadManager(this)) {} + +Application::~Application() { + delete threadManager; + delete logManager; + delete configManager; +} + + +void Application::logfv(LoggerBase::MessageCategory category, LoggerBase::MessageLevel level, const char *format, va_list ap) { int size = 100; char *buf = (char*)std::malloc(size); @@ -38,7 +49,7 @@ void Logger::logfv(MessageCategory category, MessageLevel level, const char *for va_end(ap2); if(n > -1 && n < size) { - log(category, level, buf); + logManager->log(category, level, std::time(0), buf); std::free(buf); return; } @@ -53,35 +64,35 @@ void Logger::logfv(MessageCategory category, MessageLevel level, const char *for } -void Logger::log(MessageCategory category, MessageLevel level, const std::string &message) { - LogManager::get()->log(category, level, std::time(0), message); +void Application::log(LoggerBase::MessageCategory category, LoggerBase::MessageLevel level, const std::string &message) { + logManager->log(category, level, std::time(0), message); } -void Logger::logf(MessageCategory category, MessageLevel level, const char *format, ...) { +void Application::logf(LoggerBase::MessageCategory category, LoggerBase::MessageLevel level, const char *format, ...) { va_list ap; va_start(ap, format); logfv(category, level, format, ap); va_end(ap); } -void Logger::logf(MessageCategory category, const char *format, ...) { +void Application::logf(LoggerBase::MessageCategory category, const char *format, ...) { va_list ap; va_start(ap, format); - logfv(category, DEFAULT, format, ap); + logfv(category, LoggerBase::DEFAULT, format, ap); va_end(ap); } -void Logger::logf(MessageLevel level, const char *format, ...) { +void Application::logf(LoggerBase::MessageLevel level, const char *format, ...) { va_list ap; va_start(ap, format); - logfv(GENERAL, level, format, ap); + logfv(LoggerBase::GENERAL, level, format, ap); va_end(ap); } -void Logger::logf(const char *format, ...) { +void Application::logf(const char *format, ...) { va_list ap; va_start(ap, format); - logfv(GENERAL, DEFAULT, format, ap); + logfv(LoggerBase::GENERAL, LoggerBase::DEFAULT, format, ap); va_end(ap); } diff --git a/src/Core/Application.h b/src/Core/Application.h new file mode 100644 index 0000000..bfc23db --- /dev/null +++ b/src/Core/Application.h @@ -0,0 +1,94 @@ +/* + * Application.h + * + * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de> + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef MAD_CORE_APPLICATION_H_ +#define MAD_CORE_APPLICATION_H_ + +#include "LoggerBase.h" + +#include <cstdarg> +#include <string> + +#include <boost/asio/io_service.hpp> +#include <boost/noncopyable.hpp> + +namespace Mad { +namespace Core { + +class ConfigManager; +class LogManager; +class ThreadManager; + +class Application : private boost::noncopyable { + private: + boost::asio::io_service ioService; + + ConfigManager *configManager; + LogManager *logManager; + ThreadManager *threadManager; + + void logfv(LoggerBase::MessageCategory category, LoggerBase::MessageLevel level, const char *format, va_list ap); + + protected: + Application(); + virtual ~Application(); + + public: + boost::asio::io_service& getIOService() { + return ioService; + } + + ConfigManager* getConfigManager() const { + return configManager; + } + + LogManager* getLogManager() const { + return logManager; + } + + ThreadManager* getThreadManager() const { + return threadManager; + } + + + void log(LoggerBase::MessageCategory category, LoggerBase::MessageLevel level, const std::string &message); + + void log(LoggerBase::MessageCategory category, const std::string &message) { + log(category, LoggerBase::DEFAULT, message); + } + + void log(LoggerBase::MessageLevel level, const std::string &message) { + log(LoggerBase::GENERAL, level, message); + } + + void log(const std::string &message) { + log(LoggerBase::GENERAL, LoggerBase::DEFAULT, message); + } + + + void logf(LoggerBase::MessageCategory category, LoggerBase::MessageLevel level, const char *format, ...); + void logf(LoggerBase::MessageCategory category, const char *format, ...); + void logf(LoggerBase::MessageLevel level, const char *format, ...); + void logf(const char *format, ...); +}; + +} +} + +#endif /* MAD_CORE_APPLICATION_H_ */ diff --git a/src/Core/CMakeLists.txt b/src/Core/CMakeLists.txt index 30947e3..9693460 100644 --- a/src/Core/CMakeLists.txt +++ b/src/Core/CMakeLists.txt @@ -9,12 +9,12 @@ add_library(Core Signals/Signal2.h Signals/SignalBase.h + Application.cpp Application.h ConfigEntry.cpp ConfigEntry.h ConfigManager.cpp ConfigManager.h Configurable.h Exception.cpp Exception.h - Initializable.cpp Initializable.h - Logger.cpp Logger.h + Logger.h LoggerBase.h LogManager.cpp LogManager.h RemoteLogger.h diff --git a/src/Core/ConfigManager.cpp b/src/Core/ConfigManager.cpp index 8b1ebd4..9e0dada 100644 --- a/src/Core/ConfigManager.cpp +++ b/src/Core/ConfigManager.cpp @@ -17,11 +17,10 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ +#include "Application.h" #include "ConfigManager.h" #include "ConfigEntry.h" #include "Configurable.h" -#include "Logger.h" -#include "LogManager.h" #include "Tokenizer.h" #include <fstream> @@ -30,9 +29,6 @@ namespace Mad { namespace Core { -ConfigManager ConfigManager::configManager; - - bool ConfigManager::Compare::operator() (const Configurable *c1, const Configurable *c2) { if(c1->getPriority() != c2->getPriority()) return c1->getPriority() > c2->getPriority(); @@ -50,7 +46,7 @@ void ConfigManager::handleConfigEntry(const ConfigEntry &entry) { } if(!handled) - Logger::logf(Logger::WARNING, "Invalid config option '%s'.", entry[entry.getSize()-1].getKey().c_str()); + application->logf(LoggerBase::WARNING, "Invalid config option '%s'.", entry[entry.getSize()-1].getKey().c_str()); } bool ConfigManager::loadFile(const std::string &filename) { @@ -129,13 +125,5 @@ void ConfigManager::finish() { finished = true; } -ConfigManager::ConfigManager() : finished(false) { - registerConfigurable(LogManager::get()); -} - -ConfigManager::~ConfigManager() { - unregisterConfigurable(LogManager::get()); -} - } } diff --git a/src/Core/ConfigManager.h b/src/Core/ConfigManager.h index 2d49a97..d7d7d01 100644 --- a/src/Core/ConfigManager.h +++ b/src/Core/ConfigManager.h @@ -27,6 +27,7 @@ namespace Mad { namespace Core { +class Application; class ConfigEntry; class Configurable; @@ -36,13 +37,14 @@ class ConfigManager { bool operator() (const Configurable *c1, const Configurable *c2); }; - static ConfigManager configManager; + friend class Application; + + Application *application; std::set<Configurable*, Compare> configurables; bool finished; - ConfigManager(); - ~ConfigManager(); + ConfigManager(Application *application0) : application(application0), finished(false) {} void handleConfigEntry(const ConfigEntry &entry); @@ -57,10 +59,6 @@ class ConfigManager { void unregisterConfigurable(Configurable *c) { configurables.erase(c); } - - static ConfigManager *get() { - return &configManager; - } }; } diff --git a/src/Core/Initializable.cpp b/src/Core/Initializable.cpp deleted file mode 100644 index 95d527f..0000000 --- a/src/Core/Initializable.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Initializable.cpp - * - * Copyright (C) 2008 Matthias Schiffer <matthias@gamezock.de> - * - * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -#include "Initializable.h" - -#include "ConfigManager.h" -#include "Configurable.h" -#include "Logger.h" - -namespace Mad { -namespace Core { - -std::stack<Initializable*> Initializable::initializedObjects; - -void Initializable::init() { - if(initialized) - return; - - if(initializing) { - Logger::log(Logger::CRITICAL, "Fatal initialization error: cyclic dependencies."); - std::terminate(); - } - - initializing = true; - - doInit(); - - Configurable *c = dynamic_cast<Configurable*>(this); - if(c) - ConfigManager::get()->registerConfigurable(c); - - initializing = false; - initialized = true; - initializedObjects.push(this); -} - -void Initializable::deinit() { - while(!initializedObjects.empty()) { - Initializable *in = initializedObjects.top(); - - Configurable *c = dynamic_cast<Configurable*>(in); - if(c) - ConfigManager::get()->unregisterConfigurable(c); - - in->doDeinit(); - in->initialized = false; - - initializedObjects.pop(); - } -} - -} -} diff --git a/src/Core/LogManager.cpp b/src/Core/LogManager.cpp index 91149f9..28b1f6f 100644 --- a/src/Core/LogManager.cpp +++ b/src/Core/LogManager.cpp @@ -18,16 +18,15 @@ */ #include "LogManager.h" +#include "Application.h" #include "ConfigEntry.h" +#include "ConfigManager.h" #include <iostream> namespace Mad { namespace Core { -LogManager LogManager::logManager; - - void LogManager::ConsoleLogger::logMessage(MessageCategory category _UNUSED_PARAMETER_, MessageLevel level, time_t timestamp _UNUSED_PARAMETER_, const std::string &message) { if(level != CRITICAL) {// Critical messages are printed to cerr directly, so don't print them a second time cerrLock.lock(); @@ -49,6 +48,15 @@ void LogManager::ConsoleLogger::logMessageDirect(MessageCategory category _UNUSE } +LogManager::LogManager(Application *application0) : application(application0), consoleLogger(new ConsoleLogger), configured(false), running(false) { + application->getConfigManager()->registerConfigurable(this); +} + +LogManager::~LogManager() { + application->getConfigManager()->unregisterConfigurable(this); +} + + bool LogManager::handleConfigEntry(const ConfigEntry &entry, bool handled) { if(handled) return false; @@ -61,7 +69,7 @@ bool LogManager::handleConfigEntry(const ConfigEntry &entry, bool handled) { } } else if(entry[1].empty()) { - Logger::logf(Logger::WARNING, "Unknown logger '%s'.", entry[0][0].c_str()); + application->logf(Logger::WARNING, "Unknown logger '%s'.", entry[0][0].c_str()); return true; } } diff --git a/src/Core/LogManager.h b/src/Core/LogManager.h index 8c8d091..0ed21b8 100644 --- a/src/Core/LogManager.h +++ b/src/Core/LogManager.h @@ -35,10 +35,12 @@ namespace Mad { namespace Core { +class Application; class ThreadManager; class LogManager : public Configurable { private: + friend class Application; friend class ThreadManager; typedef LoggerBase::MessageCategory MessageCategory; @@ -76,7 +78,7 @@ class LogManager : public Configurable { }; - static LogManager logManager; + Application *application; boost::shared_ptr<ConsoleLogger> consoleLogger; @@ -101,7 +103,8 @@ class LogManager : public Configurable { queueCond.notify_one(); } - LogManager() : consoleLogger(new ConsoleLogger), configured(false), running(false) {} + LogManager(Application *application0); + ~LogManager(); protected: virtual bool handleConfigEntry(const ConfigEntry &entry, bool handled); @@ -134,10 +137,6 @@ class LogManager : public Configurable { remoteLoggers.erase(logger); remoteLoggerLock.unlock(); } - - static LogManager *get() { - return &logManager; - } }; } diff --git a/src/Core/Logger.h b/src/Core/Logger.h index 3de22d2..6a8e752 100644 --- a/src/Core/Logger.h +++ b/src/Core/Logger.h @@ -22,7 +22,6 @@ #include "LoggerBase.h" -#include <cstdarg> #include <ctime> #include <string> @@ -32,34 +31,11 @@ namespace Core { class LogManager; class Logger : public LoggerBase { - private: + protected: friend class LogManager; - static void logfv(MessageCategory category, MessageLevel level, const char *format, va_list ap); - - protected: virtual void logMessage(MessageCategory category, MessageLevel level, time_t timestamp, const std::string &message) = 0; - public: - static void log(MessageCategory category, MessageLevel level, const std::string &message); - - static void log(MessageCategory category, const std::string &message) { - log(category, DEFAULT, message); - } - - static void log(MessageLevel level, const std::string &message) { - log(GENERAL, level, message); - } - - static void log(const std::string &message) { - log(GENERAL, DEFAULT, message); - } - - - static void logf(MessageCategory category, MessageLevel level, const char *format, ...); - static void logf(MessageCategory category, const char *format, ...); - static void logf(MessageLevel level, const char *format, ...); - static void logf(const char *format, ...); }; } diff --git a/src/Core/RemoteLogger.h b/src/Core/RemoteLogger.h index f5c8a6b..ca982a9 100644 --- a/src/Core/RemoteLogger.h +++ b/src/Core/RemoteLogger.h @@ -22,6 +22,7 @@ #include "LoggerBase.h" +#include <ctime> #include <string> namespace Mad { diff --git a/src/Core/Signals/GenericSignal.h b/src/Core/Signals/GenericSignal.h index 641f575..af5bae9 100644 --- a/src/Core/Signals/GenericSignal.h +++ b/src/Core/Signals/GenericSignal.h @@ -37,6 +37,8 @@ class GenericSignal : protected SignalBase { protected: std::map<Connection, slot_type> handlers; + GenericSignal(Application *application) : SignalBase(application) {} + public: Connection connect(const slot_type &slot) { boost::lock_guard<boost::mutex> lock(mutex); diff --git a/src/Core/Signals/Signal0.h b/src/Core/Signals/Signal0.h index ccfb548..c01a82a 100644 --- a/src/Core/Signals/Signal0.h +++ b/src/Core/Signals/Signal0.h @@ -21,6 +21,7 @@ #define MAD_CORE_SIGNALS_SIGNAL0_H_ #include "GenericSignal.h" +#include "../Application.h" #include "../ThreadManager.h" #include <boost/function.hpp> @@ -31,11 +32,13 @@ namespace Signals { class Signal0 : public GenericSignal<boost::function0<void> > { public: + Signal0(Application *application) : GenericSignal<boost::function0<void> >(application) {} + void emit() { boost::lock_guard<boost::mutex> lock(mutex); for(std::map<Connection, slot_type>::iterator handler = handlers.begin(); handler != handlers.end(); ++handler) - ThreadManager::get()->pushWork(handler->second); + getApplication()->getThreadManager()->pushWork(handler->second); } }; diff --git a/src/Core/Signals/Signal1.h b/src/Core/Signals/Signal1.h index e4a946c..0a03c39 100644 --- a/src/Core/Signals/Signal1.h +++ b/src/Core/Signals/Signal1.h @@ -21,6 +21,7 @@ #define MAD_CORE_SIGNALS_SIGNAL1_H_ #include "GenericSignal.h" +#include "../Application.h" #include "../ThreadManager.h" #include <boost/function.hpp> @@ -32,11 +33,13 @@ namespace Signals { template <typename T1> class Signal1 : public GenericSignal<boost::function1<void, T1> > { public: + Signal1(Application *application) : GenericSignal<boost::function1<void, T1> >(application) {} + void emit(T1 arg1) { boost::lock_guard<boost::mutex> lock(this->mutex); for(typename std::map<Connection, typename GenericSignal<boost::function1<void, T1> >::slot_type>::iterator handler = this->handlers.begin(); handler != this->handlers.end(); ++handler) - ThreadManager::get()->pushWork(boost::bind(handler->second, arg1)); + this->getApplication()->getThreadManager()->pushWork(boost::bind(handler->second, arg1)); } }; diff --git a/src/Core/Signals/Signal2.h b/src/Core/Signals/Signal2.h index 41045d7..0966258 100644 --- a/src/Core/Signals/Signal2.h +++ b/src/Core/Signals/Signal2.h @@ -21,6 +21,7 @@ #define MAD_CORE_SIGNALS_SIGNAL2_H_ #include "GenericSignal.h" +#include "../Application.h" #include "../ThreadManager.h" #include <boost/function.hpp> @@ -32,11 +33,13 @@ namespace Signals { template <typename T1, typename T2> class Signal2 : public GenericSignal<boost::function2<void, T1, T2> > { public: + Signal2(Application *application) : GenericSignal<boost::function2<void, T1, T2> >(application) {} + void emit(T1 arg1, T2 arg2) { boost::lock_guard<boost::mutex> lock(this->mutex); for(typename std::map<Connection, typename GenericSignal<boost::function2<void, T1, T2> >::slot_type>::iterator handler = this->handlers.begin(); handler != this->handlers.end(); ++handler) - ThreadManager::get()->pushWork(boost::bind(handler->second, arg1, arg2)); + this->getApplication()->getThreadManager()->pushWork(boost::bind(handler->second, arg1, arg2)); } }; diff --git a/src/Core/Signals/SignalBase.h b/src/Core/Signals/SignalBase.h index 1a5d5a3..8ec8483 100644 --- a/src/Core/Signals/SignalBase.h +++ b/src/Core/Signals/SignalBase.h @@ -27,12 +27,17 @@ namespace Mad { namespace Core { + +class Application; + namespace Signals { class SignalBase : private boost::noncopyable { private: friend class Connection; + Application *application; + unsigned long connectionId; protected: @@ -42,8 +47,12 @@ class SignalBase : private boost::noncopyable { return Connection(this, connectionId++); } - SignalBase() : connectionId(0) {} + SignalBase(Application *application0) : application(application0), connectionId(0) {} virtual ~SignalBase() {} + + Application* getApplication() { + return application; + } }; } diff --git a/src/Core/ThreadManager.cpp b/src/Core/ThreadManager.cpp index abc0bc6..c34a734 100644 --- a/src/Core/ThreadManager.cpp +++ b/src/Core/ThreadManager.cpp @@ -19,7 +19,7 @@ #include "ThreadManager.h" -#include "Logger.h" +#include "Application.h" #include "LogManager.h" #include <boost/bind.hpp> @@ -27,9 +27,6 @@ namespace Mad { namespace Core { -ThreadManager ThreadManager::threadManager; - - void ThreadManager::workerFunc() { while(true) { boost::unique_lock<boost::mutex> lock(runLock); @@ -61,7 +58,7 @@ void ThreadManager::workerFunc() { void ThreadManager::detach() { if(isThisMainThread()) { - Logger::log(Logger::CRITICAL, "Tried to detach main thread! This is just WRONG!"); + application->log(Logger::CRITICAL, "Tried to detach main thread! This is just WRONG!"); return; } @@ -91,22 +88,20 @@ void ThreadManager::pushWork(const boost::function0<void> &newWork) { } -void ThreadManager::doInit() { - running = true; - +ThreadManager::ThreadManager(Application *application0) : application(application0), running(true) { threadLock.lock(); - ioWorker.reset(new boost::asio::io_service::work(ioService)); + ioWorker.reset(new boost::asio::io_service::work(application->getIOService())); mainThreadId = boost::this_thread::get_id(); workerThread.reset(new boost::thread(&ThreadManager::workerFunc, this)); - loggerThread.reset(new boost::thread(&LogManager::loggerThread, LogManager::get())); - ioThread.reset(new boost::thread((std::size_t(boost::asio::io_service::*)())&boost::asio::io_service::run, &ioService)); + loggerThread.reset(new boost::thread(&LogManager::loggerThread, application->getLogManager())); + ioThread.reset(new boost::thread((std::size_t(boost::asio::io_service::*)())&boost::asio::io_service::run, &application->getIOService())); threadLock.unlock(); } -void ThreadManager::doDeinit() { +ThreadManager::~ThreadManager() { if(!isThisMainThread()) { // TODO Critical error!!! return; @@ -131,11 +126,11 @@ void ThreadManager::doDeinit() { // IO thread is next ioWorker.reset(); - ioService.stop(); + application->getIOService().stop(); ioThread->join(); // Finally, the logger thread has to die - LogManager::get()->stopLoggerThread(); + application->getLogManager()->stopLoggerThread(); loggerThread->join(); } diff --git a/src/Core/ThreadManager.h b/src/Core/ThreadManager.h index b512ad4..c20cb1f 100644 --- a/src/Core/ThreadManager.h +++ b/src/Core/ThreadManager.h @@ -22,8 +22,6 @@ #include <config.h> -#include "Initializable.h" - #include <queue> #include <map> @@ -36,8 +34,14 @@ namespace Mad { namespace Core { -class ThreadManager : public Initializable { +class Application; + +class ThreadManager : private boost::noncopyable { private: + friend class Application; + + Application *application; + boost::thread::id mainThreadId; boost::shared_ptr<boost::thread> workerThread, loggerThread, ioThread; std::map<boost::thread::id, boost::shared_ptr<boost::thread> > threads; @@ -53,11 +57,8 @@ class ThreadManager : public Initializable { boost::scoped_ptr<boost::asio::io_service::work> ioWorker; - boost::asio::io_service ioService; - - static ThreadManager threadManager; - - ThreadManager() {} + ThreadManager(Application *application0); + ~ThreadManager(); void workerFunc(); void ioFunc(); @@ -80,10 +81,6 @@ class ThreadManager : public Initializable { thread->join(); } - protected: - virtual void doInit(); - virtual void doDeinit(); - public: bool isThisMainThread() { return (mainThreadId == boost::this_thread::get_id()); @@ -94,17 +91,9 @@ class ThreadManager : public Initializable { return (workerThread->get_id() == boost::this_thread::get_id()); } - boost::asio::io_service& getIOService() { - return ioService; - } - void detach(); void pushWork(const boost::function0<void> &newWork); - - static ThreadManager* get() { - return &threadManager; - } }; } diff --git a/src/Daemon/Daemon.cpp b/src/Daemon/Application.cpp index 3725498..d31cbf5 100644 --- a/src/Daemon/Daemon.cpp +++ b/src/Daemon/Application.cpp @@ -1,5 +1,5 @@ /* - * Daemon.cpp + * Application.cpp * * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de> * @@ -17,5 +17,12 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ +#include "Application.h" -// Empty... +namespace Mad { +namespace Daemon { + +Application::Application() : Common::Application(false) {} + +} +} diff --git a/src/Daemon/Application.h b/src/Daemon/Application.h new file mode 100644 index 0000000..4be7f22 --- /dev/null +++ b/src/Daemon/Application.h @@ -0,0 +1,36 @@ +/* + * Application.h + * + * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de> + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef MAD_DAEMON_APPLICATION_H_ +#define MAD_DAEMON_APPLICATION_H_ + +#include <Common/Application.h> + +namespace Mad { +namespace Daemon { + +class Application : public Common::Application { + public: + Application(); +}; + +} +} + +#endif /* MAD_DAEMON_APPLICATION_H_ */ diff --git a/src/Daemon/Backends/NetworkLogger.h b/src/Daemon/Backends/NetworkLogger.h index c0b123a..557cc14 100644 --- a/src/Daemon/Backends/NetworkLogger.h +++ b/src/Daemon/Backends/NetworkLogger.h @@ -20,7 +20,6 @@ #ifndef MAD_DAEMON_BACKENDS_NETWORKLOGGER_H_ #define MAD_DAEMON_BACKENDS_NETWORKLOGGER_H_ -#include <Core/Logger.h> #include <Common/RequestManager.h> #include <Daemon/Requests/LogRequest.h> @@ -30,16 +29,17 @@ namespace Backends { class NetworkLogger : public Core::Logger { private: + Common::Application *application; Common::Connection *connection; protected: virtual void logMessage(Core::Logger::MessageCategory category, Core::Logger::MessageLevel level, time_t messageTimestamp, const std::string &message) { - boost::shared_ptr<Requests::LogRequest> request(new Requests::LogRequest(category, level, messageTimestamp, message)); - Common::RequestManager::get()->sendRequest(connection, request); + boost::shared_ptr<Requests::LogRequest> request(new Requests::LogRequest(application, category, level, messageTimestamp, message)); + application->getRequestManager()->sendRequest(connection, request); } public: - NetworkLogger(Common::Connection *connection0) : connection(connection0) {} + NetworkLogger(Common::Application *application0, Common::Connection *connection0) : application(application0), connection(connection0) {} }; } diff --git a/src/Daemon/CMakeLists.txt b/src/Daemon/CMakeLists.txt index 68c5f5d..151c229 100644 --- a/src/Daemon/CMakeLists.txt +++ b/src/Daemon/CMakeLists.txt @@ -6,6 +6,6 @@ include_directories(${INCLUDES}) add_library(Daemon Backends/NetworkLogger.h - Daemon.cpp + Application.cpp Application.h ) target_link_libraries(Daemon DaemonRequestHandlers DaemonRequests Common) diff --git a/src/Daemon/RequestHandlers/CommandRequestHandler.cpp b/src/Daemon/RequestHandlers/CommandRequestHandler.cpp index d00c415..ae11de5 100644 --- a/src/Daemon/RequestHandlers/CommandRequestHandler.cpp +++ b/src/Daemon/RequestHandlers/CommandRequestHandler.cpp @@ -31,9 +31,9 @@ void CommandRequestHandler::handleRequest(boost::shared_ptr<const Common::XmlPac std::string command = (*packet)["command"]; if(command == "reboot") - Common::SystemManager::get()->reboot(); + getApplication()->getSystemManager()->reboot(); else - Common::SystemManager::get()->shutdown(); + getApplication()->getSystemManager()->shutdown(); ret->setType("OK"); } diff --git a/src/Daemon/RequestHandlers/CommandRequestHandler.h b/src/Daemon/RequestHandlers/CommandRequestHandler.h index 22c7a4b..db7b3d4 100644 --- a/src/Daemon/RequestHandlers/CommandRequestHandler.h +++ b/src/Daemon/RequestHandlers/CommandRequestHandler.h @@ -28,10 +28,11 @@ namespace RequestHandlers { class CommandRequestHandler : public Common::RequestHandlers::SimpleRequestHandler { private: - static void handleRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret); + void handleRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret); public: - CommandRequestHandler() : Common::RequestHandlers::SimpleRequestHandler("Command", &CommandRequestHandler::handleRequest) {} + CommandRequestHandler(Common::Application *application) + : Common::RequestHandlers::SimpleRequestHandler(application, "Command", boost::bind(&CommandRequestHandler::handleRequest, this, _1, _2)) {} }; } diff --git a/src/Daemon/Requests/LogRequest.h b/src/Daemon/Requests/LogRequest.h index 6ee3b3d..a3cda41 100644 --- a/src/Daemon/Requests/LogRequest.h +++ b/src/Daemon/Requests/LogRequest.h @@ -21,7 +21,6 @@ #define MAD_DAEMON_REQUESTS_LOGREQUEST_H_ #include <Common/Request.h> -#include <Core/Logger.h> #include <ctime> namespace Mad { @@ -30,8 +29,8 @@ namespace Requests { class LogRequest : public Common::Request { private: - Core::Logger::MessageCategory category; - Core::Logger::MessageLevel level; + Core::LoggerBase::MessageCategory category; + Core::LoggerBase::MessageLevel level; time_t messageTimestamp; std::string message; @@ -39,8 +38,8 @@ class LogRequest : public Common::Request { virtual void sendRequest(); public: - LogRequest(Core::Logger::MessageCategory category0, Core::Logger::MessageLevel level0, time_t messageTimestamp0, const std::string &message0) - : category(category0), level(level0), messageTimestamp(messageTimestamp0), message(message0) {} + LogRequest(Common::Application *application, Core::LoggerBase::MessageCategory category0, Core::LoggerBase::MessageLevel level0, time_t messageTimestamp0, const std::string &message0) + : Common::Request(application), category(category0), level(level0), messageTimestamp(messageTimestamp0), message(message0) {} }; } diff --git a/src/Net/ClientConnection.h b/src/Net/ClientConnection.h index dcb6906..02cd0c7 100644 --- a/src/Net/ClientConnection.h +++ b/src/Net/ClientConnection.h @@ -36,9 +36,9 @@ class ClientConnection : private boost::base_from_member<boost::asio::ssl::conte void handleConnect(const boost::system::error_code& error); public: - ClientConnection() - : boost::base_from_member<boost::asio::ssl::context>(boost::ref(Core::ThreadManager::get()->getIOService()), boost::asio::ssl::context::sslv23), - Connection(member) + ClientConnection(Core::Application *application) + : boost::base_from_member<boost::asio::ssl::context>(boost::ref(application->getIOService()), boost::asio::ssl::context::sslv23), + Connection(application, member) { member.set_verify_mode(boost::asio::ssl::context::verify_none); } diff --git a/src/Net/Connection.cpp b/src/Net/Connection.cpp index 81f4c64..fabbd12 100644 --- a/src/Net/Connection.cpp +++ b/src/Net/Connection.cpp @@ -19,7 +19,7 @@ #include "Connection.h" -#include <Core/Logger.h> +#include <Core/Application.h> #include <cstring> #include <boost/bind.hpp> @@ -35,7 +35,7 @@ Connection::~Connection() { void Connection::handleHandshake(const boost::system::error_code& error) { if(error) { - Core::Logger::logf("Error: %s", error.message().c_str()); + application->logf("Error: %s", error.message().c_str()); // TODO Error handling doDisconnect(); @@ -61,7 +61,7 @@ void Connection::handleShutdown(const boost::system::error_code& error) { boost::lock_guard<boost::shared_mutex> lock(connectionLock); if(error) { - Core::Logger::logf(Core::Logger::VERBOSE, "Shutdown error: %s", error.message().c_str()); + application->logf(Core::LoggerBase::VERBOSE, "Shutdown error: %s", error.message().c_str()); } _setState(DISCONNECTED); @@ -110,7 +110,7 @@ void Connection::handleDataReceive(const std::vector<boost::uint8_t> &data) { void Connection::handleRead(const boost::system::error_code& error, std::size_t bytes_transferred, std::size_t length, const boost::function1<void, const std::vector<boost::uint8_t>& > ¬ify) { if(error || (bytes_transferred+received) < length) { - Core::Logger::logf(Core::Logger::VERBOSE, "Read error: %s", error.message().c_str()); + application->logf(Core::LoggerBase::VERBOSE, "Read error: %s", error.message().c_str()); // TODO Error doDisconnect(); @@ -183,7 +183,7 @@ void Connection::handleWrite(const boost::system::error_code& error, std::size_t } if(error) { - Core::Logger::logf(Core::Logger::VERBOSE, "Write error: %s", error.message().c_str()); + application->logf(Core::LoggerBase::VERBOSE, "Write error: %s", error.message().c_str()); // TODO Error doDisconnect(); diff --git a/src/Net/Connection.h b/src/Net/Connection.h index 6323164..0506d13 100644 --- a/src/Net/Connection.h +++ b/src/Net/Connection.h @@ -62,6 +62,8 @@ class Connection : boost::noncopyable { boost::asio::const_buffer buffer; }; + Core::Application *application; + boost::condition_variable_any stateChanged; State state; @@ -115,8 +117,9 @@ class Connection : boost::noncopyable { void doDisconnect(); - Connection(boost::asio::ssl::context &sslContext) : - state(DISCONNECTED), receiveBuffer(1024*1024), socket(Core::ThreadManager::get()->getIOService(), sslContext) {} + Connection(Core::Application *application0, boost::asio::ssl::context &sslContext) : + application(application0), state(DISCONNECTED), receiveBuffer(1024*1024), receiveSignal(application), connectedSignal(application), + disconnectedSignal(application), socket(application->getIOService(), sslContext) {} public: virtual ~Connection(); diff --git a/src/Net/Listener.cpp b/src/Net/Listener.cpp index 780e862..2bdb189 100644 --- a/src/Net/Listener.cpp +++ b/src/Net/Listener.cpp @@ -19,9 +19,6 @@ #include "Listener.h" -#include <Core/Logger.h> -#include <Core/ThreadManager.h> - #include <cerrno> #include <cstring> #include <fcntl.h> @@ -48,7 +45,7 @@ void Listener::handleAccept(const boost::system::error_code &error, boost::share con->socket.async_handshake(boost::asio::ssl::stream_base::server, boost::bind(&Connection::handleHandshake, con, boost::asio::placeholders::error)); } - con.reset(new Connection(sslContext)); + con.reset(new Connection(application, sslContext)); acceptor.async_accept(con->socket.lowest_layer(), boost::bind(&Listener::handleAccept, this, boost::asio::placeholders::error, con)); } @@ -76,10 +73,11 @@ void Listener::handleDisconnect(boost::shared_ptr<Connection> con) { } -Listener::Listener(const std::string &x905CertFile0, const std::string &x905KeyFile0, +Listener::Listener(Core::Application *application0, const std::string &x905CertFile0, const std::string &x905KeyFile0, const boost::asio::ip::tcp::endpoint &address0) throw(Core::Exception) -: x905CertFile(x905CertFile0), x905KeyFile(x905KeyFile0), address(address0), acceptor(Core::ThreadManager::get()->getIOService(), address), -sslContext(Core::ThreadManager::get()->getIOService(), boost::asio::ssl::context::sslv23) +: application(application0), x905CertFile(x905CertFile0), x905KeyFile(x905KeyFile0), address(address0), +acceptor(application->getIOService(), address), sslContext(application->getIOService(), boost::asio::ssl::context::sslv23), +signal(application) { sslContext.set_options(boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 @@ -89,7 +87,7 @@ sslContext(Core::ThreadManager::get()->getIOService(), boost::asio::ssl::context - boost::shared_ptr<Connection> con(new Connection(sslContext)); + boost::shared_ptr<Connection> con(new Connection(application, sslContext)); acceptor.async_accept(con->socket.lowest_layer(), boost::bind(&Listener::handleAccept, this, boost::asio::placeholders::error, con)); } diff --git a/src/Net/Listener.h b/src/Net/Listener.h index af0888b..931cd99 100644 --- a/src/Net/Listener.h +++ b/src/Net/Listener.h @@ -29,8 +29,10 @@ namespace Mad { namespace Net { -class Listener : boost::noncopyable { +class Listener : private boost::noncopyable { private: + Core::Application *application; + boost::mutex mutex; std::string x905CertFile, x905KeyFile; @@ -48,7 +50,7 @@ class Listener : boost::noncopyable { void handleDisconnect(boost::shared_ptr<Connection> con); public: - Listener(const std::string &x905CertFile0, const std::string &x905KeyFile0, + Listener(Core::Application *application0, const std::string &x905CertFile0, const std::string &x905KeyFile0, const boost::asio::ip::tcp::endpoint &address0 = boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 6666)) throw(Core::Exception); virtual ~Listener(); diff --git a/src/Server/RequestHandlers/IdentifyRequestHandler.cpp b/src/Server/Application.cpp index e48563b..3414e53 100644 --- a/src/Server/RequestHandlers/IdentifyRequestHandler.cpp +++ b/src/Server/Application.cpp @@ -1,7 +1,7 @@ /* - * IdentifyRequestHandler.cpp + * Application.cpp * - * Copyright (C) 2008 Matthias Schiffer <matthias@gamezock.de> + * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the @@ -17,23 +17,22 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ -#include "IdentifyRequestHandler.h" -#include "../ConnectionManager.h" - +#include "Application.h" +#include "ConnectionManager.h" +#include "UserManager.h" namespace Mad { namespace Server { -namespace RequestHandlers { -void IdentifyRequestHandler::handleRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret) { - if((*packet)["hostname"].isEmpty()) - ConnectionManager::get()->identifyClientConnection(getConnection()); - else - ConnectionManager::get()->identifyDaemonConnection(getConnection(), (*packet)["hostname"]); +Application::Application() : Common::Application(true), connectionManager(new ConnectionManager(this)), +userManager(new UserManager) { - ret->setType("OK"); } +Application::~Application() { + delete userManager; + delete connectionManager; } + } } diff --git a/src/Server/RequestHandlers/LogRequestHandler.h b/src/Server/Application.h index cf1ce34..b62893b 100644 --- a/src/Server/RequestHandlers/LogRequestHandler.h +++ b/src/Server/Application.h @@ -1,7 +1,7 @@ /* - * LogRequestHandler.h + * Application.h * - * Copyright (C) 2008 Matthias Schiffer <matthias@gamezock.de> + * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the @@ -17,25 +17,36 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ -#ifndef MAD_SERVER_REQUESTHANDLERS_LOGREQUESTHANDLER_H_ -#define MAD_SERVER_REQUESTHANDLERS_LOGREQUESTHANDLER_H_ +#ifndef MAD_SERVER_APPLICATION_H_ +#define MAD_SERVER_APPLICATION_H_ -#include <Common/RequestHandlers/SimpleRequestHandler.h> +#include <Common/Application.h> namespace Mad { namespace Server { -namespace RequestHandlers { -class LogRequestHandler : public Common::RequestHandlers::SimpleRequestHandler { +class ConnectionManager; +class UserManager; + +class Application : public Common::Application { private: - void handleRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret); + ConnectionManager *connectionManager; + UserManager *userManager; public: - LogRequestHandler() : Common::RequestHandlers::SimpleRequestHandler("Log", boost::bind(&LogRequestHandler::handleRequest, this, _1, _2)) {} + Application(); + virtual ~Application(); + + ConnectionManager* getConnectionManager() const { + return connectionManager; + } + + UserManager* getUserManager() const { + return userManager; + } }; } } -} -#endif /* MAD_SERVER_REQUESTHANDLERS_LOGREQUESTHANDLER_H_ */ +#endif /* MAD_SERVER_APPLICATION_H_ */ diff --git a/src/Server/CMakeLists.txt b/src/Server/CMakeLists.txt index e38d860..b609de3 100644 --- a/src/Server/CMakeLists.txt +++ b/src/Server/CMakeLists.txt @@ -4,6 +4,7 @@ add_subdirectory(Requests) include_directories(${INCLUDES}) add_library(Server + Application.cpp Application.h ConnectionManager.cpp ConnectionManager.h UserBackend.h UserManager.cpp UserManager.h diff --git a/src/Server/ConnectionManager.cpp b/src/Server/ConnectionManager.cpp index a15a516..bbf7ab1 100644 --- a/src/Server/ConnectionManager.cpp +++ b/src/Server/ConnectionManager.cpp @@ -18,16 +18,15 @@ */ #include "ConnectionManager.h" +#include "Application.h" #include <Core/ConfigEntry.h> #include <Core/ConfigManager.h> -#include <Core/Logger.h> +#include <Common/RequestManager.h> #include <Common/RequestHandlers/FSInfoRequestHandler.h> #include <Common/RequestHandlers/StatusRequestHandler.h> #include "Requests/DaemonStateUpdateRequest.h" -#include "RequestHandlers/DaemonListRequestHandler.h" //#include "RequestHandlers/GSSAPIAuthRequestHandler.h" -#include "RequestHandlers/IdentifyRequestHandler.h" -#include "RequestHandlers/LogRequestHandler.h" +#include "RequestHandlers/ConnectionRequestHandlerGroup.h" #include "RequestHandlers/DaemonRequestHandlerGroup.h" #include "RequestHandlers/UserRequestHandlerGroup.h" #include <Net/Packet.h> @@ -39,14 +38,12 @@ namespace Mad { namespace Server { -ConnectionManager ConnectionManager::connectionManager; - bool ConnectionManager::ServerConnection::send(const Net::Packet &packet) { return connection->send(packet); } -ConnectionManager::ServerConnection::ServerConnection(boost::shared_ptr<Net::Connection> connection0) -: connection(connection0), type(UNKNOWN), hostInfo(0) { +ConnectionManager::ServerConnection::ServerConnection(Core::Application *application, boost::shared_ptr<Net::Connection> connection0) +: Common::Connection(application), connection(connection0), type(UNKNOWN), hostInfo(0) { connection->connectSignalReceive(boost::bind(&ServerConnection::receive, this, _1)); } @@ -80,8 +77,8 @@ void ConnectionManager::updateState(Common::HostInfo *hostInfo, Common::HostInfo for(std::set<boost::shared_ptr<ServerConnection> >::iterator con = connections.begin(); con != connections.end(); ++con) { if((*con)->getConnectionType() == ServerConnection::CLIENT) { - boost::shared_ptr<Requests::DaemonStateUpdateRequest> request(new Requests::DaemonStateUpdateRequest(hostInfo->getName(), state)); - Common::RequestManager::get()->sendRequest(con->get(), request); + boost::shared_ptr<Requests::DaemonStateUpdateRequest> request(new Requests::DaemonStateUpdateRequest(application, hostInfo->getName(), state)); + application->getRequestManager()->sendRequest(con->get(), request); } } } @@ -141,7 +138,7 @@ bool ConnectionManager::handleConfigEntry(const Core::ConfigEntry &entry, bool h void ConnectionManager::configFinished() { if(listenerAddresses.empty()) { try { - boost::shared_ptr<Net::Listener> listener(new Net::Listener(x509CertFile, x509KeyFile)); + boost::shared_ptr<Net::Listener> listener(new Net::Listener(application, x509CertFile, x509KeyFile)); listener->connectSignalNewConnection(boost::bind(&ConnectionManager::handleNewConnection, this, _1)); listeners.push_back(listener); } @@ -152,7 +149,7 @@ void ConnectionManager::configFinished() { else { for(std::vector<boost::asio::ip::tcp::endpoint>::const_iterator address = listenerAddresses.begin(); address != listenerAddresses.end(); ++address) { try { - boost::shared_ptr<Net::Listener> listener(new Net::Listener(x509CertFile, x509KeyFile, *address)); + boost::shared_ptr<Net::Listener> listener(new Net::Listener(application, x509CertFile, x509KeyFile, *address)); listener->connectSignalNewConnection(boost::bind(&ConnectionManager::handleNewConnection, this, _1)); listeners.push_back(listener); } @@ -164,11 +161,11 @@ void ConnectionManager::configFinished() { } void ConnectionManager::handleNewConnection(boost::shared_ptr<Net::Connection> con) { - boost::shared_ptr<ServerConnection> connection(new ServerConnection(con)); + boost::shared_ptr<ServerConnection> connection(new ServerConnection(application, con)); con->connectSignalDisconnected(boost::bind(&ConnectionManager::handleDisconnect, this, connection)); connections.insert(connection); - Common::RequestManager::get()->registerConnection(connection.get()); + application->getRequestManager()->registerConnection(connection.get()); } void ConnectionManager::handleDisconnect(boost::shared_ptr<ServerConnection> con) { @@ -177,44 +174,36 @@ void ConnectionManager::handleDisconnect(boost::shared_ptr<ServerConnection> con connections.erase(con); - Common::RequestManager::get()->unregisterConnection(con.get()); + application->getRequestManager()->unregisterConnection(con.get()); } -void ConnectionManager::doInit() { - Common::RequestManager::get()->setServer(true); - - daemonRequestHandlerGroup.reset(new RequestHandlers::DaemonRequestHandlerGroup); - userRequestHandlerGroup.reset(new RequestHandlers::UserRequestHandlerGroup); +ConnectionManager::ConnectionManager(Application *application0) : application(application0), +connectionRequestHandlerGroup(new RequestHandlers::ConnectionRequestHandlerGroup(application)), +daemonRequestHandlerGroup(new RequestHandlers::DaemonRequestHandlerGroup), +userRequestHandlerGroup(new RequestHandlers::UserRequestHandlerGroup(application)) { + //requestManager->registerPacketType<RequestHandlers::GSSAPIAuthRequestHandler>("AuthGSSAPI"); + application->getRequestManager()->registerPacketType<Common::RequestHandlers::FSInfoRequestHandler>("FSInfo"); + application->getRequestManager()->registerPacketType<Common::RequestHandlers::StatusRequestHandler>("GetStatus"); - //Common::RequestManager::get()->registerPacketType<RequestHandlers::GSSAPIAuthRequestHandler>("AuthGSSAPI"); - //Common::RequestManager::get()->registerPacketType<RequestHandlers::DaemonCommandRequestHandler>("DaemonCommand"); - //Common::RequestManager::get()->registerPacketType<RequestHandlers::DaemonFSInfoRequestHandler>("DaemonFSInfo"); - Common::RequestManager::get()->registerPacketType<Common::RequestHandlers::FSInfoRequestHandler>("FSInfo"); - Common::RequestManager::get()->registerPacketType<Common::RequestHandlers::StatusRequestHandler>("GetStatus"); - //Common::RequestManager::get()->registerPacketType<RequestHandlers::DaemonStatusRequestHandler>("GetDaemonStatus"); - Common::RequestManager::get()->registerPacketType<RequestHandlers::IdentifyRequestHandler>("Identify"); - Common::RequestManager::get()->registerPacketType<RequestHandlers::DaemonListRequestHandler>("ListHosts"); - Common::RequestManager::get()->registerPacketType<RequestHandlers::LogRequestHandler>("Log"); + application->getRequestManager()->registerRequestHandlerGroup(connectionRequestHandlerGroup); + application->getRequestManager()->registerRequestHandlerGroup(daemonRequestHandlerGroup); + application->getRequestManager()->registerRequestHandlerGroup(userRequestHandlerGroup); - Common::RequestManager::get()->registerRequestHandlerGroup(daemonRequestHandlerGroup); - Common::RequestManager::get()->registerRequestHandlerGroup(userRequestHandlerGroup); + application->getConfigManager()->registerConfigurable(this); } -void ConnectionManager::doDeinit() { +ConnectionManager::~ConnectionManager() { + application->getConfigManager()->unregisterConfigurable(this); + connections.clear(); - Common::RequestManager::get()->unregisterRequestHandlerGroup(userRequestHandlerGroup); - Common::RequestManager::get()->unregisterRequestHandlerGroup(daemonRequestHandlerGroup); - - //Common::RequestManager::get()->unregisterPacketType("AuthGSSAPI"); - //Common::RequestManager::get()->unregisterPacketType("DaemonCommand"); - //Common::RequestManager::get()->unregisterPacketType("DaemonFSInfo"); - Common::RequestManager::get()->unregisterPacketType("FSInfo"); - Common::RequestManager::get()->unregisterPacketType("GetStatus"); - //Common::RequestManager::get()->unregisterPacketType("GetDaemonStatus"); - Common::RequestManager::get()->unregisterPacketType("Identify"); - Common::RequestManager::get()->unregisterPacketType("ListHosts"); - Common::RequestManager::get()->unregisterPacketType("Log"); + application->getRequestManager()->unregisterRequestHandlerGroup(userRequestHandlerGroup); + application->getRequestManager()->unregisterRequestHandlerGroup(daemonRequestHandlerGroup); + application->getRequestManager()->unregisterRequestHandlerGroup(connectionRequestHandlerGroup); + + //requestManager->unregisterPacketType("AuthGSSAPI"); + application->getRequestManager()->unregisterPacketType("FSInfo"); + application->getRequestManager()->unregisterPacketType("GetStatus"); } boost::shared_ptr<Common::Connection> ConnectionManager::getDaemonConnection(const std::string &name) const throw (Core::Exception&) { @@ -266,7 +255,7 @@ void ConnectionManager::identifyDaemonConnection(Common::Connection *con, const if(hostInfo->getState() != Common::HostInfo::INACTIVE) { try { getDaemonConnection(name)->disconnect(); - Core::Logger::log(Core::Logger::WARNING, "Disconnecting old connection."); + application->log(Core::LoggerBase::WARNING, "Disconnecting old connection."); } catch(Core::Exception&) {} } @@ -274,7 +263,7 @@ void ConnectionManager::identifyDaemonConnection(Common::Connection *con, const connection->identify(hostInfo); updateState(hostInfo, Common::HostInfo::RUNNING); - Core::Logger::logf("Identified as '%s'.", name.c_str()); + application->logf("Identified as '%s'.", name.c_str()); } void ConnectionManager::identifyClientConnection(Common::Connection *con) throw (Core::Exception&) { diff --git a/src/Server/ConnectionManager.h b/src/Server/ConnectionManager.h index 4cc12a5..b8f77f1 100644 --- a/src/Server/ConnectionManager.h +++ b/src/Server/ConnectionManager.h @@ -21,9 +21,10 @@ #define MAD_SERVER_CONNECTIONMANAGER_H_ #include <Core/Configurable.h> -#include <Core/Initializable.h> +#include <Core/Exception.h> +#include <Common/Connection.h> #include <Common/HostInfo.h> -#include <Common/RequestManager.h> +#include <Common/RequestHandlerGroup.h> #include <list> #include <vector> @@ -42,7 +43,9 @@ class Packet; namespace Server { -class ConnectionManager : public Core::Configurable, public Core::Initializable, boost::noncopyable { +class Application; + +class ConnectionManager : public Core::Configurable, private boost::noncopyable { private: class ServerConnection : public Common::Connection { public: @@ -59,7 +62,7 @@ class ConnectionManager : public Core::Configurable, public Core::Initializable, virtual bool send(const Net::Packet &packet); public: - ServerConnection(boost::shared_ptr<Net::Connection> connection0); + ServerConnection(Core::Application *application, boost::shared_ptr<Net::Connection> connection0); bool isConnected() const; @@ -89,7 +92,9 @@ class ConnectionManager : public Core::Configurable, public Core::Initializable, } }; - static ConnectionManager connectionManager; + friend class Application; + + Application *application; std::string x509TrustFile, x509CrlFile, x509CertFile, x509KeyFile; @@ -100,28 +105,23 @@ class ConnectionManager : public Core::Configurable, public Core::Initializable, std::map<std::string,Common::HostInfo> daemonInfo; + boost::shared_ptr<Common::RequestHandlerGroup> connectionRequestHandlerGroup; boost::shared_ptr<Common::RequestHandlerGroup> daemonRequestHandlerGroup; boost::shared_ptr<Common::RequestHandlerGroup> userRequestHandlerGroup; void updateState(Common::HostInfo *hostInfo, Common::HostInfo::State state); - ConnectionManager() {} - void handleNewConnection(boost::shared_ptr<Net::Connection> con); void handleDisconnect(boost::shared_ptr<ServerConnection> con); + ConnectionManager(Application *application0); + ~ConnectionManager(); + protected: virtual bool handleConfigEntry(const Core::ConfigEntry &entry, bool handled); virtual void configFinished(); - virtual void doInit(); - virtual void doDeinit(); - public: - static ConnectionManager* get() { - return &connectionManager; - } - boost::shared_ptr<Common::Connection> getDaemonConnection(const std::string &name) const throw (Core::Exception&); std::string getDaemonName(const Common::Connection *con) const throw (Core::Exception&); diff --git a/src/Server/RequestHandlers/CMakeLists.txt b/src/Server/RequestHandlers/CMakeLists.txt index 9b9b9ea..065a85d 100644 --- a/src/Server/RequestHandlers/CMakeLists.txt +++ b/src/Server/RequestHandlers/CMakeLists.txt @@ -1,10 +1,8 @@ include_directories(${INCLUDES}) add_library(ServerRequestHandlers STATIC - DaemonListRequestHandler.cpp DaemonListRequestHandler.h + ConnectionRequestHandlerGroup.cpp ConnectionRequestHandlerGroup.h DaemonRequestHandlerGroup.cpp DaemonRequestHandlerGroup.h - IdentifyRequestHandler.cpp IdentifyRequestHandler.h - LogRequestHandler.cpp LogRequestHandler.h UserRequestHandlerGroup.cpp UserRequestHandlerGroup.h ) target_link_libraries(ServerRequestHandlers Server ${KRB5_LIBRARIES}) diff --git a/src/Server/RequestHandlers/ConnectionRequestHandlerGroup.cpp b/src/Server/RequestHandlers/ConnectionRequestHandlerGroup.cpp new file mode 100644 index 0000000..3af5439 --- /dev/null +++ b/src/Server/RequestHandlers/ConnectionRequestHandlerGroup.cpp @@ -0,0 +1,79 @@ +/* + * ConnectionRequestHandlerGroup.cpp + * + * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de> + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "ConnectionRequestHandlerGroup.h" +#include "../Application.h" +#include "../ConnectionManager.h" + +#include <Core/LogManager.h> + +namespace Mad { +namespace Server { +namespace RequestHandlers { + +void ConnectionRequestHandlerGroup::handleDaemonListRequest(boost::shared_ptr<const Common::XmlPacket> packet _UNUSED_PARAMETER_, Common::XmlPacket *ret, + Common::Connection *connection _UNUSED_PARAMETER_) { + // TODO Require authentication + + ret->setType("OK"); + ret->addList("hosts"); + + std::vector<Common::HostInfo> daemons = application->getConnectionManager()->getDaemonList(); + + for(std::vector<Common::HostInfo>::iterator daemon = daemons.begin(); daemon != daemons.end(); ++daemon) { + (*ret)["hosts"].addEntry(); + + (*ret)["hosts"].back().add("name", daemon->getName()); + (*ret)["hosts"].back().add("address", daemon->getIP()); + (*ret)["hosts"].back().add("state", daemon->getState()); + } +} + +void ConnectionRequestHandlerGroup::handleIdentifyRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret, Common::Connection *connection) { + if((*packet)["hostname"].isEmpty()) + application->getConnectionManager()->identifyClientConnection(connection); + else + application->getConnectionManager()->identifyDaemonConnection(connection, (*packet)["hostname"]); + + ret->setType("OK"); +} + +void ConnectionRequestHandlerGroup::handleLogRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret, Common::Connection *connection) { + // TODO Require authentication + + try { + application->getLogManager()->log((*packet)["category"], (*packet)["level"], (*packet)["timestamp"], (*packet)["message"], + application->getConnectionManager()->getDaemonName(connection)); + } + catch(Core::Exception &e) { + application->logf(Core::LoggerBase::ERROR, "Can't determine daemon name: %s", e.strerror().c_str()); + } + + ret->setType("OK"); +} + +ConnectionRequestHandlerGroup::ConnectionRequestHandlerGroup(Application *application0) : application(application0) { + registerHandler("ListHosts", boost::bind(&ConnectionRequestHandlerGroup::handleDaemonListRequest, this, _1, _2, _3)); + registerHandler("Identify", boost::bind(&ConnectionRequestHandlerGroup::handleIdentifyRequest, this, _1, _2, _3)); + registerHandler("Log", boost::bind(&ConnectionRequestHandlerGroup::handleLogRequest, this, _1, _2, _3)); +} + +} +} +} diff --git a/src/Server/RequestHandlers/ConnectionRequestHandlerGroup.h b/src/Server/RequestHandlers/ConnectionRequestHandlerGroup.h new file mode 100644 index 0000000..6efa021 --- /dev/null +++ b/src/Server/RequestHandlers/ConnectionRequestHandlerGroup.h @@ -0,0 +1,48 @@ +/* + * ConnectionRequestHandlerGroup.h + * + * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de> + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef MAD_SERVER_REQUESTHANDLERS_CONNECTIONREQUESTHANDLERGROUP_H_ +#define MAD_SERVER_REQUESTHANDLERS_CONNECTIONREQUESTHANDLERGROUP_H_ + +#include <Common/RequestHandlers/SimpleRequestHandlerGroup.h> + +namespace Mad { +namespace Server { + +class Application; + +namespace RequestHandlers { + +class ConnectionRequestHandlerGroup : public Common::RequestHandlers::SimpleRequestHandlerGroup { + private: + Application *application; + + void handleDaemonListRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret, Common::Connection *connection); + void handleIdentifyRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret, Common::Connection *connection); + void handleLogRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret, Common::Connection *connection); + + public: + ConnectionRequestHandlerGroup(Application *application0); +}; + +} +} +} + +#endif /* MAD_SERVER_REQUESTHANDLERS_CONNECTIONREQUESTHANDLERGROUP_H_ */ diff --git a/src/Server/RequestHandlers/DaemonListRequestHandler.cpp b/src/Server/RequestHandlers/DaemonListRequestHandler.cpp deleted file mode 100644 index fc6900c..0000000 --- a/src/Server/RequestHandlers/DaemonListRequestHandler.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/* - * DaemonListRequestHandler.cpp - * - * Copyright (C) 2008 Matthias Schiffer <matthias@gamezock.de> - * - * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -#include "DaemonListRequestHandler.h" -#include "../ConnectionManager.h" - -namespace Mad { -namespace Server { -namespace RequestHandlers { - -void DaemonListRequestHandler::handleRequest(boost::shared_ptr<const Common::XmlPacket> packet _UNUSED_PARAMETER_, Common::XmlPacket *ret) { - // TODO Require authentication - - ret->setType("OK"); - ret->addList("hosts"); - - std::vector<Common::HostInfo> daemons = ConnectionManager::get()->getDaemonList(); - - for(std::vector<Common::HostInfo>::iterator daemon = daemons.begin(); daemon != daemons.end(); ++daemon) { - (*ret)["hosts"].addEntry(); - - (*ret)["hosts"].back().add("name", daemon->getName()); - (*ret)["hosts"].back().add("address", daemon->getIP()); - (*ret)["hosts"].back().add("state", daemon->getState()); - } -} - -} -} -} diff --git a/src/Server/RequestHandlers/DaemonListRequestHandler.h b/src/Server/RequestHandlers/DaemonListRequestHandler.h deleted file mode 100644 index 45eebc8..0000000 --- a/src/Server/RequestHandlers/DaemonListRequestHandler.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * DaemonListRequestHandler.h - * - * Copyright (C) 2008 Matthias Schiffer <matthias@gamezock.de> - * - * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -#ifndef MAD_SERVER_REQUESTHANDLERS_DAEMONLISTREQUESTHANDLER_H_ -#define MAD_SERVER_REQUESTHANDLERS_DAEMONLISTREQUESTHANDLER_H_ - -#include <Common/RequestHandlers/SimpleRequestHandler.h> - -namespace Mad { -namespace Server { -namespace RequestHandlers { - -class DaemonListRequestHandler : public Common::RequestHandlers::SimpleRequestHandler { - private: - static void handleRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret); - - public: - DaemonListRequestHandler() : Common::RequestHandlers::SimpleRequestHandler("ListHosts", &DaemonListRequestHandler::handleRequest) {} -}; - -} -} -} - -#endif /* MAD_SERVER_REQUESTHANDLERS_DAEMONLISTREQUESTHANDLER_H_ */ diff --git a/src/Server/RequestHandlers/DaemonRequestHandlerGroup.cpp b/src/Server/RequestHandlers/DaemonRequestHandlerGroup.cpp index 0e21fdd..344cf4c 100644 --- a/src/Server/RequestHandlers/DaemonRequestHandlerGroup.cpp +++ b/src/Server/RequestHandlers/DaemonRequestHandlerGroup.cpp @@ -18,10 +18,11 @@ */ #include "DaemonRequestHandlerGroup.h" +#include "../Application.h" #include "../ConnectionManager.h" #include "../Requests/CommandRequest.h" -#include <Core/Logger.h> +#include <Common/RequestManager.h> #include <Common/Requests/FSInfoRequest.h> #include <Common/Requests/StatusRequest.h> @@ -31,7 +32,7 @@ namespace RequestHandlers { void DaemonRequestHandlerGroup::DaemonRequestHandler::handlePacket(boost::shared_ptr<const Common::XmlPacket> packet) { if(packet->getType() != type) { - Core::Logger::log(Core::Logger::ERROR, "Received an unexpected packet."); + getApplication()->log(Core::LoggerBase::ERROR, "Received an unexpected packet."); Common::XmlPacket ret; ret.setType("Error"); @@ -46,18 +47,18 @@ void DaemonRequestHandlerGroup::DaemonRequestHandler::handlePacket(boost::shared // TODO Require authentication try { - boost::shared_ptr<Common::Connection> daemonCon = ConnectionManager::get()->getDaemonConnection((*packet)["daemon"]); + boost::shared_ptr<Common::Connection> daemonCon = dynamic_cast<Application&>(*getApplication()).getConnectionManager()->getDaemonConnection((*packet)["daemon"]); boost::shared_ptr<Common::Request> request; if(type == "DaemonCommand") - request.reset(new Requests::CommandRequest((std::string&)((*packet)["command"]) == "reboot")); + request.reset(new Requests::CommandRequest(getApplication(), (std::string&)((*packet)["command"]) == "reboot")); else if(type == "DaemonFSInfo") - request.reset(new Common::Requests::FSInfoRequest); + request.reset(new Common::Requests::FSInfoRequest(getApplication())); else // type == "GetDaemonStatus" - request.reset(new Common::Requests::StatusRequest); + request.reset(new Common::Requests::StatusRequest(getApplication())); request->connectSignalFinished(boost::bind(&DaemonRequestHandlerGroup::DaemonRequestHandler::requestFinished, this, _1, _2)); - Common::RequestManager::get()->sendRequest(daemonCon.get(), request); + getRequestManager()->sendRequest(daemonCon.get(), request); } catch(Core::Exception &e) { Common::XmlPacket ret; @@ -97,11 +98,11 @@ DaemonRequestHandlerGroup::DaemonRequestHandlerGroup() { types.insert("GetDaemonStatus"); } -boost::shared_ptr<Common::RequestHandler> DaemonRequestHandlerGroup::createRequestHandler(const std::string &type) { +boost::shared_ptr<Common::RequestHandler> DaemonRequestHandlerGroup::createRequestHandler(Common::Application *application, const std::string &type) { if(types.find(type) == types.end()) return boost::shared_ptr<Common::RequestHandler>(); else - return boost::shared_ptr<DaemonRequestHandler>(new DaemonRequestHandler(type)); + return boost::shared_ptr<DaemonRequestHandler>(new DaemonRequestHandler(application, type)); } } diff --git a/src/Server/RequestHandlers/DaemonRequestHandlerGroup.h b/src/Server/RequestHandlers/DaemonRequestHandlerGroup.h index 7a709f4..524baac 100644 --- a/src/Server/RequestHandlers/DaemonRequestHandlerGroup.h +++ b/src/Server/RequestHandlers/DaemonRequestHandlerGroup.h @@ -25,6 +25,8 @@ namespace Mad { namespace Server { +class ConnectionManager; + namespace RequestHandlers { class DaemonRequestHandlerGroup : public Common::RequestHandlerGroup { @@ -39,9 +41,12 @@ class DaemonRequestHandlerGroup : public Common::RequestHandlerGroup { virtual void handlePacket(boost::shared_ptr<const Common::XmlPacket> packet); public: - DaemonRequestHandler(const std::string &type0) : type(type0) {} + DaemonRequestHandler(Common::Application *application, const std::string &type0) + : Common::RequestHandler(application), type(type0) {} }; + ConnectionManager *connectionManager; + std::set<std::string> types; public: @@ -51,7 +56,7 @@ class DaemonRequestHandlerGroup : public Common::RequestHandlerGroup { return types; } - virtual boost::shared_ptr<Common::RequestHandler> createRequestHandler(const std::string &type); + virtual boost::shared_ptr<Common::RequestHandler> createRequestHandler(Common::Application *application, const std::string &type); }; } diff --git a/src/Server/RequestHandlers/IdentifyRequestHandler.h b/src/Server/RequestHandlers/IdentifyRequestHandler.h deleted file mode 100644 index d9954a3..0000000 --- a/src/Server/RequestHandlers/IdentifyRequestHandler.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * IdentifyRequestHandler.h - * - * Copyright (C) 2008 Matthias Schiffer <matthias@gamezock.de> - * - * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -#ifndef MAD_SERVER_REQUESTHANDLERS_IDENTIFYREQUESTHANDLER_H_ -#define MAD_SERVER_REQUESTHANDLERS_IDENTIFYREQUESTHANDLER_H_ - -#include <Common/RequestHandlers/SimpleRequestHandler.h> - -namespace Mad { -namespace Server { -namespace RequestHandlers { - -class IdentifyRequestHandler : public Common::RequestHandlers::SimpleRequestHandler { - private: - void handleRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret); - - public: - IdentifyRequestHandler() : Common::RequestHandlers::SimpleRequestHandler("Identify", boost::bind(&IdentifyRequestHandler::handleRequest, this, _1, _2)) {} -}; - -} -} -} - -#endif /* MAD_SERVER_REQUESTHANDLERS_IDENTIFYREQUESTHANDLER_H_ */ diff --git a/src/Server/RequestHandlers/LogRequestHandler.cpp b/src/Server/RequestHandlers/LogRequestHandler.cpp deleted file mode 100644 index f33aad4..0000000 --- a/src/Server/RequestHandlers/LogRequestHandler.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/* - * LogRequestHandler.cpp - * - * Copyright (C) 2008 Matthias Schiffer <matthias@gamezock.de> - * - * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -#include "LogRequestHandler.h" -#include <Core/LogManager.h> -#include "../ConnectionManager.h" - -namespace Mad { -namespace Server { -namespace RequestHandlers { - -void LogRequestHandler::handleRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret) { - // TODO Require authentication - - try { - Core::LogManager::get()->log((*packet)["category"], (*packet)["level"], (*packet)["timestamp"], (*packet)["message"], - ConnectionManager::get()->getDaemonName(getConnection())); - } - catch(Core::Exception &e) { - Core::Logger::logf(Core::Logger::ERROR, "Can't determine daemon name: %s", e.strerror().c_str()); - } - - ret->setType("OK"); -} - -} -} -} diff --git a/src/Server/RequestHandlers/UserRequestHandlerGroup.cpp b/src/Server/RequestHandlers/UserRequestHandlerGroup.cpp index 7836c34..3aaa576 100644 --- a/src/Server/RequestHandlers/UserRequestHandlerGroup.cpp +++ b/src/Server/RequestHandlers/UserRequestHandlerGroup.cpp @@ -18,14 +18,16 @@ */ #include "UserRequestHandlerGroup.h" +#include "../Application.h" #include "../UserManager.h" namespace Mad { namespace Server { namespace RequestHandlers { -void UserRequestHandlerGroup::handleUserListRequest(boost::shared_ptr<const Common::XmlPacket> packet _UNUSED_PARAMETER_, Common::XmlPacket *ret) { - boost::shared_ptr<std::map<unsigned long, Common::UserInfo> > info = UserManager::get()->getUserList(); +void UserRequestHandlerGroup::handleUserListRequest(boost::shared_ptr<const Common::XmlPacket> packet _UNUSED_PARAMETER_, Common::XmlPacket *ret, + Common::Connection *connection _UNUSED_PARAMETER_) { + boost::shared_ptr<std::map<unsigned long, Common::UserInfo> > info = application->getUserManager()->getUserList(); ret->setType("OK"); ret->addList("users"); @@ -41,8 +43,9 @@ void UserRequestHandlerGroup::handleUserListRequest(boost::shared_ptr<const Comm } } -void UserRequestHandlerGroup::handleUserInfoRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret) { - boost::shared_ptr<Common::UserInfo> info = UserManager::get()->getUserInfo((*packet)["uid"]); +void UserRequestHandlerGroup::handleUserInfoRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret, + Common::Connection *connection _UNUSED_PARAMETER_) { + boost::shared_ptr<Common::UserInfo> info = application->getUserManager()->getUserInfo((*packet)["uid"]); ret->setType("OK"); @@ -52,8 +55,9 @@ void UserRequestHandlerGroup::handleUserInfoRequest(boost::shared_ptr<const Comm ret->add("fullName", info->getFullName()); } -void UserRequestHandlerGroup::handleUserGroupListRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret) { - boost::shared_ptr<std::set<unsigned long> > groups = UserManager::get()->getUserGroupList((unsigned long)(*packet)["uid"]); +void UserRequestHandlerGroup::handleUserGroupListRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret, + Common::Connection *connection _UNUSED_PARAMETER_) { + boost::shared_ptr<std::set<unsigned long> > groups = application->getUserManager()->getUserGroupList((unsigned long)(*packet)["uid"]); ret->setType("OK"); ret->addList("groups"); @@ -66,8 +70,9 @@ void UserRequestHandlerGroup::handleUserGroupListRequest(boost::shared_ptr<const } } -void UserRequestHandlerGroup::handleGroupListRequest(boost::shared_ptr<const Common::XmlPacket> packet _UNUSED_PARAMETER_, Common::XmlPacket *ret) { - boost::shared_ptr<std::map<unsigned long, Common::GroupInfo> > info = UserManager::get()->getGroupList(); +void UserRequestHandlerGroup::handleGroupListRequest(boost::shared_ptr<const Common::XmlPacket> packet _UNUSED_PARAMETER_, Common::XmlPacket *ret, + Common::Connection *connection _UNUSED_PARAMETER_) { + boost::shared_ptr<std::map<unsigned long, Common::GroupInfo> > info = application->getUserManager()->getGroupList(); ret->setType("OK"); ret->addList("groups"); @@ -81,8 +86,9 @@ void UserRequestHandlerGroup::handleGroupListRequest(boost::shared_ptr<const Com } } -void UserRequestHandlerGroup::handleGroupUserListRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret) { - boost::shared_ptr<std::set<unsigned long> > users = UserManager::get()->getGroupUserList((unsigned long)(*packet)["gid"]); +void UserRequestHandlerGroup::handleGroupUserListRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret, + Common::Connection *connection _UNUSED_PARAMETER_) { + boost::shared_ptr<std::set<unsigned long> > users = application->getUserManager()->getGroupUserList((unsigned long)(*packet)["gid"]); ret->setType("OK"); ret->addList("users"); @@ -95,12 +101,12 @@ void UserRequestHandlerGroup::handleGroupUserListRequest(boost::shared_ptr<const } } -UserRequestHandlerGroup::UserRequestHandlerGroup() { - registerHandler("ListUsers", &UserRequestHandlerGroup::handleUserListRequest); - registerHandler("GetUserInfo", &UserRequestHandlerGroup::handleUserInfoRequest); - registerHandler("ListUserGroups", &UserRequestHandlerGroup::handleUserGroupListRequest); - registerHandler("ListGroups", &UserRequestHandlerGroup::handleGroupListRequest); - registerHandler("ListGroupUsers", &UserRequestHandlerGroup::handleGroupUserListRequest); +UserRequestHandlerGroup::UserRequestHandlerGroup(Application *application0) : application(application0) { + registerHandler("ListUsers", boost::bind(&UserRequestHandlerGroup::handleUserListRequest, this, _1, _2, _3)); + registerHandler("GetUserInfo", boost::bind(&UserRequestHandlerGroup::handleUserInfoRequest, this, _1, _2, _3)); + registerHandler("ListUserGroups", boost::bind(&UserRequestHandlerGroup::handleUserGroupListRequest, this, _1, _2, _3)); + registerHandler("ListGroups", boost::bind(&UserRequestHandlerGroup::handleGroupListRequest, this, _1, _2, _3)); + registerHandler("ListGroupUsers", boost::bind(&UserRequestHandlerGroup::handleGroupUserListRequest, this, _1, _2, _3)); } } diff --git a/src/Server/RequestHandlers/UserRequestHandlerGroup.h b/src/Server/RequestHandlers/UserRequestHandlerGroup.h index 52965dd..2a17a9a 100644 --- a/src/Server/RequestHandlers/UserRequestHandlerGroup.h +++ b/src/Server/RequestHandlers/UserRequestHandlerGroup.h @@ -24,18 +24,23 @@ namespace Mad { namespace Server { + +class Application; + namespace RequestHandlers { class UserRequestHandlerGroup : public Common::RequestHandlers::SimpleRequestHandlerGroup { private: - static void handleUserListRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret); - static void handleUserInfoRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret); - static void handleUserGroupListRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret); - static void handleGroupListRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret); - static void handleGroupUserListRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret); + Application *application; + + void handleUserListRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret, Common::Connection *connection); + void handleUserInfoRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret, Common::Connection *connection); + void handleUserGroupListRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret, Common::Connection *connection); + void handleGroupListRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret, Common::Connection *connection); + void handleGroupUserListRequest(boost::shared_ptr<const Common::XmlPacket> packet, Common::XmlPacket *ret, Common::Connection *connection); public: - UserRequestHandlerGroup(); + UserRequestHandlerGroup(Application *application0); }; } diff --git a/src/Server/Requests/CommandRequest.h b/src/Server/Requests/CommandRequest.h index 8221b14..3b2dcdd 100644 --- a/src/Server/Requests/CommandRequest.h +++ b/src/Server/Requests/CommandRequest.h @@ -34,7 +34,7 @@ class CommandRequest : public Common::Request { virtual void sendRequest(); public: - CommandRequest(bool reboot0) : reboot(reboot0) {} + CommandRequest(Common::Application *application, bool reboot0) : Common::Request(application), reboot(reboot0) {} }; } diff --git a/src/Server/Requests/DaemonStateUpdateRequest.h b/src/Server/Requests/DaemonStateUpdateRequest.h index c3ed792..762514a 100644 --- a/src/Server/Requests/DaemonStateUpdateRequest.h +++ b/src/Server/Requests/DaemonStateUpdateRequest.h @@ -36,8 +36,8 @@ class DaemonStateUpdateRequest : public Common::Request { virtual void sendRequest(); public: - DaemonStateUpdateRequest(const std::string &name0, Common::HostInfo::State state0) - : name(name0), state(state0) {} + DaemonStateUpdateRequest(Common::Application *application, const std::string &name0, Common::HostInfo::State state0) + : Common::Request(application), name(name0), state(state0) {} }; } diff --git a/src/Server/UserManager.cpp b/src/Server/UserManager.cpp index 0c45b78..243457c 100644 --- a/src/Server/UserManager.cpp +++ b/src/Server/UserManager.cpp @@ -23,9 +23,6 @@ namespace Mad { namespace Server { -UserManager UserManager::userManager; - - bool UserManager::Compare::operator() (boost::shared_ptr<UserBackend> b1, boost::shared_ptr<UserBackend> b2) { if(b1->getPriority() == b2->getPriority()) return (b1.get() > b2.get()); diff --git a/src/Server/UserManager.h b/src/Server/UserManager.h index 31f50d5..6d3c034 100644 --- a/src/Server/UserManager.h +++ b/src/Server/UserManager.h @@ -34,16 +34,17 @@ namespace Mad { namespace Server { +class Application; class UserBackend; class UserManager : boost::noncopyable { private: + friend class Application; + struct Compare { bool operator() (boost::shared_ptr<UserBackend> b1, boost::shared_ptr<UserBackend> b2); }; - static UserManager userManager; - std::set<boost::shared_ptr<UserBackend>, Compare> backends; UserManager() {} @@ -70,10 +71,6 @@ class UserManager : boost::noncopyable { void setPassword(unsigned long uid, const std::string &password) throw(Core::Exception); void addUser(const Common::UserInfo &userInfo) throw(Core::Exception); - - static UserManager *get() { - return &userManager; - } }; } diff --git a/src/mad-server.cpp b/src/mad-server.cpp index a00f33d..ba42a89 100644 --- a/src/mad-server.cpp +++ b/src/mad-server.cpp @@ -18,30 +18,27 @@ */ #include "Core/ConfigManager.h" -#include "Core/ThreadManager.h" #include "Common/ModuleManager.h" +#include "Server/Application.h" #include "Server/ConnectionManager.h" using namespace Mad; int main() { - Core::ThreadManager::get()->init(); - Server::ConnectionManager::get()->init(); + Server::Application application; - Common::ModuleManager::get()->loadModule("FileLogger"); - Common::ModuleManager::get()->loadModule("SystemBackendPosix"); - Common::ModuleManager::get()->loadModule("SystemBackendProc"); + application.getModuleManager()->loadModule("FileLogger"); + application.getModuleManager()->loadModule("SystemBackendPosix"); + application.getModuleManager()->loadModule("SystemBackendProc"); - Common::ModuleManager::get()->loadModule("UserBackendMysql"); + application.getModuleManager()->loadModule("UserBackendMysql"); - Core::ConfigManager::get()->loadFile("mad-server.conf"); - Core::ConfigManager::get()->finish(); + application.getConfigManager()->loadFile("mad-server.conf"); + application.getConfigManager()->finish(); while(true) sleep(1000); - Core::Initializable::deinit(); - return 0; } diff --git a/src/mad.cpp b/src/mad.cpp index b1dbb8f..e0266f8 100644 --- a/src/mad.cpp +++ b/src/mad.cpp @@ -17,15 +17,17 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ -#include "Core/ThreadManager.h" #include "Core/ConfigManager.h" #include "Core/LogManager.h" + #include "Common/ModuleManager.h" #include "Common/RequestManager.h" #include "Common/ClientConnection.h" #include "Common/Requests/IdentifyRequest.h" #include "Common/RequestHandlers/FSInfoRequestHandler.h" #include "Common/RequestHandlers/StatusRequestHandler.h" + +#include "Daemon/Application.h" #include "Daemon/Backends/NetworkLogger.h" #include "Daemon/RequestHandlers/CommandRequestHandler.h" @@ -35,19 +37,19 @@ using namespace Mad; int main() { - Core::ThreadManager::get()->init(); + Daemon::Application application; - Common::ModuleManager::get()->loadModule("FileLogger"); - Common::ModuleManager::get()->loadModule("SystemBackendPosix"); - Common::ModuleManager::get()->loadModule("SystemBackendProc"); + application.getModuleManager()->loadModule("FileLogger"); + application.getModuleManager()->loadModule("SystemBackendPosix"); + application.getModuleManager()->loadModule("SystemBackendProc"); - Core::ConfigManager::get()->finish(); + application.getConfigManager()->finish(); - Common::RequestManager::get()->registerPacketType<Daemon::RequestHandlers::CommandRequestHandler>("Command"); - Common::RequestManager::get()->registerPacketType<Common::RequestHandlers::FSInfoRequestHandler>("FSInfo"); - Common::RequestManager::get()->registerPacketType<Common::RequestHandlers::StatusRequestHandler>("GetStatus"); + application.getRequestManager()->registerPacketType<Daemon::RequestHandlers::CommandRequestHandler>("Command"); + application.getRequestManager()->registerPacketType<Common::RequestHandlers::FSInfoRequestHandler>("FSInfo"); + application.getRequestManager()->registerPacketType<Common::RequestHandlers::StatusRequestHandler>("GetStatus"); - Common::ClientConnection *connection = new Common::ClientConnection; + Common::ClientConnection *connection = new Common::ClientConnection(&application); try { connection->connect(boost::asio::ip::tcp::endpoint( @@ -55,40 +57,33 @@ int main() { connection->waitWhileConnecting(); - Common::RequestManager::get()->registerConnection(connection); + application.getRequestManager()->registerConnection(connection); - boost::shared_ptr<Core::Logger> networkLogger(new Daemon::Backends::NetworkLogger(connection)); - Core::LogManager::get()->registerLogger(networkLogger); + boost::shared_ptr<Core::Logger> networkLogger(new Daemon::Backends::NetworkLogger(&application, connection)); + application.getLogManager()->registerLogger(networkLogger); - - //char hostname[256]; - //gethostname(hostname, sizeof(hostname)); - //Common::RequestManager::get()->sendRequest<Daemon::Requests::IdentifyRequest>(connection, sigc::ptr_fun(requestFinished), hostname); - //Common::RequestManager::get()->sendRequest1<Common::Requests::IdentifyRequest>(connection, "test")->wait(); { - boost::shared_ptr<Common::Requests::IdentifyRequest> request(new Common::Requests::IdentifyRequest("test")); - Common::RequestManager::get()->sendRequest(connection, request); + boost::shared_ptr<Common::Requests::IdentifyRequest> request(new Common::Requests::IdentifyRequest(&application, "test")); + application.getRequestManager()->sendRequest(connection, request); request->wait(); } - Core::Logger::log("Identified."); + application.log("Identified."); connection->waitWhileConnected(); - Core::LogManager::get()->unregisterLogger(networkLogger); + application.getLogManager()->unregisterLogger(networkLogger); - Common::RequestManager::get()->unregisterConnection(connection); + application.getRequestManager()->unregisterConnection(connection); } catch(Core::Exception &e) { - Core::Logger::logf(Core::Logger::CRITICAL, "Connection error: %s", e.strerror().c_str()); + application.logf(Core::LoggerBase::CRITICAL, "Connection error: %s", e.strerror().c_str()); } delete connection; - Common::RequestManager::get()->unregisterPacketType("Command"); - Common::RequestManager::get()->unregisterPacketType("FSInfo"); - Common::RequestManager::get()->unregisterPacketType("GetStatus"); - - Core::Initializable::deinit(); + application.getRequestManager()->unregisterPacketType("Command"); + application.getRequestManager()->unregisterPacketType("FSInfo"); + application.getRequestManager()->unregisterPacketType("GetStatus"); return 0; } diff --git a/src/madc.cpp b/src/madc.cpp index ea32f2f..55c2be7 100644 --- a/src/madc.cpp +++ b/src/madc.cpp @@ -18,12 +18,12 @@ */ #include "Core/ConfigManager.h" -#include "Core/Logger.h" -#include "Core/ThreadManager.h" #include "Common/ClientConnection.h" #include "Common/RequestManager.h" #include "Common/Requests/IdentifyRequest.h" + +#include "Client/Application.h" #include "Client/CommandParser.h" #include "Client/InformationManager.h" @@ -48,12 +48,11 @@ int main(int argc, char *argv[]) { std::exit(1); } - Core::ThreadManager::get()->init(); - Client::InformationManager::get()->init(); + Client::Application application; - Core::ConfigManager::get()->finish(); + application.getConfigManager()->finish(); - Common::ClientConnection *connection = new Common::ClientConnection; + Common::ClientConnection *connection = new Common::ClientConnection(&application); try { connection->connect(boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string(argv[1]), 6666)); @@ -62,32 +61,32 @@ int main(int argc, char *argv[]) { connection->waitWhileConnecting(); - Common::RequestManager::get()->registerConnection(connection); + application.getRequestManager()->registerConnection(connection); { - boost::shared_ptr<Common::Requests::IdentifyRequest> request(new Common::Requests::IdentifyRequest); - Common::RequestManager::get()->sendRequest(connection, request); + boost::shared_ptr<Common::Requests::IdentifyRequest> request(new Common::Requests::IdentifyRequest(&application)); + application.getRequestManager()->sendRequest(connection, request); request->wait(); } std::cerr << " connected." << std::endl; std::cerr << "Receiving host list..." << std::flush; - Client::InformationManager::get()->updateDaemonList(connection); - Client::InformationManager::get()->waitWhileUpdating(); + application.getInformationManager()->updateDaemonList(connection); + application.getInformationManager()->waitWhileUpdating(); std::cerr << " done." << std::endl << std::endl; - Client::CommandParser::get()->setConnection(connection); + Client::CommandParser commandParser(&application, connection); - while(connection->isConnected() && !Client::CommandParser::get()->willDisconnect()) { + while(connection->isConnected() && !commandParser.willDisconnect()) { char *cmd = readline("mad> "); if(!cmd) { - Client::CommandParser::get()->requestDisconnect(); + commandParser.requestDisconnect(); } else if(*cmd) { - Client::CommandParser::get()->parse(cmd); + commandParser.parse(cmd); add_history(cmd); } else continue; @@ -95,15 +94,13 @@ int main(int argc, char *argv[]) { connection->waitWhileConnected(); - Common::RequestManager::get()->unregisterConnection(connection); + application.getRequestManager()->unregisterConnection(connection); } catch(Core::Exception &e) { - Core::Logger::logf(Core::Logger::CRITICAL, "Connection error: %s", e.strerror().c_str()); + application.logf(Core::LoggerBase::CRITICAL, "Connection error: %s", e.strerror().c_str()); } delete connection; - Core::Initializable::deinit(); - return 0; } diff --git a/src/modules/FileLogger/CMakeLists.txt b/src/modules/FileLogger/CMakeLists.txt index 7d90028..555425d 100644 --- a/src/modules/FileLogger/CMakeLists.txt +++ b/src/modules/FileLogger/CMakeLists.txt @@ -1,5 +1,6 @@ include_directories(${INCLUDES}) add_library(FileLogger MODULE - FileLogger.cpp FileLogger.h + FileLogger.h + Module.cpp Module.h ) diff --git a/src/modules/FileLogger/FileLogger.h b/src/modules/FileLogger/FileLogger.h index 9b0f8e2..a24f747 100644 --- a/src/modules/FileLogger/FileLogger.h +++ b/src/modules/FileLogger/FileLogger.h @@ -17,31 +17,20 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ -#ifndef MAD_MODULES_FILELOGGER_H_ -#define MAD_MODULES_FILELOGGER_H_ - -#include <Core/ConfigManager.h> -#include <Core/Configurable.h> -#include <Core/LogManager.h> +#ifndef MAD_MODULES_FILELOGGER_FILELOGGER_H_ +#define MAD_MODULES_FILELOGGER_FILELOGGER_H_ #include <fstream> +#include <Core/Logger.h> +#include <Core/RemoteLogger.h> + namespace Mad { namespace Modules { +namespace FileLogger { class FileLogger : public Core::Logger, public Core::RemoteLogger { private: - class ConfigHelper : public Core::Configurable { - protected: - virtual bool handleConfigEntry(const Core::ConfigEntry &entry, bool handled); - - public: - virtual int getPriority() const {return 1;} - }; - - static ConfigHelper configHelper; - static std::set<boost::shared_ptr<FileLogger> > loggers; - std::ofstream file; protected: @@ -55,23 +44,10 @@ class FileLogger : public Core::Logger, public Core::RemoteLogger { public: FileLogger(const std::string &filename) : file(filename.c_str(), std::ios::out|std::ios::app) {} - - static void registerConfigHelper() { - Core::ConfigManager::get()->registerConfigurable(&configHelper); - } - - static void unregisterConfigHelper() { - Core::ConfigManager::get()->unregisterConfigurable(&configHelper); - - for(std::set<boost::shared_ptr<FileLogger> >::iterator logger = loggers.begin(); logger != loggers.end(); ++logger) { - Core::LogManager::get()->unregisterLogger(boost::static_pointer_cast<Logger>(*logger)); - } - - loggers.clear(); - } }; } } +} -#endif /* MAD_MODULES_FILELOGGER_H_ */ +#endif /* MAD_MODULES_FILELOGGER_FILELOGGER_H_ */ diff --git a/src/modules/FileLogger/FileLogger.cpp b/src/modules/FileLogger/Module.cpp index bdae536..829c429 100644 --- a/src/modules/FileLogger/FileLogger.cpp +++ b/src/modules/FileLogger/Module.cpp @@ -1,7 +1,7 @@ /* - * FileLogger.cpp + * Module.cpp * - * Copyright (C) 2008 Matthias Schiffer <matthias@gamezock.de> + * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the @@ -17,19 +17,14 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ -#include "FileLogger.h" - +#include "Module.h" #include <Core/ConfigEntry.h> - namespace Mad { namespace Modules { +namespace FileLogger { -FileLogger::ConfigHelper FileLogger::configHelper; -std::set<boost::shared_ptr<FileLogger> > FileLogger::loggers; - - -bool FileLogger::ConfigHelper::handleConfigEntry(const Core::ConfigEntry &entry, bool handled) { +bool Module::handleConfigEntry(const Core::ConfigEntry &entry, bool handled) { if(handled) return false; @@ -40,10 +35,10 @@ bool FileLogger::ConfigHelper::handleConfigEntry(const Core::ConfigEntry &entry, boost::shared_ptr<FileLogger> logger(new FileLogger(entry[0][1])); loggers.insert(logger); - Core::LogManager::get()->registerLogger(boost::static_pointer_cast<Logger>(logger)); + application->getLogManager()->registerLogger(boost::static_pointer_cast<Core::Logger>(logger)); } else { - Logger::logf(Logger::WARNING, "FileLogger: no filename given."); + application->logf(Core::LoggerBase::WARNING, "FileLogger: no filename given."); } return true; @@ -56,15 +51,12 @@ bool FileLogger::ConfigHelper::handleConfigEntry(const Core::ConfigEntry &entry, } } +} extern "C" { -void FileLogger_init() { - Mad::Modules::FileLogger::registerConfigHelper(); -} - -void FileLogger_deinit() { - Mad::Modules::FileLogger::unregisterConfigHelper(); +Mad::Common::Module* FileLogger_create(Mad::Common::Application *application) { + return new Mad::Modules::FileLogger::Module(application); } } diff --git a/src/modules/FileLogger/Module.h b/src/modules/FileLogger/Module.h new file mode 100644 index 0000000..e800b69 --- /dev/null +++ b/src/modules/FileLogger/Module.h @@ -0,0 +1,67 @@ +/* + * Module.h + * + * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de> + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef MAD_MODULES_FILELOGGER_MODULE_H_ +#define MAD_MODULES_FILELOGGER_MODULE_H_ + +#include "FileLogger.h" + +#include <Core/Configurable.h> +#include <Core/ConfigManager.h> +#include <Core/LogManager.h> + +#include <Common/Application.h> +#include <Common/Module.h> + +namespace Mad { +namespace Modules { +namespace FileLogger { + +class Module : public Common::Module, private Core::Configurable { + private: + Common::Application *application; + + std::set<boost::shared_ptr<FileLogger> > loggers; + + protected: + virtual bool handleConfigEntry(const Core::ConfigEntry &entry, bool handled); + + public: + Module(Common::Application *application0) : application(application0) { + application->getConfigManager()->registerConfigurable(this); + } + + virtual ~Module() { + application->getConfigManager()->unregisterConfigurable(this); + + for(std::set<boost::shared_ptr<FileLogger> >::iterator logger = loggers.begin(); logger != loggers.end(); ++logger) { + application->getLogManager()->unregisterLogger(boost::static_pointer_cast<Core::Logger>(*logger)); + } + + loggers.clear(); + } + + virtual int getPriority() const {return 1;} +}; + +} +} +} + +#endif /* MAD_MODULES_FILELOGGER_MODULE_H_ */ diff --git a/src/modules/SystemBackendPosix/CMakeLists.txt b/src/modules/SystemBackendPosix/CMakeLists.txt index 223960b..83e8ea1 100644 --- a/src/modules/SystemBackendPosix/CMakeLists.txt +++ b/src/modules/SystemBackendPosix/CMakeLists.txt @@ -1,5 +1,6 @@ include_directories(${INCLUDES}) add_library(SystemBackendPosix MODULE + Module.cpp Module.h SystemBackendPosix.cpp SystemBackendPosix.h ) diff --git a/src/modules/SystemBackendPosix/Module.cpp b/src/modules/SystemBackendPosix/Module.cpp new file mode 100644 index 0000000..230fef4 --- /dev/null +++ b/src/modules/SystemBackendPosix/Module.cpp @@ -0,0 +1,28 @@ +/* + * Module.cpp + * + * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de> + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "Module.h" + +extern "C" { + +Mad::Common::Module* SystemBackendPosix_create(Mad::Common::Application *application) { + return new Mad::Modules::SystemBackendPosix::Module(application); +} + +} diff --git a/src/modules/SystemBackendPosix/Module.h b/src/modules/SystemBackendPosix/Module.h new file mode 100644 index 0000000..ee780f6 --- /dev/null +++ b/src/modules/SystemBackendPosix/Module.h @@ -0,0 +1,52 @@ +/* + * Module.h + * + * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de> + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef MAD_MODULES_SYSTEMBACKENDPOSIX_MODULE_H_ +#define MAD_MODULES_SYSTEMBACKENDPOSIX_MODULE_H_ + +#include "SystemBackendPosix.h" + +#include <Common/Application.h> +#include <Common/Module.h> + +namespace Mad { +namespace Modules { +namespace SystemBackendPosix { + +class Module : public Common::Module { + private: + Common::Application *application; + + boost::shared_ptr<SystemBackendPosix> backend; + + public: + Module(Common::Application *application0) : application(application0), backend(new SystemBackendPosix(application)) { + application->getSystemManager()->registerBackend(backend); + } + + virtual ~Module() { + application->getSystemManager()->unregisterBackend(backend); + } +}; + +} +} +} + +#endif /* MAD_MODULES_SYSTEMBACKENDPOSIX_MODULE_H_ */ diff --git a/src/modules/SystemBackendPosix/SystemBackendPosix.cpp b/src/modules/SystemBackendPosix/SystemBackendPosix.cpp index 4eb5807..801fcd4 100644 --- a/src/modules/SystemBackendPosix/SystemBackendPosix.cpp +++ b/src/modules/SystemBackendPosix/SystemBackendPosix.cpp @@ -26,11 +26,10 @@ namespace Mad { namespace Modules { - -boost::shared_ptr<SystemBackendPosix> SystemBackendPosix::backend; +namespace SystemBackendPosix { void SystemBackendPosix::getFSInfo(std::vector<Common::SystemManager::FSInfo> *fsInfo) throw(Core::Exception) { - Core::ThreadManager::get()->detach(); + application->getThreadManager()->detach(); FILE *pipe = popen("/bin/df -P -k", "r"); if(!pipe) @@ -79,14 +78,14 @@ void SystemBackendPosix::getFSInfo(std::vector<Common::SystemManager::FSInfo> *f } void SystemBackendPosix::shutdown() throw(Core::Exception) { - Core::ThreadManager::get()->detach(); + application->getThreadManager()->detach(); if(system("/sbin/halt") != 0) throw(Core::Exception(Core::Exception::NOT_AVAILABLE)); } void SystemBackendPosix::reboot() throw(Core::Exception) { - Core::ThreadManager::get()->detach(); + application->getThreadManager()->detach(); if(system("/sbin/reboot") != 0) throw(Core::Exception(Core::Exception::NOT_AVAILABLE)); @@ -94,16 +93,4 @@ void SystemBackendPosix::reboot() throw(Core::Exception) { } } - - -extern "C" { - -void SystemBackendPosix_init() { - Mad::Modules::SystemBackendPosix::registerBackend(); -} - -void SystemBackendPosix_deinit() { - Mad::Modules::SystemBackendPosix::unregisterBackend(); -} - } diff --git a/src/modules/SystemBackendPosix/SystemBackendPosix.h b/src/modules/SystemBackendPosix/SystemBackendPosix.h index 4aec7dd..6c5ae06 100644 --- a/src/modules/SystemBackendPosix/SystemBackendPosix.h +++ b/src/modules/SystemBackendPosix/SystemBackendPosix.h @@ -17,25 +17,19 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ -#ifndef MAD_MODULES_SYSTEMBACKENDPOSIX_H_ -#define MAD_MODULES_SYSTEMBACKENDPOSIX_H_ +#ifndef MAD_MODULES_SYSTEMBACKENDPOSIX_SYSTEMBACKENDPOSIX_H_ +#define MAD_MODULES_SYSTEMBACKENDPOSIX_SYSTEMBACKENDPOSIX_H_ #include <Common/SystemBackend.h> - -#include <map> -#include <string> -#include <vector> - -#include <sys/types.h> - -#include <boost/bind.hpp> +#include <Common/Application.h> namespace Mad { namespace Modules { +namespace SystemBackendPosix { class SystemBackendPosix : public Common::SystemBackend { private: - static boost::shared_ptr<SystemBackendPosix> backend; + Common::Application *application; protected: virtual void getFSInfo(std::vector<Common::SystemManager::FSInfo> *fsInfo) throw(Core::Exception); @@ -44,24 +38,11 @@ class SystemBackendPosix : public Common::SystemBackend { virtual void reboot() throw(Core::Exception); public: - static void registerBackend() { - if(backend) - return; - - backend.reset(new SystemBackendPosix()); - Common::SystemManager::get()->registerBackend(backend); - } - - static void unregisterBackend() { - if(!backend) - return; - - Common::SystemManager::get()->unregisterBackend(backend); - backend.reset(); - } + SystemBackendPosix(Common::Application *application0) : application(application0) {} }; } } +} -#endif /* MAD_MODULES_SYSTEMBACKENDPOSIX_H_ */ +#endif /* MAD_MODULES_SYSTEMBACKENDPOSIX_SYSTEMBACKENDPOSIX_H_ */ diff --git a/src/modules/SystemBackendProc/CMakeLists.txt b/src/modules/SystemBackendProc/CMakeLists.txt index ba5642c..42f7431 100644 --- a/src/modules/SystemBackendProc/CMakeLists.txt +++ b/src/modules/SystemBackendProc/CMakeLists.txt @@ -1,5 +1,6 @@ include_directories(${INCLUDES}) add_library(SystemBackendProc MODULE + Module.cpp Module.h SystemBackendProc.cpp SystemBackendProc.h ) diff --git a/src/modules/SystemBackendProc/Module.cpp b/src/modules/SystemBackendProc/Module.cpp new file mode 100644 index 0000000..7dbbbb5 --- /dev/null +++ b/src/modules/SystemBackendProc/Module.cpp @@ -0,0 +1,28 @@ +/* + * Module.cpp + * + * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de> + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "Module.h" + +extern "C" { + +Mad::Common::Module* SystemBackendProc_create(Mad::Common::Application *application) { + return new Mad::Modules::SystemBackendProc::Module(application); +} + +} diff --git a/src/modules/SystemBackendProc/Module.h b/src/modules/SystemBackendProc/Module.h new file mode 100644 index 0000000..6cdbd73 --- /dev/null +++ b/src/modules/SystemBackendProc/Module.h @@ -0,0 +1,52 @@ +/* + * Module.h + * + * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de> + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef MAD_MODULES_SYSTEMBACKENDPROC_MODULE_H_ +#define MAD_MODULES_SYSTEMBACKENDPROC_MODULE_H_ + +#include "SystemBackendProc.h" + +#include <Common/Application.h> +#include <Common/Module.h> + +namespace Mad { +namespace Modules { +namespace SystemBackendProc { + +class Module : public Common::Module { + private: + Common::Application *application; + + boost::shared_ptr<SystemBackendProc> backend; + + public: + Module(Common::Application *application0) : application(application0), backend(new SystemBackendProc(application)) { + application->getSystemManager()->registerBackend(backend); + } + + virtual ~Module() { + application->getSystemManager()->unregisterBackend(backend); + } +}; + +} +} +} + +#endif /* MAD_MODULES_SYSTEMBACKENDPROC_MODULE_H_ */ diff --git a/src/modules/SystemBackendProc/SystemBackendProc.cpp b/src/modules/SystemBackendProc/SystemBackendProc.cpp index e8b45cd..daae55b 100644 --- a/src/modules/SystemBackendProc/SystemBackendProc.cpp +++ b/src/modules/SystemBackendProc/SystemBackendProc.cpp @@ -26,11 +26,10 @@ namespace Mad { namespace Modules { - -boost::shared_ptr<SystemBackendProc> SystemBackendProc::backend; +namespace SystemBackendProc { void SystemBackendProc::getUptimeInfo(unsigned long *uptime, unsigned long *idleTime) throw(Core::Exception) { - Core::ThreadManager::get()->detach(); + application->getThreadManager()->detach(); uptimeFile.seekg(0, std::ios::beg); @@ -51,7 +50,7 @@ void SystemBackendProc::getUptimeInfo(unsigned long *uptime, unsigned long *idle } void SystemBackendProc::getMemoryInfo(unsigned long *totalMem, unsigned long *freeMem, unsigned long *totalSwap, unsigned long *freeSwap) throw(Core::Exception) { - Core::ThreadManager::get()->detach(); + application->getThreadManager()->detach(); if(totalMem) *totalMem = 0; @@ -93,7 +92,7 @@ void SystemBackendProc::getMemoryInfo(unsigned long *totalMem, unsigned long *fr } void SystemBackendProc::getLoadInfo(unsigned long *currentLoad, unsigned long *nProcesses, float *loadAvg1, float *loadAvg5, float *loadAvg15) throw(Core::Exception) { - Core::ThreadManager::get()->detach(); + application->getThreadManager()->detach(); unsigned long currentLoadValue = 0, nProcessesValue = 0; float loadAvg1Value = 0, loadAvg5Value = 0, loadAvg15Value = 0; @@ -129,16 +128,4 @@ void SystemBackendProc::getLoadInfo(unsigned long *currentLoad, unsigned long *n } } - - -extern "C" { - -void SystemBackendProc_init() { - Mad::Modules::SystemBackendProc::registerBackend(); -} - -void SystemBackendProc_deinit() { - Mad::Modules::SystemBackendProc::unregisterBackend(); -} - } diff --git a/src/modules/SystemBackendProc/SystemBackendProc.h b/src/modules/SystemBackendProc/SystemBackendProc.h index 9a0cb71..a54d783 100644 --- a/src/modules/SystemBackendProc/SystemBackendProc.h +++ b/src/modules/SystemBackendProc/SystemBackendProc.h @@ -17,51 +17,37 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ -#ifndef MAD_MODULES_SYSTEMBACKENDPROC_H_ -#define MAD_MODULES_SYSTEMBACKENDPROC_H_ +#ifndef MAD_MODULES_SYSTEMBACKENDPROC_SYSTEMBACKENDPROC_H_ +#define MAD_MODULES_SYSTEMBACKENDPROC_SYSTEMBACKENDPROC_H_ #include <Common/SystemBackend.h> +#include <Common/Application.h> #include <fstream> -#include <boost/noncopyable.hpp> namespace Mad { namespace Modules { +namespace SystemBackendProc { -class SystemBackendProc : public Common::SystemBackend, boost::noncopyable { +class SystemBackendProc : public Common::SystemBackend { private: - static boost::shared_ptr<SystemBackendProc> backend; + Common::Application *application; std::ifstream uptimeFile; std::ifstream meminfoFile; std::ifstream loadFile; - SystemBackendProc() : uptimeFile("/proc/uptime"), meminfoFile("/proc/meminfo"), loadFile("/proc/loadavg") {} - protected: virtual void getUptimeInfo(unsigned long *uptime, unsigned long *idleTime) throw(Core::Exception); virtual void getMemoryInfo(unsigned long *totalMem, unsigned long *freeMem, unsigned long *totalSwap, unsigned long *freeSwap) throw(Core::Exception); virtual void getLoadInfo(unsigned long *currentLoad, unsigned long *nProcesses, float *loadAvg1, float *loadAvg5, float *loadAvg15) throw(Core::Exception); public: - static void registerBackend() { - if(backend) - return; - - backend.reset(new SystemBackendProc()); - Common::SystemManager::get()->registerBackend(backend); - } - - static void unregisterBackend() { - if(!backend) - return; - - Common::SystemManager::get()->unregisterBackend(backend); - backend.reset(); - } + SystemBackendProc(Common::Application *application0) : application(application0), uptimeFile("/proc/uptime"), meminfoFile("/proc/meminfo"), loadFile("/proc/loadavg") {} }; } } +} -#endif /* MAD_MODULES_SYSTEMBACKENDPROC_H_ */ +#endif /* MAD_MODULES_SYSTEMBACKENDPROC_SYSTEMBACKENDPROC_H_ */ diff --git a/src/modules/UserBackendMysql/CMakeLists.txt b/src/modules/UserBackendMysql/CMakeLists.txt index b185c13..5f32d9c 100644 --- a/src/modules/UserBackendMysql/CMakeLists.txt +++ b/src/modules/UserBackendMysql/CMakeLists.txt @@ -1,6 +1,7 @@ include_directories(${INCLUDES} ${MYSQL_INCLUDE_DIR}) add_library(UserBackendMysql MODULE + Module.cpp Module.h UserBackendMysql.cpp UserBackendMysql.h ) diff --git a/src/modules/UserBackendMysql/Module.cpp b/src/modules/UserBackendMysql/Module.cpp new file mode 100644 index 0000000..c29f65b --- /dev/null +++ b/src/modules/UserBackendMysql/Module.cpp @@ -0,0 +1,28 @@ +/* + * Module.cpp + * + * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de> + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "Module.h" + +extern "C" { + +Mad::Common::Module* UserBackendMysql_create(Mad::Common::Application *application) { + return new Mad::Modules::UserBackendMysql::Module(application); +} + +} diff --git a/src/modules/UserBackendMysql/Module.h b/src/modules/UserBackendMysql/Module.h new file mode 100644 index 0000000..31f6692 --- /dev/null +++ b/src/modules/UserBackendMysql/Module.h @@ -0,0 +1,59 @@ +/* + * Module.h + * + * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de> + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef MAD_MODULES_USERBACKENDMYSQL_MODULE_H_ +#define MAD_MODULES_USERBACKENDMYSQL_MODULE_H_ + +#include "UserBackendMysql.h" + +#include <Server/Application.h> +#include <Server/UserManager.h> +#include <Common/Module.h> + +namespace Mad { +namespace Modules { +namespace UserBackendMysql { + +class Module : public Common::Module { + private: + Common::Application *application; + + boost::shared_ptr<UserBackendMysql> backend; + + public: + Module(Common::Application *application0) : application(application0), backend(new UserBackendMysql(application)) { + Server::Application *app = dynamic_cast<Server::Application*>(application); + + if(app) + app->getUserManager()->registerBackend(backend); + } + + virtual ~Module() { + Server::Application *app = dynamic_cast<Server::Application*>(application); + + if(app) + app->getUserManager()->unregisterBackend(backend); + } +}; + +} +} +} + +#endif /* MAD_MODULES_USERBACKENDMYSQL_MODULE_H_ */ diff --git a/src/modules/UserBackendMysql/UserBackendMysql.cpp b/src/modules/UserBackendMysql/UserBackendMysql.cpp index f0e9b2e..904c9a6 100644 --- a/src/modules/UserBackendMysql/UserBackendMysql.cpp +++ b/src/modules/UserBackendMysql/UserBackendMysql.cpp @@ -22,7 +22,6 @@ #include "UserBackendMysql.h" #include <Core/ConfigEntry.h> #include <Core/ConfigManager.h> -#include <Core/Logger.h> #include <Core/ThreadManager.h> #include <sstream> @@ -33,8 +32,8 @@ namespace Mad { namespace Modules { +namespace UserBackendMysql { -boost::shared_ptr<UserBackendMysql> UserBackendMysql::backend; bool UserBackendMysql::handleConfigEntry(const Core::ConfigEntry &entry, bool handled) { if(handled) @@ -65,7 +64,7 @@ bool UserBackendMysql::handleConfigEntry(const Core::ConfigEntry &entry, bool ha val = strtol(entry[1][0].c_str(), &endptr, 10); if(endptr != 0 || val < 0 || val > 65535) - Core::Logger::log(Core::Logger::WARNING, "UserBackendMysql: Invalid port"); + application->log(Core::LoggerBase::WARNING, "UserBackendMysql: Invalid port"); else port = val; } @@ -121,21 +120,19 @@ bool UserBackendMysql::handleConfigEntry(const Core::ConfigEntry &entry, bool ha void UserBackendMysql::configFinished() { if(db.empty()) { - Core::Logger::log(Core::Logger::ERROR, "UserBackendMysql: No database name given"); + application->log(Core::LoggerBase::ERROR, "UserBackendMysql: No database name given"); return; } mysql = mysql_init(0); mysql_real_connect(mysql, host.c_str(), username.c_str(), passwd.c_str(), db.c_str(), port, unixSocket.empty() ? 0 : unixSocket.c_str(), 0); - - Server::UserManager::get()->registerBackend(backend); } boost::shared_ptr<std::map<unsigned long, Common::UserInfo> > UserBackendMysql::getUserList() throw(Core::Exception) { - Core::ThreadManager::get()->detach(); + application->getThreadManager()->detach(); - if(mysql_ping(mysql)) + if(!mysql || mysql_ping(mysql)) throw Core::Exception(Core::Exception::NOT_AVAILABLE); mysql_real_query(mysql, queryListUsers.c_str(), queryListUsers.length()); @@ -159,9 +156,9 @@ boost::shared_ptr<std::map<unsigned long, Common::UserInfo> > UserBackendMysql:: } boost::shared_ptr<Common::UserInfo> UserBackendMysql::getUserInfo(unsigned long uid) throw(Core::Exception) { - Core::ThreadManager::get()->detach(); + application->getThreadManager()->detach(); - if(mysql_ping(mysql)) + if(!mysql || mysql_ping(mysql)) throw Core::Exception(Core::Exception::NOT_AVAILABLE); std::string query = queryUserById; @@ -196,9 +193,9 @@ boost::shared_ptr<Common::UserInfo> UserBackendMysql::getUserInfo(unsigned long } boost::shared_ptr<Common::UserInfo> UserBackendMysql::getUserInfoByName(const std::string &name) throw(Core::Exception) { - Core::ThreadManager::get()->detach(); + application->getThreadManager()->detach(); - if(mysql_ping(mysql)) + if(!mysql || mysql_ping(mysql)) throw Core::Exception(Core::Exception::NOT_AVAILABLE); boost::scoped_array<char> escapedName(new char[name.length()*2+1]); @@ -230,9 +227,9 @@ boost::shared_ptr<Common::UserInfo> UserBackendMysql::getUserInfoByName(const st } boost::shared_ptr<std::set<unsigned long> > UserBackendMysql::getUserGroupList(unsigned long uid) throw(Core::Exception) { - Core::ThreadManager::get()->detach(); + application->getThreadManager()->detach(); - if(mysql_ping(mysql)) + if(!mysql || mysql_ping(mysql)) throw Core::Exception(Core::Exception::NOT_AVAILABLE); std::ostringstream tmp; @@ -258,9 +255,9 @@ boost::shared_ptr<std::set<unsigned long> > UserBackendMysql::getUserGroupList(u boost::shared_ptr<std::map<unsigned long, Common::GroupInfo> > UserBackendMysql::getGroupList() throw(Core::Exception) { - Core::ThreadManager::get()->detach(); + application->getThreadManager()->detach(); - if(mysql_ping(mysql)) + if(!mysql || mysql_ping(mysql)) throw Core::Exception(Core::Exception::NOT_AVAILABLE); mysql_real_query(mysql, queryListGroups.c_str(), queryListGroups.length()); @@ -281,9 +278,9 @@ boost::shared_ptr<std::map<unsigned long, Common::GroupInfo> > UserBackendMysql: } std::string UserBackendMysql::getGroupName(unsigned long gid) throw(Core::Exception) { - Core::ThreadManager::get()->detach(); + application->getThreadManager()->detach(); - if(mysql_ping(mysql)) + if(!mysql || mysql_ping(mysql)) throw Core::Exception(Core::Exception::NOT_AVAILABLE); std::string query = queryGroupById; @@ -310,9 +307,9 @@ std::string UserBackendMysql::getGroupName(unsigned long gid) throw(Core::Except } unsigned long UserBackendMysql::getGroupId(const std::string &name) throw(Core::Exception) { - Core::ThreadManager::get()->detach(); + application->getThreadManager()->detach(); - if(mysql_ping(mysql)) + if(!mysql || mysql_ping(mysql)) throw Core::Exception(Core::Exception::NOT_AVAILABLE); boost::scoped_array<char> escapedName(new char[name.length()*2+1]); @@ -336,9 +333,9 @@ unsigned long UserBackendMysql::getGroupId(const std::string &name) throw(Core:: } boost::shared_ptr<std::set<unsigned long> > UserBackendMysql::getGroupUserList(unsigned long gid) throw(Core::Exception) { - Core::ThreadManager::get()->detach(); + application->getThreadManager()->detach(); - if(mysql_ping(mysql)) + if(!mysql || mysql_ping(mysql)) throw Core::Exception(Core::Exception::NOT_AVAILABLE); std::ostringstream tmp; @@ -362,36 +359,6 @@ boost::shared_ptr<std::set<unsigned long> > UserBackendMysql::getGroupUserList(u return users; } - -void UserBackendMysql::registerBackend() { - if(backend) - return; - - backend.reset(new UserBackendMysql()); - Core::ConfigManager::get()->registerConfigurable(backend.get()); } - -void UserBackendMysql::unregisterBackend() { - if(!backend) - return; - - Core::ConfigManager::get()->unregisterConfigurable(backend.get()); - Server::UserManager::get()->unregisterBackend(backend); - - backend.reset(); } - -} -} - -extern "C" { - -void UserBackendMysql_init() { - Mad::Modules::UserBackendMysql::registerBackend(); -} - -void UserBackendMysql_deinit() { - Mad::Modules::UserBackendMysql::unregisterBackend(); -} - } diff --git a/src/modules/UserBackendMysql/UserBackendMysql.h b/src/modules/UserBackendMysql/UserBackendMysql.h index 523806f..aa141da 100644 --- a/src/modules/UserBackendMysql/UserBackendMysql.h +++ b/src/modules/UserBackendMysql/UserBackendMysql.h @@ -17,22 +17,25 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ -#ifndef MAD_MODULES_USERBACKENDMYSQL_H_ -#define MAD_MODULES_USERBACKENDMYSQL_H_ +#ifndef MAD_MODULES_USERBACKENDMYSQL_USERBACKENDMYSQL_H_ +#define MAD_MODULES_USERBACKENDMYSQL_USERBACKENDMYSQL_H_ #include <Server/UserBackend.h> -#include <Server/UserManager.h> + +#include <Common/Application.h> + #include <Core/Configurable.h> +#include <Core/ConfigManager.h> #include <mysql/mysql.h> - namespace Mad { namespace Modules { +namespace UserBackendMysql { class UserBackendMysql : public Server::UserBackend, private Core::Configurable { private: - static boost::shared_ptr<UserBackendMysql> backend; + Common::Application *application; std::string host, username, passwd, db, unixSocket; uint16_t port; @@ -44,8 +47,6 @@ class UserBackendMysql : public Server::UserBackend, private Core::Configurable MYSQL *mysql; - UserBackendMysql() : port(0), mysql(0) {} - protected: virtual bool handleConfigEntry(const Core::ConfigEntry &entry, bool); virtual void configFinished(); @@ -61,18 +62,22 @@ class UserBackendMysql : public Server::UserBackend, private Core::Configurable virtual boost::shared_ptr<std::set<unsigned long> > getGroupUserList(unsigned long gid) throw(Core::Exception); public: + UserBackendMysql(Common::Application *application0) : application(application0), port(0), mysql(0) { + application->getConfigManager()->registerConfigurable(this); + } + virtual ~UserBackendMysql() { + application->getConfigManager()->unregisterConfigurable(this); + if(mysql) { mysql_close(mysql); mysql = 0; } } - - static void registerBackend(); - static void unregisterBackend(); }; } } +} -#endif /* MAD_MODULES_USERBACKENDMYSQL_H_ */ +#endif /* MAD_MODULES_USERBACKENDMYSQL_USERBACKENDMYSQL_H_ */ |