ctrl_dhcp4_srv.cc 42.3 KB
Newer Older
1
// Copyright (C) 2014-2019 Internet Systems Consortium, Inc. ("ISC")
2
//
3 4 5
// 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/.
6 7 8

#include <config.h>
#include <cc/data.h>
9
#include <cc/command_interpreter.h>
10
#include <config/command_mgr.h>
11 12 13
#include <dhcp/libdhcp++.h>
#include <dhcpsrv/cfgmgr.h>
#include <dhcpsrv/cfg_db_access.h>
14 15
#include <dhcp4/ctrl_dhcp4_srv.h>
#include <dhcp4/dhcp4_log.h>
16
#include <dhcp4/dhcp4to6_ipc.h>
17
#include <dhcp4/json_config_parser.h>
18
#include <dhcp4/parser_context.h>
19
#include <hooks/hooks.h>
20
#include <hooks/hooks_manager.h>
21
#include <stats/stats_mgr.h>
Francis Dupont's avatar
Francis Dupont committed
22
#include <cfgrpt/config_report.h>
23
#include <signal.h>
24
#include <sstream>
25

26
using namespace isc::config;
27
using namespace isc::db;
28
using namespace isc::data;
Francis Dupont's avatar
Francis Dupont committed
29
using namespace isc::dhcp;
30
using namespace isc::hooks;
31
using namespace isc::stats;
32 33
using namespace std;

34 35
namespace {

36
/// Structure that holds registered hook indexes.
37
struct CtrlDhcp4Hooks {
38 39 40
    int hooks_index_dhcp4_srv_configured_;

    /// Constructor that registers hook points for the DHCPv4 server.
41
    CtrlDhcp4Hooks() {
42 43
        hooks_index_dhcp4_srv_configured_ = HooksManager::registerHook("dhcp4_srv_configured");
    }
44

45 46 47 48 49 50
};

// Declare a Hooks object. As this is outside any function or method, it
// will be instantiated (and the constructor run) when the module is loaded.
// As a result, the hook indexes will be defined before any method in this
// module is called.
51
CtrlDhcp4Hooks Hooks;
52

53 54 55 56 57 58 59 60 61 62 63 64
/// @brief Signals handler for DHCPv4 server.
///
/// This signal handler handles the following signals received by the DHCPv4
/// server process:
/// - SIGHUP - triggers server's dynamic reconfiguration.
/// - SIGTERM - triggers server's shut down.
/// - SIGINT - triggers server's shut down.
///
/// @param signo Signal number received.
void signalHandler(int signo) {
    // SIGHUP signals a request to reconfigure the server.
    if (signo == SIGHUP) {
Francis Dupont's avatar
Francis Dupont committed
65 66
        ControlledDhcpv4Srv::processCommand("config-reload",
                                            ConstElementPtr());
67
    } else if ((signo == SIGTERM) || (signo == SIGINT)) {
Francis Dupont's avatar
Francis Dupont committed
68 69
        ControlledDhcpv4Srv::processCommand("shutdown",
                                            ConstElementPtr());
70 71 72 73 74
    }
}

}

