]> git.ipfire.org Git - thirdparty/kea.git/commitdiff
[5589] Initial checkin
authorThomas Markwalder <tmark@isc.org>
Wed, 9 May 2018 20:00:10 +0000 (16:00 -0400)
committerThomas Markwalder <tmark@isc.org>
Wed, 9 May 2018 20:00:10 +0000 (16:00 -0400)
New stat_cmds hook library initial commit.
Both stat-lease4/6-get commands implemented and unit tested

modified:
    configure.ac
    src/hooks/dhcp/Makefile.am
new:
    src/hooks/dhcp/stat_cmds/.gitignore
    src/hooks/dhcp/stat_cmds/Makefile.am
    src/hooks/dhcp/stat_cmds/stat_cmds.cc
    src/hooks/dhcp/stat_cmds/stat_cmds.dox
    src/hooks/dhcp/stat_cmds/stat_cmds.h
    src/hooks/dhcp/stat_cmds/stat_cmds_callouts.cc
    src/hooks/dhcp/stat_cmds/stat_cmds_log.cc
    src/hooks/dhcp/stat_cmds/stat_cmds_log.h
    src/hooks/dhcp/stat_cmds/stat_cmds_messages.mes
    src/hooks/dhcp/stat_cmds/tests/.gitignore
    src/hooks/dhcp/stat_cmds/tests/Makefile.am
    src/hooks/dhcp/stat_cmds/tests/run_unittests.cc
    src/hooks/dhcp/stat_cmds/tests/stat_cmds_unittest.cc
    src/hooks/dhcp/stat_cmds/version.cc

16 files changed:
configure.ac
src/hooks/dhcp/Makefile.am
src/hooks/dhcp/stat_cmds/.gitignore [new file with mode: 0644]
src/hooks/dhcp/stat_cmds/Makefile.am [new file with mode: 0644]
src/hooks/dhcp/stat_cmds/stat_cmds.cc [new file with mode: 0644]
src/hooks/dhcp/stat_cmds/stat_cmds.dox [new file with mode: 0644]
src/hooks/dhcp/stat_cmds/stat_cmds.h [new file with mode: 0644]
src/hooks/dhcp/stat_cmds/stat_cmds_callouts.cc [new file with mode: 0644]
src/hooks/dhcp/stat_cmds/stat_cmds_log.cc [new file with mode: 0644]
src/hooks/dhcp/stat_cmds/stat_cmds_log.h [new file with mode: 0644]
src/hooks/dhcp/stat_cmds/stat_cmds_messages.mes [new file with mode: 0644]
src/hooks/dhcp/stat_cmds/tests/.gitignore [new file with mode: 0644]
src/hooks/dhcp/stat_cmds/tests/Makefile.am [new file with mode: 0644]
src/hooks/dhcp/stat_cmds/tests/run_unittests.cc [new file with mode: 0644]
src/hooks/dhcp/stat_cmds/tests/stat_cmds_unittest.cc [new file with mode: 0644]
src/hooks/dhcp/stat_cmds/version.cc [new file with mode: 0644]

