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.internal;
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.hosttracker.IfHostListener;
41 import org.opendaylight.controller.hosttracker.IfIptoHost;
42 import org.opendaylight.controller.hosttracker.IfNewHostNotify;
43 import org.opendaylight.controller.sal.core.ConstructionException;
44 import org.opendaylight.controller.sal.core.Edge;
45 import org.opendaylight.controller.sal.core.Host;
46 import org.opendaylight.controller.sal.core.Node;
47 import org.opendaylight.controller.sal.core.NodeConnector;
48 import org.opendaylight.controller.sal.core.Property;
49 import org.opendaylight.controller.sal.core.State;
50 import org.opendaylight.controller.sal.core.Tier;
51 import org.opendaylight.controller.sal.core.UpdateType;
52 import org.opendaylight.controller.sal.packet.address.DataLinkAddress;
53 import org.opendaylight.controller.sal.packet.address.EthernetAddress;
54 import org.opendaylight.controller.sal.utils.GlobalConstants;
55 import org.opendaylight.controller.sal.utils.HexEncode;
56 import org.opendaylight.controller.sal.utils.NodeCreator;
57 import org.opendaylight.controller.sal.utils.Status;
58 import org.opendaylight.controller.sal.utils.StatusCode;
59 import org.opendaylight.controller.switchmanager.IInventoryListener;
60 import org.opendaylight.controller.switchmanager.ISwitchManager;
61 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
62 import org.opendaylight.controller.switchmanager.Subnet;
63 import org.opendaylight.controller.topologymanager.ITopologyManager;
64 import org.opendaylight.controller.topologymanager.ITopologyManagerAware;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
69 * @file HostTracker.java
70 * This class tracks the location of IP Hosts as to which Switch, Port, VLAN, they are
71 * connected to, as well as their MAC address. This is done dynamically as well as statically.
72 * The dynamic mechanism consists of listening to ARP messages as well sending ARP requests.
73 * Static mechanism consists of Northbound APIs to add or remove the hosts from the local
74 * database. ARP aging is also implemented to age out dynamically learned hosts. Interface
75 * methods are provided for other applications to
76 * 1. Query the local database for a single host
77 * 2. Get a list of all hosts
78 * 3. Get notification if a host is learned/added or removed the database
81 public class HostTracker implements IfIptoHost, IfHostListener,
82 ISwitchManagerAware, IInventoryListener, ITopologyManagerAware {
83 private static final Logger logger = LoggerFactory
84 .getLogger(HostTracker.class);
85 private IHostFinder hostFinder;
86 private ConcurrentMap<InetAddress, HostNodeConnector> hostsDB;
87 /* Following is a list of hosts which have been requested by NB APIs to be added,
88 * but either the switch or the port is not sup, so they will be added here until
91 private ConcurrentMap<NodeConnector, HostNodeConnector> inactiveStaticHosts;
92 private Set<IfNewHostNotify> newHostNotify = Collections
93 .synchronizedSet(new HashSet<IfNewHostNotify>());
95 private ITopologyManager topologyManager;
96 private IClusterContainerServices clusterContainerService = null;
97 private ISwitchManager switchManager = null;
99 private Timer arp_refresh_timer;
100 private String containerName = null;
102 private static class ARPPending {
103 protected InetAddress hostIP;
104 protected short sent_count;
105 protected HostTrackerCallable hostTrackerCallable;
107 public InetAddress getHostIP() {
111 public short getSent_count() {
115 public HostTrackerCallable getHostTrackerCallable() {
116 return hostTrackerCallable;
119 public void setHostIP(InetAddress networkAddr) {
120 this.hostIP = networkAddr;
123 public void setSent_count(short count) {
124 this.sent_count = count;
127 public void setHostTrackerCallable(HostTrackerCallable callable) {
128 hostTrackerCallable = callable;
132 //This list contains the hosts for which ARP requests are being sent periodically
133 private List<ARPPending> ARPPendingList = new ArrayList<HostTracker.ARPPending>();
135 * This list below contains the hosts which were initially in ARPPendingList above,
136 * but ARP response didn't come from there hosts after multiple attempts over 8
137 * seconds. The assumption is that the response didn't come back due to one of the
138 * following possibilities:
139 * 1. The L3 interface wasn't created for this host in the controller. This would
140 * cause arphandler not to know where to send the ARP
141 * 2. The host facing port is down
142 * 3. The IP host doesn't exist or is not responding to ARP requests
144 * Conditions 1 and 2 above can be recovered if ARP is sent when the relevant L3
145 * interface is added or the port facing host comes up. Whenever L3 interface is
146 * added or host facing port comes up, ARP will be sent to hosts in this list.
148 * We can't recover from condition 3 above
150 private ArrayList<ARPPending> failedARPReqList = new ArrayList<HostTracker.ARPPending>();
152 public HostTracker() {
155 private void startUp() {
160 timer.schedule(new OutStandingARPHandler(), 4000, 4000);
162 /* ARP Refresh Timer to go off every 5 seconds to implement ARP aging */
163 arp_refresh_timer = new Timer();
164 arp_refresh_timer.schedule(new ARPRefreshHandler(), 5000, 5000);
165 logger.debug("startUp: Caches created, timers started");
168 @SuppressWarnings("deprecation")
169 private void allocateCache() {
170 if (this.clusterContainerService == null) {
172 .error("un-initialized clusterContainerService, can't create cache");
175 logger.debug("Creating Cache for HostTracker");
177 this.clusterContainerService.createCache("hostTrackerAH", EnumSet
178 .of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
179 this.clusterContainerService.createCache("hostTrackerIH", EnumSet
180 .of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
181 } catch (CacheConfigException cce) {
183 .error("Cache couldn't be created for HostTracker - check cache mode");
184 } catch (CacheExistException cce) {
186 .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) {
195 .error("un-initialized clusterContainerService, can't retrieve cache");
198 logger.debug("Retrieving cache for HostTrackerAH");
199 hostsDB = (ConcurrentMap<InetAddress, HostNodeConnector>) this.clusterContainerService
200 .getCache("hostTrackerAH");
201 if (hostsDB == null) {
202 logger.error("Cache couldn't be retrieved for HostTracker");
204 logger.debug("Cache was successfully retrieved for HostTracker");
205 logger.debug("Retrieving cache for HostTrackerIH");
206 inactiveStaticHosts = (ConcurrentMap<NodeConnector, HostNodeConnector>) this.clusterContainerService
207 .getCache("hostTrackerIH");
208 if (inactiveStaticHosts == null) {
209 logger.error("Cache couldn't be retrieved for HostTrackerIH");
211 logger.debug("Cache was successfully retrieved for HostTrackerIH");
214 public void nonClusterObjectCreate() {
215 hostsDB = new ConcurrentHashMap<InetAddress, HostNodeConnector>();
216 inactiveStaticHosts = new ConcurrentHashMap<NodeConnector, HostNodeConnector>();
219 @SuppressWarnings("deprecation")
220 private void destroyCache() {
221 if (this.clusterContainerService == null) {
222 logger.error("un-initialized clusterMger, can't destroy cache");
225 logger.debug("Destroying Cache for HostTracker");
226 this.clusterContainerService.destroyCache("hostTrackerAH");
227 this.clusterContainerService.destroyCache("hostTrackerIH");
228 nonClusterObjectCreate();
231 public void shutDown() {
234 public void setnewHostNotify(IfNewHostNotify obj) {
235 this.newHostNotify.add(obj);
238 public void unsetnewHostNotify(IfNewHostNotify obj) {
239 this.newHostNotify.remove(obj);
242 public void setArpHandler(IHostFinder hostFinder) {
243 this.hostFinder = hostFinder;
246 public void unsetArpHandler(IHostFinder hostFinder) {
247 if (this.hostFinder == hostFinder) {
248 logger.debug("Arp Handler Service removed!");
249 this.hostFinder = null;
253 public void setTopologyManager(ITopologyManager s) {
254 this.topologyManager = s;
257 public void unsetTopologyManager(ITopologyManager s) {
258 if (this.topologyManager == s) {
259 logger.debug("Topology Manager Service removed!");
260 this.topologyManager = null;
264 private boolean hostExists(HostNodeConnector host) {
265 HostNodeConnector lhost = hostsDB.get(host.getNetworkAddress());
266 return host.equals(lhost);
269 private HostNodeConnector getHostFromOnActiveDB(InetAddress networkAddress) {
270 return hostsDB.get(networkAddress);
273 private Entry<NodeConnector, HostNodeConnector> getHostFromInactiveDB(
274 InetAddress networkAddress) {
275 for (Entry<NodeConnector, HostNodeConnector> entry : inactiveStaticHosts
277 if (entry.getValue().equalsByIP(networkAddress)) {
280 "getHostFromInactiveDB(): Inactive Host found for IP:{} ",
281 networkAddress.getHostAddress());
286 "getHostFromInactiveDB() Inactive Host Not found for IP: {}",
287 networkAddress.getHostAddress());
291 private void removeHostFromInactiveDB(InetAddress networkAddress) {
292 NodeConnector nodeConnector = null;
293 for (Entry<NodeConnector, HostNodeConnector> entry : inactiveStaticHosts
295 if (entry.getValue().equalsByIP(networkAddress)) {
296 nodeConnector = entry.getKey();
300 if (nodeConnector != null) {
301 inactiveStaticHosts.remove(nodeConnector);
302 logger.debug("removeHostFromInactiveDB(): Host Removed for IP: {}",
303 networkAddress.getHostAddress());
306 logger.debug("removeHostFromInactiveDB(): Host Not found for IP: {}",
307 networkAddress.getHostAddress());
310 protected boolean hostMoved(HostNodeConnector host) {
311 if (hostQuery(host.getNetworkAddress()) != null) {
317 public HostNodeConnector hostQuery(InetAddress networkAddress) {
318 return hostsDB.get(networkAddress);
321 public Future<HostNodeConnector> discoverHost(InetAddress networkAddress) {
322 ExecutorService executor = Executors.newFixedThreadPool(1);
323 if (executor == null) {
324 logger.error("discoverHost: Null executor");
327 Callable<HostNodeConnector> worker = new HostTrackerCallable(this,
329 Future<HostNodeConnector> submit = executor.submit(worker);
333 public HostNodeConnector hostFind(InetAddress networkAddress) {
335 * Sometimes at boot with containers configured in the startup
336 * we hit this path (from TIF) when hostFinder has not been set yet
337 * Caller already handles the null return
340 if (hostFinder == null) {
341 logger.debug("Exiting hostFind, null hostFinder");
345 HostNodeConnector host = hostQuery(networkAddress);
347 logger.debug("hostFind(): Host found for IP: {}", networkAddress
351 /* host is not found, initiate a discovery */
352 hostFinder.find(networkAddress);
353 /* Also add this host to ARPPending List for any potential retries */
354 AddtoARPPendingList(networkAddress);
357 "hostFind(): Host Not Found for IP: {}, Inititated Host Discovery ...",
358 networkAddress.getHostAddress());
362 public Set<HostNodeConnector> getAllHosts() {
363 Set<HostNodeConnector> allHosts = new HashSet<HostNodeConnector>();
364 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
365 HostNodeConnector host = entry.getValue();
368 logger.debug("Exiting getAllHosts, Found {} Hosts", allHosts.size());
373 public Set<HostNodeConnector> getActiveStaticHosts() {
374 Set<HostNodeConnector> list = new HashSet<HostNodeConnector>();
375 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
376 HostNodeConnector host = entry.getValue();
377 if (host.isStaticHost()) {
381 logger.debug("getActiveStaticHosts(): Found {} Hosts", list.size());
386 public Set<HostNodeConnector> getInactiveStaticHosts() {
387 Set<HostNodeConnector> list = new HashSet<HostNodeConnector>();
388 for (Entry<NodeConnector, HostNodeConnector> entry : inactiveStaticHosts
390 list.add(entry.getValue());
392 logger.debug("getInactiveStaticHosts(): Found {} Hosts", list.size());
396 private void AddtoARPPendingList(InetAddress networkAddr) {
397 ARPPending arphost = new ARPPending();
399 arphost.setHostIP(networkAddr);
400 arphost.setSent_count((short) 1);
401 ARPPendingList.add(arphost);
402 logger.debug("Host Added to ARPPending List, IP: {}", networkAddr
406 private void removePendingARPFromList(int index) {
407 if (index >= ARPPendingList.size()) {
410 "removePendingARPFromList(): index greater than the List. Size:{}, Index:{}",
411 ARPPendingList.size(), index);
414 ARPPending arphost = ARPPendingList.remove(index);
415 HostTrackerCallable htCallable = arphost.getHostTrackerCallable();
416 if (htCallable != null)
420 public void setCallableOnPendingARP(InetAddress networkAddr,
421 HostTrackerCallable callable) {
423 for (int i = 0; i < ARPPendingList.size(); i++) {
424 arphost = ARPPendingList.get(i);
425 if (arphost.getHostIP().equals(networkAddr)) {
426 arphost.setHostTrackerCallable(callable);
431 private void ProcPendingARPReqs(InetAddress networkAddr) {
434 for (int i = 0; i < ARPPendingList.size(); i++) {
435 arphost = ARPPendingList.get(i);
436 if (arphost.getHostIP().equals(networkAddr)) {
437 /* An ARP was sent for this host. The address is learned,
440 removePendingARPFromList(i);
441 logger.debug("Host Removed from ARPPending List, IP: {}",
442 networkAddr.toString());
448 * It could have been a host from the FailedARPReqList
451 for (int i = 0; i < failedARPReqList.size(); i++) {
452 arphost = failedARPReqList.get(i);
453 if (arphost.getHostIP().equals(networkAddr)) {
454 /* An ARP was sent for this host. The address is learned,
457 failedARPReqList.remove(i);
458 logger.debug("Host Removed from FailedARPReqList List, IP: {}",
459 networkAddr.toString());
466 private void learnNewHost(HostNodeConnector host) {
467 host.initArpSendCountDown();
468 hostsDB.put(host.getNetworkAddress(), host);
469 logger.debug("New Host Learned: MAC: {} IP: {}", HexEncode
470 .bytesToHexString(host.getDataLayerAddressBytes()), host
471 .getNetworkAddress().getHostAddress());
475 private void removeKnownHost(InetAddress key) {
476 HostNodeConnector host = hostsDB.get(key);
478 logger.debug("Removing Host: IP:{}", host.getNetworkAddress()
484 "removeKnownHost(): Host for IP address {} not found in hostsDB",
485 key.getHostAddress());
489 private class NotifyHostThread extends Thread {
491 private HostNodeConnector host;
493 public NotifyHostThread(HostNodeConnector h) {
498 /* Check for Host Move case */
499 if (hostMoved(host)) {
501 * Host has been moved from one location (switch,port, MAC, or VLAN).
502 * Remove the existing host with its previous location parameters,
503 * inform the applications, and add it as a new Host
505 HostNodeConnector removedHost = hostsDB.get(host
506 .getNetworkAddress());
507 removeKnownHost(host.getNetworkAddress());
508 if (removedHost != null) {
509 notifyHostLearnedOrRemoved(removedHost, false);
511 "Host move occurred. Old Host:{}, New Host: {}",
515 "Host to be removed not found in hostsDB. Host {}",
520 /* check if there is an outstanding request for this host */
521 InetAddress networkAddr = host.getNetworkAddress();
525 ProcPendingARPReqs(networkAddr);
526 notifyHostLearnedOrRemoved(host, true);
530 public void hostListener(HostNodeConnector host) {
532 if (hostExists(host)) {
533 logger.debug("ARP received for Host: {}", host);
534 HostNodeConnector existinghost = hostsDB.get(host
535 .getNetworkAddress());
536 existinghost.initArpSendCountDown();
539 new NotifyHostThread(host).start();
542 // Notify whoever is interested that a new host was learned (dynamically or statically)
543 private void notifyHostLearnedOrRemoved(HostNodeConnector host, boolean add) {
544 // Update listeners if any
545 if (newHostNotify != null) {
546 synchronized (this.newHostNotify) {
547 for (IfNewHostNotify ta : newHostNotify) {
550 ta.notifyHTClient(host);
552 ta.notifyHTClientHostRemoved(host);
554 } catch (Exception e) {
555 logger.error("Exception on callback", e);
561 .error("notifyHostLearnedOrRemoved(): New host notify is null");
564 // Topology update is for some reason outside of listeners registry logic
565 Node node = host.getnodeconnectorNode();
567 NodeConnector p = host.getnodeConnector();
569 DataLinkAddress dla = new EthernetAddress(host
570 .getDataLayerAddressBytes());
571 h = new org.opendaylight.controller.sal.core.Host(dla, host
572 .getNetworkAddress());
573 } catch (ConstructionException ce) {
578 if (topologyManager != null && p != null && h != null) {
580 Tier tier = new Tier(1);
581 switchManager.setNodeProp(node, tier);
582 topologyManager.updateHostLink(p, h, UpdateType.ADDED, null);
584 * This is a temporary fix for Cisco Live's Hadoop Demonstration.
585 * The concept of Tiering must be revisited based on other application requirements
586 * and the design might warrant a separate module (as it involves tracking the topology/
587 * host changes & updating the Tiering numbers in an effective manner).
589 updateSwitchTiers(node, 1);
592 * The following 2 lines are added for testing purposes.
593 * We can remove it once the North-Bound APIs are available for testing.
595 ArrayList<ArrayList<String>> hierarchies = getHostNetworkHierarchy(host.getNetworkAddress());
596 logHierarchies(hierarchies);
599 // No need to reset the tiering if no other hosts are currently connected
600 // If this switch was discovered to be an access switch, it still is even if the host is down
601 Tier tier = new Tier(0);
602 switchManager.setNodeProp(node, tier);
603 topologyManager.updateHostLink(p, h, UpdateType.REMOVED, null);
609 * When a new Host is learnt by the hosttracker module, it places the directly connected Node
610 * in Tier-1 & using this function, updates the Tier value for all other Nodes in the network
613 * This is a recursive function and it takes care of updating the Tier value for all the connected
614 * and eligible Nodes.
616 * @param n Node that represents one of the Vertex in the Topology Graph.
617 * @param currentTier The Tier on which n belongs
619 private void updateSwitchTiers(Node n, int currentTier) {
620 Map<Node, Set<Edge>> ndlinks = topologyManager.getNodeEdges();
621 if (ndlinks == null) {
623 "updateSwitchTiers(): ndlinks null for Node: {}, Tier:{}",
627 Set<Edge> links = ndlinks.get(n);
629 logger.debug("updateSwitchTiers(): links null for ndlinks:{}",
633 ArrayList<Node> needsVisiting = new ArrayList<Node>();
634 for (Edge lt : links) {
635 if (!lt.getHeadNodeConnector().getType().equals(
636 NodeConnector.NodeConnectorIDType.OPENFLOW)) {
637 // We don't want to work on Node that are not openflow
641 Node dstNode = lt.getHeadNodeConnector().getNode();
642 if (switchNeedsTieringUpdate(dstNode, currentTier + 1)) {
643 Tier t = new Tier(currentTier + 1);
644 switchManager.setNodeProp(dstNode, t);
645 needsVisiting.add(dstNode);
650 * Due to the nature of the problem, having a separate loop for nodes
651 * that needs visiting provides a decent walk optimization.
653 for (Node node : needsVisiting) {
654 updateSwitchTiers(node, currentTier + 1);
659 * Internal convenience routine to check the eligibility of a Switch for a Tier update.
660 * Any Node with Tier=0 or a Tier value that is greater than the new Tier Value is eligible
663 * @param n Node for which the Tier update eligibility is checked
664 * @param tier new Tier Value
665 * @return <code>true</code> if the Node is eligible for Tier Update
666 * <code>false</code> otherwise
669 private boolean switchNeedsTieringUpdate(Node n, int tier) {
671 logger.error("switchNeedsTieringUpdate(): Null node for tier: {}",
676 * Node could have gone down
678 if (!switchManager.getNodes().contains(n)) {
681 // This is the case where Tier was never set for this node
682 Tier t = (Tier) switchManager.getNodeProp(n, Tier.TierPropName);
685 if (t.getValue() == 0)
687 else if (t.getValue() > tier)
693 * Internal convenience routine to clear all the Tier values to 0.
694 * This cleanup is performed during cases such as Topology Change where the existing Tier values
695 * might become incorrect
697 private void clearTiers() {
698 Set<Node> nodes = null;
699 if (switchManager == null) {
700 logger.error("clearTiers(): Null switchManager");
703 nodes = switchManager.getNodes();
705 for (Node n : nodes) {
706 Tier t = new Tier(0);
707 switchManager.setNodeProp(n, t);
712 * Internal convenience routine to print the hierarchies of switches.
714 @SuppressWarnings("unused")
715 private void logHierarchies(ArrayList<ArrayList<String>> hierarchies) {
716 String hierarchyString = null;
718 for (ArrayList<String> hierarchy : hierarchies) {
719 StringBuffer buf = new StringBuffer();
720 buf.append("Hierarchy#" + num + " : ");
721 for (String switchName : hierarchy) {
722 buf.append(switchName + "/");
724 logger.debug("{} -> {}", getContainerName(), buf.toString());
730 * getHostNetworkHierarchy is the Back-end routine for the North-Bound API that returns
731 * the Network Hierarchy for a given Host. This API is typically used by applications like
732 * Hadoop for Rack Awareness functionality.
734 * @param hostAddress IP-Address of the host/node.
735 * @return Network Hierarchies represented by an Array of Array (of Switch-Ids as String).
737 public List<List<String>> getHostNetworkHierarchy(InetAddress hostAddress) {
738 HostNodeConnector host = hostQuery(hostAddress);
742 List<List<String>> hierarchies = new ArrayList<List<String>>();
743 ArrayList<String> currHierarchy = new ArrayList<String>();
744 hierarchies.add(currHierarchy);
746 Node node = host.getnodeconnectorNode();
747 updateCurrentHierarchy(node, currHierarchy, hierarchies);
752 * dpidToHostNameHack is a hack function for Cisco Live Hadoop Demo.
753 * Mininet is used as the network for Hadoop Demos & in order to give a meaningful
754 * rack-awareness switch names, the DPID is organized in ASCII Characters and
755 * retrieved as string.
757 * @param dpid Switch DataPath Id
758 * @return Ascii String represented by the DPID.
760 private String dpidToHostNameHack(long dpid) {
761 String hex = Long.toHexString(dpid);
763 StringBuffer sb = new StringBuffer();
765 for (int i = 0; i < hex.length(); i++) {
766 result = (int) ((dpid >> (i * 8)) & 0xff);
771 sb.append(String.format("%c", result));
773 return sb.reverse().toString();
777 * A convenient recursive routine to obtain the Hierarchy of Switches.
779 * @param node Current Node in the Recursive routine.
780 * @param currHierarchy Array of Nodes that make this hierarchy on which the Current Switch belong
781 * @param fullHierarchy Array of multiple Hierarchies that represent a given host.
783 @SuppressWarnings("unchecked")
784 private void updateCurrentHierarchy(Node node,
785 ArrayList<String> currHierarchy, List<List<String>> fullHierarchy) {
786 //currHierarchy.add(String.format("%x", currSw.getId()));
787 currHierarchy.add(dpidToHostNameHack((Long) node.getID()));
788 ArrayList<String> currHierarchyClone = (ArrayList<String>) currHierarchy
789 .clone(); //Shallow copy as required
791 Map<Node, Set<Edge>> ndlinks = topologyManager.getNodeEdges();
792 if (ndlinks == null) {
795 "updateCurrentHierarchy(): topologyManager returned null ndlinks for node: {}",
799 Node n = NodeCreator.createOFNode((Long) node.getID());
800 Set<Edge> links = ndlinks.get(n);
802 logger.debug("updateCurrentHierarchy(): Null links for ndlinks");
805 for (Edge lt : links) {
806 if (!lt.getHeadNodeConnector().getType().equals(
807 NodeConnector.NodeConnectorIDType.OPENFLOW)) {
808 // We don't want to work on Node that are not openflow
812 Node dstNode = lt.getHeadNodeConnector().getNode();
814 Tier nodeTier = (Tier) switchManager.getNodeProp(node,
816 Tier dstNodeTier = (Tier) switchManager.getNodeProp(dstNode,
818 if (dstNodeTier.getValue() > nodeTier.getValue()) {
819 ArrayList<String> buildHierarchy = currHierarchy;
820 if (currHierarchy.size() > currHierarchyClone.size()) {
821 buildHierarchy = (ArrayList<String>) currHierarchyClone
822 .clone(); //Shallow copy as required
823 fullHierarchy.add(buildHierarchy);
825 updateCurrentHierarchy(dstNode, buildHierarchy, fullHierarchy);
831 public void edgeUpdate(Edge e, UpdateType type, Set<Property> props) {
833 Short srcPort = null;
835 Short dstPort = null;
836 boolean added = false;
837 String srcType = null;
838 String dstType = null;
840 if (e == null || type == null) {
841 logger.error("Edge or Update type are null!");
844 srcType = e.getTailNodeConnector().getType();
845 dstType = e.getHeadNodeConnector().getType();
847 if (srcType.equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) {
848 logger.debug("Skip updates for {}", e);
852 if (!srcType.equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) {
853 logger.error("For now we cannot handle updates for "
854 + "non-openflow nodes");
858 if (dstType.equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) {
859 logger.debug("Skip updates for {}", e);
863 if (!dstType.equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) {
864 logger.error("For now we cannot handle updates for "
865 + "non-openflow nodes");
869 // At this point we know we got an openflow update, so
870 // lets fill everything accordingly.
871 srcNid = (Long) e.getTailNodeConnector().getNode()
873 srcPort = (Short) e.getTailNodeConnector().getID();
874 dstNid = (Long) e.getHeadNodeConnector().getNode()
876 dstPort = (Short) e.getHeadNodeConnector().getID();
878 // Now lets update the added flag
889 logger.debug("HostTracker Topology linkUpdate handling src:{}[port {}] dst:{}[port {}] added: {}",
890 new Object[] { srcNid, srcPort, dstNid, dstPort, added });
892 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
893 HostNodeConnector host = entry.getValue();
894 Node node = host.getnodeconnectorNode();
896 Tier t = new Tier(1);
897 switchManager.setNodeProp(node, t);
898 updateSwitchTiers(node, 1);
903 public void subnetNotify(Subnet sub, boolean add) {
904 logger.debug("Received subnet notification: {} add={}", sub, add);
906 for (int i = 0; i < failedARPReqList.size(); i++) {
908 arphost = failedARPReqList.get(i);
910 "Sending the ARP from FailedARPReqList fors IP: {}",
911 arphost.getHostIP().getHostAddress());
912 hostFinder.find(arphost.getHostIP());
917 class OutStandingARPHandler extends TimerTask {
920 /* This routine runs every 4 seconds */
921 // logger.info ("ARP Handler called");
922 for (int i = 0; i < ARPPendingList.size(); i++) {
923 arphost = ARPPendingList.get(i);
924 if (arphost.getSent_count() < switchManager.getHostRetryCount()) {
925 /* No reply has been received of first ARP Req, send the next one */
926 hostFinder.find(arphost.getHostIP());
927 arphost.sent_count++;
928 logger.debug("ARP Sent from ARPPending List, IP: {}",
929 arphost.getHostIP().getHostAddress());
930 } else if (arphost.getSent_count() >= switchManager
931 .getHostRetryCount()) {
932 /* Two ARP requests have been sent without
933 * receiving a reply, remove this from the
936 removePendingARPFromList(i);
939 "ARP reply not received after two attempts, removing from Pending List IP: {}",
940 arphost.getHostIP().getHostAddress());
942 * Add this host to a different list which will be processed on link
945 logger.debug("Adding the host to FailedARPReqList IP: {}",
946 arphost.getHostIP().getHostAddress());
947 failedARPReqList.add(arphost);
952 "Inavlid arp_sent count for entery at index: {}",
959 private class ARPRefreshHandler extends TimerTask {
960 @SuppressWarnings("deprecation")
962 if ((clusterContainerService != null)
963 && !clusterContainerService.amICoordinator()) {
966 if ((switchManager != null)
967 && !switchManager.isHostRefreshEnabled()) {
969 * The host probe procedure was disabled by CLI
973 if (hostsDB == null) {
974 /* hostsDB is not allocated yet */
976 .error("ARPRefreshHandler(): hostsDB is not allocated yet:");
979 for (Entry<InetAddress, HostNodeConnector> entry : hostsDB
981 HostNodeConnector host = entry.getValue();
982 if (host.isStaticHost()) {
983 /* this host was learned via API3, don't age it out */
987 short arp_cntdown = host.getArpSendCountDown();
989 if (arp_cntdown > switchManager.getHostRetryCount()) {
990 host.setArpSendCountDown(arp_cntdown);
991 } else if (arp_cntdown <= 0) {
992 /* No ARP Reply received in last 2 minutes, remove this host and inform applications*/
993 removeKnownHost(entry.getKey());
994 notifyHostLearnedOrRemoved(host, false);
995 } else if (arp_cntdown <= switchManager.getHostRetryCount()) {
996 /* Use the services of arphandler to check if host is still there */
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