75 76 77 78 79
namespace isc {
namespace dhcp {

ControlledDhcpv4Srv* ControlledDhcpv4Srv::server_ = NULL;

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 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 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
void
ControlledDhcpv4Srv::init(const std::string& file_name) {
    // Configure the server using JSON file.
    ConstElementPtr result = loadConfigFile(file_name);
    int rcode;
    ConstElementPtr comment = isc::config::parseAnswer(rcode, result);
    if (rcode != 0) {
        string reason = comment ? comment->stringValue() :
            "no details available";
        isc_throw(isc::BadValue, reason);
    }

    // We don't need to call openActiveSockets() or startD2() as these
    // methods are called in processConfig() which is called by
    // processCommand("config-set", ...)

    // Set signal handlers. When the SIGHUP is received by the process
    // the server reconfiguration will be triggered. When SIGTERM or
    // SIGINT will be received, the server will start shutting down.
    signal_set_.reset(new isc::util::SignalSet(SIGINT, SIGHUP, SIGTERM));
    // Set the pointer to the handler function.
    signal_handler_ = signalHandler;
}

void ControlledDhcpv4Srv::cleanup() {
    // Nothing to do here. No need to disconnect from anything.
}

/// @brief Configure DHCPv4 server using the configuration file specified.
///
/// This function is used to both configure the DHCP server on its startup
/// and dynamically reconfigure the server when SIGHUP signal is received.
///
/// It fetches DHCPv4 server's configuration from the 'Dhcp4' section of
/// the JSON configuration file.
///
/// @param file_name Configuration file location.
/// @return status of the command
ConstElementPtr
ControlledDhcpv4Srv::loadConfigFile(const std::string& file_name) {
    // This is a configuration backend implementation that reads the
    // configuration from a JSON file.

    isc::data::ConstElementPtr json;
    isc::data::ConstElementPtr dhcp4;
    isc::data::ConstElementPtr logger;
    isc::data::ConstElementPtr result;

    // Basic sanity check: file name must not be empty.
    try {
        if (file_name.empty()) {
            // Basic sanity check: file name must not be empty.
            isc_throw(isc::BadValue, "JSON configuration file not specified."
                      " Please use -c command line option.");
        }

        // Read contents of the file and parse it as JSON
        Parser4Context parser;
        json = parser.parseFile(file_name, Parser4Context::PARSER_DHCP4);
        if (!json) {
            isc_throw(isc::BadValue, "no configuration found");
        }

        // Let's do sanity check before we call json->get() which
        // works only for map.
        if (json->getType() != isc::data::Element::map) {
            isc_throw(isc::BadValue, "Configuration file is expected to be "
                      "a map, i.e., start with { and end with } and contain "
                      "at least an entry called 'Dhcp4' that itself is a map. "
                      << file_name
                      << " is a valid JSON, but its top element is not a map."
                      " Did you forget to add { } around your configuration?");
        }

        // Use parsed JSON structures to configure the server
        result = ControlledDhcpv4Srv::processCommand("config-set", json);
        if (!result) {
            // Undetermined status of the configuration. This should never
            // happen, but as the configureDhcp4Server returns a pointer, it is
            // theoretically possible that it will return NULL.
            isc_throw(isc::BadValue, "undefined result of "
                      "processCommand(\"config-set\", json)");
        }

        // Now check is the returned result is successful (rcode=0) or not
        // (see @ref isc::config::parseAnswer).
        int rcode;
        ConstElementPtr comment = isc::config::parseAnswer(rcode, result);
        if (rcode != 0) {
            string reason = comment ? comment->stringValue() :
                "no details available";
            isc_throw(isc::BadValue, reason);
        }
    }  catch (const std::exception& ex) {
        // If configuration failed at any stage, we drop the staging
        // configuration and continue to use the previous one.
        CfgMgr::instance().rollback();

        LOG_ERROR(dhcp4_logger, DHCP4_CONFIG_LOAD_FAIL)
            .arg(file_name).arg(ex.what());
        isc_throw(isc::BadValue, "configuration error using file '"
                  << file_name << "': " << ex.what());
    }

    return (result);
}


188 189
ConstElementPtr
ControlledDhcpv4Srv::commandShutdownHandler(const string&, ConstElementPtr) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
190 191
    if (ControlledDhcpv4Srv::getInstance()) {
        ControlledDhcpv4Srv::getInstance()->shutdown();
192 193 194 195 196 197 198
    } else {
        LOG_WARN(dhcp4_logger, DHCP4_NOT_RUNNING);
        ConstElementPtr answer = isc::config::createAnswer(1,
                                              "Shutdown failure.");
        return (answer);
    }
    ConstElementPtr answer = isc::config::createAnswer(0, "Shutting down.");
199
    return (answer);
200 201 202 203 204 205 206
}

ConstElementPtr
ControlledDhcpv4Srv::commandLibReloadHandler(const string&, ConstElementPtr) {

    /// @todo delete any stored CalloutHandles referring to the old libraries
    /// Get list of currently loaded libraries and reload them.
207
    HookLibsCollection loaded = HooksManager::getLibraryInfo();
208 209 210 211 212 213 214 215 216 217 218 219 220 221
    bool status = HooksManager::loadLibraries(loaded);
    if (!status) {
        LOG_ERROR(dhcp4_logger, DHCP4_HOOKS_LIBS_RELOAD_FAIL);
        ConstElementPtr answer = isc::config::createAnswer(1,
                                 "Failed to reload hooks libraries.");
        return (answer);
    }
    ConstElementPtr answer = isc::config::createAnswer(0,
                             "Hooks libraries successfully reloaded.");
    return (answer);
}

ConstElementPtr
ControlledDhcpv4Srv::commandConfigReloadHandler(const string&,
222 223 224 225 226 227 228 229 230 231 232 233 234 235
                                                ConstElementPtr /*args*/) {

    // Get configuration file name.
    std::string file = ControlledDhcpv4Srv::getInstance()->getConfigFile();
    try {
        LOG_INFO(dhcp4_logger, DHCP4_DYNAMIC_RECONFIGURATION).arg(file);
        return (loadConfigFile(file));
    } catch (const std::exception& ex) {
        // Log the unsuccessful reconfiguration. The reason for failure
        // should be already logged. Don't rethrow an exception so as
        // the server keeps working.
        LOG_ERROR(dhcp4_logger, DHCP4_DYNAMIC_RECONFIGURATION_FAIL)
            .arg(file);
        return (createAnswer(CONTROL_RESULT_ERROR,
236
                             "Config reload failed: " + string(ex.what())));
237
    }
238 239
}

240
ConstElementPtr
241
ControlledDhcpv4Srv::commandConfigGetHandler(const string&,
242 243 244 245 246 247
                                             ConstElementPtr /*args*/) {
    ConstElementPtr config = CfgMgr::instance().getCurrentCfg()->toElement();

    return (createAnswer(0, config));
}

248
ConstElementPtr
249 250
ControlledDhcpv4Srv::commandConfigWriteHandler(const string&,
                                               ConstElementPtr args) {
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
    string filename;

    if (args) {
        if (args->getType() != Element::map) {
            return (createAnswer(CONTROL_RESULT_ERROR, "Argument must be a map"));
        }
        ConstElementPtr filename_param = args->get("filename");
        if (filename_param) {
            if (filename_param->getType() != Element::string) {
                return (createAnswer(CONTROL_RESULT_ERROR,
                                     "passed parameter 'filename' is not a string"));
            }
            filename = filename_param->stringValue();
        }
    }

    if (filename.empty()) {
        // filename parameter was not specified, so let's use whatever we remember
        filename = getConfigFile();
    }

272 273 274
    if (filename.empty()) {
        return (createAnswer(CONTROL_RESULT_ERROR, "Unable to determine filename."
                             "Please specify filename explicitly."));
275 276
    }

277
    // Ok, it's time to write the file.
278 279
    size_t size = 0;
    try {
280 281
        ConstElementPtr cfg = CfgMgr::instance().getCurrentCfg()->toElement();
        size = writeConfigFile(filename, cfg);
282 283 284 285 286 287 288 289 290
    } catch (const isc::Exception& ex) {
        return (createAnswer(CONTROL_RESULT_ERROR, string("Error during write-config:")
                             + ex.what()));
    }
    if (size == 0) {
        return (createAnswer(CONTROL_RESULT_ERROR, "Error writing configuration to "
                             + filename));
    }

291
    // Ok, it's time to return the successful response.
292 293 294 295 296 297 298 299
    ElementPtr params = Element::createMap();
    params->set("size", Element::create(static_cast<long long>(size)));
    params->set("filename", Element::create(filename));

    return (createAnswer(CONTROL_RESULT_SUCCESS, "Configuration written to "
                         + filename + " successful", params));
}

300
ConstElementPtr
301
ControlledDhcpv4Srv::commandConfigSetHandler(const string&,
302
                                             ConstElementPtr args) {
303
    const int status_code = CONTROL_RESULT_ERROR; // 1 indicates an error
304 305 306 307
    ConstElementPtr dhcp4;
    string message;

    // Command arguments are expected to be:
308 309
    // { "Dhcp4": { ... } }
    // The Logging component is supported by backward compatiblity.
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
    if (!args) {
        message = "Missing mandatory 'arguments' parameter.";
    } else {
        dhcp4 = args->get("Dhcp4");
        if (!dhcp4) {
            message = "Missing mandatory 'Dhcp4' parameter.";
        } else if (dhcp4->getType() != Element::map) {
            message = "'Dhcp4' parameter expected to be a map.";
        }
    }

    if (!message.empty()) {
        // Something is amiss with arguments, return a failure response.
        ConstElementPtr result = isc::config::createAnswer(status_code,
                                                           message);
        return (result);
    }

328 329 330 331 332
    // We are starting the configuration process so we should remove any
    // staging configuration that has been created during previous
    // configuration attempts.
    CfgMgr::instance().rollback();

333 334
    // Check deprecated, obsolete or unknown (aka unsupported) objects.
    list<string> unsupported;
335 336 337 338 339
    for (auto obj : args->mapValue()) {
        const string& obj_name = obj.first;
        if ((obj_name == "Dhcp4") || (obj_name == "Logging")) {
            continue;
        }
340
        unsupported.push_back(obj_name);
341
    }
342

343 344
    // Relocate Logging: if there is a global Logging object takes its
    // loggers entry, move the entry to Dhcp4 and remove now empty Logging.
345 346 347 348 349 350 351
    Daemon::relocateLogging(args, "Dhcp4");

    // Parse the logger configuration explicitly into the staging config.
    // Note this does not alter the current loggers, they remain in
    // effect until we apply the logging config below.  If no logging
    // is supplied logging will revert to default logging.
    Daemon::configureLogger(dhcp4, CfgMgr::instance().getStagingCfg());
352

353
    // Let's apply the new logging. We do it early, so we'll be able to print
354
    // out what exactly is wrong with the new config in case of problems.
355 356
    CfgMgr::instance().getStagingCfg()->applyLoggingCfg();

357 358 359 360
    // Log unsupported objects.
    if (!unsupported.empty()) {
        for (auto name : unsupported) {
            LOG_ERROR(dhcp4_logger, DHCP4_CONFIG_UNSUPPORTED_OBJECT).arg(name);
361
        }
362 363

        // Will return an error in a future version.
364
    }
365

366
    // Now we configure the server proper.
367 368 369 370 371 372 373 374 375 376 377 378
    ConstElementPtr result = processConfig(dhcp4);

    // If the configuration parsed successfully, apply the new logger
    // configuration and the commit the new configuration.  We apply
    // the logging first in case there's a configuration failure.
    int rcode = 0;
    isc::config::parseAnswer(rcode, result);
    if (rcode == 0) {
        CfgMgr::instance().getStagingCfg()->applyLoggingCfg();

        // Use new configuration.
        CfgMgr::instance().commit();
379 380 381 382 383
    } else {
        // Ok, we applied the logging from the upcoming configuration, but
        // there were problems with the config. As such, we need to back off
        // and revert to the previous logging configuration.
        CfgMgr::instance().getCurrentCfg()->applyLoggingCfg();
384 385 386
    }

    return (result);
387 388
}

Francis Dupont's avatar
Francis Dupont committed
389 390 391
ConstElementPtr
ControlledDhcpv4Srv::commandConfigTestHandler(const string&,
                                              ConstElementPtr args) {
392
    const int status_code = CONTROL_RESULT_ERROR; // 1 indicates an error
Francis Dupont's avatar
Francis Dupont committed
393 394 395 396
    ConstElementPtr dhcp4;
    string message;

    // Command arguments are expected to be:
397 398
    // { "Dhcp4": { ... } }
    // The Logging component is supported by backward compatiblity.
Francis Dupont's avatar
Francis Dupont committed
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
    if (!args) {
        message = "Missing mandatory 'arguments' parameter.";
    } else {
        dhcp4 = args->get("Dhcp4");
        if (!dhcp4) {
            message = "Missing mandatory 'Dhcp4' parameter.";
        } else if (dhcp4->getType() != Element::map) {
            message = "'Dhcp4' parameter expected to be a map.";
        }
    }

    if (!message.empty()) {
        // Something is amiss with arguments, return a failure response.
        ConstElementPtr result = isc::config::createAnswer(status_code,
                                                           message);
        return (result);
    }

    // We are starting the configuration process so we should remove any
    // staging configuration that has been created during previous
    // configuration attempts.
    CfgMgr::instance().rollback();

422 423 424 425 426 427 428
    // Check obsolete objects.

    // Relocate Logging. Note this allows to check the loggers configuration.
    Daemon::relocateLogging(args, "Dhcp4");

    // Log obsolete objects and return an error.

Francis Dupont's avatar
Francis Dupont committed
429 430 431 432
    // Now we check the server proper.
    return (checkConfig(dhcp4));
}

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
ConstElementPtr
ControlledDhcpv4Srv::commandDhcpDisableHandler(const std::string&,
                                               ConstElementPtr args) {
    std::ostringstream message;
    int64_t max_period = 0;

    // Parse arguments to see if the 'max-period' parameter has been specified.
    if (args) {
        // Arguments must be a map.
        if (args->getType() != Element::map) {
            message << "arguments for the 'dhcp-disable' command must be a map";

        } else {
            ConstElementPtr max_period_element = args->get("max-period");
            // max-period is optional.
            if (max_period_element) {
                // It must be an integer, if specified.
                if (max_period_element->getType() != Element::integer) {
                    message << "'max-period' argument must be a number";

                } else {
                    // It must be positive integer.
                    max_period = max_period_element->intValue();
                    if (max_period <= 0) {
                        message << "'max-period' must be positive integer";
                    }

                    // The user specified that the DHCP service should resume not
                    // later than in max-period seconds. If the 'dhcp-enable' command
                    // is not sent, the DHCP service will resume automatically.
463
                    network_state_->delayedEnableAll(static_cast<unsigned>(max_period));
464 465 466 467 468 469 470
                }
            }
        }
    }

    // No error occurred, so let's disable the service.
    if (message.tellp() == 0) {
471
        network_state_->disableService();
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486

        message << "DHCPv4 service disabled";
        if (max_period > 0) {
            message << " for " << max_period << " seconds";
        }
        // Success.
        return (config::createAnswer(CONTROL_RESULT_SUCCESS, message.str()));
    }

    // Failure.
    return (config::createAnswer(CONTROL_RESULT_ERROR, message.str()));
}

ConstElementPtr
ControlledDhcpv4Srv::commandDhcpEnableHandler(const std::string&, ConstElementPtr) {
487
    network_state_->enableService();
488 489 490
    return (config::createAnswer(CONTROL_RESULT_SUCCESS, "DHCP service successfully enabled"));
}

Francis Dupont's avatar
Francis Dupont committed
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
ConstElementPtr
ControlledDhcpv4Srv::commandVersionGetHandler(const string&, ConstElementPtr) {
    ElementPtr extended = Element::create(Dhcpv4Srv::getVersion(true));
    ElementPtr arguments = Element::createMap();
    arguments->set("extended", extended);
    ConstElementPtr answer = isc::config::createAnswer(0,
                                Dhcpv4Srv::getVersion(false),
                                arguments);
    return (answer);
}

ConstElementPtr
ControlledDhcpv4Srv::commandBuildReportHandler(const string&,
                                               ConstElementPtr) {
    ConstElementPtr answer =
        isc::config::createAnswer(0, isc::detail::getConfigReport());
    return (answer);
}

510
ConstElementPtr
511
ControlledDhcpv4Srv::commandLeasesReclaimHandler(const string&,
Francis Dupont's avatar
Francis Dupont committed
512
                                                 ConstElementPtr args) {
513
    int status_code = CONTROL_RESULT_ERROR;
Francis Dupont's avatar
Francis Dupont committed
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
    string message;

    // args must be { "remove": <bool> }
    if (!args) {
        message = "Missing mandatory 'remove' parameter.";
    } else {
        ConstElementPtr remove_name = args->get("remove");
        if (!remove_name) {
            message = "Missing mandatory 'remove' parameter.";
        } else if (remove_name->getType() != Element::boolean) {
            message = "'remove' parameter expected to be a boolean.";
        } else {
            bool remove_lease = remove_name->boolValue();
            server_->alloc_engine_->reclaimExpiredLeases4(0, 0, remove_lease);
            status_code = 0;
            message = "Reclamation of expired leases is complete.";
        }
    }
    ConstElementPtr answer = isc::config::createAnswer(status_code, message);
533 534 535
    return (answer);
}

536 537 538 539 540 541 542 543 544 545 546
ConstElementPtr
ControlledDhcpv4Srv::commandServerTagGetHandler(const std::string&,
                                                ConstElementPtr) {
    const std::string& tag =
        CfgMgr::instance().getCurrentCfg()->getServerTag();
    ElementPtr response = Element::createMap();
    response->set("server-tag", Element::create(tag));

    return (createAnswer(CONTROL_RESULT_SUCCESS, response));
}

547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
ConstElementPtr
ControlledDhcpv4Srv::commandServerUpdateHandler(const std::string&,
                                                      ConstElementPtr) {
    auto ctl_info = CfgMgr::instance().getCurrentCfg()->getConfigControlInfo();
    if (!ctl_info) {
        return (createAnswer(CONTROL_RESULT_EMPTY, "No config backend."));
    }

    // Reschedule the periodic CB fetch.
    if (TimerMgr::instance()->isTimerRegistered("Dhcp4CBFetchTimer")) {
        TimerMgr::instance()->cancel("Dhcp4CBFetchTimer");
        TimerMgr::instance()->setup("Dhcp4CBFetchTimer");
    }

    // Code from cbFetchUpdates.
    try {
        auto srv_cfg = CfgMgr::instance().getStagingCfg();
        auto mode = CBControlDHCPv4::FetchMode::FETCH_UPDATE;
        server_->getCBControl()->databaseConfigFetch(srv_cfg, mode);
    } catch (const std::exception& ex) {
        LOG_ERROR(dhcp4_logger, DHCP4_CB_FETCH_UPDATES_FAIL)
            .arg(ex.what());
        return (createAnswer(CONTROL_RESULT_ERROR,
                             "Server update failed: " + string(ex.what())));
    }
    return (createAnswer(CONTROL_RESULT_SUCCESS, "Server update successful."));
}

575 576 577
ConstElementPtr
ControlledDhcpv4Srv::processCommand(const string& command,
                                    ConstElementPtr args) {
Francis Dupont's avatar
Francis Dupont committed
578
    string txt = args ? args->str() : "(none)";
579

580
    LOG_DEBUG(dhcp4_logger, DBG_DHCP4_COMMAND, DHCP4_COMMAND_RECEIVED)
581
              .arg(command).arg(txt);
582 583 584 585 586

    ControlledDhcpv4Srv* srv = ControlledDhcpv4Srv::getInstance();

    if (!srv) {
        ConstElementPtr no_srv = isc::config::createAnswer(1,
Tomek Mrugalski's avatar
Tomek Mrugalski committed
587
          "Server object not initialized, so can't process command '" +
588
          command + "', arguments: '" + txt + "'.");
589 590 591 592 593 594 595 596 597 598 599 600 601
        return (no_srv);
    }

    try {
        if (command == "shutdown") {
            return (srv->commandShutdownHandler(command, args));

        } else if (command == "libreload") {
            return (srv->commandLibReloadHandler(command, args));

        } else if (command == "config-reload") {
            return (srv->commandConfigReloadHandler(command, args));

602
        } else if (command == "config-set") {
603
            return (srv->commandConfigSetHandler(command, args));
604

605 606
        } else if (command == "config-get") {
            return (srv->commandConfigGetHandler(command, args));
607

Francis Dupont's avatar
Francis Dupont committed
608 609 610
        } else if (command == "config-test") {
            return (srv->commandConfigTestHandler(command, args));

611 612 613 614 615 616
        } else if (command == "dhcp-disable") {
            return (srv->commandDhcpDisableHandler(command, args));

        } else if (command == "dhcp-enable") {
            return (srv->commandDhcpEnableHandler(command, args));

Francis Dupont's avatar
Francis Dupont committed
617 618 619 620 621 622
        } else if (command == "version-get") {
            return (srv->commandVersionGetHandler(command, args));

        } else if (command == "build-report") {
            return (srv->commandBuildReportHandler(command, args));

Francis Dupont's avatar
Francis Dupont committed
623 624
        } else if (command == "leases-reclaim") {
            return (srv->commandLeasesReclaimHandler(command, args));
625 626 627 628

        } else if (command == "config-write") {
            return (srv->commandConfigWriteHandler(command, args));

629 630 631
        } else if (command == "server-tag-get") {
            return (srv->commandServerTagGetHandler(command, args));

632 633 634
        } else if (command == "server-update") {
            return (srv->commandServerUpdateHandler(command, args));

635 636 637 638 639 640
        }
        ConstElementPtr answer = isc::config::createAnswer(1,
                                 "Unrecognized command:" + command);
        return (answer);
    } catch (const Exception& ex) {
        return (isc::config::createAnswer(1, "Error while processing command '"
641
                                          + command + "':" + ex.what() +
642
                                          ", params: '" + txt + "'"));
643 644 645 646 647
    }
}

isc::data::ConstElementPtr
ControlledDhcpv4Srv::processConfig(isc::data::ConstElementPtr config) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
648 649 650 651

