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 //logger.info("Updating Switch Tier "+ (currentTier+1) +" for "+String.format("%x", dstSw.getId()));
643 needsVisiting.add(dstNode);
648 * Due to the nature of the problem, having a separate loop for nodes
649 * that needs visiting provides a decent walk optimization.
651 for (Node node : needsVisiting) {
652 updateSwitchTiers(node, currentTier + 1);
657 * Internal convenience routine to check the eligibility of a Switch for a Tier update.
658 * Any Node with Tier=0 or a Tier value that is greater than the new Tier Value is eligible
661 * @param n Node for which the Tier update eligibility is checked
662 * @param tier new Tier Value
663 * @return <code>true</code> if the Node is eligible for Tier Update
664 * <code>false</code> otherwise
667 private boolean switchNeedsTieringUpdate(Node n, int tier) {
669 logger.error("switchNeedsTieringUpdate(): Null node for tier: {}",
674 * Node could have gone down
676 if (!switchManager.getNodes().contains(n)) {
679 // This is the case where Tier was never set for this node
680 Tier t = (Tier) switchManager.getNodeProp(n, Tier.TierPropName);
683 if (t.getValue() == 0)
685 else if (t.getValue() > tier)
687 //logger.info(getContainerName()+" -> "+ "Switch "+String.format("%x", sw.getId())+ " is in better Tier "+sw.getTier()+" ... skipping "+tier);
692 * Internal convenience routine to clear all the Tier values to 0.
693 * This cleanup is performed during cases such as Topology Change where the existing Tier values
694 * might become incorrect
696 private void clearTiers() {
697 Set<Node> nodes = null;
698 if (switchManager == null) {
699 logger.error("clearTiers(): Null switchManager");
702 nodes = switchManager.getNodes();
704 for (Node n : nodes) {
705 Tier t = new Tier(0);
706 switchManager.setNodeProp(n, t);
711 * Internal convenience routine to print the hierarchies of switches.
713 @SuppressWarnings("unused")
714 private void logHierarchies(ArrayList<ArrayList<String>> hierarchies) {
715 String hierarchyString = null;
717 for (ArrayList<String> hierarchy : hierarchies) {
718 StringBuffer buf = new StringBuffer();
719 buf.append("Hierarchy#" + num + " : ");
720 for (String switchName : hierarchy) {
721 buf.append(switchName + "/");
723 logger.debug("{} -> {}", getContainerName(), buf.toString());
729 * getHostNetworkHierarchy is the Back-end routine for the North-Bound API that returns
730 * the Network Hierarchy for a given Host. This API is typically used by applications like
731 * Hadoop for Rack Awareness functionality.
733 * @param hostAddress IP-Address of the host/node.
734 * @return Network Hierarchies represented by an Array of Array (of Switch-Ids as String).
736 public List<List<String>> getHostNetworkHierarchy(InetAddress hostAddress) {
737 HostNodeConnector host = hostQuery(hostAddress);
741 List<List<String>> hierarchies = new ArrayList<List<String>>();
742 ArrayList<String> currHierarchy = new ArrayList<String>();
743 hierarchies.add(currHierarchy);
745 Node node = host.getnodeconnectorNode();
746 updateCurrentHierarchy(node, currHierarchy, hierarchies);
751 * dpidToHostNameHack is a hack function for Cisco Live Hadoop Demo.
752 * Mininet is used as the network for Hadoop Demos & in order to give a meaningful
753 * rack-awareness switch names, the DPID is organized in ASCII Characters and
754 * retrieved as string.
756 * @param dpid Switch DataPath Id
757 * @return Ascii String represented by the DPID.
759 private String dpidToHostNameHack(long dpid) {
760 String hex = Long.toHexString(dpid);
762 StringBuffer sb = new StringBuffer();
764 for (int i = 0; i < hex.length(); i++) {
765 result = (int) ((dpid >> (i * 8)) & 0xff);
770 sb.append(String.format("%c", result));
772 return sb.reverse().toString();
776 * A convenient recursive routine to obtain the Hierarchy of Switches.
778 * @param node Current Node in the Recursive routine.
779 * @param currHierarchy Array of Nodes that make this hierarchy on which the Current Switch belong
780 * @param fullHierarchy Array of multiple Hierarchies that represent a given host.
782 @SuppressWarnings("unchecked")
783 private void updateCurrentHierarchy(Node node,
784 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
788 .clone(); //Shallow copy as required
790 Map<Node, Set<Edge>> ndlinks = topologyManager.getNodeEdges();
791 if (ndlinks == null) {
794 "updateCurrentHierarchy(): topologyManager returned null ndlinks for node: {}",
798 Node n = NodeCreator.createOFNode((Long) node.getID());
799 Set<Edge> links = ndlinks.get(n);
801 logger.debug("updateCurrentHierarchy(): Null links for ndlinks");
804 for (Edge lt : links) {
805 if (!lt.getHeadNodeConnector().getType().equals(
806 NodeConnector.NodeConnectorIDType.OPENFLOW)) {
807 // We don't want to work on Node that are not openflow
811 Node dstNode = lt.getHeadNodeConnector().getNode();
813 Tier nodeTier = (Tier) switchManager.getNodeProp(node,
815 Tier dstNodeTier = (Tier) switchManager.getNodeProp(dstNode,
817 if (dstNodeTier.getValue() > nodeTier.getValue()) {
818 ArrayList<String> buildHierarchy = currHierarchy;
819 if (currHierarchy.size() > currHierarchyClone.size()) {
820 buildHierarchy = (ArrayList<String>) currHierarchyClone
821 .clone(); //Shallow copy as required
822 fullHierarchy.add(buildHierarchy);
824 updateCurrentHierarchy(dstNode, buildHierarchy, fullHierarchy);
830 public void edgeUpdate(Edge e, UpdateType type, Set<Property> props) {
832 Short srcPort = null;
834 Short dstPort = null;
835 boolean added = false;
836 String srcType = null;
837 String dstType = null;
839 if (e == null || type == null) {
840 logger.error("Edge or Update type are null!");
843 srcType = e.getTailNodeConnector().getType();
844 dstType = e.getHeadNodeConnector().getType();
846 if (srcType.equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) {
847 logger.debug("Skip updates for {}", e);
851 if (!srcType.equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) {
852 logger.error("For now we cannot handle updates for "
853 + "non-openflow nodes");
857 if (dstType.equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) {
858 logger.debug("Skip updates for {}", e);
862 if (!dstType.equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) {
863 logger.error("For now we cannot handle updates for "
864 + "non-openflow nodes");
868 // At this point we know we got an openflow update, so
869 // lets fill everything accordingly.
870 srcNid = (Long) e.getTailNodeConnector().getNode()
872 srcPort = (Short) e.getTailNodeConnector().getID();
873 dstNid = (Long) e.getHeadNodeConnector().getNode()
875 dstPort = (Short) e.getHeadNodeConnector().getID();
877 // Now lets update the added flag
888 logger.debug("HostTracker Topology linkUpdate handling src:{}[port {}] dst:{}[port {}] added: {}",
889 new Object[] { srcNid, srcPort, dstNid, dstPort, added });
891 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
892 HostNodeConnector host = entry.getValue();
893 Node node = host.getnodeconnectorNode();
895 Tier t = new Tier(1);
896 switchManager.setNodeProp(node, t);
897 updateSwitchTiers(node, 1);
902 public void subnetNotify(Subnet sub, boolean add) {
903 logger.debug("Received subnet notification: {} add={}", sub, add);
905 for (int i = 0; i < failedARPReqList.size(); i++) {
907 arphost = failedARPReqList.get(i);
909 "Sending the ARP from FailedARPReqList fors IP: {}",
910 arphost.getHostIP().getHostAddress());
911 hostFinder.find(arphost.getHostIP());
916 class OutStandingARPHandler extends TimerTask {
919 /* This routine runs every 4 seconds */
920 // logger.info ("ARP Handler called");
921 for (int i = 0; i < ARPPendingList.size(); i++) {
922 arphost = ARPPendingList.get(i);
923 if (arphost.getSent_count() < switchManager.getHostRetryCount()) {
924 /* No reply has been received of first ARP Req, send the next one */
925 hostFinder.find(arphost.getHostIP());
926 arphost.sent_count++;
927 logger.debug("ARP Sent from ARPPending List, IP: {}",
928 arphost.getHostIP().getHostAddress());
929 } else if (arphost.getSent_count() >= switchManager
930 .getHostRetryCount()) {
931 /* Two ARP requests have been sent without
932 * receiving a reply, remove this from the
935 removePendingARPFromList(i);
938 "ARP reply not received after two attempts, removing from Pending List IP: {}",
939 arphost.getHostIP().getHostAddress());
941 * Add this host to a different list which will be processed on link
944 logger.debug("Adding the host to FailedARPReqList IP: {}",
945 arphost.getHostIP().getHostAddress());
946 failedARPReqList.add(arphost);
951 "Inavlid arp_sent count for entery at index: {}",
958 private class ARPRefreshHandler extends TimerTask {
960 if ((clusterContainerService != null)
961 && !clusterContainerService.amICoordinator()) {
964 if ((switchManager != null)
965 && !switchManager.isHostRefreshEnabled()) {
967 * The host probe procedure was disabled by CLI
971 if (hostsDB == null) {
972 /* hostsDB is not allocated yet */
974 .error("ARPRefreshHandler(): hostsDB is not allocated yet:");
977 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB
979 HostNodeConnector host = entry.getValue();
980 if (host.isStaticHost()) {
981 /* this host was learned via API3, don't age it out */
985 short arp_cntdown = host.getArpSendCountDown();
987 if (arp_cntdown > switchManager.getHostRetryCount()) {
988 host.setArpSendCountDown(arp_cntdown);
989 } else if (arp_cntdown <= 0) {
990 /* No ARP Reply received in last 2 minutes, remove this host and inform applications*/
991 removeKnownHost(entry.getKey());
992 notifyHostLearnedOrRemoved(host, false);
993 } else if (arp_cntdown <= switchManager.getHostRetryCount()) {
994 /* Use the services of arphandler to check if host is still there */
995 // logger.info("Probe for Host:{}", host);
996 //logger.info("ARP Probing ("+arp_cntdown+") for "+host.toString());
997 logger.trace("ARP Probing ({}) for {}({})", new Object[] {
999 host.getNetworkAddress().getHostAddress(),
1000 HexEncode.bytesToHexString(host
1001 .getDataLayerAddressBytes()) });
1002 host.setArpSendCountDown(arp_cntdown);
1003 hostFinder.probe(host);
1010 * Inform the controller IP to MAC binding of a host and its
1011 * connectivity to an openflow switch in terms of Node, port, and
1014 * @param networkAddr IP address of the host
1015 * @param dataLayer Address MAC address of the host
1016 * @param nc NodeConnector to which host is connected
1017 * @param port Port of the switch to which host is connected
1018 * @param vlan Vlan of which this host is member of
1020 * @return Status The status object as described in {@code Status}
1021 * indicating the result of this action.
1024 public Status addStaticHostReq(InetAddress networkAddr,
1025 byte[] dataLayerAddress, NodeConnector nc, short vlan) {
1026 if (dataLayerAddress.length != 6) {
1027 return new Status(StatusCode.BADREQUEST, "Invalid MAC address");
1030 HostNodeConnector host = null;
1032 host = new HostNodeConnector(dataLayerAddress, networkAddr, nc,
1034 if (hostExists(host)) {
1035 // This host is already learned either via ARP or through a northbound request
1036 HostNodeConnector transHost = hostsDB.get(networkAddr);
1037 transHost.setStaticHost(true);
1038 return new Status(StatusCode.SUCCESS, null);
1040 host.setStaticHost(true);
1042 * Before adding host, Check if the switch and the port have already come up
1044 if (switchManager.isNodeConnectorEnabled(nc)) {
1046 notifyHostLearnedOrRemoved(host, true);
1048 inactiveStaticHosts.put(nc, host);
1051 "Switch or switchport is not up, adding host {} to inactive list",
1052 networkAddr.getHostName());
1054 return new Status(StatusCode.SUCCESS, null);
1055 } catch (ConstructionException e) {
1056 return new Status(StatusCode.INTERNALERROR, "Host could not be created");
1062 * Update the controller IP to MAC binding of a host and its
1063 * connectivity to an openflow switch in terms of
1064 * switch id, switch port, and VLAN.
1066 * @param networkAddr IP address of the host
1067 * @param dataLayer Address MAC address of the host
1068 * @param nc NodeConnector to which host is connected
1069 * @param port Port of the switch to which host is connected
1070 * @param vlan Vlan of which this host is member of
1072 * @return boolean true if the host was added successfully,
1075 public boolean updateHostReq(InetAddress networkAddr,
1076 byte[] dataLayerAddress, NodeConnector nc,
1081 HostNodeConnector host = null;
1083 host = new HostNodeConnector(dataLayerAddress, networkAddr, nc,
1085 if (!hostExists(host)) {
1086 if ((inactiveStaticHosts.get(nc)) != null) {
1087 inactiveStaticHosts.replace(nc, host);
1092 hostsDB.replace(networkAddr, host);
1094 } catch (ConstructionException e) {
1100 * Remove from the controller IP to MAC binding of a host and its
1101 * connectivity to an openflow switch
1103 * @param networkAddr IP address of the host
1105 * @return boolean true if the host was removed successfully,
1109 public Status removeStaticHostReq(InetAddress networkAddress) {
1110 // Check if host is in active hosts database
1111 HostNodeConnector host = getHostFromOnActiveDB(networkAddress);
1114 if (!host.isStaticHost()) {
1115 return new Status(StatusCode.FORBIDDEN,
1116 "Host " + networkAddress.getHostName() +
1119 // Remove and notify
1120 notifyHostLearnedOrRemoved(host, false);
1121 removeKnownHost(networkAddress);
1122 return new Status(StatusCode.SUCCESS, null);
1125 // Check if host is in inactive hosts database
1126 Entry<NodeConnector, HostNodeConnector> entry = getHostFromInactiveDB(networkAddress);
1127 if (entry != null) {
1128 host = entry.getValue();
1130 if (!host.isStaticHost()) {
1131 return new Status(StatusCode.FORBIDDEN,
1132 "Host " + networkAddress.getHostName() +
1135 this.removeHostFromInactiveDB(networkAddress);
1136 return new Status(StatusCode.SUCCESS, null);
1139 // Host is neither in active nor inactive hosts database
1140 return new Status(StatusCode.NOTFOUND, "Host does not exist");
1144 public void modeChangeNotify(Node node, boolean proactive) {
1145 logger.debug("Set Switch {} Mode to {}", node.getID(), proactive);
1149 public void notifyNode(Node node, UpdateType type,
1150 Map<String, Property> propMap) {
1156 long sid = (Long) node.getID();
1157 logger.debug("Received removedSwitch for sw id {}", HexEncode
1158 .longToHexString(sid));
1159 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB
1161 HostNodeConnector host = entry.getValue();
1162 if (host.getnodeconnectornodeId() == sid) {
1163 logger.debug("Switch: {} is down, remove from Hosts_DB",
1165 removeKnownHost(entry.getKey());
1166 notifyHostLearnedOrRemoved(host, false);
1176 public void notifyNodeConnector(NodeConnector nodeConnector,
1177 UpdateType type, Map<String, Property> propMap) {
1178 if (nodeConnector == null)
1189 State state = (State) propMap.get(State.StatePropName);
1190 if ((state != null) && (state.getValue() == State.EDGE_UP)) {
1199 handleNodeConnectorStatusUp(nodeConnector);
1201 handleNodeConnectorStatusDown(nodeConnector);
1206 public Status addStaticHost(String networkAddress, String dataLayerAddress,
1207 NodeConnector nc, String vlan) {
1209 InetAddress ip = InetAddress.getByName(networkAddress);
1211 return new Status(StatusCode.BADREQUEST, "Invalid NodeId");
1213 return addStaticHostReq(ip,
1215 .bytesFromHexString(dataLayerAddress),
1217 Short.valueOf(vlan));
1218 } catch (UnknownHostException e) {
1220 return new Status(StatusCode.BADREQUEST, "Invalid Address");
1225 public Status removeStaticHost(String networkAddress) {
1226 InetAddress address;
1228 address = InetAddress.getByName(networkAddress);
1229 return removeStaticHostReq(address);
1230 } catch (UnknownHostException e) {
1232 return new Status(StatusCode.BADREQUEST, "Invalid Address");
1236 private void handleNodeConnectorStatusUp(NodeConnector nodeConnector) {
1239 logger.debug("handleNodeConnectorStatusUp {}", nodeConnector);
1241 for (int i = 0; i < failedARPReqList.size(); i++) {
1242 arphost = failedARPReqList.get(i);
1243 logger.debug("Sending the ARP from FailedARPReqList fors IP: {}",
1244 arphost.getHostIP().getHostAddress());
1245 hostFinder.find(arphost.getHostIP());
1247 HostNodeConnector host = inactiveStaticHosts.get(nodeConnector);
1249 inactiveStaticHosts.remove(nodeConnector);
1251 notifyHostLearnedOrRemoved(host, true);
1255 private void handleNodeConnectorStatusDown(NodeConnector nodeConnector) {
1256 long sid = (Long) nodeConnector.getNode().getID();
1257 short port = (Short) nodeConnector.getID();
1259 logger.debug("handleNodeConnectorStatusDown {}", nodeConnector);
1261 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
1262 HostNodeConnector host = entry.getValue();
1263 if ((host.getnodeconnectornodeId() == sid)
1264 && (host.getnodeconnectorportId() == port)) {
1266 "Switch: {}, Port: {} is down, remove from Hosts_DB",
1268 removeKnownHost(entry.getKey());
1269 notifyHostLearnedOrRemoved(host, false);
1274 void setClusterContainerService(IClusterContainerServices s) {
1275 logger.debug("Cluster Service set");
1276 this.clusterContainerService = s;
1279 void unsetClusterContainerService(IClusterContainerServices s) {
1280 if (this.clusterContainerService == s) {
1281 logger.debug("Cluster Service removed!");
1282 this.clusterContainerService = null;
1286 void setSwitchManager(ISwitchManager s) {
1287 logger.debug("SwitchManager set");
1288 this.switchManager = s;
1291 void unsetSwitchManager(ISwitchManager s) {
1292 if (this.switchManager == s) {
1293 logger.debug("SwitchManager removed!");
1294 this.switchManager = null;
1298 public String getContainerName() {
1299 if (containerName == null)
1300 return GlobalConstants.DEFAULT.toString();
1301 return containerName;
1305 * Function called by the dependency manager when all the required
1306 * dependencies are satisfied
1309 void init(Component c) {
1310 Dictionary<?, ?> props = c.getServiceProperties();
1311 if (props != null) {
1312 this.containerName = (String) props.get("containerName");
1313 logger.debug("Running containerName: {}", this.containerName);
1315 // In the Global instance case the containerName is empty
1316 this.containerName = "";
1322 * Function called by the dependency manager when at least one
1323 * dependency become unsatisfied or when the component is shutting
1324 * down because for example bundle is being stopped.
1332 * Function called by dependency manager after "init ()" is called
1333 * and after the services provided by the class are registered in
1334 * the service registry
1341 * Function called by the dependency manager before the services
1342 * exported by the component are unregistered, this will be
1343 * followed by a "destroy ()" calls
1350 public void edgeOverUtilized(Edge edge) {
1351 // TODO Auto-generated method stub
1356 public void edgeUtilBackToNormal(Edge edge) {
1357 // TODO Auto-generated method stub