X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?p=controller.git;a=blobdiff_plain;f=opendaylight%2Fhosttracker%2Fimplementation%2Fsrc%2Fmain%2Fjava%2Forg%2Fopendaylight%2Fcontroller%2Fhosttracker%2Finternal%2FHostTracker.java;h=df62c1985a62b5e7b11db450a39586d3ce0a8d58;hp=6b7bac03e9bdcfc472ad3dce7cc2c10d1f8dd096;hb=9139d6ad1d16ba323d5fef0f71fdfde83b679125;hpb=fa52e9399f9687c7290ed98b22b00cdce4a6aacd diff --git a/opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTracker.java b/opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTracker.java index 6b7bac03e9..df62c1985a 100644 --- a/opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTracker.java +++ b/opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTracker.java @@ -24,13 +24,17 @@ import java.util.TimerTask; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.ExecutorService; 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 +66,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,10 +85,12 @@ import org.slf4j.LoggerFactory; */ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAware, IInventoryListener, - ITopologyManagerAware { + ITopologyManagerAware, ICacheUpdateAware, 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 hostsDB; + protected final Set hostFinder = new CopyOnWriteArraySet();; + protected ConcurrentMap hostsDB; /* * Following is a list of hosts which have been requested by NB APIs to be * added, but either the switch or the port is not sup, so they will be @@ -92,12 +100,15 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw private final Set newHostNotify = Collections.synchronizedSet(new HashSet()); private ITopologyManager topologyManager; - private IClusterContainerServices clusterContainerService = null; - private ISwitchManager switchManager = null; + protected IClusterContainerServices clusterContainerService = null; + protected ISwitchManager switchManager = null; private Timer timer; - private Timer arp_refresh_timer; + private Timer arpRefreshTimer; private String containerName = null; - + private ExecutorService executor; + protected boolean stopping; + private static boolean hostRefresh = true; + private static int hostRetryCount = 5; private static class ARPPending { protected InetAddress hostIP; protected short sent_count; @@ -130,7 +141,7 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw // This list contains the hosts for which ARP requests are being sent // periodically - private final List ARPPendingList = new ArrayList(); + ConcurrentMap 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,25 +158,26 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw * * We can't recover from condition 3 above */ - private final ArrayList failedARPReqList = new ArrayList(); + ConcurrentMap failedARPReqList; public HostTracker() { } private void startUp() { + nonClusterObjectCreate(); allocateCache(); retrieveCache(); + stopping = false; timer = new Timer(); 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"); } - @SuppressWarnings("deprecation") private void allocateCache() { if (this.clusterContainerService == null) { logger.error("un-initialized clusterContainerService, can't create cache"); @@ -173,10 +185,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) { @@ -185,7 +197,7 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw logger.debug("Cache successfully created for HostTracker"); } - @SuppressWarnings({ "unchecked", "deprecation" }) + @SuppressWarnings({ "unchecked" }) private void retrieveCache() { if (this.clusterContainerService == null) { logger.error("un-initialized clusterContainerService, can't retrieve cache"); @@ -193,14 +205,14 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw } logger.debug("Retrieving cache for HostTrackerAH"); hostsDB = (ConcurrentMap) 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) this.clusterContainerService - .getCache("hostTrackerIH"); + .getCache(INACTIVE_HOST_CACHE); if (inactiveStaticHosts == null) { logger.error("Cache couldn't be retrieved for HostTrackerIH"); } @@ -210,9 +222,10 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw public void nonClusterObjectCreate() { hostsDB = new ConcurrentHashMap(); inactiveStaticHosts = new ConcurrentHashMap(); + ARPPendingList = new ConcurrentHashMap(); + failedARPReqList = new ConcurrentHashMap(); } - public void shutDown() { } @@ -225,13 +238,15 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw } public void setArpHandler(IHostFinder hostFinder) { - this.hostFinder = hostFinder; + if (this.hostFinder != null) { + this.hostFinder.add(hostFinder); + } } public void unsetArpHandler(IHostFinder hostFinder) { - if (this.hostFinder == hostFinder) { + if (this.hostFinder != null) { logger.debug("Arp Handler Service removed!"); - this.hostFinder = null; + this.hostFinder.remove(hostFinder); } } @@ -296,9 +311,8 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw @Override public Future discoverHost(InetAddress networkAddress) { - ExecutorService executor = Executors.newFixedThreadPool(1); if (executor == null) { - logger.error("discoverHost: Null executor"); + logger.debug("discoverHost: Null executor"); return null; } Callable worker = new HostTrackerCallable(this, networkAddress); @@ -324,23 +338,23 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw logger.debug("hostFind(): Host found for IP: {}", networkAddress.getHostAddress()); return host; } - /* host is not found, initiate a discovery */ - hostFinder.find(networkAddress); - /* Also add this host to ARPPending List for any potential retries */ - AddtoARPPendingList(networkAddress); + + /* 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 */ + for (IHostFinder hf : hostFinder) { + hf.find(networkAddress); + } return null; } @Override public Set getAllHosts() { - Set allHosts = new HashSet(); - for (Entry entry : hostsDB.entrySet()) { - HostNodeConnector host = entry.getValue(); - allHosts.add(host); - } - logger.debug("Exiting getAllHosts, Found {} Hosts", allHosts.size()); + Set allHosts = new HashSet(hostsDB.values()); return allHosts; } @@ -353,82 +367,54 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw list.add(host); } } - logger.debug("getActiveStaticHosts(): Found {} Hosts", list.size()); return list; } @Override public Set getInactiveStaticHosts() { - Set list = new HashSet(); - for (Entry entry : inactiveStaticHosts.entrySet()) { - list.add(entry.getValue()); - } - logger.debug("getInactiveStaticHosts(): Found {} Hosts", list.size()); + Set list = new HashSet(inactiveStaticHosts.values()); return list; } - private void AddtoARPPendingList(InetAddress networkAddr) { + private void addToARPPendingList(InetAddress networkAddr) { ARPPending arphost = new ARPPending(); 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 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); } } @@ -446,9 +432,23 @@ 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:{}, New Host: {}", removedHost, newHost); + logger.debug("Host move occurred: Old Host IP:{}, New Host IP: {}", removedHost.getNetworkAddress() + .getHostAddress(), newHost.getNetworkAddress().getHostAddress()); + logger.debug("Old Host MAC: {}, New Host MAC: {}", + HexEncode.bytesToHexString(removedHost.getDataLayerAddressBytes()), + HexEncode.bytesToHexString(newHost.getDataLayerAddressBytes())); + // Display the Old and New HostNodeConnectors also + logger.debug("Old {}, New {}", removedHost, newHost); } else { /* * Host replacement has failed, do the recovery @@ -460,7 +460,7 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw notifyHostLearnedOrRemoved(removedHost, false); notifyHostLearnedOrRemoved(newHost, true); if (!newHost.isStaticHost()) { - ProcPendingARPReqs(networkAddr); + processPendingARPReqs(networkAddr); } } @@ -501,28 +501,28 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw replaceHost(networkAddr, removedHost, host); return; } else { - logger.error("Host to be removed not found in hostsDB. Host {}", removedHost); + logger.error("Host to be removed not found in hostsDB"); } } - if (removedHost == null) { - // It is a new host - learnNewHost(host); - } + // It is a new host + learnNewHost(host); /* check if there is an outstanding request for this host */ - ProcPendingARPReqs(networkAddr); + processPendingARPReqs(networkAddr); notifyHostLearnedOrRemoved(host, true); } } @Override public void hostListener(HostNodeConnector host) { - + logger.debug("Received for Host: IP {}, MAC {}, {}", host.getNetworkAddress().getHostAddress(), + HexEncode.bytesToHexString(host.getDataLayerAddressBytes()), host); if (hostExists(host)) { - logger.debug("ARP received for Host: {}", host); HostNodeConnector existinghost = hostsDB.get(host.getNetworkAddress()); existinghost.initArpSendCountDown(); + // Update the host + hostsDB.put(host.getNetworkAddress(), existinghost); return; } new NotifyHostThread(host).start(); @@ -533,6 +533,8 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw private void notifyHostLearnedOrRemoved(HostNodeConnector host, boolean add) { // Update listeners if any if (newHostNotify != null) { + logger.debug("Notifying Applications for Host {} Being {}", host.getNetworkAddress().getHostAddress(), + add ? "Added" : "Deleted"); synchronized (this.newHostNotify) { for (IfNewHostNotify ta : newHostNotify) { try { @@ -542,7 +544,7 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw ta.notifyHTClientHostRemoved(host); } } catch (Exception e) { - logger.error("Exception on callback", e); + logger.error("Exception on new host notification", e); } } } @@ -564,6 +566,8 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw } if (topologyManager != null && p != null && h != null) { + logger.debug("Notifying Topology Manager for Host {} Being {}", h.getNetworkAddress().getHostAddress(), + add ? "Added" : "Deleted"); if (add == true) { Tier tier = new Tier(1); switchManager.setNodeProp(node, tier); @@ -593,6 +597,7 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw * @param currentTier * The Tier on which n belongs */ + @SuppressWarnings("unused") private void updateSwitchTiers(Node n, int currentTier) { Map> ndlinks = topologyManager.getNodeEdges(); if (ndlinks == null) { @@ -654,12 +659,14 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw } // This is the case where Tier was never set for this node Tier t = (Tier) switchManager.getNodeProp(n, Tier.TierPropName); - if (t == null) + if (t == null) { return true; - if (t.getValue() == 0) + } + if (t.getValue() == 0) { return true; - else if (t.getValue() > tier) + } else if (t.getValue() > tier) { return true; + } return false; } @@ -668,6 +675,7 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw * cleanup is performed during cases such as Topology Change where the * existing Tier values might become incorrect */ + @SuppressWarnings("unused") private void clearTiers() { Set nodes = null; if (switchManager == null) { @@ -691,9 +699,9 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw int num = 1; for (ArrayList hierarchy : hierarchies) { StringBuffer buf = new StringBuffer(); - buf.append("Hierarchy#" + num + " : "); + buf.append("Hierarchy#").append(num).append(" : "); for (String switchName : hierarchy) { - buf.append(switchName + "/"); + buf.append(switchName).append("/"); } logger.debug("{} -> {}", getContainerName(), buf); num++; @@ -714,8 +722,9 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw @Override public List> getHostNetworkHierarchy(InetAddress hostAddress) { HostNodeConnector host = hostQuery(hostAddress); - if (host == null) + if (host == null) { return null; + } List> hierarchies = new ArrayList>(); ArrayList currHierarchy = new ArrayList(); @@ -743,10 +752,12 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw int result = 0; for (int i = 0; i < hex.length(); i++) { result = (int) ((dpid >> (i * 8)) & 0xff); - if (result == 0) + if (result == 0) { continue; - if (result < 0x30) + } + if (result < 0x30) { result += 0x40; + } sb.append(String.format("%c", result)); } return sb.reverse().toString(); @@ -765,12 +776,9 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw */ @SuppressWarnings("unchecked") private void updateCurrentHierarchy(Node node, ArrayList currHierarchy, List> fullHierarchy) { - // currHierarchy.add(String.format("%x", currSw.getId())); currHierarchy.add(dpidToHostNameHack((Long) node.getID())); - ArrayList currHierarchyClone = (ArrayList) currHierarchy.clone(); // Shallow - // copy - // as - // required + // Shallow copy as required + ArrayList currHierarchyClone = (ArrayList) currHierarchy.clone(); Map> ndlinks = topologyManager.getNodeEdges(); if (ndlinks == null) { @@ -792,14 +800,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 buildHierarchy = currHierarchy; if (currHierarchy.size() > currHierarchyClone.size()) { - buildHierarchy = (ArrayList) currHierarchyClone.clone(); // Shallow - // copy - // as - // required + // Shallow copy as required + buildHierarchy = (ArrayList) currHierarchyClone.clone(); fullHierarchy.add(buildHierarchy); } updateCurrentHierarchy(dstNode, buildHierarchy, fullHierarchy); @@ -807,7 +828,7 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw } } - private void edgeUpdate(Edge e, UpdateType type, Set props) { + private void debugEdgeUpdate(Edge e, UpdateType type, Set props) { Long srcNid = null; Short srcPort = null; Long dstNid = null; @@ -829,7 +850,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; } @@ -839,7 +860,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; } @@ -867,11 +888,14 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw @Override public void edgeUpdate(List topoedgeupdateList) { - for (int i = 0; i < topoedgeupdateList.size(); i++) { - Edge e = topoedgeupdateList.get(i).getEdge(); - Set 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 p = topoEdgeUpdate.getProperty(); + UpdateType type = topoEdgeUpdate.getUpdateType(); + + debugEdgeUpdate(e, type, p); + } } } @@ -879,11 +903,17 @@ 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 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; + } logger.debug("Sending the ARP from FailedARPReqList fors IP: {}", arphost.getHostIP().getHostAddress()); - hostFinder.find(arphost.getHostIP()); + for (IHostFinder hf : hostFinder) { + hf.find(arphost.getHostIP()); + } } } } @@ -891,36 +921,56 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw class OutStandingARPHandler extends TimerTask { @Override public void run() { + if (stopping) { + return; + } 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); - if (arphost.getSent_count() < switchManager.getHostRetryCount()) { + logger.trace("Number of Entries in ARP Pending/Failed Lists: ARPPendingList = {}, failedARPReqList = {}", + ARPPendingList.size(), failedARPReqList.size()); + for (Entry 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() < hostRetryCount) { /* * No reply has been received of first ARP Req, send the - * next one + * next one. Before sending the ARP, check if ARPHandler is + * available or not */ - hostFinder.find(arphost.getHostIP()); + if (hostFinder == null) { + logger.warn("ARPHandler Services are not available for Outstanding ARPs"); + continue; + } + for (IHostFinder hf : hostFinder) { + hf.find(arphost.getHostIP()); + } arphost.sent_count++; logger.debug("ARP Sent from ARPPending List, IP: {}", arphost.getHostIP().getHostAddress()); - } else if (arphost.getSent_count() >= switchManager.getHostRetryCount()) { + } else if (arphost.getSent_count() >= hostRetryCount) { /* - * Two ARP requests have been sent without receiving a - * reply, remove this from the pending list + * ARP requests have been sent without receiving a reply, + * remove this from the pending list */ - removePendingARPFromList(i); - logger.debug("ARP reply not received after two attempts, removing from Pending List IP: {}", + ARPPendingList.remove(entry.getKey()); + logger.debug("ARP reply not received after multiple attempts, removing from Pending List IP: {}", arphost.getHostIP().getHostAddress()); /* * Add this host to a different list which will be processed * 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); } } } @@ -928,14 +978,16 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw private class ARPRefreshHandler extends TimerTask { @Override - @SuppressWarnings("deprecation") public void run() { + if (stopping) { + return; + } if ((clusterContainerService != null) && !clusterContainerService.amICoordinator()) { return; } - if ((switchManager != null) && !switchManager.isHostRefreshEnabled()) { + if (!hostRefresh) { /* - * The host probe procedure was disabled by CLI + * The host probe procedure is turned off */ return; } @@ -953,7 +1005,7 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw short arp_cntdown = host.getArpSendCountDown(); arp_cntdown--; - if (arp_cntdown > switchManager.getHostRetryCount()) { + if (arp_cntdown > hostRetryCount) { host.setArpSendCountDown(arp_cntdown); } else if (arp_cntdown <= 0) { /* @@ -962,7 +1014,7 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw */ removeKnownHost(entry.getKey()); notifyHostLearnedOrRemoved(host, false); - } else if (arp_cntdown <= switchManager.getHostRetryCount()) { + } else if (arp_cntdown <= hostRetryCount) { /* * Use the services of arphandler to check if host is still * there @@ -974,7 +1026,18 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw HexEncode.bytesToHexString(host.getDataLayerAddressBytes()) }); } host.setArpSendCountDown(arp_cntdown); - hostFinder.probe(host); + if (hostFinder == null) { + /* + * If hostfinder is not available, then can't send the + * probe. However, continue the age out the hosts since + * we don't know if the host is indeed out there or not. + */ + logger.trace("ARPHandler is not avaialable, can't send the probe"); + continue; + } + for (IHostFinder hf : hostFinder) { + hf.probe(host); + } } } } @@ -999,7 +1062,7 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw * indicating the result of this action. */ - public Status addStaticHostReq(InetAddress networkAddr, byte[] dataLayerAddress, NodeConnector nc, short vlan) { + protected Status addStaticHostReq(InetAddress networkAddr, byte[] dataLayerAddress, NodeConnector nc, short vlan) { if (dataLayerAddress.length != NetUtils.MACAddrLengthInBytes) { return new Status(StatusCode.BADREQUEST, "Invalid MAC address"); } @@ -1015,13 +1078,13 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw // northbound request HostNodeConnector transHost = hostsDB.get(networkAddr); transHost.setStaticHost(true); - return new Status(StatusCode.SUCCESS, null); + return new Status(StatusCode.SUCCESS); } if (hostsDB.get(networkAddr) != null) { // There is already a host with this IP address (but behind // a different (switch, port, vlan) tuple. Return an error - return new Status(StatusCode.CONFLICT, "Existing IP, Use PUT to update"); + return new Status(StatusCode.CONFLICT, "Host with this IP already exists."); } host.setStaticHost(true); /* @@ -1038,13 +1101,14 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw */ if (switchManager.isNodeConnectorEnabled(nc)) { learnNewHost(host); + processPendingARPReqs(networkAddr); notifyHostLearnedOrRemoved(host, true); } else { inactiveStaticHosts.put(nc, host); logger.debug("Switch or switchport is not up, adding host {} to inactive list", networkAddr.getHostName()); } - return new Status(StatusCode.SUCCESS, null); + return new Status(StatusCode.SUCCESS); } catch (ConstructionException e) { logger.error("", e); return new Status(StatusCode.INTERNALERROR, "Host could not be created"); @@ -1172,8 +1236,9 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw @Override public void notifyNode(Node node, UpdateType type, Map propMap) { - if (node == null) + if (node == null) { return; + } switch (type) { case REMOVED: @@ -1194,8 +1259,9 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw @Override public void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map propMap) { - if (nodeConnector == null) + if (nodeConnector == null) { return; + } boolean up = false; switch (type) { @@ -1225,48 +1291,78 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw public Status addStaticHost(String networkAddress, String dataLayerAddress, NodeConnector nc, String vlan) { try { InetAddress ip = InetAddress.getByName(networkAddress); - if (nc == null) { - return new Status(StatusCode.BADREQUEST, "Invalid NodeId"); + short vl = 0; + if (vlan != null && !vlan.isEmpty()) { + vl = Short.decode(vlan); + if (vl < 1 || vl > 4095) { + return new Status(StatusCode.BADREQUEST, "Host vlan out of range [1 - 4095]"); + } } - return addStaticHostReq(ip, HexEncode.bytesFromHexString(dataLayerAddress), nc, Short.valueOf(vlan)); + + return addStaticHostReq(ip, HexEncode.bytesFromHexString(dataLayerAddress), nc, vl); + } catch (UnknownHostException e) { - logger.error("", e); - return new Status(StatusCode.BADREQUEST, "Invalid Address"); + logger.debug("Invalid host IP specified when adding static host", e); + return new Status(StatusCode.BADREQUEST, "Invalid Host IP Address"); + } catch (NumberFormatException nfe) { + logger.debug("Invalid host vlan or MAC specified when adding static host", nfe); + return new Status(StatusCode.BADREQUEST, "Invalid Host vLan/MAC"); } } @Override public Status removeStaticHost(String networkAddress) { - InetAddress address; try { - address = InetAddress.getByName(networkAddress); + InetAddress address = InetAddress.getByName(networkAddress); return removeStaticHostReq(address); } catch (UnknownHostException e) { - logger.error("", e); - return new Status(StatusCode.BADREQUEST, "Invalid Address"); + logger.debug("Invalid IP Address when trying to remove host", e); + return new Status(StatusCode.BADREQUEST, "Invalid IP Address when trying to remove host"); } } private void handleNodeConnectorStatusUp(NodeConnector nodeConnector) { ARPPending arphost; + HostNodeConnector host = null; - logger.debug("handleNodeConnectorStatusUp {}", nodeConnector); + logger.trace("handleNodeConnectorStatusUp {}", nodeConnector); - for (int i = 0; i < failedARPReqList.size(); i++) { - arphost = failedARPReqList.get(i); - logger.debug("Sending the ARP from FailedARPReqList fors IP: {}", arphost.getHostIP().getHostAddress()); - hostFinder.find(arphost.getHostIP()); + for (Entry entry : failedARPReqList.entrySet()) { + arphost = entry.getValue(); + logger.trace("Sending the ARP from FailedARPReqList fors IP: {}", arphost.getHostIP().getHostAddress()); + if (hostFinder == null) { + logger.warn("ARPHandler is not available at interface up"); + logger.warn("Since this event is missed, host(s) connected to interface {} may not be discovered", + nodeConnector); + continue; + } + + // 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); + for (IHostFinder hf : hostFinder) { + hf.probe(host); + } + } catch (ConstructionException e) { + logger.debug("HostNodeConnector couldn't be created for Host: {}, NodeConnector: {}", + arphost.getHostIP(), nodeConnector); + logger.error("", e); + } } - HostNodeConnector host = inactiveStaticHosts.get(nodeConnector); + + host = inactiveStaticHosts.get(nodeConnector); if (host != null) { inactiveStaticHosts.remove(nodeConnector); learnNewHost(host); + processPendingARPReqs(host.getNetworkAddress()); notifyHostLearnedOrRemoved(host, true); } } private void handleNodeConnectorStatusDown(NodeConnector nodeConnector) { - logger.debug("handleNodeConnectorStatusDown {}", nodeConnector); + logger.trace("handleNodeConnectorStatusDown {}", nodeConnector); for (Entry entry : hostsDB.entrySet()) { HostNodeConnector host = entry.getValue(); @@ -1303,8 +1399,9 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw } public String getContainerName() { - if (containerName == null) + if (containerName == null) { return GlobalConstants.DEFAULT.toString(); + } return containerName; } @@ -1340,6 +1437,7 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw * */ void start() { + registerWithOSGIConsole(); } /** @@ -1351,16 +1449,62 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw void stop() { } + void stopping() { + stopping = true; + arpRefreshTimer.cancel(); + timer.cancel(); + executor.shutdownNow(); + } + @Override public void edgeOverUtilized(Edge edge) { - // TODO Auto-generated method stub } @Override public void edgeUtilBackToNormal(Edge edge) { - // TODO Auto-generated method stub } + @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() { + return null; + } + + public void _dumpPendingARPReqList(CommandInterpreter ci) { + ARPPending arphost; + for (Entry entry : ARPPendingList.entrySet()) { + arphost = entry.getValue(); + ci.println(arphost.getHostIP().toString()); + } + } + + public void _dumpFailedARPReqList(CommandInterpreter ci) { + ARPPending arphost; + for (Entry entry : failedARPReqList.entrySet()) { + arphost = entry.getValue(); + ci.println(arphost.getHostIP().toString()); + } + } }