index fdef5becb9f25d3fda2faf6595c99e69f888df41..71732080b5cc1e7fffad7081df838e0a46f01f22 100644 (file)
@@ -1400,6 +1400,8 @@ AC_CONFIG_FILES([Makefile
                  src/hooks/dhcp/user_chk/Makefile
                  src/hooks/dhcp/user_chk/tests/Makefile
                  src/hooks/dhcp/user_chk/tests/test_data_files_config.h
+                 src/hooks/dhcp/stat_cmds/Makefile
+                 src/hooks/dhcp/stat_cmds/tests/Makefile
                  src/lib/Makefile
                  src/lib/asiodns/Makefile
                  src/lib/asiodns/tests/Makefile
index ebf9cfe7432f596de777bf191adab9765e6003c3..26daf09e7fbb2480ed12a0d887a326c9166ef181 100644 (file)
@@ -1 +1 @@
-SUBDIRS = user_chk lease_cmds
+SUBDIRS = user_chk lease_cmds stat_cmds
diff --git a/src/hooks/dhcp/stat_cmds/.gitignore b/src/hooks/dhcp/stat_cmds/.gitignore
new file mode 100644 (file)
index 0000000..68df133
--- /dev/null
@@ -0,0 +1,4 @@
+/stat_cmds_messages.cc
+/stat_cmds_messages.h
+/s-messages
+/html
diff --git a/src/hooks/dhcp/stat_cmds/Makefile.am b/src/hooks/dhcp/stat_cmds/Makefile.am
new file mode 100644 (file)
index 0000000..e6ff587
--- /dev/null
@@ -0,0 +1,63 @@
+SUBDIRS = . tests
+
+AM_CPPFLAGS  = -I$(top_builddir)/src/lib -I$(top_srcdir)/src/lib
+AM_CPPFLAGS += $(BOOST_INCLUDES)
+AM_CXXFLAGS  = $(KEA_CXXFLAGS)
+
+# Define rule to build logging source files from message file
+stat_cmds_messages.h stat_cmds_messages.cc: s-messages
+s-messages: stat_cmds_messages.mes
+       $(top_builddir)/src/lib/log/compiler/kea-msg-compiler $(top_srcdir)/src/hooks/dhcp/stat_cmds/stat_cmds_messages.mes
+       touch $@
+
+# Tell automake that the message files are built as part of the build process
+# (so that they are built before the main library is built).
+BUILT_SOURCES = stat_cmds_messages.h stat_cmds_messages.cc
+
+# Ensure that the message file and doxygen file is included in the distribution
+EXTRA_DIST = stat_cmds_messages.mes
+EXTRA_DIST += stat_cmds.dox
+
+# Get rid of generated message files on a clean
+CLEANFILES = *.gcno *.gcda stat_cmds_messages.h stat_cmds_messages.cc s-messages
+
+# convenience archive
+
+noinst_LTLIBRARIES = libstat_cmds.la
+
+libstat_cmds_la_SOURCES  = stat_cmds.cc stat_cmds.h
+libstat_cmds_la_SOURCES += stat_cmds_callouts.cc
+libstat_cmds_la_SOURCES += stat_cmds_log.cc stat_cmds_log.h
+libstat_cmds_la_SOURCES += version.cc
+
+nodist_libstat_cmds_la_SOURCES = stat_cmds_messages.cc stat_cmds_messages.h
+
+libstat_cmds_la_CXXFLAGS = $(AM_CXXFLAGS)
+libstat_cmds_la_CPPFLAGS = $(AM_CPPFLAGS)
+
+# install the shared object into $(libdir)/hooks
+lib_hooksdir = $(libdir)/hooks
+lib_hooks_LTLIBRARIES = libdhcp_stat_cmds.la
+
+libdhcp_stat_cmds_la_SOURCES  =
+libdhcp_stat_cmds_la_LDFLAGS  = $(AM_LDFLAGS)
+libdhcp_stat_cmds_la_LDFLAGS  += -avoid-version -export-dynamic -module
+libdhcp_stat_cmds_la_LIBADD  = libstat_cmds.la
+libdhcp_stat_cmds_la_LIBADD  += $(top_builddir)/src/lib/dhcpsrv/libkea-dhcpsrv.la
+libdhcp_stat_cmds_la_LIBADD  += $(top_builddir)/src/lib/config/libkea-cfgclient.la
+libdhcp_stat_cmds_la_LIBADD  += $(top_builddir)/src/lib/cc/libkea-cc.la
+libdhcp_stat_cmds_la_LIBADD  += $(top_builddir)/src/lib/hooks/libkea-hooks.la
+libdhcp_stat_cmds_la_LIBADD  += $(top_builddir)/src/lib/asiolink/libkea-asiolink.la
+libdhcp_stat_cmds_la_LIBADD  += $(top_builddir)/src/lib/dhcp/libkea-dhcp++.la
+libdhcp_stat_cmds_la_LIBADD  += $(top_builddir)/src/lib/eval/libkea-eval.la
+libdhcp_stat_cmds_la_LIBADD  += $(top_builddir)/src/lib/dhcp_ddns/libkea-dhcp_ddns.la
+libdhcp_stat_cmds_la_LIBADD  += $(top_builddir)/src/lib/stats/libkea-stats.la
+libdhcp_stat_cmds_la_LIBADD  += $(top_builddir)/src/lib/dns/libkea-dns++.la
+libdhcp_stat_cmds_la_LIBADD  += $(top_builddir)/src/lib/cryptolink/libkea-cryptolink.la
+libdhcp_stat_cmds_la_LIBADD  += $(top_builddir)/src/lib/log/libkea-log.la
+libdhcp_stat_cmds_la_LIBADD  += $(top_builddir)/src/lib/util/threads/libkea-threads.la
+libdhcp_stat_cmds_la_LIBADD  += $(top_builddir)/src/lib/util/libkea-util.la
+libdhcp_stat_cmds_la_LIBADD  += $(top_builddir)/src/lib/exceptions/libkea-exceptions.la
+libdhcp_stat_cmds_la_LIBADD  += $(LOG4CPLUS_LIBS)
+libdhcp_stat_cmds_la_LIBADD  += $(CRYPTO_LIBS)
+libdhcp_stat_cmds_la_LIBADD  += $(BOOST_LIBS)
diff --git a/src/hooks/dhcp/stat_cmds/stat_cmds.cc b/src/hooks/dhcp/stat_cmds/stat_cmds.cc
new file mode 100644 (file)
index 0000000..e6c45fd
--- /dev/null
@@ -0,0 +1,639 @@
+// Copyright (C) 2018 Internet Systems Consortium, Inc. ("ISC")
+//
+// 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 <config/command_mgr.h>
+#include <config/cmds_impl.h>
+#include <cc/command_interpreter.h>
+#include <cc/data.h>
+#include <dhcpsrv/cfgmgr.h>
+#include <dhcpsrv/lease_mgr.h>
+#include <dhcpsrv/lease_mgr_factory.h>
+#include <dhcpsrv/subnet_id.h>
+#include <hooks/hooks.h>
+#include <exceptions/exceptions.h>
+#include <stat_cmds.h>
+#include <stat_cmds_log.h>
+#include <stats/stats_mgr.h>
+#include <util/boost_time_utils.h>
+
+#include <boost/date_time/posix_time/posix_time.hpp>
+#include <string>
+
+using namespace isc::dhcp;
+using namespace isc::data;
+using namespace isc::config;
+using namespace isc::asiolink;
+using namespace isc::hooks;
+using namespace isc::stats;
+using namespace std;
+
+namespace isc {
+namespace stat_cmds {
+
+/// @brief Exception thrown no subnets fall within the selection criteria
+/// This exception is thrown when a valid combination of query parameters
+/// excludes all known (i.e. configured) subnets.
+class NotFound: public isc::Exception {
+public:
+    NotFound (const char* file, size_t line, const char* what) :
+        isc::Exception(file, line, what) { };
+};
+
+///@brief Implements command handlinge for stat-lease<x>-get commands
+class LeaseStatCmdsImpl : private CmdsImpl {
+public:
+
+    /// @brief Wrapper class stat-lease<x>-get command parameters.
+    class Parameters {
+    public:
+        /// @brief Specifies the subnet-id for a single subnet, or
+        /// the first subnet for a subnet range
+        SubnetID first_subnet_id_;
+
+        /// @brief Specifies the last subnet for subnet range
+        SubnetID last_subnet_id_;
+
+        /// @brief Denotes the query selection mode all, subnet,
+        /// or subnet range
+        LeaseStatsQuery::SelectMode select_mode_;
+    };
+
+public:
+
+    /// @brief Provides the implementation for stat-lease4-get,
+    /// @ref isc::stat_cmds::StatCmds::statLease4GetHandler
+    ///
+    /// It parses the command arguments, and then invokes makeResult4()
+    /// to fulfull the lease6 statistics fetch. It then constructs the outbound
+    /// response based on those results.  If a NotFound exception is caught,
+    /// a CONTROL_RESULT_EMTPY response is generated.
+    ///
+    /// @param handle Callout context - which is expected to contain the
+    /// command JSON text in the "command" argument
+    /// @return 0 upon success, non-zero otherwise
+    int
+    statLease4GetHandler(CalloutHandle& handle);
+
+    /// @brief Provides the implementation for stat-lease6-get,
+    /// @ref isc::stat_cmds::StatCmds::statLease6GetHandler
+    ///
+    /// It parses the command arguments, and then invokes makeResult6()
+    /// to fulfull the lease6 statistics fetch. It then constructs the outbound
+    /// response based on those results.  If a NotFound exception is caught,
+    /// a CONTROL_RESULT_EMTPY response is generated.
+    ///
+    /// @param handle Callout context - which is expected to contain the
+    /// command JSON text in the "command" argument
+    /// @return 0 upon success, non-zero otherwise
+    int
+    statLease6GetHandler(CalloutHandle& handle);
+
+    /// @Brief Parses command arguments into stat-lease<x>-get parameters
+    /// @param cmd_args Element form of command arguments to parse
+    /// @throw BadValue if any of the following rules are broken:
+    ///
+    /// -# If subnet-id is specified it must be an integer > 0
+    /// -# If subnet-range is specified it must contain both
+    /// first-subnet-id and last-subnet-id and their values
+    /// must fulfill: 0 < first-subnet-id < last-subnet-id
+    /// -# subnet-id and subnet-range are mutually exclusive
+    Parameters getParameters(const ConstElementPtr& cmd_args);
+
+    /// @brief Executes the lease4 query and constructs the outbound result set
+    ///
+    /// This method uses the command parameters to identify the range
+    /// of configured subnets. If the range contains no known subnets
+    /// then a NotFound exception is thrown.  Having determined the range
+    /// to be valid, it then executes the appropriate Lease4 stats query via
+    /// the LeaseMgr.
+    ///
+    /// Lastly, it iterates over the qualifying subnets adding a row
+    /// of statistics for each one to the result-set.  Each row combines
+    /// the totals from StatsMgr with the type and state counts from the
+    /// query results.  For subnets with no query data (i.e. no leases),
+    /// their rows have non-zero values for totals only.
+    ///
+    /// @param result Element to which the constructed result-set will be added.
+    /// @param params Parsed stat-lease4-cmd parameters
+    /// @throw NotFound if the selection criteria eliminates all known subnets
+    uint64_t makeResultSet4(const ElementPtr& result, const Parameters& params);
+
+    /// @brief Executes the lease4 query and constructs the outbound result set
+    /// This method uses the command parameters to identify the range
+    /// of configured subnets. If the range contains no known subnets
+    /// then a NotFound exception is thrown.  Having determined the range
+    /// to be valid, it then executes the appropriate Lease6 stats query via
+    /// the LeaseMgr.
+    ///
+    /// Lastly, it iterates over the qualifying subnets adding a row
+    /// of statistics for each one to the result-set.  Each row combines
+    /// the totals from StatsMgr with the type and state counts from the
+    /// query results.  For subnets with no query data (i.e. no leases),
+    /// their rows have non-zero values for totals only.
+    ///
+    /// @param result Element to which the constructed result-set will be added.
+    /// @param params Parsed stat-lease6-cmd parameters
+    /// @throw NotFound if the selection criteria eliminates all known subnets
+    uint64_t makeResultSet6(const ElementPtr& result, const Parameters& params);
+
+    /// @brief Instantiates a new "empty" result-set Element
+    ///
+    /// Constructs a ElementPtr tree of an empty result set
+    /// for holding rows of the given column labels. In JSON
+    /// it appears as follows:
+    ///
+    /// "result-set": {
+    ///     "timestamp": "2018-03-22 09:43:30.815371",
+    ///     "columns": ["<label-1>, <label-2>, ... ],
+    ///     "rows": []
+    /// }
+    ///
+    /// And then adds it to the given wrapper element.
+    ///
+    /// @param wrapper Element to which the newly constructed result-set
+    /// will be added.
+    /// @param column_labels list of the column labels in the order the values
+    /// for each column will appear in the result-set rows
+    /// @return A reference to the writable list of rows of the result-set
+    ElementPtr createResultSet(const ElementPtr& wrapper,
+                               const std::vector<std::string>& column_labels);
+
+    /// @brief Adds a row of Lease4 stat values to a list of value rows
+    ///
+    /// @param[out] value_rows  list of rows to which to add
+    /// @param[out] subent_id  id of the subnet of the new row. This value is
+    /// also used for fetching the total addresses in the subnet
+    /// @param assigned number of assigned addresses in the subnet
+    /// @param assigned number of declined addresses in the subnet
+    void addValueRow4(ElementPtr value_rows, const SubnetID &subnet_id,
+                      int64_t assigned, int64_t declined);
+
+    /// @brief Adds a row of Lease6 stat values to a list of value rows
+    ///
+    /// @param[out] value_rows  list of rows to which to add
+    /// @param[out] subent_id  id of the subnet of the new row. This value is
+    /// also used for fetching the total NAs and PDs in the subnet
+    /// @param assigned number of assigned NAs in the subnet
+    /// @param declined number of declined NAs in the subnet
+    /// @param assigned_pds number of assigned PDs the subnet
+    void addValueRow6(ElementPtr value_rows, const SubnetID &subnet_id,
+                      int64_t assigned, int64_t declined, int64_t assigned_pds);
+
+    /// @brief Fetches a single statistic for a subnet from StatsMgr
+    ///
+    /// Uses the given id and name to query the StatsMgr for the desired value.
+    ///
+    /// @param subnet_id id of the desired subnet
+    /// @param name name of the desired statistic
+    int64_t getSubnetStat(const SubnetID& subnet_id, const std::string& name);
+};
+
+int
+LeaseStatCmdsImpl::statLease4GetHandler(CalloutHandle& handle) {
+    ElementPtr result = Element::createMap();
+    int response_code;
+    string txt = "malformed command";
+    try {
+        // Extract the command and then the parameters
+        extractCommand(handle);
+        Parameters params = getParameters(cmd_args_);
+
+        // Now build the result set
+        txt = "building result";
+        uint64_t rows = makeResultSet4(result, params);
+
+        // Eureka it worked!
+        response_code = CONTROL_RESULT_SUCCESS;
+        std::stringstream os;
+        os << "stat-lease4-get: " << rows << " rows found";
+        txt = os.str();
+    } catch (const NotFound& ex) {
+        // Criteria was valid but included no known subnets,
+        // so we return a not found response.
+        response_code = CONTROL_RESULT_EMPTY;
+        std::stringstream os;
+        os << "stat-lease4-get: " <<  "no matching data, " << ex.what();
+        txt = os.str();
+    } catch (const std::exception& ex) {
+        LOG_ERROR(stat_cmds_logger, STAT_LEASE4_GET_FAILED)
+            .arg(txt)
+            .arg(ex.what());
+        setErrorResponse(handle, ex.what());
+        return (1);
+    }
+
+    LOG_INFO(stat_cmds_logger, STAT_LEASE4_GET).arg(txt);
+    ConstElementPtr response = createAnswer(response_code, txt, result);
+    setResponse(handle, response);
+    return (0);
+}
+
+int
+LeaseStatCmdsImpl::statLease6GetHandler(CalloutHandle& handle) {
+    ElementPtr result = Element::createMap();
+    int response_code;
+    string txt = "malformed command";
+    try {
+        // Extract the command and then the parameters
+        extractCommand(handle);
+        Parameters params = getParameters(cmd_args_);
+
+        // Now build the result set
+        txt = "building result";
+        uint64_t rows = makeResultSet6(result, params);
+
+        // Eureka it worked!
+        response_code = CONTROL_RESULT_SUCCESS;
+        std::stringstream os;
+        os << "stat-lease6-get: " << rows << " rows found";
+        txt = os.str();
+    } catch (const NotFound& ex) {
+        // Criteria was valid but included no known subnets,
+        // so we return a not found response.
+        result = Element::createMap();
+        response_code = CONTROL_RESULT_EMPTY;
+        std::stringstream os;
+        os << "stat-lease6-get: " <<  "no matching data, " << ex.what();
+        txt = os.str();
+    } catch (const std::exception& ex) {
+        LOG_ERROR(stat_cmds_logger, STAT_LEASE6_GET_FAILED)
+            .arg(txt)
+            .arg(ex.what());
+        setErrorResponse(handle, ex.what());
+        return (1);
+    }
+
+    LOG_INFO(stat_cmds_logger, STAT_LEASE6_GET).arg(txt);
+    ConstElementPtr response = createAnswer(response_code, txt, result);
+    setResponse(handle, response);
+    return (0);
+}
+
+LeaseStatCmdsImpl::Parameters
+LeaseStatCmdsImpl::getParameters(const ConstElementPtr& cmd_args) {
+    Parameters params;
+
+    if (!cmd_args || cmd_args->getType() != Element::map) {
+        isc_throw(BadValue, "Parameters missing or are not a map.");
+    }
+
+    params.select_mode_ = LeaseStatsQuery::ALL_SUBNETS;
+    if (cmd_args->contains("subnet-id")) {
+
+        ConstElementPtr value = cmd_args->get("subnet-id");
+        if (value->getType() != Element::integer) {
+            isc_throw(BadValue, "'subnet-id' parameter is not integer");
+        }
+
+        if (value->intValue() <= 0) {
+            isc_throw(BadValue, "'subnet-id' parameter must be > 0");
+        }
+
+        params.first_subnet_id_ = value->intValue();
+        params.select_mode_ = LeaseStatsQuery::SINGLE_SUBNET;
+    }
+
+    if (cmd_args->contains("subnet-range")) {
+        if (params.select_mode_ == LeaseStatsQuery::SINGLE_SUBNET) {
+            isc_throw(BadValue, "Cannot specify both subnet-id and subnet-range");
+        }
+
+        ConstElementPtr range = cmd_args->get("subnet-range");
+        if (range->getType() != Element::map) {
+            isc_throw(BadValue, "subnet-range parameter is not a map");
+        }
+
+        ConstElementPtr value = range->get("first-subnet-id");
+        if (!value || value->getType() != Element::integer) {
+            isc_throw(BadValue, "'first-subnet-id' parameter missing or not an integer");
+        }
+
+        if (value->intValue() <= 0) {
+            isc_throw(BadValue, "'first-subnet-id' parameter must be > 0");
+        }
+
+        params.first_subnet_id_ = value->intValue();
+
+        value = range->get("last-subnet-id");
+        if (!value || value->getType() != Element::integer) {
+            isc_throw(BadValue, "'last-subnet-id' parameter missing or not an integer");
+        }
+
+        if (value->intValue() <= 0) {
+            isc_throw(BadValue, "'last-subnet-id' parameter must be > 0");
+        }
+
+        params.last_subnet_id_ = value->intValue();
+
+        if (params.last_subnet_id_ < params.first_subnet_id_) {
+            isc_throw(BadValue, "'last-subnet-id' must be greater than 'first-subnet-id'");
+        }
+
+        params.select_mode_ = LeaseStatsQuery::SUBNET_RANGE;
+    }
+
+    return (params);
+}
+
+uint64_t
+LeaseStatCmdsImpl::makeResultSet4(const ElementPtr& result_wrapper,
+                                  const Parameters& params) {
+    // First we need to determine the range of configured subnets
+    // which meet the selection criteria.  If the range contains
+    // no subnets we punt.
+    const Subnet4Collection* subnets =
+        CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll();
+    const auto& idx = subnets->get<SubnetSubnetIdIndexTag>();
+
+    // Init to ALL so we can use auto ;)
+    auto lower = idx.begin();
+    auto upper = idx.end();
+    switch (params.select_mode_) {
+    case LeaseStatsQuery::SINGLE_SUBNET:
+        lower = idx.find(params.first_subnet_id_);
+        // If it's an unknown subnet, punt.
+        if (lower == idx.end()) {
+            isc_throw(NotFound, "subnet-id: "
+                      << params.first_subnet_id_ << " does not exist");
+        }
+
+        upper = idx.upper_bound(params.first_subnet_id_);
+        break;
+    case LeaseStatsQuery::SUBNET_RANGE:
+        lower = idx.lower_bound(params.first_subnet_id_);
+        upper = idx.upper_bound(params.last_subnet_id_);
+        break;
+    default:
+        break;
+    }
+
+    // If it's an empty range, punt.
+    if (lower == upper) {
+        isc_throw(NotFound, "selected ID range: "
+            << params.first_subnet_id_ << " through "
+            << params.last_subnet_id_ << " includes no known subnets");
+    }
+
+    // Now, that we have a valid range, run the Lease query.
+    LeaseStatsQueryPtr query;
+    switch (params.select_mode_) {
+    case LeaseStatsQuery::ALL_SUBNETS:
+        query = LeaseMgrFactory::instance().startLeaseStatsQuery4();
+        break;
+    case LeaseStatsQuery::SINGLE_SUBNET:
+        query = LeaseMgrFactory::instance()
+                .startSubnetLeaseStatsQuery4(params.first_subnet_id_);
+        break;
+    case LeaseStatsQuery::SUBNET_RANGE:
+        query = LeaseMgrFactory::instance()
+                .startSubnetRangeLeaseStatsQuery4(params.first_subnet_id_,
+                                                  params.last_subnet_id_);
+        break;
+    }
+
+    // Create the empty result-set.
+    std::vector<std::string>column_labels = { "subnet-id", "total-addreses",
+                                              "assigned-addreses","declined-addreses"};
+    ElementPtr value_rows = createResultSet(result_wrapper, column_labels);
+
+    // Get the first query row
+    LeaseStatsRow query_row;
+    bool query_eof = !(query->getNextRow(query_row));
+
+    // Now we iterate over the selected range, building rows accordingly.
+    for (auto cur_subnet = lower; cur_subnet != upper; ++cur_subnet) {
+        SubnetID cur_id = (*cur_subnet)->getID();
+
+        // Add total only rows for subnets that occur before,
+        // in-between, or after the subnets in the query content
+        if ((cur_id < query_row.subnet_id_) ||
+            (cur_id > query_row.subnet_id_) ||
+            (query_eof)) {
+            // Generate a totals only row
+            addValueRow4(value_rows, cur_id, 0, 0);
+            continue;
+        }
+
+        // Current subnet matches query row, so iterate over its
+        // query rows (one per state) and accumulate them
+        // into a result-set row.
+        int64_t assigned = 0;
+        int64_t declined = 0;
+        bool add_row = false;
+        while (!query_eof && query_row.subnet_id_ == cur_id) {
+            if (query_row.lease_state_ == Lease::STATE_DEFAULT) {
+                add_row = true;
+                assigned = query_row.state_count_;
+            } else if (query_row.lease_state_ == Lease::STATE_DECLINED) {
+                add_row = true;
+                declined = query_row.state_count_;
+            }
+
+            query_eof = !(query->getNextRow(query_row));
+        }
+
+        // Add the row for the current subnet
+        if (add_row) {
+            addValueRow4(value_rows, cur_id, assigned, declined);
+        }
+    }
+
+    return (value_rows->size());
+}
+
+uint64_t
+LeaseStatCmdsImpl::makeResultSet6(const ElementPtr& result_wrapper,
+                                  const Parameters& params) {
+    // Iterate over the selected range of configured subnets generating
+    // a result-set row for each one.  If a subnet has data in the query
+    // content use it, otherwise, it gets a row with totals only.  This
+    // way we send back a row for every selected subnet.
+    const Subnet6Collection* subnets =
+        CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getAll();
+
+    // Set the bounds on the selected subnet range
+    const auto& idx = subnets->get<SubnetSubnetIdIndexTag>();
+
+    // Init to all so we can use auto ;)
+    auto lower = idx.begin();
+    auto upper = idx.end();
+    switch (params.select_mode_) {
+    case LeaseStatsQuery::SINGLE_SUBNET:
+        lower = idx.lower_bound(params.first_subnet_id_);
+        // If it's an unknown subnet, punt.
+        if (lower == idx.end()) {
+            isc_throw(NotFound, "subnet-id: "
+                      << params.first_subnet_id_ << " does not exist");
+        }
+
+        upper = idx.upper_bound(params.first_subnet_id_);
+        break;
+    case LeaseStatsQuery::SUBNET_RANGE:
+        lower = idx.lower_bound(params.first_subnet_id_);
+        upper = idx.upper_bound(params.last_subnet_id_);
+        break;
+    default:
+        break;
+    }
+
+    // If it's empty range, punt.
+    if (lower == upper) {
+        isc_throw(NotFound, "selected ID range: "
+            << params.first_subnet_id_ << " through "
+            << params.last_subnet_id_ << " includes no known subnets");
+    }
+
+    // Create the result-set map.
+    // labels could be class statics?
+    std::vector<std::string>column_labels = { "subnet-id", "total-nas", "assigned-nas",
+                                              "declined-nas", "total-pds", "assigned-pds"};
+    ElementPtr value_rows = createResultSet(result_wrapper, column_labels);
+
+    // Now we can run the stats query.
+    LeaseStatsQueryPtr query;
+    switch (params.select_mode_) {
+    case LeaseStatsQuery::ALL_SUBNETS:
+        query = LeaseMgrFactory::instance().startLeaseStatsQuery6();
+        break;
+    case LeaseStatsQuery::SINGLE_SUBNET:
+        query = LeaseMgrFactory::instance()
+                .startSubnetLeaseStatsQuery6(params.first_subnet_id_);
+        break;
+    case LeaseStatsQuery::SUBNET_RANGE:
+        query = LeaseMgrFactory::instance()
+                .startSubnetRangeLeaseStatsQuery6(params.first_subnet_id_,
+                                                  params.last_subnet_id_);
+        break;
+    }
+
+    // Get the first query row
+    LeaseStatsRow query_row;
+    bool query_eof = !(query->getNextRow(query_row));
+
+    for (auto cur_subnet = lower; cur_subnet != upper; ++cur_subnet) {
+        SubnetID cur_id = (*cur_subnet)->getID();
+
+        // Add total only rows for subnets that occur before,
+        // in-between, or after subnets in the query content
+        if ((cur_id < query_row.subnet_id_) ||
+            (cur_id > query_row.subnet_id_) ||
+            (query_eof)) {
+            // Generate a totals only row
+            addValueRow6(value_rows, cur_id, 0, 0, 0);
+            continue;
+        }
+
+        // Current subnet matches query row, so iterate over
+        // its query rows and accumulate them into a result-set row.
+        int64_t assigned = 0;
+        int64_t declined = 0;
+        int64_t assigned_pds = 0;
+        bool add_row = false;
+        while (!query_eof && query_row.subnet_id_ == cur_id) {
+            if (query_row.lease_state_ == Lease::STATE_DEFAULT) {
+                add_row = true;
+                if (query_row.lease_type_ == Lease::TYPE_NA) {
+                    assigned = query_row.state_count_;
+                } else {
+                    assigned_pds = query_row.state_count_;
+                }
+                break;
+            } else if (query_row.lease_state_ == Lease::STATE_DECLINED) {
+                add_row = true;
+                declined = query_row.state_count_;
+            }
+
+            // Get next query row
+            query_eof = !(query->getNextRow(query_row));
+        }
+
+        if (add_row) {
+            addValueRow6(value_rows, cur_id, assigned, declined, assigned_pds);
+        }
+    }
+
+    return (value_rows->size());
+}
+
+ElementPtr
+LeaseStatCmdsImpl::createResultSet(const ElementPtr &result_wrapper,
+                                   const std::vector<std::string>& column_labels) {
+    // Create the result-set map and add it to the wrapper.
+    ElementPtr result_set = Element::createMap();
+    result_wrapper->set("result-set", result_set);
+
+    // Create the timestamp based on time now and add it to the result set.
+    boost::posix_time::ptime now(boost::posix_time::second_clock::universal_time());
+    ElementPtr timestamp = Element::create(isc::util::ptimeToText(now));
+    result_set->set("timestamp", timestamp);
+
+    // Create the list of column names and add it to the result set.
+    ElementPtr columns = Element::createList();
+    for (auto label = column_labels.begin(); label != column_labels.end(); ++label) {
+        columns->add(Element::create(*label));
+    }
+    result_set->set("columns", columns);
+
+    // Create the empty value_rows list, add it and then return it.
+    ElementPtr value_rows = Element::createList();
+    result_set->set("rows", value_rows);
+    return (value_rows);
+}
+
+
+void
+LeaseStatCmdsImpl::addValueRow4(ElementPtr value_rows, const SubnetID &subnet_id,
+                          int64_t assigned, int64_t declined) {
+    ElementPtr row = Element::createList();
+    row->add(Element::create(static_cast<int64_t>(subnet_id)));
+    row->add(Element::create(getSubnetStat(subnet_id, "total-addresses")));
+    row->add(Element::create(assigned));
+    row->add(Element::create(declined));
+    value_rows->add(row);
+}
+
+void
+LeaseStatCmdsImpl::addValueRow6(ElementPtr value_rows, const SubnetID &subnet_id,
+                           int64_t assigned, int64_t declined, int64_t assigned_pds) {
+    ElementPtr row = Element::createList();
+    row->add(Element::create(static_cast<int64_t>(subnet_id)));
+    row->add(Element::create(getSubnetStat(subnet_id, "total-nas")));
+    row->add(Element::create(assigned));
+    row->add(Element::create(declined));
+    row->add(Element::create(getSubnetStat(subnet_id, "total-pds")));
+    row->add(Element::create(assigned_pds));
+    value_rows->add(row);
+}
+
+int64_t
+LeaseStatCmdsImpl::getSubnetStat(const SubnetID& subnet_id, const std::string& name) {
+    ObservationPtr stat = StatsMgr::instance().
+                          getObservation(StatsMgr::generateName("subnet", subnet_id, name));
+    if (stat) {
+        return (stat->getInteger().first);
+    }
+
+    return (0);
+}
+
+int
+StatCmds::statLease4GetHandler(CalloutHandle& handle) {
+    LeaseStatCmdsImpl impl;
+    return(impl.statLease4GetHandler(handle));
+}
+
+int
+StatCmds::statLease6GetHandler(CalloutHandle& handle) {
+    LeaseStatCmdsImpl impl;
+    return(impl.statLease6GetHandler(handle));
+}
+
+StatCmds::StatCmds() {
+}
+
+};
+};
diff --git a/src/hooks/dhcp/stat_cmds/stat_cmds.dox b/src/hooks/dhcp/stat_cmds/stat_cmds.dox
new file mode 100644 (file)
index 0000000..aa1478f
--- /dev/null
@@ -0,0 +1,98 @@
+// Copyright (C) 2018 Internet Systems Consortium, Inc. ("ISC")
+//
+// 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/.
+
+/**
+
+@page libdhcp_stat_cmds Kea Stat Commands Hooks Library
+
+@section libdhcp_stat_cmdsIntro Introduction
+
+Welcome to Kea Stat Commands Hooks Library. This documentation is addressed to
+developers who are interested in the internal operation of the Stat Commands
+library. This file provides information needed to understand and perhaps extend
+this library.
+
+This documentation is stand-alone: you should have read and understood <a
+href="http://kea.isc.org/docs/devel/">Kea Developer's Guide</a> and in
+particular its section about hooks.
+
+@section stat_cmds Stat Commands Overview
+
+Stat Commands (or stat_cmds) is a Hook library that can be loaded by Kea to
+extend it with additional mechanisms.
+
+The primary purpose of this library is to provide commands that manage leases.
+As such, the whole library is structured around command handlers. When the
+library is loaded it registers a number of handlers for new commands.  When a
+command is issued (be it directly via control channel or indirectly via REST
+interface from control agent), the code receives a JSON command with
+parameters. Those are parsed and then actual operation commences.  This
+operation always interacts with an instantiation of isc::dhcp::StatMgr
+instance, which is Kea's way of storing leases. At the time of writing this text
+(Aug. 2017), Kea supports four types of lease managers: memfile, MySQL,
+PostgreSQL or Cassandra. The lease commands provided by this library
+provide a unified interface for those backends.
+
+As with other hooks, this one also keeps its code in a separate namespace which
+corresponds to the file name of the library: isc::stat_cmds.
+
+@section stat_cmdsCode Stat Commands Code Overview
+
+The library operation starts with Kea calling the load() function (file
+load_unload.cc).  It instantiates an isc::stat_cmds::StatCmds object.
+The constructor of that object registers all of the lease commands. For a list,
+see @ref isc::stat_cmds::StatCmds class documentation.  This class uses Pimpl
+design pattern, thus the real implementation is hidden in isc::stat_cmds::StatCmdsImpl.
+
+Almost every command has its own handler, except few that share the same handler
+between v4 and v6 due to its similarity. For example
+isc::stat_cmds::StatCmdsImpl::leaseAddHandler handles lease4-add and lease6-add
+commands. Although the details differ between handlers, the general approach
+is the same. First, it starts with parameters sanitization and then some
+interaction with isc::dhcp::StatMgr is conducted.
+
+For commands that do something with a specific lease (lease4-get, lease6-get,
+lease4-del, lease6-del), there is a @ref isc::stat_cmds::StatCmdsImpl::Parameters
+class that contains parsed elements.
+
+For details see documentation and code of the following handlers:
+- @ref isc::stat_cmds::StatCmdsImpl::leaseAddHandler (lease4-add, lease6-add)
+- @ref isc::stat_cmds::StatCmdsImpl::leaseGetHandler (lease4-get, lease6-get)
+- @ref isc::stat_cmds::StatCmdsImpl::lease4DelHandler (lease4-del)
+- @ref isc::stat_cmds::StatCmdsImpl::lease6DelHandler (lease6-del)
+- @ref isc::stat_cmds::StatCmdsImpl::lease4UpdateHandler (lease4-update)
+- @ref isc::stat_cmds::StatCmdsImpl::lease6UpdateHandler (lease6-update)
+- @ref isc::stat_cmds::StatCmdsImpl::lease4WipeHandler (lease4-wipe)
+- @ref isc::stat_cmds::StatCmdsImpl::lease6WipeHandler (lease6-wipe)
+
+@section stat_cmdsDesigns Stat Commands Design choices
+
+The lease manipulation commands were implemented to provide a convenient interface
+for sysadmins. The primary goal was to offer a way to interact with the live
+lease database in unified way, regardless of the actual backend being used.
+
+For some backends (MySQL, PostgreSQL and Cassandra) it is possible to interact
+directly with the backend while Kea is running and possibly change its content. This
+ability is both powerful and dangerous. In particular, only rudimentary
+checks are enforced by the DB schemas (e.g. not possible to have two leases
+for the same address). However, it does not prevent sysadmins from making
+more obscure errors, like inserting leases for subnets that do not exist
+or configuring an address that is topologically outside of the subnet to which
+it should belong. These kind of checks are only possible by DHCP-aware
+code, which this library provides.
+
+Some of the queries may require a seemingly odd set of parameters. For example,
+lease6-get query requires at least DUID, subnet-id and IAID to retrieve a lease
+by DUID. The need for a sysadmin to know and specify an IAID is troublesome.
+However, the guiding principle here was to use whatever queries were already
+exposed by the lease manager and not introduce new indexes, unless absolutely
+necessary. This ensures that there is no performance degradation when the
+library is loaded. The only exception for that was lease4-wipe and lease6-wipe
+commands that remove all leases from specific subnet. As there were no
+queries that could retrieve or otherwise enumerate leases for a specific subnet,
+a new query type and a new index had to be added.
+
+*/
diff --git a/src/hooks/dhcp/stat_cmds/stat_cmds.h b/src/hooks/dhcp/stat_cmds/stat_cmds.h
new file mode 100644 (file)
index 0000000..ce79d26
--- /dev/null
@@ -0,0 +1,131 @@
+// Copyright (C) 2017-2018 Internet Systems Consortium, Inc. ("ISC")
+//
+// 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/.
+
+#ifndef STAT_CMDS_H
+#define STAT_CMDS_H
+
+#include <cc/data.h>
+#include <hooks/hooks.h>
+
+#include <boost/shared_ptr.hpp>
+
+namespace isc {
+namespace stat_cmds {
+
+/// @brief Forward declaration of implementation class.
+class StatCmdsImpl;
+
+/// @brief Implements the logic for processing commands pertaining to
+/// stat manipulation.
+///
+/// This class is used by the callouts implementing command handlers for
+/// stat manipulations.
+class StatCmds {
+public:
+    /// @brief Constructor.
+    ///
+    /// It creates an instance of the @c StatCmdsImpl.
+    StatCmds();
+
+    /// @brief stat-lease4-get command handler
+    ///
+    /// This command attempts to fetch lease4 statistics for one or 
+    /// more subnets based upon subnet selection criteria (or lack thereof).
+    /// It extracts the command name and arguments from the given Callouthandle,
+    /// attempts to process them, and then set's the handle's "response"
+    /// arguments accordingly.
+    /// {
+    ///     "command": "stat-lease4-get",
+    ///     "arguments": {
+    ///         "from_storage: true/false, // optional - maybe?
+    ///         "subnet-id": x,            // optional
+    ///         "subnet-id-range": {       // optional
+    ///             "first-subnet-id": x,  // id >= x
+    ///             "last-subnet-id": y    // id <= x
+    ///         }
+    ///      }
+    /// }
+    ///
+    /// It produces a response as described below:
+    ///
+    /// {
+    ///     "result": 0,
+    ///     "text": "<message>",
+    ///     "arguments": {
+    ///         "result-set": {
+    ///             "timestamp": "2018-03-22 09:43:30.815371",
+    ///             "columns": ["subnet_id", "total-addresses", 
+    ///                         "assigned-addresses", "declined-addresses"],
+    ///             "rows": [
+    ///                 [1, 600, 450, 3],
+    ///                 :
+    ///             ]
+    ///         }
+    ///     }
+    /// }
+    ///
+    /// @param handle Callout context - which is expected to contain the
+    ///
+    /// add command JSON text in the "command" argument
+    /// @return result of the operation
+    int
+    statLease4GetHandler(hooks::CalloutHandle& handle);
+
+    /// @brief stat-lease6-get command handler
+    ///
+    /// This command attempts to fetch lease6 statistics for one or 
+    /// more subnets based upon subnet selection criteria (or lack thereof).
+    /// It extracts the command name and arguments from the given Callouthandle,
+    /// attempts to process them, and then set's the handle's "response"
+    /// argument accordingly.
+    /// {
+    ///     "command": "stat-lease6-get",
+    ///     "arguments": {
+    ///         "from_storage: true/false,
+    ///         "subnet-id": x,            // optional
+    ///         "subnet-id-range": {       // optional
+    ///                 "first-subnet-id": x,   // id >= x
+    ///                 "last-subnet-id": y     // id <= x
+    ///         }
+    ///      }
+    /// }
+    ///
+    /// It produces a response as described below:
+    ///
+    /// {
+    ///     "result": 0,
+    ///     "text": "<message>",
+    ///     "arguments": {
+    ///         "result-set": {
+    ///             "timestamp": "2018-03-22 09:43:30.815371",
+    ///             "columns": ["subnet_id", "total-nas", 
+    ///                         "assigned-nas", "declined-nas", 
+    ///                         "total-pds", "assigned-pds"],
+    ///             "rows": [
+    ///                 [1, 600, 450, 3, 64, 10],
+    ///                 :
+    ///             ]
+    ///         }
+    ///     }
+    /// }
+    ///
+    ///
+    /// @param handle Callout context - which is expected to contain the
+    /// add command JSON text in the "command" argument
+    /// @return result of the operation
+    int
+    statLease6GetHandler(hooks::CalloutHandle& handle);
+#if 0
+private:
+    /// Pointer to the actual implementation
+    boost::shared_ptr<StatCmdsImpl> impl_;
+#endif
+};
+
+};
+};
+
+#endif
diff --git a/src/hooks/dhcp/stat_cmds/stat_cmds_callouts.cc b/src/hooks/dhcp/stat_cmds/stat_cmds_callouts.cc
new file mode 100644 (file)
index 0000000..25acba2
--- /dev/null
@@ -0,0 +1,64 @@
+// Copyright (C) 2018 Internet Systems Consortium, Inc. ("ISC")
+//
+// This Source Code Form is subject to the terms of the End User License
+// Agreement. See COPYING file in the premium/ directory.
+
+
+// Functions accessed by the hooks framework use C linkage to avoid the name
+// mangling that accompanies use of the C++ compiler as well as to avoid
+// issues related to namespaces.
+
+#include <stat_cmds.h>
+#include <stat_cmds_log.h>
+#include <cc/command_interpreter.h>
+#include <hooks/hooks.h>
+
+using namespace isc::config;
+using namespace isc::data;
+using namespace isc::hooks;
+using namespace isc::stat_cmds;
+
+extern "C" {
+
+/// @brief This is a command callout for 'stat-lease4-get' command.
+///
+/// @param handle Callout handle used to retrieve a command and
+/// provide a response.
+/// @return 0 if this callout has been invoked successfully,
+/// 1 otherwise.
+int stat_lease4_get(CalloutHandle& handle) {
+    StatCmds stat_cmds;
+    return(stat_cmds.statLease4GetHandler(handle));
+}
+
+/// @brief This is a command callout for 'stat-lease6-get' command.
+///
+/// @param handle Callout handle used to retrieve a command and
+/// provide a response.
+/// @return 0 if this callout has been invoked successfully,
+/// 1 otherwise.
+int stat_lease6_get(CalloutHandle& handle) {
+    StatCmds stat_cmds;
+    return(stat_cmds.statLease6GetHandler(handle));
+}
+
+/// @brief This function is called when the library is loaded.
+///
+/// @param handle library handle
+/// @return 0 when initialization is successful, 1 otherwise
+int load(LibraryHandle& handle) {
+    handle.registerCommandCallout("stat-lease4-get", stat_lease4_get);
+    handle.registerCommandCallout("stat-lease6-get", stat_lease6_get);
+    LOG_INFO(stat_cmds_logger, STAT_CMDS_INIT_OK);
+    return (0);
+}
+
+/// @brief This function is called when the library is unloaded.
+///
+/// @return 0 if deregistration was successful, 1 otherwise
+int unload() {
+    LOG_INFO(stat_cmds_logger, STAT_CMDS_DEINIT_OK);
+    return (0);
+}
+
+} // end extern "C"
diff --git a/src/hooks/dhcp/stat_cmds/stat_cmds_log.cc b/src/hooks/dhcp/stat_cmds/stat_cmds_log.cc
new file mode 100644 (file)
index 0000000..e495d7c
--- /dev/null
@@ -0,0 +1,16 @@
+// Copyright (C) 2018 Internet Systems Consortium, Inc. ("ISC")
+//
+// 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 <stat_cmds_log.h>
+
+namespace isc {
+namespace stat_cmds {
+
+isc::log::Logger stat_cmds_logger("stat_cmds_hooks");
+
+}
+}
+
diff --git a/src/hooks/dhcp/stat_cmds/stat_cmds_log.h b/src/hooks/dhcp/stat_cmds/stat_cmds_log.h
new file mode 100644 (file)
index 0000000..1370608
--- /dev/null
@@ -0,0 +1,23 @@
+// Copyright (C) 2018 Internet Systems Consortium, Inc. ("ISC")
+//
+// 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/.
+
+#ifndef STAT_CMD_LOG_H
+#define STAT_CMD_LOG_H
+
+#include <log/logger_support.h>
+#include <log/macros.h>
+#include <stat_cmds_messages.h>
+
+namespace isc {
+namespace stat_cmds {
+
+extern isc::log::Logger stat_cmds_logger;
+
+} // end of isc::stat_cmds
+} // end of isc namespace
+
+
+#endif
diff --git a/src/hooks/dhcp/stat_cmds/stat_cmds_messages.mes b/src/hooks/dhcp/stat_cmds/stat_cmds_messages.mes
new file mode 100644 (file)
index 0000000..4d9a64d
--- /dev/null
@@ -0,0 +1,35 @@
+# Copyright (C) 2018 Internet Systems Consortium, Inc. ("ISC")
+
+% STAT_LEASE4_GET stat-lease4-get command successful (parameters: %1)
+The stat-lease4-get command has been successful. Parameters of the command
+are logged.
+
+% STAT_LEASE4_GET_FAILED stat-lease4-get command failed (parameters: %1, reason: %2)
+The stat-lease4-get command has failed. Both the reason as well as the
+parameters passed are logged.
+
+% STAT_LEASE6_GET stat-lease4-get command successful (parameters: %1)
+The stat-lease4-get command has been successful. Parameters of the command
+are logged.
+
+% STAT_LEASE6_GET_FAILED stat-lease4-get command failed (parameters: %1, reason: %2)
+The stat-lease4-get command has failed. Both the reason as well as the
+parameters passed are logged.
+
+% STAT_CMDS_DEINIT_FAILED unloading Stat Commands hooks library failed: %1
+This error message indicates an error during unloading the Lease Commands
+hooks library. The details of the error are provided as argument of
+the log message.
+
+% STAT_CMDS_DEINIT_OK unloading Stat Commands hooks library successful
+This info message indicates that the Stat Commands hooks library has been
+removed successfully.
+
+% STAT_CMDS_INIT_FAILED loading Stat Commands hooks library failed: %1
+This error message indicates an error during loading the Lease Commands
+hooks library. The details of the error are provided as argument of
+the log message.
+
+% STAT_CMDS_INIT_OK loading Stat Commands hooks library successful
+This info message indicates that the Stat Commands hooks library has been
+loaded successfully. Enjoy!
diff --git a/src/hooks/dhcp/stat_cmds/tests/.gitignore b/src/hooks/dhcp/stat_cmds/tests/.gitignore
new file mode 100644 (file)
index 0000000..35625b3
--- /dev/null
@@ -0,0 +1,5 @@
+stat_cmds_unittests
+stat_cmds_unittests.log
+stat_cmds_unittests.trs
+test-suite.log
+*~
diff --git a/src/hooks/dhcp/stat_cmds/tests/Makefile.am b/src/hooks/dhcp/stat_cmds/tests/Makefile.am
new file mode 100644 (file)
index 0000000..60b1fd9
--- /dev/null
@@ -0,0 +1,56 @@
+SUBDIRS = .
+
+AM_CPPFLAGS = -I$(top_builddir)/src/lib -I$(top_srcdir)/src/lib
+AM_CPPFLAGS += -I$(top_builddir)/src/hooks/dhcp/stat_cmds -I$(top_srcdir)/src/hooks/dhcp/stat_cmds
+AM_CPPFLAGS += $(BOOST_INCLUDES)
+AM_CPPFLAGS += -DSTAT_CMDS_LIB_SO=\"$(abs_top_builddir)/src/hooks/dhcp/stat_cmds/.libs/libdhcp_stat_cmds.so\"
+AM_CPPFLAGS += -DINSTALL_PROG=\"$(abs_top_srcdir)/install-sh\"
+
+AM_CXXFLAGS = $(KEA_CXXFLAGS)
+
+if USE_STATIC_LINK
+AM_LDFLAGS = -static
+endif
+
+# Unit test data files need to get installed.
+EXTRA_DIST =
+
+CLEANFILES = *.gcno *.gcda
+
+# TESTS_ENVIRONMENT = $(LIBTOOL) --mode=execute $(VALGRIND_COMMAND)
+LOG_COMPILER = $(LIBTOOL)
+AM_LOG_FLAGS = --mode=execute
+
+TESTS =
+if HAVE_GTEST
+TESTS += stat_cmds_unittests
+
+stat_cmds_unittests_SOURCES = run_unittests.cc
+stat_cmds_unittests_SOURCES += stat_cmds_unittest.cc
+
+stat_cmds_unittests_CPPFLAGS = $(AM_CPPFLAGS) $(GTEST_INCLUDES) $(LOG4CPLUS_INCLUDES)
+
+stat_cmds_unittests_LDFLAGS  = $(AM_LDFLAGS) $(CRYPTO_LDFLAGS) $(GTEST_LDFLAGS)
+
+stat_cmds_unittests_CXXFLAGS = $(AM_CXXFLAGS)
+
+stat_cmds_unittests_LDADD = $(top_builddir)/src/lib/dhcpsrv/libkea-dhcpsrv.la
+stat_cmds_unittests_LDADD += $(top_builddir)/src/lib/dhcp/libkea-dhcp++.la
+stat_cmds_unittests_LDADD += $(top_builddir)/src/lib/asiolink/libkea-asiolink.la
+stat_cmds_unittests_LDADD += $(top_builddir)/src/lib/cc/libkea-cc.la
+stat_cmds_unittests_LDADD += $(top_builddir)/src/lib/config/libkea-cfgclient.la
+stat_cmds_unittests_LDADD += $(top_builddir)/src/lib/hooks/libkea-hooks.la
+stat_cmds_unittests_LDADD += $(top_builddir)/src/lib/log/libkea-log.la
+stat_cmds_unittests_LDADD += $(top_builddir)/src/lib/util/libkea-util.la
+stat_cmds_unittests_LDADD += $(top_builddir)/src/lib/exceptions/libkea-exceptions.la
+stat_cmds_unittests_LDADD += $(LOG4CPLUS_LIBS)
+stat_cmds_unittests_LDADD += $(CRYPTO_LIBS)
+stat_cmds_unittests_LDADD += $(BOOST_LIBS)
+stat_cmds_unittests_LDADD += $(GTEST_LDADD)
+
+if HAVE_CQL
+stat_cmds_unittests_LDFLAGS += $(CQL_LIBS)
+endif
+
+endif
+noinst_PROGRAMS = $(TESTS)
diff --git a/src/hooks/dhcp/stat_cmds/tests/run_unittests.cc b/src/hooks/dhcp/stat_cmds/tests/run_unittests.cc
new file mode 100644 (file)
index 0000000..600d522
--- /dev/null
@@ -0,0 +1,17 @@
+// Copyright (C) 2017 Internet Systems Consortium, Inc. ("ISC")
+//
+// 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 <log/logger_support.h>
+#include <gtest/gtest.h>
+
+int
+main(int argc, char* argv[]) {
+    ::testing::InitGoogleTest(&argc, argv);
+    isc::log::initLogger();
+    int result = RUN_ALL_TESTS();
+
+    return (result);
+}
diff --git a/src/hooks/dhcp/stat_cmds/tests/stat_cmds_unittest.cc b/src/hooks/dhcp/stat_cmds/tests/stat_cmds_unittest.cc
new file mode 100644 (file)
index 0000000..9b0a3e8
--- /dev/null
@@ -0,0 +1,1297 @@
+// Copyright (C) 2018 Internet Systems Consortium, Inc. ("ISC")
+//
+// 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 <exceptions/exceptions.h>
+#include <hooks/hooks_manager.h>
+#include <config/command_mgr.h>
+#include <dhcpsrv/lease_mgr.h>
+#include <dhcpsrv/lease_mgr_factory.h>
+#include <dhcpsrv/cfgmgr.h>
+#include <cc/command_interpreter.h>
+#include <cc/data.h>
+#include <cc/data.h>
+
+#include <boost/date_time/posix_time/posix_time.hpp>
+#include <gtest/gtest.h>
+#include <time.h>
+
+using namespace std;
+using namespace isc;
+using namespace isc::hooks;
+using namespace isc::config;
+using namespace isc::data;
+using namespace isc::dhcp;
+using namespace isc::asiolink;
+using namespace boost::posix_time;
+
+namespace {
+
+/// @brief Test fixture for testing loading and unloading the library
+class LibLoadTest : public ::testing::Test {
+public:
+    /// @brief Constructor
+    LibLoadTest(std::string lib_filename)
+        : lib_name_(lib_filename), start_time_(second_clock::universal_time()) {
+        CommandMgr::instance();
+        unloadLibs();
+    }
+
+    /// @brief Destructor
+    /// Removes files that may be left over from previous tests
+    virtual ~LibLoadTest() {
+        unloadLibs();
+    }
+
+    /// @brief Adds library/parameters to list of libraries to be loaded
+    void addLib(const std::string& lib, ConstElementPtr params) {
+        libraries_.push_back(make_pair(lib, params));
+    }
+
+    /// @brief Load all specified libraries.
+    ///
+    /// The libraries are stored in libraries
+    void loadLibs() {
+        ASSERT_TRUE(HooksManager::loadLibraries(libraries_))
+            << "library loading failed";
+    }
+
+    /// @brief Unloads all libraries.
+    void unloadLibs() {
+        ASSERT_NO_THROW(HooksManager::unloadLibraries());
+    }
+
+    /// @brief Checks whether specified command is registered
+    ///
+    /// @param name name of the command to be checked
+    /// @param expect_true true - must be registered, false - must not be
+    void checkCommandRegistered(const std::string& name, bool expect_true) {
+
+        // First get the list of registered commands
+        ConstElementPtr lst = Element::fromJSON("{ \"command\": \"list-commands\" }");
+        ConstElementPtr rsp = CommandMgr::instance().processCommand(lst);
+
+        ASSERT_TRUE(rsp);
+
+        ConstElementPtr args = rsp->get("arguments");
+        ASSERT_TRUE(args);
+
+        string args_txt = args->str();
+
+        if (expect_true) {
+            EXPECT_TRUE(args_txt.find(name) != string::npos);
+        } else {
+            EXPECT_TRUE(args_txt.find(name) == string::npos);
+        }
+    }
+
+    /// @brief tests specified command and verifies response
+    ///
+    /// This method loads the library, sends specific command,
+    /// then checks if the result is as expected, checks if text response
+    /// is ok (optional, check skipped if exp_txt is empty) and then returns
+    /// the response (for possible additional checks).
+    ///
+    /// @param cmd JSON command to be sent (must be valid JSON)
+    /// @param exp_result 0 - success, 1 - error, 2 - ...
+    /// @param exp_txt expected text response (optional)
+    void testCommand(string cmd_txt, int exp_result, string exp_txt,
+                                string exp_result_json = "") {
+        // Let's load the library first.
+        loadLib();
+
+        ConstElementPtr cmd;
+        ASSERT_NO_THROW(cmd = Element::fromJSON(cmd_txt))
+                        << "command JSON invalid, test is broken";
+
+        // Process the command and verify response.
+        ConstElementPtr rsp = CommandMgr::instance().processCommand(cmd);
+        checkAnswer(rsp, exp_result, exp_txt);
+
+        // Don't care about argument contents, we're done.
+        if (exp_result_json.empty()) {
+            return;
+        }
+
+        // Turn expected result JSON into Element tree
+        ConstElementPtr exp_args;
+        ASSERT_NO_THROW(exp_args = Element::fromJSON(exp_result_json))
+            << "Expected result JSON is invalid, test is broken" << exp_result_json;
+
+        ASSERT_TRUE(exp_args->getType() == Element::map)
+            << "Expected args is not a map, test is broken: " << exp_result_json;
+
+        // Fetch "arguments" from the actual response
+        ConstElementPtr actual_args = rsp->get("arguments");
+        ASSERT_TRUE(actual_args && actual_args->getType() == Element::map)
+                << "'arguments' missing or not a map " << toJSON(rsp);
+
+        // If we expect nothing and nothing is what we got, we're done.
+        if (exp_args->size() == 0) {
+            ASSERT_TRUE(actual_args->size() == 0)
+                << "Acutal args should be empty:" << toJSON(actual_args);
+            return;
+        }
+
+        // Fetch "result-set" from the expected arguments
+        ConstElementPtr exp_result_set = exp_args->get("result-set");
+        ASSERT_TRUE(exp_result_set && (exp_result_set->getType() == Element::map))
+            << "Expected 'result-set' missing or not map\n" << toJSON(exp_args);
+
+        // Fetch "result-set" from the actual arguments
+        ConstElementPtr actual_result_set = actual_args->get("result-set");
+        ASSERT_TRUE(actual_result_set && (actual_result_set->getType() == Element::map))
+            << "Actual 'result-set' missing or not map\n" << toJSON(actual_args);
+
+        // Compare the actual and expected "columns"
+        ConstElementPtr exp = exp_result_set->get("columns");
+        ASSERT_TRUE(exp && exp->getType() == Element::list)
+            << "Expected 'columns' is missing or not list, test is broken"
+            << toJSON(exp_result_set);
+
+        ConstElementPtr actual = actual_result_set->get("columns");
+        ASSERT_TRUE(actual && (actual->getType() == Element::list))
+            << "Actual 'columns' is missing or not list"
+            << toJSON(actual_result_set);
+
+        ASSERT_TRUE(*exp == *actual) << "Result set columns are wrong\n"
+                << "Expected:\n" << toJSON(exp)
+                << "\nActual:\n" << toJSON(actual);
+
+        // Compare the actual and expected "rows"
+        exp = exp_result_set->get("rows");
+        ASSERT_TRUE(exp && (exp->getType() == Element::list))
+                << "Expected 'rows' is missing or not a list, test is broken";
+
+        actual = actual_result_set->get("rows");
+        ASSERT_TRUE(actual && (actual->getType() == Element::list))
+                << "Actual 'rows' is missing or not a list"
+                << toJSON(actual_result_set);
+
+        ASSERT_TRUE(*exp == *actual) << "Result set rows are wrong\n"
+                << "Expected:\n" << toJSON(exp)
+                << "\nActual:\n" << toJSON(actual);
+
+        // Make sure timestamp is present and appears valid
+        actual = actual_result_set->get("timestamp");
+        ASSERT_TRUE (actual && (actual->getType() == Element::string))
+                << "Actual result-set timestamp is missing?"
+                << toJSON(rsp);
+
+        // We expect it to be the same or later than the test start time
+        ptime timestamp = strToPtime(actual->stringValue());
+        EXPECT_TRUE(timestamp >= start_time_)
+                    << "Actual timestamp is wrong?" << actual->stringValue();
+    }
+
+    /// @brief Compares the status in the given parse result to a given value.
+    ///
+    /// @param answer Element set containing an integer response and string
+    /// comment.
+    /// @param exp_status is an integer against which to compare the status.
+    /// @param exp_txt is expected text (not checked if "")
+    void checkAnswer(isc::data::ConstElementPtr answer,
+                     int exp_status,
+                     string exp_txt = "") {
+        int rcode = 0;
+        isc::data::ConstElementPtr comment;
+        comment = isc::config::parseAnswer(rcode, answer);
+
+        if (rcode != exp_status) {
+            ADD_FAILURE() << "Expected status code " << exp_status
+                          << " but received " << rcode << ", comment: "
+                          << (comment ? comment->str() : "(none)");
+        }
+
+        // Ok, parseAnswer interface is weird. If there are no arguments,
+        // it returns content of text. But if there is an argument,
+        // it returns the argument and it's not possible to retrieve
+        // "text" (i.e. comment).
+        if (comment->getType() != Element::string) {
+            comment = answer->get("text");
+        }
+
+        if (!exp_txt.empty()) {
+            EXPECT_EQ(exp_txt, comment->stringValue());
+        }
+    }
+
+    /// @brief Loads the library specified by lib_name_
+    void loadLib() {
+        if (libraries_.empty()) {
+            data::ElementPtr params = data::Element::createMap();
+            addLib(lib_name_, params);
+        }
+        EXPECT_NO_THROW(loadLibs());
+    }
+
+    /// @brief Test checks if specified commands are provided by the library.
+    ///
+    /// @param cms a vector of string with command names
+    void testCommands(const std::vector<string> cmds) {
+
+        // The commands should not be registered yet.
+        for (auto cmd = cmds.begin(); cmd != cmds.end(); ++cmd) {
+            checkCommandRegistered(*cmd, false);
+        }
+
+        loadLib();
+
+        // The commands should be available after library was loaded.
+        for (auto cmd = cmds.begin(); cmd != cmds.end(); ++cmd) {
+            checkCommandRegistered(*cmd, true);
+        }
+
+        unloadLibs();
+
+        // and the commands should be gone now.
+        for (auto cmd = cmds.begin(); cmd != cmds.end(); ++cmd) {
+            checkCommandRegistered(*cmd, false);
+        }
+
+    }
+
+    // Check that the library can be loaded and unloaded multiple times.
+    void testMultipleLoads() {
+        EXPECT_NO_THROW(loadLib());
+        EXPECT_NO_THROW(unloadLibs());
+
+        EXPECT_NO_THROW(loadLib());
+        EXPECT_NO_THROW(unloadLibs());
+
+        EXPECT_NO_THROW(loadLib());
+        EXPECT_NO_THROW(unloadLibs());
+
+        EXPECT_NO_THROW(loadLib());
+        EXPECT_NO_THROW(unloadLibs());
+    }
+
+    std::string toJSON(ConstElementPtr element) {
+        std::stringstream os;
+        element->toJSON(os);
+        return (os.str());
+    }
+
+    /// @brief Converts a string into a boost::posix_time::ptime
+    ///
+    /// The expected format of the input string is:
+    ///
+    ///    "%Y-%m-%d %H:%M:%S"
+    ///
+    /// Example: "2018-04-21 15:03:37"
+    ///
+    /// Any content beyond this length is ignored.
+    ///
+    ///  We're doing it this way because boost's function, time_from_string(),
+    ///  is part of their date/time library which is not header only.
+    ///
+    /// @param timestamp string to convert into a ptime
+    /// @throw BadValue if the string cannot be converted into a ptime
+    boost::posix_time::ptime strToPtime(const std::string& timestamp) {
+        struct tm tm_result;
+
+        if (!strptime(timestamp.c_str(), "%Y-%m-%d %H:%M:%S", &tm_result)) {
+            isc_throw(BadValue, "cannot convert timestamp string: " << timestamp);
+        }
+
+        return (ptime_from_tm(tm_result));
+    }
+
+    /// List of libraries to be/being loaded (usually just one)
+    HookLibsCollection libraries_;
+
+    /// Path to the library filename
+    std::string lib_name_;
+
+    /// @brief Holds the time the test started
+    boost::posix_time::ptime start_time_;
+};
+
+/// @brief Class dedicated to testing lease_cmds library.
+///
+/// Provides convenience methods for loading, testing all commands and
+/// unloading the lease_cmds library.
+class StatCmdsTest : public LibLoadTest {
+public:
+
+    /// @brief Constructor
+    ///
+    /// Sets the library filename and clears the lease manager pointer.
+    /// Also ensured there is no lease manager leftovers from previous
+    /// test.
+    StatCmdsTest()
+        :LibLoadTest(STAT_CMDS_LIB_SO), hwaddr_({10,20,30,40,50,00}),
+         duid_({10,20,30,40,50,60,70,00}) {
+        LeaseMgrFactory::destroy();
+        lmptr_ = 0;
+    }
+
+    /// @brief Destructor
+    ///
+    /// Removes library (if any), destroys lease manager (if any).
+    virtual ~StatCmdsTest() {
+        // destroys lease manager first because the other order triggers
+        // a clang/boost bug
+        LeaseMgrFactory::destroy();
+        unloadLibs();
+        lmptr_ = 0;
+    }
+
+    /// @brief Initializes lease manager for v6 operation
+    ///
+    /// Creates a lease manager (memfile, trimmed down to keep everything in memory
+    /// only) and adds five subnets to the configuration.
+    void initLeaseMgr4() {
+        LeaseMgrFactory::destroy();
+        LeaseMgrFactory::create("type=memfile persist=false universe=4");
+
+        lmptr_ = &(LeaseMgrFactory::instance());
+        ASSERT_TRUE(lmptr_);
+
+        CfgMgr& cfg_mgr = CfgMgr::instance();
+        CfgSubnets4Ptr subnets = cfg_mgr.getStagingCfg()->getCfgSubnets4();
+
+        Subnet4Ptr subnet;
+        Pool4Ptr pool;
+
+        subnet.reset(new Subnet4(IOAddress("192.0.1.0"), 24, 1, 2, 3, 10));
+        pool.reset(new Pool4(IOAddress("192.0.1.0"), 24));
+        subnet->addPool(pool);
+        subnets->add(subnet);
+
+        subnet.reset(new Subnet4(IOAddress("192.0.2.0"), 28, 1, 2, 3, 20));
+        pool.reset(new Pool4(IOAddress("192.0.2.0"), 28));
+        subnet->addPool(pool);
+        subnets->add(subnet);
+
+        subnet.reset(new Subnet4(IOAddress("192.0.3.0"), 24, 1, 2, 3, 30));
+        pool.reset(new Pool4(IOAddress("192.0.3.0"), 24));
+        subnet->addPool(pool);
+        subnets->add(subnet);
+
+        subnet.reset(new Subnet4(IOAddress("192.0.4.0"), 28, 1, 2, 3, 40));
+        pool.reset(new Pool4(IOAddress("192.0.4.0"), 28));
+        subnet->addPool(pool);
+        subnets->add(subnet);
+
+        subnet.reset(new Subnet4(IOAddress("192.0.5.0"), 24, 1, 2, 3, 50));
+        pool.reset(new Pool4(IOAddress("192.0.5.0"), 24));
+        subnet->addPool(pool);
+        subnets->add(subnet);
+
+        cfg_mgr.commit();
+
+#if 0
+            addLease4("192.0.2.1", 1);
+            addLease4("192.0.2.2", 2, Lease::STATE_DECLINED);
+#endif
+    }
+
+    /// @brief Initializes lease manager for v6 operation
+    ///
+    /// Creates a lease manager (memfile, trimmed down to keep everything in memory
+    /// only) and adds five subnets to the configuration.
+    void initLeaseMgr6() {
+        LeaseMgrFactory::destroy();
+        LeaseMgrFactory::create("type=memfile persist=false universe=6");
+
+        lmptr_ = &(LeaseMgrFactory::instance());
+        ASSERT_TRUE(lmptr_);
+
+        CfgMgr& cfg_mgr = CfgMgr::instance();
+        CfgSubnets6Ptr subnets = cfg_mgr.getStagingCfg()->getCfgSubnets6();
+
+        Subnet6Ptr subnet;
+        Pool6Ptr pool;
+
+        subnet.reset(new Subnet6(IOAddress("2001:db8:1::"), 64, 1, 2, 3, 4, 10));
+        pool.reset(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:1::"), 112));
+        subnet->addPool(pool);
+        subnets->add(subnet);
+
+        subnet.reset(new Subnet6(IOAddress("2001:db8:2::"), 64, 1, 2, 3, 4, 20));
+        pool.reset(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:2::"), 104));
+        subnet->addPool(pool);
+        subnets->add(subnet);
+
+        subnet.reset(new Subnet6(IOAddress("2001:db8:3::"), 64, 1, 2, 3, 4, 30));
+        pool.reset(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:3::"), 124));
+        subnet->addPool(pool);
+        pool.reset(new Pool6(Lease::TYPE_PD, IOAddress("3001::"), 96, 112));
+        subnet->addPool(pool);
+        subnets->add(subnet);
+
+        subnet.reset(new Subnet6(IOAddress("2001:db8:4::"), 64, 1, 2, 3, 4, 40));
+        pool.reset(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:4::"), 104));
+        subnet->addPool(pool);
+        subnets->add(subnet);
+
+        subnet.reset(new Subnet6(IOAddress("2001:db8:5::"), 64, 1, 2, 3, 4, 50));
+        pool.reset(new Pool6(Lease::TYPE_PD, IOAddress("5001::"), 96, 112));
+        subnet->addPool(pool);
+        subnets->add(subnet);
+
+        cfg_mgr.commit();
+
+#if 0
+        addLease6("2001:db8:1::1", 10);
+#endif
+    }
+
+    /// @brief Creates an IPv4 lease
+    ///
+    /// Lease parameters: valid lifetime = 3600, cltt = 12345678, fqdn-fwd = false,
+    /// fqdn-rev = true, hostname = myhost.example.com
+    ///
+    /// @param ip_address IP address for the lease.
+    /// @param subnet_id subnet identifier
+    /// @param state lease state
+    void addLease4(const std::string& ip_address, const SubnetID& subnet_id,
+                   const int state = Lease::STATE_DEFAULT) {
+        Lease4Ptr lease(new Lease4());
+
+        lease->addr_ = IOAddress(ip_address);
+
+        // Initialize unused fields.
+        lease->t1_ = 0;                             // Not saved
+        lease->t2_ = 0;                             // Not saved
+
+
+        ++hwaddr_[5];
+
+        // Set other parameters.  For historical reasons, address 0 is not used.
+        lease->hwaddr_.reset(new HWAddr(hwaddr_, HTYPE_ETHER));
+        lease->valid_lft_ = 3600;
+        lease->cltt_ = 12345678;
+        lease->subnet_id_ = subnet_id;
+        lease->fqdn_fwd_ = false;
+        lease->fqdn_rev_ = true;
+        lease->hostname_ = "myhost.example.com.";
+        lease->state_ = state;
+
+        ASSERT_NO_THROW(lmptr_->addLease(lease))
+                        << "cannot add lease4: " << ip_address
+                        << " subnet: " << subnet_id;
+    }
+
+    /// @brief Creates an IPv6 lease
+    ///
+    /// Lease parameters: cltt = 12345678, fqdn-fwd = false, fqdn-rev = true,
+    /// hostname = myhost.example.com, preferred lifetime = 1800,
+    /// valid lifetime = 3600
+    ///
+    /// @param ip_address IP address for the lease.
+    /// @param subnet_id subnet identifier
+    /// @param state lease state
+    void addLease6(const std::string& ip_address, const SubnetID& subnet_id,
+                   const int state = Lease::STATE_DEFAULT) {
+        Lease6Ptr lease(new Lease6());
+
+        ++duid_[7];
+
+        lease->addr_ = IOAddress(ip_address);
+        lease->type_ = Lease::TYPE_NA;
+        lease->prefixlen_ = 128;
+        lease->iaid_ = 42;
+        lease->duid_ = DuidPtr(new DUID(duid_));
+        lease->preferred_lft_ = 1800;
+        lease->valid_lft_ = 3600;
+        lease->cltt_ = 12345678;
+        lease->subnet_id_ = subnet_id;
+        lease->fqdn_fwd_ = false;
+        lease->fqdn_rev_ = true;
+        lease->hostname_ = "myhost.example.com.";
+        lease->state_ = state;
+
+        ASSERT_NO_THROW(lmptr_->addLease(lease))
+                        << "cannot add lease6: " << ip_address
+                        << " subnet: " << subnet_id;
+    }
+
+    /// @brief Pointer to the lease manager
+    LeaseMgr* lmptr_;
+
+    /// @brief Holds the hardware address for creating v4 leases
+    vector<uint8_t> hwaddr_;
+
+    /// @brief Holds the DUID for creating v6 leases
+    vector<uint8_t> duid_;
+};
+
+// Simple test that checks the library really registers the commands.
+TEST_F(StatCmdsTest, commands) {
+
+    vector<string> cmds = { "stat-lease4-get",
+                            "stat-lease6-get" };
+    testCommands(cmds);
+}
+
+// Check that the library can be loaded and unloaded multiple times.
+TEST_F(StatCmdsTest, multipleLoads) {
+    testMultipleLoads();
+}
+
+using namespace isc::dhcp;
+
+struct TestScenario {
+    std::string description_;
+    std::string command_txt_;
+    std::string exp_response_;
+    std::string exp_result_json;
+};
+
+TEST_F(StatCmdsTest, StatLease4GetBadParams) {
+    // Initialize lease manager
+    initLeaseMgr4();
+
+    std::vector<TestScenario> tests = {
+        {
+        "subnet-id 0",
+        "{\n"
+        "    \"command\": \"stat-lease4-get\",\n"
+        "    \"arguments\": {"
+        "        \"subnet-id\": 0\n"
+        "    }\n"
+        "}",
+        "'subnet-id' parameter must be > 0"
+        },
+
+        {
+        "subnet-id -1",
+        "{\n"
+        "    \"command\": \"stat-lease4-get\",\n"
+        "    \"arguments\": {"
+        "        \"subnet-id\": -1\n"
+        "    }\n"
+        "}",
+        "'subnet-id' parameter must be > 0"
+        },
+        {
+        "subnet-id string",
+        "{\n"
+        "    \"command\": \"stat-lease4-get\",\n"
+        "    \"arguments\": {"
+        "        \"subnet-id\": \"boo\"\n"
+        "    }\n"
+        "}",
+        "'subnet-id' parameter is not integer"
+        },
+        {
+        "subnet-range not a map",
+        "{\n"
+        "    \"command\": \"stat-lease4-get\",\n"
+        "    \"arguments\": {"
+        "        \"subnet-range\": -1\n"
+        "    }\n"
+        "}",
+        "subnet-range parameter is not a map"
+        },
+        {
+        "subnet-range empty",
+        "{\n"
+        "    \"command\": \"stat-lease4-get\",\n"
+        "    \"arguments\": {"
+        "        \"subnet-range\": {\n"
+        "       }\n"
+        "    }\n"
+        "}",
+        "'first-subnet-id' parameter missing or not an integer"
+        },
+        {
+        "first-subnet-id string",
+        "{\n"
+        "    \"command\": \"stat-lease4-get\",\n"
+        "    \"arguments\": {"
+        "        \"subnet-range\": {\n"
+        "           \"first-subnet-id\": \"boo\"\n"
+        "       }\n"
+        "    }\n"
+        "}",
+        "'first-subnet-id' parameter missing or not an integer"
+        },
+        {
+        "first-subnet-id < 0",
+        "{\n"
+        "    \"command\": \"stat-lease4-get\",\n"
+        "    \"arguments\": {"
+        "        \"subnet-range\": {\n"
+        "           \"first-subnet-id\": -77\n"
+        "       }\n"
+        "    }\n"
+        "}",
+        "'first-subnet-id' parameter must be > 0"
+        },
+        {
+        "last-subnet-id missing",
+        "{\n"
+        "    \"command\": \"stat-lease4-get\",\n"
+        "    \"arguments\": {"
+        "        \"subnet-range\": {\n"
+        "           \"first-subnet-id\": 10\n"
+        "       }\n"
+        "    }\n"
+        "}",
+        "'last-subnet-id' parameter missing or not an integer"
+        },
+        {
+        "last-subnet-id string",
+        "{\n"
+        "    \"command\": \"stat-lease4-get\",\n"
+        "    \"arguments\": {"
+        "        \"subnet-range\": {\n"
+        "           \"first-subnet-id\": 10,\n"
+        "           \"last-subnet-id\": \"boo\"\n"
+        "       }\n"
+        "    }\n"
+        "}",
+        "'last-subnet-id' parameter missing or not an integer"
+        },
+        {
+        "last-subnet-id < 0",
+        "{\n"
+        "    \"command\": \"stat-lease4-get\",\n"
+        "    \"arguments\": {"
+        "        \"subnet-range\": {\n"
+        "           \"first-subnet-id\": 10,\n"
+        "           \"last-subnet-id\": -1\n"
+        "       }\n"
+        "    }\n"
+        "}",
+        "'last-subnet-id' parameter must be > 0"
+        },
+        {
+        "invalid range",
+        "{\n"
+        "    \"command\": \"stat-lease4-get\",\n"
+        "    \"arguments\": {"
+        "        \"subnet-range\": {\n"
+        "           \"first-subnet-id\": 50,\n"
+        "           \"last-subnet-id\": 2\n"
+        "       }\n"
+        "    }\n"
+        "}",
+        "'last-subnet-id' must be greater than 'first-subnet-id'"
+        },
+    };
+
+    for (auto test = tests.begin(); test != tests.end(); ++test) {
+        {
+        SCOPED_TRACE((*test).description_);
+        testCommand((*test).command_txt_, CONTROL_RESULT_ERROR,(*test).exp_response_);
+        }
+    }
+}
+
+// Verifies result content for v4s statistics with with subnets,
+// but no leases.  These tests make it easier to see that the
+// permutations of selection criteria generate the correct rows.
+// These test scenarios are all valid, and not expected to throw.
+TEST_F(StatCmdsTest, statLease4GetValidNoLeases) {
+
+    // Initialize lease manager (false = v4, false = don't add leases)
+    initLeaseMgr4();
+
+    // Note timestamp actual values are not important but are included
+    // for clarity.
+    std::vector<TestScenario> tests = {
+        {
+        "ALL-Subnets",
+        "{\n"
+        "    \"command\": \"stat-lease4-get\",\n"
+        "    \"arguments\": {"
+        "    }\n"
+        "}",
+        "stat-lease4-get: 5 rows found",
+        "{\n"
+        "\"result-set\": {\n"
+        "   \"columns\": [\n"
+        "        \"subnet-id\", \"total-addreses\",\n"
+        "        \"assigned-addreses\", \"declined-addreses\"\n"
+        "   ],\n"
+        "   \"rows\": [\n"
+        "       [ 10, 256, 0, 0 ],\n"
+        "       [ 20,  16, 0, 0 ],\n"
+        "       [ 30, 256, 0, 0 ],\n"
+        "       [ 40,  16, 0, 0 ],\n"
+        "       [ 50, 256, 0, 0 ]\n"
+        "   ],\n"
+        "   \"timestamp\": \"2018-05-04 15:03:37.000000\" }\n"
+        "}\n"
+        },
+        {
+        "Single-Subnet",
+        "{\n"
+        "    \"command\": \"stat-lease4-get\",\n"
+        "    \"arguments\": {"
+        "       \"subnet-id\": 20"
+        "    }\n"
+        "}",
+        "stat-lease4-get: 1 rows found",
+        "{\n"
+        "\"result-set\": {\n"
+        "   \"columns\": [\n"
+        "        \"subnet-id\", \"total-addreses\",\n"
+        "        \"assigned-addreses\", \"declined-addreses\"\n"
+        "   ],\n"
+        "   \"rows\": [\n"
+        "       [ 20, 16, 0, 0 ],\n"
+        "   ],\n"
+        "   \"timestamp\": \"2018-05-04 15:03:37.000000\" }\n"
+        "}\n"
+        },
+        {
+        "Subnet-Range: beginning to middle",
+        "{\n"
+        "    \"command\": \"stat-lease4-get\",\n"
+        "    \"arguments\": {"
+        "       \"subnet-range\": {\n"
+        "           \"first-subnet-id\": 10,"
+        "           \"last-subnet-id\": 30"
+        "       }\n"
+        "    }\n"
+        "}",
+        "stat-lease4-get: 3 rows found",
+        "{\n"
+        "\"result-set\": {\n"
+        "   \"columns\": [\n"
+        "        \"subnet-id\", \"total-addreses\",\n"
+        "        \"assigned-addreses\", \"declined-addreses\"\n"
+        "   ],\n"
+        "   \"rows\": [\n"
+        "       [ 10, 256, 0, 0 ],\n"
+        "       [ 20,  16, 0, 0 ],\n"
+        "       [ 30, 256, 0, 0 ],\n"
+        "   ],\n"
+        "   \"timestamp\": \"2018-05-04 15:03:37.000000\" }\n"
+        "}\n"
+        },
+        {
+        "Subnet-Range: all in the middle",
+        "{\n"
+        "    \"command\": \"stat-lease4-get\",\n"
+        "    \"arguments\": {"
+        "       \"subnet-range\": {\n"
+        "           \"first-subnet-id\": 20,"
+        "           \"last-subnet-id\": 40"
+        "       }\n"
+        "    }\n"
+        "}",
+        "stat-lease4-get: 3 rows found",
+        "{\n"
+        "\"result-set\": {\n"
+        "   \"columns\": [\n"
+        "        \"subnet-id\", \"total-addreses\",\n"
+        "        \"assigned-addreses\", \"declined-addreses\"\n"
+        "   ],\n"
+        "   \"rows\": [\n"
+        "       [ 20,  16, 0, 0 ],\n"
+        "       [ 30, 256, 0, 0 ],\n"
+        "       [ 40,  16, 0, 0 ],\n"
+        "   ],\n"
+        "   \"timestamp\": \"2018-05-04 15:03:37.000000\" }\n"
+        "}\n"
+        },
+        {
+        "Subnet-Range: middle to end",
+        "{\n"
+        "    \"command\": \"stat-lease4-get\",\n"
+        "    \"arguments\": {"
+        "       \"subnet-range\": {\n"
+        "           \"first-subnet-id\": 30,"
+        "           \"last-subnet-id\": 50"
+        "       }\n"
+        "    }\n"
+        "}",
+        "stat-lease4-get: 3 rows found",
+        "{\n"
+        "\"result-set\": {\n"
+        "   \"columns\": [\n"
+        "        \"subnet-id\", \"total-addreses\",\n"
+        "        \"assigned-addreses\", \"declined-addreses\"\n"
+        "   ],\n"
+        "   \"rows\": [\n"
+        "       [ 30, 256, 0, 0 ],\n"
+        "       [ 40,  16, 0, 0 ],\n"
+        "       [ 50, 256, 0, 0 ],\n"
+        "   ],\n"
+        "   \"timestamp\": \"2018-05-04 15:03:37.000000\" }\n"
+        "}\n"
+        },
+        {
+        "Subnet-Range: fuzzy range",
+        "{\n"
+        "    \"command\": \"stat-lease4-get\",\n"
+        "    \"arguments\": {"
+        "       \"subnet-range\": {\n"
+        "           \"first-subnet-id\": 25,"
+        "           \"last-subnet-id\": 45"
+        "       }\n"
+        "    }\n"
+        "}",
+        "stat-lease4-get: 2 rows found",
+        "{\n"
+        "\"result-set\": {\n"
+        "   \"columns\": [\n"
+        "        \"subnet-id\", \"total-addreses\",\n"
+        "        \"assigned-addreses\", \"declined-addreses\"\n"
+        "   ],\n"
+        "   \"rows\": [\n"
+        "       [ 30, 256, 0, 0 ],\n"
+        "       [ 40,  16, 0, 0 ],\n"
+        "   ],\n"
+        "   \"timestamp\": \"2018-05-04 15:03:37.000000\" }\n"
+        "}\n"
+        }
+    };
+
+    for (auto test = tests.begin(); test != tests.end(); ++test) {
+        {
+        SCOPED_TRACE((*test).description_);
+        testCommand((*test).command_txt_, CONTROL_RESULT_SUCCESS,
+                    (*test).exp_response_, (*test).exp_result_json);
+        }
+    }
+
+}
+
+TEST_F(StatCmdsTest, statLease4GetSubnetsNotFound) {
+
+    // Initialize lease manager (false = v4, false = don't add leases)
+    initLeaseMgr4();
+
+    // Note timestamp actual values are not important but are included
+    // for clarity.
+    std::vector<TestScenario> tests = {
+        {
+        "Single-Subnet, undefined subnet",
+        "{\n"
+        "    \"command\": \"stat-lease4-get\",\n"
+        "    \"arguments\": {"
+        "       \"subnet-id\": 88"
+        "    }\n"
+        "}",
+        "stat-lease4-get: no matching data, subnet-id: 88 does not exist",
+        "{}"
+        },
+        {
+        "Subnet-Range: empty range below",
+        "{\n"
+        "    \"command\": \"stat-lease4-get\",\n"
+        "    \"arguments\": {"
+        "       \"subnet-range\": {\n"
+        "           \"first-subnet-id\": 2,"
+        "           \"last-subnet-id\": 6"
+        "       }\n"
+        "    }\n"
+        "}",
+        "stat-lease4-get: no matching data, selected ID range: 2 through 6 includes no known subnets",
+        "{}"
+        },
+        {
+        "Subnet-Range: empty range above",
+        "{\n"
+        "    \"command\": \"stat-lease4-get\",\n"
+        "    \"arguments\": {"
+        "       \"subnet-range\": {\n"
+        "           \"first-subnet-id\": 200,"
+        "           \"last-subnet-id\": 600"
+        "       }\n"
+        "    }\n"
+        "}",
+        "stat-lease4-get: no matching data, selected ID range: 200 through 600 includes no known subnets",
+        "{}"
+        }
+    };
+
+    for (auto test = tests.begin(); test != tests.end(); ++test) {
+        {
+        SCOPED_TRACE((*test).description_);
+        testCommand((*test).command_txt_, CONTROL_RESULT_EMPTY,
+                    (*test).exp_response_, (*test).exp_result_json);
+        }
+    }
+
+}
+
+
+TEST_F(StatCmdsTest, StatLease6GetBadParams) {
+    // Initialize lease manager
+    initLeaseMgr6();
+
+    std::vector<TestScenario> tests = {
+        {
+        "subnet-id 0",
+        "{\n"
+        "    \"command\": \"stat-lease6-get\",\n"
+        "    \"arguments\": {"
+        "        \"subnet-id\": 0\n"
+        "    }\n"
+        "}",
+        "'subnet-id' parameter must be > 0"
+        },
+
+        {
+        "subnet-id -1",
+        "{\n"
+        "    \"command\": \"stat-lease6-get\",\n"
+        "    \"arguments\": {"
+        "        \"subnet-id\": -1\n"
+        "    }\n"
+        "}",
+        "'subnet-id' parameter must be > 0"
+        },
+        {
+        "subnet-id string",
+        "{\n"
+        "    \"command\": \"stat-lease6-get\",\n"
+        "    \"arguments\": {"
+        "        \"subnet-id\": \"boo\"\n"
+        "    }\n"
+        "}",
+        "'subnet-id' parameter is not integer"
+        },
+        {
+        "subnet-range not a map",
+        "{\n"
+        "    \"command\": \"stat-lease6-get\",\n"
+        "    \"arguments\": {"
+        "        \"subnet-range\": -1\n"
+        "    }\n"
+        "}",
+        "subnet-range parameter is not a map"
+        },
+        {
+        "subnet-range empty",
+        "{\n"
+        "    \"command\": \"stat-lease6-get\",\n"
+        "    \"arguments\": {"
+        "        \"subnet-range\": {\n"
+        "       }\n"
+        "    }\n"
+        "}",
+        "'first-subnet-id' parameter missing or not an integer"
+        },
+        {
+        "first-subnet-id string",
+        "{\n"
+        "    \"command\": \"stat-lease6-get\",\n"
+        "    \"arguments\": {"
+        "        \"subnet-range\": {\n"
+        "           \"first-subnet-id\": \"boo\"\n"
+        "       }\n"
+        "    }\n"
+        "}",
+        "'first-subnet-id' parameter missing or not an integer"
+        },
+        {
+        "first-subnet-id < 0",
+        "{\n"
+        "    \"command\": \"stat-lease6-get\",\n"
+        "    \"arguments\": {"
+        "        \"subnet-range\": {\n"
+        "           \"first-subnet-id\": -77\n"
+        "       }\n"
+        "    }\n"
+        "}",
+        "'first-subnet-id' parameter must be > 0"
+        },
+        {
+        "last-subnet-id missing",
+        "{\n"
+        "    \"command\": \"stat-lease6-get\",\n"
+        "    \"arguments\": {"
+        "        \"subnet-range\": {\n"
+        "           \"first-subnet-id\": 10\n"
+        "       }\n"
+        "    }\n"
+        "}",
+        "'last-subnet-id' parameter missing or not an integer"
+        },
+        {
+        "last-subnet-id string",
+        "{\n"
+        "    \"command\": \"stat-lease6-get\",\n"
+        "    \"arguments\": {"
+        "        \"subnet-range\": {\n"
+        "           \"first-subnet-id\": 10,\n"
+        "           \"last-subnet-id\": \"boo\"\n"
+        "       }\n"
+        "    }\n"
+        "}",
+        "'last-subnet-id' parameter missing or not an integer"
+        },
+        {
+        "last-subnet-id < 0",
+        "{\n"
+        "    \"command\": \"stat-lease6-get\",\n"
+        "    \"arguments\": {"
+        "        \"subnet-range\": {\n"
+        "           \"first-subnet-id\": 10,\n"
+        "           \"last-subnet-id\": -1\n"
+        "       }\n"
+        "    }\n"
+        "}",
+        "'last-subnet-id' parameter must be > 0"
+        },
+        {
+        "invalid range",
+        "{\n"
+        "    \"command\": \"stat-lease6-get\",\n"
+        "    \"arguments\": {"
+        "        \"subnet-range\": {\n"
+        "           \"first-subnet-id\": 50,\n"
+        "           \"last-subnet-id\": 2\n"
+        "       }\n"
+        "    }\n"
+        "}",
+        "'last-subnet-id' must be greater than 'first-subnet-id'"
+        },
+    };
+
+    for (auto test = tests.begin(); test != tests.end(); ++test) {
+        {
+        SCOPED_TRACE((*test).description_);
+        testCommand((*test).command_txt_, CONTROL_RESULT_ERROR,(*test).exp_response_);
+        }
+    }
+}
+
+// Verifies result content for v6s statistics with with subnets,
+// but no leases.  These tests make it easier to see that the
+// permutations of selection criteria generate the correct rows.
+// These test scenarios are all valid, and not expected to throw.
+TEST_F(StatCmdsTest, statLease6GetValidNoLeases) {
+
+    // Initialize lease manager
+    initLeaseMgr6();
+
+    // Note timestamp actual values are not important but are included
+    // for clarity.
+    std::vector<TestScenario> tests = {
+        {
+        "ALL-Subnets6",
+        "{\n"
+        "    \"command\": \"stat-lease6-get\",\n"
+        "    \"arguments\": {"
+        "    }\n"
+        "}",
+        "stat-lease6-get: 5 rows found",
+        "{\n"
+        "\"result-set\": {\n"
+        "   \"columns\": [\n"
+        "        \"subnet-id\", \"total-nas\", \"assigned-nas\",\n"
+        "        \"declined-nas\", \"total-pds\", \"assigned-pds\"\n"
+        "   ],\n"
+        "   \"rows\": [\n"
+        "       [ 10, 65536, 0, 0, 0, 0 ],\n"
+        "       [ 20, 16777216, 0, 0, 0, 0 ],\n"
+        "       [ 30, 16, 0, 0, 65536, 0 ],\n"
+        "       [ 40, 16777216, 0, 0, 0, 0 ],\n"
+        "       [ 50, 0, 0, 0, 65536, 0 ]\n"
+        "   ],\n"
+        "   \"timestamp\": \"2018-05-04 15:03:37.000000\" }\n"
+        "}\n"
+        },
+        {
+        "Single-Subnet6",
+        "{\n"
+        "    \"command\": \"stat-lease6-get\",\n"
+        "    \"arguments\": {"
+        "       \"subnet-id\": 20"
+        "    }\n"
+        "}",
+        "stat-lease6-get: 1 rows found",
+        "{\n"
+        "\"result-set\": {\n"
+        "   \"columns\": [\n"
+        "        \"subnet-id\", \"total-nas\", \"assigned-nas\",\n"
+        "        \"declined-nas\", \"total-pds\", \"assigned-pds\"\n"
+        "   ],\n"
+        "   \"rows\": [\n"
+        "       [ 20, 16777216, 0, 0, 0, 0 ]\n"
+        "   ],\n"
+        "   \"timestamp\": \"2018-05-04 15:03:37.000000\" }\n"
+        "}\n"
+        },
+        {
+        "Subnet-Range6: beginning to middle",
+        "{\n"
+        "    \"command\": \"stat-lease6-get\",\n"
+        "    \"arguments\": {"
+        "       \"subnet-range\": {\n"
+        "           \"first-subnet-id\": 10,"
+        "           \"last-subnet-id\": 30"
+        "       }\n"
+        "    }\n"
+        "}",
+        "stat-lease6-get: 3 rows found",
+        "{\n"
+        "\"result-set\": {\n"
+        "   \"columns\": [\n"
+        "        \"subnet-id\", \"total-nas\", \"assigned-nas\",\n"
+        "        \"declined-nas\", \"total-pds\", \"assigned-pds\"\n"
+        "   ],\n"
+        "   \"rows\": [\n"
+        "       [ 10, 65536, 0, 0, 0, 0 ],\n"
+        "       [ 20, 16777216, 0, 0, 0, 0 ],\n"
+        "       [ 30, 16, 0, 0, 65536, 0 ]\n"
+        "   ],\n"
+        "   \"timestamp\": \"2018-05-04 15:03:37.000000\" }\n"
+        "}\n"
+        },
+        {
+        "Subnet-Range6: all in the middle",
+        "{\n"
+        "    \"command\": \"stat-lease6-get\",\n"
+        "    \"arguments\": {"
+        "       \"subnet-range\": {\n"
+        "           \"first-subnet-id\": 20,"
+        "           \"last-subnet-id\": 40"
+        "       }\n"
+        "    }\n"
+        "}",
+        "stat-lease6-get: 3 rows found",
+        "{\n"
+        "\"result-set\": {\n"
+        "   \"columns\": [\n"
+        "        \"subnet-id\", \"total-nas\", \"assigned-nas\",\n"
+        "        \"declined-nas\", \"total-pds\", \"assigned-pds\"\n"
+        "   ],\n"
+        "   \"rows\": [\n"
+        "       [ 20, 16777216, 0, 0, 0, 0 ],\n"
+        "       [ 30, 16, 0, 0, 65536, 0 ],\n"
+        "       [ 40, 16777216, 0, 0, 0, 0 ]\n"
+        "   ],\n"
+        "   \"timestamp\": \"2018-05-04 15:03:37.000000\" }\n"
+        "}\n"
+        },
+        {
+        "Subnet-Range6: middle to end",
+        "{\n"
+        "    \"command\": \"stat-lease6-get\",\n"
+        "    \"arguments\": {"
+        "       \"subnet-range\": {\n"
+        "           \"first-subnet-id\": 30,"
+        "           \"last-subnet-id\": 50"
+        "       }\n"
+        "    }\n"
+        "}",
+        "stat-lease6-get: 3 rows found",
+        "{\n"
+        "\"result-set\": {\n"
+        "   \"columns\": [\n"
+        "        \"subnet-id\", \"total-nas\", \"assigned-nas\",\n"
+        "        \"declined-nas\", \"total-pds\", \"assigned-pds\"\n"
+        "   ],\n"
+        "   \"rows\": [\n"
+        "       [ 30, 16, 0, 0, 65536, 0 ],\n"
+        "       [ 40, 16777216, 0, 0, 0, 0 ],\n"
+        "       [ 50, 0, 0, 0, 65536, 0 ]\n"
+        "   ],\n"
+        "   \"timestamp\": \"2018-05-04 15:03:37.000000\" }\n"
+        "}\n"
+        },
+        {
+        "Subnet-Range6: fuzzy range",
+        "{\n"
+        "    \"command\": \"stat-lease6-get\",\n"
+        "    \"arguments\": {"
+        "       \"subnet-range\": {\n"
+        "           \"first-subnet-id\": 25,"
+        "           \"last-subnet-id\": 45"
+        "       }\n"
+        "    }\n"
+        "}",
+        "stat-lease6-get: 2 rows found",
+        "{\n"
+        "\"result-set\": {\n"
+        "   \"columns\": [\n"
+        "        \"subnet-id\", \"total-nas\", \"assigned-nas\",\n"
+        "        \"declined-nas\", \"total-pds\", \"assigned-pds\"\n"
+        "   ],\n"
+        "   \"rows\": [\n"
+        "       [ 30, 16, 0, 0, 65536, 0 ],\n"
+        "       [ 40, 16777216, 0, 0, 0, 0 ]\n"
+        "   ],\n"
+        "   \"timestamp\": \"2018-05-04 15:03:37.000000\" }\n"
+        "}\n"
+        }
+    };
+
+    for (auto test = tests.begin(); test != tests.end(); ++test) {
+        {
+        SCOPED_TRACE((*test).description_);
+        testCommand((*test).command_txt_, CONTROL_RESULT_SUCCESS,
+                    (*test).exp_response_, (*test).exp_result_json);
+        }
+    }
+
+}
+
+TEST_F(StatCmdsTest, statLease6GetSubnetsNotFound) {
+
+    // Initialize lease manager
+    initLeaseMgr6();
+
+    // Note timestamp actual values are not important but are included
+    // for clarity.
+    std::vector<TestScenario> tests = {
+        {
+        "Single-Subnet6, undefined subnet",
+        "{\n"
+        "    \"command\": \"stat-lease6-get\",\n"
+        "    \"arguments\": {"
+        "       \"subnet-id\": 88"
+        "    }\n"
+        "}",
+        "stat-lease6-get: no matching data, subnet-id: 88 does not exist",
+        "{}"
+        },
+        {
+        "Subnet-Range6: empty range below",
+        "{\n"
+        "    \"command\": \"stat-lease6-get\",\n"
+        "    \"arguments\": {"
+        "       \"subnet-range\": {\n"
+        "           \"first-subnet-id\": 2,"
+        "           \"last-subnet-id\": 6"
+        "       }\n"
+        "    }\n"
+        "}",
+        "stat-lease6-get: no matching data, selected ID range: 2 through 6 includes no known subnets",
+        "{}"
+        },
+        {
+        "Subnet-Range6: empty range above",
+        "{\n"
+        "    \"command\": \"stat-lease6-get\",\n"
+        "    \"arguments\": {"
+        "       \"subnet-range\": {\n"
+        "           \"first-subnet-id\": 200,"
+        "           \"last-subnet-id\": 600"
+        "       }\n"
+        "    }\n"
+        "}",
+        "stat-lease6-get: no matching data, selected ID range: 200 through 600 includes no known subnets",
+        "{}"
+        }
+    };
+
+    for (auto test = tests.begin(); test != tests.end(); ++test) {
+        {
+        SCOPED_TRACE((*test).description_);
+        testCommand((*test).command_txt_, CONTROL_RESULT_EMPTY,
+                    (*test).exp_response_, (*test).exp_result_json);
+        }
+    }
+
+}
+
+
+
+} // end of anonymous namespace
+
diff --git a/src/hooks/dhcp/stat_cmds/version.cc b/src/hooks/dhcp/stat_cmds/version.cc
new file mode 100644 (file)
index 0000000..32834ce
--- /dev/null
@@ -0,0 +1,17 @@
+// Copyright (C) 2018 Internet Systems Consortium, Inc. ("ISC")
+//
+// 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 <hooks/hooks.h>
+
+extern "C" {
+
+/// @brief returns Kea hooks version.
+int version() {
+    return (KEA_HOOKS_VERSION);
+}
+
+}