    LOG_DEBUG(dhcp4_logger, DBG_DHCP4_COMMAND, DHCP4_CONFIG_RECEIVED)
              .arg(config->str());

652 653
    ControlledDhcpv4Srv* srv = ControlledDhcpv4Srv::getInstance();

Tomek Mrugalski's avatar
Tomek Mrugalski committed
654 655 656
    // Single stream instance used in all error clauses
    std::ostringstream err;

657
    if (!srv) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
658 659
        err << "Server object not initialized, can't process config.";
        return (isc::config::createAnswer(1, err.str()));
660
    }
661

662
    ConstElementPtr answer = configureDhcp4Server(*srv, config);
663

664 665 666 667 668 669 670 671 672
    // Check that configuration was successful. If not, do not reopen sockets
    // and don't bother with DDNS stuff.
    try {
        int rcode = 0;
        isc::config::parseAnswer(rcode, answer);
        if (rcode != 0) {
            return (answer);
        }
    } catch (const std::exception& ex) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
673 674
        err << "Failed to process configuration:" << ex.what();
        return (isc::config::createAnswer(1, err.str()));
675 676
    }

677 678
    // Re-open lease and host database with new parameters.
    try {
679 680
        DatabaseConnection::db_lost_callback =
            boost::bind(&ControlledDhcpv4Srv::dbLostCallback, srv, _1);
681 682
        CfgDbAccessPtr cfg_db = CfgMgr::instance().getStagingCfg()->getCfgDbAccess();
        cfg_db->setAppendedParameters("universe=4");
683
        cfg_db->createManagers();
684 685 686 687 688
    } catch (const std::exception& ex) {
        err << "Unable to open database: " << ex.what();
        return (isc::config::createAnswer(1, err.str()));
    }

