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