ctrl_dhcp6_srv.cc 35.8 KB
Newer Older
1
// Copyright (C) 2014-2018 Internet Systems Consortium, Inc. ("ISC")
Tomek Mrugalski's avatar
Tomek Mrugalski committed
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/.
Tomek Mrugalski's avatar
Tomek Mrugalski committed
6 7 8

#include <config.h>
#include <cc/data.h>
9
#include <cc/command_interpreter.h>
10
#include <config/command_mgr.h>
11
#include <dhcp/libdhcp++.h>
12
#include <dhcpsrv/cfgmgr.h>
13
#include <dhcpsrv/cfg_db_access.h>
14
#include <dhcpsrv/database_connection.h>
Tomek Mrugalski's avatar
Tomek Mrugalski committed
15
#include <dhcp6/ctrl_dhcp6_srv.h>
16
#include <dhcp6/dhcp6to4_ipc.h>
Tomek Mrugalski's avatar
Tomek Mrugalski committed
17 18
#include <dhcp6/dhcp6_log.h>
#include <dhcp6/json_config_parser.h>
19
#include <dhcp6/parser_context.h>
20 21
#include <hooks/hooks_manager.h>
#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>
Tomek Mrugalski's avatar
Tomek Mrugalski committed
25

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

33 34
namespace {

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
/// Structure that holds registered hook indexes.
struct CtrlDhcp6Hooks {
    int hooks_index_dhcp6_srv_configured_;

    /// Constructor that registers hook points for the DHCPv6 server.
    CtrlDhcp6Hooks() {
        hooks_index_dhcp6_srv_configured_ = HooksManager::registerHook("dhcp6_srv_configured");
    }

};

// 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.
CtrlDhcp6Hooks Hooks;

52 53 54
// Name of the file holding server identifier.
static const char* SERVER_DUID_FILE = "kea-dhcp6-serverid";

55 56 57 58 59 60 61 62 63 64 65 66
/// @brief Signals handler for DHCPv6 server.
///
/// This signal handler handles the following signals received by the DHCPv6
/// 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
67 68
        ControlledDhcpv6Srv::processCommand("config-reload",
                                            ConstElementPtr());
69
    } else if ((signo == SIGTERM) || (signo == SIGINT)) {
Francis Dupont's avatar
Francis Dupont committed
70 71
        ControlledDhcpv6Srv::processCommand("shutdown",
                                            ConstElementPtr());
72 73 74
    }
}

75 76
}

Tomek Mrugalski's avatar
Tomek Mrugalski committed
77 78 79 80 81
namespace isc {
namespace dhcp {

ControlledDhcpv6Srv* ControlledDhcpv6Srv::server_ = NULL;

82 83 84 85 86 87 88 89 90
/// @brief Configure DHCPv6 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 DHCPv6 server's configuration from the 'Dhcp6' section of
/// the JSON configuration file.
///
/// @param file_name Configuration file location.
Francis Dupont's avatar
Francis Dupont committed
91
/// @return status of the command
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
ConstElementPtr
ControlledDhcpv6Srv::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 dhcp6;
    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
        Parser6Context parser;
        json = parser.parseFile(file_name, Parser6Context::PARSER_DHCP6);
        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 'Dhcp6' 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 = ControlledDhcpv6Srv::processCommand("config-set", json);
        if (!result) {
            // Undetermined status of the configuration. This should never
            // happen, but as the configureDhcp6Server 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;
        isc::data::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(dhcp6_logger, DHCP6_CONFIG_LOAD_FAIL)
            .arg(file_name).arg(ex.what());
        isc_throw(isc::BadValue, "configuration error using file '"
                  << file_name << "': " << ex.what());
    }

    return (result);
}


void
ControlledDhcpv6Srv::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
Francis Dupont's avatar
Francis Dupont committed
177
    // processCommand("config-set", ...)
178 179 180 181 182 183 184 185 186 187 188 189 190 191

    // 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 ControlledDhcpv6Srv::cleanup() {
    // Nothing to do here. No need to disconnect from anything.
}


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

