ctrl_dhcp6_srv_unittest.cc 62 KB
Newer Older
1
// Copyright (C) 2012-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

#include <config.h>
8

Francis Dupont's avatar
Francis Dupont committed
9
#include <asiolink/io_address.h>
10
#include <cc/command_interpreter.h>
11
#include <config/command_mgr.h>
12
#include <dhcp/libdhcp++.h>
Tomek Mrugalski's avatar
Tomek Mrugalski committed
13
#include <dhcpsrv/cfgmgr.h>
Francis Dupont's avatar
Francis Dupont committed
14 15
#include <dhcpsrv/lease.h>
#include <dhcpsrv/lease_mgr_factory.h>
16
#include <dhcp6/ctrl_dhcp6_srv.h>
17
#include <dhcp6/tests/dhcp6_test_utils.h>
18
#include <hooks/hooks_manager.h>
19
#include <log/logger_support.h>
Francis Dupont's avatar
Francis Dupont committed
20
#include <stats/stats_mgr.h>
21
#include <testutils/io_utils.h>
22
#include <testutils/unix_control_client.h>
23
#include <testutils/sandbox.h>
24
#include <util/boost_time_utils.h>
25 26 27

#include "marker_file.h"
#include "test_libraries.h"
28

29
#include <boost/scoped_ptr.hpp>
30 31
#include <gtest/gtest.h>

32 33 34
#include <iomanip>
#include <sstream>

35
#include <sys/select.h>
36
#include <sys/stat.h>
37
#include <sys/ioctl.h>
38
#include <cstdlib>
39

40 41
#include <thread>

42
using namespace std;
43
using namespace isc;
Francis Dupont's avatar
Francis Dupont committed
44
using namespace isc::asiolink;
45
using namespace isc::config;
46 47 48 49
using namespace isc::data;
using namespace isc::dhcp;
using namespace isc::dhcp::test;
using namespace isc::hooks;
Francis Dupont's avatar
Francis Dupont committed
50
using namespace isc::stats;
51
using namespace isc::test;
52 53 54

namespace {

55 56 57 58
/// @brief Simple RAII class which stops IO service upon destruction
/// of the object.
class IOServiceWork {
public:
59

60 61 62
    /// @brief Constructor.
    ///
    /// @param io_service Pointer to the IO service to be stopped.
63
    explicit IOServiceWork(const IOServicePtr& io_service)
64 65 66 67 68 69 70 71 72
        : io_service_(io_service) {
    }

    /// @brief Destructor.
    ///
    /// Stops IO service.
    ~IOServiceWork() {
        io_service_->stop();
    }
73

74 75 76 77 78 79
private:

    /// @brief Pointer to the IO service to be stopped upon destruction.
    IOServicePtr io_service_;

};
80

81
class NakedControlledDhcpv6Srv: public ControlledDhcpv6Srv {
82
    // "Naked" DHCPv6 server, exposes internal fields
83
public:
84
    NakedControlledDhcpv6Srv():ControlledDhcpv6Srv(DHCP6_SERVER_PORT + 10000) {
Francis Dupont's avatar
Francis Dupont committed
85
        CfgMgr::instance().setFamily(AF_INET6);
86 87
    }

88 89
    /// Expose internal methods for the sake of testing
    using Dhcpv6Srv::receivePacket;
90
    using Dhcpv6Srv::network_state_;
91 92
};

93
/// @brief Default control connection timeout.
94
const size_t DEFAULT_CONNECTION_TIMEOUT = 10000;
95

96
class CtrlDhcpv6SrvTest : public BaseServerTest {
97
public:
98 99
    CtrlDhcpv6SrvTest()
        : BaseServerTest() {
100
        reset();
101 102
    }

103
    virtual ~CtrlDhcpv6SrvTest() {
Francis Dupont's avatar
Francis Dupont committed
104 105
        LeaseMgrFactory::destroy();
        StatsMgr::instance().removeAll();
106
        CommandMgr::instance().deregisterAll();
107 108
        CommandMgr::instance().setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);

109
        reset();
110
    };
111

112

113 114 115 116
    /// @brief Reset hooks data
    ///
    /// Resets the data for the hooks-related portion of the test by ensuring
    /// that no libraries are loaded and that any marker files are deleted.
117
    virtual void reset() {
118 119 120 121
        // Unload any previously-loaded libraries.
        HooksManager::unloadLibraries();

        // Get rid of any marker files.
122 123
        static_cast<void>(remove(LOAD_MARKER_FILE));
        static_cast<void>(remove(UNLOAD_MARKER_FILE));
124 125 126 127 128 129 130 131
        IfaceMgr::instance().deleteAllExternalSockets();
        CfgMgr::instance().clear();
    }

};

class CtrlChannelDhcpv6SrvTest : public CtrlDhcpv6SrvTest {
public:
132
    isc::test::Sandbox sandbox;
133 134

    /// @brief Path to the UNIX socket being used to communicate with the server
135
    std::string socket_path_;
136 137

    /// @brief Pointer to the tested server object
138 139
    boost::shared_ptr<NakedControlledDhcpv6Srv> server_;

140 141 142
    /// @brief Default constructor
    ///
    /// Sets socket path to its default value.
143
    CtrlChannelDhcpv6SrvTest() {
144 145 146 147
        const char* env = getenv("KEA_SOCKET_TEST_DIR");
        if (env) {
            socket_path_ = string(env) + "/kea6.sock";
        } else {
148
            socket_path_ = sandbox.join("/kea6.sock");
149
        }
150 151 152
        reset();
    }

153
    /// @brief Destructor
154 155 156 157 158
    ~CtrlChannelDhcpv6SrvTest() {
        server_.reset();
        reset();
    };

159 160 161 162 163 164 165 166
    /// @brief Returns pointer to the server's IO service.
    ///
    /// @return Pointer to the server's IO service or null pointer if the server
    /// hasn't been created.
    IOServicePtr getIOService() {
        return (server_ ? server_->getIOService() : IOServicePtr());
    }

167
    void createUnixChannelServer() {
168
        static_cast<void>(::remove(socket_path_.c_str()));
169 170 171

        // Just a simple config. The important part here is the socket
        // location information.
172
        std::string header =
173 174 175 176
            "{"
            "    \"interfaces-config\": {"
            "        \"interfaces\": [ \"*\" ]"
            "    },"
Francis Dupont's avatar
Francis Dupont committed
177 178 179 180 181
            "    \"expired-leases-processing\": {"
            "         \"reclaim-timer-wait-time\": 60,"
            "         \"hold-reclaimed-time\": 500,"
            "         \"flush-reclaimed-timer-wait-time\": 60"
            "    },"
182 183 184 185 186 187
            "    \"rebind-timer\": 2000, "
            "    \"renew-timer\": 1000, "
            "    \"subnet6\": [ ],"
            "    \"valid-lifetime\": 4000,"
            "    \"control-socket\": {"
            "        \"socket-type\": \"unix\","
188 189 190 191
            "        \"socket-name\": \"";

        std::string footer =
            "\"    },"
192 193 194 195
            "    \"lease-database\": {"
            "       \"type\": \"memfile\", \"persist\": false }"
            "}";

196 197 198 199
        // Fill in the socket-name value with socket_path_  to
        // make the actual configuration text.
        std::string config_txt = header + socket_path_  + footer;

200 201
        ASSERT_NO_THROW(server_.reset(new NakedControlledDhcpv6Srv()));

202
        ConstElementPtr config;
203
        ASSERT_NO_THROW(config = parseDHCP6(config_txt));
204
        ConstElementPtr answer = server_->processConfig(config);
205 206 207 208 209 210

        // Commit the configuration so any subsequent reconfigurations
        // will only close the command channel if its configuration has
        // changed.
        CfgMgr::instance().commit();

211 212 213
        ASSERT_TRUE(answer);

        int status = 0;
214 215 216
        ConstElementPtr txt = isc::config::parseAnswer(status, answer);
        // This should succeed. If not, print the error message.
        ASSERT_EQ(0, status) << txt->str();
217 218 219 220 221 222 223 224

        // Now check that the socket was indeed open.
        ASSERT_GT(isc::config::CommandMgr::instance().getControlSocketFD(), -1);
    }

