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

#include <config.h>
8 9
#include <agent/ca_controller.h>
#include <agent/ca_process.h>
10
#include <agent/ca_command_mgr.h>
11
#include <cc/data.h>
12
#include <cc/command_interpreter.h>
13
#include <process/testutils/d_test_stubs.h>
14
#include <boost/pointer_cast.hpp>
15
#include <sstream>
16
#include <unistd.h>
17

18
using namespace std;
19
using namespace isc::agent;
20
using namespace isc::data;
21
using namespace isc::http;
22
using namespace isc::process;
23
using namespace boost::posix_time;
24 25 26 27

namespace {

/// @brief Valid Control Agent Config used in tests.
28 29 30
const char* valid_agent_config =
    "{"
    "  \"http-host\": \"127.0.0.1\","
31 32
    "  \"http-port\": 8081,"
    "  \"control-sockets\": {"
33
    "    \"dhcp4\": {"
34 35 36
    "      \"socket-type\": \"unix\","
    "      \"socket-name\": \"/first/dhcp4/socket\""
    "    },"
37
    "    \"dhcp6\": {"
38 39 40 41
    "      \"socket-type\": \"unix\","
    "      \"socket-name\": \"/first/dhcp6/socket\""
    "    }"
    "  }"
42
    "}";
43

44 45 46
/// @brief test fixture class for testing CtrlAgentController class.
///
/// This class derives from DControllerTest and wraps CtrlAgentController. Much
47 48 49 50 51 52 53 54 55 56 57
/// of the underlying functionality is in the DControllerBase class which
/// has extensive set of unit tests that are independent from the Control
/// Agent.
class CtrlAgentControllerTest : public DControllerTest {
public:

    /// @brief Constructor.
    CtrlAgentControllerTest()
        : DControllerTest(CtrlAgentController::instance) {
    }

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
    /// @brief Returns pointer to CtrlAgentProcess instance.
    CtrlAgentProcessPtr getCtrlAgentProcess() {
        return (boost::dynamic_pointer_cast<CtrlAgentProcess>(getProcess()));
    }

    /// @brief Returns pointer to CtrlAgentCfgMgr instance for a process.
    CtrlAgentCfgMgrPtr getCtrlAgentCfgMgr() {
        CtrlAgentCfgMgrPtr p;
        if (getCtrlAgentProcess()) {
            p = getCtrlAgentProcess()->getCtrlAgentCfgMgr();
        }
        return (p);
    }

    /// @brief Returns a pointer to the configuration context.
    CtrlAgentCfgContextPtr getCtrlAgentCfgContext() {
        CtrlAgentCfgContextPtr p;
        if (getCtrlAgentCfgMgr()) {
            p = getCtrlAgentCfgMgr()->getCtrlAgentCfgContext();
        }
        return (p);
    }

    /// @brief Tests that socket info structure contains 'unix' socket-type
    /// value and the expected socket-name.
    ///
84
    /// @param service Service type.
85
    /// @param exp_socket_name Expected socket name.
86
    void testUnixSocketInfo(const std::string& service,
87 88 89 90
                            const std::string& exp_socket_name) {
        CtrlAgentCfgContextPtr ctx = getCtrlAgentCfgContext();
        ASSERT_TRUE(ctx);

91
        ConstElementPtr sock_info = ctx->getControlSocketInfo(service);
92 93 94 95 96 97 98 99
        ASSERT_TRUE(sock_info);
        ASSERT_TRUE(sock_info->contains("socket-type"));
        EXPECT_EQ("unix", sock_info->get("socket-type")->stringValue());
        ASSERT_TRUE(sock_info->contains("socket-name"));
        EXPECT_EQ(exp_socket_name,
                  sock_info->get("socket-name")->stringValue());
    }

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
        /// @brief Compares the status in the given parse result to a given value.
    ///
    /// @param answer Element set containing an integer response and string
    /// comment.
    /// @param exp_status is an integer against which to compare the status.
    /// @param exp_txt is expected text (not checked if "")
    ///
    void checkAnswer(isc::data::ConstElementPtr answer,
                     int exp_status,
                     string exp_txt = "") {

        // Get rid of the outer list.
        ASSERT_TRUE(answer);
        ASSERT_EQ(Element::list, answer->getType());
        ASSERT_LE(1, answer->size());
        answer = answer->get(0);

        int rcode = 0;
        isc::data::ConstElementPtr comment;
        comment = isc::config::parseAnswer(rcode, answer);

        if (rcode != exp_status) {
            ADD_FAILURE() << "Expected status code " << exp_status
                          << " but received " << rcode << ", comment: "
                          << (comment ? comment->str() : "(none)");
        }

        // Ok, parseAnswer interface is weird. If there are no arguments,
        // it returns content of text. But if there is an argument,
        // it returns the argument and it's not possible to retrieve
        // "text" (i.e. comment).
        if (comment->getType() != Element::string) {
            comment = answer->get("text");
        }

        if (!exp_txt.empty()) {
            EXPECT_EQ(exp_txt, comment->stringValue());
        }
    }

