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.opendaylight.controller.clustering.services.CacheConfigException;
33 import org.opendaylight.controller.clustering.services.CacheExistException;
34 import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
35 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
36 import org.opendaylight.controller.clustering.services.IClusterServices;
37 import org.opendaylight.controller.hosttracker.IfHostListener;
38 import org.opendaylight.controller.hosttracker.IfIptoHost;
39 import org.opendaylight.controller.hosttracker.IfNewHostNotify;
40 import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
41 import org.opendaylight.controller.hosttracker.hostAware.IHostFinder;
42 import org.opendaylight.controller.sal.core.ConstructionException;
43 import org.opendaylight.controller.sal.core.Edge;
44 import org.opendaylight.controller.sal.core.Host;
45 import org.opendaylight.controller.sal.core.Node;
46 import org.opendaylight.controller.sal.core.NodeConnector;
47 import org.opendaylight.controller.sal.core.Property;
48 import org.opendaylight.controller.sal.core.State;
49 import org.opendaylight.controller.sal.core.Tier;
50 import org.opendaylight.controller.sal.core.UpdateType;
51 import org.opendaylight.controller.sal.packet.address.DataLinkAddress;
52 import org.opendaylight.controller.sal.packet.address.EthernetAddress;
53 import org.opendaylight.controller.sal.topology.TopoEdgeUpdate;
54 import org.opendaylight.controller.sal.utils.GlobalConstants;
55 import org.opendaylight.controller.sal.utils.HexEncode;
56 import org.opendaylight.controller.sal.utils.NetUtils;
57 import org.opendaylight.controller.sal.utils.NodeCreator;
58 import org.opendaylight.controller.sal.utils.Status;
59 import org.opendaylight.controller.sal.utils.StatusCode;
60 import org.opendaylight.controller.switchmanager.IInventoryListener;
61 import org.opendaylight.controller.switchmanager.ISwitchManager;
62 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
63 import org.opendaylight.controller.switchmanager.Subnet;
64 import org.opendaylight.controller.topologymanager.ITopologyManager;
65 import org.opendaylight.controller.topologymanager.ITopologyManagerAware;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
70 * @file HostTracker.java This class tracks the location of IP Hosts as to which
71 * Switch, Port, VLAN, they are connected to, as well as their MAC
72 * address. This is done dynamically as well as statically. The dynamic
73 * mechanism consists of listening to ARP messages as well sending ARP
74 * requests. Static mechanism consists of Northbound APIs to add or remove
75 * the hosts from the local database. ARP aging is also implemented to age
76 * out dynamically learned hosts. Interface methods are provided for other
77 * applications to 1. Query the local database for a single host 2. Get a
78 * list of all hosts 3. Get notification if a host is learned/added or
79 * removed the database
82 public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAware, IInventoryListener,
83 ITopologyManagerAware, ICacheUpdateAware<InetAddress, HostNodeConnector> {
84 static final String ACTIVE_HOST_CACHE = "hostTrackerAH";
85 static final String INACTIVE_HOST_CACHE = "hostTrackerIH";
86 private static final Logger logger = LoggerFactory.getLogger(HostTracker.class);
87 private IHostFinder hostFinder;
88 private ConcurrentMap<InetAddress, HostNodeConnector> hostsDB;
90 * Following is a list of hosts which have been requested by NB APIs to be
91 * added, but either the switch or the port is not sup, so they will be
92 * added here until both come up
94 private ConcurrentMap<NodeConnector, HostNodeConnector> inactiveStaticHosts;
95 private final Set<IfNewHostNotify> newHostNotify = Collections.synchronizedSet(new HashSet<IfNewHostNotify>());
97 private ITopologyManager topologyManager;
98 private IClusterContainerServices clusterContainerService = null;
99 private ISwitchManager switchManager = null;
101 private Timer arpRefreshTimer;
102 private String containerName = null;
103 private ExecutorService executor;
104 private static class ARPPending {
105 protected InetAddress hostIP;
106 protected short sent_count;
107 protected HostTrackerCallable hostTrackerCallable;
109 public InetAddress getHostIP() {
113 public short getSent_count() {
117 public HostTrackerCallable getHostTrackerCallable() {
118 return hostTrackerCallable;
121 public void setHostIP(InetAddress networkAddr) {
122 this.hostIP = networkAddr;
125 public void setSent_count(short count) {
126 this.sent_count = count;
129 public void setHostTrackerCallable(HostTrackerCallable callable) {
130 hostTrackerCallable = callable;
134 // This list contains the hosts for which ARP requests are being sent
136 private final List<ARPPending> ARPPendingList = new ArrayList<HostTracker.ARPPending>();
138 * This list below contains the hosts which were initially in ARPPendingList
139 * above, but ARP response didn't come from there hosts after multiple
140 * attempts over 8 seconds. The assumption is that the response didn't come
141 * back due to one of the following possibilities: 1. The L3 interface
142 * wasn't created for this host in the controller. This would cause
143 * arphandler not to know where to send the ARP 2. The host facing port is
144 * down 3. The IP host doesn't exist or is not responding to ARP requests
146 * Conditions 1 and 2 above can be recovered if ARP is sent when the
147 * relevant L3 interface is added or the port facing host comes up. Whenever
148 * L3 interface is added or host facing port comes up, ARP will be sent to
149 * hosts in this list.
151 * We can't recover from condition 3 above
153 private final List<ARPPending> failedARPReqList = new ArrayList<HostTracker.ARPPending>();
155 public HostTracker() {
158 private void startUp() {
163 timer.schedule(new OutStandingARPHandler(), 4000, 4000);
164 executor = Executors.newFixedThreadPool(2);
165 /* ARP Refresh Timer to go off every 5 seconds to implement ARP aging */
166 arpRefreshTimer = new Timer();
167 arpRefreshTimer.schedule(new ARPRefreshHandler(), 5000, 5000);
168 logger.debug("startUp: Caches created, timers started");
171 @SuppressWarnings("deprecation")
172 private void allocateCache() {
173 if (this.clusterContainerService == null) {
174 logger.error("un-initialized clusterContainerService, can't create cache");
177 logger.debug("Creating Cache for HostTracker");
179 this.clusterContainerService.createCache(ACTIVE_HOST_CACHE,
180 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
181 this.clusterContainerService.createCache(INACTIVE_HOST_CACHE,
182 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
183 } catch (CacheConfigException cce) {
184 logger.error("Cache couldn't be created for HostTracker - check cache mode");
185 } catch (CacheExistException cce) {
186 logger.error("Cache for HostTracker already exists, destroy and recreate");
188 logger.debug("Cache successfully created for HostTracker");
191 @SuppressWarnings({ "unchecked", "deprecation" })
192 private void retrieveCache() {
193 if (this.clusterContainerService == null) {
194 logger.error("un-initialized clusterContainerService, can't retrieve cache");
197 logger.debug("Retrieving cache for HostTrackerAH");
198 hostsDB = (ConcurrentMap<InetAddress, HostNodeConnector>) this.clusterContainerService
199 .getCache(ACTIVE_HOST_CACHE);
200 if (hostsDB == null) {
201 logger.error("Cache couldn't be retrieved for HostTracker");
203 logger.debug("Cache was successfully retrieved for HostTracker");
204 logger.debug("Retrieving cache for HostTrackerIH");
205 inactiveStaticHosts = (ConcurrentMap<NodeConnector, HostNodeConnector>) this.clusterContainerService
206 .getCache(INACTIVE_HOST_CACHE);
207 if (inactiveStaticHosts == null) {
208 logger.error("Cache couldn't be retrieved for HostTrackerIH");
210 logger.debug("Cache was successfully retrieved for HostTrackerIH");
213 public void nonClusterObjectCreate() {
214 hostsDB = new ConcurrentHashMap<InetAddress, HostNodeConnector>();
215 inactiveStaticHosts = new ConcurrentHashMap<NodeConnector, HostNodeConnector>();
219 public void shutDown() {
222 public void setnewHostNotify(IfNewHostNotify obj) {
223 this.newHostNotify.add(obj);
226 public void unsetnewHostNotify(IfNewHostNotify obj) {
227 this.newHostNotify.remove(obj);
230 public void setArpHandler(IHostFinder hostFinder) {
231 this.hostFinder = hostFinder;
234 public void unsetArpHandler(IHostFinder hostFinder) {
235 if (this.hostFinder == hostFinder) {
236 logger.debug("Arp Handler Service removed!");
237 this.hostFinder = null;
241 public void setTopologyManager(ITopologyManager s) {
242 this.topologyManager = s;
245 public void unsetTopologyManager(ITopologyManager s) {
246 if (this.topologyManager == s) {
247 logger.debug("Topology Manager Service removed!");
248 this.topologyManager = null;
252 private boolean hostExists(HostNodeConnector host) {
253 HostNodeConnector lhost = hostsDB.get(host.getNetworkAddress());
254 return host.equals(lhost);
257 private HostNodeConnector getHostFromOnActiveDB(InetAddress networkAddress) {
258 return hostsDB.get(networkAddress);
261 private Entry<NodeConnector, HostNodeConnector> getHostFromInactiveDB(InetAddress networkAddress) {
262 for (Entry<NodeConnector, HostNodeConnector> entry : inactiveStaticHosts.entrySet()) {
263 if (entry.getValue().equalsByIP(networkAddress)) {
264 logger.debug("getHostFromInactiveDB(): Inactive Host found for IP:{} ", networkAddress.getHostAddress());
268 logger.debug("getHostFromInactiveDB() Inactive Host Not found for IP: {}", networkAddress.getHostAddress());
272 private void removeHostFromInactiveDB(InetAddress networkAddress) {
273 NodeConnector nodeConnector = null;
274 for (Entry<NodeConnector, HostNodeConnector> entry : inactiveStaticHosts.entrySet()) {
275 if (entry.getValue().equalsByIP(networkAddress)) {
276 nodeConnector = entry.getKey();
280 if (nodeConnector != null) {
281 inactiveStaticHosts.remove(nodeConnector);
282 logger.debug("removeHostFromInactiveDB(): Host Removed for IP: {}", networkAddress.getHostAddress());
285 logger.debug("removeHostFromInactiveDB(): Host Not found for IP: {}", networkAddress.getHostAddress());
288 protected boolean hostMoved(HostNodeConnector host) {
289 if (hostQuery(host.getNetworkAddress()) != null) {
296 public HostNodeConnector hostQuery(InetAddress networkAddress) {
297 return hostsDB.get(networkAddress);
301 public Future<HostNodeConnector> discoverHost(InetAddress networkAddress) {
302 if (executor == null) {
303 logger.error("discoverHost: Null executor");
306 Callable<HostNodeConnector> worker = new HostTrackerCallable(this, networkAddress);
307 Future<HostNodeConnector> submit = executor.submit(worker);
312 public HostNodeConnector hostFind(InetAddress networkAddress) {
314 * Sometimes at boot with containers configured in the startup we hit
315 * this path (from TIF) when hostFinder has not been set yet Caller
316 * already handles the null return
319 if (hostFinder == null) {
320 logger.debug("Exiting hostFind, null hostFinder");
324 HostNodeConnector host = hostQuery(networkAddress);
326 logger.debug("hostFind(): Host found for IP: {}", networkAddress.getHostAddress());
330 /* Add this host to ARPPending List for any potential retries */
332 AddtoARPPendingList(networkAddress);
333 logger.debug("hostFind(): Host Not Found for IP: {}, Inititated Host Discovery ...",
334 networkAddress.getHostAddress());
336 /* host is not found, initiate a discovery */
338 hostFinder.find(networkAddress);
343 public Set<HostNodeConnector> getAllHosts() {
344 Set<HostNodeConnector> allHosts = new HashSet<HostNodeConnector>();
345 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
346 HostNodeConnector host = entry.getValue();
349 logger.debug("Exiting getAllHosts, Found {} Hosts", allHosts.size());
354 public Set<HostNodeConnector> getActiveStaticHosts() {
355 Set<HostNodeConnector> list = new HashSet<HostNodeConnector>();
356 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
357 HostNodeConnector host = entry.getValue();
358 if (host.isStaticHost()) {
362 logger.debug("getActiveStaticHosts(): Found {} Hosts", list.size());
367 public Set<HostNodeConnector> getInactiveStaticHosts() {
368 Set<HostNodeConnector> list = new HashSet<HostNodeConnector>();
369 for (Entry<NodeConnector, HostNodeConnector> entry : inactiveStaticHosts.entrySet()) {
370 list.add(entry.getValue());
372 logger.debug("getInactiveStaticHosts(): Found {} Hosts", list.size());
376 private void AddtoARPPendingList(InetAddress networkAddr) {
377 ARPPending arphost = new ARPPending();
379 arphost.setHostIP(networkAddr);
380 arphost.setSent_count((short) 1);
381 ARPPendingList.add(arphost);
382 logger.debug("Host Added to ARPPending List, IP: {}", networkAddr);
385 private void removePendingARPFromList(int index) {
386 if (index >= ARPPendingList.size()) {
387 logger.warn("removePendingARPFromList(): index greater than the List. Size:{}, Index:{}",
388 ARPPendingList.size(), index);
391 ARPPending arphost = ARPPendingList.remove(index);
392 HostTrackerCallable htCallable = arphost.getHostTrackerCallable();
393 if (htCallable != null)
397 public void setCallableOnPendingARP(InetAddress networkAddr, HostTrackerCallable callable) {
399 for (int i = 0; i < ARPPendingList.size(); i++) {
400 arphost = ARPPendingList.get(i);
401 if (arphost.getHostIP().equals(networkAddr)) {
402 arphost.setHostTrackerCallable(callable);
407 private void processPendingARPReqs(InetAddress networkAddr) {
410 for (int i = 0; i < ARPPendingList.size(); i++) {
411 arphost = ARPPendingList.get(i);
412 if (arphost.getHostIP().equals(networkAddr)) {
414 * An ARP was sent for this host. The address is learned, remove
417 removePendingARPFromList(i);
418 logger.debug("Host Removed from ARPPending List, IP: {}", networkAddr);
424 * It could have been a host from the FailedARPReqList
427 for (int i = 0; i < failedARPReqList.size(); i++) {
428 arphost = failedARPReqList.get(i);
429 if (arphost.getHostIP().equals(networkAddr)) {
431 * An ARP was sent for this host. The address is learned, remove
434 failedARPReqList.remove(i);
435 logger.debug("Host Removed from FailedARPReqList List, IP: {}", networkAddr);
442 private void learnNewHost(HostNodeConnector host) {
443 host.initArpSendCountDown();
444 HostNodeConnector rHost = hostsDB.putIfAbsent(host.getNetworkAddress(), host);
446 // Another host is already learned for this IP address, replace it
447 replaceHost(host.getNetworkAddress(), rHost, host);
449 logger.debug("New Host Learned: MAC: {} IP: {}", HexEncode.bytesToHexString(host
450 .getDataLayerAddressBytes()), host.getNetworkAddress().getHostAddress());
454 private void replaceHost(InetAddress networkAddr, HostNodeConnector removedHost, HostNodeConnector newHost) {
455 newHost.initArpSendCountDown();
456 if (hostsDB.replace(networkAddr, removedHost, newHost)) {
457 logger.debug("Host move occurred: Old Host IP:{}, New Host IP: {}", removedHost.getNetworkAddress()
458 .getHostAddress(), newHost.getNetworkAddress().getHostAddress());
459 logger.debug("Old Host MAC: {}, New Host MAC: {}",
460 HexEncode.bytesToHexString(removedHost.getDataLayerAddressBytes()),
461 HexEncode.bytesToHexString(newHost.getDataLayerAddressBytes()));
462 // Display the Old and New HostNodeConnectors also
463 logger.debug("Old {}, New {}", removedHost, newHost);
466 * Host replacement has failed, do the recovery
468 hostsDB.put(networkAddr, newHost);
469 logger.error("Host replacement failed. Overwrite the host. Repalced Host: {}, New Host: {}", removedHost,
472 notifyHostLearnedOrRemoved(removedHost, false);
473 notifyHostLearnedOrRemoved(newHost, true);
474 if (!newHost.isStaticHost()) {
475 processPendingARPReqs(networkAddr);
480 private void removeKnownHost(InetAddress key) {
481 HostNodeConnector host = hostsDB.get(key);
483 logger.debug("Removing Host: IP:{}", host.getNetworkAddress().getHostAddress());
486 logger.error("removeKnownHost(): Host for IP address {} not found in hostsDB", key.getHostAddress());
490 private class NotifyHostThread extends Thread {
492 private final HostNodeConnector host;
494 public NotifyHostThread(HostNodeConnector h) {
500 HostNodeConnector removedHost = null;
501 InetAddress networkAddr = host.getNetworkAddress();
503 /* Check for Host Move case */
504 if (hostMoved(host)) {
506 * Host has been moved from one location (switch,port, MAC, or
507 * VLAN) to another. Replace the existing host and its previous
508 * location parameters with new information, and notify the
509 * applications listening to host move.
511 removedHost = hostsDB.get(networkAddr);
512 if (removedHost != null) {
513 replaceHost(networkAddr, removedHost, host);
516 logger.error("Host to be removed not found in hostsDB. Host {}", removedHost);
520 if (removedHost == null) {
525 /* check if there is an outstanding request for this host */
526 processPendingARPReqs(networkAddr);
527 notifyHostLearnedOrRemoved(host, true);
532 public void hostListener(HostNodeConnector host) {
534 logger.debug("ARP received for Host: IP {}, MAC {}, {}", host.getNetworkAddress().getHostAddress(),
535 HexEncode.bytesToHexString(host.getDataLayerAddressBytes()), host);
536 if (hostExists(host)) {
537 HostNodeConnector existinghost = hostsDB.get(host.getNetworkAddress());
538 existinghost.initArpSendCountDown();
541 new NotifyHostThread(host).start();
544 // Notify whoever is interested that a new host was learned (dynamically or
546 private void notifyHostLearnedOrRemoved(HostNodeConnector host, boolean add) {
547 // Update listeners if any
548 if (newHostNotify != null) {
549 logger.debug("Notifying Applications for Host {} Being {}", host.getNetworkAddress().getHostAddress(),
550 add ? "Added" : "Deleted");
551 synchronized (this.newHostNotify) {
552 for (IfNewHostNotify ta : newHostNotify) {
555 ta.notifyHTClient(host);
557 ta.notifyHTClientHostRemoved(host);
559 } catch (Exception e) {
560 logger.error("Exception on callback", e);
565 logger.error("notifyHostLearnedOrRemoved(): New host notify is null");
568 // Topology update is for some reason outside of listeners registry
570 Node node = host.getnodeconnectorNode();
572 NodeConnector p = host.getnodeConnector();
574 DataLinkAddress dla = new EthernetAddress(host.getDataLayerAddressBytes());
575 h = new Host(dla, host.getNetworkAddress());
576 } catch (ConstructionException ce) {
581 if (topologyManager != null && p != null && h != null) {
582 logger.debug("Notifying Topology Manager for Host {} Being {}", h.getNetworkAddress().getHostAddress(),
583 add ? "Added" : "Deleted");
585 Tier tier = new Tier(1);
586 switchManager.setNodeProp(node, tier);
587 topologyManager.updateHostLink(p, h, UpdateType.ADDED, null);
589 // No need to reset the tiering if no other hosts are currently
591 // If this switch was discovered to be an access switch, it
592 // still is even if the host is down
593 Tier tier = new Tier(0);
594 switchManager.setNodeProp(node, tier);
595 topologyManager.updateHostLink(p, h, UpdateType.REMOVED, null);
601 * When a new Host is learnt by the hosttracker module, it places the
602 * directly connected Node in Tier-1 & using this function, updates the Tier
603 * value for all other Nodes in the network hierarchy.
605 * This is a recursive function and it takes care of updating the Tier value
606 * for all the connected and eligible Nodes.
609 * Node that represents one of the Vertex in the Topology Graph.
611 * The Tier on which n belongs
613 private void updateSwitchTiers(Node n, int currentTier) {
614 Map<Node, Set<Edge>> ndlinks = topologyManager.getNodeEdges();
615 if (ndlinks == null) {
616 logger.debug("updateSwitchTiers(): ndlinks null for Node: {}, Tier:{}", n, currentTier);
619 Set<Edge> links = ndlinks.get(n);
621 logger.debug("updateSwitchTiers(): links null for ndlinks:{}", ndlinks);
624 ArrayList<Node> needsVisiting = new ArrayList<Node>();
625 for (Edge lt : links) {
626 if (!lt.getHeadNodeConnector().getType().equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) {
627 // We don't want to work on Node that are not openflow
631 Node dstNode = lt.getHeadNodeConnector().getNode();
632 if (switchNeedsTieringUpdate(dstNode, currentTier + 1)) {
633 Tier t = new Tier(currentTier + 1);
634 switchManager.setNodeProp(dstNode, t);
635 needsVisiting.add(dstNode);
640 * Due to the nature of the problem, having a separate loop for nodes
641 * that needs visiting provides a decent walk optimization.
643 for (Node node : needsVisiting) {
644 updateSwitchTiers(node, currentTier + 1);
649 * Internal convenience routine to check the eligibility of a Switch for a
650 * Tier update. Any Node with Tier=0 or a Tier value that is greater than
651 * the new Tier Value is eligible for the update.
654 * Node for which the Tier update eligibility is checked
657 * @return <code>true</code> if the Node is eligible for Tier Update
658 * <code>false</code> otherwise
661 private boolean switchNeedsTieringUpdate(Node n, int tier) {
663 logger.error("switchNeedsTieringUpdate(): Null node for tier: {}", tier);
667 * Node could have gone down
669 if (!switchManager.getNodes().contains(n)) {
672 // This is the case where Tier was never set for this node
673 Tier t = (Tier) switchManager.getNodeProp(n, Tier.TierPropName);
676 if (t.getValue() == 0)
678 else if (t.getValue() > tier)
684 * Internal convenience routine to clear all the Tier values to 0. This
685 * cleanup is performed during cases such as Topology Change where the
686 * existing Tier values might become incorrect
688 private void clearTiers() {
689 Set<Node> nodes = null;
690 if (switchManager == null) {
691 logger.error("clearTiers(): Null switchManager");
694 nodes = switchManager.getNodes();
696 for (Node n : nodes) {
697 Tier t = new Tier(0);
698 switchManager.setNodeProp(n, t);
703 * Internal convenience routine to print the hierarchies of switches.
705 @SuppressWarnings("unused")
706 private void logHierarchies(ArrayList<ArrayList<String>> hierarchies) {
707 String hierarchyString = null;
709 for (ArrayList<String> hierarchy : hierarchies) {
710 StringBuffer buf = new StringBuffer();
711 buf.append("Hierarchy#" + num + " : ");
712 for (String switchName : hierarchy) {
713 buf.append(switchName + "/");
715 logger.debug("{} -> {}", getContainerName(), buf);
721 * getHostNetworkHierarchy is the Back-end routine for the North-Bound API
722 * that returns the Network Hierarchy for a given Host. This API is
723 * typically used by applications like Hadoop for Rack Awareness
727 * IP-Address of the host/node.
728 * @return Network Hierarchies represented by an Array of Array (of
729 * Switch-Ids as String).
732 public List<List<String>> getHostNetworkHierarchy(InetAddress hostAddress) {
733 HostNodeConnector host = hostQuery(hostAddress);
737 List<List<String>> hierarchies = new ArrayList<List<String>>();
738 ArrayList<String> currHierarchy = new ArrayList<String>();
739 hierarchies.add(currHierarchy);
741 Node node = host.getnodeconnectorNode();
742 updateCurrentHierarchy(node, currHierarchy, hierarchies);
747 * dpidToHostNameHack is a hack function for Cisco Live Hadoop Demo. Mininet
748 * is used as the network for Hadoop Demos & in order to give a meaningful
749 * rack-awareness switch names, the DPID is organized in ASCII Characters
750 * and retrieved as string.
754 * @return Ascii String represented by the DPID.
756 private String dpidToHostNameHack(long dpid) {
757 String hex = Long.toHexString(dpid);
759 StringBuffer sb = new StringBuffer();
761 for (int i = 0; i < hex.length(); i++) {
762 result = (int) ((dpid >> (i * 8)) & 0xff);
767 sb.append(String.format("%c", result));
769 return sb.reverse().toString();
773 * A convenient recursive routine to obtain the Hierarchy of Switches.
776 * Current Node in the Recursive routine.
777 * @param currHierarchy
778 * Array of Nodes that make this hierarchy on which the Current
780 * @param fullHierarchy
781 * Array of multiple Hierarchies that represent a given host.
783 @SuppressWarnings("unchecked")
784 private void updateCurrentHierarchy(Node node, ArrayList<String> currHierarchy, List<List<String>> fullHierarchy) {
785 // currHierarchy.add(String.format("%x", currSw.getId()));
786 currHierarchy.add(dpidToHostNameHack((Long) node.getID()));
787 ArrayList<String> currHierarchyClone = (ArrayList<String>) currHierarchy.clone(); // Shallow
792 Map<Node, Set<Edge>> ndlinks = topologyManager.getNodeEdges();
793 if (ndlinks == null) {
794 logger.debug("updateCurrentHierarchy(): topologyManager returned null ndlinks for node: {}", node);
797 Node n = NodeCreator.createOFNode((Long) node.getID());
798 Set<Edge> links = ndlinks.get(n);
800 logger.debug("updateCurrentHierarchy(): Null links for ndlinks");
803 for (Edge lt : links) {
804 if (!lt.getHeadNodeConnector().getType().equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) {
805 // We don't want to work on Node that are not openflow
809 Node dstNode = lt.getHeadNodeConnector().getNode();
811 Tier nodeTier = (Tier) switchManager.getNodeProp(node, Tier.TierPropName);
812 Tier dstNodeTier = (Tier) switchManager.getNodeProp(dstNode, Tier.TierPropName);
813 if (dstNodeTier.getValue() > nodeTier.getValue()) {
814 ArrayList<String> buildHierarchy = currHierarchy;
815 if (currHierarchy.size() > currHierarchyClone.size()) {
816 buildHierarchy = (ArrayList<String>) currHierarchyClone.clone(); // Shallow
820 fullHierarchy.add(buildHierarchy);
822 updateCurrentHierarchy(dstNode, buildHierarchy, fullHierarchy);
827 private void debugEdgeUpdate(Edge e, UpdateType type, Set<Property> props) {
829 Short srcPort = null;
831 Short dstPort = null;
832 boolean added = false;
833 String srcType = null;
834 String dstType = null;
836 if (e == null || type == null) {
837 logger.error("Edge or Update type are null!");
840 srcType = e.getTailNodeConnector().getType();
841 dstType = e.getHeadNodeConnector().getType();
843 if (srcType.equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) {
844 logger.debug("Skip updates for {}", e);
848 if (!srcType.equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) {
849 logger.debug("For now we cannot handle updates for non-openflow nodes");
853 if (dstType.equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) {
854 logger.debug("Skip updates for {}", e);
858 if (!dstType.equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) {
859 logger.debug("For now we cannot handle updates for non-openflow nodes");
863 // At this point we know we got an openflow update, so
864 // lets fill everything accordingly.
865 srcNid = (Long) e.getTailNodeConnector().getNode().getID();
866 srcPort = (Short) e.getTailNodeConnector().getID();
867 dstNid = (Long) e.getHeadNodeConnector().getNode().getID();
868 dstPort = (Short) e.getHeadNodeConnector().getID();
870 // Now lets update the added flag
881 logger.debug("HostTracker Topology linkUpdate handling src:{}[port {}] dst:{}[port {}] added: {}",
882 new Object[] { srcNid, srcPort, dstNid, dstPort, added });
886 public void edgeUpdate(List<TopoEdgeUpdate> topoedgeupdateList) {
887 if (logger.isDebugEnabled()) {
888 for (TopoEdgeUpdate topoEdgeUpdate : topoedgeupdateList) {
889 Edge e = topoEdgeUpdate.getEdge();
890 Set<Property> p = topoEdgeUpdate.getProperty();
891 UpdateType type = topoEdgeUpdate.getUpdateType();
893 debugEdgeUpdate(e, type, p);
899 public void subnetNotify(Subnet sub, boolean add) {
900 logger.debug("Received subnet notification: {} add={}", sub, add);
902 for (int i = 0; i < failedARPReqList.size(); i++) {
904 arphost = failedARPReqList.get(i);
905 if (hostFinder == null) {
906 logger.warn("ARPHandler Services are not available on subnet addition");
909 logger.debug("Sending the ARP from FailedARPReqList fors IP: {}", arphost.getHostIP().getHostAddress());
910 hostFinder.find(arphost.getHostIP());
915 class OutStandingARPHandler extends TimerTask {
919 /* This routine runs every 4 seconds */
920 for (int i = 0; i < ARPPendingList.size(); i++) {
921 arphost = ARPPendingList.get(i);
922 if (arphost.getSent_count() < switchManager.getHostRetryCount()) {
924 * No reply has been received of first ARP Req, send the
925 * next one. Before sending the ARP, check if ARPHandler
926 * is available or not
928 if (hostFinder == null) {
929 logger.warn("ARPHandler Services are not available for Outstanding ARPs");
932 hostFinder.find(arphost.getHostIP());
933 arphost.sent_count++;
934 logger.debug("ARP Sent from ARPPending List, IP: {}", arphost.getHostIP().getHostAddress());
935 } else if (arphost.getSent_count() >= switchManager.getHostRetryCount()) {
937 * ARP requests have been sent without receiving a
938 * reply, remove this from the pending list
940 removePendingARPFromList(i);
941 logger.debug("ARP reply not received after multiple attempts, removing from Pending List IP: {}",
942 arphost.getHostIP().getHostAddress());
944 * Add this host to a different list which will be processed
947 logger.debug("Adding the host to FailedARPReqList IP: {}", arphost.getHostIP().getHostAddress());
948 failedARPReqList.add(arphost);
951 logger.error("Inavlid arp_sent count for entry at index: {}", i);
957 private class ARPRefreshHandler extends TimerTask {
959 @SuppressWarnings("deprecation")
961 if ((clusterContainerService != null) && !clusterContainerService.amICoordinator()) {
964 if ((switchManager != null) && !switchManager.isHostRefreshEnabled()) {
966 * The host probe procedure was disabled by CLI
970 if (hostsDB == null) {
971 /* hostsDB is not allocated yet */
972 logger.error("ARPRefreshHandler(): hostsDB is not allocated yet:");
975 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
976 HostNodeConnector host = entry.getValue();
977 if (host.isStaticHost()) {
978 /* this host was learned via API3, don't age it out */
982 short arp_cntdown = host.getArpSendCountDown();
984 if (arp_cntdown > switchManager.getHostRetryCount()) {
985 host.setArpSendCountDown(arp_cntdown);
986 } else if (arp_cntdown <= 0) {
988 * No ARP Reply received in last 2 minutes, remove this host
989 * and inform applications
991 removeKnownHost(entry.getKey());
992 notifyHostLearnedOrRemoved(host, false);
993 } else if (arp_cntdown <= switchManager.getHostRetryCount()) {
995 * Use the services of arphandler to check if host is still
998 if (logger.isTraceEnabled()) {
1000 "ARP Probing ({}) for {}({})",
1001 new Object[] { arp_cntdown, host.getNetworkAddress().getHostAddress(),
1002 HexEncode.bytesToHexString(host.getDataLayerAddressBytes()) });
1004 host.setArpSendCountDown(arp_cntdown);
1005 if (hostFinder == null) {
1007 * If hostfinder is not available, then can't send the
1008 * probe. However, continue the age out the hosts since
1009 * we don't know if the host is indeed out there or not.
1011 logger.warn("ARPHandler is not avaialable, can't send the probe");
1014 hostFinder.probe(host);
1021 * Inform the controller IP to MAC binding of a host and its connectivity to
1022 * an openflow switch in terms of Node, port, and VLAN.
1024 * @param networkAddr
1025 * IP address of the host
1027 * Address MAC address of the host
1029 * NodeConnector to which host is connected
1031 * Port of the switch to which host is connected
1033 * Vlan of which this host is member of
1035 * @return Status The status object as described in {@code Status}
1036 * indicating the result of this action.
1039 public Status addStaticHostReq(InetAddress networkAddr, byte[] dataLayerAddress, NodeConnector nc, short vlan) {
1040 if (dataLayerAddress.length != NetUtils.MACAddrLengthInBytes) {
1041 return new Status(StatusCode.BADREQUEST, "Invalid MAC address");
1045 return new Status(StatusCode.BADREQUEST, "Invalid NodeConnector");
1047 HostNodeConnector host = null;
1049 host = new HostNodeConnector(dataLayerAddress, networkAddr, nc, vlan);
1050 if (hostExists(host)) {
1051 // This host is already learned either via ARP or through a
1052 // northbound request
1053 HostNodeConnector transHost = hostsDB.get(networkAddr);
1054 transHost.setStaticHost(true);
1055 return new Status(StatusCode.SUCCESS, null);
1058 if (hostsDB.get(networkAddr) != null) {
1059 // There is already a host with this IP address (but behind
1060 // a different (switch, port, vlan) tuple. Return an error
1061 return new Status(StatusCode.CONFLICT, "Existing IP, Use PUT to update");
1063 host.setStaticHost(true);
1065 * Check if the nc is an ISL port
1067 if (topologyManager != null) {
1068 if (topologyManager.isInternal(nc)) {
1069 return new Status(StatusCode.BADREQUEST, "Cannot add host on ISL port");
1073 * Before adding host, Check if the switch and the port have already
1076 if (switchManager.isNodeConnectorEnabled(nc)) {
1078 notifyHostLearnedOrRemoved(host, true);
1080 inactiveStaticHosts.put(nc, host);
1081 logger.debug("Switch or switchport is not up, adding host {} to inactive list",
1082 networkAddr.getHostName());
1084 return new Status(StatusCode.SUCCESS, null);
1085 } catch (ConstructionException e) {
1086 logger.error("", e);
1087 return new Status(StatusCode.INTERNALERROR, "Host could not be created");
1093 * Update the controller IP to MAC binding of a host and its connectivity to
1094 * an openflow switch in terms of switch id, switch port, and VLAN.
1096 * @param networkAddr
1097 * IP address of the host
1099 * Address MAC address of the host
1101 * NodeConnector to which host is connected
1103 * Port of the switch to which host is connected
1105 * Vlan of which this host is member of
1107 * @return Status The status object as described in {@code Status}
1108 * indicating the result of this action.
1110 public Status updateHostReq(InetAddress networkAddr, byte[] dataLayerAddress, NodeConnector nc, short vlan) {
1111 HostNodeConnector tobeUpdatedHost;
1112 HostNodeConnector host = null;
1114 if (dataLayerAddress.length != NetUtils.MACAddrLengthInBytes) {
1115 return new Status(StatusCode.BADREQUEST, "Invalid MAC address");
1119 return new Status(StatusCode.BADREQUEST, "Invalid NodeConnector");
1123 host = new HostNodeConnector(dataLayerAddress, networkAddr, nc, vlan);
1124 if (hostExists(host)) {
1125 return new Status(StatusCode.BADREQUEST, "Host already exists");
1128 if ((tobeUpdatedHost = hostsDB.get(networkAddr)) != null) {
1129 if (hostsDB.replace(networkAddr, tobeUpdatedHost, host)) {
1130 logger.debug("Host replaced from hostsDB. Old host: {} New Host: {}", tobeUpdatedHost, host);
1131 notifyHostLearnedOrRemoved(tobeUpdatedHost, false);
1132 notifyHostLearnedOrRemoved(host, true);
1133 return new Status(StatusCode.SUCCESS);
1135 logger.error("Static host replacement failed from hostsDB, Replaced Host: {}, New Host: {}",
1136 tobeUpdatedHost, host);
1137 return new Status(StatusCode.INTERNALERROR,
1138 "Host Replacement Failed due to presence of another host with same IP");
1142 // Check if the host exists in inactive hosts database
1143 if ((tobeUpdatedHost = inactiveStaticHosts.get(nc)) != null) {
1144 if (inactiveStaticHosts.replace(nc, tobeUpdatedHost, host)) {
1145 logger.debug("Host replaced from inactive hostsDB. Old host: {} New Host: {}", tobeUpdatedHost,
1147 return new Status(StatusCode.SUCCESS);
1149 logger.error("Static host replacement failed, Replaced Host: {}, New Host: {}", tobeUpdatedHost,
1151 return new Status(StatusCode.INTERNALERROR,
1152 "Host Replacement Failed due to presence of another host with same IP");
1156 // Host doesn't exist
1157 return new Status(StatusCode.BADREQUEST, "Host doesn't exists, can't update");
1158 } catch (ConstructionException e) {
1159 logger.error("", e);
1160 return new Status(StatusCode.INTERNALERROR, "host object creation failure");
1165 * Remove from the controller IP to MAC binding of a host and its
1166 * connectivity to an openflow switch
1168 * @param networkAddr
1169 * IP address of the host
1171 * @return boolean true if the host was removed successfully, false
1175 public Status removeStaticHostReq(InetAddress networkAddress) {
1176 // Check if host is in active hosts database
1177 HostNodeConnector host = getHostFromOnActiveDB(networkAddress);
1180 if (!host.isStaticHost()) {
1181 return new Status(StatusCode.FORBIDDEN, "Host " + networkAddress.getHostName() + " is not static");
1183 // Remove and notify
1184 notifyHostLearnedOrRemoved(host, false);
1185 removeKnownHost(networkAddress);
1186 return new Status(StatusCode.SUCCESS, null);
1189 // Check if host is in inactive hosts database
1190 Entry<NodeConnector, HostNodeConnector> entry = getHostFromInactiveDB(networkAddress);
1191 if (entry != null) {
1192 host = entry.getValue();
1194 if (!host.isStaticHost()) {
1195 return new Status(StatusCode.FORBIDDEN, "Host " + networkAddress.getHostName() + " is not static");
1197 this.removeHostFromInactiveDB(networkAddress);
1198 return new Status(StatusCode.SUCCESS, null);
1201 // Host is neither in active nor inactive hosts database
1202 return new Status(StatusCode.NOTFOUND, "Host does not exist");
1206 public void modeChangeNotify(Node node, boolean proactive) {
1207 logger.debug("Set Switch {} Mode to {}", node.getID(), proactive);
1211 public void notifyNode(Node node, UpdateType type, Map<String, Property> propMap) {
1217 logger.debug("Received removed node {}", node);
1218 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
1219 HostNodeConnector host = entry.getValue();
1220 if (host.getnodeconnectorNode().equals(node)) {
1221 logger.debug("Node: {} is down, remove from Hosts_DB", node);
1222 removeKnownHost(entry.getKey());
1223 notifyHostLearnedOrRemoved(host, false);
1233 public void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map<String, Property> propMap) {
1234 if (nodeConnector == null)
1245 State state = (State) propMap.get(State.StatePropName);
1246 if ((state != null) && (state.getValue() == State.EDGE_UP)) {
1255 handleNodeConnectorStatusUp(nodeConnector);
1257 handleNodeConnectorStatusDown(nodeConnector);
1262 public Status addStaticHost(String networkAddress, String dataLayerAddress, NodeConnector nc, String vlan) {
1264 InetAddress ip = InetAddress.getByName(networkAddress);
1266 return new Status(StatusCode.BADREQUEST, "Invalid NodeId");
1268 return addStaticHostReq(ip, HexEncode.bytesFromHexString(dataLayerAddress), nc, Short.valueOf(vlan));
1269 } catch (UnknownHostException e) {
1270 logger.error("", e);
1271 return new Status(StatusCode.BADREQUEST, "Invalid Address");
1276 public Status removeStaticHost(String networkAddress) {
1277 InetAddress address;
1279 address = InetAddress.getByName(networkAddress);
1280 return removeStaticHostReq(address);
1281 } catch (UnknownHostException e) {
1282 logger.error("", e);
1283 return new Status(StatusCode.BADREQUEST, "Invalid Address");
1287 private void handleNodeConnectorStatusUp(NodeConnector nodeConnector) {
1290 logger.debug("handleNodeConnectorStatusUp {}", nodeConnector);
1292 for (int i = 0; i < failedARPReqList.size(); i++) {
1293 arphost = failedARPReqList.get(i);
1294 logger.debug("Sending the ARP from FailedARPReqList fors IP: {}", arphost.getHostIP().getHostAddress());
1295 if (hostFinder == null) {
1296 logger.warn("ARPHandler is not available at interface up");
1297 logger.warn("Since this event is missed, host(s) connected to interface {} may not be discovered",
1301 hostFinder.find(arphost.getHostIP());
1303 HostNodeConnector host = inactiveStaticHosts.get(nodeConnector);
1305 inactiveStaticHosts.remove(nodeConnector);
1307 notifyHostLearnedOrRemoved(host, true);
1311 private void handleNodeConnectorStatusDown(NodeConnector nodeConnector) {
1312 logger.debug("handleNodeConnectorStatusDown {}", nodeConnector);
1314 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
1315 HostNodeConnector host = entry.getValue();
1316 if (host.getnodeConnector().equals(nodeConnector)) {
1317 logger.debug(" NodeConnector: {} is down, remove from Hosts_DB", nodeConnector);
1318 removeKnownHost(entry.getKey());
1319 notifyHostLearnedOrRemoved(host, false);
1324 void setClusterContainerService(IClusterContainerServices s) {
1325 logger.debug("Cluster Service set");
1326 this.clusterContainerService = s;
1329 void unsetClusterContainerService(IClusterContainerServices s) {
1330 if (this.clusterContainerService == s) {
1331 logger.debug("Cluster Service removed!");
1332 this.clusterContainerService = null;
1336 void setSwitchManager(ISwitchManager s) {
1337 logger.debug("SwitchManager set");
1338 this.switchManager = s;
1341 void unsetSwitchManager(ISwitchManager s) {
1342 if (this.switchManager == s) {
1343 logger.debug("SwitchManager removed!");
1344 this.switchManager = null;
1348 public String getContainerName() {
1349 if (containerName == null)
1350 return GlobalConstants.DEFAULT.toString();
1351 return containerName;
1355 * Function called by the dependency manager when all the required
1356 * dependencies are satisfied
1359 void init(Component c) {
1360 Dictionary<?, ?> props = c.getServiceProperties();
1361 if (props != null) {
1362 this.containerName = (String) props.get("containerName");
1363 logger.debug("Running containerName: {}", this.containerName);
1365 // In the Global instance case the containerName is empty
1366 this.containerName = "";
1372 * Function called by the dependency manager when at least one dependency
1373 * become unsatisfied or when the component is shutting down because for
1374 * example bundle is being stopped.
1381 * Function called by dependency manager after "init ()" is called and after
1382 * the services provided by the class are registered in the service registry
1389 * Function called by the dependency manager before the services exported by
1390 * the component are unregistered, this will be followed by a "destroy ()"
1398 arpRefreshTimer.cancel();
1400 executor.shutdown();
1404 public void edgeOverUtilized(Edge edge) {
1405 // TODO Auto-generated method stub
1410 public void edgeUtilBackToNormal(Edge edge) {
1411 // TODO Auto-generated method stub
1416 public void entryCreated(InetAddress key, String cacheName,
1417 boolean originLocal) {
1418 if (originLocal) return;
1419 processPendingARPReqs(key);
1423 public void entryUpdated(InetAddress key, HostNodeConnector new_value,
1424 String cacheName, boolean originLocal) {
1428 public void entryDeleted(InetAddress key, String cacheName,
1429 boolean originLocal) {