    /// @brief Reset
    void reset() {
        CtrlDhcpv6SrvTest::reset();
225 226

        // Remove unix socket file
227
        static_cast<void>(::remove(socket_path_.c_str()));
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
    }

    /// @brief Conducts a command/response exchange via UnixCommandSocket
    ///
    /// This method connects to the given server over the given socket path.
    /// If successful, it then sends the given command and retrieves the
    /// server's response.  Note that it calls the server's receivePacket()
    /// method where needed to cause the server to process IO events on
    /// control channel the control channel sockets.
    ///
    /// @param command the command text to execute in JSON form
    /// @param response variable into which the received response should be
    /// placed.
    void sendUnixCommand(const std::string& command, std::string& response) {
        response = "";
        boost::scoped_ptr<UnixControlClient> client;
        client.reset(new UnixControlClient());
        ASSERT_TRUE(client);

247 248
        // Connect to the server. This is expected to trigger server's acceptor
        // handler when IOService::poll() is run.
249
        ASSERT_TRUE(client->connectToServer(socket_path_));
250
        ASSERT_NO_THROW(getIOService()->poll());
251

252 253 254
        // Send the command. This will trigger server's handler which receives
        // data over the unix domain socket. The server will start sending
        // response to the client.
255
        ASSERT_TRUE(client->sendCommand(command));
256
        ASSERT_NO_THROW(getIOService()->poll());
257 258 259 260 261 262 263 264

        // Read the response generated by the server. Note that getResponse
        // only fails if there an IO error or no response data was present.
        // It is not based on the response content.
        ASSERT_TRUE(client->getResponse(response));

        // Now disconnect and process the close event
        client->disconnectFromServer();
265 266

        ASSERT_NO_THROW(getIOService()->poll());
267
    }
268 269 270 271 272 273 274 275 276 277

    /// @brief Checks response for list-commands
    ///
    /// This method checks if the list-commands response is generally sane
    /// and whether specified command is mentioned in the response.
    ///
    /// @param rsp response sent back by the server
    /// @param command command expected to be on the list.
    void checkListCommands(const ConstElementPtr& rsp, const std::string& command) {
        ConstElementPtr params;
Francis Dupont's avatar
Francis Dupont committed
278
        int status_code = -1;
279 280 281 282 283 284
        EXPECT_NO_THROW(params = parseAnswer(status_code, rsp));
        EXPECT_EQ(CONTROL_RESULT_SUCCESS, status_code);
        ASSERT_TRUE(params);
        ASSERT_EQ(Element::list, params->getType());

        int cnt = 0;
Francis Dupont's avatar
Francis Dupont committed
285
        for (size_t i = 0; i < params->size(); ++i) {
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
            string tmp = params->get(i)->stringValue();
            if (tmp == command) {
                // Command found, but that's not enough. Need to continue working
                // through the list to see if there are no duplicates.
                cnt++;
            }
        }

        // Exactly one command on the list is expected.
        EXPECT_EQ(1, cnt) << "Command " << command << " not found";
    }

    /// @brief Check if the answer for write-config command is correct
    ///
    /// @param response_txt response in text form (as read from the control socket)
    /// @param exp_status expected status (0 success, 1 failure)
    /// @param exp_txt for success cases this defines the expected filename,
    ///                for failure cases this defines the expected error message
    void checkConfigWrite(const std::string& response_txt, int exp_status,
                          const std::string& exp_txt = "") {

        ConstElementPtr rsp;
        EXPECT_NO_THROW(rsp = Element::fromJSON(response_txt));
        ASSERT_TRUE(rsp);

        int status;
        ConstElementPtr params = parseAnswer(status, rsp);
        EXPECT_EQ(exp_status, status);

        if (exp_status == CONTROL_RESULT_SUCCESS) {
            // Let's check couple things...

            // The parameters must include filename
            ASSERT_TRUE(params);
            ASSERT_TRUE(params->get("filename"));
Francis Dupont's avatar
Francis Dupont committed
321
            ASSERT_EQ(Element::string, params->get("filename")->getType());
322 323 324 325 326
            EXPECT_EQ(exp_txt, params->get("filename")->stringValue());

            // The parameters must include size. And the size
            // must indicate some content.
            ASSERT_TRUE(params->get("size"));
Francis Dupont's avatar
Francis Dupont committed
327
            ASSERT_EQ(Element::integer, params->get("size")->getType());
328 329 330 331 332 333 334 335 336 337 338
            int64_t size = params->get("size")->intValue();
            EXPECT_LE(1, size);

            // Now check if the file is really there and suitable for
            // opening.
            ifstream f(exp_txt, ios::binary | ios::ate);
            ASSERT_TRUE(f.good());

            // Now check that it is the correct size as reported.
            EXPECT_EQ(size, static_cast<int64_t>(f.tellg()));

339 340 341
            // Finally, check that it's really a JSON.
            ElementPtr from_file = Element::fromJSONFile(exp_txt);
            ASSERT_TRUE(from_file);
342 343 344 345 346 347 348 349 350 351 352
        } else if (exp_status == CONTROL_RESULT_ERROR) {

            // Let's check if the reason for failure was given.
            ConstElementPtr text = rsp->get("text");
            ASSERT_TRUE(text);
            ASSERT_EQ(Element::string, text->getType());
            EXPECT_EQ(exp_txt, text->stringValue());
        } else {
            ADD_FAILURE() << "Invalid expected status: " << exp_status;
        }
    }
353

354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
    /// @brief Handler for long command.
    ///
    /// It checks whether the received command is equal to the one specified
    /// as an argument.
    ///
    /// @param expected_command String representing an expected command.
    /// @param command_name Command name received by the handler.
    /// @param arguments Command arguments received by the handler.
    ///
    /// @returns Success answer.
    static ConstElementPtr
    longCommandHandler(const std::string& expected_command,
                       const std::string& command_name,
                       const ConstElementPtr& arguments) {
        // The handler is called with a command name and the structure holding
        // command arguments. We have to rebuild the command from those
        // two arguments so as it can be compared against expected_command.
        ElementPtr entire_command = Element::createMap();
        entire_command->set("command", Element::create(command_name));
        entire_command->set("arguments", (arguments));

        // The rebuilt command will have a different order of parameters so
        // let's parse expected_command back to JSON to guarantee that
        // both structures are built using the same order.
        EXPECT_EQ(Element::fromJSON(expected_command)->str(),
                  entire_command->str());
        return (createAnswer(0, "long command received ok"));
    }

383
    /// @brief Command handler which generates long response
384 385 386 387
    ///
    /// This handler generates a large response (over 400kB). It includes
    /// a list of randomly generated strings to make sure that the test
    /// can catch out of order delivery.
388 389 390
    static ConstElementPtr longResponseHandler(const std::string&,
                                               const ConstElementPtr&) {
        ElementPtr arguments = Element::createList();
391
        for (unsigned i = 0; i < 80000; ++i) {
392
            std::ostringstream s;
393
            s << std::setw(5) << i;
394
            arguments->add(Element::create(s.str()));
395 396 397
        }
        return (createAnswer(0, arguments));
    }
398 399 400 401
};

