3 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
5 * This program and the accompanying materials are made available under the
6 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7 * and is available at http://www.eclipse.org/legal/epl-v10.html
10 package org.opendaylight.controller.hosttracker;
12 import java.net.InetAddress;
13 import java.net.UnknownHostException;
14 import java.util.ArrayList;
15 import java.util.Collections;
16 import java.util.Dictionary;
17 import java.util.EnumSet;
18 import java.util.HashSet;
19 import java.util.List;
21 import java.util.Map.Entry;
23 import java.util.Timer;
24 import java.util.TimerTask;
25 import java.util.concurrent.Callable;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ConcurrentMap;
28 import java.util.concurrent.ExecutorService;
29 import java.util.concurrent.Executors;
30 import java.util.concurrent.Future;
32 import org.apache.felix.dm.Component;
33 import org.apache.taglibs.standard.lang.jstl.DivideOperator;
34 import org.opendaylight.controller.clustering.services.CacheConfigException;
35 import org.opendaylight.controller.clustering.services.CacheExistException;
36 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
37 import org.opendaylight.controller.clustering.services.IClusterServices;
38 import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
39 import org.opendaylight.controller.hosttracker.hostAware.IHostFinder;
40 import org.opendaylight.controller.sal.core.ConstructionException;
41 import org.opendaylight.controller.sal.core.Edge;
42 import org.opendaylight.controller.sal.core.Host;
43 import org.opendaylight.controller.sal.core.Node;
44 import org.opendaylight.controller.sal.core.NodeConnector;
45 import org.opendaylight.controller.sal.core.Property;
46 import org.opendaylight.controller.sal.core.State;
47 import org.opendaylight.controller.sal.core.Tier;
48 import org.opendaylight.controller.sal.core.UpdateType;
49 import org.opendaylight.controller.sal.packet.address.DataLinkAddress;
50 import org.opendaylight.controller.sal.packet.address.EthernetAddress;
51 import org.opendaylight.controller.sal.utils.GlobalConstants;
52 import org.opendaylight.controller.sal.utils.HexEncode;
53 import org.opendaylight.controller.sal.utils.NodeCreator;
54 import org.opendaylight.controller.sal.utils.Status;
55 import org.opendaylight.controller.sal.utils.StatusCode;
56 import org.opendaylight.controller.switchmanager.IInventoryListener;
57 import org.opendaylight.controller.switchmanager.ISwitchManager;
58 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
59 import org.opendaylight.controller.switchmanager.Subnet;
60 import org.opendaylight.controller.topologymanager.ITopologyManager;
61 import org.opendaylight.controller.topologymanager.ITopologyManagerAware;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
66 * @file HostTracker.java
67 * This class tracks the location of IP Hosts as to which Switch, Port, VLAN, they are
68 * connected to, as well as their MAC address. This is done dynamically as well as statically.
69 * The dynamic mechanism consists of listening to ARP messages as well sending ARP requests.
70 * Static mechanism consists of Northbound APIs to add or remove the hosts from the local
71 * database. ARP aging is also implemented to age out dynamically learned hosts. Interface
72 * methods are provided for other applications to
73 * 1. Query the local database for a single host
74 * 2. Get a list of all hosts
75 * 3. Get notification if a host is learned/added or removed the database
78 public class HostTracker implements IfIptoHost, IfHostListener,
79 ISwitchManagerAware, IInventoryListener, ITopologyManagerAware {
80 private static final Logger logger = LoggerFactory
81 .getLogger(HostTracker.class);
82 private IHostFinder hostFinder;
83 private ConcurrentMap<InetAddress, HostNodeConnector> hostsDB;
84 /* Following is a list of hosts which have been requested by NB APIs to be added,
85 * but either the switch or the port is not sup, so they will be added here until
88 private ConcurrentMap<NodeConnector, HostNodeConnector> inactiveStaticHosts;
89 private Set<IfNewHostNotify> newHostNotify = Collections
90 .synchronizedSet(new HashSet<IfNewHostNotify>());
92 private ITopologyManager topologyManager;
93 private IClusterContainerServices clusterContainerService = null;
94 private ISwitchManager switchManager = null;
96 private Timer arp_refresh_timer;
97 private String containerName = null;
99 private static class ARPPending {
100 protected InetAddress hostIP;
101 protected short sent_count;
102 protected HostTrackerCallable hostTrackerCallable;
104 public InetAddress getHostIP() {
108 public short getSent_count() {
112 public HostTrackerCallable getHostTrackerCallable() {
113 return hostTrackerCallable;
116 public void setHostIP(InetAddress networkAddr) {
117 this.hostIP = networkAddr;
120 public void setSent_count(short count) {
121 this.sent_count = count;
124 public void setHostTrackerCallable(HostTrackerCallable callable) {
125 hostTrackerCallable = callable;
129 //This list contains the hosts for which ARP requests are being sent periodically
130 private List<ARPPending> ARPPendingList = new ArrayList<HostTracker.ARPPending>();
132 * This list below contains the hosts which were initially in ARPPendingList above,
133 * but ARP response didn't come from there hosts after multiple attempts over 8
134 * seconds. The assumption is that the response didn't come back due to one of the
135 * following possibilities:
136 * 1. The L3 interface wasn't created for this host in the controller. This would
137 * cause arphandler not to know where to send the ARP
138 * 2. The host facing port is down
139 * 3. The IP host doesn't exist or is not responding to ARP requests
141 * Conditions 1 and 2 above can be recovered if ARP is sent when the relevant L3
142 * interface is added or the port facing host comes up. Whenever L3 interface is
143 * added or host facing port comes up, ARP will be sent to hosts in this list.
145 * We can't recover from condition 3 above
147 private ArrayList<ARPPending> failedARPReqList = new ArrayList<HostTracker.ARPPending>();
149 public HostTracker() {
152 private void startUp() {
157 timer.schedule(new OutStandingARPHandler(), 4000, 4000);
159 /* ARP Refresh Timer to go off every 5 seconds to implement ARP aging */
160 arp_refresh_timer = new Timer();
161 arp_refresh_timer.schedule(new ARPRefreshHandler(), 5000, 5000);
162 logger.debug("startUp: Caches created, timers started");
165 @SuppressWarnings("deprecation")
166 private void allocateCache() {
167 if (this.clusterContainerService == null) {
169 .error("un-initialized clusterContainerService, can't create cache");
172 logger.debug("Creating Cache for HostTracker");
174 this.clusterContainerService.createCache("hostTrackerAH", EnumSet
175 .of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
176 this.clusterContainerService.createCache("hostTrackerIH", EnumSet
177 .of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
178 } catch (CacheConfigException cce) {
180 .error("Cache couldn't be created for HostTracker - check cache mode");
181 } catch (CacheExistException cce) {
183 .error("Cache for HostTracker already exists, destroy and recreate");
185 logger.debug("Cache successfully created for HostTracker");
188 @SuppressWarnings({ "unchecked", "deprecation" })
189 private void retrieveCache() {
190 if (this.clusterContainerService == null) {
192 .error("un-initialized clusterContainerService, can't retrieve cache");
195 logger.debug("Retrieving cache for HostTrackerAH");
196 hostsDB = (ConcurrentMap<InetAddress, HostNodeConnector>) this.clusterContainerService
197 .getCache("hostTrackerAH");
198 if (hostsDB == null) {
199 logger.error("Cache couldn't be retrieved for HostTracker");
201 logger.debug("Cache was successfully retrieved for HostTracker");
202 logger.debug("Retrieving cache for HostTrackerIH");
203 inactiveStaticHosts = (ConcurrentMap<NodeConnector, HostNodeConnector>) this.clusterContainerService
204 .getCache("hostTrackerIH");
205 if (inactiveStaticHosts == null) {
206 logger.error("Cache couldn't be retrieved for HostTrackerIH");
208 logger.debug("Cache was successfully retrieved for HostTrackerIH");
211 public void nonClusterObjectCreate() {
212 hostsDB = new ConcurrentHashMap<InetAddress, HostNodeConnector>();
213 inactiveStaticHosts = new ConcurrentHashMap<NodeConnector, HostNodeConnector>();
216 @SuppressWarnings("deprecation")
217 private void destroyCache() {
218 if (this.clusterContainerService == null) {
219 logger.error("un-initialized clusterMger, can't destroy cache");
222 logger.debug("Destroying Cache for HostTracker");
223 this.clusterContainerService.destroyCache("hostTrackerAH");
224 this.clusterContainerService.destroyCache("hostTrackerIH");
225 nonClusterObjectCreate();
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(
271 InetAddress networkAddress) {
272 for (Entry<NodeConnector, HostNodeConnector> entry : inactiveStaticHosts
274 if (entry.getValue().equalsByIP(networkAddress)) {
277 "getHostFromInactiveDB(): Inactive Host found for IP:{} ",
278 networkAddress.getHostAddress());
283 "getHostFromInactiveDB() Inactive Host Not found for IP: {}",
284 networkAddress.getHostAddress());
288 private void removeHostFromInactiveDB(InetAddress networkAddress) {
289 NodeConnector nodeConnector = null;
290 for (Entry<NodeConnector, HostNodeConnector> entry : inactiveStaticHosts
292 if (entry.getValue().equalsByIP(networkAddress)) {
293 nodeConnector = entry.getKey();
297 if (nodeConnector != null) {
298 inactiveStaticHosts.remove(nodeConnector);
299 logger.debug("removeHostFromInactiveDB(): Host Removed for IP: {}",
300 networkAddress.getHostAddress());
303 logger.debug("removeHostFromInactiveDB(): Host Not found for IP: {}",
304 networkAddress.getHostAddress());
307 protected boolean hostMoved(HostNodeConnector host) {
308 if (hostQuery(host.getNetworkAddress()) != null) {
314 public HostNodeConnector hostQuery(InetAddress networkAddress) {
315 return hostsDB.get(networkAddress);
318 public Future<HostNodeConnector> discoverHost(InetAddress networkAddress) {
319 ExecutorService executor = Executors.newFixedThreadPool(1);
320 if (executor == null) {
321 logger.error("discoverHost: Null executor");
324 Callable<HostNodeConnector> worker = new HostTrackerCallable(this,
326 Future<HostNodeConnector> submit = executor.submit(worker);
330 public HostNodeConnector hostFind(InetAddress networkAddress) {
332 * Sometimes at boot with containers configured in the startup
333 * we hit this path (from TIF) when hostFinder has not been set yet
334 * Caller already handles the null return
337 if (hostFinder == null) {
338 logger.debug("Exiting hostFind, null hostFinder");
342 HostNodeConnector host = hostQuery(networkAddress);
344 logger.debug("hostFind(): Host found for IP: {}", networkAddress
348 /* host is not found, initiate a discovery */
349 hostFinder.find(networkAddress);
350 /* Also add this host to ARPPending List for any potential retries */
351 AddtoARPPendingList(networkAddress);
354 "hostFind(): Host Not Found for IP: {}, Inititated Host Discovery ...",
355 networkAddress.getHostAddress());
359 public Set<HostNodeConnector> getAllHosts() {
360 Set<HostNodeConnector> allHosts = new HashSet<HostNodeConnector>();
361 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
362 HostNodeConnector host = entry.getValue();
365 logger.debug("Exiting getAllHosts, Found {} Hosts", allHosts.size());
370 public Set<HostNodeConnector> getActiveStaticHosts() {
371 Set<HostNodeConnector> list = new HashSet<HostNodeConnector>();
372 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
373 HostNodeConnector host = entry.getValue();
374 if (host.isStaticHost()) {
378 logger.debug("getActiveStaticHosts(): Found {} Hosts", list.size());
383 public Set<HostNodeConnector> getInactiveStaticHosts() {
384 Set<HostNodeConnector> list = new HashSet<HostNodeConnector>();
385 for (Entry<NodeConnector, HostNodeConnector> entry : inactiveStaticHosts
387 list.add(entry.getValue());
389 logger.debug("getInactiveStaticHosts(): Found {} Hosts", list.size());
393 private void AddtoARPPendingList(InetAddress networkAddr) {
394 ARPPending arphost = new ARPPending();
396 arphost.setHostIP(networkAddr);
397 arphost.setSent_count((short) 1);
398 ARPPendingList.add(arphost);
399 logger.debug("Host Added to ARPPending List, IP: {}", networkAddr
403 private void removePendingARPFromList(int index) {
404 if (index >= ARPPendingList.size()) {
407 "removePendingARPFromList(): index greater than the List. Size:{}, Index:{}",
408 ARPPendingList.size(), index);
411 ARPPending arphost = ARPPendingList.remove(index);
412 HostTrackerCallable htCallable = arphost.getHostTrackerCallable();
413 if (htCallable != null)
417 public void setCallableOnPendingARP(InetAddress networkAddr,
418 HostTrackerCallable callable) {
420 for (int i = 0; i < ARPPendingList.size(); i++) {
421 arphost = ARPPendingList.get(i);
422 if (arphost.getHostIP().equals(networkAddr)) {
423 arphost.setHostTrackerCallable(callable);
428 private void ProcPendingARPReqs(InetAddress networkAddr) {
431 for (int i = 0; i < ARPPendingList.size(); i++) {
432 arphost = ARPPendingList.get(i);
433 if (arphost.getHostIP().equals(networkAddr)) {
434 /* An ARP was sent for this host. The address is learned,
437 removePendingARPFromList(i);
438 logger.debug("Host Removed from ARPPending List, IP: {}",
439 networkAddr.toString());
445 * It could have been a host from the FailedARPReqList
448 for (int i = 0; i < failedARPReqList.size(); i++) {
449 arphost = failedARPReqList.get(i);
450 if (arphost.getHostIP().equals(networkAddr)) {
451 /* An ARP was sent for this host. The address is learned,
454 failedARPReqList.remove(i);
455 logger.debug("Host Removed from FailedARPReqList List, IP: {}",
456 networkAddr.toString());
463 private void learnNewHost(HostNodeConnector host) {
464 host.initArpSendCountDown();
465 hostsDB.put(host.getNetworkAddress(), host);
466 logger.debug("New Host Learned: MAC: {} IP: {}", HexEncode
467 .bytesToHexString(host.getDataLayerAddressBytes()), host
468 .getNetworkAddress().getHostAddress());
472 private void removeKnownHost(InetAddress key) {
473 HostNodeConnector host = hostsDB.get(key);
475 logger.debug("Removing Host: IP:{}", host.getNetworkAddress()
481 "removeKnownHost(): Host for IP address {} not found in hostsDB",
482 key.getHostAddress());
486 private class NotifyHostThread extends Thread {
488 private HostNodeConnector host;
490 public NotifyHostThread(HostNodeConnector h) {
495 /* Check for Host Move case */
496 if (hostMoved(host)) {
498 * Host has been moved from one location (switch,port, MAC, or VLAN).
499 * Remove the existing host with its previous location parameters,
500 * inform the applications, and add it as a new Host
502 HostNodeConnector removedHost = hostsDB.get(host
503 .getNetworkAddress());
504 removeKnownHost(host.getNetworkAddress());
505 if (removedHost != null) {
506 notifyHostLearnedOrRemoved(removedHost, false);
508 "Host move occurred. Old Host:{}, New Host: {}",
512 "Host to be removed not found in hostsDB. Host {}",
517 /* check if there is an outstanding request for this host */
518 InetAddress networkAddr = host.getNetworkAddress();
522 ProcPendingARPReqs(networkAddr);
523 notifyHostLearnedOrRemoved(host, true);
527 public void hostListener(HostNodeConnector host) {
529 if (hostExists(host)) {
530 logger.debug("ARP received for Host: {}", host);
531 HostNodeConnector existinghost = hostsDB.get(host
532 .getNetworkAddress());
533 existinghost.initArpSendCountDown();
536 new NotifyHostThread(host).start();
539 // Notify whoever is interested that a new host was learned (dynamically or statically)
540 private void notifyHostLearnedOrRemoved(HostNodeConnector host, boolean add) {
541 // Update listeners if any
542 if (newHostNotify != null) {
543 synchronized (this.newHostNotify) {
544 for (IfNewHostNotify ta : newHostNotify) {
547 ta.notifyHTClient(host);
549 ta.notifyHTClientHostRemoved(host);
551 } catch (Exception e) {
552 logger.error("Exception on callback", e);
558 .error("notifyHostLearnedOrRemoved(): New host notify is null");
561 // Topology update is for some reason outside of listeners registry logic
562 Node node = host.getnodeconnectorNode();
564 NodeConnector p = host.getnodeConnector();
566 DataLinkAddress dla = new EthernetAddress(host
567 .getDataLayerAddressBytes());
568 h = new org.opendaylight.controller.sal.core.Host(dla, host
569 .getNetworkAddress());
570 } catch (ConstructionException ce) {
575 if (topologyManager != null && p != null && h != null) {
577 Tier tier = new Tier(1);
578 switchManager.setNodeProp(node, tier);
579 topologyManager.updateHostLink(p, h, UpdateType.ADDED, null);
581 * This is a temporary fix for Cisco Live's Hadoop Demonstration.
582 * The concept of Tiering must be revisited based on other application requirements
583 * and the design might warrant a separate module (as it involves tracking the topology/
584 * host changes & updating the Tiering numbers in an effective manner).
586 updateSwitchTiers(node, 1);
589 * The following 2 lines are added for testing purposes.
590 * We can remove it once the North-Bound APIs are available for testing.
592 ArrayList<ArrayList<String>> hierarchies = getHostNetworkHierarchy(host.getNetworkAddress());
593 logHierarchies(hierarchies);
596 // No need to reset the tiering if no other hosts are currently connected
597 // If this switch was discovered to be an access switch, it still is even if the host is down
598 Tier tier = new Tier(0);
599 switchManager.setNodeProp(node, tier);
600 topologyManager.updateHostLink(p, h, UpdateType.REMOVED, null);
606 * When a new Host is learnt by the hosttracker module, it places the directly connected Node
607 * in Tier-1 & using this function, updates the Tier value for all other Nodes in the network
610 * This is a recursive function and it takes care of updating the Tier value for all the connected
611 * and eligible Nodes.
613 * @param n Node that represents one of the Vertex in the Topology Graph.
614 * @param currentTier The Tier on which n belongs
616 private void updateSwitchTiers(Node n, int currentTier) {
617 Map<Node, Set<Edge>> ndlinks = topologyManager.getNodeEdges();
618 if (ndlinks == null) {
620 "updateSwitchTiers(): ndlinks null for Node: {}, Tier:{}",
624 Set<Edge> links = ndlinks.get(n);
626 logger.debug("updateSwitchTiers(): links null for ndlinks:{}",
630 ArrayList<Node> needsVisiting = new ArrayList<Node>();
631 for (Edge lt : links) {
632 if (!lt.getHeadNodeConnector().getType().equals(
633 NodeConnector.NodeConnectorIDType.OPENFLOW)) {
634 // We don't want to work on Node that are not openflow
638 Node dstNode = lt.getHeadNodeConnector().getNode();
639 if (switchNeedsTieringUpdate(dstNode, currentTier + 1)) {
640 Tier t = new Tier(currentTier + 1);
641 switchManager.setNodeProp(dstNode, t);
642 needsVisiting.add(dstNode);
647 * Due to the nature of the problem, having a separate loop for nodes
648 * that needs visiting provides a decent walk optimization.
650 for (Node node : needsVisiting) {
651 updateSwitchTiers(node, currentTier + 1);
656 * Internal convenience routine to check the eligibility of a Switch for a Tier update.
657 * Any Node with Tier=0 or a Tier value that is greater than the new Tier Value is eligible
660 * @param n Node for which the Tier update eligibility is checked
661 * @param tier new Tier Value
662 * @return <code>true</code> if the Node is eligible for Tier Update
663 * <code>false</code> otherwise
666 private boolean switchNeedsTieringUpdate(Node n, int tier) {
668 logger.error("switchNeedsTieringUpdate(): Null node for tier: {}",
673 * Node could have gone down
675 if (!switchManager.getNodes().contains(n)) {
678 // This is the case where Tier was never set for this node
679 Tier t = (Tier) switchManager.getNodeProp(n, Tier.TierPropName);
682 if (t.getValue() == 0)
684 else if (t.getValue() > tier)
690 * Internal convenience routine to clear all the Tier values to 0.
691 * This cleanup is performed during cases such as Topology Change where the existing Tier values
692 * might become incorrect
694 private void clearTiers() {
695 Set<Node> nodes = null;
696 if (switchManager == null) {
697 logger.error("clearTiers(): Null switchManager");
700 nodes = switchManager.getNodes();
702 for (Node n : nodes) {
703 Tier t = new Tier(0);
704 switchManager.setNodeProp(n, t);
709 * Internal convenience routine to print the hierarchies of switches.
711 @SuppressWarnings("unused")
712 private void logHierarchies(ArrayList<ArrayList<String>> hierarchies) {
713 String hierarchyString = null;
715 for (ArrayList<String> hierarchy : hierarchies) {
716 StringBuffer buf = new StringBuffer();
717 buf.append("Hierarchy#" + num + " : ");
718 for (String switchName : hierarchy) {
719 buf.append(switchName + "/");
721 logger.debug("{} -> {}", getContainerName(), buf.toString());
727 * getHostNetworkHierarchy is the Back-end routine for the North-Bound API that returns
728 * the Network Hierarchy for a given Host. This API is typically used by applications like
729 * Hadoop for Rack Awareness functionality.
731 * @param hostAddress IP-Address of the host/node.
732 * @return Network Hierarchies represented by an Array of Array (of Switch-Ids as String).
734 public List<List<String>> getHostNetworkHierarchy(InetAddress hostAddress) {
735 HostNodeConnector host = hostQuery(hostAddress);
739 List<List<String>> hierarchies = new ArrayList<List<String>>();
740 ArrayList<String> currHierarchy = new ArrayList<String>();
741 hierarchies.add(currHierarchy);
743 Node node = host.getnodeconnectorNode();
744 updateCurrentHierarchy(node, currHierarchy, hierarchies);
749 * dpidToHostNameHack is a hack function for Cisco Live Hadoop Demo.
750 * Mininet is used as the network for Hadoop Demos & in order to give a meaningful
751 * rack-awareness switch names, the DPID is organized in ASCII Characters and
752 * retrieved as string.
754 * @param dpid Switch DataPath Id
755 * @return Ascii String represented by the DPID.
757 private String dpidToHostNameHack(long dpid) {
758 String hex = Long.toHexString(dpid);
760 StringBuffer sb = new StringBuffer();
762 for (int i = 0; i < hex.length(); i++) {
763 result = (int) ((dpid >> (i * 8)) & 0xff);
768 sb.append(String.format("%c", result));
770 return sb.reverse().toString();
774 * A convenient recursive routine to obtain the Hierarchy of Switches.
776 * @param node Current Node in the Recursive routine.
777 * @param currHierarchy Array of Nodes that make this hierarchy on which the Current Switch belong
778 * @param fullHierarchy Array of multiple Hierarchies that represent a given host.
780 @SuppressWarnings("unchecked")
781 private void updateCurrentHierarchy(Node node,
782 ArrayList<String> currHierarchy, List<List<String>> fullHierarchy) {
783 //currHierarchy.add(String.format("%x", currSw.getId()));
784 currHierarchy.add(dpidToHostNameHack((Long) node.getID()));
785 ArrayList<String> currHierarchyClone = (ArrayList<String>) currHierarchy
786 .clone(); //Shallow copy as required
788 Map<Node, Set<Edge>> ndlinks = topologyManager.getNodeEdges();
789 if (ndlinks == null) {
792 "updateCurrentHierarchy(): topologyManager returned null ndlinks for node: {}",
796 Node n = NodeCreator.createOFNode((Long) node.getID());
797 Set<Edge> links = ndlinks.get(n);
799 logger.debug("updateCurrentHierarchy(): Null links for ndlinks");
802 for (Edge lt : links) {
803 if (!lt.getHeadNodeConnector().getType().equals(
804 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,
813 Tier dstNodeTier = (Tier) switchManager.getNodeProp(dstNode,
815 if (dstNodeTier.getValue() > nodeTier.getValue()) {
816 ArrayList<String> buildHierarchy = currHierarchy;
817 if (currHierarchy.size() > currHierarchyClone.size()) {
818 buildHierarchy = (ArrayList<String>) currHierarchyClone
819 .clone(); //Shallow copy as required
820 fullHierarchy.add(buildHierarchy);
822 updateCurrentHierarchy(dstNode, buildHierarchy, fullHierarchy);
828 public void edgeUpdate(Edge e, UpdateType type, Set<Property> props) {
830 Short srcPort = null;
832 Short dstPort = null;
833 boolean added = false;
834 String srcType = null;
835 String dstType = null;
837 if (e == null || type == null) {
838 logger.error("Edge or Update type are null!");
841 srcType = e.getTailNodeConnector().getType();
842 dstType = e.getHeadNodeConnector().getType();
844 if (srcType.equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) {
845 logger.debug("Skip updates for {}", e);
849 if (!srcType.equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) {
850 logger.error("For now we cannot handle updates for "
851 + "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.error("For now we cannot handle updates for "
862 + "non-openflow nodes");
866 // At this point we know we got an openflow update, so
867 // lets fill everything accordingly.
868 srcNid = (Long) e.getTailNodeConnector().getNode()
870 srcPort = (Short) e.getTailNodeConnector().getID();
871 dstNid = (Long) e.getHeadNodeConnector().getNode()
873 dstPort = (Short) e.getHeadNodeConnector().getID();
875 // Now lets update the added flag
886 logger.debug("HostTracker Topology linkUpdate handling src:{}[port {}] dst:{}[port {}] added: {}",
887 new Object[] { srcNid, srcPort, dstNid, dstPort, added });
889 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
890 HostNodeConnector host = entry.getValue();
891 Node node = host.getnodeconnectorNode();
893 Tier t = new Tier(1);
894 switchManager.setNodeProp(node, t);
895 updateSwitchTiers(node, 1);
900 public void subnetNotify(Subnet sub, boolean add) {
901 logger.debug("Received subnet notification: {} add={}", sub, add);
903 for (int i = 0; i < failedARPReqList.size(); i++) {
905 arphost = failedARPReqList.get(i);
907 "Sending the ARP from FailedARPReqList fors IP: {}",
908 arphost.getHostIP().getHostAddress());
909 hostFinder.find(arphost.getHostIP());
914 class OutStandingARPHandler extends TimerTask {
917 /* This routine runs every 4 seconds */
918 // logger.info ("ARP Handler called");
919 for (int i = 0; i < ARPPendingList.size(); i++) {
920 arphost = ARPPendingList.get(i);
921 if (arphost.getSent_count() < switchManager.getHostRetryCount()) {
922 /* No reply has been received of first ARP Req, send the next one */
923 hostFinder.find(arphost.getHostIP());
924 arphost.sent_count++;
925 logger.debug("ARP Sent from ARPPending List, IP: {}",
926 arphost.getHostIP().getHostAddress());
927 } else if (arphost.getSent_count() >= switchManager
928 .getHostRetryCount()) {
929 /* Two ARP requests have been sent without
930 * receiving a reply, remove this from the
933 removePendingARPFromList(i);
936 "ARP reply not received after two attempts, removing from Pending List IP: {}",
937 arphost.getHostIP().getHostAddress());
939 * Add this host to a different list which will be processed on link
942 logger.debug("Adding the host to FailedARPReqList IP: {}",
943 arphost.getHostIP().getHostAddress());
944 failedARPReqList.add(arphost);
949 "Inavlid arp_sent count for entery at index: {}",
956 private class ARPRefreshHandler extends TimerTask {
957 @SuppressWarnings("deprecation")
959 if ((clusterContainerService != null)
960 && !clusterContainerService.amICoordinator()) {
963 if ((switchManager != null)
964 && !switchManager.isHostRefreshEnabled()) {
966 * The host probe procedure was disabled by CLI
970 if (hostsDB == null) {
971 /* hostsDB is not allocated yet */
973 .error("ARPRefreshHandler(): hostsDB is not allocated yet:");
976 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB
978 HostNodeConnector host = entry.getValue();
979 if (host.isStaticHost()) {
980 /* this host was learned via API3, don't age it out */
984 short arp_cntdown = host.getArpSendCountDown();
986 if (arp_cntdown > switchManager.getHostRetryCount()) {
987 host.setArpSendCountDown(arp_cntdown);
988 } else if (arp_cntdown <= 0) {
989 /* No ARP Reply received in last 2 minutes, remove this host and inform applications*/
990 removeKnownHost(entry.getKey());
991 notifyHostLearnedOrRemoved(host, false);
992 } else if (arp_cntdown <= switchManager.getHostRetryCount()) {
993 /* Use the services of arphandler to check if host is still there */
994 logger.trace("ARP Probing ({}) for {}({})", new Object[] {
996 host.getNetworkAddress().getHostAddress(),
997 HexEncode.bytesToHexString(host
998 .getDataLayerAddressBytes()) });
999 host.setArpSendCountDown(arp_cntdown);
1000 hostFinder.probe(host);
1007 * Inform the controller IP to MAC binding of a host and its
1008 * connectivity to an openflow switch in terms of Node, port, and
1011 * @param networkAddr IP address of the host
1012 * @param dataLayer Address MAC address of the host
1013 * @param nc NodeConnector to which host is connected
1014 * @param port Port of the switch to which host is connected
1015 * @param vlan Vlan of which this host is member of
1017 * @return Status The status object as described in {@code Status}
1018 * indicating the result of this action.
1021 public Status addStaticHostReq(InetAddress networkAddr,
1022 byte[] dataLayerAddress, NodeConnector nc, short vlan) {
1023 if (dataLayerAddress.length != 6) {
1024 return new Status(StatusCode.BADREQUEST, "Invalid MAC address");
1027 HostNodeConnector host = null;
1029 host = new HostNodeConnector(dataLayerAddress, networkAddr, nc,
1031 if (hostExists(host)) {
1032 // This host is already learned either via ARP or through a northbound request
1033 HostNodeConnector transHost = hostsDB.get(networkAddr);
1034 transHost.setStaticHost(true);
1035 return new Status(StatusCode.SUCCESS, null);
1037 host.setStaticHost(true);
1039 * Before adding host, Check if the switch and the port have already come up
1041 if (switchManager.isNodeConnectorEnabled(nc)) {
1043 notifyHostLearnedOrRemoved(host, true);
1045 inactiveStaticHosts.put(nc, host);
1048 "Switch or switchport is not up, adding host {} to inactive list",
1049 networkAddr.getHostName());
1051 return new Status(StatusCode.SUCCESS, null);
1052 } catch (ConstructionException e) {
1053 return new Status(StatusCode.INTERNALERROR, "Host could not be created");
1059 * Update the controller IP to MAC binding of a host and its
1060 * connectivity to an openflow switch in terms of
1061 * switch id, switch port, and VLAN.
1063 * @param networkAddr IP address of the host
1064 * @param dataLayer Address MAC address of the host
1065 * @param nc NodeConnector to which host is connected
1066 * @param port Port of the switch to which host is connected
1067 * @param vlan Vlan of which this host is member of
1069 * @return boolean true if the host was added successfully,
1072 public boolean updateHostReq(InetAddress networkAddr,
1073 byte[] dataLayerAddress, NodeConnector nc,
1078 HostNodeConnector host = null;
1080 host = new HostNodeConnector(dataLayerAddress, networkAddr, nc,
1082 if (!hostExists(host)) {
1083 if ((inactiveStaticHosts.get(nc)) != null) {
1084 inactiveStaticHosts.replace(nc, host);
1089 hostsDB.replace(networkAddr, host);
1091 } catch (ConstructionException e) {
1097 * Remove from the controller IP to MAC binding of a host and its
1098 * connectivity to an openflow switch
1100 * @param networkAddr IP address of the host
1102 * @return boolean true if the host was removed successfully,
1106 public Status removeStaticHostReq(InetAddress networkAddress) {
1107 // Check if host is in active hosts database
1108 HostNodeConnector host = getHostFromOnActiveDB(networkAddress);
1111 if (!host.isStaticHost()) {
1112 return new Status(StatusCode.FORBIDDEN,
1113 "Host " + networkAddress.getHostName() +
1116 // Remove and notify
1117 notifyHostLearnedOrRemoved(host, false);
1118 removeKnownHost(networkAddress);
1119 return new Status(StatusCode.SUCCESS, null);
1122 // Check if host is in inactive hosts database
1123 Entry<NodeConnector, HostNodeConnector> entry = getHostFromInactiveDB(networkAddress);
1124 if (entry != null) {
1125 host = entry.getValue();
1127 if (!host.isStaticHost()) {
1128 return new Status(StatusCode.FORBIDDEN,
1129 "Host " + networkAddress.getHostName() +
1132 this.removeHostFromInactiveDB(networkAddress);
1133 return new Status(StatusCode.SUCCESS, null);
1136 // Host is neither in active nor inactive hosts database
1137 return new Status(StatusCode.NOTFOUND, "Host does not exist");
1141 public void modeChangeNotify(Node node, boolean proactive) {
1142 logger.debug("Set Switch {} Mode to {}", node.getID(), proactive);
1146 public void notifyNode(Node node, UpdateType type,
1147 Map<String, Property> propMap) {
1153 long sid = (Long) node.getID();
1154 logger.debug("Received removedSwitch for sw id {}", HexEncode
1155 .longToHexString(sid));
1156 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB
1158 HostNodeConnector host = entry.getValue();
1159 if (host.getnodeconnectornodeId() == sid) {
1160 logger.debug("Switch: {} is down, remove from Hosts_DB",
1162 removeKnownHost(entry.getKey());
1163 notifyHostLearnedOrRemoved(host, false);
1173 public void notifyNodeConnector(NodeConnector nodeConnector,
1174 UpdateType type, Map<String, Property> propMap) {
1175 if (nodeConnector == null)
1186 State state = (State) propMap.get(State.StatePropName);
1187 if ((state != null) && (state.getValue() == State.EDGE_UP)) {
1196 handleNodeConnectorStatusUp(nodeConnector);
1198 handleNodeConnectorStatusDown(nodeConnector);
1203 public Status addStaticHost(String networkAddress, String dataLayerAddress,
1204 NodeConnector nc, String vlan) {
1206 InetAddress ip = InetAddress.getByName(networkAddress);
1208 return new Status(StatusCode.BADREQUEST, "Invalid NodeId");
1210 return addStaticHostReq(ip,
1212 .bytesFromHexString(dataLayerAddress),
1214 Short.valueOf(vlan));
1215 } catch (UnknownHostException e) {
1217 return new Status(StatusCode.BADREQUEST, "Invalid Address");
1222 public Status removeStaticHost(String networkAddress) {
1223 InetAddress address;
1225 address = InetAddress.getByName(networkAddress);
1226 return removeStaticHostReq(address);
1227 } catch (UnknownHostException e) {
1229 return new Status(StatusCode.BADREQUEST, "Invalid Address");
1233 private void handleNodeConnectorStatusUp(NodeConnector nodeConnector) {
1236 logger.debug("handleNodeConnectorStatusUp {}", nodeConnector);
1238 for (int i = 0; i < failedARPReqList.size(); i++) {
1239 arphost = failedARPReqList.get(i);
1240 logger.debug("Sending the ARP from FailedARPReqList fors IP: {}",
1241 arphost.getHostIP().getHostAddress());
1242 hostFinder.find(arphost.getHostIP());
1244 HostNodeConnector host = inactiveStaticHosts.get(nodeConnector);
1246 inactiveStaticHosts.remove(nodeConnector);
1248 notifyHostLearnedOrRemoved(host, true);
1252 private void handleNodeConnectorStatusDown(NodeConnector nodeConnector) {
1253 long sid = (Long) nodeConnector.getNode().getID();
1254 short port = (Short) nodeConnector.getID();
1256 logger.debug("handleNodeConnectorStatusDown {}", nodeConnector);
1258 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
1259 HostNodeConnector host = entry.getValue();
1260 if ((host.getnodeconnectornodeId() == sid)
1261 && (host.getnodeconnectorportId() == port)) {
1263 "Switch: {}, Port: {} is down, remove from Hosts_DB",
1265 removeKnownHost(entry.getKey());
1266 notifyHostLearnedOrRemoved(host, false);
1271 void setClusterContainerService(IClusterContainerServices s) {
1272 logger.debug("Cluster Service set");
1273 this.clusterContainerService = s;
1276 void unsetClusterContainerService(IClusterContainerServices s) {
1277 if (this.clusterContainerService == s) {
1278 logger.debug("Cluster Service removed!");
1279 this.clusterContainerService = null;
1283 void setSwitchManager(ISwitchManager s) {
1284 logger.debug("SwitchManager set");
1285 this.switchManager = s;
1288 void unsetSwitchManager(ISwitchManager s) {
1289 if (this.switchManager == s) {
1290 logger.debug("SwitchManager removed!");
1291 this.switchManager = null;
1295 public String getContainerName() {
1296 if (containerName == null)
1297 return GlobalConstants.DEFAULT.toString();
1298 return containerName;
1302 * Function called by the dependency manager when all the required
1303 * dependencies are satisfied
1306 void init(Component c) {
1307 Dictionary<?, ?> props = c.getServiceProperties();
1308 if (props != null) {
1309 this.containerName = (String) props.get("containerName");
1310 logger.debug("Running containerName: {}", this.containerName);
1312 // In the Global instance case the containerName is empty
1313 this.containerName = "";
1319 * Function called by the dependency manager when at least one
1320 * dependency become unsatisfied or when the component is shutting
1321 * down because for example bundle is being stopped.
1329 * Function called by dependency manager after "init ()" is called
1330 * and after the services provided by the class are registered in
1331 * the service registry
1338 * Function called by the dependency manager before the services
1339 * exported by the component are unregistered, this will be
1340 * followed by a "destroy ()" calls
1347 public void edgeOverUtilized(Edge edge) {
1348 // TODO Auto-generated method stub
1353 public void edgeUtilBackToNormal(Edge edge) {
1354 // TODO Auto-generated method stub