route: Correct bidirectional links with differing costs

refs: #2801

Change-Id: Iacabcb5484f4ccab6c74700dd8ebcf7b1ad99917
diff --git a/src/route/routing-table-calculator.cpp b/src/route/routing-table-calculator.cpp
index 24707b0..a2c93e3 100644
--- a/src/route/routing-table-calculator.cpp
+++ b/src/route/routing-table-calculator.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,10 +17,8 @@
  *
  * 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 <iostream>
 #include <cmath>
 #include "lsdb.hpp"
@@ -78,6 +77,37 @@
       }
     }
   }
+
+  // Links that do not have the same cost for both directions should have their
+  // costs corrected:
+  //
+  //   If the cost of one side of the link is 0, both sides of the link should have their cost
+  //   corrected to 0.
+  //
+  //   Otherwise, both sides of the link should use the larger of the two costs.
+  //
+  for (size_t row = 0; row < m_nRouters; ++row) {
+    for (size_t col = 0; col < m_nRouters; ++col) {
+      double toCost = adjMatrix[row][col];
+      double fromCost = adjMatrix[col][row];
+
+      if (fromCost != toCost) {
+        double correctedCost = 0.0;
+
+        if (toCost != 0 && fromCost != 0) {
+          // If both sides of the link are up, use the larger cost
+          correctedCost = std::max(toCost, fromCost);
+        }
+
+        _LOG_WARN("Cost between [" << row << "][" << col << "] and [" << col << "][" << row <<
+                  "] are not the same (" << toCost << " != " << fromCost << "). " <<
+                  "Correcting to cost: " << correctedCost);
+
+        adjMatrix[row][col] = correctedCost;
+        adjMatrix[col][row] = correctedCost;
+      }
+    }
+  }
 }
 
 void
