d_controller.h 18.2 KB
Newer Older
1
// Copyright (C) 2013-2014 Internet Systems Consortium, Inc. ("ISC")
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

#ifndef D_CONTROLLER_H
#define D_CONTROLLER_H

#include <cc/data.h>
19
#include <d2/d2_asio.h>
20 21
#include <d2/d2_log.h>
#include <d2/d_process.h>
22
#include <dhcpsrv/daemon.h>
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
#include <exceptions/exceptions.h>
#include <log/logger_support.h>

#include <boost/shared_ptr.hpp>
#include <boost/noncopyable.hpp>


namespace isc {
namespace d2 {

/// @brief Exception thrown when the command line is invalid.
class InvalidUsage : public isc::Exception {
public:
    InvalidUsage(const char* file, size_t line, const char* what) :
        isc::Exception(file, line, what) { };
};

40 41 42 43 44 45 46
/// @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) { };
};

47
/// @brief Exception thrown when the application process encounters an
48 49 50 51 52 53 54
/// 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) { };
};

55 56 57 58 59 60 61 62
/// @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) { };
};


63
/// @brief Defines a shared pointer to DControllerBase.
64 65 66 67 68 69
class DControllerBase;
typedef boost::shared_ptr<DControllerBase> DControllerBasePtr;

/// @brief Application Controller
///
/// DControllerBase is an abstract singleton which provides the framework and
70
/// services for managing an application process that implements the
71 72 73 74 75
/// 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.
76 77
/// It creates the IOService instance which is used for runtime control
/// events and passes the IOService into the application process at process
78 79 80 81 82
/// 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 registed with and monitored by the controller's IOService such that
/// the appropriate handler can be invoked.
83
///
84 85
/// NOTE: Derivations must supply their own static singleton instance method(s)
/// for creating and fetching the instance. The base class declares the instance
86 87
/// member in order for it to be available for static callback functions.
class DControllerBase : public dhcp::Daemon {
88
public:
89
    /// @brief Constructor
90
    ///
91 92
    /// @param app_name is display name of the application under control. This
    /// name appears in log statements.
93
    /// @param bin_name is the name of the application executable.
94
    DControllerBase(const char* app_name, const char* bin_name);
95 96 97 98 99 100 101 102 103

    /// @brief Destructor
    virtual ~DControllerBase();

    /// @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
104
    /// 3. load the configuration file
105
    /// 4. start and wait on the application process event loop
106
    /// 5. exit to the caller
107 108
    ///
    /// It is intended to be called from main() and be given the command line
109
    /// arguments.
110
    ///
111
    /// This function can be run in "test mode". It prevents initialization
112
    /// of D2 module logger. This is used in unit tests which initialize logger
113 114
    /// in their main function. Such a logger uses environmental variables to
    /// control severity, verbosity etc.
115
    ///
116
    /// @param argc  is the number of command line arguments supplied
117
    /// @param argv  is the array of string (char *) command line arguments
118 119 120 121
    /// @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.
122
    ///
123 124 125 126
    /// @throw throws one of the following exceptions:
    /// InvalidUsage - Indicates invalid command line.
    /// ProcessInitError  - Failed to create and initialize application
    /// process object.
127
    /// ProcessRunError - A fatal error occurred while in the application
128
    /// process event loop.
129
    virtual void launch(int argc, char* argv[], const bool test_mode);
130

131 132 133 134
    /// @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
135 136
    /// configuration and then invoke the application process' configure method.
    ///
137 138
    /// @param  new_config is the new configuration
    ///
139
    /// @return returns an Element that contains the results of configuration
140 141
    /// update composed of an integer status value (0 means successful,
    /// non-zero means failure), and a string explanation of the outcome.
142 143
    virtual isc::data::ConstElementPtr updateConfig(isc::data::ConstElementPtr
                                                    new_config);
144

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    /// @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
    ///  { "<module-name>": {<module-config>} }
    ///
    ///  where:
    ///     module-name : is a label which uniquely identifies the
    ///                   configuration data for this controller's application
    ///
    ///     module-config: a set of zero or more JSON elements which comprise
    ///                    the application'ss configuration values
    /// @endcode
    ///
    /// The method extracts the set of configuration elements for the
    /// module-name which matches the controller's app_name_ and passes that
    /// set into @c udpateConfig().
    ///
    /// The file may contain an arbitrary number of other modules.
    ///
    /// @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 configFromFile();
171 172

