2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.hosttracker.internal;
11 import java.net.InetAddress;
12 import java.net.UnknownHostException;
13 import java.util.ArrayList;
14 import java.util.Collections;
15 import java.util.Dictionary;
16 import java.util.EnumSet;
17 import java.util.HashSet;
18 import java.util.List;
20 import java.util.Map.Entry;
22 import java.util.Timer;
23 import java.util.TimerTask;
24 import java.util.concurrent.Callable;
25 import java.util.concurrent.ConcurrentHashMap;
26 import java.util.concurrent.ConcurrentMap;
27 import java.util.concurrent.ExecutorService;
28 import java.util.concurrent.Executors;
29 import java.util.concurrent.Future;
31 import org.apache.felix.dm.Component;
32 import org.eclipse.osgi.framework.console.CommandInterpreter;
33 import org.eclipse.osgi.framework.console.CommandProvider;
34 import org.opendaylight.controller.clustering.services.CacheConfigException;
35 import org.opendaylight.controller.clustering.services.CacheExistException;
36 import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
37 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
38 import org.opendaylight.controller.clustering.services.IClusterServices;
39 import org.opendaylight.controller.hosttracker.IfHostListener;
40 import org.opendaylight.controller.hosttracker.IfIptoHost;
41 import org.opendaylight.controller.hosttracker.IfNewHostNotify;
42 import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
43 import org.opendaylight.controller.hosttracker.hostAware.IHostFinder;
44 import org.opendaylight.controller.sal.core.ConstructionException;
45 import org.opendaylight.controller.sal.core.Edge;
46 import org.opendaylight.controller.sal.core.Host;
47 import org.opendaylight.controller.sal.core.Node;
48 import org.opendaylight.controller.sal.core.NodeConnector;
49 import org.opendaylight.controller.sal.core.Property;
50 import org.opendaylight.controller.sal.core.State;
51 import org.opendaylight.controller.sal.core.Tier;
52 import org.opendaylight.controller.sal.core.UpdateType;
53 import org.opendaylight.controller.sal.packet.address.DataLinkAddress;
54 import org.opendaylight.controller.sal.packet.address.EthernetAddress;
55 import org.opendaylight.controller.sal.topology.TopoEdgeUpdate;
56 import org.opendaylight.controller.sal.utils.GlobalConstants;
57 import org.opendaylight.controller.sal.utils.HexEncode;
58 import org.opendaylight.controller.sal.utils.NetUtils;
59 import org.opendaylight.controller.sal.utils.NodeCreator;
60 import org.opendaylight.controller.sal.utils.Status;
61 import org.opendaylight.controller.sal.utils.StatusCode;
62 import org.opendaylight.controller.switchmanager.IInventoryListener;
63 import org.opendaylight.controller.switchmanager.ISwitchManager;
64 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
65 import org.opendaylight.controller.switchmanager.Subnet;
66 import org.opendaylight.controller.topologymanager.ITopologyManager;
67 import org.opendaylight.controller.topologymanager.ITopologyManagerAware;
68 import org.osgi.framework.BundleContext;
69 import org.osgi.framework.FrameworkUtil;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
74 * @file HostTracker.java This class tracks the location of IP Hosts as to which
75 * Switch, Port, VLAN, they are connected to, as well as their MAC
76 * address. This is done dynamically as well as statically. The dynamic
77 * mechanism consists of listening to ARP messages as well sending ARP
78 * requests. Static mechanism consists of Northbound APIs to add or remove
79 * the hosts from the local database. ARP aging is also implemented to age
80 * out dynamically learned hosts. Interface methods are provided for other
81 * applications to 1. Query the local database for a single host 2. Get a
82 * list of all hosts 3. Get notification if a host is learned/added or
83 * removed the database
86 public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAware, IInventoryListener,
87 ITopologyManagerAware, ICacheUpdateAware<InetAddress, HostNodeConnector>, CommandProvider {
88 static final String ACTIVE_HOST_CACHE = "hosttracker.ActiveHosts";
89 static final String INACTIVE_HOST_CACHE = "hosttracker.InactiveHosts";
90 private static final Logger logger = LoggerFactory.getLogger(HostTracker.class);
91 protected IHostFinder hostFinder;
92 protected ConcurrentMap<InetAddress, HostNodeConnector> hostsDB;
94 * Following is a list of hosts which have been requested by NB APIs to be
95 * added, but either the switch or the port is not sup, so they will be
96 * added here until both come up
98 private ConcurrentMap<NodeConnector, HostNodeConnector> inactiveStaticHosts;
99 private final Set<IfNewHostNotify> newHostNotify = Collections.synchronizedSet(new HashSet<IfNewHostNotify>());
101 private ITopologyManager topologyManager;
102 protected IClusterContainerServices clusterContainerService = null;
103 protected ISwitchManager switchManager = null;
105 private Timer arpRefreshTimer;
106 private String containerName = null;
107 private ExecutorService executor;
108 protected boolean stopping;
109 private static boolean hostRefresh = true;
110 private static int hostRetryCount = 5;
111 private static class ARPPending {
112 protected InetAddress hostIP;
113 protected short sent_count;
114 protected HostTrackerCallable hostTrackerCallable;
116 public InetAddress getHostIP() {
120 public short getSent_count() {
124 public HostTrackerCallable getHostTrackerCallable() {
125 return hostTrackerCallable;
128 public void setHostIP(InetAddress networkAddr) {
129 this.hostIP = networkAddr;
132 public void setSent_count(short count) {
133 this.sent_count = count;
136 public void setHostTrackerCallable(HostTrackerCallable callable) {
137 hostTrackerCallable = callable;
141 // This list contains the hosts for which ARP requests are being sent
143 ConcurrentMap<InetAddress, ARPPending> ARPPendingList;
145 * This list below contains the hosts which were initially in ARPPendingList
146 * above, but ARP response didn't come from there hosts after multiple
147 * attempts over 8 seconds. The assumption is that the response didn't come
148 * back due to one of the following possibilities: 1. The L3 interface
149 * wasn't created for this host in the controller. This would cause
150 * arphandler not to know where to send the ARP 2. The host facing port is
151 * down 3. The IP host doesn't exist or is not responding to ARP requests
153 * Conditions 1 and 2 above can be recovered if ARP is sent when the
154 * relevant L3 interface is added or the port facing host comes up. Whenever
155 * L3 interface is added or host facing port comes up, ARP will be sent to
156 * hosts in this list.
158 * We can't recover from condition 3 above
160 ConcurrentMap<InetAddress, ARPPending> failedARPReqList;
162 public HostTracker() {
165 private void startUp() {
166 nonClusterObjectCreate();
172 timer.schedule(new OutStandingARPHandler(), 4000, 4000);
173 executor = Executors.newFixedThreadPool(2);
174 /* ARP Refresh Timer to go off every 5 seconds to implement ARP aging */
175 arpRefreshTimer = new Timer();
176 arpRefreshTimer.schedule(new ARPRefreshHandler(), 5000, 5000);
177 logger.debug("startUp: Caches created, timers started");
180 private void allocateCache() {
181 if (this.clusterContainerService == null) {
182 logger.error("un-initialized clusterContainerService, can't create cache");
185 logger.debug("Creating Cache for HostTracker");
187 this.clusterContainerService.createCache(ACTIVE_HOST_CACHE,
188 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
189 this.clusterContainerService.createCache(INACTIVE_HOST_CACHE,
190 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
191 } catch (CacheConfigException cce) {
192 logger.error("Cache couldn't be created for HostTracker - check cache mode");
193 } catch (CacheExistException cce) {
194 logger.error("Cache for HostTracker already exists, destroy and recreate");
196 logger.debug("Cache successfully created for HostTracker");
199 @SuppressWarnings({ "unchecked" })
200 private void retrieveCache() {
201 if (this.clusterContainerService == null) {
202 logger.error("un-initialized clusterContainerService, can't retrieve cache");
205 logger.debug("Retrieving cache for HostTrackerAH");
206 hostsDB = (ConcurrentMap<InetAddress, HostNodeConnector>) this.clusterContainerService
207 .getCache(ACTIVE_HOST_CACHE);
208 if (hostsDB == null) {
209 logger.error("Cache couldn't be retrieved for HostTracker");
211 logger.debug("Cache was successfully retrieved for HostTracker");
212 logger.debug("Retrieving cache for HostTrackerIH");
213 inactiveStaticHosts = (ConcurrentMap<NodeConnector, HostNodeConnector>) this.clusterContainerService
214 .getCache(INACTIVE_HOST_CACHE);
215 if (inactiveStaticHosts == null) {
216 logger.error("Cache couldn't be retrieved for HostTrackerIH");
218 logger.debug("Cache was successfully retrieved for HostTrackerIH");
221 public void nonClusterObjectCreate() {
222 hostsDB = new ConcurrentHashMap<InetAddress, HostNodeConnector>();
223 inactiveStaticHosts = new ConcurrentHashMap<NodeConnector, HostNodeConnector>();
224 ARPPendingList = new ConcurrentHashMap<InetAddress, ARPPending>();
225 failedARPReqList = new ConcurrentHashMap<InetAddress, ARPPending>();
228 public void shutDown() {
231 public void setnewHostNotify(IfNewHostNotify obj) {
232 this.newHostNotify.add(obj);
235 public void unsetnewHostNotify(IfNewHostNotify obj) {
236 this.newHostNotify.remove(obj);
239 public void setArpHandler(IHostFinder hostFinder) {
240 this.hostFinder = hostFinder;
243 public void unsetArpHandler(IHostFinder hostFinder) {
244 if (this.hostFinder == hostFinder) {
245 logger.debug("Arp Handler Service removed!");
246 this.hostFinder = null;
250 public void setTopologyManager(ITopologyManager s) {
251 this.topologyManager = s;
254 public void unsetTopologyManager(ITopologyManager s) {
255 if (this.topologyManager == s) {
256 logger.debug("Topology Manager Service removed!");
257 this.topologyManager = null;
261 private boolean hostExists(HostNodeConnector host) {
262 HostNodeConnector lhost = hostsDB.get(host.getNetworkAddress());
263 return host.equals(lhost);
266 private HostNodeConnector getHostFromOnActiveDB(InetAddress networkAddress) {
267 return hostsDB.get(networkAddress);
270 private Entry<NodeConnector, HostNodeConnector> getHostFromInactiveDB(InetAddress networkAddress) {
271 for (Entry<NodeConnector, HostNodeConnector> entry : inactiveStaticHosts.entrySet()) {
272 if (entry.getValue().equalsByIP(networkAddress)) {
273 logger.debug("getHostFromInactiveDB(): Inactive Host found for IP:{} ", networkAddress.getHostAddress());
277 logger.debug("getHostFromInactiveDB() Inactive Host Not found for IP: {}", networkAddress.getHostAddress());
281 private void removeHostFromInactiveDB(InetAddress networkAddress) {
282 NodeConnector nodeConnector = null;
283 for (Entry<NodeConnector, HostNodeConnector> entry : inactiveStaticHosts.entrySet()) {
284 if (entry.getValue().equalsByIP(networkAddress)) {
285 nodeConnector = entry.getKey();
289 if (nodeConnector != null) {
290 inactiveStaticHosts.remove(nodeConnector);
291 logger.debug("removeHostFromInactiveDB(): Host Removed for IP: {}", networkAddress.getHostAddress());
294 logger.debug("removeHostFromInactiveDB(): Host Not found for IP: {}", networkAddress.getHostAddress());
297 protected boolean hostMoved(HostNodeConnector host) {
298 if (hostQuery(host.getNetworkAddress()) != null) {
305 public HostNodeConnector hostQuery(InetAddress networkAddress) {
306 return hostsDB.get(networkAddress);
310 public Future<HostNodeConnector> discoverHost(InetAddress networkAddress) {
311 if (executor == null) {
312 logger.debug("discoverHost: Null executor");
315 Callable<HostNodeConnector> worker = new HostTrackerCallable(this, networkAddress);
316 Future<HostNodeConnector> submit = executor.submit(worker);
321 public HostNodeConnector hostFind(InetAddress networkAddress) {
323 * Sometimes at boot with containers configured in the startup we hit
324 * this path (from TIF) when hostFinder has not been set yet Caller
325 * already handles the null return
328 if (hostFinder == null) {
329 logger.debug("Exiting hostFind, null hostFinder");
333 HostNodeConnector host = hostQuery(networkAddress);
335 logger.debug("hostFind(): Host found for IP: {}", networkAddress.getHostAddress());
339 /* Add this host to ARPPending List for any potential retries */
341 addToARPPendingList(networkAddress);
342 logger.debug("hostFind(): Host Not Found for IP: {}, Inititated Host Discovery ...",
343 networkAddress.getHostAddress());
345 /* host is not found, initiate a discovery */
347 hostFinder.find(networkAddress);
352 public Set<HostNodeConnector> getAllHosts() {
353 Set<HostNodeConnector> allHosts = new HashSet<HostNodeConnector>(hostsDB.values());
358 public Set<HostNodeConnector> getActiveStaticHosts() {
359 Set<HostNodeConnector> list = new HashSet<HostNodeConnector>();
360 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
361 HostNodeConnector host = entry.getValue();
362 if (host.isStaticHost()) {
370 public Set<HostNodeConnector> getInactiveStaticHosts() {
371 Set<HostNodeConnector> list = new HashSet<HostNodeConnector>(inactiveStaticHosts.values());
375 private void addToARPPendingList(InetAddress networkAddr) {
376 ARPPending arphost = new ARPPending();
378 arphost.setHostIP(networkAddr);
379 arphost.setSent_count((short) 1);
380 ARPPendingList.put(networkAddr, arphost);
381 logger.debug("Host Added to ARPPending List, IP: {}", networkAddr);
384 public void setCallableOnPendingARP(InetAddress networkAddr, HostTrackerCallable callable) {
386 for (Entry<InetAddress, ARPPending> entry : ARPPendingList.entrySet()) {
387 arphost = entry.getValue();
388 if (arphost.getHostIP().equals(networkAddr)) {
389 arphost.setHostTrackerCallable(callable);
394 private void processPendingARPReqs(InetAddress networkAddr) {
397 if ((arphost = ARPPendingList.remove(networkAddr)) != null) {
398 // Remove the arphost from ARPPendingList as it has been learned now
399 logger.debug("Host Removed from ARPPending List, IP: {}", networkAddr);
400 HostTrackerCallable htCallable = arphost.getHostTrackerCallable();
401 if (htCallable != null) {
408 * It could have been a host from the FailedARPReqList
411 if (failedARPReqList.containsKey(networkAddr)) {
412 failedARPReqList.remove(networkAddr);
413 logger.debug("Host Removed from FailedARPReqList List, IP: {}", networkAddr);
418 private void learnNewHost(HostNodeConnector host) {
419 host.initArpSendCountDown();
420 HostNodeConnector rHost = hostsDB.putIfAbsent(host.getNetworkAddress(), host);
422 // Another host is already learned for this IP address, replace it
423 replaceHost(host.getNetworkAddress(), rHost, host);
425 logger.debug("New Host Learned: MAC: {} IP: {}", HexEncode.bytesToHexString(host
426 .getDataLayerAddressBytes()), host.getNetworkAddress().getHostAddress());
430 private void replaceHost(InetAddress networkAddr, HostNodeConnector removedHost, HostNodeConnector newHost) {
431 // Ignore ARP messages from internal nodes
432 NodeConnector newHostNc = newHost.getnodeConnector();
433 boolean newHostIsInternal = topologyManager.isInternal(newHostNc);
434 if (newHostIsInternal) {
438 newHost.initArpSendCountDown();
440 if (hostsDB.replace(networkAddr, removedHost, newHost)) {
441 logger.debug("Host move occurred: Old Host IP:{}, New Host IP: {}", removedHost.getNetworkAddress()
442 .getHostAddress(), newHost.getNetworkAddress().getHostAddress());
443 logger.debug("Old Host MAC: {}, New Host MAC: {}",
444 HexEncode.bytesToHexString(removedHost.getDataLayerAddressBytes()),
445 HexEncode.bytesToHexString(newHost.getDataLayerAddressBytes()));
446 // Display the Old and New HostNodeConnectors also
447 logger.debug("Old {}, New {}", removedHost, newHost);
450 * Host replacement has failed, do the recovery
452 hostsDB.put(networkAddr, newHost);
453 logger.error("Host replacement failed. Overwrite the host. Repalced Host: {}, New Host: {}", removedHost,
456 notifyHostLearnedOrRemoved(removedHost, false);
457 notifyHostLearnedOrRemoved(newHost, true);
458 if (!newHost.isStaticHost()) {
459 processPendingARPReqs(networkAddr);
464 private void removeKnownHost(InetAddress key) {
465 HostNodeConnector host = hostsDB.get(key);
467 logger.debug("Removing Host: IP:{}", host.getNetworkAddress().getHostAddress());
470 logger.error("removeKnownHost(): Host for IP address {} not found in hostsDB", key.getHostAddress());
474 private class NotifyHostThread extends Thread {
476 private final HostNodeConnector host;
478 public NotifyHostThread(HostNodeConnector h) {
484 HostNodeConnector removedHost = null;
485 InetAddress networkAddr = host.getNetworkAddress();
487 /* Check for Host Move case */
488 if (hostMoved(host)) {
490 * Host has been moved from one location (switch,port, MAC, or
491 * VLAN) to another. Replace the existing host and its previous
492 * location parameters with new information, and notify the
493 * applications listening to host move.
495 removedHost = hostsDB.get(networkAddr);
496 if (removedHost != null) {
497 replaceHost(networkAddr, removedHost, host);
500 logger.error("Host to be removed not found in hostsDB");
507 /* check if there is an outstanding request for this host */
508 processPendingARPReqs(networkAddr);
509 notifyHostLearnedOrRemoved(host, true);
514 public void hostListener(HostNodeConnector host) {
516 logger.debug("ARP received for Host: IP {}, MAC {}, {}", host.getNetworkAddress().getHostAddress(),
517 HexEncode.bytesToHexString(host.getDataLayerAddressBytes()), host);
518 if (hostExists(host)) {
519 HostNodeConnector existinghost = hostsDB.get(host.getNetworkAddress());
520 existinghost.initArpSendCountDown();
522 hostsDB.put(host.getNetworkAddress(), existinghost);
525 new NotifyHostThread(host).start();
528 // Notify whoever is interested that a new host was learned (dynamically or
530 private void notifyHostLearnedOrRemoved(HostNodeConnector host, boolean add) {
531 // Update listeners if any
532 if (newHostNotify != null) {
533 logger.debug("Notifying Applications for Host {} Being {}", host.getNetworkAddress().getHostAddress(),
534 add ? "Added" : "Deleted");
535 synchronized (this.newHostNotify) {
536 for (IfNewHostNotify ta : newHostNotify) {
539 ta.notifyHTClient(host);
541 ta.notifyHTClientHostRemoved(host);
543 } catch (Exception e) {
544 logger.error("Exception on new host notification", e);
549 logger.error("notifyHostLearnedOrRemoved(): New host notify is null");
552 // Topology update is for some reason outside of listeners registry
554 Node node = host.getnodeconnectorNode();
556 NodeConnector p = host.getnodeConnector();
558 DataLinkAddress dla = new EthernetAddress(host.getDataLayerAddressBytes());
559 h = new Host(dla, host.getNetworkAddress());
560 } catch (ConstructionException ce) {
565 if (topologyManager != null && p != null && h != null) {
566 logger.debug("Notifying Topology Manager for Host {} Being {}", h.getNetworkAddress().getHostAddress(),
567 add ? "Added" : "Deleted");
569 Tier tier = new Tier(1);
570 switchManager.setNodeProp(node, tier);
571 topologyManager.updateHostLink(p, h, UpdateType.ADDED, null);
573 // No need to reset the tiering if no other hosts are currently
575 // If this switch was discovered to be an access switch, it
576 // still is even if the host is down
577 Tier tier = new Tier(0);
578 switchManager.setNodeProp(node, tier);
579 topologyManager.updateHostLink(p, h, UpdateType.REMOVED, null);
585 * When a new Host is learnt by the hosttracker module, it places the
586 * directly connected Node in Tier-1 & using this function, updates the Tier
587 * value for all other Nodes in the network hierarchy.
589 * This is a recursive function and it takes care of updating the Tier value
590 * for all the connected and eligible Nodes.
593 * Node that represents one of the Vertex in the Topology Graph.
595 * The Tier on which n belongs
597 @SuppressWarnings("unused")
598 private void updateSwitchTiers(Node n, int currentTier) {
599 Map<Node, Set<Edge>> ndlinks = topologyManager.getNodeEdges();
600 if (ndlinks == null) {
601 logger.debug("updateSwitchTiers(): ndlinks null for Node: {}, Tier:{}", n, currentTier);
604 Set<Edge> links = ndlinks.get(n);
606 logger.debug("updateSwitchTiers(): links null for ndlinks:{}", ndlinks);
609 ArrayList<Node> needsVisiting = new ArrayList<Node>();
610 for (Edge lt : links) {
611 if (!lt.getHeadNodeConnector().getType().equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) {
612 // We don't want to work on Node that are not openflow
616 Node dstNode = lt.getHeadNodeConnector().getNode();
617 if (switchNeedsTieringUpdate(dstNode, currentTier + 1)) {
618 Tier t = new Tier(currentTier + 1);
619 switchManager.setNodeProp(dstNode, t);
620 needsVisiting.add(dstNode);
625 * Due to the nature of the problem, having a separate loop for nodes
626 * that needs visiting provides a decent walk optimization.
628 for (Node node : needsVisiting) {
629 updateSwitchTiers(node, currentTier + 1);
634 * Internal convenience routine to check the eligibility of a Switch for a
635 * Tier update. Any Node with Tier=0 or a Tier value that is greater than
636 * the new Tier Value is eligible for the update.
639 * Node for which the Tier update eligibility is checked
642 * @return <code>true</code> if the Node is eligible for Tier Update
643 * <code>false</code> otherwise
646 private boolean switchNeedsTieringUpdate(Node n, int tier) {
648 logger.error("switchNeedsTieringUpdate(): Null node for tier: {}", tier);
652 * Node could have gone down
654 if (!switchManager.getNodes().contains(n)) {
657 // This is the case where Tier was never set for this node
658 Tier t = (Tier) switchManager.getNodeProp(n, Tier.TierPropName);
662 if (t.getValue() == 0) {
664 } else if (t.getValue() > tier) {
671 * Internal convenience routine to clear all the Tier values to 0. This
672 * cleanup is performed during cases such as Topology Change where the
673 * existing Tier values might become incorrect
675 @SuppressWarnings("unused")
676 private void clearTiers() {
677 Set<Node> nodes = null;
678 if (switchManager == null) {
679 logger.error("clearTiers(): Null switchManager");
682 nodes = switchManager.getNodes();
684 for (Node n : nodes) {
685 Tier t = new Tier(0);
686 switchManager.setNodeProp(n, t);
691 * Internal convenience routine to print the hierarchies of switches.
693 @SuppressWarnings("unused")
694 private void logHierarchies(ArrayList<ArrayList<String>> hierarchies) {
695 String hierarchyString = null;
697 for (ArrayList<String> hierarchy : hierarchies) {
698 StringBuffer buf = new StringBuffer();
699 buf.append("Hierarchy#" + num + " : ");
700 for (String switchName : hierarchy) {
701 buf.append(switchName + "/");
703 logger.debug("{} -> {}", getContainerName(), buf);
709 * getHostNetworkHierarchy is the Back-end routine for the North-Bound API
710 * that returns the Network Hierarchy for a given Host. This API is
711 * typically used by applications like Hadoop for Rack Awareness
715 * IP-Address of the host/node.
716 * @return Network Hierarchies represented by an Array of Array (of
717 * Switch-Ids as String).
720 public List<List<String>> getHostNetworkHierarchy(InetAddress hostAddress) {
721 HostNodeConnector host = hostQuery(hostAddress);
726 List<List<String>> hierarchies = new ArrayList<List<String>>();
727 ArrayList<String> currHierarchy = new ArrayList<String>();
728 hierarchies.add(currHierarchy);
730 Node node = host.getnodeconnectorNode();
731 updateCurrentHierarchy(node, currHierarchy, hierarchies);
736 * dpidToHostNameHack is a hack function for Cisco Live Hadoop Demo. Mininet
737 * is used as the network for Hadoop Demos & in order to give a meaningful
738 * rack-awareness switch names, the DPID is organized in ASCII Characters
739 * and retrieved as string.
743 * @return Ascii String represented by the DPID.
745 private String dpidToHostNameHack(long dpid) {
746 String hex = Long.toHexString(dpid);
748 StringBuffer sb = new StringBuffer();
750 for (int i = 0; i < hex.length(); i++) {
751 result = (int) ((dpid >> (i * 8)) & 0xff);
758 sb.append(String.format("%c", result));
760 return sb.reverse().toString();
764 * A convenient recursive routine to obtain the Hierarchy of Switches.
767 * Current Node in the Recursive routine.
768 * @param currHierarchy
769 * Array of Nodes that make this hierarchy on which the Current
771 * @param fullHierarchy
772 * Array of multiple Hierarchies that represent a given host.
774 @SuppressWarnings("unchecked")
775 private void updateCurrentHierarchy(Node node, ArrayList<String> currHierarchy, List<List<String>> fullHierarchy) {
776 // currHierarchy.add(String.format("%x", currSw.getId()));
777 currHierarchy.add(dpidToHostNameHack((Long) node.getID()));
778 // Shallow copy as required
779 ArrayList<String> currHierarchyClone = (ArrayList<String>) currHierarchy.clone();
781 Map<Node, Set<Edge>> ndlinks = topologyManager.getNodeEdges();
782 if (ndlinks == null) {
783 logger.debug("updateCurrentHierarchy(): topologyManager returned null ndlinks for node: {}", node);
786 Node n = NodeCreator.createOFNode((Long) node.getID());
787 Set<Edge> links = ndlinks.get(n);
789 logger.debug("updateCurrentHierarchy(): Null links for ndlinks");
792 for (Edge lt : links) {
793 if (!lt.getHeadNodeConnector().getType().equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) {
794 // We don't want to work on Node that are not openflow
798 Node dstNode = lt.getHeadNodeConnector().getNode();
800 Tier nodeTier = (Tier) switchManager.getNodeProp(node, Tier.TierPropName);
802 * If the host is directly attached to the src node, then the node
803 * should have been assigned the "Access" tier in
804 * notifyHostLearnedOrRemoved. If not, it would be assigned
805 * "Unknown" tier. Thus the tier of host attached node cannot be
806 * null. If the src node here, is the next node in the hierarchy of
807 * the nodes, then its tier cannot be null
810 Tier dstNodeTier = (Tier) switchManager.getNodeProp(dstNode, Tier.TierPropName);
812 * Skip if the tier of the destination node is null
814 if (dstNodeTier == null) {
817 if (dstNodeTier.getValue() > nodeTier.getValue()) {
818 ArrayList<String> buildHierarchy = currHierarchy;
819 if (currHierarchy.size() > currHierarchyClone.size()) {
820 // Shallow copy as required
821 buildHierarchy = (ArrayList<String>) currHierarchyClone.clone();
822 fullHierarchy.add(buildHierarchy);
824 updateCurrentHierarchy(dstNode, buildHierarchy, fullHierarchy);
829 private void debugEdgeUpdate(Edge e, UpdateType type, Set<Property> props) {
831 Short srcPort = null;
833 Short dstPort = null;
834 boolean added = false;
835 String srcType = null;
836 String dstType = null;
838 if (e == null || type == null) {
839 logger.error("Edge or Update type are null!");
842 srcType = e.getTailNodeConnector().getType();
843 dstType = e.getHeadNodeConnector().getType();
845 if (srcType.equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) {
846 logger.debug("Skip updates for {}", e);
850 if (!srcType.equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) {
851 logger.debug("For now we cannot handle updates for non-openflow nodes");
855 if (dstType.equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) {
856 logger.debug("Skip updates for {}", e);
860 if (!dstType.equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) {
861 logger.debug("For now we cannot handle updates for non-openflow nodes");
865 // At this point we know we got an openflow update, so
866 // lets fill everything accordingly.
867 srcNid = (Long) e.getTailNodeConnector().getNode().getID();
868 srcPort = (Short) e.getTailNodeConnector().getID();
869 dstNid = (Long) e.getHeadNodeConnector().getNode().getID();
870 dstPort = (Short) e.getHeadNodeConnector().getID();
872 // Now lets update the added flag
883 logger.debug("HostTracker Topology linkUpdate handling src:{}[port {}] dst:{}[port {}] added: {}",
884 new Object[] { srcNid, srcPort, dstNid, dstPort, added });
888 public void edgeUpdate(List<TopoEdgeUpdate> topoedgeupdateList) {
889 if (logger.isDebugEnabled()) {
890 for (TopoEdgeUpdate topoEdgeUpdate : topoedgeupdateList) {
891 Edge e = topoEdgeUpdate.getEdge();
892 Set<Property> p = topoEdgeUpdate.getProperty();
893 UpdateType type = topoEdgeUpdate.getUpdateType();
895 debugEdgeUpdate(e, type, p);
901 public void subnetNotify(Subnet sub, boolean add) {
902 logger.debug("Received subnet notification: {} add={}", sub, add);
904 for (Entry<InetAddress, ARPPending> entry : failedARPReqList.entrySet()) {
906 arphost = entry.getValue();
907 if (hostFinder == null) {
908 logger.warn("ARPHandler Services are not available on subnet addition");
911 logger.debug("Sending the ARP from FailedARPReqList fors IP: {}", arphost.getHostIP().getHostAddress());
912 hostFinder.find(arphost.getHostIP());
917 class OutStandingARPHandler extends TimerTask {
924 /* This routine runs every 4 seconds */
925 logger.trace("Number of Entries in ARP Pending/Failed Lists: ARPPendingList = {}, failedARPReqList = {}",
926 ARPPendingList.size(), failedARPReqList.size());
927 for (Entry<InetAddress, ARPPending> entry : ARPPendingList.entrySet()) {
928 arphost = entry.getValue();
930 if (hostsDB.containsKey(arphost.getHostIP())) {
931 // this host is already learned, shouldn't be in
933 // Remove it and continue
934 logger.warn("Learned Host {} found in ARPPendingList", arphost.getHostIP());
935 ARPPendingList.remove(entry.getKey());
938 if (arphost.getSent_count() < hostRetryCount) {
940 * No reply has been received of first ARP Req, send the
941 * next one. Before sending the ARP, check if ARPHandler is
944 if (hostFinder == null) {
945 logger.warn("ARPHandler Services are not available for Outstanding ARPs");
948 hostFinder.find(arphost.getHostIP());
949 arphost.sent_count++;
950 logger.debug("ARP Sent from ARPPending List, IP: {}", arphost.getHostIP().getHostAddress());
951 } else if (arphost.getSent_count() >= hostRetryCount) {
953 * ARP requests have been sent without receiving a reply,
954 * remove this from the pending list
956 ARPPendingList.remove(entry.getKey());
957 logger.debug("ARP reply not received after multiple attempts, removing from Pending List IP: {}",
958 arphost.getHostIP().getHostAddress());
960 * Add this host to a different list which will be processed
963 logger.debug("Adding the host to FailedARPReqList IP: {}", arphost.getHostIP().getHostAddress());
964 failedARPReqList.put(entry.getKey(), arphost);
967 logger.error("Inavlid arp_sent count for entry: {}", entry);
973 private class ARPRefreshHandler extends TimerTask {
979 if ((clusterContainerService != null) && !clusterContainerService.amICoordinator()) {
984 * The host probe procedure is turned off
988 if (hostsDB == null) {
989 /* hostsDB is not allocated yet */
990 logger.error("ARPRefreshHandler(): hostsDB is not allocated yet:");
993 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
994 HostNodeConnector host = entry.getValue();
995 if (host.isStaticHost()) {
996 /* this host was learned via API3, don't age it out */
1000 short arp_cntdown = host.getArpSendCountDown();
1002 if (arp_cntdown > hostRetryCount) {
1003 host.setArpSendCountDown(arp_cntdown);
1004 } else if (arp_cntdown <= 0) {
1006 * No ARP Reply received in last 2 minutes, remove this host
1007 * and inform applications
1009 removeKnownHost(entry.getKey());
1010 notifyHostLearnedOrRemoved(host, false);
1011 } else if (arp_cntdown <= hostRetryCount) {
1013 * Use the services of arphandler to check if host is still
1016 if (logger.isTraceEnabled()) {
1018 "ARP Probing ({}) for {}({})",
1019 new Object[] { arp_cntdown, host.getNetworkAddress().getHostAddress(),
1020 HexEncode.bytesToHexString(host.getDataLayerAddressBytes()) });
1022 host.setArpSendCountDown(arp_cntdown);
1023 if (hostFinder == null) {
1025 * If hostfinder is not available, then can't send the
1026 * probe. However, continue the age out the hosts since
1027 * we don't know if the host is indeed out there or not.
1029 logger.trace("ARPHandler is not avaialable, can't send the probe");
1032 hostFinder.probe(host);
1039 * Inform the controller IP to MAC binding of a host and its connectivity to
1040 * an openflow switch in terms of Node, port, and VLAN.
1042 * @param networkAddr
1043 * IP address of the host
1045 * Address MAC address of the host
1047 * NodeConnector to which host is connected
1049 * Port of the switch to which host is connected
1051 * Vlan of which this host is member of
1053 * @return Status The status object as described in {@code Status}
1054 * indicating the result of this action.
1057 protected Status addStaticHostReq(InetAddress networkAddr, byte[] dataLayerAddress, NodeConnector nc, short vlan) {
1058 if (dataLayerAddress.length != NetUtils.MACAddrLengthInBytes) {
1059 return new Status(StatusCode.BADREQUEST, "Invalid MAC address");
1063 return new Status(StatusCode.BADREQUEST, "Invalid NodeConnector");
1065 HostNodeConnector host = null;
1067 host = new HostNodeConnector(dataLayerAddress, networkAddr, nc, vlan);
1068 if (hostExists(host)) {
1069 // This host is already learned either via ARP or through a
1070 // northbound request
1071 HostNodeConnector transHost = hostsDB.get(networkAddr);
1072 transHost.setStaticHost(true);
1073 return new Status(StatusCode.SUCCESS);
1076 if (hostsDB.get(networkAddr) != null) {
1077 // There is already a host with this IP address (but behind
1078 // a different (switch, port, vlan) tuple. Return an error
1079 return new Status(StatusCode.CONFLICT, "Host with this IP already exists.");
1081 host.setStaticHost(true);
1083 * Check if the nc is an ISL port
1085 if (topologyManager != null) {
1086 if (topologyManager.isInternal(nc)) {
1087 return new Status(StatusCode.BADREQUEST, "Cannot add host on ISL port");
1091 * Before adding host, Check if the switch and the port have already
1094 if (switchManager.isNodeConnectorEnabled(nc)) {
1096 processPendingARPReqs(networkAddr);
1097 notifyHostLearnedOrRemoved(host, true);
1099 inactiveStaticHosts.put(nc, host);
1100 logger.debug("Switch or switchport is not up, adding host {} to inactive list",
1101 networkAddr.getHostName());
1103 return new Status(StatusCode.SUCCESS);
1104 } catch (ConstructionException e) {
1105 logger.error("", e);
1106 return new Status(StatusCode.INTERNALERROR, "Host could not be created");
1112 * Update the controller IP to MAC binding of a host and its connectivity to
1113 * an openflow switch in terms of switch id, switch port, and VLAN.
1115 * @param networkAddr
1116 * IP address of the host
1118 * Address MAC address of the host
1120 * NodeConnector to which host is connected
1122 * Port of the switch to which host is connected
1124 * Vlan of which this host is member of
1126 * @return Status The status object as described in {@code Status}
1127 * indicating the result of this action.
1129 public Status updateHostReq(InetAddress networkAddr, byte[] dataLayerAddress, NodeConnector nc, short vlan) {
1130 HostNodeConnector tobeUpdatedHost;
1131 HostNodeConnector host = null;
1133 if (dataLayerAddress.length != NetUtils.MACAddrLengthInBytes) {
1134 return new Status(StatusCode.BADREQUEST, "Invalid MAC address");
1138 return new Status(StatusCode.BADREQUEST, "Invalid NodeConnector");
1142 host = new HostNodeConnector(dataLayerAddress, networkAddr, nc, vlan);
1143 if (hostExists(host)) {
1144 return new Status(StatusCode.BADREQUEST, "Host already exists");
1147 if ((tobeUpdatedHost = hostsDB.get(networkAddr)) != null) {
1148 if (hostsDB.replace(networkAddr, tobeUpdatedHost, host)) {
1149 logger.debug("Host replaced from hostsDB. Old host: {} New Host: {}", tobeUpdatedHost, host);
1150 notifyHostLearnedOrRemoved(tobeUpdatedHost, false);
1151 notifyHostLearnedOrRemoved(host, true);
1152 return new Status(StatusCode.SUCCESS);
1154 logger.error("Static host replacement failed from hostsDB, Replaced Host: {}, New Host: {}",
1155 tobeUpdatedHost, host);
1156 return new Status(StatusCode.INTERNALERROR,
1157 "Host Replacement Failed due to presence of another host with same IP");
1161 // Check if the host exists in inactive hosts database
1162 if ((tobeUpdatedHost = inactiveStaticHosts.get(nc)) != null) {
1163 if (inactiveStaticHosts.replace(nc, tobeUpdatedHost, host)) {
1164 logger.debug("Host replaced from inactive hostsDB. Old host: {} New Host: {}", tobeUpdatedHost,
1166 return new Status(StatusCode.SUCCESS);
1168 logger.error("Static host replacement failed, Replaced Host: {}, New Host: {}", tobeUpdatedHost,
1170 return new Status(StatusCode.INTERNALERROR,
1171 "Host Replacement Failed due to presence of another host with same IP");
1175 // Host doesn't exist
1176 return new Status(StatusCode.BADREQUEST, "Host doesn't exists, can't update");
1177 } catch (ConstructionException e) {
1178 logger.error("", e);
1179 return new Status(StatusCode.INTERNALERROR, "host object creation failure");
1184 * Remove from the controller IP to MAC binding of a host and its
1185 * connectivity to an openflow switch
1187 * @param networkAddr
1188 * IP address of the host
1190 * @return boolean true if the host was removed successfully, false
1194 public Status removeStaticHostReq(InetAddress networkAddress) {
1195 // Check if host is in active hosts database
1196 HostNodeConnector host = getHostFromOnActiveDB(networkAddress);
1199 if (!host.isStaticHost()) {
1200 return new Status(StatusCode.FORBIDDEN, "Host " + networkAddress.getHostName() + " is not static");
1202 // Remove and notify
1203 notifyHostLearnedOrRemoved(host, false);
1204 removeKnownHost(networkAddress);
1205 return new Status(StatusCode.SUCCESS, null);
1208 // Check if host is in inactive hosts database
1209 Entry<NodeConnector, HostNodeConnector> entry = getHostFromInactiveDB(networkAddress);
1210 if (entry != null) {
1211 host = entry.getValue();
1213 if (!host.isStaticHost()) {
1214 return new Status(StatusCode.FORBIDDEN, "Host " + networkAddress.getHostName() + " is not static");
1216 this.removeHostFromInactiveDB(networkAddress);
1217 return new Status(StatusCode.SUCCESS, null);
1220 // Host is neither in active nor inactive hosts database
1221 return new Status(StatusCode.NOTFOUND, "Host does not exist");
1225 public void modeChangeNotify(Node node, boolean proactive) {
1226 logger.debug("Set Switch {} Mode to {}", node.getID(), proactive);
1230 public void notifyNode(Node node, UpdateType type, Map<String, Property> propMap) {
1237 logger.debug("Received removed node {}", node);
1238 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
1239 HostNodeConnector host = entry.getValue();
1240 if (host.getnodeconnectorNode().equals(node)) {
1241 logger.debug("Node: {} is down, remove from Hosts_DB", node);
1242 removeKnownHost(entry.getKey());
1243 notifyHostLearnedOrRemoved(host, false);
1253 public void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map<String, Property> propMap) {
1254 if (nodeConnector == null) {
1266 State state = (State) propMap.get(State.StatePropName);
1267 if ((state != null) && (state.getValue() == State.EDGE_UP)) {
1276 handleNodeConnectorStatusUp(nodeConnector);
1278 handleNodeConnectorStatusDown(nodeConnector);
1283 public Status addStaticHost(String networkAddress, String dataLayerAddress, NodeConnector nc, String vlan) {
1285 InetAddress ip = InetAddress.getByName(networkAddress);
1287 if (vlan != null && !vlan.isEmpty()) {
1288 vl = Short.decode(vlan);
1289 if (vl < 1 || vl > 4095) {
1290 return new Status(StatusCode.BADREQUEST, "Host vlan out of range [1 - 4095]");
1294 return addStaticHostReq(ip, HexEncode.bytesFromHexString(dataLayerAddress), nc, vl);
1296 } catch (UnknownHostException e) {
1297 logger.debug("Invalid host IP specified when adding static host", e);
1298 return new Status(StatusCode.BADREQUEST, "Invalid Host IP Address");
1299 } catch (NumberFormatException nfe) {
1300 logger.debug("Invalid host vlan or MAC specified when adding static host", nfe);
1301 return new Status(StatusCode.BADREQUEST, "Invalid Host vLan/MAC");
1306 public Status removeStaticHost(String networkAddress) {
1308 InetAddress address = InetAddress.getByName(networkAddress);
1309 return removeStaticHostReq(address);
1310 } catch (UnknownHostException e) {
1311 logger.debug("Invalid IP Address when trying to remove host", e);
1312 return new Status(StatusCode.BADREQUEST, "Invalid IP Address when trying to remove host");
1316 private void handleNodeConnectorStatusUp(NodeConnector nodeConnector) {
1318 HostNodeConnector host = null;
1320 logger.trace("handleNodeConnectorStatusUp {}", nodeConnector);
1322 for (Entry<InetAddress, ARPPending> entry : failedARPReqList.entrySet()) {
1323 arphost = entry.getValue();
1324 logger.trace("Sending the ARP from FailedARPReqList fors IP: {}", arphost.getHostIP().getHostAddress());
1325 if (hostFinder == null) {
1326 logger.warn("ARPHandler is not available at interface up");
1327 logger.warn("Since this event is missed, host(s) connected to interface {} may not be discovered",
1332 // Send a broadcast ARP only on the interface which just came up.
1333 // Use hostFinder's "probe" method
1335 byte[] dataLayerAddress = NetUtils.getBroadcastMACAddr();
1336 host = new HostNodeConnector(dataLayerAddress, arphost.getHostIP(), nodeConnector, (short) 0);
1337 hostFinder.probe(host);
1338 } catch (ConstructionException e) {
1339 logger.debug("HostNodeConnector couldn't be created for Host: {}, NodeConnector: {}",
1340 arphost.getHostIP(), nodeConnector);
1341 logger.error("", e);
1345 host = inactiveStaticHosts.get(nodeConnector);
1347 inactiveStaticHosts.remove(nodeConnector);
1349 processPendingARPReqs(host.getNetworkAddress());
1350 notifyHostLearnedOrRemoved(host, true);
1354 private void handleNodeConnectorStatusDown(NodeConnector nodeConnector) {
1355 logger.trace("handleNodeConnectorStatusDown {}", nodeConnector);
1357 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
1358 HostNodeConnector host = entry.getValue();
1359 if (host.getnodeConnector().equals(nodeConnector)) {
1360 logger.debug(" NodeConnector: {} is down, remove from Hosts_DB", nodeConnector);
1361 removeKnownHost(entry.getKey());
1362 notifyHostLearnedOrRemoved(host, false);
1367 void setClusterContainerService(IClusterContainerServices s) {
1368 logger.debug("Cluster Service set");
1369 this.clusterContainerService = s;
1372 void unsetClusterContainerService(IClusterContainerServices s) {
1373 if (this.clusterContainerService == s) {
1374 logger.debug("Cluster Service removed!");
1375 this.clusterContainerService = null;
1379 void setSwitchManager(ISwitchManager s) {
1380 logger.debug("SwitchManager set");
1381 this.switchManager = s;
1384 void unsetSwitchManager(ISwitchManager s) {
1385 if (this.switchManager == s) {
1386 logger.debug("SwitchManager removed!");
1387 this.switchManager = null;
1391 public String getContainerName() {
1392 if (containerName == null) {
1393 return GlobalConstants.DEFAULT.toString();
1395 return containerName;
1399 * Function called by the dependency manager when all the required
1400 * dependencies are satisfied
1403 void init(Component c) {
1404 Dictionary<?, ?> props = c.getServiceProperties();
1405 if (props != null) {
1406 this.containerName = (String) props.get("containerName");
1407 logger.debug("Running containerName: {}", this.containerName);
1409 // In the Global instance case the containerName is empty
1410 this.containerName = "";
1416 * Function called by the dependency manager when at least one dependency
1417 * become unsatisfied or when the component is shutting down because for
1418 * example bundle is being stopped.
1425 * Function called by dependency manager after "init ()" is called and after
1426 * the services provided by the class are registered in the service registry
1430 registerWithOSGIConsole();
1434 * Function called by the dependency manager before the services exported by
1435 * the component are unregistered, this will be followed by a "destroy ()"
1444 arpRefreshTimer.cancel();
1446 executor.shutdownNow();
1450 public void edgeOverUtilized(Edge edge) {
1455 public void edgeUtilBackToNormal(Edge edge) {
1460 public void entryCreated(InetAddress key, String cacheName, boolean originLocal) {
1464 processPendingARPReqs(key);
1468 public void entryUpdated(InetAddress key, HostNodeConnector new_value, String cacheName, boolean originLocal) {
1472 public void entryDeleted(InetAddress key, String cacheName, boolean originLocal) {
1475 private void registerWithOSGIConsole() {
1476 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
1477 bundleContext.registerService(CommandProvider.class.getName(), this, null);
1481 public String getHelp() {
1485 public void _dumpPendingARPReqList(CommandInterpreter ci) {
1487 for (Entry<InetAddress, ARPPending> entry : ARPPendingList.entrySet()) {
1488 arphost = entry.getValue();
1489 ci.println(arphost.getHostIP().toString());
1493 public void _dumpFailedARPReqList(CommandInterpreter ci) {
1495 for (Entry<InetAddress, ARPPending> entry : failedARPReqList.entrySet()) {
1496 arphost = entry.getValue();
1497 ci.println(arphost.getHostIP().toString());