diff --git a/tests/test-link-state-calculator.cpp b/tests/test-link-state-calculator.cpp
new file mode 100644
index 0000000..df61cdb
--- /dev/null
+++ b/tests/test-link-state-calculator.cpp
@@ -0,0 +1,268 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * 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.
+ *
+ * NLSR 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.
+ *
+ * NLSR 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
+ * NLSR, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+#include "route/routing-table-calculator.hpp"
+
+#include "adjacency-list.hpp"
+#include "lsa.hpp"
+#include "lsdb.hpp"
+#include "nlsr.hpp"
+#include "test-common.hpp"
+#include "route/map.hpp"
+#include "route/routing-table.hpp"
+
+#include <ndn-cxx/util/dummy-client-face.hpp>
+
+namespace nlsr {
+namespace test {
+
+static const ndn::time::system_clock::TimePoint MAX_TIME =
+  ndn::time::system_clock::TimePoint::max();
+
+class LinkStateCalculatorFixture : public BaseFixture
+{
+public:
+  LinkStateCalculatorFixture()
+    : face(ndn::util::makeDummyClientFace(g_ioService))
+    , nlsr(g_ioService, g_scheduler, ndn::ref(*face))
+    , routingTable(nlsr.getRoutingTable())
+    , lsdb(nlsr.getLsdb())
+  {
+    setUpTopology();
+  }
+
+  // Triangle topology with routers A, B, C connected
+  void setUpTopology()
+  {
+    INIT_LOGGERS("/tmp", "TRACE");
+
+    ConfParameter& conf = nlsr.getConfParameter();
+    conf.setNetwork("/ndn");
+    conf.setSiteName("/router");
+    conf.setRouterName("/a");
+    conf.buildRouterPrefix();
+
+    Adjacent a(ROUTER_A_NAME, ROUTER_A_FACE, 0, Adjacent::STATUS_ACTIVE, 0, 0);
+    Adjacent b(ROUTER_B_NAME, ROUTER_B_FACE, 0, Adjacent::STATUS_ACTIVE, 0, 0);
+    Adjacent c(ROUTER_C_NAME, ROUTER_C_FACE, 0, Adjacent::STATUS_ACTIVE, 0, 0);
+
+    // Router A
+    b.setLinkCost(LINK_AB_COST);
+    c.setLinkCost(LINK_AC_COST);
+
+    AdjacencyList& adjacencyListA = nlsr.getAdjacencyList();
+    adjacencyListA.insert(b);
+    adjacencyListA.insert(c);
+
+    AdjLsa adjA(a.getName(), AdjLsa::TYPE_STRING, 1, MAX_TIME, 2, adjacencyListA);
+    lsdb.installAdjLsa(adjA);
+
+    // Router B
+    a.setLinkCost(LINK_AB_COST);
+    c.setLinkCost(LINK_BC_COST);
+
+    AdjacencyList adjacencyListB;
+    adjacencyListB.insert(a);
+    adjacencyListB.insert(c);
+
+    AdjLsa adjB(b.getName(), AdjLsa::TYPE_STRING, 1, MAX_TIME, 2, adjacencyListB);
+    lsdb.installAdjLsa(adjB);
+
+    // Router C
+    a.setLinkCost(LINK_AC_COST);
+    b.setLinkCost(LINK_BC_COST);
+
+    AdjacencyList adjacencyListC;
+    adjacencyListC.insert(a);
+    adjacencyListC.insert(b);
+
+    AdjLsa adjC(c.getName(), AdjLsa::TYPE_STRING, 1, MAX_TIME, 2, adjacencyListC);
+    lsdb.installAdjLsa(adjC);
+
+    map.createFromAdjLsdb(nlsr);
+  }
+
+public:
+  shared_ptr<ndn::util::DummyClientFace> face;
+  Nlsr nlsr;
+  Map map;
+
+  RoutingTable& routingTable;
+  Lsdb& lsdb;
+
+  static const ndn::Name ROUTER_A_NAME;
+  static const ndn::Name ROUTER_B_NAME;
+  static const ndn::Name ROUTER_C_NAME;
+
+  static const std::string ROUTER_A_FACE;
+  static const std::string ROUTER_B_FACE;
+  static const std::string ROUTER_C_FACE;
+
+  static const double LINK_AB_COST;
+  static const double LINK_AC_COST;
+  static const double LINK_BC_COST;
+};
+
+const ndn::Name LinkStateCalculatorFixture::ROUTER_A_NAME = "/ndn/router/a";
+const ndn::Name LinkStateCalculatorFixture::ROUTER_B_NAME = "/ndn/router/b";
+const ndn::Name LinkStateCalculatorFixture::ROUTER_C_NAME = "/ndn/router/c";
+
+const std::string LinkStateCalculatorFixture::ROUTER_A_FACE = "face-a";
+const std::string LinkStateCalculatorFixture::ROUTER_B_FACE = "face-b";
+const std::string LinkStateCalculatorFixture::ROUTER_C_FACE = "face-c";
+
+const double LinkStateCalculatorFixture::LINK_AB_COST = 5;
+const double LinkStateCalculatorFixture::LINK_AC_COST = 10;
+const double LinkStateCalculatorFixture::LINK_BC_COST = 17;
+
+BOOST_FIXTURE_TEST_SUITE(TestLinkStateRoutingCalculator, LinkStateCalculatorFixture)
+
+BOOST_AUTO_TEST_CASE(Basic)
+{
+  LinkStateRoutingTableCalculator calculator(map.getMapSize());
+  calculator.calculatePath(map, routingTable, nlsr);
+
+  RoutingTableEntry* entryB = routingTable.findRoutingTableEntry(ROUTER_B_NAME);
+  BOOST_REQUIRE(entryB != nullptr);
+
+  // Router A should be able to get to B through B and to B through C
+  NexthopList& bHopList = entryB->getNexthopList();
+  BOOST_REQUIRE_EQUAL(bHopList.getNextHops().size(), 2);
+
+  for (const NextHop& hop : bHopList) {
+    std::string faceUri = hop.getConnectingFaceUri();
+    uint64_t cost = hop.getRouteCostAsAdjustedInteger();
+
+    BOOST_CHECK((faceUri == ROUTER_B_FACE && cost == LINK_AB_COST) ||
+                (faceUri == ROUTER_C_FACE && cost == LINK_AC_COST + LINK_BC_COST));
+
+  }
+
+  RoutingTableEntry* entryC = routingTable.findRoutingTableEntry(ROUTER_C_NAME);
+  BOOST_REQUIRE(entryC != nullptr);
+
+  // Router A should be able to get to C through C and to C through B
+  NexthopList& cHopList = entryC->getNexthopList();
+  BOOST_REQUIRE_EQUAL(cHopList.getNextHops().size(), 2);
+
+  for (const NextHop& hop : cHopList) {
+    std::string faceUri = hop.getConnectingFaceUri();
+    uint64_t cost = hop.getRouteCostAsAdjustedInteger();
+
+    BOOST_CHECK((faceUri == ROUTER_C_FACE && cost == LINK_AC_COST) ||
+                (faceUri == ROUTER_B_FACE && cost == LINK_AB_COST + LINK_BC_COST));
+  }
+}
+
+BOOST_AUTO_TEST_CASE(Asymmetric)
+{
+  // Asymmetric link cost between B and C
+  ndn::Name key = ndn::Name(ROUTER_B_NAME).append(AdjLsa::TYPE_STRING);
+  AdjLsa* lsa = nlsr.getLsdb().findAdjLsa(key);
+  BOOST_REQUIRE(lsa != nullptr);
+
+  Adjacent* c = lsa->getAdl().findAdjacent(ROUTER_C_NAME);
+  BOOST_REQUIRE(c != nullptr);
+
+  double higherLinkCost = LINK_BC_COST + 1;
+  c->setLinkCost(higherLinkCost);
+
+  // Calculation should consider the link between B and C as having cost = higherLinkCost
+  LinkStateRoutingTableCalculator calculator(map.getMapSize());
+  calculator.calculatePath(map, routingTable, nlsr);
+
+  RoutingTableEntry* entryB = routingTable.findRoutingTableEntry(ROUTER_B_NAME);
+  BOOST_REQUIRE(entryB != nullptr);
+
+  // Router A should be able to get to B through B and to B through C
+  NexthopList& bHopList = entryB->getNexthopList();
+  BOOST_REQUIRE_EQUAL(bHopList.getNextHops().size(), 2);
+
+  for (const NextHop& hop : bHopList) {
+    std::string faceUri = hop.getConnectingFaceUri();
+    uint64_t cost = hop.getRouteCostAsAdjustedInteger();
+
+    BOOST_CHECK((faceUri == ROUTER_B_FACE && cost == LINK_AB_COST) ||
+                (faceUri == ROUTER_C_FACE && cost == LINK_AC_COST + higherLinkCost));
+
+  }
+
+  RoutingTableEntry* entryC = routingTable.findRoutingTableEntry(ROUTER_C_NAME);
+  BOOST_REQUIRE(entryC != nullptr);
+
+  // Router A should be able to get to C through C and to C through B
+  NexthopList& cHopList = entryC->getNexthopList();
+  BOOST_REQUIRE_EQUAL(cHopList.getNextHops().size(), 2);
+
+  for (const NextHop& hop : cHopList) {
+    std::string faceUri = hop.getConnectingFaceUri();
+    uint64_t cost = hop.getRouteCostAsAdjustedInteger();
+
+    BOOST_CHECK((faceUri == ROUTER_C_FACE && cost == LINK_AC_COST) ||
+                (faceUri == ROUTER_B_FACE && cost == LINK_AB_COST + higherLinkCost));
+  }
+}
+
+BOOST_AUTO_TEST_CASE(AsymmetricZeroCost)
+{
+  // Asymmetric link cost between B and C
+  ndn::Name key = ndn::Name(ROUTER_B_NAME).append(AdjLsa::TYPE_STRING);
+  AdjLsa* lsa = nlsr.getLsdb().findAdjLsa(key);
+  BOOST_REQUIRE(lsa != nullptr);
+
+  Adjacent* c = lsa->getAdl().findAdjacent(ROUTER_C_NAME);
+  BOOST_REQUIRE(c != nullptr);
+
+  c->setLinkCost(0);
+
+  // Calculation should consider the link between B and C as down
+  LinkStateRoutingTableCalculator calculator(map.getMapSize());
+  calculator.calculatePath(map, routingTable, nlsr);
+
+  // Router A should be able to get to B through B but not through C
+  RoutingTableEntry* entryB = routingTable.findRoutingTableEntry(ROUTER_B_NAME);
+  BOOST_REQUIRE(entryB != nullptr);
+
+  NexthopList& bHopList = entryB->getNexthopList();
+  BOOST_REQUIRE_EQUAL(bHopList.getNextHops().size(), 1);
+
+  NextHop& nextHopForB = bHopList.getNextHops().front();
+
+  BOOST_CHECK(nextHopForB.getConnectingFaceUri() == ROUTER_B_FACE &&
+              nextHopForB.getRouteCostAsAdjustedInteger() == LINK_AB_COST);
+
+  // Router A should be able to get to C through C but not through B
+  RoutingTableEntry* entryC = routingTable.findRoutingTableEntry(ROUTER_C_NAME);
+  BOOST_REQUIRE(entryC != nullptr);
+
+  NexthopList& cHopList = entryC->getNexthopList();
+  BOOST_REQUIRE_EQUAL(cHopList.getNextHops().size(), 1);
+
+  NextHop& nextHopForC = cHopList.getNextHops().front();
+
+  BOOST_CHECK(nextHopForC.getConnectingFaceUri() == ROUTER_C_FACE &&
+              nextHopForC.getRouteCostAsAdjustedInteger() == LINK_AC_COST);
+}
+
+BOOST_AUTO_TEST_SUITE_END()
+
+} //namespace test
+} //namespace nlsr
diff --git a/tests/test-nlsr.cpp b/tests/test-nlsr.cpp
index ee9b7e7..6f1af7d 100644
--- a/tests/test-nlsr.cpp
+++ b/tests/test-nlsr.cpp
@@ -113,6 +113,7 @@
 {
   shared_ptr<ndn::util::DummyClientFace> face = ndn::util::makeDummyClientFace(g_ioService);
   Nlsr nlsr(g_ioService, g_scheduler, ndn::ref(*face));
+  Lsdb& lsdb = nlsr.getLsdb();
 
   // Simulate loading configuration file
   ConfParameter& conf = nlsr.getConfParameter();
@@ -133,20 +134,46 @@
   neighbors.insert(failNeighbor);
 
   // Create an additional neighbor so an adjacency LSA can be built after the face is destroyed
-  Adjacent otherNeighbor("/ndn/neighborB", "uri://faceB", 25, Adjacent::STATUS_ACTIVE, 0, 256);
+  Adjacent otherNeighbor("/ndn/neighborB", "uri://faceB", 10, Adjacent::STATUS_ACTIVE, 0, 256);
   neighbors.insert(otherNeighbor);
 
   nlsr.initialize();
 
   // Simulate successful HELLO responses
-  nlsr.getLsdb().scheduleAdjLsaBuild();
+  lsdb.scheduleAdjLsaBuild();
+
+  // Set up adjacency LSAs
+  // This router
+  Adjacent thisRouter(conf.getRouterPrefix(), "uri://faceB", 10, Adjacent::STATUS_ACTIVE, 0, 256);
+
+  AdjLsa ownAdjLsa(conf.getRouterPrefix(), AdjLsa::TYPE_STRING, 10, ndn::time::system_clock::now(),
+                   1, neighbors);
+  lsdb.installAdjLsa(ownAdjLsa);
+
+  // Router that will fail
+  AdjacencyList failAdjacencies;
+  failAdjacencies.insert(thisRouter);
+
+  AdjLsa failAdjLsa("/ndn/neighborA", AdjLsa::TYPE_STRING, 10,
+                     ndn::time::system_clock::now() + ndn::time::seconds(3600), 1, failAdjacencies);
+
+  lsdb.installAdjLsa(failAdjLsa);
+
+  // Other router
+  AdjacencyList otherAdjacencies;
+  otherAdjacencies.insert(thisRouter);
+
+  AdjLsa otherAdjLsa("/ndn/neighborB", AdjLsa::TYPE_STRING, 10,
+                     ndn::time::system_clock::now() + ndn::time::seconds(3600), 1, otherAdjacencies);
+
+  lsdb.installAdjLsa(otherAdjLsa);
 
   // Run the scheduler to build an adjacency LSA
   this->advanceClocks(ndn::time::milliseconds(1));
 
   // Make sure an adjacency LSA was built
   ndn::Name key = ndn::Name(nlsr.getConfParameter().getRouterPrefix()).append(AdjLsa::TYPE_STRING);
-  AdjLsa* lsa = nlsr.getLsdb().findAdjLsa(key);
+  AdjLsa* lsa = lsdb.findAdjLsa(key);
   BOOST_REQUIRE(lsa != nullptr);
 
   uint32_t lastAdjLsaSeqNo = nlsr.getSequencingManager().getAdjLsaSeq();
@@ -232,6 +259,23 @@
   // Simulate successful HELLO responses from neighbor B
   lsdb.scheduleAdjLsaBuild();
 
+  // Set up adjacency LSAs
+  // This router
+  Adjacent thisRouter(conf.getRouterPrefix(), "uri://faceB", 25, Adjacent::STATUS_ACTIVE, 0, 256);
+
+  AdjLsa ownAdjLsa(conf.getRouterPrefix(), AdjLsa::TYPE_STRING, 10, ndn::time::system_clock::now(),
+                   1, neighbors);
+  lsdb.installAdjLsa(ownAdjLsa);
+
+  // Other ACTIVE router
+  AdjacencyList otherAdjacencies;
+  otherAdjacencies.insert(thisRouter);
+
+  AdjLsa otherAdjLsa("/ndn/neighborB", AdjLsa::TYPE_STRING, 10,
+                     ndn::time::system_clock::now() + ndn::time::seconds(3600), 1, otherAdjacencies);
+
+  lsdb.installAdjLsa(otherAdjLsa);
+
   // Run the scheduler to build an adjacency LSA
   this->advanceClocks(ndn::time::milliseconds(1));