kea_controller_unittest.cc 39.9 KB
Newer Older
1
// Copyright (C) 2014-2020 Internet Systems Consortium, Inc. ("ISC")
2
//
3 4 5
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6 7 8

#include <config.h>

9
#include <asiolink/interval_timer.h>
10
#include <asiolink/io_address.h>
11
#include <asiolink/io_service.h>
12
#include <cc/command_interpreter.h>
13
#include <dhcp/dhcp4.h>
14 15
#include <dhcp/hwaddr.h>
#include <dhcp/iface_mgr.h>
16
#include <dhcp4/ctrl_dhcp4_srv.h>
17
#include <dhcp4/parser_context.h>
18
#include <dhcp4/tests/dhcp4_test_utils.h>
19
#include <dhcpsrv/cb_ctl_dhcp4.h>
20
#include <dhcpsrv/cfgmgr.h>
21 22
#include <dhcpsrv/lease.h>
#include <dhcpsrv/lease_mgr_factory.h>
23
#include <process/config_base.h>
24 25 26 27 28

#ifdef HAVE_MYSQL
#include <mysql/testutils/mysql_schema.h>
#endif

29
#include <log/logger_support.h>
30
#include <util/stopwatch.h>
31

32
#include <boost/pointer_cast.hpp>
33 34 35
#include <boost/scoped_ptr.hpp>
#include <gtest/gtest.h>

36
#include <functional>
37 38
#include <fstream>
#include <iostream>
39
#include <signal.h>
40 41 42 43 44 45 46 47 48 49
#include <sstream>

#include <arpa/inet.h>
#include <unistd.h>

using namespace std;
using namespace isc;
using namespace isc::asiolink;
using namespace isc::config;
using namespace isc::data;
50 51

#ifdef HAVE_MYSQL
52
using namespace isc::db::test;
53 54
#endif

55
using namespace isc::dhcp;
56
using namespace isc::dhcp::test;
57 58 59 60
using namespace isc::hooks;

namespace {

61 62 63 64 65 66 67 68 69 70 71 72 73
/// @brief Test implementation of the @c CBControlDHCPv4.
///
/// This implementation is installed on the test server instance. It
/// overrides the implementation of the @c databaseConfigFetch function
/// to verify arguments passed to this function and throw an exception
/// when desired in the negative test scenarios. It doesn't do the
/// actual configuration fetch as this is tested elswhere and would
/// require setting up a database configuration backend.
class TestCBControlDHCPv4 : public CBControlDHCPv4 {
public:

    /// @brief Constructor.
    TestCBControlDHCPv4()
74 75
        : CBControlDHCPv4(), db_total_config_fetch_calls_(0),
          db_current_config_fetch_calls_(0), db_staging_config_fetch_calls_(0),
76
          enable_check_fetch_mode_(false), enable_throw_(false) {
77 78 79 80
    }

    /// @brief Stub implementation of the "fetch" function.
    ///
81 82 83 84 85 86
    /// If this is not the first invocation of this function, it
    /// verifies that the @c fetch_mode has been correctly set to
    /// @c FetchMode::FETCH_UPDATE.
    ///
    /// It also throws an exception when desired by a test, to
    /// verify that the server gracefully handles such exception.
87
    ///
88
    /// @param config either the staging or the current configuration.
89 90
    /// @param fetch_mode value indicating if the method is called upon the
    /// server start up or it is called to fetch configuration updates.
91 92
    ///
    /// @throw Unexpected when configured to do so.
93
    virtual void databaseConfigFetch(const process::ConfigPtr& config,
94
                                     const FetchMode& fetch_mode) {
95 96 97 98 99 100 101
        ++db_total_config_fetch_calls_;

        if (config == CfgMgr::instance().getCurrentCfg()) {
            ++db_current_config_fetch_calls_;
        } else if (config == CfgMgr::instance().getStagingCfg()) {
            ++db_staging_config_fetch_calls_;
        }
102

103
        if (enable_check_fetch_mode_) {
104 105
            if ((db_total_config_fetch_calls_ <= 1) &&
                (fetch_mode == FetchMode::FETCH_UPDATE)) {
106
                ADD_FAILURE() << "databaseConfigFetch was called with the value "
107
                    "of fetch_mode=FetchMode::FETCH_UPDATE upon the server configuration";
108

109 110
            } else if ((db_total_config_fetch_calls_ > 1) &&
                       (fetch_mode == FetchMode::FETCH_ALL)) {
111
                ADD_FAILURE() << "databaseConfigFetch was called with the value "
112
                    "of fetch_mode=FetchMode::FETCH_ALL during fetching the updates";
113
            }
114 115 116 117 118 119 120
        }

        if (enable_throw_) {
            isc_throw(Unexpected, "testing if exceptions are corectly handled");
        }
    }

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    /// @brief Returns number of invocations of the @c databaseConfigFetch
    /// (total).
    size_t getDatabaseTotalConfigFetchCalls() const {
        return (db_total_config_fetch_calls_);
    }

    /// @brief Returns number of invocations of the @c databaseConfigFetch
    /// (current configuration).
    size_t getDatabaseCurrentConfigFetchCalls() const {
        return (db_current_config_fetch_calls_);
    }

    /// @brief Returns number of invocations of the @c databaseConfigFetch
    /// (staging configuration).
    size_t getDatabaseStagingConfigFetchCalls() const {
        return (db_staging_config_fetch_calls_);
137 138
    }

139 140 141
    /// @brief Enables checking of the @c fetch_mode value.
    void enableCheckFetchMode() {
        enable_check_fetch_mode_ = true;
142 143
    }

144 145 146 147 148 149 150
    /// @brief Enables the object to throw from @c databaseConfigFetch.
    void enableThrow() {
        enable_throw_ = true;
    }

private:

151 152 153 154 155 156 157 158 159 160 161
    /// @brief Counter holding number of invocations of the
    /// @c databaseConfigFetch (total).
    size_t db_total_config_fetch_calls_;

