cql_host_data_source_unittest.cc 19.7 KB
Newer Older
Andrei Pavel's avatar
Andrei Pavel committed
1
// Copyright (C) 2015-2017 Internet Systems Consortium, Inc. ("ISC")
Andrei Pavel's avatar
Andrei Pavel committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <config.h>

#include <asiolink/io_address.h>
#include <dhcpsrv/cql_connection.h>
#include <dhcpsrv/cql_host_data_source.h>
#include <dhcpsrv/cql_lease_mgr.h>
#include <dhcpsrv/host.h>
#include <dhcpsrv/host_data_source_factory.h>
#include <dhcpsrv/tests/generic_host_data_source_unittest.h>
#include <dhcpsrv/tests/test_utils.h>
#include <dhcpsrv/testutils/cql_schema.h>
#include <exceptions/exceptions.h>

#include <gtest/gtest.h>

#include <algorithm>
#include <sstream>
#include <string>
#include <utility>

Andrei Pavel's avatar
Andrei Pavel committed
27 28
namespace {

Andrei Pavel's avatar
Andrei Pavel committed
29 30 31 32 33 34 35
using namespace isc;
using namespace isc::asiolink;
using namespace isc::dhcp;
using namespace isc::dhcp::test;

class CqlHostDataSourceTest : public GenericHostDataSourceTest {
public:
Andrei Pavel's avatar
Andrei Pavel committed
36 37
    /// @brief Clears the database and opens connection to it.
    void initializeTest() {
Andrei Pavel's avatar
Andrei Pavel committed
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
        // Ensure schema is the correct one.
        destroyCqlSchema(false, true);
        createCqlSchema(false, true);

        // Connect to the database
        try {
            HostDataSourceFactory::create(validCqlConnectionString());
        } catch (...) {
            std::cerr << "*** ERROR: unable to open database. The test"
                         "*** environment is broken and must be fixed before"
                         "*** the CQL tests will run correctly."
                         "*** The reason for the problem is described in the"
                         "*** accompanying exception output.";
            throw;
        }

        hdsptr_ = HostDataSourceFactory::getHostDataSourcePtr();
    }

Andrei Pavel's avatar
Andrei Pavel committed
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
    /// @brief Destroys the HDS and the schema.
    void destroyTest() {
        try {
            hdsptr_->rollback();
        } catch (...) {
            // Rollback may fail if backend is in read only mode. That's ok.
        }
        HostDataSourceFactory::destroy();
        destroyCqlSchema(false, true);
    }

    /// @brief Constructor
    ///
    /// Deletes everything from the database and opens it.
    CqlHostDataSourceTest() {
        initializeTest();
    }

Andrei Pavel's avatar
Andrei Pavel committed
75 76 77 78 79 80
    /// @brief Destructor
    ///
    /// Rolls back all pending transactions.  The deletion of myhdsptr_ will
    /// close the database.  Then reopen it and delete everything created by the
    /// test.
    virtual ~CqlHostDataSourceTest() {
Andrei Pavel's avatar
Andrei Pavel committed
81
        destroyTest();
Andrei Pavel's avatar
Andrei Pavel committed
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
    }