TEST_F(CtrlDhcpv6SrvTest, commands) {

402 403 404 405
    boost::scoped_ptr<ControlledDhcpv6Srv> srv;
    ASSERT_NO_THROW(
        srv.reset(new ControlledDhcpv6Srv(DHCP6_SERVER_PORT + 10000))
    );
406

407
    // Use empty parameters list
408 409 410
    ElementPtr params(new isc::data::MapElement());
    int rcode = -1;

411
    // Case 1: send bogus command
Tomek Mrugalski's avatar
Tomek Mrugalski committed
412
    ConstElementPtr result = ControlledDhcpv6Srv::processCommand("blah", params);
413
    ConstElementPtr comment = parseAnswer(rcode, result);
414 415
    EXPECT_EQ(1, rcode); // expect failure (no such command as blah)

416
    // Case 2: send shutdown command without any parameters
Tomek Mrugalski's avatar
Tomek Mrugalski committed
417
    result = ControlledDhcpv6Srv::processCommand("shutdown", params);
418
    comment = parseAnswer(rcode, result);
419 420 421 422 423 424
    EXPECT_EQ(0, rcode); // expect success

    const pid_t pid(getpid());
    ConstElementPtr x(new isc::data::IntElement(pid));
    params->set("pid", x);

425
    // Case 3: send shutdown command with 1 parameter: pid
Tomek Mrugalski's avatar
Tomek Mrugalski committed
426
    result = ControlledDhcpv6Srv::processCommand("shutdown", params);
427 428
    comment = parseAnswer(rcode, result);
    EXPECT_EQ(0, rcode); // expect success
429 430
}

431
// Check that the "libreload" command will reload libraries
432 433
TEST_F(CtrlChannelDhcpv6SrvTest, libreload) {
    createUnixChannelServer();
Tomek Mrugalski's avatar
Tomek Mrugalski committed
434

435 436 437 438 439
    // Ensure no marker files to start with.
    ASSERT_FALSE(checkMarkerFileExists(LOAD_MARKER_FILE));
    ASSERT_FALSE(checkMarkerFileExists(UNLOAD_MARKER_FILE));

    // Load two libraries
440 441 442
    HookLibsCollection libraries;
    libraries.push_back(make_pair(CALLOUT_LIBRARY_1, ConstElementPtr()));
    libraries.push_back(make_pair(CALLOUT_LIBRARY_2, ConstElementPtr()));
443 444 445
    HooksManager::loadLibraries(libraries);

    // Check they are loaded.
446 447
    HookLibsCollection loaded_libraries =
        HooksManager::getLibraryInfo();
448 449 450
    ASSERT_TRUE(libraries == loaded_libraries);

    // ... which also included checking that the marker file created by the
451 452 453
    // load functions exists and holds the correct value (of "12" - the
    // first library appends "1" to the file, the second appends "2"). Also
    // check that the unload marker file does not yet exist.
454 455 456 457 458
    EXPECT_TRUE(checkMarkerFile(LOAD_MARKER_FILE, "12"));
    EXPECT_FALSE(checkMarkerFileExists(UNLOAD_MARKER_FILE));

    // Now execute the "libreload" command.  This should cause the libraries
    // to unload and to reload.
459 460 461 462 463
    std::string response;
    sendUnixCommand("{ \"command\": \"libreload\" }", response);
    EXPECT_EQ("{ \"result\": 0, "
              "\"text\": \"Hooks libraries successfully reloaded.\" }"
              , response);
464 465 466 467 468 469 470 471

    // Check that the libraries have unloaded and reloaded.  The libraries are
    // unloaded in the reverse order to which they are loaded.  When they load,
    // they should append information to the loading marker file.
    EXPECT_TRUE(checkMarkerFile(UNLOAD_MARKER_FILE, "21"));
    EXPECT_TRUE(checkMarkerFile(LOAD_MARKER_FILE, "1212"));
}

472 473 474 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
typedef std::map<std::string, isc::data::ConstElementPtr> ElementMap;