ConstElementPtr
ControlledDhcpv6Srv::commandLibReloadHandler(const string&, ConstElementPtr) {
207 208
    /// @todo delete any stored CalloutHandles referring to the old libraries
    /// Get list of currently loaded libraries and reload them.
209
    HookLibsCollection loaded = HooksManager::getLibraryInfo();
Tomek Mrugalski's avatar
Tomek Mrugalski committed
210 211 212 213 214 215 216 217 218 219 220 221 222
    bool status = HooksManager::loadLibraries(loaded);
    if (!status) {
        LOG_ERROR(dhcp6_logger, DHCP6_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
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
ControlledDhcpv6Srv::commandConfigReloadHandler(const string&,
                                                ConstElementPtr /*args*/) {
    // Get configuration file name.
    std::string file = ControlledDhcpv6Srv::getInstance()->getConfigFile();
    try {
        LOG_INFO(dhcp6_logger, DHCP6_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(dhcp6_logger, DHCP6_DYNAMIC_RECONFIGURATION_FAIL)
            .arg(file);
        return (createAnswer(CONTROL_RESULT_ERROR,
                             "Config reload failed:" + string(ex.what())));
    }
Tomek Mrugalski's avatar
Tomek Mrugalski committed
239 240
}

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

    return (createAnswer(0, config));
}

249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
ConstElementPtr
ControlledDhcpv6Srv::commandConfigWriteHandler(const string&, ConstElementPtr args) {
    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
        // from the command-line
        filename = getConfigFile();
    }

273 274 275
    if (filename.empty()) {
        return (createAnswer(CONTROL_RESULT_ERROR, "Unable to determine filename."
                             "Please specify filename explicitly."));
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
    }

    // Ok, it's time to write the file.
    size_t size = 0;
    try {
        size = writeConfigFile(filename);
    } 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));
    }

    // Ok, it's time to return the successful response.
    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
ControlledDhcpv6Srv::commandConfigSetHandler(const string&,
302
                                             ConstElementPtr args) {
303
    const int status_code = CONTROL_RESULT_ERROR;
304 305 306 307 308
    ConstElementPtr dhcp6;
    string message;

    // Command arguments are expected to be:
    // { "Dhcp6": { ... }, "Logging": { ... } }
309 310
    // The Logging component is technically optional. If it's not supplied
    // logging will revert to default logging.
311 312 313 314 315 316 317 318 319 320
    if (!args) {
        message = "Missing mandatory 'arguments' parameter.";
    } else {
        dhcp6 = args->get("Dhcp6");
        if (!dhcp6) {
            message = "Missing mandatory 'Dhcp6' parameter.";
        } else if (dhcp6->getType() != Element::map) {
            message = "'Dhcp6' parameter expected to be a map.";
        }
    }
Tomek Mrugalski's avatar
Tomek Mrugalski committed
321

322 323 324 325 326 327
    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 333
    // We are starting the configuration process so we should remove any
    // staging configuration that has been created during previous
    // configuration attempts.
    CfgMgr::instance().rollback();

334
    // Logging is a sibling element and must be parsed explicitly.
335
    // The call to configureLogger parses the given Logging element if
336
    // not null, into the staging config.  Note this does not alter the
337
    // current loggers, they remain in effect until we apply the
338 339
    // logging config below.  If no logging is supplied logging will
    // revert to default logging.
340 341 342
    Daemon::configureLogger(args->get("Logging"),
                            CfgMgr::instance().getStagingCfg());

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

347
    // Now we configure the server proper.
348 349 350 351 352 353 354
    ConstElementPtr result = processConfig(dhcp6);

    // 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);
355
    if (rcode == CONTROL_RESULT_SUCCESS) {
356 357 358 359
        CfgMgr::instance().getStagingCfg()->applyLoggingCfg();

        // Use new configuration.
        CfgMgr::instance().commit();
360 361 362 363 364
    } 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();
365 366 367
    }

    return (result);
Tomek Mrugalski's avatar
Tomek Mrugalski committed
368 369
}

