// Copyright (C) 2013-2017 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef D_CONTROLLER_H #define D_CONTROLLER_H #include #include #include #include #include #include #include #include #include #include namespace isc { namespace process { /// @brief Exception thrown when the command line is invalid. /// Can be used to transmit negative messages too. class InvalidUsage : public isc::Exception { public: InvalidUsage(const char* file, size_t line, const char* what) : isc::Exception(file, line, what) { }; }; /// @brief Exception used to convey version info upwards. /// Since command line argument parsing is done as part of /// DControllerBase::launch(), it uses this exception to propagate /// version information up to main(), when command line argument /// -v, -V or -W is given. Can be used to transmit positive messages too. class VersionMessage : public isc::Exception { public: VersionMessage(const char* file, size_t line, const char* what) : isc::Exception(file, line, what) { }; }; /// @brief Exception thrown when the controller launch fails. class LaunchError: public isc::Exception { public: LaunchError (const char* file, size_t line, const char* what) : isc::Exception(file, line, what) { }; }; /// @brief Exception thrown when the application process fails. class ProcessInitError: public isc::Exception { public: ProcessInitError (const char* file, size_t line, const char* what) : isc::Exception(file, line, what) { }; }; /// @brief Exception thrown when the application process encounters an /// operation in its event loop (i.e. run method). class ProcessRunError: public isc::Exception { public: ProcessRunError (const char* file, size_t line, const char* what) : isc::Exception(file, line, what) { }; }; /// @brief Exception thrown when the controller encounters an operational error. class DControllerBaseError : public isc::Exception { public: DControllerBaseError (const char* file, size_t line, const char* what) : isc::Exception(file, line, what) { }; }; /// @brief Defines a shared pointer to DControllerBase. class DControllerBase; typedef boost::shared_ptr DControllerBasePtr; /// @brief Application Controller /// /// DControllerBase is an abstract singleton which provides the framework and /// services for managing an application process that implements the /// DProcessBase interface. It runs the process like a stand-alone, command /// line driven executable, which must be supplied a configuration file at /// startup. It coordinates command line argument parsing, process /// instantiation and initialization, and runtime control through external /// command and configuration event handling. /// It creates the IOService instance which is used for runtime control /// events and passes the IOService into the application process at process /// creation. /// It provides the callback handlers for command and configuration events /// which could be triggered by an external source. Such sources are intended /// to be registered with and monitored by the controller's IOService such that /// the appropriate handler can be invoked. /// /// DControllerBase provides dynamic configuration file reloading upon receipt /// of SIGHUP, and graceful shutdown upon receipt of either SIGINT or SIGTERM. /// /// NOTE: Derivations must supply their own static singleton instance method(s) /// for creating and fetching the instance. The base class declares the instance /// member in order for it to be available for static callback functions. class DControllerBase : public dhcp::Daemon { public: /// @brief Constructor /// /// @param app_name is display name of the application under control. This /// name appears in log statements. /// @param bin_name is the name of the application executable. DControllerBase(const char* app_name, const char* bin_name); /// @brief Destructor virtual ~DControllerBase(); /// @brief returns Kea version on stdout and exit. /// redeclaration/redefinition. @ref isc::dhcp::Daemon::getVersion() static std::string getVersion(bool extended); /// @brief Acts as the primary entry point into the controller execution /// and provides the outermost application control logic: /// /// 1. parse command line arguments /// 2. instantiate and initialize the application process /// 3. load the configuration file /// 4. initialize signal handling /// 5. start and wait on the application process event loop /// 6. exit to the caller /// /// It is intended to be called from main() and be given the command line /// arguments. /// /// This function can be run in "test mode". It prevents initialization /// of module logger. This is used in unit tests which initialize logger /// in their main function. Such a logger uses environmental variables to /// control severity, verbosity etc. /// /// @param argc is the number of command line arguments supplied /// @param argv is the array of string (char *) command line arguments /// @param test_mode is a bool value which indicates if /// @c DControllerBase::launch should be run in the test mode (if true). /// This parameter doesn't have default value to force test implementers to /// enable test mode explicitly. /// /// @throw throws one of the following exceptions: /// InvalidUsage - Indicates invalid command line. /// ProcessInitError - Failed to create and initialize application /// process object. /// ProcessRunError - A fatal error occurred while in the application /// process event loop. virtual void launch(int argc, char* argv[], const bool test_mode); /// @brief Instance method invoked by the configuration event handler and /// which processes the actual configuration update. Provides behavioral /// path for both integrated and stand-alone modes. The current /// implementation will merge the configuration update into the existing /// configuration and then invoke the application process' configure method. /// /// @param new_config is the new configuration /// /// @return returns an Element that contains the results of configuration /// update composed of an integer status value (0 means successful, /// non-zero means failure), and a string explanation of the outcome. virtual isc::data::ConstElementPtr updateConfig(isc::data::ConstElementPtr new_config); /// @brief Instance method invoked by the configuration event handler and /// which processes the actual configuration check. Provides behavioral /// path for both integrated and stand-alone modes. The current /// implementation will merge the configuration update into the existing /// configuration and then invoke the application process' configure method /// with a final rollback. /// /// @param new_config is the new configuration /// /// @return returns an Element that contains the results of configuration /// update composed of an integer status value (0 means successful, /// non-zero means failure), and a string explanation of the outcome. virtual isc::data::ConstElementPtr checkConfig(isc::data::ConstElementPtr new_config); /// @brief Reconfigures the process from a configuration file /// /// By default the file is assumed to be a JSON text file whose contents /// include at least: /// /// @code /// { "": {} /// /// # Logging element is optional /// ,"Logging": {(input); // just tu shut up the unused parameter warning isc::data::ConstElementPtr elements; return (elements); } /// @brief Instantiates the application process and then initializes it. /// This is the second step taken during launch, following successful /// command line parsing. It is used to invoke the derivation-specific /// implementation of createProcess, following by an invoking of the /// newly instantiated process's init method. /// /// @throw throws DControllerBaseError or indirectly DProcessBaseError /// if there is a failure creating or initializing the application process. void initProcess(); /// @brief Invokes the application process's event loop,(DBaseProcess::run). /// It is called during launch only after successfully completing the /// requested setup: command line parsing, application initialization, /// and session establishment (if not stand-alone). /// The process event loop is expected to only return upon application /// shutdown either in response to the shutdown command or due to an /// unrecoverable error. /// // @throw throws DControllerBaseError or indirectly DProcessBaseError void runProcess(); /// @brief Initiates shutdown procedure. This method is invoked /// by executeCommand in response to the shutdown command. It will invoke /// the application process's shutdown method which causes the process to /// to begin its shutdown process. /// /// Note, it is assumed that the process of shutting down is neither /// instantaneous nor synchronous. This method does not "block" waiting /// until the process has halted. Rather it is used to convey the /// need to shutdown. A successful return indicates that the shutdown /// has successfully commenced, but does not indicate that the process /// has actually exited. /// /// @return returns an Element that contains the results of shutdown /// command composed of an integer status value (0 means successful, /// non-zero means failure), and a string explanation of the outcome. /// /// @param args is a set of derivation-specific arguments (if any) /// for the shutdown command. isc::data::ConstElementPtr shutdownProcess(isc::data::ConstElementPtr args); /// @brief Initializes signal handling /// /// This method configures the controller to catch and handle signals. /// It instantiates an IOSignalQueue, registers @c osSignalHandler() as /// the SignalSet "on-receipt" handler, and lastly instantiates a SignalSet /// which listens for SIGHUP, SIGINT, and SIGTERM. void initSignalHandling(); /// @brief Handler for processing OS-level signals /// /// This method is installed as the SignalSet "on-receipt" handler. Upon /// invocation, it uses the controller's IOSignalQueue to schedule an /// IOSignal with for the given signal value. /// /// @param signum OS signal value (e.g. SIGINT, SIGUSR1 ...) to received /// /// @return SignalSet "on-receipt" handlers are required to return a /// boolean indicating if the OS signal has been processed (true) or if it /// should be saved for deferred processing (false). Currently this /// method processes all received signals, so it always returns true. bool osSignalHandler(int signum); /// @brief Handler for processing IOSignals /// /// This method is supplied as the callback when IOSignals are scheduled. /// It fetches the IOSignal for the given sequence_id and then invokes /// the virtual method, @c processSignal() passing it the signal value /// obtained from the IOSignal. This allows derivations to supply a /// custom signal processing method, while ensuring IOSignalQueue /// integrity. /// /// @param sequence_id id of the IOSignal instance "received" void ioSignalHandler(IOSignalId sequence_id); /// @brief Fetches the current process /// /// @return a pointer to the current process instance. DProcessBasePtr getProcess() { return (process_); } /// @brief Prints the program usage text to std error. /// /// @param text is a string message which will preceded the usage text. /// This is intended to be used for specific usage violation messages. void usage(const std::string& text); private: /// @brief Name of the service under control. /// This name is used as the configuration module name and appears in log /// statements. std::string app_name_; /// @brief Name of the service executable. /// By convention this matches the executable name. It is also used to /// establish the logger name. std::string bin_name_; /// @brief Indicates if the verbose logging mode is enabled. bool verbose_; /// @brief Indicates if the check only mode is enabled. bool check_only_; /// @brief The absolute file name of the JSON spec file. std::string spec_file_name_; /// @brief Pointer to the instance of the process. /// /// This is required for config and command handlers to gain access to /// the process DProcessBasePtr process_; /// @brief Shared pointer to an IOService object, used for ASIO operations. asiolink::IOServicePtr io_service_; /// @brief Queue for propagating caught signals to the IOService. IOSignalQueuePtr io_signal_queue_; /// @brief Singleton instance value. static DControllerBasePtr controller_; // DControllerTest is named a friend class to facilitate unit testing while // leaving the intended member scopes intact. friend class DControllerTest; }; }; // namespace isc::process }; // namespace isc #endif