689 690 691 692
    // Server will start DDNS communications if its enabled.
    try {
        srv->startD2();
    } catch (const std::exception& ex) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
693 694
        err << "Error starting DHCP_DDNS client after server reconfiguration: "
            << ex.what();
695 696 697
        return (isc::config::createAnswer(1, err.str()));
    }

698 699
    // Setup DHCPv4-over-DHCPv6 IPC
    try {
700
        Dhcp4to6Ipc::instance().open();
701 702 703 704 705 706 707
    } catch (const std::exception& ex) {
        std::ostringstream err;
        err << "error starting DHCPv4-over-DHCPv6 IPC "
               " after server reconfiguration: " << ex.what();
        return (isc::config::createAnswer(1, err.str()));
    }

708
    // Configure DHCP packet queueing
709
    try {
710
        data::ConstElementPtr qc;
711
        qc  = CfgMgr::instance().getStagingCfg()->getDHCPQueueControl();
712
        if (IfaceMgr::instance().configureDHCPPacketQueue(AF_INET, qc)) {
713
            LOG_INFO(dhcp4_logger, DHCP4_CONFIG_PACKET_QUEUE)
714
                      .arg(IfaceMgr::instance().getPacketQueue4()->getInfoStr());
715 716
        }

717 718 719 720 721 722
    } catch (const std::exception& ex) {
        err << "Error setting packet queue controls after server reconfiguration: "
            << ex.what();
        return (isc::config::createAnswer(1, err.str()));
    }

