HostTracker Bundle Separation
[controller.git] / opendaylight / hosttracker / implementation / src / main / java / org / opendaylight / controller / hosttracker / internal / HostTracker.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.controller.hosttracker.internal;
10
11 import java.net.InetAddress;
12 import java.net.UnknownHostException;
13 import java.util.ArrayList;
14 import java.util.Collections;
15 import java.util.Dictionary;
16 import java.util.EnumSet;
17 import java.util.HashSet;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Map.Entry;
21 import java.util.Set;
22 import java.util.Timer;
23 import java.util.TimerTask;
24 import java.util.concurrent.Callable;
25 import java.util.concurrent.ConcurrentHashMap;
26 import java.util.concurrent.ConcurrentMap;
27 import java.util.concurrent.ExecutorService;
28 import java.util.concurrent.Executors;
29 import java.util.concurrent.Future;
30
31 import org.apache.felix.dm.Component;
32 import org.opendaylight.controller.clustering.services.CacheConfigException;
33 import org.opendaylight.controller.clustering.services.CacheExistException;
34 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
35 import org.opendaylight.controller.clustering.services.IClusterServices;
36 import org.opendaylight.controller.hosttracker.IfHostListener;
37 import org.opendaylight.controller.hosttracker.IfIptoHost;
38 import org.opendaylight.controller.hosttracker.IfNewHostNotify;
39 import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
40 import org.opendaylight.controller.hosttracker.hostAware.IHostFinder;
41 import org.opendaylight.controller.sal.core.ConstructionException;
42 import org.opendaylight.controller.sal.core.Edge;
43 import org.opendaylight.controller.sal.core.Host;
44 import org.opendaylight.controller.sal.core.Node;
45 import org.opendaylight.controller.sal.core.NodeConnector;
46 import org.opendaylight.controller.sal.core.Property;
47 import org.opendaylight.controller.sal.core.State;
48 import org.opendaylight.controller.sal.core.Tier;
49 import org.opendaylight.controller.sal.core.UpdateType;
50 import org.opendaylight.controller.sal.packet.address.DataLinkAddress;
51 import org.opendaylight.controller.sal.packet.address.EthernetAddress;
52 import org.opendaylight.controller.sal.topology.TopoEdgeUpdate;
53 import org.opendaylight.controller.sal.utils.GlobalConstants;
54 import org.opendaylight.controller.sal.utils.HexEncode;
55 import org.opendaylight.controller.sal.utils.NodeCreator;
56 import org.opendaylight.controller.sal.utils.Status;
57 import org.opendaylight.controller.sal.utils.StatusCode;
58 import org.opendaylight.controller.switchmanager.IInventoryListener;
59 import org.opendaylight.controller.switchmanager.ISwitchManager;
60 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
61 import org.opendaylight.controller.switchmanager.Subnet;
62 import org.opendaylight.controller.topologymanager.ITopologyManager;
63 import org.opendaylight.controller.topologymanager.ITopologyManagerAware;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66
67 /**
68  * @file HostTracker.java This class tracks the location of IP Hosts as to which
69  *       Switch, Port, VLAN, they are connected to, as well as their MAC
70  *       address. This is done dynamically as well as statically. The dynamic
71  *       mechanism consists of listening to ARP messages as well sending ARP
72  *       requests. Static mechanism consists of Northbound APIs to add or remove
73  *       the hosts from the local database. ARP aging is also implemented to age
74  *       out dynamically learned hosts. Interface methods are provided for other
75  *       applications to 1. Query the local database for a single host 2. Get a
76  *       list of all hosts 3. Get notification if a host is learned/added or
77  *       removed the database
78  */
79
80 public class HostTracker implements IfIptoHost, IfHostListener,
81         ISwitchManagerAware, IInventoryListener, ITopologyManagerAware {
82     private static final Logger logger = LoggerFactory
83             .getLogger(HostTracker.class);
84     private IHostFinder hostFinder;
85     private ConcurrentMap<InetAddress, HostNodeConnector> hostsDB;
86     /*
87      * Following is a list of hosts which have been requested by NB APIs to be
88      * added, but either the switch or the port is not sup, so they will be
89      * added here until both come up
90      */
91     private ConcurrentMap<NodeConnector, HostNodeConnector> inactiveStaticHosts;
92     private Set<IfNewHostNotify> newHostNotify = Collections
93             .synchronizedSet(new HashSet<IfNewHostNotify>());
94
95     private ITopologyManager topologyManager;
96     private IClusterContainerServices clusterContainerService = null;
97     private ISwitchManager switchManager = null;
98     private Timer timer;
99     private Timer arp_refresh_timer;
100     private String containerName = null;
101
102     private static class ARPPending {
103         protected InetAddress hostIP;
104         protected short sent_count;
105         protected HostTrackerCallable hostTrackerCallable;
106
107         public InetAddress getHostIP() {
108             return hostIP;
109         }
110
111         public short getSent_count() {
112             return sent_count;
113         }
114
115         public HostTrackerCallable getHostTrackerCallable() {
116             return hostTrackerCallable;
117         }
118
119         public void setHostIP(InetAddress networkAddr) {
120             this.hostIP = networkAddr;
121         }
122
123         public void setSent_count(short count) {
124             this.sent_count = count;
125         }
126
127         public void setHostTrackerCallable(HostTrackerCallable callable) {
128             hostTrackerCallable = callable;
129         }
130     }
131
132     // This list contains the hosts for which ARP requests are being sent
133     // periodically
134     private List<ARPPending> ARPPendingList = new ArrayList<HostTracker.ARPPending>();
135     /*
136      * This list below contains the hosts which were initially in ARPPendingList
137      * above, but ARP response didn't come from there hosts after multiple
138      * attempts over 8 seconds. The assumption is that the response didn't come
139      * back due to one of the following possibilities: 1. The L3 interface
140      * wasn't created for this host in the controller. This would cause
141      * arphandler not to know where to send the ARP 2. The host facing port is
142      * down 3. The IP host doesn't exist or is not responding to ARP requests
143      *
144      * Conditions 1 and 2 above can be recovered if ARP is sent when the
145      * relevant L3 interface is added or the port facing host comes up. Whenever
146      * L3 interface is added or host facing port comes up, ARP will be sent to
147      * hosts in this list.
148      *
149      * We can't recover from condition 3 above
150      */
151     private ArrayList<ARPPending> failedARPReqList = new ArrayList<HostTracker.ARPPending>();
152
153     public HostTracker() {
154     }
155
156     private void startUp() {
157         allocateCache();
158         retrieveCache();
159
160         timer = new Timer();
161         timer.schedule(new OutStandingARPHandler(), 4000, 4000);
162
163         /* ARP Refresh Timer to go off every 5 seconds to implement ARP aging */
164         arp_refresh_timer = new Timer();
165         arp_refresh_timer.schedule(new ARPRefreshHandler(), 5000, 5000);
166         logger.debug("startUp: Caches created, timers started");
167     }
168
169     @SuppressWarnings("deprecation")
170     private void allocateCache() {
171         if (this.clusterContainerService == null) {
172             logger.error("un-initialized clusterContainerService, can't create cache");
173             return;
174         }
175         logger.debug("Creating Cache for HostTracker");
176         try {
177             this.clusterContainerService.createCache("hostTrackerAH",
178                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
179             this.clusterContainerService.createCache("hostTrackerIH",
180                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
181         } catch (CacheConfigException cce) {
182             logger.error("Cache couldn't be created for HostTracker -  check cache mode");
183         } catch (CacheExistException cce) {
184             logger.error("Cache for HostTracker already exists, destroy and recreate");
185         }
186         logger.debug("Cache successfully created for HostTracker");
187     }
188
189     @SuppressWarnings({ "unchecked", "deprecation" })
190     private void retrieveCache() {
191         if (this.clusterContainerService == null) {
192             logger.error("un-initialized clusterContainerService, can't retrieve cache");
193             return;
194         }
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");
200         }
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");
207         }
208         logger.debug("Cache was successfully retrieved for HostTrackerIH");
209     }
210
211     public void nonClusterObjectCreate() {
212         hostsDB = new ConcurrentHashMap<InetAddress, HostNodeConnector>();
213         inactiveStaticHosts = new ConcurrentHashMap<NodeConnector, HostNodeConnector>();
214     }
215
216     @SuppressWarnings("deprecation")
217     private void destroyCache() {
218         if (this.clusterContainerService == null) {
219             logger.error("un-initialized clusterMger, can't destroy cache");
220             return;
221         }
222         logger.debug("Destroying Cache for HostTracker");
223         this.clusterContainerService.destroyCache("hostTrackerAH");
224         this.clusterContainerService.destroyCache("hostTrackerIH");
225         nonClusterObjectCreate();
226     }
227
228     public void shutDown() {
229     }
230
231     public void setnewHostNotify(IfNewHostNotify obj) {
232         this.newHostNotify.add(obj);
233     }
234
235     public void unsetnewHostNotify(IfNewHostNotify obj) {
236         this.newHostNotify.remove(obj);
237     }
238
239     public void setArpHandler(IHostFinder hostFinder) {
240         this.hostFinder = hostFinder;
241     }
242
243     public void unsetArpHandler(IHostFinder hostFinder) {
244         if (this.hostFinder == hostFinder) {
245             logger.debug("Arp Handler Service removed!");
246             this.hostFinder = null;
247         }
248     }
249
250     public void setTopologyManager(ITopologyManager s) {
251         this.topologyManager = s;
252     }
253
254     public void unsetTopologyManager(ITopologyManager s) {
255         if (this.topologyManager == s) {
256             logger.debug("Topology Manager Service removed!");
257             this.topologyManager = null;
258         }
259     }
260
261     private boolean hostExists(HostNodeConnector host) {
262         HostNodeConnector lhost = hostsDB.get(host.getNetworkAddress());
263         return host.equals(lhost);
264     }
265
266     private HostNodeConnector getHostFromOnActiveDB(InetAddress networkAddress) {
267         return hostsDB.get(networkAddress);
268     }
269
270     private Entry<NodeConnector, HostNodeConnector> getHostFromInactiveDB(
271             InetAddress networkAddress) {
272         for (Entry<NodeConnector, HostNodeConnector> entry : inactiveStaticHosts
273                 .entrySet()) {
274             if (entry.getValue().equalsByIP(networkAddress)) {
275                 logger.debug(
276                         "getHostFromInactiveDB(): Inactive Host found for IP:{} ",
277                         networkAddress.getHostAddress());
278                 return entry;
279             }
280         }
281         logger.debug(
282                 "getHostFromInactiveDB() Inactive Host Not found for IP: {}",
283                 networkAddress.getHostAddress());
284         return null;
285     }
286
287     private void removeHostFromInactiveDB(InetAddress networkAddress) {
288         NodeConnector nodeConnector = null;
289         for (Entry<NodeConnector, HostNodeConnector> entry : inactiveStaticHosts
290                 .entrySet()) {
291             if (entry.getValue().equalsByIP(networkAddress)) {
292                 nodeConnector = entry.getKey();
293                 break;
294             }
295         }
296         if (nodeConnector != null) {
297             inactiveStaticHosts.remove(nodeConnector);
298             logger.debug("removeHostFromInactiveDB(): Host Removed for IP: {}",
299                     networkAddress.getHostAddress());
300             return;
301         }
302         logger.debug("removeHostFromInactiveDB(): Host Not found for IP: {}",
303                 networkAddress.getHostAddress());
304     }
305
306     protected boolean hostMoved(HostNodeConnector host) {
307         if (hostQuery(host.getNetworkAddress()) != null) {
308             return true;
309         }
310         return false;
311     }
312
313     public HostNodeConnector hostQuery(InetAddress networkAddress) {
314         return hostsDB.get(networkAddress);
315     }
316
317     public Future<HostNodeConnector> discoverHost(InetAddress networkAddress) {
318         ExecutorService executor = Executors.newFixedThreadPool(1);
319         if (executor == null) {
320             logger.error("discoverHost: Null executor");
321             return null;
322         }
323         Callable<HostNodeConnector> worker = new HostTrackerCallable(this,
324                 networkAddress);
325         Future<HostNodeConnector> submit = executor.submit(worker);
326         return submit;
327     }
328
329     public HostNodeConnector hostFind(InetAddress networkAddress) {
330         /*
331          * Sometimes at boot with containers configured in the startup we hit
332          * this path (from TIF) when hostFinder has not been set yet Caller
333          * already handles the null return
334          */
335
336         if (hostFinder == null) {
337             logger.debug("Exiting hostFind, null hostFinder");
338             return null;
339         }
340
341         HostNodeConnector host = hostQuery(networkAddress);
342         if (host != null) {
343             logger.debug("hostFind(): Host found for IP: {}",
344                     networkAddress.getHostAddress());
345             return host;
346         }
347         /* host is not found, initiate a discovery */
348         hostFinder.find(networkAddress);
349         /* Also add this host to ARPPending List for any potential retries */
350         AddtoARPPendingList(networkAddress);
351         logger.debug(
352                 "hostFind(): Host Not Found for IP: {}, Inititated Host Discovery ...",
353                 networkAddress.getHostAddress());
354         return null;
355     }
356
357     public Set<HostNodeConnector> getAllHosts() {
358         Set<HostNodeConnector> allHosts = new HashSet<HostNodeConnector>();
359         for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
360             HostNodeConnector host = entry.getValue();
361             allHosts.add(host);
362         }
363         logger.debug("Exiting getAllHosts, Found {} Hosts", allHosts.size());
364         return allHosts;
365     }
366
367     @Override
368     public Set<HostNodeConnector> getActiveStaticHosts() {
369         Set<HostNodeConnector> list = new HashSet<HostNodeConnector>();
370         for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
371             HostNodeConnector host = entry.getValue();
372             if (host.isStaticHost()) {
373                 list.add(host);
374             }
375         }
376         logger.debug("getActiveStaticHosts(): Found {} Hosts", list.size());
377         return list;
378     }
379
380     @Override
381     public Set<HostNodeConnector> getInactiveStaticHosts() {
382         Set<HostNodeConnector> list = new HashSet<HostNodeConnector>();
383         for (Entry<NodeConnector, HostNodeConnector> entry : inactiveStaticHosts
384                 .entrySet()) {
385             list.add(entry.getValue());
386         }
387         logger.debug("getInactiveStaticHosts(): Found {} Hosts", list.size());
388         return list;
389     }
390
391     private void AddtoARPPendingList(InetAddress networkAddr) {
392         ARPPending arphost = new ARPPending();
393
394         arphost.setHostIP(networkAddr);
395         arphost.setSent_count((short) 1);
396         ARPPendingList.add(arphost);
397         logger.debug("Host Added to ARPPending List, IP: {}", networkAddr);
398     }
399
400     private void removePendingARPFromList(int index) {
401         if (index >= ARPPendingList.size()) {
402             logger.warn(
403                     "removePendingARPFromList(): index greater than the List. Size:{}, Index:{}",
404                     ARPPendingList.size(), index);
405             return;
406         }
407         ARPPending arphost = ARPPendingList.remove(index);
408         HostTrackerCallable htCallable = arphost.getHostTrackerCallable();
409         if (htCallable != null)
410             htCallable.wakeup();
411     }
412
413     public void setCallableOnPendingARP(InetAddress networkAddr,
414             HostTrackerCallable callable) {
415         ARPPending arphost;
416         for (int i = 0; i < ARPPendingList.size(); i++) {
417             arphost = ARPPendingList.get(i);
418             if (arphost.getHostIP().equals(networkAddr)) {
419                 arphost.setHostTrackerCallable(callable);
420             }
421         }
422     }
423
424     private void ProcPendingARPReqs(InetAddress networkAddr) {
425         ARPPending arphost;
426
427         for (int i = 0; i < ARPPendingList.size(); i++) {
428             arphost = ARPPendingList.get(i);
429             if (arphost.getHostIP().equals(networkAddr)) {
430                 /*
431                  * An ARP was sent for this host. The address is learned, remove
432                  * the request
433                  */
434                 removePendingARPFromList(i);
435                 logger.debug("Host Removed from ARPPending List, IP: {}",
436                         networkAddr);
437                 return;
438             }
439         }
440
441         /*
442          * It could have been a host from the FailedARPReqList
443          */
444
445         for (int i = 0; i < failedARPReqList.size(); i++) {
446             arphost = failedARPReqList.get(i);
447             if (arphost.getHostIP().equals(networkAddr)) {
448                 /*
449                  * An ARP was sent for this host. The address is learned, remove
450                  * the request
451                  */
452                 failedARPReqList.remove(i);
453                 logger.debug("Host Removed from FailedARPReqList List, IP: {}",
454                         networkAddr);
455                 return;
456             }
457         }
458     }
459
460     // Learn a new Host
461     private void learnNewHost(HostNodeConnector host) {
462         host.initArpSendCountDown();
463         hostsDB.put(host.getNetworkAddress(), host);
464         logger.debug("New Host Learned: MAC: {}  IP: {}",
465                 HexEncode.bytesToHexString(host.getDataLayerAddressBytes()),
466                 host.getNetworkAddress().getHostAddress());
467     }
468
469     // Remove known Host
470     private void removeKnownHost(InetAddress key) {
471         HostNodeConnector host = hostsDB.get(key);
472         if (host != null) {
473             logger.debug("Removing Host: IP:{}", host.getNetworkAddress()
474                     .getHostAddress());
475             hostsDB.remove(key);
476         } else {
477             logger.error(
478                     "removeKnownHost(): Host for IP address {} not found in hostsDB",
479                     key.getHostAddress());
480         }
481     }
482
483     private class NotifyHostThread extends Thread {
484
485         private HostNodeConnector host;
486
487         public NotifyHostThread(HostNodeConnector h) {
488             this.host = h;
489         }
490
491         public void run() {
492             /* Check for Host Move case */
493             if (hostMoved(host)) {
494                 /*
495                  * Host has been moved from one location (switch,port, MAC, or
496                  * VLAN). Remove the existing host with its previous location
497                  * parameters, inform the applications, and add it as a new Host
498                  */
499                 HostNodeConnector removedHost = hostsDB.get(host
500                         .getNetworkAddress());
501                 removeKnownHost(host.getNetworkAddress());
502                 if (removedHost != null) {
503                     notifyHostLearnedOrRemoved(removedHost, false);
504                     logger.debug(
505                             "Host move occurred. Old Host:{}, New Host: {}",
506                             removedHost, host);
507                 } else {
508                     logger.error(
509                             "Host to be removed not found in hostsDB. Host {}",
510                             removedHost);
511                 }
512             }
513
514             /* check if there is an outstanding request for this host */
515             InetAddress networkAddr = host.getNetworkAddress();
516
517             // add and notify
518             learnNewHost(host);
519             ProcPendingARPReqs(networkAddr);
520             notifyHostLearnedOrRemoved(host, true);
521         }
522     }
523
524     public void hostListener(HostNodeConnector host) {
525
526         if (hostExists(host)) {
527             logger.debug("ARP received for Host: {}", host);
528             HostNodeConnector existinghost = hostsDB.get(host
529                     .getNetworkAddress());
530             existinghost.initArpSendCountDown();
531             return;
532         }
533         new NotifyHostThread(host).start();
534     }
535
536     // Notify whoever is interested that a new host was learned (dynamically or
537     // statically)
538     private void notifyHostLearnedOrRemoved(HostNodeConnector host, boolean add) {
539         // Update listeners if any
540         if (newHostNotify != null) {
541             synchronized (this.newHostNotify) {
542                 for (IfNewHostNotify ta : newHostNotify) {
543                     try {
544                         if (add) {
545                             ta.notifyHTClient(host);
546                         } else {
547                             ta.notifyHTClientHostRemoved(host);
548                         }
549                     } catch (Exception e) {
550                         logger.error("Exception on callback", e);
551                     }
552                 }
553             }
554         } else {
555             logger.error("notifyHostLearnedOrRemoved(): New host notify is null");
556         }
557
558         // Topology update is for some reason outside of listeners registry
559         // logic
560         Node node = host.getnodeconnectorNode();
561         Host h = null;
562         NodeConnector p = host.getnodeConnector();
563         try {
564             DataLinkAddress dla = new EthernetAddress(
565                     host.getDataLayerAddressBytes());
566             h = new org.opendaylight.controller.sal.core.Host(dla,
567                     host.getNetworkAddress());
568         } catch (ConstructionException ce) {
569             p = null;
570             h = null;
571         }
572
573         if (topologyManager != null && p != null && h != null) {
574             if (add == true) {
575                 Tier tier = new Tier(1);
576                 switchManager.setNodeProp(node, tier);
577                 topologyManager.updateHostLink(p, h, UpdateType.ADDED, null);
578             } else {
579                 // No need to reset the tiering if no other hosts are currently
580                 // connected
581                 // If this switch was discovered to be an access switch, it
582                 // still is even if the host is down
583                 Tier tier = new Tier(0);
584                 switchManager.setNodeProp(node, tier);
585                 topologyManager.updateHostLink(p, h, UpdateType.REMOVED, null);
586             }
587         }
588     }
589
590     /**
591      * When a new Host is learnt by the hosttracker module, it places the
592      * directly connected Node in Tier-1 & using this function, updates the Tier
593      * value for all other Nodes in the network hierarchy.
594      *
595      * This is a recursive function and it takes care of updating the Tier value
596      * for all the connected and eligible Nodes.
597      *
598      * @param n
599      *            Node that represents one of the Vertex in the Topology Graph.
600      * @param currentTier
601      *            The Tier on which n belongs
602      */
603     private void updateSwitchTiers(Node n, int currentTier) {
604         Map<Node, Set<Edge>> ndlinks = topologyManager.getNodeEdges();
605         if (ndlinks == null) {
606             logger.debug(
607                     "updateSwitchTiers(): ndlinks null for Node: {}, Tier:{}",
608                     n, currentTier);
609             return;
610         }
611         Set<Edge> links = ndlinks.get(n);
612         if (links == null) {
613             logger.debug("updateSwitchTiers(): links null for ndlinks:{}",
614                     ndlinks);
615             return;
616         }
617         ArrayList<Node> needsVisiting = new ArrayList<Node>();
618         for (Edge lt : links) {
619             if (!lt.getHeadNodeConnector().getType()
620                     .equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) {
621                 // We don't want to work on Node that are not openflow
622                 // for now
623                 continue;
624             }
625             Node dstNode = lt.getHeadNodeConnector().getNode();
626             if (switchNeedsTieringUpdate(dstNode, currentTier + 1)) {
627                 Tier t = new Tier(currentTier + 1);
628                 switchManager.setNodeProp(dstNode, t);
629                 needsVisiting.add(dstNode);
630             }
631         }
632
633         /*
634          * Due to the nature of the problem, having a separate loop for nodes
635          * that needs visiting provides a decent walk optimization.
636          */
637         for (Node node : needsVisiting) {
638             updateSwitchTiers(node, currentTier + 1);
639         }
640     }
641
642     /**
643      * Internal convenience routine to check the eligibility of a Switch for a
644      * Tier update. Any Node with Tier=0 or a Tier value that is greater than
645      * the new Tier Value is eligible for the update.
646      *
647      * @param n
648      *            Node for which the Tier update eligibility is checked
649      * @param tier
650      *            new Tier Value
651      * @return <code>true</code> if the Node is eligible for Tier Update
652      *         <code>false</code> otherwise
653      */
654
655     private boolean switchNeedsTieringUpdate(Node n, int tier) {
656         if (n == null) {
657             logger.error("switchNeedsTieringUpdate(): Null node for tier: {}",
658                     tier);
659             return false;
660         }
661         /*
662          * Node could have gone down
663          */
664         if (!switchManager.getNodes().contains(n)) {
665             return false;
666         }
667         // This is the case where Tier was never set for this node
668         Tier t = (Tier) switchManager.getNodeProp(n, Tier.TierPropName);
669         if (t == null)
670             return true;
671         if (t.getValue() == 0)
672             return true;
673         else if (t.getValue() > tier)
674             return true;
675         return false;
676     }
677
678     /**
679      * Internal convenience routine to clear all the Tier values to 0. This
680      * cleanup is performed during cases such as Topology Change where the
681      * existing Tier values might become incorrect
682      */
683     private void clearTiers() {
684         Set<Node> nodes = null;
685         if (switchManager == null) {
686             logger.error("clearTiers(): Null switchManager");
687             return;
688         }
689         nodes = switchManager.getNodes();
690
691         for (Node n : nodes) {
692             Tier t = new Tier(0);
693             switchManager.setNodeProp(n, t);
694         }
695     }
696
697     /**
698      * Internal convenience routine to print the hierarchies of switches.
699      */
700     @SuppressWarnings("unused")
701     private void logHierarchies(ArrayList<ArrayList<String>> hierarchies) {
702         String hierarchyString = null;
703         int num = 1;
704         for (ArrayList<String> hierarchy : hierarchies) {
705             StringBuffer buf = new StringBuffer();
706             buf.append("Hierarchy#" + num + " : ");
707             for (String switchName : hierarchy) {
708                 buf.append(switchName + "/");
709             }
710             logger.debug("{} -> {}", getContainerName(), buf);
711             num++;
712         }
713     }
714
715     /**
716      * getHostNetworkHierarchy is the Back-end routine for the North-Bound API
717      * that returns the Network Hierarchy for a given Host. This API is
718      * typically used by applications like Hadoop for Rack Awareness
719      * functionality.
720      *
721      * @param hostAddress
722      *            IP-Address of the host/node.
723      * @return Network Hierarchies represented by an Array of Array (of
724      *         Switch-Ids as String).
725      */
726     public List<List<String>> getHostNetworkHierarchy(InetAddress hostAddress) {
727         HostNodeConnector host = hostQuery(hostAddress);
728         if (host == null)
729             return null;
730
731         List<List<String>> hierarchies = new ArrayList<List<String>>();
732         ArrayList<String> currHierarchy = new ArrayList<String>();
733         hierarchies.add(currHierarchy);
734
735         Node node = host.getnodeconnectorNode();
736         updateCurrentHierarchy(node, currHierarchy, hierarchies);
737         return hierarchies;
738     }
739
740     /**
741      * dpidToHostNameHack is a hack function for Cisco Live Hadoop Demo. Mininet
742      * is used as the network for Hadoop Demos & in order to give a meaningful
743      * rack-awareness switch names, the DPID is organized in ASCII Characters
744      * and retrieved as string.
745      *
746      * @param dpid
747      *            Switch DataPath Id
748      * @return Ascii String represented by the DPID.
749      */
750     private String dpidToHostNameHack(long dpid) {
751         String hex = Long.toHexString(dpid);
752
753         StringBuffer sb = new StringBuffer();
754         int result = 0;
755         for (int i = 0; i < hex.length(); i++) {
756             result = (int) ((dpid >> (i * 8)) & 0xff);
757             if (result == 0)
758                 continue;
759             if (result < 0x30)
760                 result += 0x40;
761             sb.append(String.format("%c", result));
762         }
763         return sb.reverse().toString();
764     }
765
766     /**
767      * A convenient recursive routine to obtain the Hierarchy of Switches.
768      *
769      * @param node
770      *            Current Node in the Recursive routine.
771      * @param currHierarchy
772      *            Array of Nodes that make this hierarchy on which the Current
773      *            Switch belong
774      * @param fullHierarchy
775      *            Array of multiple Hierarchies that represent a given host.
776      */
777     @SuppressWarnings("unchecked")
778     private void updateCurrentHierarchy(Node node,
779             ArrayList<String> currHierarchy, List<List<String>> fullHierarchy) {
780         // currHierarchy.add(String.format("%x", currSw.getId()));
781         currHierarchy.add(dpidToHostNameHack((Long) node.getID()));
782         ArrayList<String> currHierarchyClone = (ArrayList<String>) currHierarchy
783                 .clone(); // Shallow copy as required
784
785         Map<Node, Set<Edge>> ndlinks = topologyManager.getNodeEdges();
786         if (ndlinks == null) {
787             logger.debug(
788                     "updateCurrentHierarchy(): topologyManager returned null ndlinks for node: {}",
789                     node);
790             return;
791         }
792         Node n = NodeCreator.createOFNode((Long) node.getID());
793         Set<Edge> links = ndlinks.get(n);
794         if (links == null) {
795             logger.debug("updateCurrentHierarchy(): Null links for ndlinks");
796             return;
797         }
798         for (Edge lt : links) {
799             if (!lt.getHeadNodeConnector().getType()
800                     .equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) {
801                 // We don't want to work on Node that are not openflow
802                 // for now
803                 continue;
804             }
805             Node dstNode = lt.getHeadNodeConnector().getNode();
806
807             Tier nodeTier = (Tier) switchManager.getNodeProp(node,
808                     Tier.TierPropName);
809             Tier dstNodeTier = (Tier) switchManager.getNodeProp(dstNode,
810                     Tier.TierPropName);
811             if (dstNodeTier.getValue() > nodeTier.getValue()) {
812                 ArrayList<String> buildHierarchy = currHierarchy;
813                 if (currHierarchy.size() > currHierarchyClone.size()) {
814                     buildHierarchy = (ArrayList<String>) currHierarchyClone
815                             .clone(); // Shallow copy as required
816                     fullHierarchy.add(buildHierarchy);
817                 }
818                 updateCurrentHierarchy(dstNode, buildHierarchy, fullHierarchy);
819             }
820         }
821     }
822
823     private void edgeUpdate(Edge e, UpdateType type, Set<Property> props) {
824         Long srcNid = null;
825         Short srcPort = null;
826         Long dstNid = null;
827         Short dstPort = null;
828         boolean added = false;
829         String srcType = null;
830         String dstType = null;
831
832         if (e == null || type == null) {
833             logger.error("Edge or Update type are null!");
834             return;
835         } else {
836             srcType = e.getTailNodeConnector().getType();
837             dstType = e.getHeadNodeConnector().getType();
838
839             if (srcType.equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) {
840                 logger.debug("Skip updates for {}", e);
841                 return;
842             }
843
844             if (!srcType.equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) {
845                 logger.error("For now we cannot handle updates for "
846                         + "non-openflow nodes");
847                 return;
848             }
849
850             if (dstType.equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) {
851                 logger.debug("Skip updates for {}", e);
852                 return;
853             }
854
855             if (!dstType.equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) {
856                 logger.error("For now we cannot handle updates for "
857                         + "non-openflow nodes");
858                 return;
859             }
860
861             // At this point we know we got an openflow update, so
862             // lets fill everything accordingly.
863             srcNid = (Long) e.getTailNodeConnector().getNode().getID();
864             srcPort = (Short) e.getTailNodeConnector().getID();
865             dstNid = (Long) e.getHeadNodeConnector().getNode().getID();
866             dstPort = (Short) e.getHeadNodeConnector().getID();
867
868             // Now lets update the added flag
869             switch (type) {
870             case ADDED:
871             case CHANGED:
872                 added = true;
873                 break;
874             case REMOVED:
875                 added = false;
876             }
877         }
878
879         logger.debug(
880                 "HostTracker Topology linkUpdate handling src:{}[port {}] dst:{}[port {}] added: {}",
881                 new Object[] { srcNid, srcPort, dstNid, dstPort, added });
882     }
883
884     @Override
885     public void edgeUpdate(List<TopoEdgeUpdate> topoedgeupdateList) {
886         for (int i = 0; i < topoedgeupdateList.size(); i++) {
887             Edge e = topoedgeupdateList.get(i).getEdge();
888             Set<Property> p = topoedgeupdateList.get(i).getProperty();
889             UpdateType type = topoedgeupdateList.get(i).getUpdateType();
890             edgeUpdate(e, type, p);
891         }
892     }
893
894     public void subnetNotify(Subnet sub, boolean add) {
895         logger.debug("Received subnet notification: {}  add={}", sub, add);
896         if (add) {
897             for (int i = 0; i < failedARPReqList.size(); i++) {
898                 ARPPending arphost;
899                 arphost = failedARPReqList.get(i);
900                 logger.debug(
901                         "Sending the ARP from FailedARPReqList fors IP: {}",
902                         arphost.getHostIP().getHostAddress());
903                 hostFinder.find(arphost.getHostIP());
904             }
905         }
906     }
907
908     class OutStandingARPHandler extends TimerTask {
909         public void run() {
910             ARPPending arphost;
911             /* This routine runs every 4 seconds */
912             // logger.info ("ARP Handler called");
913             for (int i = 0; i < ARPPendingList.size(); i++) {
914                 arphost = ARPPendingList.get(i);
915                 if (arphost.getSent_count() < switchManager.getHostRetryCount()) {
916                     /*
917                      * No reply has been received of first ARP Req, send the
918                      * next one
919                      */
920                     hostFinder.find(arphost.getHostIP());
921                     arphost.sent_count++;
922                     logger.debug("ARP Sent from ARPPending List, IP: {}",
923                             arphost.getHostIP().getHostAddress());
924                 } else if (arphost.getSent_count() >= switchManager
925                         .getHostRetryCount()) {
926                     /*
927                      * Two ARP requests have been sent without receiving a
928                      * reply, remove this from the pending list
929                      */
930                     removePendingARPFromList(i);
931                     logger.debug(
932                             "ARP reply not received after two attempts, removing from Pending List IP: {}",
933                             arphost.getHostIP().getHostAddress());
934                     /*
935                      * Add this host to a different list which will be processed
936                      * on link up events
937                      */
938                     logger.debug("Adding the host to FailedARPReqList IP: {}",
939                             arphost.getHostIP().getHostAddress());
940                     failedARPReqList.add(arphost);
941
942                 } else {
943                     logger.error(
944                             "Inavlid arp_sent count for entery at index: {}", i);
945                 }
946             }
947         }
948     }
949
950     private class ARPRefreshHandler extends TimerTask {
951         @SuppressWarnings("deprecation")
952         public void run() {
953             if ((clusterContainerService != null)
954                     && !clusterContainerService.amICoordinator()) {
955                 return;
956             }
957             if ((switchManager != null)
958                     && !switchManager.isHostRefreshEnabled()) {
959                 /*
960                  * The host probe procedure was disabled by CLI
961                  */
962                 return;
963             }
964             if (hostsDB == null) {
965                 /* hostsDB is not allocated yet */
966                 logger.error("ARPRefreshHandler(): hostsDB is not allocated yet:");
967                 return;
968             }
969             for (Entry<InetAddress, HostNodeConnector> entry : hostsDB
970                     .entrySet()) {
971                 HostNodeConnector host = entry.getValue();
972                 if (host.isStaticHost()) {
973                     /* this host was learned via API3, don't age it out */
974                     continue;
975                 }
976
977                 short arp_cntdown = host.getArpSendCountDown();
978                 arp_cntdown--;
979                 if (arp_cntdown > switchManager.getHostRetryCount()) {
980                     host.setArpSendCountDown(arp_cntdown);
981                 } else if (arp_cntdown <= 0) {
982                     /*
983                      * No ARP Reply received in last 2 minutes, remove this host
984                      * and inform applications
985                      */
986                     removeKnownHost(entry.getKey());
987                     notifyHostLearnedOrRemoved(host, false);
988                 } else if (arp_cntdown <= switchManager.getHostRetryCount()) {
989                     /*
990                      * Use the services of arphandler to check if host is still
991                      * there
992                      */
993                     if (logger.isTraceEnabled()) {
994                         logger.trace(
995                                 "ARP Probing ({}) for {}({})",
996                                 new Object[] {
997                                         arp_cntdown,
998                                         host.getNetworkAddress()
999                                                 .getHostAddress(),
1000                                         HexEncode.bytesToHexString(host
1001                                                 .getDataLayerAddressBytes()) });
1002                     }
1003                     host.setArpSendCountDown(arp_cntdown);
1004                     hostFinder.probe(host);
1005                 }
1006             }
1007         }
1008     }
1009
1010     /**
1011      * Inform the controller IP to MAC binding of a host and its connectivity to
1012      * an openflow switch in terms of Node, port, and VLAN.
1013      *
1014      * @param networkAddr
1015      *            IP address of the host
1016      * @param dataLayer
1017      *            Address MAC address of the host
1018      * @param nc
1019      *            NodeConnector to which host is connected
1020      * @param port
1021      *            Port of the switch to which host is connected
1022      * @param vlan
1023      *            Vlan of which this host is member of
1024      *
1025      * @return Status The status object as described in {@code Status}
1026      *         indicating the result of this action.
1027      */
1028
1029     public Status addStaticHostReq(InetAddress networkAddr,
1030             byte[] dataLayerAddress, NodeConnector nc, short vlan) {
1031         if (dataLayerAddress.length != 6) {
1032             return new Status(StatusCode.BADREQUEST, "Invalid MAC address");
1033         }
1034
1035         HostNodeConnector host = null;
1036         try {
1037             host = new HostNodeConnector(dataLayerAddress, networkAddr, nc,
1038                     vlan);
1039             if (hostExists(host)) {
1040                 // This host is already learned either via ARP or through a
1041                 // northbound request
1042                 HostNodeConnector transHost = hostsDB.get(networkAddr);
1043                 transHost.setStaticHost(true);
1044                 return new Status(StatusCode.SUCCESS, null);
1045             }
1046             host.setStaticHost(true);
1047             /*
1048              * Before adding host, Check if the switch and the port have already
1049              * come up
1050              */
1051             if (switchManager.isNodeConnectorEnabled(nc)) {
1052                 learnNewHost(host);
1053                 notifyHostLearnedOrRemoved(host, true);
1054             } else {
1055                 inactiveStaticHosts.put(nc, host);
1056                 logger.debug(
1057                         "Switch or switchport is not up, adding host {} to inactive list",
1058                         networkAddr.getHostName());
1059             }
1060             return new Status(StatusCode.SUCCESS, null);
1061         } catch (ConstructionException e) {
1062             return new Status(StatusCode.INTERNALERROR,
1063                     "Host could not be created");
1064         }
1065
1066     }
1067
1068     /**
1069      * Update the controller IP to MAC binding of a host and its connectivity to
1070      * an openflow switch in terms of switch id, switch port, and VLAN.
1071      *
1072      * @param networkAddr
1073      *            IP address of the host
1074      * @param dataLayer
1075      *            Address MAC address of the host
1076      * @param nc
1077      *            NodeConnector to which host is connected
1078      * @param port
1079      *            Port of the switch to which host is connected
1080      * @param vlan
1081      *            Vlan of which this host is member of
1082      *
1083      * @return boolean true if the host was added successfully, false otherwise
1084      */
1085     public boolean updateHostReq(InetAddress networkAddr,
1086             byte[] dataLayerAddress, NodeConnector nc, short vlan) {
1087         if (nc == null) {
1088             return false;
1089         }
1090         HostNodeConnector host = null;
1091         try {
1092             host = new HostNodeConnector(dataLayerAddress, networkAddr, nc,
1093                     vlan);
1094             if (!hostExists(host)) {
1095                 if ((inactiveStaticHosts.get(nc)) != null) {
1096                     inactiveStaticHosts.replace(nc, host);
1097                     return true;
1098                 }
1099                 return false;
1100             }
1101             hostsDB.replace(networkAddr, host);
1102             return true;
1103         } catch (ConstructionException e) {
1104         }
1105         return false;
1106     }
1107
1108     /**
1109      * Remove from the controller IP to MAC binding of a host and its
1110      * connectivity to an openflow switch
1111      *
1112      * @param networkAddr
1113      *            IP address of the host
1114      *
1115      * @return boolean true if the host was removed successfully, false
1116      *         otherwise
1117      */
1118
1119     public Status removeStaticHostReq(InetAddress networkAddress) {
1120         // Check if host is in active hosts database
1121         HostNodeConnector host = getHostFromOnActiveDB(networkAddress);
1122         if (host != null) {
1123             // Validation check
1124             if (!host.isStaticHost()) {
1125                 return new Status(StatusCode.FORBIDDEN, "Host "
1126                         + networkAddress.getHostName() + " is not static");
1127             }
1128             // Remove and notify
1129             notifyHostLearnedOrRemoved(host, false);
1130             removeKnownHost(networkAddress);
1131             return new Status(StatusCode.SUCCESS, null);
1132         }
1133
1134         // Check if host is in inactive hosts database
1135         Entry<NodeConnector, HostNodeConnector> entry = getHostFromInactiveDB(networkAddress);
1136         if (entry != null) {
1137             host = entry.getValue();
1138             // Validation check
1139             if (!host.isStaticHost()) {
1140                 return new Status(StatusCode.FORBIDDEN, "Host "
1141                         + networkAddress.getHostName() + " is not static");
1142             }
1143             this.removeHostFromInactiveDB(networkAddress);
1144             return new Status(StatusCode.SUCCESS, null);
1145         }
1146
1147         // Host is neither in active nor inactive hosts database
1148         return new Status(StatusCode.NOTFOUND, "Host does not exist");
1149     }
1150
1151     @Override
1152     public void modeChangeNotify(Node node, boolean proactive) {
1153         logger.debug("Set Switch {} Mode to {}", node.getID(), proactive);
1154     }
1155
1156     @Override
1157     public void notifyNode(Node node, UpdateType type,
1158             Map<String, Property> propMap) {
1159         if (node == null)
1160             return;
1161
1162         switch (type) {
1163         case REMOVED:
1164             logger.debug("Received removed node {}", node);
1165             for (Entry<InetAddress, HostNodeConnector> entry : hostsDB
1166                     .entrySet()) {
1167                 HostNodeConnector host = entry.getValue();
1168                 if (host.getnodeconnectorNode().equals(node)) {
1169                     logger.debug("Node: {} is down, remove from Hosts_DB", node);
1170                     removeKnownHost(entry.getKey());
1171                     notifyHostLearnedOrRemoved(host, false);
1172                 }
1173             }
1174             break;
1175         default:
1176             break;
1177         }
1178     }
1179
1180     @Override
1181     public void notifyNodeConnector(NodeConnector nodeConnector,
1182             UpdateType type, Map<String, Property> propMap) {
1183         if (nodeConnector == null)
1184             return;
1185
1186         boolean up = false;
1187         switch (type) {
1188         case ADDED:
1189             up = true;
1190             break;
1191         case REMOVED:
1192             break;
1193         case CHANGED:
1194             State state = (State) propMap.get(State.StatePropName);
1195             if ((state != null) && (state.getValue() == State.EDGE_UP)) {
1196                 up = true;
1197             }
1198             break;
1199         default:
1200             return;
1201         }
1202
1203         if (up) {
1204             handleNodeConnectorStatusUp(nodeConnector);
1205         } else {
1206             handleNodeConnectorStatusDown(nodeConnector);
1207         }
1208     }
1209
1210     @Override
1211     public Status addStaticHost(String networkAddress, String dataLayerAddress,
1212             NodeConnector nc, String vlan) {
1213         try {
1214             InetAddress ip = InetAddress.getByName(networkAddress);
1215             if (nc == null) {
1216                 return new Status(StatusCode.BADREQUEST, "Invalid NodeId");
1217             }
1218             return addStaticHostReq(ip,
1219                     HexEncode.bytesFromHexString(dataLayerAddress), nc,
1220                     Short.valueOf(vlan));
1221         } catch (UnknownHostException e) {
1222             logger.error("", e);
1223             return new Status(StatusCode.BADREQUEST, "Invalid Address");
1224         }
1225     }
1226
1227     @Override
1228     public Status removeStaticHost(String networkAddress) {
1229         InetAddress address;
1230         try {
1231             address = InetAddress.getByName(networkAddress);
1232             return removeStaticHostReq(address);
1233         } catch (UnknownHostException e) {
1234             logger.error("", e);
1235             return new Status(StatusCode.BADREQUEST, "Invalid Address");
1236         }
1237     }
1238
1239     private void handleNodeConnectorStatusUp(NodeConnector nodeConnector) {
1240         ARPPending arphost;
1241
1242         logger.debug("handleNodeConnectorStatusUp {}", nodeConnector);
1243
1244         for (int i = 0; i < failedARPReqList.size(); i++) {
1245             arphost = failedARPReqList.get(i);
1246             logger.debug("Sending the ARP from FailedARPReqList fors IP: {}",
1247                     arphost.getHostIP().getHostAddress());
1248             hostFinder.find(arphost.getHostIP());
1249         }
1250         HostNodeConnector host = inactiveStaticHosts.get(nodeConnector);
1251         if (host != null) {
1252             inactiveStaticHosts.remove(nodeConnector);
1253             learnNewHost(host);
1254             notifyHostLearnedOrRemoved(host, true);
1255         }
1256     }
1257
1258     private void handleNodeConnectorStatusDown(NodeConnector nodeConnector) {
1259         logger.debug("handleNodeConnectorStatusDown {}", nodeConnector);
1260
1261         for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
1262             HostNodeConnector host = entry.getValue();
1263             if (host.getnodeConnector().equals(nodeConnector)) {
1264                 logger.debug(
1265                         " NodeConnector: {} is down, remove from Hosts_DB",
1266                         nodeConnector);
1267                 removeKnownHost(entry.getKey());
1268                 notifyHostLearnedOrRemoved(host, false);
1269             }
1270         }
1271     }
1272
1273     void setClusterContainerService(IClusterContainerServices s) {
1274         logger.debug("Cluster Service set");
1275         this.clusterContainerService = s;
1276     }
1277
1278     void unsetClusterContainerService(IClusterContainerServices s) {
1279         if (this.clusterContainerService == s) {
1280             logger.debug("Cluster Service removed!");
1281             this.clusterContainerService = null;
1282         }
1283     }
1284
1285     void setSwitchManager(ISwitchManager s) {
1286         logger.debug("SwitchManager set");
1287         this.switchManager = s;
1288     }
1289
1290     void unsetSwitchManager(ISwitchManager s) {
1291         if (this.switchManager == s) {
1292             logger.debug("SwitchManager removed!");
1293             this.switchManager = null;
1294         }
1295     }
1296
1297     public String getContainerName() {
1298         if (containerName == null)
1299             return GlobalConstants.DEFAULT.toString();
1300         return containerName;
1301     }
1302
1303     /**
1304      * Function called by the dependency manager when all the required
1305      * dependencies are satisfied
1306      *
1307      */
1308     void init(Component c) {
1309         Dictionary<?, ?> props = c.getServiceProperties();
1310         if (props != null) {
1311             this.containerName = (String) props.get("containerName");
1312             logger.debug("Running containerName: {}", this.containerName);
1313         } else {
1314             // In the Global instance case the containerName is empty
1315             this.containerName = "";
1316         }
1317         startUp();
1318     }
1319
1320     /**
1321      * Function called by the dependency manager when at least one dependency
1322      * become unsatisfied or when the component is shutting down because for
1323      * example bundle is being stopped.
1324      *
1325      */
1326     void destroy() {
1327         destroyCache();
1328     }
1329
1330     /**
1331      * Function called by dependency manager after "init ()" is called and after
1332      * the services provided by the class are registered in the service registry
1333      *
1334      */
1335     void start() {
1336     }
1337
1338     /**
1339      * Function called by the dependency manager before the services exported by
1340      * the component are unregistered, this will be followed by a "destroy ()"
1341      * calls
1342      *
1343      */
1344     void stop() {
1345     }
1346
1347     @Override
1348     public void edgeOverUtilized(Edge edge) {
1349         // TODO Auto-generated method stub
1350
1351     }
1352
1353     @Override
1354     public void edgeUtilBackToNormal(Edge edge) {
1355         // TODO Auto-generated method stub
1356
1357     }
1358
1359 }