    /// @brief Instance method invoked by the command event handler and  which
173 174
    /// processes the actual command directive.
    ///
175 176 177
    /// It supports the execution of:
    ///
    ///   1. Stock controller commands - commands common to all DControllerBase
178
    /// derivations.  Currently there is only one, the shutdown command.
179 180 181
    ///
    ///   2. Custom controller commands - commands that the deriving controller
    /// class implements.  These commands are executed by the deriving
182
    /// controller.
183 184 185
    ///
    ///   3. Custom application commands - commands supported by the application
    /// process implementation.  These commands are executed by the application
186
    /// process.
187 188 189
    ///
    /// @param command is a string label representing the command to execute.
    /// @param args is a set of arguments (if any) required for the given
190
    /// command.
191 192 193 194 195 196 197 198 199
    ///
    /// @return an Element that contains the results of command composed
    /// of an integer status value and a string explanation of the outcome.
    /// The status value is one of the following:
    ///   D2::COMMAND_SUCCESS - Command executed successfully
    ///   D2::COMMAND_ERROR - Command is valid but suffered an operational
    ///   failure.
    ///   D2::COMMAND_INVALID - Command is not recognized as valid be either
    ///   the controller or the application process.
200 201 202 203 204 205 206 207
    virtual isc::data::ConstElementPtr executeCommand(const std::string&
                                                      command,
                                                      isc::data::
                                                      ConstElementPtr args);

    /// @brief Fetches the name of the application under control.
    ///
    /// @return returns the controller service name string
208
    std::string getAppName() const {
209 210 211 212 213 214
        return (app_name_);
    }

    /// @brief Fetches the name of the application executable.
    ///
    /// @return returns the controller logger name string
215
    std::string getBinName() const {
216 217
        return (bin_name_);
    }
218 219 220 221 222

protected:
    /// @brief Virtual method that provides derivations the opportunity to
    /// support additional command line options.  It is invoked during command
    /// line argument parsing (see parseArgs method) if the option is not
223
    /// recognized as a stock DControllerBase option.
224 225
    ///
    /// @param option is the option "character" from the command line, without
226
    /// any prefixing hyphen(s)
227
    /// @param optarg is the argument value (if one) associated with the option
228
    ///
229 230
    /// @return must return true if the option was valid, false is it is
    /// invalid. (Note the default implementation always returns false.)
231 232
    virtual bool customOption(int option, char *optarg);

233
    /// @brief Abstract method that is responsible for instantiating the
234
    /// application process object. It is invoked by the controller after
235
    /// command line argument parsing as part of the process initialization
236
    /// (see initProcess method).
237
    ///
238
    /// @return returns a pointer to the new process object (DProcessBase*)
239
    /// or NULL if the create fails.
240 241 242 243 244
    /// Note this value is subsequently wrapped in a smart pointer.
    virtual DProcessBase* createProcess() = 0;

    /// @brief Virtual method that provides derivations the opportunity to
    /// support custom external commands executed by the controller.  This
245
    /// method is invoked by the processCommand if the received command is
246 247 248 249
    /// not a stock controller command.
    ///
    /// @param command is a string label representing the command to execute.
    /// @param args is a set of arguments (if any) required for the given
250
    /// command.
251 252 253 254 255 256 257
    ///
    /// @return an Element that contains the results of command composed
    /// of an integer status value and a string explanation of the outcome.
    /// The status value is one of the following:
    ///   D2::COMMAND_SUCCESS - Command executed successfully
    ///   D2::COMMAND_ERROR - Command is valid but suffered an operational
    ///   failure.
258 259
    ///   D2::COMMAND_INVALID - Command is not recognized as a valid custom
    ///   controller command.
260 261 262 263 264 265 266 267
    virtual isc::data::ConstElementPtr customControllerCommand(
            const std::string& command, isc::data::ConstElementPtr args);

    /// @brief Virtual method which can be used to contribute derivation
    /// specific usage text.  It is invoked by the usage() method under
    /// invalid usage conditions.
    ///
    /// @return returns the desired text.
268
    virtual const std::string getUsageText() const {
269 270 271 272
        return ("");
    }

    /// @brief Virtual method which returns a string containing the option
273
    /// letters for any custom command line options supported by the derivation.
274
    /// These are added to the stock options of "c" and "v" during command
275 276 277
    /// line interpretation.
    ///
    /// @return returns a string containing the custom option letters.
278
    virtual const std::string getCustomOpts() const {
279 280 281
        return ("");
    }

282
    /// @brief Supplies whether or not verbose logging is enabled.
283 284
    ///
    /// @return returns true if verbose logging is enabled.
285
    bool isVerbose() const {
286 287 288
        return (verbose_);
    }

289
    /// @brief Method for enabling or disabling verbose logging.
290 291 292 293 294 295 296 297 298 299 300 301 302
    ///
    /// @param value is the new value to assign the flag.
    void setVerbose(bool value) {
        verbose_ = value;
    }