723
    // Configuration may change active interfaces. Therefore, we have to reopen
724 725 726 727 728 729
    // sockets according to new configuration. It is possible that this
    // operation will fail for some interfaces but the openSockets function
    // guards against exceptions and invokes a callback function to
    // log warnings. Since we allow that this fails for some interfaces there
    // is no need to rollback configuration if socket fails to open on any
    // of the interfaces.
730
    CfgMgr::instance().getStagingCfg()->getCfgIface()->
731 732
        openSockets(AF_INET, srv->getServerPort(),
                    getInstance()->useBroadcast());
733

734 735 736 737 738 739 740 741 742 743 744 745 746 747
    // Install the timers for handling leases reclamation.
    try {
        CfgMgr::instance().getStagingCfg()->getCfgExpiration()->
            setupTimers(&ControlledDhcpv4Srv::reclaimExpiredLeases,
                        &ControlledDhcpv4Srv::deleteExpiredReclaimedLeases,
                        server_);

    } catch (const std::exception& ex) {
        err << "unable to setup timers for periodically running the"
            " reclamation of the expired leases: "
            << ex.what() << ".";
        return (isc::config::createAnswer(1, err.str()));
    }

748 749 750 751 752 753
    auto ctl_info = CfgMgr::instance().getStagingCfg()->getConfigControlInfo();
    if (ctl_info) {
        long fetch_time = static_cast<long>(ctl_info->getConfigFetchWaitTime());
        // Only schedule the CB fetch timer if the fetch wait time is greater
        // than 0.
        if (fetch_time > 0) {
754 755 756 757 758
            // When we run unit tests, we want to use milliseconds unit for the
            // specified interval. Otherwise, we use seconds. Note that using
            // milliseconds as a unit in unit tests prevents us from waiting 1
            // second on more before the timer goes off. Instead, we wait one
            // millisecond which significantly reduces the test time.
759
            if (!server_->inTestMode()) {
760 761 762
                fetch_time = 1000 * fetch_time;
            }

763
            boost::shared_ptr<unsigned> failure_count(new unsigned(0));
764 765 766
            TimerMgr::instance()->
                registerTimer("Dhcp4CBFetchTimer",
                              boost::bind(&ControlledDhcpv4Srv::cbFetchUpdates,
767 768
                                          server_, CfgMgr::instance().getStagingCfg(),
                                          failure_count),
769 770 771 772 773 774
                              fetch_time,
                              asiolink::IntervalTimer::ONE_SHOT);
            TimerMgr::instance()->setup("Dhcp4CBFetchTimer");
        }
    }

