Make LSA buildable when one node is ACTIVE

refs: #2802

Change-Id: If3f99895522e22103130f32bb6634bf9a5691fe7
diff --git a/src/adjacency-list.cpp b/src/adjacency-list.cpp
index 3e535ee..88f50bd 100644
--- a/src/adjacency-list.cpp
+++ b/src/adjacency-list.cpp
@@ -1,7 +1,8 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /**
- * Copyright (c) 2014  University of Memphis,
- *                     Regents of the University of California
+ * Copyright (c) 2014-2015,  The University of Memphis,
+ *                           Regents of the University of California,
+ *                           Arizona Board of Regents.
  *
  * This file is part of NLSR (Named-data Link State Routing).
  * See AUTHORS.md for complete list of NLSR authors and contributors.
@@ -16,19 +17,16 @@
  *
  * You should have received a copy of the GNU General Public License along with
  * NLSR, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
- *
- * \author A K M Mahmudul Hoque <ahoque1@memphis.edu>
- *
  **/
-#include <algorithm>
-#include <ndn-cxx/common.hpp>
 
 #include "adjacency-list.hpp"
+
 #include "adjacent.hpp"
 #include "common.hpp"
-#include "nlsr.hpp"
 #include "logger.hpp"
 
+#include <algorithm>
+
 namespace nlsr {
 
 INIT_LOGGER("AdjacencyList");
@@ -197,25 +195,26 @@
 }
 
 bool