// This test checks which commands are registered by the DHCPv6 server.
TEST_F(CtrlDhcpv6SrvTest, commandsRegistration) {

    ConstElementPtr list_cmds = createCommand("list-commands");
    ConstElementPtr answer;

    // By default the list should be empty (except the standard list-commands
    // supported by the CommandMgr itself)
    EXPECT_NO_THROW(answer = CommandMgr::instance().processCommand(list_cmds));
    ASSERT_TRUE(answer);
    ASSERT_TRUE(answer->get("arguments"));
    EXPECT_EQ("[ \"list-commands\" ]", answer->get("arguments")->str());

    // Created server should register several additional commands.
    boost::scoped_ptr<ControlledDhcpv6Srv> srv;
    ASSERT_NO_THROW(
        srv.reset(new ControlledDhcpv6Srv(0));
    );

    EXPECT_NO_THROW(answer = CommandMgr::instance().processCommand(list_cmds));
    ASSERT_TRUE(answer);

    ASSERT_TRUE(answer->get("arguments"));
    std::string command_list = answer->get("arguments")->str();

    EXPECT_TRUE(command_list.find("\"list-commands\"") != string::npos);
    EXPECT_TRUE(command_list.find("\"build-report\"") != string::npos);
    EXPECT_TRUE(command_list.find("\"config-get\"") != string::npos);
    EXPECT_TRUE(command_list.find("\"config-set\"") != string::npos);
    EXPECT_TRUE(command_list.find("\"config-write\"") != string::npos);
    EXPECT_TRUE(command_list.find("\"leases-reclaim\"") != string::npos);
    EXPECT_TRUE(command_list.find("\"libreload\"") != string::npos);
    EXPECT_TRUE(command_list.find("\"server-tag-get\"") != string::npos);
507
    EXPECT_TRUE(command_list.find("\"server-update\"") != string::npos);
508 509 510 511 512 513 514 515 516 517 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
    EXPECT_TRUE(command_list.find("\"shutdown\"") != string::npos);
    EXPECT_TRUE(command_list.find("\"statistic-get\"") != string::npos);
    EXPECT_TRUE(command_list.find("\"statistic-get-all\"") != string::npos);
    EXPECT_TRUE(command_list.find("\"statistic-remove\"") != string::npos);
    EXPECT_TRUE(command_list.find("\"statistic-remove-all\"") != string::npos);
    EXPECT_TRUE(command_list.find("\"statistic-reset\"") != string::npos);
    EXPECT_TRUE(command_list.find("\"statistic-reset-all\"") != string::npos);
    EXPECT_TRUE(command_list.find("\"statistic-sample-age-set\"") != string::npos);
    EXPECT_TRUE(command_list.find("\"statistic-sample-age-set-all\"") != string::npos);
    EXPECT_TRUE(command_list.find("\"statistic-sample-count-set\"") != string::npos);
    EXPECT_TRUE(command_list.find("\"statistic-sample-count-set-all\"") != string::npos);
    EXPECT_TRUE(command_list.find("\"version-get\"") != string::npos);

    // Ok, and now delete the server. It should deregister its commands.
    srv.reset();

    // The list should be (almost) empty again.
    EXPECT_NO_THROW(answer = CommandMgr::instance().processCommand(list_cmds));
    ASSERT_TRUE(answer);
    ASSERT_TRUE(answer->get("arguments"));
    EXPECT_EQ("[ \"list-commands\" ]", answer->get("arguments")->str());
}

// Tests that the server properly responds to invalid commands sent
// via ControlChannel
TEST_F(CtrlChannelDhcpv6SrvTest, controlChannelNegative) {
    createUnixChannelServer();
    std::string response;

    sendUnixCommand("{ \"command\": \"bogus\" }", response);
    EXPECT_EQ("{ \"result\": 2,"
              " \"text\": \"'bogus' command not supported.\" }", response);

    sendUnixCommand("utter nonsense", response);
    EXPECT_EQ("{ \"result\": 1, "
              "\"text\": \"invalid first character u\" }",
              response);
}

// Tests that the server properly responds to shtudown command sent
// via ControlChannel
TEST_F(CtrlChannelDhcpv6SrvTest, controlChannelShutdown) {
    createUnixChannelServer();
    std::string response;

    sendUnixCommand("{ \"command\": \"shutdown\" }", response);
    EXPECT_EQ("{ \"result\": 0, \"text\": \"Shutting down.\" }",response);
}