775 776 777 778
    // Finally, we can commit runtime option definitions in libdhcp++. This is
    // exception free.
    LibDHCP::commitRuntimeOptionDefs();

779
    // This hook point notifies hooks libraries that the configuration of the
780 781 782 783
    // DHCPv4 server has completed. It provides the hook library with the pointer
    // to the common IO service object, new server configuration in the JSON
    // format and with the pointer to the configuration storage where the
    // parsed configuration is stored.
784 785 786
    if (HooksManager::calloutsPresent(Hooks.hooks_index_dhcp4_srv_configured_)) {
        CalloutHandlePtr callout_handle = HooksManager::createCalloutHandle();

787
        callout_handle->setArgument("io_context", srv->getIOService());
788
        callout_handle->setArgument("network_state", srv->getNetworkState());
789 790
        callout_handle->setArgument("json_config", config);
        callout_handle->setArgument("server_config", CfgMgr::instance().getStagingCfg());
791 792 793

        HooksManager::callCallouts(Hooks.hooks_index_dhcp4_srv_configured_,
                                   *callout_handle);
794 795 796

        // Ignore status code as none of them would have an effect on further
        // operation.
797 798
    }

799 800 801
    return (answer);
}

Francis Dupont's avatar
Francis Dupont committed
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
isc::data::ConstElementPtr
ControlledDhcpv4Srv::checkConfig(isc::data::ConstElementPtr config) {

    LOG_DEBUG(dhcp4_logger, DBG_DHCP4_COMMAND, DHCP4_CONFIG_RECEIVED)
              .arg(config->str());

    ControlledDhcpv4Srv* srv = ControlledDhcpv4Srv::getInstance();

    // Single stream instance used in all error clauses
    std::ostringstream err;

    if (!srv) {
        err << "Server object not initialized, can't process config.";
        return (isc::config::createAnswer(1, err.str()));
    }

    return (configureDhcp4Server(*srv, config, true));
}

821 822 823 824
ControlledDhcpv4Srv::ControlledDhcpv4Srv(uint16_t server_port /*= DHCP4_SERVER_PORT*/,
                                         uint16_t client_port /*= 0*/)
    : Dhcpv4Srv(server_port, client_port), io_service_(),
      timer_mgr_(TimerMgr::instance()) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
825
    if (getInstance()) {
826 827 828
        isc_throw(InvalidOperation,
                  "There is another Dhcpv4Srv instance already.");
    }
Tomek Mrugalski's avatar
Tomek Mrugalski committed
829
    server_ = this; // remember this instance for later use in handlers
830

831
    // TimerMgr uses IO service to run asynchronous timers.
832
    TimerMgr::instance()->setIOService(getIOService());
833 834

    // CommandMgr uses IO service to run asynchronous socket operations.
835
    CommandMgr::instance().setIOService(getIOService());
836

837 838
    // These are the commands always supported by the DHCPv4 server.
    // Please keep the list in alphabetic order.
Francis Dupont's avatar
Francis Dupont committed
839 840 841
    CommandMgr::instance().registerCommand("build-report",
        boost::bind(&ControlledDhcpv4Srv::commandBuildReportHandler, this, _1, _2));

842 843
    CommandMgr::instance().registerCommand("config-get",
        boost::bind(&ControlledDhcpv4Srv::commandConfigGetHandler, this, _1, _2));
844

845 846 847 848
    CommandMgr::instance().registerCommand("config-reload",
        boost::bind(&ControlledDhcpv4Srv::commandConfigReloadHandler, this, _1, _2));

    CommandMgr::instance().registerCommand("config-set",
849
        boost::bind(&ControlledDhcpv4Srv::commandConfigSetHandler, this, _1, _2));
850

Francis Dupont's avatar
Francis Dupont committed
851 852 853
    CommandMgr::instance().registerCommand("config-test",
        boost::bind(&ControlledDhcpv4Srv::commandConfigTestHandler, this, _1, _2));

854 855 856
    CommandMgr::instance().registerCommand("config-write",
        boost::bind(&ControlledDhcpv4Srv::commandConfigWriteHandler, this, _1, _2));

857 858 859 860 861 862
    CommandMgr::instance().registerCommand("dhcp-enable",
        boost::bind(&ControlledDhcpv4Srv::commandDhcpEnableHandler, this, _1, _2));

    CommandMgr::instance().registerCommand("dhcp-disable",
        boost::bind(&ControlledDhcpv4Srv::commandDhcpDisableHandler, this, _1, _2));

863 864
    CommandMgr::instance().registerCommand("libreload",
        boost::bind(&ControlledDhcpv4Srv::commandLibReloadHandler, this, _1, _2));
865