    /// @brief Counter holding number of invocations of the
    /// @c databaseConfigFetch (current configuration).
    size_t db_current_config_fetch_calls_;

    /// @brief Counter holding number of invocations of the
    /// @c databaseConfigFetch (staging configuration).
    size_t db_staging_config_fetch_calls_;
162

163
    /// @brief Boolean flag indicated if the value of the @c fetch_mode
164
    /// should be verified.
165
    bool enable_check_fetch_mode_;
166

167 168 169 170 171 172 173 174 175 176 177 178
    /// @brief Boolean flag indicating if the @c databaseConfigFetch should
    /// throw.
    bool enable_throw_;
};

/// @brief Shared pointer to the @c TestCBControlDHCPv4.
typedef boost::shared_ptr<TestCBControlDHCPv4> TestCBControlDHCPv4Ptr;

/// @brief "Naked" DHCPv4 server.
///
/// Exposes internal fields and installs stub implementation of the
/// @c CBControlDHCPv4 object.
179 180
class NakedControlledDhcpv4Srv: public ControlledDhcpv4Srv {
public:
181 182 183 184 185 186 187 188 189

    /// @brief Constructor.
    NakedControlledDhcpv4Srv()
        : ControlledDhcpv4Srv(0) {
        // We're replacing the @c CBControlDHCPv4 instance with our
        // stub implementation used in tests.
        cb_control_.reset(new TestCBControlDHCPv4());
    }

190
    using ControlledDhcpv4Srv::signal_handler_;
191 192
};

Tomek Mrugalski's avatar
Tomek Mrugalski committed
193 194
/// @brief test class for Kea configuration backend
///
195 196 197 198
/// This class is used for testing Kea configuration backend.
/// It is very simple and currently focuses on reading
/// config file from disk. It is expected to be expanded in the
/// near future.
199
class JSONFileBackendTest : public isc::dhcp::test::BaseServerTest {
200 201 202 203 204
public:
    JSONFileBackendTest() {
    }

