Fix for hosttracker. Ignore ARP messages from internal nodes.
[controller.git] / opendaylight / hosttracker / implementation / src / main / java / org / opendaylight / controller / hosttracker / internal / HostTracker.java
index f600e6b2acc3afbe456b616ae97aadecfd7f056e..367df5ebb05e87e7b93737f9a9db03bd43075e9f 100644 (file)
@@ -29,8 +29,11 @@ import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
 
 import org.apache.felix.dm.Component;
+import org.eclipse.osgi.framework.console.CommandInterpreter;
+import org.eclipse.osgi.framework.console.CommandProvider;
 import org.opendaylight.controller.clustering.services.CacheConfigException;
 import org.opendaylight.controller.clustering.services.CacheExistException;
+import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
 import org.opendaylight.controller.clustering.services.IClusterServices;
 import org.opendaylight.controller.hosttracker.IfHostListener;
@@ -62,6 +65,8 @@ import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
 import org.opendaylight.controller.switchmanager.Subnet;
 import org.opendaylight.controller.topologymanager.ITopologyManager;
 import org.opendaylight.controller.topologymanager.ITopologyManagerAware;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.FrameworkUtil;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -79,7 +84,9 @@ import org.slf4j.LoggerFactory;
  */
 
 public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAware, IInventoryListener,