866 867 868
    CommandMgr::instance().registerCommand("leases-reclaim",
        boost::bind(&ControlledDhcpv4Srv::commandLeasesReclaimHandler, this, _1, _2));

869 870 871
    CommandMgr::instance().registerCommand("server-tag-get",
        boost::bind(&ControlledDhcpv4Srv::commandServerTagGetHandler, this, _1, _2));

872 873 874
    CommandMgr::instance().registerCommand("server-update",
        boost::bind(&ControlledDhcpv4Srv::commandServerUpdateHandler, this, _1, _2));

875 876
    CommandMgr::instance().registerCommand("shutdown",
        boost::bind(&ControlledDhcpv4Srv::commandShutdownHandler, this, _1, _2));
877

Francis Dupont's avatar
Francis Dupont committed
878 879 880
    CommandMgr::instance().registerCommand("version-get",
        boost::bind(&ControlledDhcpv4Srv::commandVersionGetHandler, this, _1, _2));

881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
    // Register statistic related commands
    CommandMgr::instance().registerCommand("statistic-get",
        boost::bind(&StatsMgr::statisticGetHandler, _1, _2));

    CommandMgr::instance().registerCommand("statistic-reset",
        boost::bind(&StatsMgr::statisticResetHandler, _1, _2));

    CommandMgr::instance().registerCommand("statistic-remove",
        boost::bind(&StatsMgr::statisticRemoveHandler, _1, _2));

    CommandMgr::instance().registerCommand("statistic-get-all",
        boost::bind(&StatsMgr::statisticGetAllHandler, _1, _2));

    CommandMgr::instance().registerCommand("statistic-reset-all",
        boost::bind(&StatsMgr::statisticResetAllHandler, _1, _2));

    CommandMgr::instance().registerCommand("statistic-remove-all",
        boost::bind(&StatsMgr::statisticRemoveAllHandler, _1, _2));
899

Razvan Becheriu's avatar
Razvan Becheriu committed
900
    CommandMgr::instance().registerCommand("statistic-sample-age-set",
901 902
        boost::bind(&StatsMgr::statisticSetMaxSampleAgeHandler, _1, _2));

Razvan Becheriu's avatar
Razvan Becheriu committed
903
    CommandMgr::instance().registerCommand("statistic-sample-age-set-all",
904 905
        boost::bind(&StatsMgr::statisticSetMaxSampleAgeAllHandler, _1, _2));

Razvan Becheriu's avatar
Razvan Becheriu committed
906 907 908 909
    CommandMgr::instance().registerCommand("statistic-sample-count-set",
        boost::bind(&StatsMgr::statisticSetMaxSampleCountHandler, _1, _2));

    CommandMgr::instance().registerCommand("statistic-sample-count-set-all",
910
        boost::bind(&StatsMgr::statisticSetMaxSampleCountAllHandler, _1, _2));
911 912 913 914 915 916 917 918
}

void ControlledDhcpv4Srv::shutdown() {
    io_service_.stop(); // Stop ASIO transmissions
    Dhcpv4Srv::shutdown(); // Initiate DHCPv4 shutdown procedure.
}

ControlledDhcpv4Srv::~ControlledDhcpv4Srv() {
919 920 921
    try {
        cleanup();

922 923 924 925
        // The closure captures either a shared pointer (memory leak)
        // or a raw pointer (pointing to a deleted object).
        DatabaseConnection::db_lost_callback = 0;

926
        timer_mgr_->unregisterTimers();
927 928 929 930

        // Close the command socket (if it exists).
        CommandMgr::instance().closeCommandSocket();

931
        // Deregister any registered commands (please keep in alphabetic order)
Francis Dupont's avatar
Francis Dupont committed
932
        CommandMgr::instance().deregisterCommand("build-report");
933
        CommandMgr::instance().deregisterCommand("config-get");
934
        CommandMgr::instance().deregisterCommand("config-reload");
935
        CommandMgr::instance().deregisterCommand("config-set");
Francis Dupont's avatar
Francis Dupont committed
936
        CommandMgr::instance().deregisterCommand("config-test");
937
        CommandMgr::instance().deregisterCommand("config-write");
938 939
        CommandMgr::instance().deregisterCommand("dhcp-disable");
        CommandMgr::instance().deregisterCommand("dhcp-enable");
940 941
        CommandMgr::instance().deregisterCommand("leases-reclaim");
        CommandMgr::instance().deregisterCommand("libreload");
942
        CommandMgr::instance().deregisterCommand("server-tag-get");
943
        CommandMgr::instance().deregisterCommand("server-update");
944
        CommandMgr::instance().deregisterCommand("shutdown");
945 946
        CommandMgr::instance().deregisterCommand("statistic-get");
        CommandMgr::instance().deregisterCommand("statistic-get-all");
947
        CommandMgr::instance().deregisterCommand("statistic-remove");
948
        CommandMgr::instance().deregisterCommand("statistic-remove-all");
949 950
        CommandMgr::instance().deregisterCommand("statistic-reset");
        CommandMgr::instance().deregisterCommand("statistic-reset-all");
Razvan Becheriu's avatar
Razvan Becheriu committed
951 952 953 954
        CommandMgr::instance().deregisterCommand("statistic-sample-age-set");
        CommandMgr::instance().deregisterCommand("statistic-sample-age-set-all");
        CommandMgr::instance().deregisterCommand("statistic-sample-count-set");
        CommandMgr::instance().deregisterCommand("statistic-sample-count-set-all");
Francis Dupont's avatar
Francis Dupont committed
955
        CommandMgr::instance().deregisterCommand("version-get");
956 957 958 959 960 961

    } catch (...) {
        // Don't want to throw exceptions from the destructor. The server
        // is shutting down anyway.
        ;
    }
962

Tomek Mrugalski's avatar
Tomek Mrugalski committed
963 964
    server_ = NULL; // forget this instance. Noone should call any handlers at
                    // this stage.
965 966 967 968 969
}

void ControlledDhcpv4Srv::sessionReader(void) {
    // Process one asio event. If there are more events, iface_mgr will call
    // this callback more than once.
Tomek Mrugalski's avatar
Tomek Mrugalski committed
970 971
    if (getInstance()) {
        getInstance()->io_service_.run_one();
972 973 974
    }
}