    ~JSONFileBackendTest() {
205
        LeaseMgrFactory::destroy();
206
        static_cast<void>(remove(TEST_FILE));
207
        static_cast<void>(remove(TEST_INCLUDE));
208 209
    };

210 211 212 213 214
    /// @brief writes specified content to a well known file
    ///
    /// Writes specified content to TEST_FILE. Tests will
    /// attempt to read that file.
    ///
215
    /// @param file_name name of file to be written
216
    /// @param content content to be written to file
217 218
    void writeFile(const std::string& file_name, const std::string& content) {
        static_cast<void>(remove(file_name.c_str()));
219

220
        ofstream out(file_name.c_str(), ios::trunc);
221 222 223 224 225
        EXPECT_TRUE(out.is_open());
        out << content;
        out.close();
    }

226 227
    /// @brief Runs timers for specified time.
    ///
228
    /// @param io_service Pointer to the IO service to be ran.
229
    /// @param timeout_ms Amount of time after which the method returns.
230 231 232 233
    /// @param cond Pointer to the function which if returns true it
    /// stops the IO service and causes the function to return.
    void runTimersWithTimeout(const IOServicePtr& io_service, const long timeout_ms,
                              std::function<bool()> cond = std::function<bool()>()) {
234
        IntervalTimer timer(*io_service);
235 236
        bool stopped = false;
        timer.setup([&io_service, &stopped]() {
237
            io_service->stop();
238
            stopped = true;
239
        }, timeout_ms, IntervalTimer::ONE_SHOT);
240 241 242 243 244 245

        // Run as long as the timeout hasn't occurred and the interrupting
        // condition is not specified or not met.
        while (!stopped && (!cond || !cond())) {
            io_service->run_one();
        }
246
        io_service->get_io_service().reset();
247 248
    }

249 250 251
    /// @brief This test verifies that the timer used to fetch the configuration
    /// updates from the database works as expected.
    void testConfigBackendTimer(const int config_wait_fetch_time,
252 253
                                const bool throw_during_fetch = false,
                                const bool call_command = false) {
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
        std::ostringstream config;
        config <<
            "{ \"Dhcp4\": {"
            "\"interfaces-config\": {"
            "    \"interfaces\": [ ]"
            "},"
            "\"lease-database\": {"
            "     \"type\": \"memfile\","
            "     \"persist\": false"
            "},"
            "\"config-control\": {"
            "     \"config-fetch-wait-time\": " << config_wait_fetch_time <<
            "},"
            "\"rebind-timer\": 2000, "
            "\"renew-timer\": 1000, \n"
            "\"subnet4\": [ ],"
            "\"valid-lifetime\": 4000 }"
            "}";
        writeFile(TEST_FILE, config.str());

        // Create an instance of the server and initialize it.
        boost::scoped_ptr<NakedControlledDhcpv4Srv> srv;
        ASSERT_NO_THROW(srv.reset(new NakedControlledDhcpv4Srv()));
        ASSERT_NO_THROW(srv->init(TEST_FILE));

        // Get the CBControlDHCPv4 object belonging to this server.
        auto cb_control = boost::dynamic_pointer_cast<TestCBControlDHCPv4>(srv->getCBControl());

282 283 284
        // Verify that the parameter passed to the databaseConfigFetch has an
        // expected value.
        cb_control->enableCheckFetchMode();
285

286 287 288 289 290 291 292
        // Instruct our stub implementation of the CBControlDHCPv4 to throw as a
        // result of fetch if desired.
        if (throw_during_fetch) {
            cb_control->enableThrow();
        }

        // So far there should be exactly one attempt to fetch the configuration
293 294 295 296 297 298 299 300 301 302
        // from the backend. That's the attempt made upon startup on
        // the staging configuration.
        // All other fetches will be on the current configuration:
        //  - the timer makes a closure with the staging one but it is
        //    committed so becomes the current one.
        //  - the command is called outside configuration so it must
        //    be the current configuration. The test explicitly checks this.
        EXPECT_EQ(1, cb_control->getDatabaseTotalConfigFetchCalls());
        EXPECT_EQ(0, cb_control->getDatabaseCurrentConfigFetchCalls());
        EXPECT_EQ(1, cb_control->getDatabaseStagingConfigFetchCalls());
303 304


305 306 307 308 309 310
        if (call_command) {
            // The case where there is no backend is tested in the
            // controlled server tests so we have only to verify
            // that the command calls the database config fetch.

            // Count the startup.
311 312 313
            EXPECT_EQ(cb_control->getDatabaseTotalConfigFetchCalls(), 1);
            EXPECT_EQ(cb_control->getDatabaseCurrentConfigFetchCalls(), 0);
            EXPECT_EQ(cb_control->getDatabaseStagingConfigFetchCalls(), 1);
314 315

            ConstElementPtr result =
316
                ControlledDhcpv4Srv::processCommand("config-backend-pull",
317
                                                    ConstElementPtr());
318
            EXPECT_EQ(cb_control->getDatabaseTotalConfigFetchCalls(), 2);
319 320 321 322
            std::string expected;

            if (throw_during_fetch) {
                expected = "{ \"result\": 1, \"text\": ";
323
                expected += "\"On demand configuration update failed: ";
324 325 326
                expected += "testing if exceptions are corectly handled\" }";
            } else {
                expected = "{ \"result\": 0, \"text\": ";
327
                expected += "\"On demand configuration update successful.\" }";
328 329 330 331
            }
            EXPECT_EQ(expected, result->str());

            // No good way to check the rescheduling...
332
            ASSERT_NO_THROW(runTimersWithTimeout(srv->getIOService(), 20));
333 334

            if (config_wait_fetch_time > 0) {
335 336 337
                EXPECT_GE(cb_control->getDatabaseTotalConfigFetchCalls(), 5);
                EXPECT_GE(cb_control->getDatabaseCurrentConfigFetchCalls(), 4);
                EXPECT_EQ(cb_control->getDatabaseStagingConfigFetchCalls(), 1);
338
            } else {
339 340 341
                EXPECT_EQ(cb_control->getDatabaseTotalConfigFetchCalls(), 2);
                EXPECT_EQ(cb_control->getDatabaseCurrentConfigFetchCalls(), 1);
                EXPECT_EQ(cb_control->getDatabaseStagingConfigFetchCalls(), 1);
342 343 344
            }

        } else if ((config_wait_fetch_time > 0) && (!throw_during_fetch)) {
345 346 347 348 349 350 351 352 353
            // If we're configured to run the timer, we expect that it was
            // invoked at least 3 times. This is sufficient to verify that
            // the timer was scheduled and that the timer continued to run
            // even when an exception occurred during fetch (that's why it
            // is 3 not 2).
            ASSERT_NO_THROW(runTimersWithTimeout(srv->getIOService(), 500,
                [cb_control]() {
                    // Interrupt the timers poll if we have recorded at
                    // least 3 attempts to fetch the updates.
354
                    return (cb_control->getDatabaseTotalConfigFetchCalls() >= 3);
355
                }));
356 357 358
            EXPECT_GE(cb_control->getDatabaseTotalConfigFetchCalls(), 3);
            EXPECT_GE(cb_control->getDatabaseCurrentConfigFetchCalls(), 2);
            EXPECT_EQ(cb_control->getDatabaseStagingConfigFetchCalls(), 1);
359 360 361

        } else {
            ASSERT_NO_THROW(runTimersWithTimeout(srv->getIOService(), 500));
362 363 364 365 366 367 368

            if (throw_during_fetch) {
                // If we're simulating the failure condition the number
                // of consecutive failures should not exceed 10. Therefore
                // the number of recorded fetches should be 12. One at
                // startup, 10 failures and one that causes the timer
                // to stop.
369 370 371
                EXPECT_EQ(12, cb_control->getDatabaseTotalConfigFetchCalls());
                EXPECT_EQ(11, cb_control->getDatabaseCurrentConfigFetchCalls());
                EXPECT_EQ(1, cb_control->getDatabaseStagingConfigFetchCalls());
372 373 374 375

            } else {
                // If the server is not configured to schedule the timer,
                // we should still have one fetch attempt recorded.
376 377 378
                EXPECT_EQ(1, cb_control->getDatabaseTotalConfigFetchCalls());
                EXPECT_EQ(0, cb_control->getDatabaseCurrentConfigFetchCalls());
                EXPECT_EQ(1, cb_control->getDatabaseStagingConfigFetchCalls());
379
            }
380 381 382
        }
    }

383
    /// Name of a config file used during tests
384
    static const char* TEST_FILE;
385
    static const char* TEST_INCLUDE;
386 387
};

388
const char* JSONFileBackendTest::TEST_FILE  = "test-config.json";
389
const char* JSONFileBackendTest::TEST_INCLUDE = "test-include.json";
390 391 392 393 394

// This test checks if configuration can be read from a JSON file.
TEST_F(JSONFileBackendTest, jsonFile) {

    // Prepare configuration file.
395 396 397 398
    string config = "{ \"Dhcp4\": {"
        "\"interfaces-config\": {"
        "    \"interfaces\": [ \"*\" ]"
        "},"
399 400 401
        "\"rebind-timer\": 2000, "
        "\"renew-timer\": 1000, "
        "\"subnet4\": [ { "
402
        "    \"pools\": [ { \"pool\": \"192.0.2.1 - 192.0.2.100\" } ],"
403 404 405
        "    \"subnet\": \"192.0.2.0/24\" "
        " },"
        " {"
406
        "    \"pools\": [ { \"pool\": \"192.0.3.101 - 192.0.3.150\" } ],"
407 408 409 410
        "    \"subnet\": \"192.0.3.0/24\", "
        "    \"id\": 0 "
        " },"
        " {"
411
        "    \"pools\": [ { \"pool\": \"192.0.4.101 - 192.0.4.150\" } ],"
412 413
        "    \"subnet\": \"192.0.4.0/24\" "
        " } ],"
414 415
        "\"valid-lifetime\": 4000 }"
        "}";
416

417
    writeFile(TEST_FILE, config);
418 419 420 421 422 423 424 425 426 427 428

    // Now initialize the server
    boost::scoped_ptr<ControlledDhcpv4Srv> srv;
    ASSERT_NO_THROW(
        srv.reset(new ControlledDhcpv4Srv(0))
    );

    // And configure it using the config file.
    EXPECT_NO_THROW(srv->init(TEST_FILE));

    // Now check if the configuration has been applied correctly.
429 430
    const Subnet4Collection* subnets =
        CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll();
431 432 433 434
    ASSERT_TRUE(subnets);
    ASSERT_EQ(3, subnets->size()); // We expect 3 subnets.

    // Check subnet 1.
435
    auto subnet = subnets->begin();
436
    ASSERT_TRUE(subnet != subnets->end());
437 438
    EXPECT_EQ("192.0.2.0", (*subnet)->get().first.toText());
    EXPECT_EQ(24, (*subnet)->get().second);
439 440

    // Check pools in the first subnet.
441
    const PoolCollection& pools1 = (*subnet)->getPools(Lease::TYPE_V4);
442 443 444 445 446 447
    ASSERT_EQ(1, pools1.size());
    EXPECT_EQ("192.0.2.1", pools1.at(0)->getFirstAddress().toText());
    EXPECT_EQ("192.0.2.100", pools1.at(0)->getLastAddress().toText());
    EXPECT_EQ(Lease::TYPE_V4, pools1.at(0)->getType());

    // Check subnet 2.
448
    ++subnet;
449
    ASSERT_TRUE(subnet != subnets->end());
450 451
    EXPECT_EQ("192.0.3.0", (*subnet)->get().first.toText());
    EXPECT_EQ(24, (*subnet)->get().second);
452 453

    // Check pools in the second subnet.
454
    const PoolCollection& pools2 = (*subnet)->getPools(Lease::TYPE_V4);
455 456 457 458 459 460
    ASSERT_EQ(1, pools2.size());
    EXPECT_EQ("192.0.3.101", pools2.at(0)->getFirstAddress().toText());
    EXPECT_EQ("192.0.3.150", pools2.at(0)->getLastAddress().toText());
    EXPECT_EQ(Lease::TYPE_V4, pools2.at(0)->getType());

    // And finally check subnet 3.
461
    ++subnet;
462
    ASSERT_TRUE(subnet != subnets->end());
463 464
    EXPECT_EQ("192.0.4.0", (*subnet)->get().first.toText());
    EXPECT_EQ(24, (*subnet)->get().second);
465 466

    // ... and it's only pool.
467
    const PoolCollection& pools3 = (*subnet)->getPools(Lease::TYPE_V4);
468 469
    EXPECT_EQ("192.0.4.101", pools3.at(0)->getFirstAddress().toText());
    EXPECT_EQ("192.0.4.150", pools3.at(0)->getLastAddress().toText());
470
    EXPECT_EQ(Lease::TYPE_V4, pools3.at(0)->getType());
471 472
}

473 474 475
// This test checks if configuration can be read from a JSON file
// using hash (#) line comments
TEST_F(JSONFileBackendTest, hashComments) {
476 477 478

    string config_hash_comments = "# This is a comment. It should be \n"
        "#ignored. Real config starts in line below\n"
479 480 481 482
        "{ \"Dhcp4\": {"
        "\"interfaces-config\": {"
        "    \"interfaces\": [ \"*\" ]"
        "},"
483 484 485 486
        "\"rebind-timer\": 2000, "
        "\"renew-timer\": 1000, \n"
        "# comments in the middle should be ignored, too\n"
        "\"subnet4\": [ { "
487
        "    \"pools\": [ { \"pool\": \"192.0.2.0/24\" } ],"
488 489 490 491 492
        "    \"subnet\": \"192.0.2.0/22\" "
        " } ],"
        "\"valid-lifetime\": 4000 }"
        "}";

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
    writeFile(TEST_FILE, config_hash_comments);

    // Now initialize the server
    boost::scoped_ptr<ControlledDhcpv4Srv> srv;
    ASSERT_NO_THROW(
        srv.reset(new ControlledDhcpv4Srv(0))
    );

    // And configure it using config with comments.
    EXPECT_NO_THROW(srv->init(TEST_FILE));

    // Now check if the configuration has been applied correctly.
    const Subnet4Collection* subnets =
        CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll();
    ASSERT_TRUE(subnets);
    ASSERT_EQ(1, subnets->size());

    // Check subnet 1.
511
    auto subnet = subnets->begin();
512
    ASSERT_TRUE(subnet != subnets->end());
513 514
    EXPECT_EQ("192.0.2.0", (*subnet)->get().first.toText());
    EXPECT_EQ(22, (*subnet)->get().second);
515 516

    // Check pools in the first subnet.
517
    const PoolCollection& pools1 = (*subnet)->getPools(Lease::TYPE_V4);
518 519 520 521 522
    ASSERT_EQ(1, pools1.size());
    EXPECT_EQ("192.0.2.0", pools1.at(0)->getFirstAddress().toText());
    EXPECT_EQ("192.0.2.255", pools1.at(0)->getLastAddress().toText());
    EXPECT_EQ(Lease::TYPE_V4, pools1.at(0)->getType());
}
523

524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
// This test checks if configuration can be read from a JSON file
// using C++ line (//) comments.
TEST_F(JSONFileBackendTest, cppLineComments) {

    string config_cpp_line_comments = "// This is a comment. It should be \n"
        "//ignored. Real config starts in line below\n"
        "{ \"Dhcp4\": {"
        "\"interfaces-config\": {"
        "    \"interfaces\": [ \"*\" ]"
        "},"
        "\"rebind-timer\": 2000, "
        "\"renew-timer\": 1000, \n"
        "// comments in the middle should be ignored, too\n"
        "\"subnet4\": [ { "
        "    \"pools\": [ { \"pool\": \"192.0.2.0/24\" } ],"
        "    \"subnet\": \"192.0.2.0/22\" "
        " } ],"
        "\"valid-lifetime\": 4000 }"
        "}";

    writeFile(TEST_FILE, config_cpp_line_comments);
545 546 547 548 549 550 551

    // Now initialize the server
    boost::scoped_ptr<ControlledDhcpv4Srv> srv;
    ASSERT_NO_THROW(
        srv.reset(new ControlledDhcpv4Srv(0))
    );

Tomek Mrugalski's avatar
Tomek Mrugalski committed
552
    // And configure it using config with comments.
553 554 555
    EXPECT_NO_THROW(srv->init(TEST_FILE));

    // Now check if the configuration has been applied correctly.
556 557
    const Subnet4Collection* subnets =
        CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll();
558 559 560 561
    ASSERT_TRUE(subnets);
    ASSERT_EQ(1, subnets->size());

    // Check subnet 1.
562
    auto subnet = subnets->begin();
563
    ASSERT_TRUE(subnet != subnets->end());
564 565
    EXPECT_EQ("192.0.2.0", (*subnet)->get().first.toText());
    EXPECT_EQ(22, (*subnet)->get().second);
566 567

    // Check pools in the first subnet.
568
    const PoolCollection& pools1 = (*subnet)->getPools(Lease::TYPE_V4);
569 570 571
    ASSERT_EQ(1, pools1.size());
    EXPECT_EQ("192.0.2.0", pools1.at(0)->getFirstAddress().toText());
    EXPECT_EQ("192.0.2.255", pools1.at(0)->getLastAddress().toText());
572
    EXPECT_EQ(Lease::TYPE_V4, pools1.at(0)->getType());
573 574
}

575 576 577 578 579
// This test checks if configuration can be read from a JSON file
// using C block (/* */) comments
TEST_F(JSONFileBackendTest, cBlockComments) {

    string config_c_block_comments = "/* This is a comment. It should be \n"
580
        "ignored. Real config starts in line below*/\n"
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
        "{ \"Dhcp4\": {"
        "\"interfaces-config\": {"
        "    \"interfaces\": [ \"*\" ]"
        "},"
        "\"rebind-timer\": 2000, "
        "\"renew-timer\": 1000, \n"
        "/* comments in the middle should be ignored, too*/\n"
        "\"subnet4\": [ { "
        "    \"pools\": [ { \"pool\": \"192.0.2.0/24\" } ],"
        "    \"subnet\": \"192.0.2.0/22\" "
        " } ],"
        "\"valid-lifetime\": 4000 }"
        "}";

    writeFile(TEST_FILE, config_c_block_comments);

    // Now initialize the server
    boost::scoped_ptr<ControlledDhcpv4Srv> srv;
    ASSERT_NO_THROW(
        srv.reset(new ControlledDhcpv4Srv(0))
    );
602

603 604 605 606 607 608 609 610 611 612
    // And configure it using config with comments.
    EXPECT_NO_THROW(srv->init(TEST_FILE));

    // Now check if the configuration has been applied correctly.
    const Subnet4Collection* subnets =
        CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll();
    ASSERT_TRUE(subnets);
    ASSERT_EQ(1, subnets->size());

    // Check subnet 1.
613
    auto subnet = subnets->begin();
614
    ASSERT_TRUE(subnet != subnets->end());
615 616
    EXPECT_EQ("192.0.2.0", (*subnet)->get().first.toText());
    EXPECT_EQ(22, (*subnet)->get().second);
617 618

    // Check pools in the first subnet.
619
    const PoolCollection& pools1 = (*subnet)->getPools(Lease::TYPE_V4);
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
    ASSERT_EQ(1, pools1.size());
    EXPECT_EQ("192.0.2.0", pools1.at(0)->getFirstAddress().toText());
    EXPECT_EQ("192.0.2.255", pools1.at(0)->getLastAddress().toText());
    EXPECT_EQ(Lease::TYPE_V4, pools1.at(0)->getType());
}

// This test checks if configuration can be read from a JSON file
// using an include file.
TEST_F(JSONFileBackendTest, include) {

    string config_hash_comments = "{ \"Dhcp4\": {"
        "\"interfaces-config\": {"
        "    \"interfaces\": [ \"*\" ]"
        "},"
        "\"rebind-timer\": 2000, "
        "\"renew-timer\": 1000, \n"
        "<?include \"" + string(TEST_INCLUDE) + "\"?>,"
        "\"valid-lifetime\": 4000 }"
        "}";
    string include = "\n"
        "\"subnet4\": [ { "
        "    \"pools\": [ { \"pool\": \"192.0.2.0/24\" } ],"
        "    \"subnet\": \"192.0.2.0/22\" "
        " } ]\n";

    writeFile(TEST_FILE, config_hash_comments);
    writeFile(TEST_INCLUDE, include);
647 648 649 650 651 652 653

    // Now initialize the server
    boost::scoped_ptr<ControlledDhcpv4Srv> srv;
    ASSERT_NO_THROW(
        srv.reset(new ControlledDhcpv4Srv(0))
    );

Tomek Mrugalski's avatar
Tomek Mrugalski committed
654
    // And configure it using config with comments.
655 656 657
    EXPECT_NO_THROW(srv->init(TEST_FILE));

    // Now check if the configuration has been applied correctly.
658 659
    const Subnet4Collection* subnets =
        CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll();
660 661 662 663
    ASSERT_TRUE(subnets);
    ASSERT_EQ(1, subnets->size());

    // Check subnet 1.
664
    auto subnet = subnets->begin();
665
    ASSERT_TRUE(subnet != subnets->end());
666 667
    EXPECT_EQ("192.0.2.0", (*subnet)->get().first.toText());
    EXPECT_EQ(22, (*subnet)->get().second);
668 669

    // Check pools in the first subnet.
670
    const PoolCollection& pools1 = (*subnet)->getPools(Lease::TYPE_V4);
671 672 673
    ASSERT_EQ(1, pools1.size());
    EXPECT_EQ("192.0.2.0", pools1.at(0)->getFirstAddress().toText());
    EXPECT_EQ("192.0.2.255", pools1.at(0)->getLastAddress().toText());
674
    EXPECT_EQ(Lease::TYPE_V4, pools1.at(0)->getType());
675 676
}

677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
// This test checks if recursive include of a file is detected
TEST_F(JSONFileBackendTest, recursiveInclude) {

    string config_recursive_include = "{ \"Dhcp4\": {"
        "\"interfaces-config\": {"
        "  \"interfaces\": [ <?include \"" + string(TEST_INCLUDE) + "\"?> ]"
        "},"
        "\"rebind-timer\": 2000, "
        "\"renew-timer\": 1000, \n"
        "\"subnet4\": [ { "
        "    \"pools\": [ { \"pool\": \"192.0.2.0/24\" } ],"
        "    \"subnet\": \"192.0.2.0/22\" "
        " } ],"
        "\"valid-lifetime\": 4000 }"
        "}";
    string include = "\"eth\", <?include \"" + string(TEST_INCLUDE) + "\"?>";
    string msg = "configuration error using file '" + string(TEST_FILE) +
        "': Too many nested include.";

    writeFile(TEST_FILE, config_recursive_include);
    writeFile(TEST_INCLUDE, include);

    // Now initialize the server
    boost::scoped_ptr<ControlledDhcpv4Srv> srv;
    ASSERT_NO_THROW(
        srv.reset(new ControlledDhcpv4Srv(0))
    );

    // And configure it using config with comments.
    try {
        srv->init(TEST_FILE);
        FAIL() << "Expected Dhcp4ParseError but nothing was raised";
    }
    catch (const Exception& ex) {
        EXPECT_EQ(msg, ex.what());
    }
}

715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
// This test checks if configuration detects failure when trying:
// - empty file
// - empty filename
// - no Dhcp4 element
// - Config file that contains Dhcp4 but has a content error
TEST_F(JSONFileBackendTest, configBroken) {

    // Empty config is not allowed, because Dhcp4 element is missing
    string config_empty = "";

    // This config does not have mandatory Dhcp4 element
    string config_v4 = "{ \"Dhcp6\": { \"interfaces\": [ \"*\" ],"
        "\"preferred-lifetime\": 3000,"
        "\"rebind-timer\": 2000, "
        "\"renew-timer\": 1000, "
        "\"subnet4\": [ { "
        "    \"pool\": [ \"2001:db8::/80\" ],"
        "    \"subnet\": \"2001:db8::/64\" "
        " } ]}";

    // This has Dhcp4 element, but it's utter nonsense
    string config_nonsense = "{ \"Dhcp4\": { \"reviews\": \"are so much fun\" } }";

    // Now initialize the server
    boost::scoped_ptr<ControlledDhcpv4Srv> srv;
    ASSERT_NO_THROW(
        srv.reset(new ControlledDhcpv4Srv(0))
    );

    // Try to configure without filename. Should fail.
    EXPECT_THROW(srv->init(""), BadValue);

    // Try to configure it using empty file. Should fail.
748
    writeFile(TEST_FILE, config_empty);
749 750 751
    EXPECT_THROW(srv->init(TEST_FILE), BadValue);

    // Now try to load a config that does not have Dhcp4 component.
752
    writeFile(TEST_FILE, config_v4);
753 754 755
    EXPECT_THROW(srv->init(TEST_FILE), BadValue);

    // Now try to load a config with Dhcp4 full of nonsense.
756
    writeFile(TEST_FILE, config_nonsense);
757 758 759
    EXPECT_THROW(srv->init(TEST_FILE), BadValue);
}

Tomek Mrugalski's avatar
Tomek Mrugalski committed
760 761 762 763 764
/// This unit-test reads all files enumerated in configs-test.txt file, loads
/// each of them and verify that they can be loaded.
///
/// @todo: Unfortunately, we have this test disabled, because all loaded
/// configs use memfile, which attempts to create lease file in
765
/// /usr/local/var/lib/kea/kea-leases4.csv. We have couple options here:
Tomek Mrugalski's avatar
Tomek Mrugalski committed
766 767 768 769 770 771 772 773 774 775
/// a) disable persistence in example configs - a very bad thing to do
///    as users will forget to reenable it and then will be surprised when their
///    leases disappear
/// b) change configs to store lease file in /tmp. It's almost as bad as the
///    previous one. Users will then be displeased when all their leases are
///    wiped. (most systems wipe /tmp during boot)
/// c) read each config and rewrite it on the fly, so persistence is disabled.
///    This is probably the way to go, but this is a work for a dedicated ticket.
///
/// Hence I'm leaving the test in, but it is disabled.
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
TEST_F(JSONFileBackendTest, DISABLED_loadAllConfigs) {

    // Create server first
    boost::scoped_ptr<ControlledDhcpv4Srv> srv;
    ASSERT_NO_THROW(
        srv.reset(new ControlledDhcpv4Srv(0))
    );

    const char* configs_list = "configs-list.txt";
    fstream configs(configs_list, ios::in);
    ASSERT_TRUE(configs.is_open());
    std::string config_name;
    while (std::getline(configs, config_name)) {

        // Ignore empty and commented lines
        if (config_name.empty() || config_name[0] == '#') {
            continue;
        }

        // Unit-tests usually do not print out anything, but in this case I
        // think printing out tests configs is warranted.
        std::cout << "Loading config file " << config_name << std::endl;

        try {
            srv->init(config_name);
        } catch (const std::exception& ex) {
            ADD_FAILURE() << "Exception thrown" << ex.what() << endl;
        }
    }
}

807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
// This test verifies that the DHCP server installs the timers for reclaiming
// and flushing expired leases.
TEST_F(JSONFileBackendTest, timers) {
    // This is a basic configuration which enables timers for reclaiming
    // expired leases and flushing them after 500 seconds since they expire.
    // Both timers run at 1 second intervals.
    string config =
        "{ \"Dhcp4\": {"
        "\"interfaces-config\": {"
        "    \"interfaces\": [ ]"
        "},"
        "\"lease-database\": {"
        "     \"type\": \"memfile\","
        "     \"persist\": false"
        "},"
        "\"expired-leases-processing\": {"
        "     \"reclaim-timer-wait-time\": 1,"
        "     \"hold-reclaimed-time\": 500,"
        "     \"flush-reclaimed-timer-wait-time\": 1"
        "},"
        "\"rebind-timer\": 2000, "
        "\"renew-timer\": 1000, \n"
        "\"subnet4\": [ ],"
        "\"valid-lifetime\": 4000 }"
        "}";
832
    writeFile(TEST_FILE, config);
833

Andrei Pavel's avatar
Andrei Pavel committed
834
    // Create an instance of the server and initialize it.
835 836 837 838 839 840 841 842 843 844 845
    boost::scoped_ptr<ControlledDhcpv4Srv> srv;
    ASSERT_NO_THROW(srv.reset(new ControlledDhcpv4Srv(0)));
    ASSERT_NO_THROW(srv->init(TEST_FILE));

    // Create an expired lease. The lease is expired by 40 seconds ago
    // (valid lifetime = 60, cltt = now - 100). The lease will be reclaimed
    // but shouldn't be flushed in the database because the reclaimed are
    // held in the database 500 seconds after reclamation, according to the
    // current configuration.
    HWAddrPtr hwaddr_expired(new HWAddr(HWAddr::fromText("00:01:02:03:04:05")));
    Lease4Ptr lease_expired(new Lease4(IOAddress("10.0.0.1"), hwaddr_expired,
846
                                       ClientIdPtr(), 60,
847 848 849 850 851 852 853
                                       time(NULL) - 100, SubnetID(1)));

    // Create expired-reclaimed lease. The lease has expired 1000 - 60 seconds
    // ago. It should be removed from the lease database when the "flush" timer
    // goes off.
    HWAddrPtr hwaddr_reclaimed(new HWAddr(HWAddr::fromText("01:02:03:04:05:06")));
    Lease4Ptr lease_reclaimed(new Lease4(IOAddress("10.0.0.2"), hwaddr_reclaimed,
854
                                         ClientIdPtr(), 60,
855 856 857 858
                                         time(NULL) - 1000, SubnetID(1)));
    lease_reclaimed->state_ = Lease4::STATE_EXPIRED_RECLAIMED;

    // Add leases to the database.
859
    LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
860 861 862 863 864 865 866 867 868
    ASSERT_NO_THROW(lease_mgr.addLease(lease_expired));
    ASSERT_NO_THROW(lease_mgr.addLease(lease_reclaimed));

    // Make sure they have been added.
    ASSERT_TRUE(lease_mgr.getLease4(IOAddress("10.0.0.1")));
    ASSERT_TRUE(lease_mgr.getLease4(IOAddress("10.0.0.2")));

    // Poll the timers for a while to make sure that each of them is executed
    // at least once.
869
    ASSERT_NO_THROW(runTimersWithTimeout(srv->getIOService(), 5000));
870 871 872 873 874 875 876 877 878

    // Verify that the leases in the database have been processed as expected.

    // First lease should be reclaimed, but not removed.
    ASSERT_NO_THROW(lease_expired = lease_mgr.getLease4(IOAddress("10.0.0.1")));
    ASSERT_TRUE(lease_expired);
    EXPECT_TRUE(lease_expired->stateExpiredReclaimed());

    // Second lease should have been removed.
879 880 881 882
    ASSERT_NO_THROW(
        lease_reclaimed = lease_mgr.getLease4(IOAddress("10.0.0.2"));
    );
    EXPECT_FALSE(lease_reclaimed);
883 884
}

885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
// This test verifies that the server uses default (Memfile) lease database
// backend when no backend is explicitly specified in the configuration.
TEST_F(JSONFileBackendTest, defaultLeaseDbBackend) {
    // This is basic server configuration which excludes lease database
    // backend specification. The default Memfile backend should be
    // initialized in this case.
    string config =
        "{ \"Dhcp4\": {"
        "\"interfaces-config\": {"
        "    \"interfaces\": [ ]"
        "},"
        "\"rebind-timer\": 2000, "
        "\"renew-timer\": 1000, \n"
        "\"subnet4\": [ ],"
        "\"valid-lifetime\": 4000 }"
        "}";
901
    writeFile(TEST_FILE, config);
902

Andrei Pavel's avatar
Andrei Pavel committed
903
    // Create an instance of the server and initialize it.
904 905 906 907 908 909 910 911
    boost::scoped_ptr<ControlledDhcpv4Srv> srv;
    ASSERT_NO_THROW(srv.reset(new ControlledDhcpv4Srv(0)));
    ASSERT_NO_THROW(srv->init(TEST_FILE));

    // The backend should have been created.
    EXPECT_NO_THROW(static_cast<void>(LeaseMgrFactory::instance()));
}

912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
// This test verifies that the timer triggering configuration updates
// is invoked according to the configured value of the
// config-fetch-wait-time.
TEST_F(JSONFileBackendTest, configBackendTimer) {
    testConfigBackendTimer(1);
}

// This test verifies that the timer for triggering configuration updates
// is not invoked when the value of the config-fetch-wait-time is set
// to 0.
TEST_F(JSONFileBackendTest, configBackendTimerDisabled) {
    testConfigBackendTimer(0);
}

// This test verifies that the server will gracefully handle exceptions
// thrown from the CBControlDHCPv4::databaseConfigFetch, i.e. will
// reschedule the timer.
TEST_F(JSONFileBackendTest, configBackendTimerWithThrow) {
    // The true value instructs the test to throw during the fetch.
    testConfigBackendTimer(1, true);
}

934 935
// This test verifies that the server will be updated by the
// config-backend-pull command.
936
TEST_F(JSONFileBackendTest, configBackendPullCommand) {
937 938 939
    testConfigBackendTimer(0, false, true);
}

940 941
// This test verifies that the server will be updated by the
// config-backend-pull command even when updates fail.
942
TEST_F(JSONFileBackendTest, configBackendPullCommandWithThrow) {
943 944 945
    testConfigBackendTimer(0, true, true);
}

946 947
// This test verifies that the server will be updated by the
// config-backend-pull command and the timer rescheduled.
948
TEST_F(JSONFileBackendTest, configBackendPullCommandWithTimer) {
949 950 951
    testConfigBackendTimer(1, false, true);
}

952 953
// Starting tests which require MySQL backend availability. Those tests
// will not be executed if Kea has been compiled without the
954
// --with-mysql.
955 956 957 958 959 960 961 962 963 964 965
#ifdef HAVE_MYSQL

/// @brief Test fixture class for the tests utilizing MySQL database
/// backend.
class JSONFileBackendMySQLTest : public JSONFileBackendTest {
public:

    /// @brief Constructor.
    ///
    /// Recreates MySQL schema for a test.
    JSONFileBackendMySQLTest() : JSONFileBackendTest() {
966
        // Ensure we have the proper schema with no transient data.
967 968 969 970 971 972 973
        createMySQLSchema();
    }

    /// @brief Destructor.
    ///
    /// Destroys MySQL schema.
    virtual ~JSONFileBackendMySQLTest() {
974
        // If data wipe enabled, delete transient data otherwise destroy the schema.
975 976 977 978 979 980 981 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 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
        destroyMySQLSchema();
    }

    /// @brief Creates server configuration with specified backend type.
    ///
    /// @param backend Backend type or empty string to indicate that the
    /// backend configuration should not be placed in the resulting
    /// JSON configuration.
    ///
    /// @return Server configuration.
    std::string createConfiguration(const std::string& backend) const;

    /// @brief Test reconfiguration with a backend change.
    ///
    /// If any of the parameters is an empty string it indicates that the
    /// created configuration should exclude backend configuration.
    ///
    /// @param backend_first Type of a backend to be used initially.
    /// @param backend_second Type of a backend to be used after
    /// reconfiguration.
    void testBackendReconfiguration(const std::string& backend_first,
                                    const std::string& backend_second);
};

std::string
JSONFileBackendMySQLTest::createConfiguration(const std::string& backend) const {
    // This is basic server configuration which excludes lease database
    // backend specification. The default Memfile backend should be
    // initialized in this case.
    std::ostringstream config;
    config <<
        "{ \"Dhcp4\": {"
        "\"interfaces-config\": {"
        "    \"interfaces\": [ ]"
        "},";

    // For non-empty lease backend type we have to add a backend configuration
    // section.
    if (!backend.empty()) {
        config <<
        "\"lease-database\": {"
        "     \"type\": \"" << backend << "\"";

        // SQL backends require database credentials.
        if (backend != "memfile") {
            config <<
                ","
                "     \"name\": \"keatest\","
                "     \"user\": \"keatest\","
                "     \"password\": \"keatest\"";
        }
        config << "},";
    }

    // Append the rest of the configuration.
    config <<
        "\"rebind-timer\": 2000, "
        "\"renew-timer\": 1000, \n"
        "\"subnet4\": [ ],"
        "\"valid-lifetime\": 4000 }"
        "}";

    return (config.str());
}

void
JSONFileBackendMySQLTest::
testBackendReconfiguration(const std::string& backend_first,
                           const std::string& backend_second) {
1044
    writeFile(TEST_FILE, createConfiguration(backend_first));
1045

Andrei Pavel's avatar
Andrei Pavel committed
1046
    // Create an instance of the server and initialize it.
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
    boost::scoped_ptr<NakedControlledDhcpv4Srv> srv;
    ASSERT_NO_THROW(srv.reset(new NakedControlledDhcpv4Srv()));
    srv->setConfigFile(TEST_FILE);
    ASSERT_NO_THROW(srv->init(TEST_FILE));

    // The backend should have been created and its type should be
    // correct.
    ASSERT_NO_THROW(static_cast<void>(LeaseMgrFactory::instance()));
    EXPECT_EQ(backend_first.empty() ? "memfile" : backend_first,
              LeaseMgrFactory::instance().getType());

1058
    // New configuration modifies the lease database backend type.
1059
    writeFile(TEST_FILE, createConfiguration(backend_second));
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092

    // Explicitly calling signal handler for SIGHUP to trigger server
    // reconfiguration.
    srv->signal_handler_(SIGHUP);

    // The backend should have been created and its type should be
    // correct.
    ASSERT_NO_THROW(static_cast<void>(LeaseMgrFactory::instance()));
    EXPECT_EQ(backend_second.empty() ? "memfile" : backend_second,
              LeaseMgrFactory::instance().getType());
}


// This test verifies that backend specification can be added on
// server reconfiguration.
TEST_F(JSONFileBackendMySQLTest, reconfigureBackendUndefinedToMySQL) {
    testBackendReconfiguration("", "mysql");
}

// This test verifies that when backend specification is removed the
// default backend is used.
TEST_F(JSONFileBackendMySQLTest, reconfigureBackendMySQLToUndefined) {
    testBackendReconfiguration("mysql", "");
}

// This test verifies that backend type can be changed from Memfile
// to MySQL.
TEST_F(JSONFileBackendMySQLTest, reconfigureBackendMemfileToMySQL) {
    testBackendReconfiguration("memfile", "mysql");
}

#endif

1093
} // End of anonymous namespace