d_controller.cc 15.7 KB
Newer Older
1
// Copyright (C) 2013-2015 Internet Systems Consortium, Inc. ("ISC")
2 3 4 5 6 7 8 9 10 11 12 13 14
//
// 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.

15
#include <config.h>
16
#include <d2/d2_log.h>
17
#include <cc/command_interpreter.h>
18 19 20
#include <d2/d_controller.h>
#include <exceptions/exceptions.h>
#include <log/logger_support.h>
21
#include <dhcpsrv/cfgmgr.h>
22 23

#include <sstream>
24
#include <unistd.h>
25 26 27 28 29 30 31

namespace isc {
namespace d2 {

DControllerBasePtr DControllerBase::controller_;

// Note that the constructor instantiates the controller's primary IOService.
32
DControllerBase::DControllerBase(const char* app_name, const char* bin_name)
33
    : app_name_(app_name), bin_name_(bin_name),
34
      verbose_(false), spec_file_name_(""),
35 36
      io_service_(new isc::asiolink::IOService()),
      signal_set_(), io_signal_queue_() {
37 38
}

39
void
40
DControllerBase::setController(const DControllerBasePtr& controller) {
41 42 43 44 45 46 47
    if (controller_) {
        // This shouldn't happen, but let's make sure it can't be done.
        // It represents a programmatic error.
        isc_throw (DControllerBaseError,
                "Multiple controller instances attempted.");
    }

48
    controller_ = controller;
49 50
}

51
void
52
DControllerBase::launch(int argc, char* argv[], const bool test_mode) {
53

54 55 56 57 58
    // Step 1 is to parse the command line arguments.
    try {
        parseArgs(argc, argv);
    } catch (const InvalidUsage& ex) {
        usage(ex.what());
59
        throw; // rethrow it
60 61
    }

62 63 64 65 66 67 68 69 70 71
    // It is important that we set a default logger name because this name
    // will be used when the user doesn't provide the logging configuration
    // in the Kea configuration file.
    isc::dhcp::CfgMgr::instance().setDefaultLoggerName(bin_name_);

    // Logger's default configuration depends on whether we are in the
    // verbose mode or not. CfgMgr manages the logger configuration so
    // the verbose mode is set for CfgMgr.
    isc::dhcp::CfgMgr::instance().setVerbose(verbose_);

72 73 74 75
    // Do not initialize logger here if we are running unit tests. It would
    // replace an instance of unit test specific logger.
    if (!test_mode) {
        // Now that we know what the mode flags are, we can init logging.
76
        Daemon::loggerInit(bin_name_.c_str(), verbose_);
77
    }
78

79 80 81
    // Log the starting of the service.  Although this is the controller
    // module, use a "DHCP_DDNS_" prefix to the module (to conform to the
    // principle of least astonishment).
82
    LOG_INFO(dctl_logger, DHCP_DDNS_STARTING).arg(getpid()).arg(VERSION);
83
    try {
84
        // Step 2 is to create and initialize the application process object.
85
        initProcess();
86
    } catch (const std::exception& ex) {
87 88 89
        LOG_FATAL(dctl_logger, DCTL_INIT_PROCESS_FAIL)
                  .arg(app_name_).arg(ex.what());
        isc_throw (ProcessInitError,
90
                   "Application Process initialization failed: " << ex.what());
91
    }
92

93

94 95 96 97 98 99 100 101 102 103 104
    LOG_DEBUG(dctl_logger, DBGLVL_START_SHUT, DCTL_STANDALONE).arg(app_name_);

    // Step 3 is to load configuration from file.
    int rcode;
    isc::data::ConstElementPtr comment
        = isc::config::parseAnswer(rcode, configFromFile());
    if (rcode != 0) {
        LOG_FATAL(dctl_logger, DCTL_CONFIG_FILE_LOAD_FAIL)
                  .arg(app_name_).arg(comment->stringValue());
        isc_throw (ProcessInitError, "Could Not load configration file: "
                   << comment->stringValue());
105
    }
106

107 108 109
    // Everything is clear for launch, so start the application's
    // event loop.
    try {
110 111
        // Now that we have a proces, we can set up signal handling.
        initSignalHandling();
112 113
        runProcess();
    } catch (const std::exception& ex) {
114 115 116
        LOG_FATAL(dctl_logger, DCTL_PROCESS_FAILED)
                  .arg(app_name_).arg(ex.what());
        isc_throw (ProcessRunError,
117
                   "Application process event loop failed: " << ex.what());
118 119
    }

120 121 122
    // All done, so bail out.  Log the event (using a DHCP_DDNS_ prefix
    // for the same reason as used for DHCP_DDNS_STARTING).
    LOG_INFO(dctl_logger, DHCP_DDNS_SHUTDOWN);
123 124 125 126 127
}

void
DControllerBase::parseArgs(int argc, char* argv[])
{
128
    // Iterate over the given command line options. If its a stock option
129 130 131
    // ("s" or "v") handle it here.  If its a valid custom option, then
    // invoke customOption.
    int ch;
132
    opterr = 0;
133
    optind = 1;
134
    std::string opts("dvVc:" + getCustomOpts());
135 136
    while ((ch = getopt(argc, argv, opts.c_str())) != -1) {
        switch (ch) {
137
        case 'd':
138 139 140 141
            // Enables verbose logging.
            verbose_ = true;
            break;

142
        case 'v':
143 144 145 146
            // gather Kea version and throw so main() can catch and return
            // rather than calling exit() here which disrupts gtest.
            isc_throw(VersionMessage, getVersion(false));
            break;
147 148

        case 'V':
149 150 151 152
            // gather Kea version and throw so main() can catch and return
            // rather than calling exit() here which disrupts gtest.
            isc_throw(VersionMessage, getVersion(true));
            break;
153
            
154 155 156 157 158 159 160
        case 'c':
            // config file name
            if (optarg == NULL) {
                isc_throw(InvalidUsage, "configuration file name missing");
            }

            Daemon::init(optarg);
161 162 163 164
            break;

        case '?': {
            // We hit an invalid option.
165
            isc_throw(InvalidUsage, "unsupported option: ["
166 167
                      << static_cast<char>(optopt) << "] "
                      << (!optarg ? "" : optarg));
168 169 170

            break;
            }
171

172 173 174
        default:
            // We hit a valid custom option
            if (!customOption(ch, optarg)) {
175
                // This would be a programmatic error.
176
                isc_throw(InvalidUsage, " Option listed but implemented?: ["
177 178
                          << static_cast<char>(ch) << "] "
                          << (!optarg ? "" : optarg));
179 180 181 182 183 184 185
            }
            break;
        }
    }

    // There was too much information on the command line.
    if (argc > optind) {
186
        isc_throw(InvalidUsage, "extraneous command line information");
187 188 189
    }
}

190
bool
191 192 193 194 195 196 197 198
DControllerBase::customOption(int /* option */, char* /*optarg*/)
{
    // Default implementation returns false.
    return (false);
}

void
DControllerBase::initProcess() {
199
    LOG_DEBUG(dctl_logger, DBGLVL_START_SHUT, DCTL_INIT_PROCESS).arg(app_name_);
200 201

    // Invoke virtual method to instantiate the application process.
202
    try {
203
        process_.reset(createProcess());
204
    } catch (const std::exception& ex) {
205
        isc_throw(DControllerBaseError, std::string("createProcess failed: ")
206
                  + ex.what());
207 208 209 210
    }

    // This is pretty unlikely, but will test for it just to be safe..
    if (!process_) {
211
        isc_throw(DControllerBaseError, "createProcess returned NULL");
212
    }
213

214 215
    // Invoke application's init method (Note this call should throw
    // DProcessBaseError if it fails).
216 217 218
    process_->init();
}

219 220
isc::data::ConstElementPtr
DControllerBase::configFromFile() {
221 222 223 224
    // Rollback any previous staging configuration. For D2, only a
    // logger configuration is used here.
    isc::dhcp::CfgMgr::instance().rollback();
    // Will hold configuration.
225
    isc::data::ConstElementPtr module_config;
226 227
    // Will receive configuration result.
    isc::data::ConstElementPtr answer;
228
    try {
229
        std::string config_file = getConfigFile();
230 231 232 233 234 235 236 237 238 239
        if (config_file.empty()) {
            // Basic sanity check: file name must not be empty.
            isc_throw(BadValue, "JSON configuration file not specified. Please "
                                "use -c command line option.");
        }

        // Read contents of the file and parse it as JSON
        isc::data::ConstElementPtr whole_config =
            isc::data::Element::fromJSONFile(config_file, true);

240 241 242 243
        // Let's configure logging before applying the configuration,
        // so we can log things during configuration process.

        // Temporary storage for logging configuration
244
        isc::dhcp::SrvConfigPtr storage =
245
            isc::dhcp::CfgMgr::instance().getStagingCfg();
246

Tomek Mrugalski's avatar
Tomek Mrugalski committed
247 248
        // Get 'Logging' element from the config and use it to set up
        // logging. If there's no such element, we'll just pass NULL.
249
        Daemon::configureLogger(whole_config->get("Logging"), storage);
250

251 252 253 254 255 256 257
        // Extract derivation-specific portion of the configuration.
        module_config = whole_config->get(getAppName());
        if (!module_config) {
            isc_throw(BadValue, "Config file " << config_file <<
                                " does not include '" <<
                                 getAppName() << "' entry.");
        }
258 259 260 261 262 263 264 265 266 267 268

        answer = updateConfig(module_config);
        int rcode = 0;
        isc::config::parseAnswer(rcode, answer);
        if (!rcode) {
            // Configuration successful, so apply the logging configuration
            // to log4cplus.
            isc::dhcp::CfgMgr::instance().getStagingCfg()->applyLoggingCfg();
            isc::dhcp::CfgMgr::instance().commit();
        }

269
    } catch (const std::exception& ex) {
270 271
        // Rollback logging configuration.
        isc::dhcp::CfgMgr::instance().rollback();
272 273 274 275 276
        // build an error result
        isc::data::ConstElementPtr error =
            isc::config::createAnswer(1,
                std::string("Configuration parsing failed: ") + ex.what());
        return (error);
277 278
    }

279
    return (answer);
280 281
}

282

283 284
void
DControllerBase::runProcess() {
285
    LOG_DEBUG(dctl_logger, DBGLVL_START_SHUT, DCTL_RUN_PROCESS).arg(app_name_);
286 287 288 289 290
    if (!process_) {
        // This should not be possible.
        isc_throw(DControllerBaseError, "Process not initialized");
    }

291 292
    // Invoke the application process's run method. This may throw
    // DProcessBaseError
293 294 295
    process_->run();
}

296
// Instance method for handling new config
297 298
isc::data::ConstElementPtr
DControllerBase::updateConfig(isc::data::ConstElementPtr new_config) {
299
    return (process_->configure(new_config));
300 301 302
}


303
// Instance method for executing commands
304
isc::data::ConstElementPtr
305
DControllerBase::executeCommand(const std::string& command,
306
                            isc::data::ConstElementPtr args) {
307
    // Shutdown is universal.  If its not that, then try it as
308 309 310 311 312
    // an custom command supported by the derivation.  If that
    // doesn't pan out either, than send to it the application
    // as it may be supported there.
    isc::data::ConstElementPtr answer;
    if (command.compare(SHUT_DOWN_COMMAND) == 0) {
313
        answer = shutdownProcess(args);
314 315 316 317
    } else {
        // It wasn't shutdown, so may be a custom controller command.
        int rcode = 0;
        answer = customControllerCommand(command, args);
318
        isc::config::parseAnswer(rcode, answer);
319 320 321
        if (rcode == COMMAND_INVALID)
        {
            // It wasn't controller command, so may be an application command.
322
            answer = process_->command(command, args);
323 324 325 326 327 328 329
        }
    }

    return (answer);
}

isc::data::ConstElementPtr
330
DControllerBase::customControllerCommand(const std::string& command,
331 332 333 334
                                     isc::data::ConstElementPtr /* args */) {

    // Default implementation always returns invalid command.
    return (isc::config::createAnswer(COMMAND_INVALID,
335
                                      "Unrecognized command: " + command));
336 337
}

338
isc::data::ConstElementPtr
339
DControllerBase::shutdownProcess(isc::data::ConstElementPtr args) {
340
    if (process_) {
341
        return (process_->shutdown(args));
342
    }
343

344 345 346 347
    // Not really a failure, but this condition is worth noting. In reality
    // it should be pretty hard to cause this.
    LOG_WARN(dctl_logger, DCTL_NOT_RUNNING).arg(app_name_);
    return (isc::config::createAnswer(0, "Process has not been initialzed."));
348 349
}

350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
void
DControllerBase::initSignalHandling() {
    /// @todo block everything we don't handle

    // Create our signal queue.
    io_signal_queue_.reset(new IOSignalQueue(io_service_));

    // Install the on-receipt handler
    util::SignalSet::setOnReceiptHandler(boost::bind(&DControllerBase::
                                                     osSignalHandler,
                                                     this, _1));
    // Register for the signals we wish to handle.
    signal_set_.reset(new util::SignalSet(SIGHUP,SIGINT,SIGTERM));
}

bool
DControllerBase::osSignalHandler(int signum) {
    // Create a IOSignal to propagate the signal to IOService.
    io_signal_queue_->pushSignal(signum, boost::bind(&DControllerBase::
                                                     ioSignalHandler,
                                                     this, _1));
    return (true);
}

void
DControllerBase::ioSignalHandler(IOSignalId sequence_id) {
    // Pop the signal instance off the queue.  This should make us
    // the only one holding it, so when we leave it should be freed.
    // (note that popSignal will throw if signal is not found, which
    // in turn will caught, logged, and swallowed by IOSignal callback
    // invocation code.)
    IOSignalPtr io_signal = io_signal_queue_->popSignal(sequence_id);

    // Now call virtual signal processing method.
    processSignal(io_signal->getSignum());
}

void
DControllerBase::processSignal(int signum) {
    switch (signum) {
        case SIGHUP:
        {
            LOG_INFO(dctl_logger, DHCP_DDNS_CFG_FILE_RELOAD_SIGNAL_RECVD)
                     .arg(signum).arg(getConfigFile());
            int rcode;
            isc::data::ConstElementPtr comment = isc::config::
                                                 parseAnswer(rcode,
                                                             configFromFile());
            if (rcode != 0) {
                LOG_ERROR(dctl_logger, DHCP_DDNS_CFG_FILE_RELOAD_ERROR)
                          .arg(comment->stringValue());
            }

            break;
        }

        case SIGINT:
        case SIGTERM:
        {
409 410
            LOG_DEBUG(dctl_logger, DBGLVL_START_SHUT,
                      DHCP_DDNS_SHUTDOWN_SIGNAL_RECVD).arg(signum);
411 412 413 414 415 416
            isc::data::ElementPtr arg_set;
            executeCommand(SHUT_DOWN_COMMAND, arg_set);
            break;
        }

        default:
417
            LOG_WARN(dctl_logger, DHCP_DDNS_UNSUPPORTED_SIGNAL).arg(signum);
418 419 420 421
            break;
    }
}

422 423 424 425
void
DControllerBase::usage(const std::string & text)
{
    if (text != "") {
426
        std::cerr << "Usage error: " << text << std::endl;
427 428
    }

429 430 431
    std::cerr << "Usage: " << bin_name_ <<  std::endl
              << "  -c <config file name> : mandatory,"
              <<   " specifies name of configuration file " << std::endl
432 433 434 435
              << "  -d: optional, verbose output " << std::endl
              << "  -v: print version number and exit" << std::endl
              << "  -V: print extended version information and exit"
              << std::endl;
436

437
    // add any derivation specific usage
438
    std::cerr << getUsageText() << std::endl;
439 440 441 442 443 444
}

DControllerBase::~DControllerBase() {
}

}; // namespace isc::d2
445

446
}; // namespace isc
Tomek Mrugalski's avatar
Tomek Mrugalski committed
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462

std::string
isc::dhcp::Daemon::getVersion(bool extended) {
    std::stringstream tmp;

    tmp << VERSION;
    if (extended) {
        tmp << std::endl << EXTENDED_VERSION;

        // @todo print more details (is it Botan or OpenSSL build,
        // with or without MySQL/Postgres? What compilation options were
        // used? etc)
    }

    return (tmp.str());
}