975 976 977
void
ControlledDhcpv4Srv::reclaimExpiredLeases(const size_t max_leases,
                                          const uint16_t timeout,
978 979
                                          const bool remove_lease,
                                          const uint16_t max_unwarned_cycles) {
980
    server_->alloc_engine_->reclaimExpiredLeases4(max_leases, timeout,
981 982
                                                  remove_lease,
                                                  max_unwarned_cycles);
983 984 985 986 987 988 989 990 991 992 993
    // We're using the ONE_SHOT timer so there is a need to re-schedule it.
    TimerMgr::instance()->setup(CfgExpiration::RECLAIM_EXPIRED_TIMER_NAME);
}

void
ControlledDhcpv4Srv::deleteExpiredReclaimedLeases(const uint32_t secs) {
    server_->alloc_engine_->deleteExpiredReclaimedLeases4(secs);
    // We're using the ONE_SHOT timer so there is a need to re-schedule it.
    TimerMgr::instance()->setup(CfgExpiration::FLUSH_RECLAIMED_TIMER_NAME);
}

994
void
995
ControlledDhcpv4Srv::dbReconnect(ReconnectCtlPtr db_reconnect_ctl) {
996 997 998 999 1000
    bool reopened = false;

    // Re-open lease and host database with new parameters.
    try {
        CfgDbAccessPtr cfg_db = CfgMgr::instance().getCurrentCfg()->getCfgDbAccess();
1001
        cfg_db->createManagers();
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
        reopened = true;
    } catch (const std::exception& ex) {
        LOG_ERROR(dhcp4_logger, DHCP4_DB_RECONNECT_ATTEMPT_FAILED).arg(ex.what());
    }

    if (reopened) {
        // Cancel the timer.
        if (TimerMgr::instance()->isTimerRegistered("Dhcp4DbReconnectTimer")) {
            TimerMgr::instance()->cancel("Dhcp4DbReconnectTimer");
        }

        // Set network state to service enabled
1014
        network_state_->enableService();
1015

1016
        // Toss the reconnect control, we're done with it
1017
        db_reconnect_ctl.reset();
1018
    } else {
1019
        if (!db_reconnect_ctl->checkRetries()) {
1020
            LOG_ERROR(dhcp4_logger, DHCP4_DB_RECONNECT_RETRIES_EXHAUSTED)
1021
            .arg(db_reconnect_ctl->maxRetries());
1022 1023 1024 1025 1026
            shutdown();
            return;
        }

        LOG_INFO(dhcp4_logger, DHCP4_DB_RECONNECT_ATTEMPT_SCHEDULE)
1027 1028 1029
                .arg(db_reconnect_ctl->maxRetries() - db_reconnect_ctl->retriesLeft() + 1)
                .arg(db_reconnect_ctl->maxRetries())
                .arg(db_reconnect_ctl->retryInterval());
1030 1031 1032

        if (!TimerMgr::instance()->isTimerRegistered("Dhcp4DbReconnectTimer")) {
            TimerMgr::instance()->registerTimer("Dhcp4DbReconnectTimer",
1033 1034
                            boost::bind(&ControlledDhcpv4Srv::dbReconnect, this,
                                        db_reconnect_ctl),
1035
                            db_reconnect_ctl->retryInterval(),
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
                            asiolink::IntervalTimer::ONE_SHOT);
        }

        TimerMgr::instance()->setup("Dhcp4DbReconnectTimer");
    }
}

bool
ControlledDhcpv4Srv::dbLostCallback(ReconnectCtlPtr db_reconnect_ctl) {
    // Disable service until we recover
1046
    network_state_->disableService();
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063

    if (!db_reconnect_ctl) {
        // This shouldn't never happen
        LOG_ERROR(dhcp4_logger, DHCP4_DB_RECONNECT_NO_DB_CTL);
        return (false);
    }

    // If reconnect isn't enabled, log it and return false
    if (!db_reconnect_ctl->retriesLeft() ||
        !db_reconnect_ctl->retryInterval()) {
        LOG_INFO(dhcp4_logger, DHCP4_DB_RECONNECT_DISABLED)
            .arg(db_reconnect_ctl->retriesLeft())
            .arg(db_reconnect_ctl->retryInterval());
        return(false);
    }

    // Invoke reconnect method
1064
    dbReconnect(db_reconnect_ctl);
1065 1066 1067 1068

    return(true);
}

1069
void
1070 1071
ControlledDhcpv4Srv::cbFetchUpdates(const SrvConfigPtr& srv_cfg,
                                    boost::shared_ptr<unsigned> failure_count) {
1072
    try {
1073
        // Fetch any configuration backend updates since our last fetch.
1074 1075
        server_->getCBControl()->databaseConfigFetch(srv_cfg,
                                                     CBControlDHCPv4::FetchMode::FETCH_UPDATE);
1076
        (*failure_count) = 0;
1077 1078 1079 1080

    } catch (const std::exception& ex) {
        LOG_ERROR(dhcp4_logger, DHCP4_CB_FETCH_UPDATES_FAIL)
            .arg(ex.what());
1081 1082 1083 1084 1085 1086 1087 1088

        // We allow at most 10 consecutive failures after which we stop
        // making further attempts to fetch the configuration updates.
        // Let's return without re-scheduling the timer.
        if (++(*failure_count) > 10) {
            LOG_ERROR(dhcp4_logger, DHCP4_CB_FETCH_UPDATES_RETRIES_EXHAUSTED);
            return;
        }
1089 1090 1091 1092 1093 1094 1095 1096 1097
    }

    // Reschedule the timer to fetch new updates or re-try if
    // the previous attempt resulted in an error.
    if (TimerMgr::instance()->isTimerRegistered("Dhcp4CBFetchTimer")) {
        TimerMgr::instance()->setup("Dhcp4CBFetchTimer");
    }
}

1098 1099
}; // end of isc::dhcp namespace
}; // end of isc namespace