Francis Dupont's avatar
Francis Dupont committed
370 371 372
ConstElementPtr
ControlledDhcpv6Srv::commandConfigTestHandler(const string&,
                                              ConstElementPtr args) {
373
    const int status_code = CONTROL_RESULT_ERROR; // 1 indicates an error
Francis Dupont's avatar
Francis Dupont committed
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
    ConstElementPtr dhcp6;
    string message;

    // Command arguments are expected to be:
    // { "Dhcp6": { ... }, "Logging": { ... } }
    // The Logging component is technically optional. If it's not supplied
    // logging will revert to default logging.
    if (!args) {
        message = "Missing mandatory 'arguments' parameter.";
    } else {
        dhcp6 = args->get("Dhcp6");
        if (!dhcp6) {
            message = "Missing mandatory 'Dhcp6' parameter.";
        } else if (dhcp6->getType() != Element::map) {
            message = "'Dhcp6' 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();

    // Now we check the server proper.
    return (checkConfig(dhcp6));
}
407

408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
ConstElementPtr
ControlledDhcpv6Srv::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.
438
                    network_state_->delayedEnableAll(static_cast<unsigned>(max_period));
439 440 441 442 443 444 445
                }
            }
        }
    }

    // No error occurred, so let's disable the service.
    if (message.tellp() == 0) {
446
        network_state_->disableService();
447

448
        message << "DHCPv6 service disabled";
449 450 451 452 453 454 455 456 457 458 459 460 461
        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
ControlledDhcpv6Srv::commandDhcpEnableHandler(const std::string&, ConstElementPtr) {
462
    network_state_->enableService();
463 464 465
    return (config::createAnswer(CONTROL_RESULT_SUCCESS, "DHCP service successfully enabled"));
}

Francis Dupont's avatar
Francis Dupont committed
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
ConstElementPtr
ControlledDhcpv6Srv::commandVersionGetHandler(const string&, ConstElementPtr) {
    ElementPtr extended = Element::create(Dhcpv6Srv::getVersion(true));
    ElementPtr arguments = Element::createMap();
    arguments->set("extended", extended);
    ConstElementPtr answer = isc::config::createAnswer(0,
                                Dhcpv6Srv::getVersion(false),
                                arguments);
    return (answer);
}

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

484
ConstElementPtr
485
ControlledDhcpv6Srv::commandLeasesReclaimHandler(const string&,
Francis Dupont's avatar
Francis Dupont committed
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
                                                 ConstElementPtr args) {
    int status_code = 1;
    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_->reclaimExpiredLeases6(0, 0, remove_lease);
            status_code = 0;
            message = "Reclamation of expired leases is complete.";
        }
    }
    ConstElementPtr answer = isc::config::createAnswer(status_code, message);
507 508 509
    return (answer);
}

Tomek Mrugalski's avatar
Tomek Mrugalski committed
510 511 512
isc::data::ConstElementPtr
ControlledDhcpv6Srv::processCommand(const std::string& command,
                                    isc::data::ConstElementPtr args) {
Francis Dupont's avatar
Francis Dupont committed
513
    string txt = args ? args->str() : "(none)";
514

Tomek Mrugalski's avatar
Tomek Mrugalski committed
515
    LOG_DEBUG(dhcp6_logger, DBG_DHCP6_COMMAND, DHCP6_COMMAND_RECEIVED)
516
              .arg(command).arg(txt);
Tomek Mrugalski's avatar
Tomek Mrugalski committed
517 518 519 520 521 522

    ControlledDhcpv6Srv* srv = ControlledDhcpv6Srv::getInstance();

    if (!srv) {
        ConstElementPtr no_srv = isc::config::createAnswer(1,
          "Server object not initialized, can't process command '" +
523
          command + "', arguments: '" + txt + "'.");
Tomek Mrugalski's avatar
Tomek Mrugalski committed
524 525 526 527 528 529 530 531 532 533 534 535
        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));
Francis Dupont's avatar
Francis Dupont committed
536

537
        } else if (command == "config-set") {
538
            return (srv->commandConfigSetHandler(command, args));
539

540 541
        } else if (command == "config-get") {
            return (srv->commandConfigGetHandler(command, args));
542

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

546 547 548 549 550 551
        } 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
552 553 554 555 556 557
        } 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