    /// @brief Getter for fetching the controller's IOService
    ///
    /// @return returns a pointer reference to the IOService.
    IOServicePtr& getIOService() {
        return (io_service_);
    }

303
    /// @brief Getter for fetching the name of the controller's config spec
304 305
    /// file.
    ///
306
    /// @return returns the file name string.
307
    const std::string getSpecFileName() const {
308 309 310
        return (spec_file_name_);
    }

311
    /// @brief Setter for setting the name of the controller's config spec file.
312
    ///
313
    /// @param spec_file_name the file name string.
314 315 316 317 318 319 320 321 322 323 324 325
    void setSpecFileName(const std::string& spec_file_name) {
        spec_file_name_ = spec_file_name;
    }

    /// @brief Static getter which returns the singleton instance.
    ///
    /// @return returns a pointer reference to the private singleton instance
    /// member.
    static DControllerBasePtr& getController() {
        return (controller_);
    }

326 327 328
    /// @brief Static setter which sets the singleton instance.
    ///
    /// @param controller is a pointer to the singleton instance.
329 330 331
    ///
    /// @throw throws DControllerBase error if an attempt is made to set the
    /// instance a second time.
332
    static void setController(const DControllerBasePtr& controller);
333 334 335 336 337 338 339

    /// @brief Processes the command line arguments. It is the first step
    /// taken after the controller has been launched.  It combines the stock
    /// list of options with those returned by getCustomOpts(), and uses
    /// cstdlib's getopt to loop through the command line.  The stock options
    /// It handles stock options directly, and passes any custom options into
    /// the customOption method.  Currently there are only two stock options
340
    /// -c for specifying the configuration file, and -v for verbose logging.
341
    ///
342
    /// @param argc  is the number of command line arguments supplied
343 344
    /// @param argv  is the array of string (char *) command line arguments
    ///
345
    /// @throw throws InvalidUsage when there are usage errors.
346 347 348
    void parseArgs(int argc, char* argv[]);

    /// @brief Instantiates the application process and then initializes it.
349
    /// This is the second step taken during launch, following successful
350
    /// command line parsing. It is used to invoke the derivation-specific
351 352
    /// implementation of createProcess, following by an invoking of the
    /// newly instantiated process's init method.
353 354 355 356 357 358
    ///
    /// @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).
359 360 361 362
    /// 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
363
    /// shutdown either in response to the shutdown command or due to an
364
    /// unrecoverable error.
365 366 367 368 369 370
    ///
    // @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
371 372 373 374 375 376 377 378
    /// 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
    /// instanteneous 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
379
    /// has actually exited.
380
    ///
381
    /// @return returns an Element that contains the results of shutdown
382
    /// command composed of an integer status value (0 means successful,
383
    /// non-zero means failure), and a string explanation of the outcome.
384 385 386 387 388 389 390 391
    isc::data::ConstElementPtr shutdownProcess(isc::data::ConstElementPtr args);

    /// @brief Fetches the current process
    ///
    /// @return the a pointer to the current process instance.
    DProcessBasePtr getProcess() {
        return (process_);
    }
392 393

    /// @brief Prints the program usage text to std error.
394
    ///
395 396
    /// @param text is a string message which will preceded the usage text.
    /// This is intended to be used for specific usage violation messages.
397
    void usage(const std::string& text);
398 399

private:
400 401 402
    /// @brief Name of the service under control.
    /// This name is used as the configuration module name and appears in log
    /// statements.
403 404
    std::string app_name_;

405 406 407
    /// @brief Name of the service executable.
    /// By convention this matches the executable nam. It is also used to
    /// establish the logger name.
408
    std::string bin_name_;
409

410
    /// @brief Indicates if the verbose logging mode is enabled.
411
    bool verbose_;
412

413
    /// @brief The absolute file name of the JSON spec file.
414 415 416 417 418 419 420 421 422 423 424
    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.
    IOServicePtr io_service_;

425
    /// @brief Singleton instance value.
426 427
    static DControllerBasePtr controller_;

428
// DControllerTest is named a friend class to facilitate unit testing while
429 430 431 432 433 434 435 436
// leaving the intended member scopes intact.
friend class DControllerTest;
};

}; // namespace isc::d2
}; // namespace isc

#endif