    /// @brief Checks whether specified command is registered
    ///
    /// @param name name of the command to be checked
    /// @param expect_true true - must be registered, false - must not be
    void checkCommandRegistered(const std::string& name, bool expect_true = true) {

        // First get the list of registered commands
        ConstElementPtr lst = Element::fromJSON("{ \"command\": \"list-commands\" }");
        ConstElementPtr rsp = CtrlAgentCommandMgr::instance().processCommand(lst);

        // The response must be an array with at least one element
        ASSERT_TRUE(rsp);
        ASSERT_EQ(Element::list, rsp->getType());
        ASSERT_LE(1, rsp->size());
        ConstElementPtr args = rsp->get(0)->get("arguments");
        ASSERT_TRUE(args);

        string args_txt = args->str();

        if (expect_true) {
            EXPECT_TRUE(args_txt.find(name) != string::npos);
        } else {
            EXPECT_TRUE(args_txt.find(name) == string::npos);
        }
    }

166 167 168 169 170 171
};

// Basic Controller instantiation testing.
// Verifies that the controller singleton gets created and that the
// basic derivation from the base class is intact.
TEST_F(CtrlAgentControllerTest, basicInstanceTesting) {
172 173
    // Verify the singleton instance can be fetched and that
    // it has the correct type.
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
    DControllerBasePtr& controller = DControllerTest::getController();
    ASSERT_TRUE(controller);
    ASSERT_NO_THROW(boost::dynamic_pointer_cast<CtrlAgentController>(controller));

    // Verify that controller's app name is correct.
    EXPECT_TRUE(checkAppName(CtrlAgentController::agent_app_name_));

    // Verify that controller's bin name is correct.
    EXPECT_TRUE(checkBinName(CtrlAgentController::agent_bin_name_));

    // Verify that controller's IOService exists.
    EXPECT_TRUE(checkIOService());

    // Verify that the Process does NOT exist.
    EXPECT_FALSE(checkProcess());
}


// Tests basic command line processing.
// Verifies that:
// 1. Standard command line options are supported.
// 2. Invalid options are detected.
TEST_F(CtrlAgentControllerTest, commandLineArgs) {
    char* argv[] = { const_cast<char*>("progName"),
                     const_cast<char*>("-c"),
                     const_cast<char*>(DControllerTest::CFG_TEST_FILE),
                     const_cast<char*>("-d") };
    int argc = 4;

    // Verify that verbose flag is false initially.
    EXPECT_TRUE(checkVerbose(false));

    // Verify that standard options can be parsed without error.
    EXPECT_NO_THROW(parseArgs(argc, argv));

    // Verify that verbose flag is true.
    EXPECT_TRUE(checkVerbose(true));

    // Verify configuration file name is correct.
    EXPECT_TRUE(checkConfigFileName(DControllerTest::CFG_TEST_FILE));

    // Verify that an unknown option is detected.
    char* argv2[] = { const_cast<char*>("progName"),
                      const_cast<char*>("-x") };
    argc = 2;
    EXPECT_THROW(parseArgs(argc, argv2), InvalidUsage);
}

// Tests application process creation and initialization.
// Verifies that the process can be successfully created and initialized.
TEST_F(CtrlAgentControllerTest, initProcessTesting) {
    ASSERT_NO_THROW(initProcess());
    EXPECT_TRUE(checkProcess());
}

// Tests launch and normal shutdown (stand alone mode).
// This creates an interval timer to generate a normal shutdown and then
// launches with a valid, stand-alone command line and no simulated errors.
TEST_F(CtrlAgentControllerTest, launchNormalShutdown) {
    // Write valid_agent_config and then run launch() for 1000 ms.
    time_duration elapsed_time;
    runWithConfig(valid_agent_config, 1000, elapsed_time);

Francis Dupont's avatar
Francis Dupont committed
237
    // Give a generous margin to accommodate slower test environs.
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
    EXPECT_TRUE(elapsed_time.total_milliseconds() >= 800 &&
                elapsed_time.total_milliseconds() <= 1300);
}

// Tests that the SIGINT triggers a normal shutdown.
TEST_F(CtrlAgentControllerTest, sigintShutdown) {
    // Setup to raise SIGHUP in 1 ms.
    TimedSignal sighup(*getIOService(), SIGINT, 1);

    // Write valid_agent_config and then run launch() for a maximum
    // of 1000 ms.
    time_duration elapsed_time;
    runWithConfig(valid_agent_config, 1000, elapsed_time);

    // Signaled shutdown should make our elapsed time much smaller than
Francis Dupont's avatar
Francis Dupont committed
253
    // the maximum run time.  Give generous margin to accommodate slow
254 255 256 257 258 259
    // test environs.
    EXPECT_TRUE(elapsed_time.total_milliseconds() < 300);
}

// Tests that the SIGTERM triggers a normal shutdown.
TEST_F(CtrlAgentControllerTest, sigtermShutdown) {
260
    // Setup to raise SIGTERM in 1 ms.
261 262 263 264 265 266 267
    TimedSignal sighup(*getIOService(), SIGTERM, 1);

    // Write valid_agent_config and then run launch() for a maximum of 1 s.
    time_duration elapsed_time;
    runWithConfig(valid_agent_config, 1000, elapsed_time);

    // Signaled shutdown should make our elapsed time much smaller than
Francis Dupont's avatar
Francis Dupont committed
268
    // the maximum run time.  Give generous margin to accommodate slow
269 270 271 272
    // test environs.
    EXPECT_TRUE(elapsed_time.total_milliseconds() < 300);
}

273 274
// Tests that the sockets settings are updated upon successful reconfiguration.
TEST_F(CtrlAgentControllerTest, successfulConfigUpdate) {
Josh Soref's avatar
Josh Soref committed
275
    // This configuration should be used to override the initial configuration.
276 277 278 279 280
    const char* second_config =
        "{"
        "  \"http-host\": \"127.0.0.1\","
        "  \"http-port\": 8080,"
        "  \"control-sockets\": {"
281
        "    \"dhcp4\": {"
282 283 284
        "      \"socket-type\": \"unix\","
        "      \"socket-name\": \"/second/dhcp4/socket\""
        "    },"
285
        "    \"dhcp6\": {"
286 287 288 289 290 291
        "      \"socket-type\": \"unix\","
        "      \"socket-name\": \"/second/dhcp6/socket\""
        "    }"
        "  }"
        "}";

292
    // Schedule reconfiguration.
293
    scheduleTimedWrite(second_config, 100);
294
    // Schedule SIGHUP signal to trigger reconfiguration.
295 296
    TimedSignal sighup(*getIOService(), SIGHUP, 200);

297
    // Start the server.
298 299 300 301 302 303
    time_duration elapsed_time;
    runWithConfig(valid_agent_config, 500, elapsed_time);

    CtrlAgentCfgContextPtr ctx = getCtrlAgentCfgContext();
    ASSERT_TRUE(ctx);

304
    // The server should now hold the new listener configuration.
305 306 307
    EXPECT_EQ("127.0.0.1", ctx->getHttpHost());
    EXPECT_EQ(8080, ctx->getHttpPort());

308
    // The forwarding configuration should have been updated too.
309 310
    testUnixSocketInfo("dhcp4", "/second/dhcp4/socket");
    testUnixSocketInfo("dhcp6", "/second/dhcp6/socket");
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334

    CtrlAgentProcessPtr process = getCtrlAgentProcess();
    ASSERT_TRUE(process);

    // Check that the HTTP listener still exists after reconfiguration.
    ConstHttpListenerPtr listener = process->getHttpListener();
    ASSERT_TRUE(listener);
    EXPECT_TRUE(process->isListening());

    // The listener should have been reconfigured to use new address and port.
    EXPECT_EQ("127.0.0.1", listener->getLocalAddress().toText());
    EXPECT_EQ(8080, listener->getLocalPort());
}

// Tests that the server continues to use an old configuration when the listener
// reconfiguration is unsuccessful.
TEST_F(CtrlAgentControllerTest, unsuccessfulConfigUpdate) {
    // This is invalid configuration. We're using restricted port number and
    // IP address of 1.1.1.1.
    const char* second_config =
        "{"
        "  \"http-host\": \"1.1.1.1\","
        "  \"http-port\": 1,"
        "  \"control-sockets\": {"
335
        "    \"dhcp4\": {"
336 337 338
        "      \"socket-type\": \"unix\","
        "      \"socket-name\": \"/second/dhcp4/socket\""
        "    },"
339
        "    \"dhcp6\": {"
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
        "      \"socket-type\": \"unix\","
        "      \"socket-name\": \"/second/dhcp6/socket\""
        "    }"
        "  }"
        "}";

    // Schedule reconfiguration.
    scheduleTimedWrite(second_config, 100);
    // Schedule SIGHUP signal to trigger reconfiguration.
    TimedSignal sighup(*getIOService(), SIGHUP, 200);

    // Start the server.
    time_duration elapsed_time;
    runWithConfig(valid_agent_config, 500, elapsed_time);

    CtrlAgentCfgContextPtr ctx = getCtrlAgentCfgContext();
    ASSERT_TRUE(ctx);

    // The reconfiguration should have been unsuccessful, and the server should
    // still use the original configuration.
    EXPECT_EQ("127.0.0.1", ctx->getHttpHost());
    EXPECT_EQ(8081, ctx->getHttpPort());

    // Same for forwarding.
364 365
    testUnixSocketInfo("dhcp4", "/first/dhcp4/socket");
    testUnixSocketInfo("dhcp6", "/first/dhcp6/socket");
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382

    CtrlAgentProcessPtr process = getCtrlAgentProcess();
    ASSERT_TRUE(process);

    // We should still be using an original listener.
    ConstHttpListenerPtr listener = process->getHttpListener();
    ASSERT_TRUE(listener);
    EXPECT_TRUE(process->isListening());

    EXPECT_EQ("127.0.0.1", listener->getLocalAddress().toText());
    EXPECT_EQ(8081, listener->getLocalPort());
}

// Tests that it is possible to update the configuration in such a way that the
// listener configuration remains the same. The server should continue using the
// listener instance it has been using prior to the reconfiguration.
TEST_F(CtrlAgentControllerTest, noListenerChange) {
Josh Soref's avatar
Josh Soref committed
383
    // This configuration should be used to override the initial configuration.
384 385 386 387 388
    const char* second_config =
        "{"
        "  \"http-host\": \"127.0.0.1\","
        "  \"http-port\": 8081,"
        "  \"control-sockets\": {"
389
        "    \"dhcp4\": {"
390 391 392
        "      \"socket-type\": \"unix\","
        "      \"socket-name\": \"/second/dhcp4/socket\""
        "    },"
393
        "    \"dhcp6\": {"
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
        "      \"socket-type\": \"unix\","
        "      \"socket-name\": \"/second/dhcp6/socket\""
        "    }"
        "  }"
        "}";

    // Schedule reconfiguration.
    scheduleTimedWrite(second_config, 100);
    // Schedule SIGHUP signal to trigger reconfiguration.
    TimedSignal sighup(*getIOService(), SIGHUP, 200);

    // Start the server.
    time_duration elapsed_time;
    runWithConfig(valid_agent_config, 500, elapsed_time);

    CtrlAgentCfgContextPtr ctx = getCtrlAgentCfgContext();
    ASSERT_TRUE(ctx);

    // The server should use a correct listener configuration.
    EXPECT_EQ("127.0.0.1", ctx->getHttpHost());
    EXPECT_EQ(8081, ctx->getHttpPort());

    // The forwarding configuration should have been updated.
417 418
    testUnixSocketInfo("dhcp4", "/second/dhcp4/socket");
    testUnixSocketInfo("dhcp6", "/second/dhcp6/socket");
419 420 421 422 423 424 425 426 427 428 429

    CtrlAgentProcessPtr process = getCtrlAgentProcess();
    ASSERT_TRUE(process);

    // The listener should keep listening.
    ConstHttpListenerPtr listener = process->getHttpListener();
    ASSERT_TRUE(listener);
    EXPECT_TRUE(process->isListening());

    EXPECT_EQ("127.0.0.1", listener->getLocalAddress().toText());
    EXPECT_EQ(8081, listener->getLocalPort());
430 431
}

432 433 434 435 436 437 438 439 440
// Tests that registerCommands actually registers anything.
TEST_F(CtrlAgentControllerTest, registeredCommands) {
    ASSERT_NO_THROW(initProcess());
    EXPECT_TRUE(checkProcess());

    // The framework available makes it very difficult to test the actual
    // code as CtrlAgentController is not initialized the same way it is
    // in production code. In particular, the way CtrlAgentController
    // is initialized in tests does not call registerCommands().
Josh Soref's avatar
Josh Soref committed
441
    // This is a crude workaround for this problem. Proper solution should
442 443 444 445 446 447 448 449 450 451
    // be developed sooner rather than later.
    const DControllerBasePtr& base = getController();
    const CtrlAgentControllerPtr& ctrl =
        boost::dynamic_pointer_cast<CtrlAgentController>(base);
    ASSERT_TRUE(ctrl);
    ctrl->registerCommands();

    // Check that the following command are really available.
    checkCommandRegistered("build-report");
    checkCommandRegistered("config-get");
452
    checkCommandRegistered("config-reload");
453
    checkCommandRegistered("config-set");
454 455 456 457
    checkCommandRegistered("config-test");
    checkCommandRegistered("config-write");
    checkCommandRegistered("list-commands");
    checkCommandRegistered("shutdown");
458
    checkCommandRegistered("status-get");
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
    checkCommandRegistered("version-get");

    ctrl->deregisterCommands();
}

// Tests that config-write really writes a config file that contains
// Control-agent configuration and not some other random nonsense.
TEST_F(CtrlAgentControllerTest, configWrite) {
    ASSERT_NO_THROW(initProcess());
    EXPECT_TRUE(checkProcess());

    // The framework available makes it very difficult to test the actual
    // code as CtrlAgentController is not initialized the same way it is
    // in production code. In particular, the way CtrlAgentController
    // is initialized in tests does not call registerCommands().
Josh Soref's avatar
Josh Soref committed
474
    // This is a crude workaround for this problem. Proper solution should
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
    // be developed sooner rather than later.
    const DControllerBasePtr& base = getController();
    const CtrlAgentControllerPtr& ctrl
        = boost::dynamic_pointer_cast<CtrlAgentController>(base);
    ASSERT_TRUE(ctrl);
    // Now clean up after ourselves.
    ctrl->registerCommands();

    // First, build the command:
    string file = string(TEST_DATA_BUILDDIR) + string("/config-write.json");
    string cmd_txt = "{ \"command\": \"config-write\" }";
    ConstElementPtr cmd = Element::fromJSON(cmd_txt);
    ConstElementPtr params = Element::fromJSON("{\"filename\": \"" + file + "\" }");
    CtrlAgentCommandMgr& mgr_ =  CtrlAgentCommandMgr::instance();

    // Send the command
    ConstElementPtr answer = mgr_.handleCommand("config-write", params, cmd);

    // Check that the command was successful
    checkAnswer(answer, isc::config::CONTROL_RESULT_SUCCESS);

    // Now check that the file is there.
    ifstream f(file.c_str());
    ASSERT_TRUE(f.good());

    // Now that's some rough check that the the config written really contains
    // something that looks like Control-agent configuration.
    ConstElementPtr from_file = Element::fromJSONFile(file, true);
    ASSERT_TRUE(from_file);
    ConstElementPtr ca = from_file->get("Control-agent");
    ASSERT_TRUE(ca);
    EXPECT_TRUE(ca->get("control-sockets"));
    EXPECT_TRUE(ca->get("hooks-libraries"));
    EXPECT_TRUE(ca->get("http-host"));
    EXPECT_TRUE(ca->get("http-port"));

    // Remove the file.
    ::remove(file.c_str());

    // Now clean up after ourselves.
    ctrl->deregisterCommands();
}

518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 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 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
// Tests if config-reload attempts to reload a file and reports that the
// file is missing.
TEST_F(CtrlAgentControllerTest, configReloadMissingFile) {
    ASSERT_NO_THROW(initProcess());
    EXPECT_TRUE(checkProcess());

    // The framework available makes it very difficult to test the actual
    // code as CtrlAgentController is not initialized the same way it is
    // in production code. In particular, the way CtrlAgentController
    // is initialized in tests does not call registerCommands().
    // This is a crude workaround for this problem. Proper solution should
    // be developed sooner rather than later.
    const DControllerBasePtr& base = getController();
    const CtrlAgentControllerPtr& ctrl
        = boost::dynamic_pointer_cast<CtrlAgentController>(base);
    ASSERT_TRUE(ctrl);
    // Now clean up after ourselves.
    ctrl->registerCommands();

    // This is normally set to whatever value is passed to -c when the server is
    // started, but we're not starting it that way, so need to set it by hand.
    getController()->setConfigFile("does-not-exist.json");

    // Build and execute the command.
    string cmd_txt = "{ \"command\": \"config-reload\" }";
    ConstElementPtr cmd = Element::fromJSON(cmd_txt);
    ConstElementPtr params;
    ConstElementPtr answer;
    answer = CtrlAgentCommandMgr::instance().handleCommand("config-reload",
                                                           params, cmd);

    // Verify the reload was rejected.
    string expected = "[ { \"result\": 1, \"text\": "
        "\"Configuration parsing failed: "
        "Unable to open file does-not-exist.json\" } ]";
    EXPECT_EQ(expected, answer->str());

    // Now clean up after ourselves.
    ctrl->deregisterCommands();
}

// Tests if config-reload attempts to reload a file and reports that the
// file is not a valid JSON.
TEST_F(CtrlAgentControllerTest, configReloadBrokenFile) {
    ASSERT_NO_THROW(initProcess());
    EXPECT_TRUE(checkProcess());

    // The framework available makes it very difficult to test the actual
    // code as CtrlAgentController is not initialized the same way it is
    // in production code. In particular, the way CtrlAgentController
    // is initialized in tests does not call registerCommands().
    // This is a crude workaround for this problem. Proper solution should
    // be developed sooner rather than later.
    const DControllerBasePtr& base = getController();
    const CtrlAgentControllerPtr& ctrl
        = boost::dynamic_pointer_cast<CtrlAgentController>(base);
    ASSERT_TRUE(ctrl);
    // Now clean up after ourselves.
    ctrl->registerCommands();

    // This is normally set to whatever value is passed to -c when the server is
    // started, but we're not starting it that way, so need to set it by hand.
    getController()->setConfigFile("testbad.json");

    // Although Kea is smart, its AI routines are not smart enough to handle
    // this one... at least not yet.
    ofstream f("testbad.json", ios::trunc);
    f << "bla bla bla...";
    f.close();

    // Build and execute the command.
    string cmd_txt = "{ \"command\": \"config-reload\" }";
    ConstElementPtr cmd = Element::fromJSON(cmd_txt);
    ConstElementPtr params;
    ConstElementPtr answer;
    answer = CtrlAgentCommandMgr::instance().handleCommand("config-reload",
                                                           params, cmd);

    // Verify the reload was rejected.
    string expected = "[ { \"result\": 1, \"text\": "
        "\"Configuration parsing failed: "
        "testbad.json:1.1: Invalid character: b\" } ]";
    EXPECT_EQ(expected, answer->str());

    // Remove the file.
    ::remove("testbad.json");

    // Now clean up after ourselves.
    ctrl->deregisterCommands();
}

// Tests if config-reload attempts to reload a file and reports that the
// file is missing.
TEST_F(CtrlAgentControllerTest, configReloadFileValid) {
    ASSERT_NO_THROW(initProcess());
    EXPECT_TRUE(checkProcess());

    // The framework available makes it very difficult to test the actual
    // code as CtrlAgentController is not initialized the same way it is
    // in production code. In particular, the way CtrlAgentController
    // is initialized in tests does not call registerCommands().
    // This is a crude workaround for this problem. Proper solution should
    // be developed sooner rather than later.
    const DControllerBasePtr& base = getController();
    const CtrlAgentControllerPtr& ctrl
        = boost::dynamic_pointer_cast<CtrlAgentController>(base);
    ASSERT_TRUE(ctrl);
    // Now clean up after ourselves.
    ctrl->registerCommands();

    // This is normally set to whatever value is passed to -c when the server is
    // started, but we're not starting it that way, so need to set it by hand.
    getController()->setConfigFile("testvalid.json");

    // Ok, enough fooling around. Let's create a valid config.
    ofstream f("testvalid.json", ios::trunc);
    f << "{ \"Control-agent\": "
      << string(valid_agent_config)
      << " }" << endl;
    f.close();

    // Build and execute the command.
    string cmd_txt = "{ \"command\": \"config-reload\" }";
    ConstElementPtr cmd = Element::fromJSON(cmd_txt);
    ConstElementPtr params;
    ConstElementPtr answer;
    answer = CtrlAgentCommandMgr::instance().handleCommand("config-reload",
                                                           params, cmd);


    // Verify the reload was successful.
    string expected = "[ { \"result\": 0, \"text\": "
        "\"Configuration applied successfully.\" } ]";
    EXPECT_EQ(expected, answer->str());

    // Check that the config was indeed applied?

    // Remove the file.
656
    ::remove("testvalid.json");
657 658 659 660 661

    // Now clean up after ourselves.
    ctrl->deregisterCommands();
}

662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
// Tests that status-get returns expected info (pid, uptime and reload).
TEST_F(CtrlAgentControllerTest, statusGet) {
    // Start the server.
    time_duration elapsed_time;
    runWithConfig(valid_agent_config, 500, elapsed_time);

    const DControllerBasePtr& ctrl = getController();
    ConstElementPtr response;
    ASSERT_NO_THROW(response = ctrl->statusGetHandler("status-get", ConstElementPtr()));
    ASSERT_TRUE(response);
    ASSERT_EQ(Element::map, response->getType());
    EXPECT_EQ(2, response->size());
    ConstElementPtr result = response->get("result");
    ASSERT_TRUE(result);
    ASSERT_EQ(Element::integer, result->getType());
    EXPECT_EQ(0, result->intValue());
    ConstElementPtr arguments = response->get("arguments");
    ASSERT_EQ(Element::map, arguments->getType());
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697

    // The returned pid should be the pid of our process.
    auto found_pid = arguments->get("pid");
    ASSERT_TRUE(found_pid);
    EXPECT_EQ(static_cast<int64_t>(getpid()), found_pid->intValue());

    // It is hard to check the actual uptime (and reload) as it is based
    // on current time. Let's just make sure it is within a reasonable
    // range.
    auto found_uptime = arguments->get("uptime");
    ASSERT_TRUE(found_uptime);
    EXPECT_LE(found_uptime->intValue(), 5);
    EXPECT_GE(found_uptime->intValue(), 0);

    auto found_reload = arguments->get("reload");
    ASSERT_TRUE(found_reload);
    EXPECT_LE(found_reload->intValue(), 5);
    EXPECT_GE(found_reload->intValue(), 0);
698 699
}

700
}