558 559
        } else if (command == "leases-reclaim") {
            return (srv->commandLeasesReclaimHandler(command, args));
560 561 562 563

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

Tomek Mrugalski's avatar
Tomek Mrugalski committed
564 565 566 567 568 569 570 571 572 573 574 575 576
        }

        return (isc::config::createAnswer(1, "Unrecognized command:"
                                          + command));

    } catch (const Exception& ex) {
        return (isc::config::createAnswer(1, "Error while processing command '"
                                          + command + "':" + ex.what()));
    }
}

isc::data::ConstElementPtr
ControlledDhcpv6Srv::processConfig(isc::data::ConstElementPtr config) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
577 578 579 580

    LOG_DEBUG(dhcp6_logger, DBG_DHCP6_COMMAND, DHCP6_CONFIG_RECEIVED)
              .arg(config->str());

Tomek Mrugalski's avatar
Tomek Mrugalski committed
581 582 583
    ControlledDhcpv6Srv* srv = ControlledDhcpv6Srv::getInstance();

    if (!srv) {
584 585 586
        ConstElementPtr no_srv = isc::config::createAnswer(
            CONTROL_RESULT_ERROR,
            "Server object not initialized, can't process config.");
Tomek Mrugalski's avatar
Tomek Mrugalski committed
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
        return (no_srv);
    }

    ConstElementPtr answer = configureDhcp6Server(*srv, config);

    // 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) {
        return (isc::config::createAnswer(1, "Failed to process configuration:"
                                          + string(ex.what())));
    }

605 606
    // Re-open lease and host database with new parameters.
    try {
607 608
        DatabaseConnection::db_lost_callback =
            boost::bind(&ControlledDhcpv6Srv::dbLostCallback, srv, _1);
609 610
        CfgDbAccessPtr cfg_db = CfgMgr::instance().getStagingCfg()->getCfgDbAccess();
        cfg_db->setAppendedParameters("universe=6");
611
        cfg_db->createManagers();
612 613 614 615 616
    } catch (const std::exception& ex) {
        return (isc::config::createAnswer(1, "Unable to open database: "
                                          + std::string(ex.what())));
    }

617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
    // Regenerate server identifier if needed.
    try {
        const std::string duid_file = CfgMgr::instance().getDataDir() + "/" +
            std::string(SERVER_DUID_FILE);
        DuidPtr duid = CfgMgr::instance().getStagingCfg()->getCfgDUID()->create(duid_file);
        server_->serverid_.reset(new Option(Option::V6, D6O_SERVERID, duid->getDuid()));
        if (duid) {
            LOG_INFO(dhcp6_logger, DHCP6_USING_SERVERID)
                .arg(duid->toText())
                .arg(duid_file);
        }

    } catch (const std::exception& ex) {
        std::ostringstream err;
        err << "unable to configure server identifier: " << ex.what();
        return (isc::config::createAnswer(1, err.str()));
    }

Tomek Mrugalski's avatar
Tomek Mrugalski committed
635 636 637 638 639 640 641
    // Server will start DDNS communications if its enabled.
    try {
        srv->startD2();
    } catch (const std::exception& ex) {
        std::ostringstream err;
        err << "error starting DHCP_DDNS client "
                " after server reconfiguration: " << ex.what();
642 643 644 645 646
        return (isc::config::createAnswer(1, err.str()));
    }

    // Setup DHCPv4-over-DHCPv6 IPC
    try {
647
        Dhcp6to4Ipc::instance().open();
648 649 650 651
    } catch (const std::exception& ex) {
        std::ostringstream err;
        err << "error starting DHCPv4-over-DHCPv6 IPC "
               " after server reconfiguration: " << ex.what();
Tomek Mrugalski's avatar
Tomek Mrugalski committed
652 653 654 655
        return (isc::config::createAnswer(1, err.str()));
    }

    // Configuration may change active interfaces. Therefore, we have to reopen
656 657 658 659 660 661
    // 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.
662
    CfgMgr::instance().getStagingCfg()->getCfgIface()->openSockets(AF_INET6, srv->getPort());