557
// Check that the "config-set" command will replace current configuration
558
TEST_F(CtrlChannelDhcpv6SrvTest, configSet) {
559 560 561 562
    createUnixChannelServer();

    // Define strings to permutate the config arguments
    // (Note the line feeds makes errors easy to find)
563
    string set_config_txt = "{ \"command\": \"config-set\" \n";
564 565 566 567 568 569 570 571 572 573
    string args_txt = " \"arguments\": { \n";
    string dhcp6_cfg_txt =
        "    \"Dhcp6\": { \n"
        "        \"interfaces-config\": { \n"
        "            \"interfaces\": [\"*\"] \n"
        "        },   \n"
        "        \"preferred-lifetime\": 3000, \n"
        "        \"valid-lifetime\": 4000, \n"
        "        \"renew-timer\": 1000, \n"
        "        \"rebind-timer\": 2000, \n"
574 575 576 577 578 579
        "        \"lease-database\": { \n"
        "           \"type\": \"memfile\", \n"
        "           \"persist\":false, \n"
        "           \"lfc-interval\": 0  \n"
        "        }, \n"
        "        \"expired-leases-processing\": { \n"
580 581 582 583
        "            \"reclaim-timer-wait-time\": 0, \n"
        "            \"hold-reclaimed-time\": 0, \n"
        "            \"flush-reclaimed-timer-wait-time\": 0 \n"
        "        },"
584 585 586 587 588 589 590 591
        "        \"subnet6\": [ \n";
    string subnet1 =
        "               {\"subnet\": \"3002::/64\", \n"
        "                \"pools\": [{ \"pool\": \"3002::100-3002::200\" }]}\n";
    string subnet2 =
        "               {\"subnet\": \"3003::/64\", \n"
        "                \"pools\": [{ \"pool\": \"3003::100-3003::200\" }]}\n";
    string bad_subnet =
592
        "               {\"comment\": \"3005::/64\", \n"
593 594 595
        "                \"pools\": [{ \"pool\": \"3005::100-3005::200\" }]}\n";
    string subnet_footer =
        "          ] \n";
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
    string option_def =
        "    ,\"option-def\": [\n"
        "    {\n"
        "        \"name\": \"foo\",\n"
        "        \"code\": 163,\n"
        "        \"type\": \"uint32\",\n"
        "        \"array\": false,\n"
        "        \"record-types\": \"\",\n"
        "        \"space\": \"dhcp6\",\n"
        "        \"encapsulate\": \"\"\n"
        "    }\n"
        "]\n";
    string option_data =
        "    ,\"option-data\": [\n"
        "    {\n"
        "        \"name\": \"foo\",\n"
        "        \"code\": 163,\n"
        "        \"space\": \"dhcp6\",\n"
        "        \"csv-format\": true,\n"
        "        \"data\": \"12345\"\n"
        "    }\n"
        "]\n";
618 619 620 621 622 623 624 625 626
    string control_socket_header =
        "       ,\"control-socket\": { \n"
        "       \"socket-type\": \"unix\", \n"
        "       \"socket-name\": \"";
    string control_socket_footer =
        "\"   \n} \n";
    string logger_txt =
        "    \"Logging\": { \n"
        "        \"loggers\": [ { \n"
627 628
        "            \"name\": \"kea\", \n"
        "            \"severity\": \"FATAL\", \n"
629
        "            \"output_options\": [{ \n"
630
        "                \"output\": \"/dev/null\" \n"
631 632 633 634 635 636 637 638 639 640 641 642
        "            }] \n"
        "        }] \n"
        "    } \n";

    std::ostringstream os;

    // Create a valid config with all the parts should parse
    os << set_config_txt << ","
        << args_txt
        << dhcp6_cfg_txt
        << subnet1
        << subnet_footer
643 644
        << option_def
        << option_data
645 646 647 648 649
        << control_socket_header
        << socket_path_
        << control_socket_footer
        << "}\n"                      // close dhcp6
        << ","
650 651
        << logger_txt
        << "}}";
652

653
    // Send the config-set command
654 655 656 657 658 659 660 661 662 663 664 665
    std::string response;
    sendUnixCommand(os.str(), response);

    // Verify the configuration was successful.
    EXPECT_EQ("{ \"result\": 0, \"text\": \"Configuration successful.\" }",
              response);

    // Check that the config was indeed applied.
    const Subnet6Collection* subnets =
        CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getAll();
    EXPECT_EQ(1, subnets->size());

666 667 668
    OptionDefinitionPtr def = LibDHCP::getRuntimeOptionDef("dhcp6", 163);
    ASSERT_TRUE(def);

669 670 671 672 673 674 675 676 677 678 679
    // Create a config with malformed subnet that should fail to parse.
    os.str("");
    os << set_config_txt << ","
        << args_txt
        << dhcp6_cfg_txt
        << bad_subnet
        << subnet_footer
        << control_socket_header
        << socket_path_
        << control_socket_footer
        << "}\n"                      // close dhcp6
680
        "}}";
681

682
    // Send the config-set command
683 684 685 686
    sendUnixCommand(os.str(), response);

    // Should fail with a syntax error
    EXPECT_EQ("{ \"result\": 1, "
687 688
              "\"text\": \"subnet configuration failed: mandatory 'subnet' "
              "parameter is missing for a subnet being configured (<wire>:20:17)\" }",
689 690 691 692 693 694
              response);

    // Check that the config was not lost
    subnets = CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getAll();
    EXPECT_EQ(1, subnets->size());

695 696 697
    def = LibDHCP::getRuntimeOptionDef("dhcp6", 163);
    ASSERT_TRUE(def);

698
    // Create a valid config with two subnets and no command channel.
699
    // It should succeed, client should still receive the response
700 701 702 703 704 705 706 707 708
    os.str("");
    os << set_config_txt << ","
        << args_txt
        << dhcp6_cfg_txt
        << subnet1
        << ",\n"
        << subnet2
        << subnet_footer
        << "}\n"                      // close dhcp6
709
        << "}}";
710

711
    // Verify the control channel socket exists.
712 713
    ASSERT_TRUE(fileExists(socket_path_));

714
    // Send the config-set command.
715 716
    sendUnixCommand(os.str(), response);

717
    // Verify the control channel socket no longer exists.
718 719 720 721 722
    EXPECT_FALSE(fileExists(socket_path_));

    // With no command channel, should still receive the response.
    EXPECT_EQ("{ \"result\": 0, \"text\": \"Configuration successful.\" }",
              response);
723 724 725 726 727 728 729 730 731

    // Check that the config was not lost
    subnets = CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getAll();
    EXPECT_EQ(2, subnets->size());

    // Clean up after the test.
    CfgMgr::instance().clear();
}

732 733
// Tests if the server returns its configuration using config-get.
// Note there are separate tests that verify if toElement() called by the
Razvan Becheriu's avatar
Razvan Becheriu committed
734
// config-get handler are actually converting the configuration correctly.
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
TEST_F(CtrlChannelDhcpv6SrvTest, configGet) {
    createUnixChannelServer();
    std::string response;

    sendUnixCommand("{ \"command\": \"config-get\" }", response);
    ConstElementPtr rsp;

    // The response should be a valid JSON.
    EXPECT_NO_THROW(rsp = Element::fromJSON(response));
    ASSERT_TRUE(rsp);

    int status;
    ConstElementPtr cfg = parseAnswer(status, rsp);
    EXPECT_EQ(CONTROL_RESULT_SUCCESS, status);

    // Ok, now roughly check if the response seems legit.
    ASSERT_TRUE(cfg);
    ASSERT_EQ(Element::map, cfg->getType());
    EXPECT_TRUE(cfg->get("Dhcp6"));
}