    /// @brief Reopen the database
    ///
    /// Closes the database and re-open it.  Anything committed should be
    /// visible.
    ///
    /// Parameter is ignored for CQL backend as the v4 and v6 leases share
    /// the same database.
    void reopen(Universe) {
        HostDataSourceFactory::destroy();
        HostDataSourceFactory::create(validCqlConnectionString());
        hdsptr_ = HostDataSourceFactory::getHostDataSourcePtr();
    }
};

/// @brief Check that database can be opened
///
/// This test checks if the CqlHostDataSource can be instantiated.  This happens
/// only if the database can be opened.  Note that this is not part of the
/// CqlLeaseMgr test fixure set.  This test checks that the database can be
/// opened: the fixtures assume that and check basic operations.

TEST(CqlHostDataSource, OpenDatabase) {
    // Schema needs to be created for the test to work.
    destroyCqlSchema(false, true);
    createCqlSchema(false, true);

    // Check that lease manager open the database opens correctly and tidy up.
    //  If it fails, print the error message.
    try {
        HostDataSourceFactory::create(validCqlConnectionString());
        EXPECT_NO_THROW((void)HostDataSourceFactory::getHostDataSourcePtr());
        HostDataSourceFactory::destroy();
    } catch (const isc::Exception& ex) {
        FAIL() << "*** ERROR: unable to open database, reason:\n"
               << "    " << ex.what() << "\n"
               << "*** The test environment is broken and must be fixed\n"
               << "*** before the CQL tests will run correctly.\n";
    }

    // Check that lease manager open the database opens correctly with a longer
    // timeout.  If it fails, print the error message.
    try {
        std::string connection_string = validCqlConnectionString() +
                                        std::string(" ") +
                                        std::string(VALID_TIMEOUT);
        HostDataSourceFactory::create(connection_string);
        EXPECT_NO_THROW((void)HostDataSourceFactory::getHostDataSourcePtr());
        HostDataSourceFactory::destroy();
    } catch (const isc::Exception& ex) {
        FAIL() << "*** ERROR: unable to open database, reason:\n"
               << "    " << ex.what() << "\n"
               << "*** The test environment is broken and must be fixed\n"
               << "*** before the CQL tests will run correctly.\n";
    }

    // Check that attempting to get an instance of the host data source when
    // none is set throws an exception.
    EXPECT_FALSE(HostDataSourceFactory::getHostDataSourcePtr());

    // Check that wrong specification of backend throws an exception.
    // (This is really a check on HostDataSourceFactory, but is convenient to
    // perform here.)
    EXPECT_THROW(
        HostDataSourceFactory::create(connectionString(
            NULL, VALID_NAME, VALID_HOST, INVALID_USER, VALID_PASSWORD)),
        InvalidParameter);
    EXPECT_THROW(
        HostDataSourceFactory::create(connectionString(
            INVALID_TYPE, VALID_NAME, VALID_HOST, VALID_USER, VALID_PASSWORD)),
        InvalidType);

    // Check that invalid login data does not cause an exception, CQL should use
    // default values.
    EXPECT_NO_THROW(HostDataSourceFactory::create(connectionString(
        CQL_VALID_TYPE, INVALID_NAME, VALID_HOST, VALID_USER, VALID_PASSWORD)));
    EXPECT_NO_THROW(HostDataSourceFactory::create(connectionString(
        CQL_VALID_TYPE, VALID_NAME, INVALID_HOST, VALID_USER, VALID_PASSWORD)));
    EXPECT_NO_THROW(HostDataSourceFactory::create(connectionString(
        CQL_VALID_TYPE, VALID_NAME, VALID_HOST, INVALID_USER, VALID_PASSWORD)));
    EXPECT_NO_THROW(HostDataSourceFactory::create(connectionString(
        CQL_VALID_TYPE, VALID_NAME, VALID_HOST, VALID_USER, INVALID_PASSWORD)));

    // Check that invalid timeouts throw DbOperationError.
    EXPECT_THROW(HostDataSourceFactory::create(connectionString(
                     CQL_VALID_TYPE, VALID_NAME, VALID_HOST, VALID_USER,
                     VALID_PASSWORD, INVALID_TIMEOUT_1)),
                 DbOperationError);
    EXPECT_THROW(HostDataSourceFactory::create(connectionString(
                     CQL_VALID_TYPE, VALID_NAME, VALID_HOST, VALID_USER,
                     VALID_PASSWORD, INVALID_TIMEOUT_2)),
                 DbOperationError);

    // Check that CQL allows the hostname to not be specified.
    EXPECT_NO_THROW(HostDataSourceFactory::create(connectionString(
        CQL_VALID_TYPE, NULL, VALID_HOST, INVALID_USER, VALID_PASSWORD)));

    // Tidy up after the test
    destroyCqlSchema(false, true);
}

Andrei Pavel's avatar
Andrei Pavel committed
184
/// @brief Check conversion methods
Andrei Pavel's avatar
Andrei Pavel committed
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 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 282 283 284 285 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 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 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 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
///
/// The server works using cltt and valid_filetime.  In the database, the
/// information is stored as expire_time and valid-lifetime, which are
/// related by
///
/// expire_time = cltt + valid_lifetime
///
/// This test checks that the conversion is correct.  It does not check that the
/// data is entered into the database correctly, only that the CQL_TIME
/// structure used for the entry is correctly set up.
TEST(CqlConnection, checkTimeConversion) {
    const time_t cltt = time(NULL);
    const uint32_t valid_lft = 86400;  // 1 day
    cass_int64_t cql_expire;

    // Convert to the database time
    CqlExchange::convertToDatabaseTime(cltt, valid_lft, cql_expire);

    // Convert back
    time_t converted_cltt = 0;
    CqlExchange::convertFromDatabaseTime(cql_expire, valid_lft, converted_cltt);
    EXPECT_EQ(cltt, converted_cltt);
}
// Test verifies if a host reservation can be added and later retrieved by IPv4
// address. Host uses hw address as identifier.
TEST_F(CqlHostDataSourceTest, basic4HWAddr) {
    testBasic4(Host::IDENT_HWADDR);
}

// Test verifies if a host reservation can be added and later retrieved by IPv4
// address. Host uses client-id (DUID) as identifier.
TEST_F(CqlHostDataSourceTest, basic4ClientId) {
    testBasic4(Host::IDENT_DUID);
}

// Test verifies that multiple hosts can be added and later retrieved by their
// reserved IPv4 address. This test uses HW addresses as identifiers.
TEST_F(CqlHostDataSourceTest, getByIPv4HWaddr) {
    testGetByIPv4(Host::IDENT_HWADDR);
}

// Test verifies that multiple hosts can be added and later retrieved by their
// reserved IPv4 address. This test uses client-id (DUID) as identifiers.
TEST_F(CqlHostDataSourceTest, getByIPv4ClientId) {
    testGetByIPv4(Host::IDENT_DUID);
}

// Test verifies if a host reservation can be added and later retrieved by
// hardware address.
TEST_F(CqlHostDataSourceTest, get4ByHWaddr) {
    testGet4ByIdentifier(Host::IDENT_HWADDR);
}

// Test verifies if a host reservation can be added and later retrieved by
// DUID.
TEST_F(CqlHostDataSourceTest, get4ByDUID) {
    testGet4ByIdentifier(Host::IDENT_DUID);
}

// Test verifies if a host reservation can be added and later retrieved by
// circuit id.
TEST_F(CqlHostDataSourceTest, get4ByCircuitId) {
    testGet4ByIdentifier(Host::IDENT_CIRCUIT_ID);
}

// Test verifies if hardware address and client identifier are not confused.
TEST_F(CqlHostDataSourceTest, hwaddrNotClientId1) {
    testHWAddrNotClientId();
}

// Test verifies if hardware address and client identifier are not confused.
TEST_F(CqlHostDataSourceTest, hwaddrNotClientId2) {
    testClientIdNotHWAddr();
}

// Test verifies if a host with FQDN hostname can be stored and later retrieved.
TEST_F(CqlHostDataSourceTest, hostnameFQDN) {
    testHostname("foo.example.org", 1);
}

// Test verifies if 100 hosts with unique FQDN hostnames can be stored and later
// retrieved.
TEST_F(CqlHostDataSourceTest, hostnameFQDN100) {
    testHostname("foo.example.org", 100);
}

// Test verifies if a host without any hostname specified can be stored and
// later retrieved.
TEST_F(CqlHostDataSourceTest, noHostname) {
    testHostname("", 1);
}

// Test verifies if the hardware or client-id query can match hardware address.
TEST_F(CqlHostDataSourceTest, DISABLED_hwaddrOrClientId1) {
    /// @todo: The logic behind ::get4(subnet_id, hwaddr, duid) call needs to
    /// be discussed.
    ///
    /// @todo: Add host reservation with hardware address X, try to retrieve
    /// host for hardware address X or client identifier Y, verify that the
    /// reservation is returned.
}

// Test verifies if the hardware or client-id query can match client-id.
TEST_F(CqlHostDataSourceTest, DISABLED_hwaddrOrClientId2) {
    /// @todo: The logic behind ::get4(subnet_id, hwaddr, duid) call needs to
    /// be discussed.
    ///
    /// @todo: Add host reservation with client identifier Y, try to retrieve
    /// host for hardware address X or client identifier Y, verify that the
    /// reservation is returned.
}

// Test verifies that host with IPv6 address and DUID can be added and
// later retrieved by IPv6 address.
TEST_F(CqlHostDataSourceTest, get6AddrWithDuid) {
    testGetByIPv6(Host::IDENT_DUID, false);
}

// Test verifies that host with IPv6 address and HWAddr can be added and
// later retrieved by IPv6 address.
TEST_F(CqlHostDataSourceTest, get6AddrWithHWAddr) {
    testGetByIPv6(Host::IDENT_HWADDR, false);
}

// Test verifies that host with IPv6 prefix and DUID can be added and
// later retrieved by IPv6 prefix.
TEST_F(CqlHostDataSourceTest, get6PrefixWithDuid) {
    testGetByIPv6(Host::IDENT_DUID, true);
}

// Test verifies that host with IPv6 prefix and HWAddr can be added and
// later retrieved by IPv6 prefix.
TEST_F(CqlHostDataSourceTest, get6PrefixWithHWaddr) {
    testGetByIPv6(Host::IDENT_HWADDR, true);
}

// Test verifies that host with IPv6 prefix reservation can be retrieved
// by subnet id and prefix value.
TEST_F(CqlHostDataSourceTest, get6SubnetPrefix) {
    testGetBySubnetIPv6();
}

// Test verifies if a host reservation can be added and later retrieved by
// hardware address.
TEST_F(CqlHostDataSourceTest, get6ByHWaddr) {
    testGet6ByHWAddr();
}

// Test verifies if a host reservation can be added and later retrieved by
// client identifier.
TEST_F(CqlHostDataSourceTest, get6ByClientId) {
    testGet6ByClientId();
}

// Test verifies if a host reservation can be stored with both IPv6 address and
// prefix.
TEST_F(CqlHostDataSourceTest, addr6AndPrefix) {
    testAddr6AndPrefix();
}

// Tests if host with multiple IPv6 reservations can be added and then
// retrieved correctly. Test checks reservations comparing.
TEST_F(CqlHostDataSourceTest, multipleReservations) {
    testMultipleReservations();
}

// Tests if compareIPv6Reservations() method treats same pool of reservations
// but added in different order as equal.
TEST_F(CqlHostDataSourceTest, multipleReservationsDifferentOrder) {
    testMultipleReservationsDifferentOrder();
}

// Test verifies if multiple client classes for IPv4 can be stored.
TEST_F(CqlHostDataSourceTest, DISABLED_multipleClientClasses4) {
    /// @todo: Implement this test as part of #4213.

    /// Add host reservation with a multiple v4 client-classes, retrieve it and
    /// make sure that all client classes are retrieved properly.
}

// Test verifies if multiple client classes for IPv6 can be stored.
TEST_F(CqlHostDataSourceTest, DISABLED_multipleClientClasses6) {
    /// @todo: Implement this test as part of #4213.

    /// Add host reservation with a multiple v6 client-classes, retrieve it and
    /// make sure that all client classes are retrieved properly.
}

// Test verifies if multiple client classes for both IPv4 and IPv6 can be
// stored.
TEST_F(CqlHostDataSourceTest, DISABLED_multipleClientClassesBoth) {
    /// @todo: Implement this test as part of #4213.

    /// Add host reservation with a multiple v4 and v6 client-classes, retrieve
    /// it and make sure that all client classes are retrieved properly. Also,
    /// check that the classes are not confused.
}

// Test if the same host can have reservations in different subnets (with the
// same hardware address). The test logic is as follows:
// Insert 10 host reservations for a given physical host (the same
// hardware address), but for different subnets (different subnet-ids).
// Make sure that getAll() returns them all correctly.
TEST_F(CqlHostDataSourceTest, multipleSubnetsHWAddr) {
    testMultipleSubnets(10, Host::IDENT_HWADDR);
}

// Test if the same host can have reservations in different subnets (with the
// same client identifier). The test logic is as follows:
//
// Insert 10 host reservations for a given physical host (the same
// client-identifier), but for different subnets (different subnet-ids).
// Make sure that getAll() returns them correctly.
TEST_F(CqlHostDataSourceTest, multipleSubnetsClientId) {
    testMultipleSubnets(10, Host::IDENT_DUID);
}

// Test if host reservations made for different IPv6 subnets are handled
// correctly. The test logic is as follows:
//
// Insert 10 host reservations for different subnets. Make sure that
// get6(subnet-id, ...) calls return correct reservation.
TEST_F(CqlHostDataSourceTest, subnetId6) {
    testSubnetId6(10, Host::IDENT_HWADDR);
}

// Test if the duplicate host instances can't be inserted. The test logic is as
// follows: try to add multiple instances of the same host reservation and
// verify that the second and following attempts will throw exceptions.
// Hosts with same DUID.
TEST_F(CqlHostDataSourceTest, addDuplicate6WithDUID) {
    testAddDuplicate6WithSameDUID();
}

// Test if the duplicate host instances can't be inserted. The test logic is as
// follows: try to add multiple instances of the same host reservation and
// verify that the second and following attempts will throw exceptions.
// Hosts with same HWAddr.
TEST_F(CqlHostDataSourceTest, addDuplicate6WithHWAddr) {
    testAddDuplicate6WithSameHWAddr();
}

// Test if the duplicate IPv4 host instances can't be inserted. The test logic
// is as follows: try to add multiple instances of the same host reservation and
// verify that the second and following attempts will throw exceptions.
TEST_F(CqlHostDataSourceTest, addDuplicate4) {
    testAddDuplicate4();
}

// This test verifies that DHCPv4 options can be inserted in a binary format
/// and retrieved from the CQL host database.
TEST_F(CqlHostDataSourceTest, optionsReservations4) {
    testOptionsReservations4(false);
}

// This test verifies that DHCPv6 options can be inserted in a binary format
/// and retrieved from the CQL host database.
TEST_F(CqlHostDataSourceTest, optionsReservations6) {
    testOptionsReservations6(false);
}

// This test verifies that DHCPv4 and DHCPv6 options can be inserted in a
/// binary format and retrieved with a single query to the database.
TEST_F(CqlHostDataSourceTest, optionsReservations46) {
    testOptionsReservations46(false);
}

// This test verifies that DHCPv4 options can be inserted in a textual format
/// and retrieved from the CQL host database.
TEST_F(CqlHostDataSourceTest, formattedOptionsReservations4) {
    testOptionsReservations4(true);
}

// This test verifies that DHCPv6 options can be inserted in a textual format
/// and retrieved from the CQL host database.
TEST_F(CqlHostDataSourceTest, formattedOptionsReservations6) {
    testOptionsReservations6(true);
}

// This test verifies that DHCPv4 and DHCPv6 options can be inserted in a
// textual format and retrieved with a single query to the database.
TEST_F(CqlHostDataSourceTest, formattedOptionsReservations46) {
    testOptionsReservations46(true);
}

// This test checks transactional insertion of the host information
// into the database. The failure to insert host information at
// any stage should cause the whole transaction to be rolled back.
TEST_F(CqlHostDataSourceTest, testAddRollback) {
    // Make sure we have the pointer to the host data source.
    ASSERT_TRUE(hdsptr_);

    // To test the transaction rollback mechanism we need to cause the
    // insertion of host information to fail at some stage. The 'hosts'
    // table should be updated correctly but the failure should occur
    // when inserting reservations or options. The simplest way to
    // achieve that is to simply drop one of the tables. To do so, we
    // connect to the database and issue a DROP query.
    CqlConnection::ParameterMap params;
    params["name"] = "keatest";
    params["user"] = "keatest";
    params["password"] = "keatest";
    CqlConnection connection(params);
    ASSERT_NO_THROW(connection.openDatabase());

Andrei Pavel's avatar
Andrei Pavel committed
490
    // Drop every table so we make sure host_reservations doesn't exist anymore.
Andrei Pavel's avatar
Andrei Pavel committed
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
    destroyCqlSchema(false, true);

    // Create a host with a reservation.
    HostPtr host = initializeHost6("2001:db8:1::1", Host::IDENT_HWADDR, false);
    // Let's assign some DHCPv4 subnet to the host, because we will use the
    // DHCPv4 subnet to try to retrieve the host after failed insertion.
    host->setIPv4SubnetID(SubnetID(4));

    // There is no ipv6_reservations table, so the insertion should fail.
    ASSERT_THROW(hdsptr_->add(host), DbOperationError);

    // Even though we have created a DHCPv6 host, we can't use get6()
    // method to retrieve the host from the database, because the
    // query would expect that the ipv6_reservations table is present.
    // Therefore, the query would fail. Instead, we use the get4 method
    // which uses the same client identifier, but doesn't attempt to
    // retrieve the data from ipv6_reservations table. The query should
    // pass but return no host because the (insert) transaction is expected
    // to be rolled back.
    ASSERT_THROW(
        hdsptr_->get4(host->getIPv4SubnetID(), host->getIdentifierType(),
                      &host->getIdentifier()[0], host->getIdentifier().size()),
        DbOperationError);
}

516
}  // namespace