Tomek Mrugalski's avatar
Tomek Mrugalski committed
663

664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
    // Install the timers for handling leases reclamation.
    try {
        CfgMgr::instance().getStagingCfg()->getCfgExpiration()->
            setupTimers(&ControlledDhcpv6Srv::reclaimExpiredLeases,
                        &ControlledDhcpv6Srv::deleteExpiredReclaimedLeases,
                        server_);

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

679 680 681 682
    // Finally, we can commit runtime option definitions in libdhcp++. This is
    // exception free.
    LibDHCP::commitRuntimeOptionDefs();

683 684 685 686 687 688 689 690 691
    // This hook point notifies hooks libraries that the configuration of the
    // DHCPv6 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.
    if (HooksManager::calloutsPresent(Hooks.hooks_index_dhcp6_srv_configured_)) {
        CalloutHandlePtr callout_handle = HooksManager::createCalloutHandle();

        callout_handle->setArgument("io_context", srv->getIOService());
692
        callout_handle->setArgument("network_state", srv->getNetworkState());
693 694 695 696 697 698 699 700 701 702
        callout_handle->setArgument("json_config", config);
        callout_handle->setArgument("server_config", CfgMgr::instance().getStagingCfg());

        HooksManager::callCallouts(Hooks.hooks_index_dhcp6_srv_configured_,
                                   *callout_handle);

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

Tomek Mrugalski's avatar
Tomek Mrugalski committed
703 704 705
    return (answer);
}

Francis Dupont's avatar
Francis Dupont committed
706 707
isc::data::ConstElementPtr
ControlledDhcpv6Srv::checkConfig(isc::data::ConstElementPtr config) {
708

Francis Dupont's avatar
Francis Dupont committed
709 710
    LOG_DEBUG(dhcp6_logger, DBG_DHCP6_COMMAND, DHCP6_CONFIG_RECEIVED)
        .arg(config->str());
711

Francis Dupont's avatar
Francis Dupont committed
712
    ControlledDhcpv6Srv* srv = ControlledDhcpv6Srv::getInstance();
713

Francis Dupont's avatar
Francis Dupont committed
714 715 716 717 718
    if (!srv) {
        ConstElementPtr no_srv = isc::config::createAnswer(1,
            "Server object not initialized, can't process config.");
        return (no_srv);
    }
719

Francis Dupont's avatar
Francis Dupont committed
720 721 722
    return (configureDhcp6Server(*srv, config, true));
}

Tomek Mrugalski's avatar
Tomek Mrugalski committed
723
ControlledDhcpv6Srv::ControlledDhcpv6Srv(uint16_t port)
724
    : Dhcpv6Srv(port), io_service_(), timer_mgr_(TimerMgr::instance()) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
725 726 727 728 729
    if (server_) {
        isc_throw(InvalidOperation,
                  "There is another Dhcpv6Srv instance already.");
    }
    server_ = this; // remember this instance for use in callback
730

731
    // TimerMgr uses IO service to run asynchronous timers.
732 733
    TimerMgr::instance()->setIOService(getIOService());

734 735 736
    // CommandMgr uses IO service to run asynchronous socket operations.
    CommandMgr::instance().setIOService(getIOService());

737 738
    // These are the commands always supported by the DHCPv6 server.
    // Please keep the list in alphabetic order.
Francis Dupont's avatar
Francis Dupont committed
739 740 741
    CommandMgr::instance().registerCommand("build-report",
        boost::bind(&ControlledDhcpv6Srv::commandBuildReportHandler, this, _1, _2));

742 743 744
    CommandMgr::instance().registerCommand("config-get",
        boost::bind(&ControlledDhcpv6Srv::commandConfigGetHandler, this, _1, _2));

745 746
    CommandMgr::instance().registerCommand("config-reload",
        boost::bind(&ControlledDhcpv6Srv::commandConfigReloadHandler, this, _1, _2));
747

Francis Dupont's avatar
Francis Dupont committed
748 749 750
    CommandMgr::instance().registerCommand("config-test",
        boost::bind(&ControlledDhcpv6Srv::commandConfigTestHandler, this, _1, _2));

751 752 753
    CommandMgr::instance().registerCommand("config-write",
        boost::bind(&ControlledDhcpv6Srv::commandConfigWriteHandler, this, _1, _2));

754 755 756 757 758 759
    CommandMgr::instance().registerCommand("dhcp-disable",
        boost::bind(&ControlledDhcpv6Srv::commandDhcpDisableHandler, this, _1, _2));

    CommandMgr::instance().registerCommand("dhcp-enable",
        boost::bind(&ControlledDhcpv6Srv::commandDhcpEnableHandler, this, _1, _2));

760 761
    CommandMgr::instance().registerCommand("leases-reclaim",
        boost::bind(&ControlledDhcpv6Srv::commandLeasesReclaimHandler, this, _1, _2));
762

763 764
    CommandMgr::instance().registerCommand("libreload",
        boost::bind(&ControlledDhcpv6Srv::commandLibReloadHandler, this, _1, _2));
765

766
    CommandMgr::instance().registerCommand("config-set",
767
        boost::bind(&ControlledDhcpv6Srv::commandConfigSetHandler, this, _1, _2));
768

769 770
    CommandMgr::instance().registerCommand("shutdown",
        boost::bind(&ControlledDhcpv6Srv::commandShutdownHandler, this, _1, _2));
771

Francis Dupont's avatar
Francis Dupont committed
772 773 774
    CommandMgr::instance().registerCommand("version-get",
        boost::bind(&ControlledDhcpv6Srv::commandVersionGetHandler, this, _1, _2));

775 776 777 778 779 780 781
    // Register statistic related commands
    CommandMgr::instance().registerCommand("statistic-get",
        boost::bind(&StatsMgr::statisticGetHandler, _1, _2));

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

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

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

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

791 792
    CommandMgr::instance().registerCommand("statistic-remove-all",
        boost::bind(&StatsMgr::statisticRemoveAllHandler, _1, _2));
Tomek Mrugalski's avatar
Tomek Mrugalski committed
793 794 795 796 797 798 799 800
}