756
// Verify that the "config-test" command will do what we expect.
757
TEST_F(CtrlChannelDhcpv6SrvTest, configTest) {
Francis Dupont's avatar
Francis Dupont committed
758 759 760 761
    createUnixChannelServer();

    // Define strings to permutate the config arguments
    // (Note the line feeds makes errors easy to find)
762
    string set_config_txt = "{ \"command\": \"config-set\" \n";
Francis Dupont's avatar
Francis Dupont committed
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
    string config_test_txt = "{ \"command\": \"config-test\" \n";
    string args_txt = " \"arguments\": { \n";
    string dhcp6_cfg_txt =
        "    \"Dhcp6\": { \n"
        "        \"interfaces-config\": { \n"
        "            \"interfaces\": [\"*\"] \n"
        "        },   \n"
        "        \"preferred-lifetime\": 3000, \n"
        "        \"valid-lifetime\": 4000, \n"
        "        \"renew-timer\": 1000, \n"
        "        \"rebind-timer\": 2000, \n"
        "        \"lease-database\": { \n"
        "           \"type\": \"memfile\", \n"
        "           \"persist\":false, \n"
        "           \"lfc-interval\": 0  \n"
        "        }, \n"
        "        \"expired-leases-processing\": { \n"
        "            \"reclaim-timer-wait-time\": 0, \n"
        "            \"hold-reclaimed-time\": 0, \n"
        "            \"flush-reclaimed-timer-wait-time\": 0 \n"
        "        },"
        "        \"subnet6\": [ \n";
    string subnet1 =
        "               {\"subnet\": \"3002::/64\", \n"
        "                \"pools\": [{ \"pool\": \"3002::100-3002::200\" }]}\n";
    string subnet2 =
        "               {\"subnet\": \"3003::/64\", \n"
        "                \"pools\": [{ \"pool\": \"3003::100-3003::200\" }]}\n";
    string bad_subnet =
792
        "               {\"comment\": \"3005::/64\", \n"
Francis Dupont's avatar
Francis Dupont committed
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
        "                \"pools\": [{ \"pool\": \"3005::100-3005::200\" }]}\n";
    string subnet_footer =
        "          ] \n";
    string control_socket_header =
        "       ,\"control-socket\": { \n"
        "       \"socket-type\": \"unix\", \n"
        "       \"socket-name\": \"";
    string control_socket_footer =
        "\"   \n} \n";
    string logger_txt =
        "    \"Logging\": { \n"
        "        \"loggers\": [ { \n"
        "            \"name\": \"kea\", \n"
        "            \"severity\": \"FATAL\", \n"
        "            \"output_options\": [{ \n"
        "                \"output\": \"/dev/null\" \n"
        "            }] \n"
        "        }] \n"
        "    } \n";

    std::ostringstream os;

    // Create a valid config with all the parts should parse
    os << set_config_txt << ","
        << args_txt
        << dhcp6_cfg_txt
        << subnet1
        << subnet_footer
        << control_socket_header
        << socket_path_
        << control_socket_footer
        << "}\n"                      // close dhcp6
        << ","
        << logger_txt
        << "}}";

829
    // Send the config-set command
Francis Dupont's avatar
Francis Dupont committed
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
    std::string response;
    sendUnixCommand(os.str(), response);

    // Verify the configuration was successful.
    EXPECT_EQ("{ \"result\": 0, \"text\": \"Configuration successful.\" }",
              response);

    // Check that the config was indeed applied.
    const Subnet6Collection* subnets =
        CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getAll();
    EXPECT_EQ(1, subnets->size());

    // Create a config with malformed subnet that should fail to parse.
    os.str("");
    os << config_test_txt << ","
        << args_txt
        << dhcp6_cfg_txt
        << bad_subnet
        << subnet_footer
        << control_socket_header
        << socket_path_
        << control_socket_footer
        << "}\n"                      // close dhcp6
        "}}";

    // Send the config-test command
    sendUnixCommand(os.str(), response);

    // Should fail with a syntax error
    EXPECT_EQ("{ \"result\": 1, "
860
              "\"text\": \"subnet configuration failed: mandatory 'subnet' parameter "
861
              "is missing for a subnet being configured (<wire>:20:17)\" }",
Francis Dupont's avatar
Francis Dupont committed
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
              response);

    // Check that the config was not lost
    subnets = CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getAll();
    EXPECT_EQ(1, subnets->size());

    // Create a valid config with two subnets and no command channel.
    os.str("");
    os << config_test_txt << ","
        << args_txt
        << dhcp6_cfg_txt
        << subnet1
        << ",\n"
        << subnet2
        << subnet_footer
        << "}\n"                      // close dhcp6
        << "}}";

880
    // Verify the control channel socket exists.
Francis Dupont's avatar
Francis Dupont committed
881 882
    ASSERT_TRUE(fileExists(socket_path_));

883
    // Send the config-test command.
Francis Dupont's avatar
Francis Dupont committed
884 885
    sendUnixCommand(os.str(), response);

886
    // Verify the control channel socket still exists.
Francis Dupont's avatar
Francis Dupont committed
887 888 889
    EXPECT_TRUE(fileExists(socket_path_));

    // Verify the configuration was successful.
890
    EXPECT_EQ("{ \"result\": 0, \"text\": \"Configuration seems sane. "
Francis Dupont's avatar
Francis Dupont committed
891 892
              "Control-socket, hook-libraries, and D2 configuration were "
              "sanity checked, but not applied.\" }",
Francis Dupont's avatar
Francis Dupont committed
893 894 895 896 897 898 899 900 901 902
              response);

    // Check that the config was not applied.
    subnets = CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getAll();
    EXPECT_EQ(1, subnets->size());

    // Clean up after the test.
    CfgMgr::instance().clear();
}

Francis Dupont's avatar
Francis Dupont committed
903
// This test verifies that the DHCP server handles version-get commands
Razvan Becheriu's avatar
Razvan Becheriu committed
904
TEST_F(CtrlChannelDhcpv6SrvTest, getVersion) {
Francis Dupont's avatar
Francis Dupont committed
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
    createUnixChannelServer();

    std::string response;

    // Send the version-get command
    sendUnixCommand("{ \"command\": \"version-get\" }", response);
    EXPECT_TRUE(response.find("\"result\": 0") != string::npos);
    EXPECT_TRUE(response.find("log4cplus") != string::npos);
    EXPECT_FALSE(response.find("GTEST_VERSION") != string::npos);

    // Send the build-report command
    sendUnixCommand("{ \"command\": \"build-report\" }", response);
    EXPECT_TRUE(response.find("\"result\": 0") != string::npos);
    EXPECT_TRUE(response.find("GTEST_VERSION") != string::npos);
}

921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
// This test verifies that the DHCP server handles server-tag-get command
TEST_F(CtrlChannelDhcpv6SrvTest, serverTagGet) {
    createUnixChannelServer();

    std::string response;
    std::string expected;

    // Send the server-tag-get command
    sendUnixCommand("{ \"command\": \"server-tag-get\" }", response);
    expected = "{ \"arguments\": { \"server-tag\": \"\" }, \"result\": 0 }";
    EXPECT_EQ(expected, response);

    // Set a value to the server tag
    CfgMgr::instance().getCurrentCfg()->setServerTag("foobar");

    // Retry...
    sendUnixCommand("{ \"command\": \"server-tag-get\" }", response);
    expected = "{ \"arguments\": { \"server-tag\": \"foobar\" }, \"result\": 0 }";
}

941 942 943 944 945 946 947 948 949 950 951 952 953
// This test verifies that the DHCP server handles server-update command
TEST_F(CtrlChannelDhcpv6SrvTest, serverUpdate) {
    createUnixChannelServer();

    std::string response;
    std::string expected;

    // Send the server-update command. Note there is no configured backed.
    sendUnixCommand("{ \"command\": \"server-update\" }", response);
    expected = "{ \"result\": 3, \"text\": \"No config backend.\" }";
    EXPECT_EQ(expected, response);
}