-AdjacencyList::isAdjLsaBuildable(Nlsr& pnlsr)
+AdjacencyList::isAdjLsaBuildable(const uint32_t interestRetryNo) const
 {
-  uint32_t nbrCount = 0;
-  for (std::list<Adjacent>::iterator it = m_adjList.begin(); it != m_adjList.end() ; it++) {
+  uint32_t nTimedOutNeighbors = 0;
 
-    if (it->getStatus() == Adjacent::STATUS_ACTIVE) {
-      nbrCount++;
+  for (const Adjacent& adjacency : m_adjList) {
+
+    if (adjacency.getStatus() == Adjacent::STATUS_ACTIVE) {
+      return true;
     }
-    else {
-      if ((*it).getInterestTimedOutNo() >=
-          pnlsr.getConfParameter().getInterestRetryNumber()) {
-        nbrCount++;
-      }
+    else if (adjacency.getInterestTimedOutNo() >= interestRetryNo) {
+      nTimedOutNeighbors++;
     }
   }
-  if (nbrCount == m_adjList.size()) {
+
+  if (nTimedOutNeighbors == m_adjList.size()) {
     return true;
   }
-  return false;
+  else {
+    return false;
+  }
 }
 
 int32_t
diff --git a/src/adjacency-list.hpp b/src/adjacency-list.hpp
index 2325f49..259bf61 100644
--- a/src/adjacency-list.hpp
+++ b/src/adjacency-list.hpp
@@ -29,7 +29,6 @@
 #include "adjacent.hpp"
 
 namespace nlsr {
-class Nlsr;
 
 class AdjacencyList
 {
@@ -74,7 +73,7 @@
   addAdjacents(AdjacencyList& adl);
 
   bool
-  isAdjLsaBuildable(Nlsr& pnlsr);
+  isAdjLsaBuildable(const uint32_t interestRetryNo) const;
 
   int32_t
   getNumOfActiveNeighbor();
diff --git a/src/hello-protocol.hpp b/src/hello-protocol.hpp
index bc5267d..3fd4c03 100644
--- a/src/hello-protocol.hpp
+++ b/src/hello-protocol.hpp
@@ -22,7 +22,8 @@
 #ifndef NLSR_HELLO_PROTOCOL_HPP
 #define NLSR_HELLO_PROTOCOL_HPP
 
-#include <boost/cstdint.hpp>
+#include "test-access-control.hpp"
+
 #include <ndn-cxx/face.hpp>
 #include <ndn-cxx/management/nfd-control-parameters.hpp>
 #include <ndn-cxx/util/scheduler.hpp>
@@ -59,9 +60,11 @@
   void
   onContent(const ndn::Interest& interest, const ndn::Data& data);
 
+PUBLIC_WITH_TESTS_ELSE_PRIVATE:
   void
   onContentValidated(const ndn::shared_ptr<const ndn::Data>& data);
 
+private:
   void
   onContentValidationFailed(const ndn::shared_ptr<const ndn::Data>& data,
                             const std::string& msg);
diff --git a/src/lsa.hpp b/src/lsa.hpp
index c797815..e149a6e 100644
--- a/src/lsa.hpp
+++ b/src/lsa.hpp
@@ -32,6 +32,8 @@
 
 namespace nlsr {
 
+class Nlsr;
+
 class Lsa
 {
 public:
diff --git a/src/lsdb.cpp b/src/lsdb.cpp
index 5b1fda6..1486c2c 100644
--- a/src/lsdb.cpp
+++ b/src/lsdb.cpp
@@ -557,32 +557,37 @@
 void
 Lsdb::buildAdjLsa()
 {
-  _LOG_TRACE("buildAdjLsa called");
+  _LOG_TRACE("Lsdb::buildAdjLsa called");
 
   m_nlsr.setIsBuildAdjLsaSheduled(false);
-  if (m_nlsr.getAdjacencyList().isAdjLsaBuildable(m_nlsr)) {
+
+  if (m_nlsr.getAdjacencyList().isAdjLsaBuildable(m_nlsr.getConfParameter().getInterestRetryNumber())) {
+
     int adjBuildCount = m_nlsr.getAdjBuildCount();
+
+    // Is the adjacency LSA build still necessary, or has another build
+    // fulfilled this request?
     if (adjBuildCount > 0) {
       if (m_nlsr.getAdjacencyList().getNumOfActiveNeighbor() > 0) {
-        _LOG_DEBUG("Building and installing Adj LSA");
+        _LOG_DEBUG("Building and installing own Adj LSA");
         buildAndInstallOwnAdjLsa();
       }
       else {
+        _LOG_DEBUG("Removing own Adj LSA; no ACTIVE neighbors")
         ndn::Name key = m_nlsr.getConfParameter().getRouterPrefix();
         key.append(AdjLsa::TYPE_STRING);
+
         removeAdjLsa(key);
+
         m_nlsr.getRoutingTable().scheduleRoutingTableCalculation(m_nlsr);
       }
+
+      // Since more adjacency LSA builds may have been scheduled while this build
+      // was in progress, decrease the build count by the number of scheduled
+      // builds at the beginning of this build.
       m_nlsr.setAdjBuildCount(m_nlsr.getAdjBuildCount() - adjBuildCount);
     }
   }
-  else {
-    m_nlsr.setIsBuildAdjLsaSheduled(true);
-    int schedulingTime = m_nlsr.getConfParameter().getInterestRetryNumber() *
-                         m_nlsr.getConfParameter().getInterestResendTime();
-    m_scheduler.scheduleEvent(ndn::time::seconds(schedulingTime),
-                              ndn::bind(&Lsdb::buildAdjLsa, this));
-  }
 }
 
 
diff --git a/src/nlsr.cpp b/src/nlsr.cpp
index 6753a13..2f098fe 100644
--- a/src/nlsr.cpp
+++ b/src/nlsr.cpp
@@ -57,10 +57,10 @@
   , m_fib(m_nlsrFace, scheduler, m_adjacencyList, m_confParam, m_keyChain)
   , m_namePrefixTable(*this)
   , m_syncLogicHandler(m_nlsrFace, m_nlsrLsdb, m_confParam, m_sequencingManager)
-  , m_helloProtocol(*this, scheduler)
   , m_lsdbDatasetHandler(m_nlsrLsdb,
                          m_nlsrFace,
                          m_keyChain)
+  , m_helloProtocol(*this, scheduler)
   , m_certificateCache(new ndn::CertificateCacheTtl(ioService))
   , m_validator(m_nlsrFace, DEFAULT_BROADCAST_PREFIX, m_certificateCache, m_certStore)
   , m_prefixUpdateProcessor(m_nlsrFace,
diff --git a/src/nlsr.hpp b/src/nlsr.hpp
index 4e9cc23..f53ba4a 100644
--- a/src/nlsr.hpp
+++ b/src/nlsr.hpp
@@ -372,9 +372,11 @@
   Fib m_fib;
   NamePrefixTable m_namePrefixTable;
   SyncLogicHandler m_syncLogicHandler;
-  HelloProtocol m_helloProtocol;
   LsdbDatasetInterestHandler m_lsdbDatasetHandler;
 
+PUBLIC_WITH_TESTS_ELSE_PRIVATE:
+  HelloProtocol m_helloProtocol;
+
 private:
   ndn::shared_ptr<ndn::CertificateCacheTtl> m_certificateCache;
   security::CertificateStore m_certStore;
diff --git a/tests/test-adjacency-list.cpp b/tests/test-adjacency-list.cpp
index 40411f8..271b542 100644
--- a/tests/test-adjacency-list.cpp
+++ b/tests/test-adjacency-list.cpp
@@ -1,7 +1,8 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /**
- * Copyright (c) 2014  University of Memphis,
- *                     Regents of the University of California
+ * Copyright (c) 2014-2015,  The University of Memphis,
+ *                           Regents of the University of California,
+ *                           Arizona Board of Regents.
  *
  * This file is part of NLSR (Named-data Link State Routing).
  * See AUTHORS.md for complete list of NLSR authors and contributors.
@@ -16,23 +17,23 @@
  *
  * You should have received a copy of the GNU General Public License along with
  * NLSR, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
- *
- * \author Ashlesh Gawande <agawande@memphis.edu>
- *
  **/
+
 #include "adjacency-list.hpp"
+
 #include "adjacent.hpp"
+#include "conf-parameter.hpp"
+
 #include <boost/test/unit_test.hpp>
 
 namespace nlsr {
-
 namespace test {
 
 using namespace std;
 
-BOOST_AUTO_TEST_SUITE(TestAdjacenctList)
+BOOST_AUTO_TEST_SUITE(TestAdjacencyList)
 
-BOOST_AUTO_TEST_CASE(AdjacenctListBasic)
+BOOST_AUTO_TEST_CASE(Basic)
 {
   const string ADJ_NAME_1 = "testname";
   const string ADJ_NAME_2 = "testname2";
@@ -63,7 +64,65 @@
   BOOST_CHECK_EQUAL(adjacentList1.getStatusOfNeighbor(n1), Adjacent::STATUS_ACTIVE);
 }
 
+BOOST_AUTO_TEST_CASE(AdjLsaIsBuildableWithOneNodeActive)
+{
+  Adjacent adjacencyA("/router/A");
+  Adjacent adjacencyB("/router/B");
+
+  adjacencyA.setStatus(Adjacent::STATUS_ACTIVE);
+  adjacencyB.setStatus(Adjacent::STATUS_INACTIVE);
+
+  AdjacencyList adjacencies;
+  adjacencies.insert(adjacencyA);
+  adjacencies.insert(adjacencyB);
+
+  ConfParameter conf;
+  BOOST_CHECK(adjacencies.isAdjLsaBuildable(conf.getInterestRetryNumber()));
+}
+
+BOOST_AUTO_TEST_CASE(AdjLsaIsBuildableWithAllNodesTimedOut)
+{
+  Adjacent adjacencyA("/router/A");
+  Adjacent adjacencyB("/router/B");
+
+  adjacencyA.setStatus(Adjacent::STATUS_INACTIVE);
+  adjacencyB.setStatus(Adjacent::STATUS_INACTIVE);
+
+  adjacencyA.setInterestTimedOutNo(HELLO_RETRIES_DEFAULT);
+  adjacencyB.setInterestTimedOutNo(HELLO_RETRIES_DEFAULT);
+
+  AdjacencyList adjacencies;
+  adjacencies.insert(adjacencyA);
+  adjacencies.insert(adjacencyB);
+
+  ConfParameter conf;
+  conf.setInterestRetryNumber(HELLO_RETRIES_DEFAULT);
+
+  BOOST_CHECK(adjacencies.isAdjLsaBuildable(conf.getInterestRetryNumber()));
+}
+
+BOOST_AUTO_TEST_CASE(AdjLsaIsNotBuildable)
+{
+  Adjacent adjacencyA("/router/A");
+  Adjacent adjacencyB("/router/B");
+
+  adjacencyA.setStatus(Adjacent::STATUS_INACTIVE);
+  adjacencyB.setStatus(Adjacent::STATUS_INACTIVE);
+
+  adjacencyA.setInterestTimedOutNo(HELLO_RETRIES_DEFAULT);
+  adjacencyB.setInterestTimedOutNo(0);
+
+  AdjacencyList adjacencies;
+  adjacencies.insert(adjacencyA);
+  adjacencies.insert(adjacencyB);
+
+  ConfParameter conf;
+  conf.setInterestRetryNumber(HELLO_RETRIES_DEFAULT);
+
+  BOOST_CHECK(!adjacencies.isAdjLsaBuildable(conf.getInterestRetryNumber()));
+}
+
 BOOST_AUTO_TEST_SUITE_END()
 
-} //namespace tests
-} //namespace nlsr
+} // namespace tests
+} // namespace nlsr
diff --git a/tests/test-nlsr.cpp b/tests/test-nlsr.cpp
index 5ad6efd..a469d5f 100644
--- a/tests/test-nlsr.cpp
+++ b/tests/test-nlsr.cpp
@@ -32,16 +32,40 @@
 
 using ndn::shared_ptr;
 
-BOOST_FIXTURE_TEST_SUITE(TestNlsr, BaseFixture)
+class NlsrFixture : public UnitTestTimeFixture
+{
+public:
+  NlsrFixture()
+    : face(make_shared<ndn::util::DummyClientFace>())
+    , nlsr(g_ioService, g_scheduler, ndn::ref(*face))
+    , lsdb(nlsr.getLsdb())
+    , neighbors(nlsr.getAdjacencyList())
+  {
+  }
+
+  void
+  receiveHelloData(const ndn::Name& sender, const ndn::Name& receiver)
+  {
+    ndn::Name dataName(sender);
+    dataName.append("NLSR").append("INFO").append(receiver.wireEncode()).appendVersion();
+
+    shared_ptr<ndn::Data> data = make_shared<ndn::Data>(dataName);
+
+    nlsr.m_helloProtocol.onContentValidated(data);
+  }
+
+public:
+  shared_ptr<ndn::util::DummyClientFace> face;
+  Nlsr nlsr;
+  Lsdb& lsdb;
+  AdjacencyList& neighbors;
+};
+
+BOOST_FIXTURE_TEST_SUITE(TestNlsr, NlsrFixture)
 
 BOOST_AUTO_TEST_CASE(HyperbolicOn_ZeroCostNeighbors)
 {
-  shared_ptr<ndn::util::DummyClientFace> face = make_shared<ndn::util::DummyClientFace>();
-  Nlsr nlsr(g_ioService, g_scheduler, ndn::ref(*face));
-
   // Simulate loading configuration file
-  AdjacencyList& neighbors = nlsr.getAdjacencyList();
-
   Adjacent neighborA("/ndn/neighborA", "uri://faceA", 25, Adjacent::STATUS_INACTIVE, 0, 0);
   neighbors.insert(neighborA);
 
@@ -63,12 +87,7 @@
 
 BOOST_AUTO_TEST_CASE(HyperbolicOff_LinkStateCost)
 {
-  shared_ptr<ndn::util::DummyClientFace> face = make_shared<ndn::util::DummyClientFace>();
-  Nlsr nlsr(g_ioService, g_scheduler, ndn::ref(*face));
-
   // Simulate loading configuration file
-  AdjacencyList& neighbors = nlsr.getAdjacencyList();
-
   Adjacent neighborA("/ndn/neighborA", "uri://faceA", 25, Adjacent::STATUS_INACTIVE, 0, 0);
   neighbors.insert(neighborA);
 
@@ -88,9 +107,6 @@
 
 BOOST_AUTO_TEST_CASE(SetEventIntervals)
 {
-  shared_ptr<ndn::util::DummyClientFace> face = make_shared<ndn::util::DummyClientFace>();
-  Nlsr nlsr(g_ioService, g_scheduler, ndn::ref(*face));
-
   // Simulate loading configuration file
   ConfParameter& conf = nlsr.getConfParameter();
   conf.setAdjLsaBuildInterval(3);
@@ -123,7 +139,6 @@
 
   // Add active neighbors
   AdjacencyList& neighbors = nlsr.getAdjacencyList();
-
   uint64_t destroyFaceId = 128;
 
   // Create a neighbor whose Face will be destroyed
@@ -323,11 +338,8 @@
   BOOST_CHECK_EQUAL(parameters.getName(), nameToAdvertise);
 }
 
-BOOST_FIXTURE_TEST_CASE(GetCertificate, UnitTestTimeFixture)
+BOOST_AUTO_TEST_CASE(GetCertificate)
 {
-  shared_ptr<ndn::util::DummyClientFace> face = make_shared<ndn::util::DummyClientFace>(g_ioService);
-  Nlsr nlsr(g_ioService, g_scheduler, ndn::ref(*face));
-
   // Create certificate
   ndn::Name identity("/TestNLSR/identity");
   identity.appendVersion();
@@ -355,11 +367,8 @@
   BOOST_CHECK(nlsr.getCertificate(certKey) != nullptr);
 }
 
-BOOST_FIXTURE_TEST_CASE(SetRouterCommandPrefix, UnitTestTimeFixture)
+BOOST_AUTO_TEST_CASE(SetRouterCommandPrefix)
 {
-  shared_ptr<ndn::util::DummyClientFace> face = make_shared<ndn::util::DummyClientFace>(g_ioService);
-  Nlsr nlsr(g_ioService, g_scheduler, ndn::ref(*face));
-
   // Simulate loading configuration file
   ConfParameter& conf = nlsr.getConfParameter();
   conf.setNetwork("/ndn");
@@ -372,6 +381,70 @@
                     ndn::Name("/ndn/site/%C1.router/this-router/lsdb"));
 }
 
+BOOST_AUTO_TEST_CASE(BuildAdjLsaAfterHelloResponse)
+{
+  // Configure NLSR
+  ConfParameter& conf = nlsr.getConfParameter();
+  conf.setNetwork("/ndn");
+  conf.setSiteName("/site");
+
+  ndn::Name routerName("/%C1.Router/this-router");
+  conf.setRouterName(routerName);
+
+  conf.setAdjLsaBuildInterval(1);
+
+  // Add neighbors
+  // Router A
+  ndn::Name neighborAName("/ndn/site/%C1.router/routerA");
+  Adjacent neighborA(neighborAName, "uri://faceA", 0, Adjacent::STATUS_INACTIVE, 0, 0);
+  neighbors.insert(neighborA);
+
+  // Router B
+  ndn::Name neighborBName("/ndn/site/%C1.router/routerB");
+  Adjacent neighborB(neighborBName, "uri://faceA", 0, Adjacent::STATUS_INACTIVE, 0, 0);
+  neighbors.insert(neighborB);
+
+  nlsr.initialize();
+  this->advanceClocks(ndn::time::milliseconds(1));
+
+  // Receive HELLO response from Router A
+  receiveHelloData(neighborAName, conf.getRouterPrefix());
+  this->advanceClocks(ndn::time::seconds(1));
+
+  ndn::Name lsaKey = ndn::Name(conf.getRouterPrefix()).append(AdjLsa::TYPE_STRING);
+
+  // Adjacency LSA should be built even though other router is INACTIVE
+  AdjLsa* lsa = lsdb.findAdjLsa(lsaKey);
+  BOOST_REQUIRE(lsa != nullptr);
+  BOOST_CHECK_EQUAL(lsa->getAdl().getSize(), 1);
+
+  // Receive HELLO response from Router B
+  receiveHelloData(neighborBName, conf.getRouterPrefix());
+
+  // Both routers become INACTIVE and HELLO Interests have timed out
+  for (Adjacent& adjacency : neighbors.getAdjList()) {
+    adjacency.setStatus(Adjacent::STATUS_INACTIVE);
+    adjacency.setInterestTimedOutNo(HELLO_RETRIES_DEFAULT);
+  }
+
+  this->advanceClocks(ndn::time::seconds(1));
+
+  // Adjacency LSA should have been removed since this router's adjacencies are INACTIVE
+  // and have timed out
+  lsa = lsdb.findAdjLsa(lsaKey);
+  BOOST_CHECK(lsa == nullptr);
+
+  // Receive HELLO response from Router A and B
+  receiveHelloData(neighborAName, conf.getRouterPrefix());
+  receiveHelloData(neighborBName, conf.getRouterPrefix());
+  this->advanceClocks(ndn::time::seconds(1));
+
+  // Adjacency LSA should be built
+  lsa = lsdb.findAdjLsa(lsaKey);
+  BOOST_REQUIRE(lsa != nullptr);
+  BOOST_CHECK_EQUAL(lsa->getAdl().getSize(), 2);
+}
+
 BOOST_AUTO_TEST_SUITE_END()
 
 } //namespace test