void ControlledDhcpv6Srv::shutdown() {
    io_service_.stop(); // Stop ASIO transmissions
    Dhcpv6Srv::shutdown(); // Initiate DHCPv6 shutdown procedure.
}

ControlledDhcpv6Srv::~ControlledDhcpv6Srv() {
801 802 803
    try {
        cleanup();

804 805 806 807
        // The closure captures either a shared pointer (memory leak)
        // or a raw pointer (pointing to a deleted object).
        DatabaseConnection::db_lost_callback = 0;

808
        timer_mgr_->unregisterTimers();
809 810 811 812

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

813
        // Deregister any registered commands (please keep in alphabetic order)
Francis Dupont's avatar
Francis Dupont committed
814
        CommandMgr::instance().deregisterCommand("build-report");
815
        CommandMgr::instance().deregisterCommand("config-get");
816 817
        CommandMgr::instance().deregisterCommand("config-set");
        CommandMgr::instance().deregisterCommand("config-reload");
Francis Dupont's avatar
Francis Dupont committed
818
        CommandMgr::instance().deregisterCommand("config-test");
819
        CommandMgr::instance().deregisterCommand("config-write");
820 821
        CommandMgr::instance().deregisterCommand("dhcp-disable");
        CommandMgr::instance().deregisterCommand("dhcp-enable");
822
        CommandMgr::instance().deregisterCommand("leases-reclaim");
Francis Dupont's avatar
Francis Dupont committed
823
        CommandMgr::instance().deregisterCommand("libreload");
824
        CommandMgr::instance().deregisterCommand("shutdown");
825 826
        CommandMgr::instance().deregisterCommand("statistic-get");
        CommandMgr::instance().deregisterCommand("statistic-get-all");
827
        CommandMgr::instance().deregisterCommand("statistic-remove");
828
        CommandMgr::instance().deregisterCommand("statistic-remove-all");
829 830
        CommandMgr::instance().deregisterCommand("statistic-reset");
        CommandMgr::instance().deregisterCommand("statistic-reset-all");
Francis Dupont's avatar
Francis Dupont committed
831
        CommandMgr::instance().deregisterCommand("version-get");
832 833 834 835 836 837

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

Tomek Mrugalski's avatar
Tomek Mrugalski committed
839 840 841 842 843 844 845 846 847 848 849 850
    server_ = NULL; // forget this instance. There should be no callback anymore
                    // at this stage anyway.
}

void ControlledDhcpv6Srv::sessionReader(void) {
    // Process one asio event. If there are more events, iface_mgr will call
    // this callback more than once.
    if (server_) {
        server_->io_service_.run_one();
    }
}

851 852 853
void
ControlledDhcpv6Srv::reclaimExpiredLeases(const size_t max_leases,
                                          const uint16_t timeout,
854 855
                                          const bool remove_lease,
                                          const uint16_t max_unwarned_cycles) {
856
    server_->alloc_engine_->reclaimExpiredLeases6(max_leases, timeout,
857 858
                                                  remove_lease,
                                                  max_unwarned_cycles);
859 860 861 862 863 864 865 866 867 868 869
    // 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
ControlledDhcpv6Srv::deleteExpiredReclaimedLeases(const uint32_t secs) {
    server_->alloc_engine_->deleteExpiredReclaimedLeases6(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);
}

870
void
871
ControlledDhcpv6Srv::dbReconnect(ReconnectCtlPtr db_reconnect_ctl) {
872 873 874 875 876
    bool reopened = false;

    // Re-open lease and host database with new parameters.
    try {
        CfgDbAccessPtr cfg_db = CfgMgr::instance().getCurrentCfg()->getCfgDbAccess();
877
        cfg_db->createManagers();
878 879 880 881 882 883 884 885 886 887 888
        reopened = true;
    } catch (const std::exception& ex) {
        LOG_ERROR(dhcp6_logger, DHCP6_DB_RECONNECT_ATTEMPT_FAILED).arg(ex.what());
    }

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

        // Set network state to service enabled
889
        network_state_->enableService();
890 891

        // Toss the reconnct control, we're done with it
892
        db_reconnect_ctl.reset();
893
    } else {
894
        if (!db_reconnect_ctl->checkRetries()) {
895
            LOG_ERROR(dhcp6_logger, DHCP6_DB_RECONNECT_RETRIES_EXHAUSTED)
896
            .arg(db_reconnect_ctl->maxRetries());
897 898 899 900 901
            shutdown();
            return;
        }

        LOG_INFO(dhcp6_logger, DHCP6_DB_RECONNECT_ATTEMPT_SCHEDULE)
902 903 904
                .arg(db_reconnect_ctl->maxRetries() - db_reconnect_ctl->retriesLeft() + 1)
                .arg(db_reconnect_ctl->maxRetries())
                .arg(db_reconnect_ctl->retryInterval());
905 906 907

        if (!TimerMgr::instance()->isTimerRegistered("Dhcp6DbReconnectTimer")) {
            TimerMgr::instance()->registerTimer("Dhcp6DbReconnectTimer",
908 909 910
                            boost::bind(&ControlledDhcpv6Srv::dbReconnect, this,
                            db_reconnect_ctl),
                            db_reconnect_ctl->retryInterval() * 1000,
911 912 913 914 915 916 917 918 919 920
                            asiolink::IntervalTimer::ONE_SHOT);
        }

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

bool
ControlledDhcpv6Srv::dbLostCallback(ReconnectCtlPtr db_reconnect_ctl) {
    // Disable service until we recover
921
    network_state_->disableService();
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938

    if (!db_reconnect_ctl) {
        // This shouldn't never happen
        LOG_ERROR(dhcp6_logger, DHCP6_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(dhcp6_logger, DHCP6_DB_RECONNECT_DISABLED)
            .arg(db_reconnect_ctl->retriesLeft())
            .arg(db_reconnect_ctl->retryInterval());
        return(false);
    }

    // Invoke reconnect method
939
    dbReconnect(db_reconnect_ctl);
940 941 942

    return(true);
}
943

Tomek Mrugalski's avatar
Tomek Mrugalski committed
944 945
}; // end of isc::dhcp namespace
}; // end of isc namespace