Francis Dupont's avatar
Francis Dupont committed
954
// This test verifies that the DHCP server immediately reclaims expired
Francis Dupont's avatar
Francis Dupont committed
955 956 957 958
// leases on leases-reclaim command
TEST_F(CtrlChannelDhcpv6SrvTest, controlLeasesReclaim) {
    createUnixChannelServer();

Francis Dupont's avatar
Francis Dupont committed
959
    // Create expired leases. Leases are expired by 40 seconds ago
Francis Dupont's avatar
Francis Dupont committed
960
    // (valid lifetime = 60, cltt = now - 100).
Francis Dupont's avatar
Francis Dupont committed
961 962
    DuidPtr duid0(new DUID(DUID::fromText("00:01:02:03:04:05:06").getDuid()));
    Lease6Ptr lease0(new Lease6(Lease::TYPE_NA, IOAddress("3000::1"),
963
                                duid0, 1, 50, 60, SubnetID(1)));
Francis Dupont's avatar
Francis Dupont committed
964 965 966
    lease0->cltt_ = time(NULL) - 100;
    DuidPtr duid1(new DUID(DUID::fromText("01:02:03:04:05:06:07").getDuid()));
    Lease6Ptr lease1(new Lease6(Lease::TYPE_NA, IOAddress("3000::2"),
967
                                duid1, 1, 50, 60, SubnetID(1)));
Francis Dupont's avatar
Francis Dupont committed
968 969 970
    lease1->cltt_ = time(NULL) - 100;

    // Add leases to the database.
971
    LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
Francis Dupont's avatar
Francis Dupont committed
972 973
    ASSERT_NO_THROW(lease_mgr.addLease(lease0));
    ASSERT_NO_THROW(lease_mgr.addLease(lease1));
Francis Dupont's avatar
Francis Dupont committed
974

Francis Dupont's avatar
Francis Dupont committed
975
    // Make sure they have been added.
Francis Dupont's avatar
Francis Dupont committed
976
    ASSERT_TRUE(lease_mgr.getLease6(Lease::TYPE_NA, IOAddress("3000::1")));
Francis Dupont's avatar
Francis Dupont committed
977
    ASSERT_TRUE(lease_mgr.getLease6(Lease::TYPE_NA, IOAddress("3000::2")));
Francis Dupont's avatar
Francis Dupont committed
978

Francis Dupont's avatar
Francis Dupont committed
979
    // No arguments
Francis Dupont's avatar
Francis Dupont committed
980 981
    std::string response;
    sendUnixCommand("{ \"command\": \"leases-reclaim\" }", response);
Francis Dupont's avatar
Francis Dupont committed
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
    EXPECT_EQ("{ \"result\": 1, \"text\": "
              "\"Missing mandatory 'remove' parameter.\" }", response);

    // Bad argument name
    sendUnixCommand("{ \"command\": \"leases-reclaim\", "
                    "\"arguments\": { \"reclaim\": true } }", response);
    EXPECT_EQ("{ \"result\": 1, \"text\": "
              "\"Missing mandatory 'remove' parameter.\" }", response);

    // Bad remove argument type
    sendUnixCommand("{ \"command\": \"leases-reclaim\", "
                    "\"arguments\": { \"remove\": \"bogus\" } }", response);
    EXPECT_EQ("{ \"result\": 1, \"text\": "
              "\"'remove' parameter expected to be a boolean.\" }", response);

    // Send the command
    sendUnixCommand("{ \"command\": \"leases-reclaim\", "
                    "\"arguments\": { \"remove\": false } }", response);
    EXPECT_EQ("{ \"result\": 0, \"text\": "
              "\"Reclamation of expired leases is complete.\" }", response);

    // Leases should be reclaimed, but not removed
    ASSERT_NO_THROW(
        lease0 = lease_mgr.getLease6(Lease::TYPE_NA, IOAddress("3000::1"))
    );
    ASSERT_NO_THROW(
        lease1 = lease_mgr.getLease6(Lease::TYPE_NA, IOAddress("3000::2"))
    );
    ASSERT_TRUE(lease0);
    ASSERT_TRUE(lease1);
    EXPECT_TRUE(lease0->stateExpiredReclaimed());
    EXPECT_TRUE(lease1->stateExpiredReclaimed());
}

// This test verifies that the DHCP server immediately reclaims expired
// leases on leases-reclaim command with remove = true
TEST_F(CtrlChannelDhcpv6SrvTest, controlLeasesReclaimRemove) {
    createUnixChannelServer();
Francis Dupont's avatar
Francis Dupont committed
1020

Francis Dupont's avatar
Francis Dupont committed
1021 1022 1023 1024
    // Create expired leases. Leases are expired by 40 seconds ago
    // (valid lifetime = 60, cltt = now - 100).
    DuidPtr duid0(new DUID(DUID::fromText("00:01:02:03:04:05:06").getDuid()));
    Lease6Ptr lease0(new Lease6(Lease::TYPE_NA, IOAddress("3000::1"),
1025
                                duid0, 1, 50, 60, SubnetID(1)));
Francis Dupont's avatar
Francis Dupont committed
1026 1027 1028
    lease0->cltt_ = time(NULL) - 100;
    DuidPtr duid1(new DUID(DUID::fromText("01:02:03:04:05:06:07").getDuid()));
    Lease6Ptr lease1(new Lease6(Lease::TYPE_NA, IOAddress("3000::2"),
1029
                                duid1, 1, 50, 60, SubnetID(1)));
Francis Dupont's avatar
Francis Dupont committed
1030 1031 1032
    lease1->cltt_ = time(NULL) - 100;

    // Add leases to the database.
1033
    LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
Francis Dupont's avatar
Francis Dupont committed
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
    ASSERT_NO_THROW(lease_mgr.addLease(lease0));
    ASSERT_NO_THROW(lease_mgr.addLease(lease1));

    // Make sure they have been added.
    ASSERT_TRUE(lease_mgr.getLease6(Lease::TYPE_NA, IOAddress("3000::1")));
    ASSERT_TRUE(lease_mgr.getLease6(Lease::TYPE_NA, IOAddress("3000::2")));

    // Send the command
    std::string response;
    sendUnixCommand("{ \"command\": \"leases-reclaim\", "
                    "\"arguments\": { \"remove\": true } }", response);
    EXPECT_EQ("{ \"result\": 0, \"text\": "
              "\"Reclamation of expired leases is complete.\" }", response);

    // Leases should have been removed.
    ASSERT_NO_THROW(
        lease0 = lease_mgr.getLease6(Lease::TYPE_NA, IOAddress("3000::1"))
    );
Francis Dupont's avatar
Francis Dupont committed
1052
    ASSERT_NO_THROW(
Francis Dupont's avatar
Francis Dupont committed
1053
        lease1 = lease_mgr.getLease6(Lease::TYPE_NA, IOAddress("3000::2"))
Francis Dupont's avatar
Francis Dupont committed
1054
    );
Francis Dupont's avatar
Francis Dupont committed
1055 1056
    ASSERT_FALSE(lease0);
    ASSERT_FALSE(lease1);
Francis Dupont's avatar
Francis Dupont committed
1057 1058
}