-        ITopologyManagerAware {
+        ITopologyManagerAware, ICacheUpdateAware<InetAddress, HostNodeConnector>, CommandProvider {
+    static final String ACTIVE_HOST_CACHE = "hosttracker.ActiveHosts";
+    static final String INACTIVE_HOST_CACHE = "hosttracker.InactiveHosts";
     private static final Logger logger = LoggerFactory.getLogger(HostTracker.class);
     private IHostFinder hostFinder;
     private ConcurrentMap<InetAddress, HostNodeConnector> hostsDB;
@@ -95,7 +102,7 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
     private IClusterContainerServices clusterContainerService = null;
     private ISwitchManager switchManager = null;
     private Timer timer;
-    private Timer arp_refresh_timer;
+    private Timer arpRefreshTimer;
     private String containerName = null;
     private ExecutorService executor;
     private static class ARPPending {
@@ -127,10 +134,9 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
             hostTrackerCallable = callable;
         }
     }
-
     // This list contains the hosts for which ARP requests are being sent
     // periodically
-    private final List<ARPPending> ARPPendingList = new ArrayList<HostTracker.ARPPending>();
+    ConcurrentMap<InetAddress, ARPPending> ARPPendingList;
     /*
      * This list below contains the hosts which were initially in ARPPendingList
      * above, but ARP response didn't come from there hosts after multiple
@@ -147,12 +153,13 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
      *
      * We can't recover from condition 3 above
      */
-    private final ArrayList<ARPPending> failedARPReqList = new ArrayList<HostTracker.ARPPending>();
+    ConcurrentMap<InetAddress, ARPPending> failedARPReqList;
 
     public HostTracker() {
     }
 
     private void startUp() {
+        nonClusterObjectCreate();
         allocateCache();
         retrieveCache();
 
@@ -160,8 +167,8 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
         timer.schedule(new OutStandingARPHandler(), 4000, 4000);
         executor = Executors.newFixedThreadPool(2);
         /* ARP Refresh Timer to go off every 5 seconds to implement ARP aging */
-        arp_refresh_timer = new Timer();
-        arp_refresh_timer.schedule(new ARPRefreshHandler(), 5000, 5000);
+        arpRefreshTimer = new Timer();
+        arpRefreshTimer.schedule(new ARPRefreshHandler(), 5000, 5000);
         logger.debug("startUp: Caches created, timers started");
     }
 
@@ -173,10 +180,10 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
         }
         logger.debug("Creating Cache for HostTracker");
         try {
-            this.clusterContainerService.createCache("hostTrackerAH",
-                    EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
-            this.clusterContainerService.createCache("hostTrackerIH",
-                    EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
+            this.clusterContainerService.createCache(ACTIVE_HOST_CACHE,
+                    EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
+            this.clusterContainerService.createCache(INACTIVE_HOST_CACHE,
+                    EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
         } catch (CacheConfigException cce) {
             logger.error("Cache couldn't be created for HostTracker -  check cache mode");
         } catch (CacheExistException cce) {
@@ -193,14 +200,14 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
         }
         logger.debug("Retrieving cache for HostTrackerAH");
         hostsDB = (ConcurrentMap<InetAddress, HostNodeConnector>) this.clusterContainerService
-                .getCache("hostTrackerAH");
+                .getCache(ACTIVE_HOST_CACHE);
         if (hostsDB == null) {
             logger.error("Cache couldn't be retrieved for HostTracker");
         }
         logger.debug("Cache was successfully retrieved for HostTracker");
         logger.debug("Retrieving cache for HostTrackerIH");
         inactiveStaticHosts = (ConcurrentMap<NodeConnector, HostNodeConnector>) this.clusterContainerService
-                .getCache("hostTrackerIH");
+                .getCache(INACTIVE_HOST_CACHE);
         if (inactiveStaticHosts == null) {
             logger.error("Cache couldn't be retrieved for HostTrackerIH");
         }
@@ -210,6 +217,8 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
     public void nonClusterObjectCreate() {
         hostsDB = new ConcurrentHashMap<InetAddress, HostNodeConnector>();
         inactiveStaticHosts = new ConcurrentHashMap<NodeConnector, HostNodeConnector>();
+        ARPPendingList = new ConcurrentHashMap<InetAddress, ARPPending>();
+        failedARPReqList = new ConcurrentHashMap<InetAddress, ARPPending>();
     }
 
 
@@ -324,15 +333,15 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
             return host;
         }
 
-        /* host is not found, initiate a discovery */
-
-        hostFinder.find(networkAddress);
-
-        /* Also add this host to ARPPending List for any potential retries */
+        /* Add this host to ARPPending List for any potential retries */
 
         AddtoARPPendingList(networkAddress);
         logger.debug("hostFind(): Host Not Found for IP: {}, Inititated Host Discovery ...",
                 networkAddress.getHostAddress());
+
+        /* host is not found, initiate a discovery */
+
+        hostFinder.find(networkAddress);
         return null;
     }
 
@@ -375,63 +384,39 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
 
         arphost.setHostIP(networkAddr);
         arphost.setSent_count((short) 1);
-        ARPPendingList.add(arphost);
+        ARPPendingList.put(networkAddr, arphost);
         logger.debug("Host Added to ARPPending List, IP: {}", networkAddr);
     }
 
-    private void removePendingARPFromList(int index) {
-        if (index >= ARPPendingList.size()) {
-            logger.warn("removePendingARPFromList(): index greater than the List. Size:{}, Index:{}",
-                    ARPPendingList.size(), index);
-            return;
-        }
-        ARPPending arphost = ARPPendingList.remove(index);
-        HostTrackerCallable htCallable = arphost.getHostTrackerCallable();
-        if (htCallable != null)
-            htCallable.wakeup();
-    }
-
     public void setCallableOnPendingARP(InetAddress networkAddr, HostTrackerCallable callable) {
         ARPPending arphost;
-        for (int i = 0; i < ARPPendingList.size(); i++) {
-            arphost = ARPPendingList.get(i);
+        for (Entry <InetAddress, ARPPending> entry : ARPPendingList.entrySet()) {
+            arphost = entry.getValue();
             if (arphost.getHostIP().equals(networkAddr)) {
                 arphost.setHostTrackerCallable(callable);
             }
         }
     }
 
-    private void ProcPendingARPReqs(InetAddress networkAddr) {
+    private void processPendingARPReqs(InetAddress networkAddr) {
         ARPPending arphost;
 
-        for (int i = 0; i < ARPPendingList.size(); i++) {
-            arphost = ARPPendingList.get(i);
-            if (arphost.getHostIP().equals(networkAddr)) {
-                /*
-                 * An ARP was sent for this host. The address is learned, remove
-                 * the request
-                 */
-                removePendingARPFromList(i);
-                logger.debug("Host Removed from ARPPending List, IP: {}", networkAddr);
-                return;
-            }
+        if ((arphost = ARPPendingList.remove(networkAddr)) != null) {
+            // Remove the arphost from ARPPendingList as it has been learned now
+            logger.debug("Host Removed from ARPPending List, IP: {}", networkAddr);
+            HostTrackerCallable htCallable = arphost.getHostTrackerCallable();
+            if (htCallable != null)
+                htCallable.wakeup();
+            return;
         }
 
         /*
          * It could have been a host from the FailedARPReqList
          */
 
-        for (int i = 0; i < failedARPReqList.size(); i++) {
-            arphost = failedARPReqList.get(i);
-            if (arphost.getHostIP().equals(networkAddr)) {
-                /*
-                 * An ARP was sent for this host. The address is learned, remove
-                 * the request
-                 */
-                failedARPReqList.remove(i);
-                logger.debug("Host Removed from FailedARPReqList List, IP: {}", networkAddr);
-                return;
-            }
+        if  (failedARPReqList.containsKey(networkAddr)) {
+            failedARPReqList.remove(networkAddr);
+            logger.debug("Host Removed from FailedARPReqList List, IP: {}", networkAddr);
         }
     }
 
@@ -449,7 +434,15 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
     }
 
     private void replaceHost(InetAddress networkAddr, HostNodeConnector removedHost, HostNodeConnector newHost) {
+        // Ignore ARP messages from internal nodes
+        NodeConnector newHostNc = newHost.getnodeConnector();
+        boolean newHostIsInternal = topologyManager.isInternal(newHostNc);
+        if (newHostIsInternal) {
+            return;
+        }
+
         newHost.initArpSendCountDown();
+
         if (hostsDB.replace(networkAddr, removedHost, newHost)) {
             logger.debug("Host move occurred: Old Host IP:{}, New Host IP: {}", removedHost.getNetworkAddress()
                     .getHostAddress(), newHost.getNetworkAddress().getHostAddress());
@@ -469,7 +462,7 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
         notifyHostLearnedOrRemoved(removedHost, false);
         notifyHostLearnedOrRemoved(newHost, true);
         if (!newHost.isStaticHost()) {
-            ProcPendingARPReqs(networkAddr);
+            processPendingARPReqs(networkAddr);
         }
     }
 
@@ -520,7 +513,7 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
             }
 
             /* check if there is an outstanding request for this host */
-            ProcPendingARPReqs(networkAddr);
+            processPendingARPReqs(networkAddr);
             notifyHostLearnedOrRemoved(host, true);
         }
     }
@@ -781,10 +774,8 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
     private void updateCurrentHierarchy(Node node, ArrayList<String> currHierarchy, List<List<String>> fullHierarchy) {
         // currHierarchy.add(String.format("%x", currSw.getId()));
         currHierarchy.add(dpidToHostNameHack((Long) node.getID()));
-        ArrayList<String> currHierarchyClone = (ArrayList<String>) currHierarchy.clone(); // Shallow
-                                                                                          // copy
-                                                                                          // as
-                                                                                          // required
+        // Shallow copy as required
+        ArrayList<String> currHierarchyClone = (ArrayList<String>) currHierarchy.clone();
 
         Map<Node, Set<Edge>> ndlinks = topologyManager.getNodeEdges();
         if (ndlinks == null) {
@@ -806,14 +797,27 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
             Node dstNode = lt.getHeadNodeConnector().getNode();
 
             Tier nodeTier = (Tier) switchManager.getNodeProp(node, Tier.TierPropName);
+            /*
+             * If the host is directly attached to the src node, then the node
+             * should have been assigned the "Access" tier in
+             * notifyHostLearnedOrRemoved. If not, it would be assigned
+             * "Unknown" tier. Thus the tier of host attached node cannot be
+             * null. If the src node here, is the next node in the hierarchy of
+             * the nodes, then its tier cannot be null
+             */
+
             Tier dstNodeTier = (Tier) switchManager.getNodeProp(dstNode, Tier.TierPropName);
+            /*
+             * Skip if the tier of the destination node is null
+             */
+            if (dstNodeTier == null) {
+                continue;
+            }
             if (dstNodeTier.getValue() > nodeTier.getValue()) {
                 ArrayList<String> buildHierarchy = currHierarchy;
                 if (currHierarchy.size() > currHierarchyClone.size()) {
-                    buildHierarchy = (ArrayList<String>) currHierarchyClone.clone(); // Shallow
-                                                                                     // copy
-                                                                                     // as
-                                                                                     // required
+                    // Shallow copy as required
+                    buildHierarchy = (ArrayList<String>) currHierarchyClone.clone();
                     fullHierarchy.add(buildHierarchy);
                 }
                 updateCurrentHierarchy(dstNode, buildHierarchy, fullHierarchy);
@@ -821,7 +825,7 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
         }
     }
 
-    private void edgeUpdate(Edge e, UpdateType type, Set<Property> props) {
+    private void debugEdgeUpdate(Edge e, UpdateType type, Set<Property> props) {
         Long srcNid = null;
         Short srcPort = null;
         Long dstNid = null;
@@ -843,7 +847,7 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
             }
 
             if (!srcType.equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) {
-                logger.error("For now we cannot handle updates for " + "non-openflow nodes");
+                logger.debug("For now we cannot handle updates for non-openflow nodes");
                 return;
             }
 
@@ -853,7 +857,7 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
             }
 
             if (!dstType.equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) {
-                logger.error("For now we cannot handle updates for " + "non-openflow nodes");
+                logger.debug("For now we cannot handle updates for non-openflow nodes");
                 return;
             }
 
@@ -881,11 +885,14 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
 
     @Override
     public void edgeUpdate(List<TopoEdgeUpdate> topoedgeupdateList) {
-        for (int i = 0; i < topoedgeupdateList.size(); i++) {
-            Edge e = topoedgeupdateList.get(i).getEdge();
-            Set<Property> p = topoedgeupdateList.get(i).getProperty();
-            UpdateType type = topoedgeupdateList.get(i).getUpdateType();
-            edgeUpdate(e, type, p);
+        if (logger.isDebugEnabled()) {
+            for (TopoEdgeUpdate topoEdgeUpdate : topoedgeupdateList) {
+                Edge e = topoEdgeUpdate.getEdge();
+                Set<Property> p = topoEdgeUpdate.getProperty();
+                UpdateType type = topoEdgeUpdate.getUpdateType();
+
+                debugEdgeUpdate(e, type, p);
+            }
         }
     }
 
@@ -893,9 +900,9 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
     public void subnetNotify(Subnet sub, boolean add) {
         logger.debug("Received subnet notification: {}  add={}", sub, add);
         if (add) {
-            for (int i = 0; i < failedARPReqList.size(); i++) {
+            for (Entry <InetAddress, ARPPending> entry : failedARPReqList.entrySet()) {
                 ARPPending arphost;
-                arphost = failedARPReqList.get(i);
+                arphost = entry.getValue();
                 if (hostFinder == null) {
                     logger.warn("ARPHandler Services are not available on subnet addition");
                     continue;
@@ -910,10 +917,20 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
         @Override
         public void run() {
             ARPPending arphost;
+
             /* This routine runs every 4 seconds */
-            // logger.info ("ARP Handler called");
-            for (int i = 0; i < ARPPendingList.size(); i++) {
-                arphost = ARPPendingList.get(i);
+            logger.trace("Number of Entries in ARP Pending/Failed Lists: ARPPendingList = {}, failedARPReqList = {}",
+                    ARPPendingList.size(), failedARPReqList.size());
+            for (Entry <InetAddress, ARPPending> entry : ARPPendingList.entrySet()) {
+                arphost = entry.getValue();
+
+                if (hostsDB.containsKey(arphost.getHostIP())) {
+                    // this host is already learned, shouldn't be in ARPPendingList
+                    // Remove it and continue
+                    logger.warn("Learned Host {} found in ARPPendingList", arphost.getHostIP());
+                    ARPPendingList.remove(entry.getKey());
+                    continue;
+                }
                 if (arphost.getSent_count() < switchManager.getHostRetryCount()) {
                     /*
                      * No reply has been received of first ARP Req, send the
@@ -932,7 +949,7 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
                      * ARP requests have been sent without receiving a
                      * reply, remove this from the pending list
                      */
-                    removePendingARPFromList(i);
+                    ARPPendingList.remove(entry.getKey());
                     logger.debug("ARP reply not received after multiple attempts, removing from Pending List IP: {}",
                             arphost.getHostIP().getHostAddress());
                     /*
@@ -940,10 +957,10 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
                      * on link up events
                      */
                     logger.debug("Adding the host to FailedARPReqList IP: {}", arphost.getHostIP().getHostAddress());
-                    failedARPReqList.add(arphost);
+                    failedARPReqList.put(entry.getKey(), arphost);
 
                 } else {
-                    logger.error("Inavlid arp_sent count for entery at index: {}", i);
+                    logger.error("Inavlid arp_sent count for entry: {}", entry);
                 }
             }
         }
@@ -1070,6 +1087,7 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
              */
             if (switchManager.isNodeConnectorEnabled(nc)) {
                 learnNewHost(host);
+                processPendingARPReqs(networkAddr);
                 notifyHostLearnedOrRemoved(host, true);
             } else {
                 inactiveStaticHosts.put(nc, host);
@@ -1281,11 +1299,12 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
 
     private void handleNodeConnectorStatusUp(NodeConnector nodeConnector) {
         ARPPending arphost;
+        HostNodeConnector host = null;
 
         logger.debug("handleNodeConnectorStatusUp {}", nodeConnector);
 
-        for (int i = 0; i < failedARPReqList.size(); i++) {
-            arphost = failedARPReqList.get(i);
+        for (Entry <InetAddress, ARPPending> entry : failedARPReqList.entrySet()) {
+            arphost = entry.getValue();
             logger.debug("Sending the ARP from FailedARPReqList fors IP: {}", arphost.getHostIP().getHostAddress());
             if (hostFinder == null) {
                 logger.warn("ARPHandler is not available at interface  up");
@@ -1293,12 +1312,26 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
                         nodeConnector);
                 continue;
             }
-            hostFinder.find(arphost.getHostIP());
+
+            // Send a broadcast ARP only on the interface which just came up.
+            // Use hostFinder's "probe" method
+            try {
+                byte[] dataLayerAddress = NetUtils.getBroadcastMACAddr();
+                host = new HostNodeConnector(dataLayerAddress, arphost.getHostIP(), nodeConnector, (short) 0);
+                hostFinder.probe(host);
+            } catch (ConstructionException e) {
+                logger.debug("HostNodeConnector couldn't be created for Host: {}, NodeConnector: {}",
+                        arphost.getHostIP(), nodeConnector);
+                logger.error("", e);
+            }
+            logger.debug("Done. handleNodeConnectorStatusUp {}", nodeConnector);
         }
-        HostNodeConnector host = inactiveStaticHosts.get(nodeConnector);
+
+        host = inactiveStaticHosts.get(nodeConnector);
         if (host != null) {
             inactiveStaticHosts.remove(nodeConnector);
             learnNewHost(host);
+            processPendingARPReqs(host.getNetworkAddress());
             notifyHostLearnedOrRemoved(host, true);
         }
     }
@@ -1378,6 +1411,7 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
      *
      */
     void start() {
+        registerWithOSGIConsole();
     }
 
     /**
@@ -1386,7 +1420,12 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
      * calls
      *
      */
-    void stop() {
+    void stop(){
+    }
+
+    void stopping() {
+        arpRefreshTimer.cancel();
+        timer.cancel();
         executor.shutdown();
     }
 
@@ -1402,4 +1441,47 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
 
     }
 
+    @Override
+    public void entryCreated(InetAddress key, String cacheName,
+            boolean originLocal) {
+        if (originLocal) return;
+        processPendingARPReqs(key);
+    }
+
+    @Override
+    public void entryUpdated(InetAddress key, HostNodeConnector new_value,
+            String cacheName, boolean originLocal) {
+    }
+
+    @Override
+    public void entryDeleted(InetAddress key, String cacheName,
+            boolean originLocal) {
+    }
+
+    private void registerWithOSGIConsole() {
+        BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
+        bundleContext.registerService(CommandProvider.class.getName(), this, null);
+    }
+
+    @Override
+    public String getHelp() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    public void _dumpPendingARPReqList(CommandInterpreter ci) {
+        ARPPending arphost;
+        for (Entry <InetAddress, ARPPending> entry : ARPPendingList.entrySet()) {
+            arphost = entry.getValue();
+            ci.println(arphost.getHostIP().toString());
+        }
+    }
+
+    public void _dumpFailedARPReqList(CommandInterpreter ci) {
+        ARPPending arphost;
+        for (Entry <InetAddress, ARPPending> entry : failedARPReqList.entrySet()) {
+            arphost = entry.getValue();
+            ci.println(arphost.getHostIP().toString());
+        }
+    }
 }