add DbMgr again & testing data
Change-Id: I3e2153fe1d7bf68a9880b8ff533d9fe27d1e15ba
diff --git a/src/common.hpp b/src/common.hpp
new file mode 100644
index 0000000..d813913
--- /dev/null
+++ b/src/common.hpp
@@ -0,0 +1,39 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014, Regents of the University of California.
+ *
+ * This file is part of NDNS (Named Data Networking Domain Name Service).
+ * See AUTHORS.md for complete list of NDNS authors and contributors.
+ *
+ * NDNS is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * NDNS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * NDNS, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef COMMON_HPP
+#define COMMON_HPP
+
+#ifdef NDNS_HAVE_TESTS
+#define NDNS_VIRTUAL_WITH_TESTS virtual
+#define NDNS_PUBLIC_WITH_TESTS_ELSE_PROTECTED public
+#define NDNS_PUBLIC_WITH_TESTS_ELSE_PRIVATE public
+#define NDNS_PROTECTED_WITH_TESTS_ELSE_PRIVATE protected
+#else
+#define NDNS_VIRTUAL_WITH_TESTS
+#define NDNS_PUBLIC_WITH_TESTS_ELSE_PROTECTED protected
+#define NDNS_PUBLIC_WITH_TESTS_ELSE_PRIVATE private
+#define NDNS_PROTECTED_WITH_TESTS_ELSE_PRIVATE private
+#endif
+
+
+
+
+
+#endif // COMMON_HPP
diff --git a/src/daemon/db-mgr.cpp b/src/daemon/db-mgr.cpp
new file mode 100644
index 0000000..35af5de
--- /dev/null
+++ b/src/daemon/db-mgr.cpp
@@ -0,0 +1,393 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014, Regents of the University of California.
+ *
+ * This file is part of NDNS (Named Data Networking Domain Name Service).
+ * See AUTHORS.md for complete list of NDNS authors and contributors.
+ *
+ * NDNS is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * NDNS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * NDNS, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "db-mgr.hpp"
+#include "logger.hpp"
+#include "clients/response.hpp"
+
+#include <iostream>
+#include <fstream>
+
+namespace ndn {
+namespace ndns {
+
+NDNS_LOG_INIT("DbMgr");
+
+static const std::string NDNS_SCHEMA = "\
+CREATE TABLE IF NOT EXISTS zones ( \n\
+ id INTEGER NOT NULL PRIMARY KEY, \n\
+ name blob NOT NULL UNIQUE, \n\
+ ttl integer(10) NOT NULL); \n\
+ \n\
+CREATE TABLE IF NOT EXISTS rrsets ( \n\
+ id INTEGER NOT NULL PRIMARY KEY, \n\
+ zone_id integer(10) NOT NULL, \n\
+ label blob NOT NULL, \n\
+ type blob NOT NULL, \n\
+ version blob NOT NULL, \n\
+ ttl integer(10) NOT NULL, \n\
+ data blob NOT NULL, \n\
+ FOREIGN KEY(zone_id) REFERENCES zones(id) ON UPDATE Cascade ON DELETE Cascade); \n\
+ \n\
+CREATE UNIQUE INDEX rrsets_zone_id_label_type_version \n\
+ ON rrsets (zone_id, label, type, version); \n\
+";
+
+DbMgr::DbMgr(const std::string& dbFile/* = DEFAULT_CONFIG_PATH "/" "ndns.db"*/)
+ : m_dbFile(dbFile)
+ , m_conn(0)
+{
+ if (dbFile.empty())
+ m_dbFile = DEFAULT_DATABASE_PATH "/" "ndns.db";
+
+ this->open();
+
+ NDNS_LOG_INFO("open database: " << m_dbFile);
+}
+
+
+DbMgr::~DbMgr()
+{
+ if (m_conn != 0) {
+ this->close();
+ }
+}
+
+void
+DbMgr::open()
+{
+ int res = sqlite3_open_v2(m_dbFile.c_str(), &m_conn,
+ SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
+#ifdef DISABLE_SQLITE3_FS_LOCKING
+ "unix-dotfile"
+#else
+ 0
+#endif
+ );
+
+ if (res != SQLITE_OK) {
+ NDNS_LOG_FATAL("Cannot open the db file: " << m_dbFile);
+ throw ConnectError("Cannot open the db file: " + m_dbFile);
+ }
+ // ignore any errors from DB creation (command will fail for the existing database, which is ok)
+ sqlite3_exec(m_conn, NDNS_SCHEMA.c_str(), 0, 0, 0);
+}
+
+void
+DbMgr::close()
+{
+ if (m_conn == 0)
+ return;
+
+ int ret = sqlite3_close(m_conn);
+ if (ret != SQLITE_OK) {
+ NDNS_LOG_FATAL("Cannot close the db: " << m_dbFile);
+ }
+ else {
+ m_conn = 0;
+ NDNS_LOG_INFO("Close database: " << m_dbFile);
+ }
+}
+
+void
+DbMgr::clearAllData()
+{
+ const char* sql = "DELETE FROM zones; DELETE FROM rrsets;";
+
+ int rc = sqlite3_exec(m_conn, sql, 0, 0, 0); // sqlite3_step cannot execute multiple SQL statement
+ if (rc != SQLITE_OK) {
+ throw ExecuteError(sql);
+ }
+
+ NDNS_LOG_INFO("clear all the data in the database: " << m_dbFile);
+}
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// Zone
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+void
+DbMgr::insert(Zone& zone)
+{
+ if (zone.getId() > 0)
+ return;
+
+ sqlite3_stmt* stmt;
+ const char* sql = "INSERT INTO zones (name, ttl) VALUES (?, ?)";
+ int rc = sqlite3_prepare_v2(m_conn, sql, -1, &stmt, 0);
+ if (rc != SQLITE_OK) {
+ throw PrepareError(sql);
+ }
+
+ const Block& zoneName = zone.getName().wireEncode();
+ sqlite3_bind_blob(stmt, 1, zoneName.wire(), zoneName.size(), SQLITE_STATIC);
+ sqlite3_bind_int(stmt, 2, zone.getTtl().count());
+
+ rc = sqlite3_step(stmt);
+ if (rc != SQLITE_DONE) {
+ sqlite3_finalize(stmt);
+ throw ExecuteError(sql);
+ }
+
+ zone.setId(sqlite3_last_insert_rowid(m_conn));
+ sqlite3_finalize(stmt);
+}
+
+bool
+DbMgr::find(Zone& zone)
+{
+ sqlite3_stmt* stmt;
+ const char* sql = "SELECT id, ttl FROM zones WHERE name=?";
+ int rc = sqlite3_prepare_v2(m_conn, sql, -1, &stmt, 0);
+ if (rc != SQLITE_OK) {
+ throw PrepareError(sql);
+ }
+
+ const Block& zoneName = zone.getName().wireEncode();
+ sqlite3_bind_blob(stmt, 1, zoneName.wire(), zoneName.size(), SQLITE_STATIC);
+
+ if (sqlite3_step(stmt) == SQLITE_ROW) {
+ zone.setId(sqlite3_column_int64(stmt, 0));
+ zone.setTtl(time::seconds(sqlite3_column_int(stmt, 1)));
+ } else {
+ zone.setId(0);
+ }
+
+ sqlite3_finalize(stmt);
+
+ return zone.getId() != 0;
+}
+
+void
+DbMgr::remove(Zone& zone)
+{
+ if (zone.getId() == 0)
+ return;
+
+ sqlite3_stmt* stmt;
+ const char* sql = "DELETE FROM zones where id=?";
+ int rc = sqlite3_prepare_v2(m_conn, sql, -1, &stmt, 0);
+ if (rc != SQLITE_OK) {
+ throw PrepareError(sql);
+ }
+
+ sqlite3_bind_int64(stmt, 1, zone.getId());
+
+ rc = sqlite3_step(stmt);
+ if (rc != SQLITE_DONE) {
+ sqlite3_finalize(stmt);
+ throw ExecuteError(sql);
+ }
+
+ sqlite3_finalize(stmt);
+
+ zone = Zone();
+}
+
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// Rrset
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+void
+DbMgr::insert(Rrset& rrset)
+{
+ if (rrset.getId() != 0)
+ return;
+
+ if (rrset.getZone() == 0) {
+ throw RrsetError("Rrset has not been assigned to a zone");
+ }
+
+ if (rrset.getZone()->getId() == 0) {
+ insert(*rrset.getZone());
+ }
+
+ const char* sql =
+ "INSERT INTO rrsets (zone_id, label, type, version, ttl, data)"
+ " VALUES (?, ?, ?, ?, ?, ?)";
+
+ sqlite3_stmt* stmt;
+ int rc = sqlite3_prepare_v2(m_conn, sql, -1, &stmt, 0);
+ if (rc != SQLITE_OK) {
+ throw PrepareError(sql);
+ }
+
+ sqlite3_bind_int64(stmt, 1, rrset.getZone()->getId());
+
+ const Block& label = rrset.getLabel().wireEncode();
+ sqlite3_bind_blob(stmt, 2, label.wire(), label.size(), SQLITE_STATIC);
+ sqlite3_bind_blob(stmt, 3, rrset.getType().wire(), rrset.getType().size(), SQLITE_STATIC);
+ sqlite3_bind_blob(stmt, 4, rrset.getVersion().wire(), rrset.getVersion().size(), SQLITE_STATIC);
+ sqlite3_bind_int64(stmt, 5, rrset.getTtl().count());
+ sqlite3_bind_blob(stmt, 6, rrset.getData().wire(), rrset.getData().size(), SQLITE_STATIC);
+
+ rc = sqlite3_step(stmt);
+ if (rc != SQLITE_DONE) {
+ sqlite3_finalize(stmt);
+ throw ExecuteError(sql);
+ }
+
+ rrset.setId(sqlite3_last_insert_rowid(m_conn));
+ sqlite3_finalize(stmt);
+}
+
+bool
+DbMgr::find(Rrset& rrset)
+{
+ if (rrset.getZone() == 0) {
+ throw RrsetError("Rrset has not been assigned to a zone");
+ }
+
+ if (rrset.getZone()->getId() == 0) {
+ bool isFound = find(*rrset.getZone());
+ if (!isFound) {
+ return false;
+ }
+ }
+
+ sqlite3_stmt* stmt;
+ const char* sql =
+ "SELECT id, ttl, version, data FROM rrsets"
+ " WHERE zone_id=? and label=? and type=?";
+ int rc = sqlite3_prepare_v2(m_conn, sql, -1, &stmt, 0);
+
+ if (rc != SQLITE_OK) {
+ throw PrepareError(sql);
+ }
+
+ sqlite3_bind_int64(stmt, 1, rrset.getZone()->getId());
+
+ const Block& label = rrset.getLabel().wireEncode();
+ sqlite3_bind_blob(stmt, 2, label.wire(), label.size(), SQLITE_STATIC);
+ sqlite3_bind_blob(stmt, 3, rrset.getType().wire(), rrset.getType().size(), SQLITE_STATIC);
+
+ if (sqlite3_step(stmt) == SQLITE_ROW) {
+ rrset.setId(sqlite3_column_int64(stmt, 0));
+ rrset.setTtl(time::seconds(sqlite3_column_int64(stmt, 1)));
+ rrset.setVersion(Block(static_cast<const uint8_t*>(sqlite3_column_blob(stmt, 2)),
+ sqlite3_column_bytes(stmt, 2)));
+ rrset.setData(Block(static_cast<const uint8_t*>(sqlite3_column_blob(stmt, 3)),
+ sqlite3_column_bytes(stmt, 3)));
+ } else {
+ rrset.setId(0);
+ }
+ sqlite3_finalize(stmt);
+
+ return rrset.getId() != 0;
+}
+
+std::vector<Rrset>
+DbMgr::findRrsets(Zone& zone)
+{
+ if (zone.getId() == 0)
+ find(zone);
+
+ if (zone.getId() == 0)
+ throw RrsetError("Attempting to find all the rrsets with a zone does not in the database");
+
+ std::vector<Rrset> vec;
+ sqlite3_stmt* stmt;
+ const char* sql = "SELECT id, ttl, version, data, label, type "
+ "FROM rrsets where zone_id=? ";
+
+ int rc = sqlite3_prepare_v2(m_conn, sql, -1, &stmt, 0);
+ if (rc != SQLITE_OK) {
+ throw PrepareError(sql);
+ }
+ sqlite3_bind_int64(stmt, 1, zone.getId());
+
+ while (sqlite3_step(stmt) == SQLITE_ROW) {
+ vec.emplace_back(&zone);
+ Rrset& rrset = vec.back();
+
+ rrset.setId(sqlite3_column_int64(stmt, 0));
+ rrset.setTtl(time::seconds(sqlite3_column_int64(stmt, 1)));
+ rrset.setVersion(Block(static_cast<const uint8_t*>(sqlite3_column_blob(stmt, 2)),
+ sqlite3_column_bytes(stmt, 2)));
+ rrset.setData(Block(static_cast<const uint8_t*>(sqlite3_column_blob(stmt, 3)),
+ sqlite3_column_bytes(stmt, 3)));
+ rrset.setLabel(Name(Block(static_cast<const uint8_t*>(sqlite3_column_blob(stmt, 4)),
+ sqlite3_column_bytes(stmt, 4))));
+ rrset.setType(Block(static_cast<const uint8_t*>(sqlite3_column_blob(stmt, 5)),
+ sqlite3_column_bytes(stmt, 5)));
+ }
+ sqlite3_finalize(stmt);
+
+ return vec;
+}
+
+
+void
+DbMgr::remove(Rrset& rrset)
+{
+ if (rrset.getId() == 0)
+ throw RrsetError("Attempting to remove Rrset that has no assigned id");
+
+ sqlite3_stmt* stmt;
+ const char* sql = "DELETE FROM rrsets WHERE id=?";
+ int rc = sqlite3_prepare_v2(m_conn, sql, -1, &stmt, 0);
+
+ if (rc != SQLITE_OK) {
+ throw PrepareError(sql);
+ }
+
+ sqlite3_bind_int64(stmt, 1, rrset.getId());
+
+ rc = sqlite3_step(stmt);
+ if (rc != SQLITE_DONE) {
+ sqlite3_finalize(stmt);
+ throw ExecuteError(sql);
+ }
+
+ sqlite3_finalize(stmt);
+
+ rrset = Rrset(rrset.getZone());
+}
+
+void
+DbMgr::update(Rrset& rrset)
+{
+ if (rrset.getId() == 0) {
+ throw RrsetError("Attempting to replace Rrset that has no assigned id");
+ }
+
+ if (rrset.getZone() == 0) {
+ throw RrsetError("Rrset has not been assigned to a zone");
+ }
+
+ sqlite3_stmt* stmt;
+ const char* sql = "UPDATE rrsets SET ttl=?, version=?, data=? WHERE id=?";
+ int rc = sqlite3_prepare_v2(m_conn, sql, -1, &stmt, 0);
+
+ if (rc != SQLITE_OK) {
+ throw PrepareError(sql);
+ }
+
+ sqlite3_bind_int64(stmt, 1, rrset.getTtl().count());
+ sqlite3_bind_blob(stmt, 2, rrset.getVersion().wire(), rrset.getVersion().size(), SQLITE_STATIC);
+ sqlite3_bind_blob(stmt, 3, rrset.getData().wire(), rrset.getData().size(), SQLITE_STATIC);
+ sqlite3_bind_int64(stmt, 4, rrset.getId());
+
+ sqlite3_step(stmt);
+ sqlite3_finalize(stmt);
+}
+
+} // namespace ndns
+} // namespace ndn
diff --git a/src/daemon/db-mgr.hpp b/src/daemon/db-mgr.hpp
new file mode 100644
index 0000000..ca83691
--- /dev/null
+++ b/src/daemon/db-mgr.hpp
@@ -0,0 +1,188 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014, Regents of the University of California.
+ *
+ * This file is part of NDNS (Named Data Networking Domain Name Service).
+ * See AUTHORS.md for complete list of NDNS authors and contributors.
+ *
+ * NDNS is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * NDNS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * NDNS, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef NDNS_DAEMON_DB_MGR_HPP
+#define NDNS_DAEMON_DB_MGR_HPP
+
+#include "config.hpp"
+#include "zone.hpp"
+#include "rrset.hpp"
+
+#include <ndn-cxx/common.hpp>
+#include <sqlite3.h>
+
+namespace ndn {
+namespace ndns {
+
+#define DEFINE_ERROR(ErrorName, Base) \
+class ErrorName : public Base \
+{ \
+ public: \
+ explicit \
+ ErrorName(const std::string& what) \
+ : Base(what) \
+ { \
+ } \
+};
+
+
+
+/**
+ * @brief Database Manager, provides CRUD operations on stored entities
+ *
+ * @note Method names follow MongoDB convention: insert/remove/find/update
+ */
+class DbMgr : noncopyable
+{
+public:
+
+ /**
+ * @brief The Database Status
+ */
+ enum DbStatus {
+ DB_CONNECTED,
+ DB_CLOSED,
+ DB_ERROR
+ };
+
+ DEFINE_ERROR(Error, std::runtime_error);
+ DEFINE_ERROR(PrepareError, Error);
+ DEFINE_ERROR(ExecuteError, Error);
+ DEFINE_ERROR(ConnectError, Error);
+
+public:
+ explicit
+ DbMgr(const std::string& dbFile = DEFAULT_DATABASE_PATH "/" "ndns.db");
+
+ ~DbMgr();
+
+ /**
+ * @brief connect to the database. If it's already opened, do nothing.
+ */
+ void
+ open();
+
+ /**
+ * @brief close the database connection. Do nothing if it's already closed.
+ * Destructor would automatically close the database connection as well.
+ */
+ void
+ close();
+
+ /**
+ * @brief clear all the data in the database
+ */
+ void
+ clearAllData();
+
+public: // Zone manipulation
+ DEFINE_ERROR(ZoneError, Error);
+
+ /**
+ * @brief insert the m_zone to the database, and set the zone's id.
+ * If the zone is already in the db, handle the exception without leaving it to upper level,
+ * meanwhile, set the zone's id too.
+ * @pre m_zone.getId() == 0
+ * @post m_zone.getId() > 0
+ */
+ void
+ insert(Zone& zone);
+
+ /**
+ * @brief lookup the zone by name, fill the m_id and m_ttl
+ * @post whatever the previous id is
+ * @return true if the record exist
+ */
+ bool
+ find(Zone& zone);
+
+ /**
+ * @brief remove the zone
+ * @pre m_zone.getId() > 0
+ * @post m_zone.getId() == 0
+ */
+ void
+ remove(Zone& zone);
+
+public: // Rrset manipulation
+ DEFINE_ERROR(RrsetError, Error);
+
+ /**
+ * @brief add the rrset
+ * @pre m_rrset.getId() == 0
+ * @post m_rrset.getId() > 0
+ */
+ void
+ insert(Rrset& rrset);
+
+ /**
+ * @brief get the data from db according to `m_zone`, `m_label`, `m_type`.
+ *
+ * If record exists, `m_ttl`, `m_version` and `m_data` is set
+ *
+ * @pre m_rrset.getZone().getId() > 0
+ * @post whatever the previous id is,
+ * m_rrset.getId() > 0 if record exists, otherwise m_rrset.getId() == 0
+ * @return true if the record exist
+ */
+ bool
+ find(Rrset& rrset);
+
+ /**
+ * @brief get all the rrsets which is stored at given zone
+ * @throw RrsetError() if zone does not exist in the database
+ * @note if zone.getId() == 0, the function setId for the zone automatically
+ * @note all returned rrsets' m_zone point to the memory of the param[in] zone
+ */
+ std::vector<Rrset>
+ findRrsets(Zone& zone);
+
+ /**
+ * @brief remove the rrset
+ * @pre m_rrset.getId() > 0
+ * @post m_rrset.getId() == 0
+ */
+ void
+ remove(Rrset& rrset);
+
+ /**
+ * @brief replace ttl, version, and Data with new values
+ * @pre m_rrset.getId() > 0
+ */
+ void
+ update(Rrset& rrset);
+
+ ////////////////////////////////
+ ////////getter and setter
+public:
+ const std::string&
+ getDbFile() const
+ {
+ return m_dbFile;
+ }
+
+private:
+ std::string m_dbFile;
+ sqlite3* m_conn;
+};
+
+} // namespace ndns
+} // namespace ndn
+
+#endif // NDNS_DAEMON_DB_MGR_HPP
diff --git a/src/logger.cpp b/src/logger.cpp
index c2ca954..274e10e 100644
--- a/src/logger.cpp
+++ b/src/logger.cpp
@@ -35,7 +35,7 @@
namespace log {
void
-init(const std::string& configFile/* = "log4cxx.properties"*/)
+init(const std::string& configFile/*= DEFAULT_CONFIG_PATH "/" "log4cxx.properties"*/)
{
using namespace log4cxx;
using namespace log4cxx::helpers;
diff --git a/src/logger.hpp b/src/logger.hpp
index c17527b..a8999f2 100644
--- a/src/logger.hpp
+++ b/src/logger.hpp
@@ -20,6 +20,7 @@
#ifndef NDNS_LOGGER_HPP
#define NDNS_LOGGER_HPP
+#include "config.hpp"
#include <log4cxx/logger.h>
namespace ndn {
@@ -27,7 +28,7 @@
namespace log {
void
-init(const std::string& configFile = "log4cxx.properties");
+init(const std::string& configFile = DEFAULT_CONFIG_PATH "/" "log4cxx.properties");
// The following has to be pre-processor defines in order to properly determine
// log locations
diff --git a/tests/main.cpp b/tests/main.cpp
index 7d606e7..ac55966 100644
--- a/tests/main.cpp
+++ b/tests/main.cpp
@@ -23,12 +23,13 @@
#include <boost/test/unit_test.hpp>
#include "logger.hpp"
+#include "config.hpp"
namespace ndn {
namespace ndns {
namespace tests {
-class UnitTestsLogging
+class UnitTestsLogging : boost::noncopyable
{
public:
UnitTestsLogging()
diff --git a/tests/unit/daemon/db-mgr.cpp b/tests/unit/daemon/db-mgr.cpp
new file mode 100644
index 0000000..fb621d2
--- /dev/null
+++ b/tests/unit/daemon/db-mgr.cpp
@@ -0,0 +1,221 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014, Regents of the University of California.
+ *
+ * This file is part of NDNS (Named Data Networking Domain Name Service).
+ * See AUTHORS.md for complete list of NDNS authors and contributors.
+ *
+ * NDNS is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * NDNS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * NDNS, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "config.hpp"
+#include "daemon/db-mgr.hpp"
+#include "logger.hpp"
+
+#include "../../boost-test.hpp"
+#include <boost/filesystem.hpp>
+
+#include <algorithm> // std::sort
+
+namespace ndn {
+namespace ndns {
+namespace tests {
+
+NDNS_LOG_INIT("DbMgrTest")
+
+BOOST_AUTO_TEST_SUITE(DbMgr)
+
+static const boost::filesystem::path TEST_DATABASE2 = TEST_CONFIG_PATH "/" "test-ndns.db";
+
+class DbMgrFixture
+{
+public:
+ DbMgrFixture()
+ : session(TEST_DATABASE2.string())
+ {
+ }
+
+ ~DbMgrFixture()
+ {
+ session.close();
+ boost::filesystem::remove(TEST_DATABASE2);
+ NDNS_LOG_INFO("remove database " << TEST_DATABASE2);
+ }
+
+public:
+ ndns::DbMgr session;
+};
+
+
+
+BOOST_FIXTURE_TEST_CASE(Zones, DbMgrFixture)
+{
+ Zone zone1;
+ zone1.setName("/net");
+ zone1.setTtl(time::seconds(4600));
+ BOOST_CHECK_NO_THROW(session.insert(zone1));
+ BOOST_CHECK_GT(zone1.getId(), 0);
+
+ Zone zone2;
+ zone2.setName("/net");
+ session.find(zone2);
+ BOOST_CHECK_EQUAL(zone2.getId(), zone1.getId());
+ BOOST_CHECK_EQUAL(zone2.getTtl(), zone1.getTtl());
+
+ BOOST_CHECK_NO_THROW(session.insert(zone2)); // zone2 already has id. Nothing to execute
+
+ zone2.setId(0);
+ BOOST_CHECK_THROW(session.insert(zone2), ndns::DbMgr::ExecuteError);
+
+ BOOST_CHECK_NO_THROW(session.remove(zone1));
+ BOOST_CHECK_EQUAL(zone1.getId(), 0);
+
+ // record shouldn't exist at this point
+ BOOST_CHECK_NO_THROW(session.find(zone2));
+ BOOST_CHECK_EQUAL(zone2.getId(), 0);
+}
+
+BOOST_FIXTURE_TEST_CASE(Rrsets, DbMgrFixture)
+{
+ Zone zone("/net");
+ Rrset rrset1(&zone);
+
+ // Add
+
+ rrset1.setLabel("/net/ksk-123");
+ rrset1.setType(name::Component("ID-CERT"));
+ rrset1.setVersion(name::Component::fromVersion(567));
+ rrset1.setTtl(time::seconds(4600));
+
+ static const std::string DATA1 = "SOME DATA";
+ rrset1.setData(dataBlock(ndn::tlv::Content, DATA1.c_str(), DATA1.size()));
+
+ BOOST_CHECK_EQUAL(rrset1.getId(), 0);
+ BOOST_CHECK_NO_THROW(session.insert(rrset1));
+ BOOST_CHECK_GT(rrset1.getId(), 0);
+ BOOST_CHECK_GT(rrset1.getZone()->getId(), 0);
+
+ // Lookup
+
+ Rrset rrset2(&zone);
+ rrset2.setLabel("/net/ksk-123");
+ rrset2.setType(name::Component("ID-CERT"));
+
+ bool isFound = false;
+ BOOST_CHECK_NO_THROW(isFound = session.find(rrset2));
+ BOOST_CHECK_EQUAL(isFound, true);
+
+ BOOST_CHECK_EQUAL(rrset2.getId(), rrset1.getId());
+ BOOST_CHECK_EQUAL(rrset2.getLabel(), rrset1.getLabel());
+ BOOST_CHECK_EQUAL(rrset2.getType(), rrset1.getType());
+ BOOST_CHECK_EQUAL(rrset2.getVersion(), rrset1.getVersion());
+ BOOST_CHECK_EQUAL(rrset2.getTtl(), rrset1.getTtl());
+ BOOST_CHECK(rrset2.getData() == rrset1.getData());
+
+ // Replace
+
+ rrset1.setVersion(name::Component::fromVersion(890));
+ static const std::string DATA2 = "ANOTHER DATA";
+ rrset1.setData(dataBlock(ndn::tlv::Content, DATA2.c_str(), DATA2.size()));
+
+ BOOST_CHECK_NO_THROW(session.update(rrset1));
+
+ rrset2 = Rrset(&zone);
+ rrset2.setLabel("/net/ksk-123");
+ rrset2.setType(name::Component("ID-CERT"));
+
+ isFound = false;
+ BOOST_CHECK_NO_THROW(isFound = session.find(rrset2));
+ BOOST_CHECK_EQUAL(isFound, true);
+
+ BOOST_CHECK_EQUAL(rrset2.getId(), rrset1.getId());
+ BOOST_CHECK_EQUAL(rrset2.getLabel(), rrset1.getLabel());
+ BOOST_CHECK_EQUAL(rrset2.getType(), rrset1.getType());
+ BOOST_CHECK_EQUAL(rrset2.getVersion(), rrset1.getVersion());
+ BOOST_CHECK_EQUAL(rrset2.getTtl(), rrset1.getTtl());
+ BOOST_CHECK(rrset2.getData() == rrset1.getData());
+
+ // Remove
+
+ BOOST_CHECK_NO_THROW(session.remove(rrset1));
+
+ rrset2 = Rrset(&zone);
+ rrset2.setLabel("/net/ksk-123");
+ rrset2.setType(name::Component("ID-CERT"));
+
+ isFound = false;
+ BOOST_CHECK_NO_THROW(isFound = session.find(rrset2));
+ BOOST_CHECK_EQUAL(isFound, false);
+
+ // Check error handling
+
+ rrset1 = Rrset();
+ BOOST_CHECK_THROW(session.insert(rrset1), ndns::DbMgr::RrsetError);
+ BOOST_CHECK_THROW(session.find(rrset1), ndns::DbMgr::RrsetError);
+
+ rrset1.setId(1);
+ BOOST_CHECK_THROW(session.update(rrset1), ndns::DbMgr::RrsetError);
+
+ rrset1.setId(0);
+ rrset1.setZone(&zone);
+ BOOST_CHECK_THROW(session.update(rrset1), ndns::DbMgr::RrsetError);
+
+ BOOST_CHECK_THROW(session.remove(rrset1), ndns::DbMgr::RrsetError);
+
+ rrset1.setId(1);
+ BOOST_CHECK_NO_THROW(session.remove(rrset1));
+
+ rrset1.setZone(0);
+ rrset1.setId(1);
+ BOOST_CHECK_NO_THROW(session.remove(rrset1));
+}
+
+
+BOOST_FIXTURE_TEST_CASE(FindRrsets, DbMgrFixture)
+{
+ Zone zone("/");
+ Rrset rrset1(&zone);
+ rrset1.setLabel("/net/ksk-123");
+ rrset1.setType(name::Component("ID-CERT"));
+ rrset1.setVersion(name::Component::fromVersion(567));
+ rrset1.setTtl(time::seconds(4600));
+
+ static const std::string DATA1 = "SOME DATA";
+ rrset1.setData(dataBlock(ndn::tlv::Content, DATA1.data(), DATA1.size()));
+ session.insert(rrset1);
+
+ Rrset rrset2(&zone);
+ rrset2.setLabel("/net");
+ rrset2.setType(name::Component("NS"));
+ rrset2.setVersion(name::Component::fromVersion(232));
+ rrset2.setTtl(time::seconds(2100));
+ std::string data2 = "host1.net";
+ rrset2.setData(dataBlock(ndn::tlv::Content, data2.c_str(), data2.size()));
+ session.insert(rrset2);
+
+ std::vector<Rrset> vec = session.findRrsets(zone);
+ BOOST_CHECK_EQUAL(vec.size(), 2);
+
+ std::sort(vec.begin(),
+ vec.end(),
+ [] (const Rrset& n1, const Rrset& n2) {
+ return n1.getLabel().size() < n2.getLabel().size();
+ });
+ BOOST_CHECK_EQUAL(vec[0].getLabel(), "/net");
+ BOOST_CHECK_EQUAL(vec[1].getLabel(), "/net/ksk-123");
+}
+
+BOOST_AUTO_TEST_SUITE_END()
+
+} // namespace tests
+} // namespace ndns
+} // namespace ndn
diff --git a/tests/unit/database-test-data.cpp b/tests/unit/database-test-data.cpp
new file mode 100644
index 0000000..3db2335
--- /dev/null
+++ b/tests/unit/database-test-data.cpp
@@ -0,0 +1,180 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014, Regents of the University of California.
+ *
+ * This file is part of NDNS (Named Data Networking Domain Name Service).
+ * See AUTHORS.md for complete list of NDNS authors and contributors.
+ *
+ * NDNS is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * NDNS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * NDNS, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "database-test-data.hpp"
+#include "logger.hpp"
+
+#include <boost/filesystem.hpp>
+
+namespace ndn {
+namespace ndns {
+namespace tests {
+NDNS_LOG_INIT("TestFakeData")
+
+const boost::filesystem::path DbTestData::TEST_DATABASE = TEST_CONFIG_PATH "/" "test-ndns.db";
+const Name DbTestData::TEST_IDENTITY_NAME("/");
+const boost::filesystem::path DbTestData::TEST_CERT =
+ TEST_CONFIG_PATH "/" "anchors/root.cert";
+
+DbTestData::DbTestData()
+ : doesTestIdentityExist(false)
+ , m_session(TEST_DATABASE.string())
+{
+ NDNS_LOG_TRACE("start creating test data");
+ // m_session.clearAllData();
+
+ ndns::Validator::VALIDATOR_CONF_FILE = TEST_CONFIG_PATH "/" "validator.conf";
+
+ if (!m_keyChain.doesIdentityExist(TEST_IDENTITY_NAME)) {
+ m_keyChain.createIdentity(TEST_IDENTITY_NAME);
+ }
+ else {
+ doesTestIdentityExist = true;
+ }
+
+ m_keyName = m_keyChain.generateRsaKeyPair(TEST_IDENTITY_NAME, false);
+
+ shared_ptr<IdentityCertificate> scert = m_keyChain.selfSign(m_keyName);
+ m_keyChain.addCertificate(*scert);
+ m_certName = scert->getName();
+
+ ndn::io::save(*scert, TEST_CERT.string());
+ NDNS_LOG_TRACE("test key: " << m_keyName);
+ NDNS_LOG_TRACE("save test root cert " << m_certName << " to: " << TEST_CERT.string());
+
+ BOOST_CHECK_GT(m_certName.size(), 0);
+ NDNS_LOG_TRACE("test certName: " << m_certName);
+
+ Zone root("/");
+ Zone net("/net");
+ Zone ndnsim("/net/ndnsim");
+
+ m_session.insert(root);
+ BOOST_CHECK_GT(root.getId(), 0);
+ m_session.insert(net);
+ BOOST_CHECK_GT(net.getId(), 0);
+ m_session.insert(ndnsim);
+ BOOST_CHECK_GT(ndnsim.getId(), 0);
+
+ m_zones.push_back(root);
+ m_zones.push_back(net);
+ m_zones.push_back(ndnsim);
+
+ int certificateIndex = 0;
+ function<void(const Name&,Zone&,const name::Component&)> addQueryRrset =
+ [this, &certificateIndex] (const Name& label, Zone& zone,
+ const name::Component& type) {
+ const time::seconds ttl(3000 + 100 * certificateIndex);
+ const name::Component version = name::Component::fromVersion(100 + 1000 * certificateIndex);
+ name::Component qType(label::NDNS_ITERATIVE_QUERY);
+ NdnsType ndnsType = NDNS_RESP;
+ if (type == label::CERT_RR_TYPE) {
+ ndnsType = NDNS_RAW;
+ qType = label::NDNS_CERT_QUERY;
+ }
+ std::ostringstream os;
+ os << "a fake content: " << (++certificateIndex) << "th";
+
+ addRrset(zone, label, type, ttl, version, qType, ndnsType, os.str());
+ };
+ addQueryRrset("/dsk-1", root, label::CERT_RR_TYPE);
+ addQueryRrset("/net/ksk-2", root, label::CERT_RR_TYPE);
+ addQueryRrset("/dsk-3", net, label::CERT_RR_TYPE);
+ addQueryRrset("/ndnsim/ksk-4", net, label::CERT_RR_TYPE);
+ addQueryRrset("/dsk-5", ndnsim, label::CERT_RR_TYPE);
+
+ addQueryRrset("net", root, label::NS_RR_TYPE);
+ addQueryRrset("ndnsim", net, label::NS_RR_TYPE);
+ addQueryRrset("www", ndnsim, label::TXT_RR_TYPE);
+ addQueryRrset("doc/www", ndnsim, label::TXT_RR_TYPE);
+
+
+ addRrset(ndnsim, Name("doc"), label::NS_RR_TYPE , time::seconds(2000),
+ name::Component("1234"), label::NDNS_ITERATIVE_QUERY, NDNS_AUTH, std::string(""));
+
+ NDNS_LOG_INFO("insert testing data: OK");
+}
+
+
+
+void
+DbTestData::addRrset(Zone& zone, const Name& label, const name::Component& type,
+ const time::seconds& ttl, const name::Component& version,
+ const name::Component& qType, NdnsType ndnsType, const std::string& msg)
+{
+ Rrset rrset(&zone);
+ rrset.setLabel(label);
+ rrset.setType(type);
+ rrset.setTtl(ttl);
+ rrset.setVersion(version);
+
+ Response re;
+ re.setZone(zone.getName());
+ re.setQueryType(qType);
+ re.setRrLabel(label);
+ re.setRrType(type);
+ re.setVersion(version);
+ re.setNdnsType(ndnsType);
+ re.setFreshnessPeriod(ttl);
+
+ if (msg.size() > 0) {
+ if (type == label::CERT_RR_TYPE)
+ re.setAppContent(dataBlock(ndn::tlv::Content, msg.c_str(), msg.size()));
+ else
+ re.addRr(msg);
+ }
+ shared_ptr<Data> data = re.toData();
+ m_keyChain.sign(*data, m_certName); // now we ignore the certificate to sign the data
+ shared_ptr<IdentityCertificate> cert = m_keyChain.getCertificate(m_certName);
+ BOOST_CHECK_EQUAL(Validator::verifySignature(*data, cert->getPublicKeyInfo()), true);
+ rrset.setData(data->wireEncode());
+
+ m_session.insert(rrset);
+
+ m_rrsets.push_back(rrset);
+}
+
+DbTestData::~DbTestData()
+{
+ for (auto& zone : m_zones)
+ m_session.remove(zone);
+
+ for (auto& rrset : m_rrsets)
+ m_session.remove(rrset);
+
+ m_session.close();
+
+ boost::filesystem::remove(TEST_DATABASE);
+ boost::filesystem::remove(TEST_CERT);
+
+ if (doesTestIdentityExist) {
+ m_keyChain.deleteCertificate(m_certName);
+ m_keyChain.deleteKey(m_keyName);
+ NDNS_LOG_TRACE("delete key: " << m_keyName << " and certificate: " << m_certName);
+ }
+ else{
+ m_keyChain.deleteIdentity(TEST_IDENTITY_NAME);
+ }
+
+ NDNS_LOG_INFO("remove database: " << TEST_DATABASE);
+}
+
+} // namespace tests
+} // namespace ndns
+} // namespace ndn
diff --git a/tests/unit/database-test-data.hpp b/tests/unit/database-test-data.hpp
new file mode 100644
index 0000000..38b1d43
--- /dev/null
+++ b/tests/unit/database-test-data.hpp
@@ -0,0 +1,68 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014, Regents of the University of California.
+ *
+ * This file is part of NDNS (Named Data Networking Domain Name Service).
+ * See AUTHORS.md for complete list of NDNS authors and contributors.
+ *
+ * NDNS is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * NDNS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * NDNS, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef NDNS_TESTS_UNIT_DATABASE_TEST_DATA_HPP
+#define NDNS_TESTS_UNIT_DATABASE_TEST_DATA_HPP
+
+#include "daemon/db-mgr.hpp"
+#include "clients/response.hpp"
+#include "clients/query.hpp"
+#include "validator.hpp"
+
+#include "../boost-test.hpp"
+
+#include <ndn-cxx/security/key-chain.hpp>
+#include <boost/filesystem.hpp>
+
+namespace ndn {
+namespace ndns {
+namespace tests {
+
+class DbTestData
+{
+public:
+ static const boost::filesystem::path TEST_DATABASE;
+ static const Name TEST_IDENTITY_NAME;
+ static const boost::filesystem::path TEST_CERT;
+
+ DbTestData();
+
+ ~DbTestData();
+
+private:
+ void
+ addRrset(Zone& zone, const Name& label, const name::Component& type,
+ const time::seconds& ttl, const name::Component& version,
+ const name::Component& qType, NdnsType ndnsType, const std::string& msg);
+public:
+ Name m_certName;
+ Name m_keyName;
+ std::vector<Zone> m_zones;
+ std::vector<Rrset> m_rrsets;
+
+ bool doesTestIdentityExist;
+ DbMgr m_session;
+ KeyChain m_keyChain;
+};
+
+} // namespace tests
+} // namespace ndns
+} // namespace ndn
+
+#endif // NDNS_TESTS_UNIT_DATABASE_TEST_DATA_HPP
diff --git a/tests/unit/logger.cpp b/tests/unit/logger.cpp
index 100aa5b..c2491ad 100644
--- a/tests/unit/logger.cpp
+++ b/tests/unit/logger.cpp
@@ -19,6 +19,7 @@
#include "logger.hpp"
#include "../boost-test.hpp"
+#include "config.hpp"
#include <fstream>