1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
// Tests that the server properly responds to statistics commands.  Note this
// is really only intended to verify that the appropriate Statistics handler
// is called based on the command.  It is not intended to be an exhaustive
// test of Dhcpv6 statistics.
TEST_F(CtrlChannelDhcpv6SrvTest, controlChannelStats) {
    createUnixChannelServer();
    std::string response;

    // Check statistic-get
    sendUnixCommand("{ \"command\" : \"statistic-get\", "
                    "  \"arguments\": {"
                    "  \"name\":\"bogus\" }}", response);
    EXPECT_EQ("{ \"arguments\": {  }, \"result\": 0 }", response);

    // Check statistic-get-all
    sendUnixCommand("{ \"command\" : \"statistic-get-all\", "
                    "  \"arguments\": {}}", response);

1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
    std::set<std::string> initial_stats = {
        "pkt6-received",
        "pkt6-solicit-received",
        "pkt6-advertise-received",
        "pkt6-request-received",
        "pkt6-reply-received",
        "pkt6-renew-received",
        "pkt6-rebind-received",
        "pkt6-decline-received",
        "pkt6-release-received",
        "pkt6-infrequest-received",
        "pkt6-dhcpv4-query-received",
        "pkt6-dhcpv4-response-received",
        "pkt6-unknown-received",
        "pkt6-sent",
        "pkt6-advertise-sent",
        "pkt6-reply-sent",
        "pkt6-dhcpv4-response-sent",
        "pkt6-parse-failed",
        "pkt6-receive-drop"
    };

    std::ostringstream s;
    s << "{ \"arguments\": { ";
    for (auto st = initial_stats.begin(); st != initial_stats.end();) {
        s << "\"" << *st << "\": [ [ 0, \"";
        s << isc::util::ptimeToText(StatsMgr::instance().getObservation(*st)->getInteger().second);
        s << "\" ] ]";
        if (++st != initial_stats.end()) {
            s << ", ";
        }
    }
    s << " }, \"result\": 0 }";

    auto stats_get_all = s.str();
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169

    EXPECT_EQ(stats_get_all, response);

    // Check statistic-reset
    sendUnixCommand("{ \"command\" : \"statistic-reset\", "
                    "  \"arguments\": {"
                    "  \"name\":\"bogus\" }}", response);
    EXPECT_EQ("{ \"result\": 1, \"text\": \"No 'bogus' statistic found\" }",
              response);

    // Check statistic-reset-all
    sendUnixCommand("{ \"command\" : \"statistic-reset-all\", "
                    "  \"arguments\": {}}", response);
    EXPECT_EQ("{ \"result\": 0, \"text\": "
              "\"All statistics reset to neutral values.\" }", response);

    // Check statistic-remove
    sendUnixCommand("{ \"command\" : \"statistic-remove\", "
                    "  \"arguments\": {"
                    "  \"name\":\"bogus\" }}", response);
    EXPECT_EQ("{ \"result\": 1, \"text\": \"No 'bogus' statistic found\" }",
              response);

    // Check statistic-remove-all
    sendUnixCommand("{ \"command\" : \"statistic-remove-all\", "
                    "  \"arguments\": {}}", response);
    EXPECT_EQ("{ \"result\": 0, \"text\": \"All statistics removed.\" }",
              response);

    // Check statistic-sample-age-set
    sendUnixCommand("{ \"command\" : \"statistic-sample-age-set\", "
                    "  \"arguments\": {"
                    "  \"name\":\"bogus\", \"duration\": 1245 }}", response);
    EXPECT_EQ("{ \"result\": 1, \"text\": \"No 'bogus' statistic found\" }",
              response);

    // Check statistic-sample-age-set-all
    sendUnixCommand("{ \"command\" : \"statistic-sample-age-set-all\", "
                    "  \"arguments\": {"
                    "  \"duration\": 1245 }}", response);
    EXPECT_EQ("{ \"result\": 0, \"text\": \"All statistics duration limit are set.\" }",
              response);

    // Check statistic-sample-count-set
    sendUnixCommand("{ \"command\" : \"statistic-sample-count-set\", "
                    "  \"arguments\": {"
                    "  \"name\":\"bogus\", \"max-samples\": 100 }}", response);
    EXPECT_EQ("{ \"result\": 1, \"text\": \"No 'bogus' statistic found\" }",
              response);

    // Check statistic-sample-count-set-all
    sendUnixCommand("{ \"command\" : \"statistic-sample-count-set-all\", "
                    "  \"arguments\": {"
                    "  \"max-samples\": 100 }}", response);
    EXPECT_EQ("{ \"result\": 0, \"text\": \"All statistics count limit are set.\" }",
              response);
}

1170 1171
// Tests that the server properly responds to shtudown command sent
// via ControlChannel
Razvan Becheriu's avatar
Razvan Becheriu committed
1172
TEST_F(CtrlChannelDhcpv6SrvTest, listCommands) {
1173 1174 1175 1176 1177 1178 1179 1180 1181
    createUnixChannelServer();
    std::string response;

    sendUnixCommand("{ \"command\": \"list-commands\" }", response);

    ConstElementPtr rsp;
    EXPECT_NO_THROW(rsp = Element::fromJSON(response));

    // We expect the server to report at least the following commands:
Francis Dupont's avatar
Francis Dupont committed
1182
    checkListCommands(rsp, "build-report");
1183
    checkListCommands(rsp, "config-get");
1184
    checkListCommands(rsp, "config-reload");
1185
    checkListCommands(rsp, "config-set");
Francis Dupont's avatar
Francis Dupont committed
1186
    checkListCommands(rsp, "config-test");
1187 1188 1189 1190
    checkListCommands(rsp, "config-write");
    checkListCommands(rsp, "list-commands");
    checkListCommands(rsp, "leases-reclaim");
    checkListCommands(rsp, "libreload");
Francis Dupont's avatar
Francis Dupont committed
1191
    checkListCommands(rsp, "version-get");
1192
    checkListCommands(rsp, "server-tag-get");
1193
    checkListCommands(rsp, "server-update");
1194 1195 1196 1197 1198 1199 1200
    checkListCommands(rsp, "shutdown");
    checkListCommands(rsp, "statistic-get");
    checkListCommands(rsp, "statistic-get-all");
    checkListCommands(rsp, "statistic-remove");
    checkListCommands(rsp, "statistic-remove-all");
    checkListCommands(rsp, "statistic-reset");
    checkListCommands(rsp, "statistic-reset-all");
Razvan Becheriu's avatar
Razvan Becheriu committed
1201 1202 1203 1204
    checkListCommands(rsp, "statistic-sample-age-set");
    checkListCommands(rsp, "statistic-sample-age-set-all");
    checkListCommands(rsp, "statistic-sample-count-set");
    checkListCommands(rsp, "statistic-sample-count-set-all");
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227