1. Controller switchEvents queue should be priority based. The queue holds switch...
[controller.git] / opendaylight / switchmanager / implementation / src / main / java / org / opendaylight / controller / switchmanager / internal / SwitchManager.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.switchmanager.internal;
10
11 import java.io.FileNotFoundException;
12 import java.io.IOException;
13 import java.io.ObjectInputStream;
14 import java.net.InetAddress;
15 import java.net.NetworkInterface;
16 import java.net.SocketException;
17 import java.util.ArrayList;
18 import java.util.Collections;
19 import java.util.Dictionary;
20 import java.util.EnumSet;
21 import java.util.Enumeration;
22 import java.util.HashMap;
23 import java.util.HashSet;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Set;
27 import java.util.concurrent.ConcurrentHashMap;
28 import java.util.concurrent.ConcurrentMap;
29 import java.util.concurrent.CopyOnWriteArrayList;
30
31 import org.apache.felix.dm.Component;
32 import org.eclipse.osgi.framework.console.CommandInterpreter;
33 import org.eclipse.osgi.framework.console.CommandProvider;
34 import org.opendaylight.controller.clustering.services.CacheConfigException;
35 import org.opendaylight.controller.clustering.services.CacheExistException;
36 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
37 import org.opendaylight.controller.clustering.services.IClusterServices;
38 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
39 import org.opendaylight.controller.sal.core.Bandwidth;
40 import org.opendaylight.controller.sal.core.Config;
41 import org.opendaylight.controller.sal.core.ConstructionException;
42 import org.opendaylight.controller.sal.core.Description;
43 import org.opendaylight.controller.sal.core.ForwardingMode;
44 import org.opendaylight.controller.sal.core.MacAddress;
45 import org.opendaylight.controller.sal.core.Name;
46 import org.opendaylight.controller.sal.core.Node;
47 import org.opendaylight.controller.sal.core.NodeConnector;
48 import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType;
49 import org.opendaylight.controller.sal.core.Property;
50 import org.opendaylight.controller.sal.core.State;
51 import org.opendaylight.controller.sal.core.Tier;
52 import org.opendaylight.controller.sal.core.UpdateType;
53 import org.opendaylight.controller.sal.inventory.IInventoryService;
54 import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates;
55 import org.opendaylight.controller.sal.reader.NodeDescription;
56 import org.opendaylight.controller.sal.utils.GlobalConstants;
57 import org.opendaylight.controller.sal.utils.HexEncode;
58 import org.opendaylight.controller.sal.utils.IObjectReader;
59 import org.opendaylight.controller.sal.utils.ObjectReader;
60 import org.opendaylight.controller.sal.utils.ObjectWriter;
61 import org.opendaylight.controller.sal.utils.Status;
62 import org.opendaylight.controller.sal.utils.StatusCode;
63 import org.opendaylight.controller.statisticsmanager.IStatisticsManager;
64 import org.opendaylight.controller.switchmanager.IInventoryListener;
65 import org.opendaylight.controller.switchmanager.ISpanAware;
66 import org.opendaylight.controller.switchmanager.ISwitchManager;
67 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
68 import org.opendaylight.controller.switchmanager.SpanConfig;
69 import org.opendaylight.controller.switchmanager.Subnet;
70 import org.opendaylight.controller.switchmanager.SubnetConfig;
71 import org.opendaylight.controller.switchmanager.Switch;
72 import org.opendaylight.controller.switchmanager.SwitchConfig;
73 import org.osgi.framework.BundleContext;
74 import org.osgi.framework.FrameworkUtil;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
77
78 /**
79  * The class describes SwitchManager which is the central repository of all the
80  * inventory data including nodes, node connectors, properties attached, Layer3
81  * configurations, Span configurations, node configurations, network device
82  * representations viewed by Controller Web applications. One SwitchManager
83  * instance per container of the network. All the node/nodeConnector properties
84  * are maintained in the default container only.
85  */
86 public class SwitchManager implements ISwitchManager, IConfigurationContainerAware,
87                                       IObjectReader, IListenInventoryUpdates, CommandProvider {
88     private static Logger log = LoggerFactory.getLogger(SwitchManager.class);
89     private static String ROOT = GlobalConstants.STARTUPHOME.toString();
90     private String subnetFileName, spanFileName, switchConfigFileName;
91     private final List<NodeConnector> spanNodeConnectors = new CopyOnWriteArrayList<NodeConnector>();
92     // Collection of Subnets keyed by the InetAddress
93     private ConcurrentMap<InetAddress, Subnet> subnets;
94     private ConcurrentMap<String, SubnetConfig> subnetsConfigList;
95     private ConcurrentMap<SpanConfig, SpanConfig> spanConfigList;
96     // manually configured parameters for the node such as name, tier, mode
97     private ConcurrentMap<String, SwitchConfig> nodeConfigList;
98     private ConcurrentMap<Node, Map<String, Property>> nodeProps;
99     private ConcurrentMap<NodeConnector, Map<String, Property>> nodeConnectorProps;
100     private ConcurrentMap<Node, Map<String, NodeConnector>> nodeConnectorNames;
101     private ConcurrentMap<String, Property> controllerProps;
102     private IInventoryService inventoryService;
103     private IStatisticsManager statisticsManager;
104     private final Set<ISwitchManagerAware> switchManagerAware = Collections
105             .synchronizedSet(new HashSet<ISwitchManagerAware>());
106     private final Set<IInventoryListener> inventoryListeners = Collections
107             .synchronizedSet(new HashSet<IInventoryListener>());
108     private final Set<ISpanAware> spanAware = Collections.synchronizedSet(new HashSet<ISpanAware>());
109     private static boolean hostRefresh = true;
110     private int hostRetryCount = 5;
111     private IClusterContainerServices clusterContainerService = null;
112     private String containerName = null;
113     private boolean isDefaultContainer = true;
114     private static final int REPLACE_RETRY = 1;
115
116     public void notifySubnetChange(Subnet sub, boolean add) {
117         synchronized (switchManagerAware) {
118             for (Object subAware : switchManagerAware) {
119                 try {
120                     ((ISwitchManagerAware) subAware).subnetNotify(sub, add);
121                 } catch (Exception e) {
122                     log.error("Failed to notify Subnet change {}",
123                             e.getMessage());
124                 }
125             }
126         }
127     }
128
129     public void notifySpanPortChange(Node node, List<NodeConnector> ports, boolean add) {
130         synchronized (spanAware) {
131             for (Object sa : spanAware) {
132                 try {
133                     ((ISpanAware) sa).spanUpdate(node, ports, add);
134                 } catch (Exception e) {
135                     log.error("Failed to notify Span Interface change {}",
136                             e.getMessage());
137                 }
138             }
139         }
140     }
141
142     private void notifyModeChange(Node node, boolean proactive) {
143         synchronized (switchManagerAware) {
144             for (ISwitchManagerAware service : switchManagerAware) {
145                 try {
146                     service.modeChangeNotify(node, proactive);
147                 } catch (Exception e) {
148                     log.error("Failed to notify Subnet change {}",
149                             e.getMessage());
150                 }
151             }
152         }
153     }
154
155     public void startUp() {
156         String container = this.getContainerName();
157         // Initialize configuration file names
158         subnetFileName = ROOT + "subnets_" + container + ".conf";
159         spanFileName = ROOT + "spanPorts_" + container + ".conf";
160         switchConfigFileName = ROOT + "switchConfig_" + container + ".conf";
161
162         // Instantiate cluster synced variables
163         allocateCaches();
164         retrieveCaches();
165
166         /*
167          * Read startup and build database if we have not already gotten the
168          * configurations synced from another node
169          */
170         if (subnetsConfigList.isEmpty()) {
171             loadSubnetConfiguration();
172         }
173         if (spanConfigList.isEmpty()) {
174             loadSpanConfiguration();
175         }
176         if (nodeConfigList.isEmpty()) {
177             loadSwitchConfiguration();
178         }
179
180         // Add controller MAC, if first node in the cluster
181         if (!controllerProps.containsKey(MacAddress.name)) {
182             byte controllerMac[] = getHardwareMAC();
183             if (controllerMac != null) {
184                 Property existing = controllerProps.putIfAbsent(MacAddress.name, new MacAddress(controllerMac));
185                 if (existing == null && log.isTraceEnabled()) {
186                     log.trace("Container {}: Setting controller MAC address in the cluster: {}", container,
187                             HexEncode.bytesToHexStringFormat(controllerMac));
188                 }
189             }
190         }
191     }
192
193     public void shutDown() {
194     }
195
196     @SuppressWarnings("deprecation")
197     private void allocateCaches() {
198         if (this.clusterContainerService == null) {
199             this.nonClusterObjectCreate();
200             log.warn("un-initialized clusterContainerService, can't create cache");
201             return;
202         }
203
204         try {
205             clusterContainerService.createCache(
206                     "switchmanager.subnetsConfigList",
207                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
208             clusterContainerService.createCache("switchmanager.spanConfigList",
209                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
210             clusterContainerService.createCache("switchmanager.nodeConfigList",
211                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
212             clusterContainerService.createCache("switchmanager.subnets",
213                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
214             clusterContainerService.createCache(
215                     "switchmanager.configSaveEvent",
216                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
217             clusterContainerService.createCache("switchmanager.nodeProps",
218                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
219             clusterContainerService.createCache(
220                     "switchmanager.nodeConnectorProps",
221                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
222             clusterContainerService.createCache(
223                     "switchmanager.nodeConnectorNames",
224                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
225             clusterContainerService.createCache(
226                     "switchmanager.controllerProps",
227                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
228         } catch (CacheConfigException cce) {
229             log.error("\nCache configuration invalid - check cache mode");
230         } catch (CacheExistException ce) {
231             log.error("\nCache already exits - destroy and recreate if needed");
232         }
233     }
234
235     @SuppressWarnings({ "unchecked", "deprecation" })
236     private void retrieveCaches() {
237         if (this.clusterContainerService == null) {
238             log.info("un-initialized clusterContainerService, can't create cache");
239             return;
240         }
241
242         subnetsConfigList = (ConcurrentMap<String, SubnetConfig>) clusterContainerService
243                 .getCache("switchmanager.subnetsConfigList");
244         if (subnetsConfigList == null) {
245             log.error("\nFailed to get cache for subnetsConfigList");
246         }
247
248         spanConfigList = (ConcurrentMap<SpanConfig, SpanConfig>) clusterContainerService
249                 .getCache("switchmanager.spanConfigList");
250         if (spanConfigList == null) {
251             log.error("\nFailed to get cache for spanConfigList");
252         }
253
254         nodeConfigList = (ConcurrentMap<String, SwitchConfig>) clusterContainerService
255                 .getCache("switchmanager.nodeConfigList");
256         if (nodeConfigList == null) {
257             log.error("\nFailed to get cache for nodeConfigList");
258         }
259
260         subnets = (ConcurrentMap<InetAddress, Subnet>) clusterContainerService
261                 .getCache("switchmanager.subnets");
262         if (subnets == null) {
263             log.error("\nFailed to get cache for subnets");
264         }
265
266         nodeProps = (ConcurrentMap<Node, Map<String, Property>>) clusterContainerService
267                 .getCache("switchmanager.nodeProps");
268         if (nodeProps == null) {
269             log.error("\nFailed to get cache for nodeProps");
270         }
271
272         nodeConnectorProps = (ConcurrentMap<NodeConnector, Map<String, Property>>) clusterContainerService
273                 .getCache("switchmanager.nodeConnectorProps");
274         if (nodeConnectorProps == null) {
275             log.error("\nFailed to get cache for nodeConnectorProps");
276         }
277
278         nodeConnectorNames = (ConcurrentMap<Node, Map<String, NodeConnector>>) clusterContainerService
279                 .getCache("switchmanager.nodeConnectorNames");
280         if (nodeConnectorNames == null) {
281             log.error("\nFailed to get cache for nodeConnectorNames");
282         }
283
284         controllerProps = (ConcurrentMap<String, Property>) clusterContainerService
285                 .getCache("switchmanager.controllerProps");
286         if (controllerProps == null) {
287             log.error("\nFailed to get cache for controllerProps");
288         }
289     }
290
291     private void nonClusterObjectCreate() {
292         subnetsConfigList = new ConcurrentHashMap<String, SubnetConfig>();
293         spanConfigList = new ConcurrentHashMap<SpanConfig, SpanConfig>();
294         nodeConfigList = new ConcurrentHashMap<String, SwitchConfig>();
295         subnets = new ConcurrentHashMap<InetAddress, Subnet>();
296         nodeProps = new ConcurrentHashMap<Node, Map<String, Property>>();
297         nodeConnectorProps = new ConcurrentHashMap<NodeConnector, Map<String, Property>>();
298         nodeConnectorNames = new ConcurrentHashMap<Node, Map<String, NodeConnector>>();
299         controllerProps = new ConcurrentHashMap<String, Property>();
300     }
301
302     @Override
303     public List<SubnetConfig> getSubnetsConfigList() {
304         return new ArrayList<SubnetConfig>(subnetsConfigList.values());
305     }
306
307     @Override
308     public SubnetConfig getSubnetConfig(String subnet) {
309         return subnetsConfigList.get(subnet);
310     }
311
312     private List<SpanConfig> getSpanConfigList(Node node) {
313         List<SpanConfig> confList = new ArrayList<SpanConfig>();
314         String nodeId = node.toString();
315         for (SpanConfig conf : spanConfigList.values()) {
316             if (conf.matchNode(nodeId)) {
317                 confList.add(conf);
318             }
319         }
320         return confList;
321     }
322
323     public List<SwitchConfig> getNodeConfigList() {
324         return new ArrayList<SwitchConfig>(nodeConfigList.values());
325     }
326
327     @Override
328     public SwitchConfig getSwitchConfig(String switchId) {
329         return nodeConfigList.get(switchId);
330     }
331
332     public Switch getSwitchByNode(Node node) {
333         Switch sw = new Switch(node);
334         sw.setNode(node);
335         MacAddress mac = (MacAddress) this.getNodeProp(node,
336                 MacAddress.name);
337         if (mac != null) {
338             sw.setDataLayerAddress(mac.getMacAddress());
339         }
340         Set<NodeConnector> ncSet = getPhysicalNodeConnectors(node);
341         sw.setNodeConnectors(ncSet);
342
343         List<NodeConnector> ncList = new ArrayList<NodeConnector>();
344         for (NodeConnector nodeConnector : ncSet) {
345             if (spanNodeConnectors.contains(nodeConnector)) {
346                 ncList.add(nodeConnector);
347             }
348         }
349         sw.addSpanPorts(ncList);
350
351         return sw;
352     }
353
354     @Override
355     public List<Switch> getNetworkDevices() {
356         Set<Node> nodeSet = getNodes();
357         List<Switch> swList = new ArrayList<Switch>();
358         if (nodeSet != null) {
359             for (Node node : nodeSet) {
360                 swList.add(getSwitchByNode(node));
361             }
362         }
363
364         return swList;
365     }
366
367     private Status updateConfig(SubnetConfig conf, boolean add) {
368         if (add) {
369             if(subnetsConfigList.putIfAbsent(conf.getName(), conf) != null) {
370                 String msg = "Cluster conflict: Subnet with name " + conf.getName() + "already exists.";
371                 return new Status(StatusCode.CONFLICT, msg);
372             }
373         } else {
374             subnetsConfigList.remove(conf.getName());
375         }
376         return new Status(StatusCode.SUCCESS);
377     }
378
379     private Status updateDatabase(SubnetConfig conf, boolean add) {
380         if (add) {
381             Subnet subnetCurr = subnets.get(conf.getIPnum());
382             Subnet subnet;
383             if (subnetCurr == null) {
384                 subnet = new Subnet(conf);
385             } else {
386                 subnet = subnetCurr.clone();
387             }
388             // In case of API3 call we may receive the ports along with the
389             // subnet creation
390             if (!conf.isGlobal()) {
391                 Set<NodeConnector> sp = conf.getSubnetNodeConnectors();
392                 subnet.addNodeConnectors(sp);
393             }
394             boolean putNewSubnet = false;
395             if(subnetCurr == null) {
396                 if(subnets.putIfAbsent(conf.getIPnum(), subnet) == null) {
397                     putNewSubnet = true;
398                 }
399             } else {
400                 putNewSubnet = subnets.replace(conf.getIPnum(), subnetCurr, subnet);
401             }
402             if(!putNewSubnet) {
403                 String msg = "Cluster conflict: Conflict while adding the subnet " + conf.getIPnum();
404                 return new Status(StatusCode.CONFLICT, msg);
405             }
406
407         // Subnet removal case
408         } else {
409             subnets.remove(conf.getIPnum());
410         }
411         return new Status(StatusCode.SUCCESS);
412     }
413
414     private Status semanticCheck(SubnetConfig conf) {
415         Subnet newSubnet = new Subnet(conf);
416         Set<InetAddress> IPs = subnets.keySet();
417         if (IPs == null) {
418             return new Status(StatusCode.SUCCESS);
419         }
420         for (InetAddress i : IPs) {
421             Subnet existingSubnet = subnets.get(i);
422             if ((existingSubnet != null)
423                     && !existingSubnet.isMutualExclusive(newSubnet)) {
424                 return new Status(StatusCode.CONFLICT);
425             }
426         }
427         return new Status(StatusCode.SUCCESS);
428     }
429
430     private Status addRemoveSubnet(SubnetConfig conf, boolean isAdding) {
431         // Valid config check
432         if (!conf.isValidConfig()) {
433             String msg = "Invalid Subnet configuration";
434             log.warn(msg);
435             return new Status(StatusCode.BADREQUEST, msg);
436         }
437
438         if (isAdding) {
439             // Presence check
440             if (subnetsConfigList.containsKey(conf.getName())) {
441                 return new Status(StatusCode.CONFLICT,
442                         "Subnet with the specified name already configured.");
443             }
444             // Semantic check
445             Status rc = semanticCheck(conf);
446             if (!rc.isSuccess()) {
447                 return rc;
448             }
449         }
450
451         // Update Database
452         Status rc = updateDatabase(conf, isAdding);
453
454         if (rc.isSuccess()) {
455             // Update Configuration
456             rc = updateConfig(conf, isAdding);
457             if(!rc.isSuccess()) {
458                 updateDatabase(conf, (!isAdding));
459             }
460         }
461
462         return rc;
463     }
464
465     /**
466      * Adds Subnet configured in GUI or API3
467      */
468     @Override
469     public Status addSubnet(SubnetConfig conf) {
470         return this.addRemoveSubnet(conf, true);
471     }
472
473     @Override
474     public Status removeSubnet(SubnetConfig conf) {
475         return this.addRemoveSubnet(conf, false);
476     }
477
478     @Override
479     public Status removeSubnet(String name) {
480         SubnetConfig conf = subnetsConfigList.get(name);
481         if (conf == null) {
482             return new Status(StatusCode.SUCCESS, "Subnet not present");
483         }
484         return this.addRemoveSubnet(conf, false);
485     }
486
487     @Override
488     public Status addPortsToSubnet(String name, String switchPorts) {
489         SubnetConfig confCurr = subnetsConfigList.get(name);
490         if (confCurr == null) {
491             return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
492         }
493         if (!confCurr.isValidSwitchPort(switchPorts)) {
494             return new Status(StatusCode.BADREQUEST, "Invalid switchports");
495         }
496
497         Subnet subCurr = subnets.get(confCurr.getIPnum());
498         if (subCurr == null) {
499             log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPnum());
500             return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
501         }
502
503         // Update Database
504         Subnet sub = subCurr.clone();
505         Set<NodeConnector> sp = confCurr.getNodeConnectors(switchPorts);
506         sub.addNodeConnectors(sp);
507         boolean subnetsReplaced = subnets.replace(confCurr.getIPnum(), subCurr, sub);
508         if (!subnetsReplaced) {
509             String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
510             return new Status(StatusCode.CONFLICT, msg);
511         }
512
513         // Update Configuration
514         SubnetConfig conf = confCurr.clone();
515         conf.addNodeConnectors(switchPorts);
516         boolean configReplaced = subnetsConfigList.replace(name, confCurr, conf);
517         if (!configReplaced) {
518             // TODO: recovery using Transactionality
519             String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
520             return new Status(StatusCode.CONFLICT, msg);
521         }
522
523         return new Status(StatusCode.SUCCESS);
524     }
525
526     @Override
527     public Status removePortsFromSubnet(String name, String switchPorts) {
528         SubnetConfig confCurr = subnetsConfigList.get(name);
529         if (confCurr == null) {
530             return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
531         }
532
533         Subnet subCurr = subnets.get(confCurr.getIPnum());
534         if (subCurr == null) {
535             log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPnum());
536             return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
537         }
538
539         // Update Database
540         Subnet sub = subCurr.clone();
541         Set<NodeConnector> sp = confCurr.getNodeConnectors(switchPorts);
542         sub.deleteNodeConnectors(sp);
543         boolean subnetsReplace = subnets.replace(confCurr.getIPnum(), subCurr, sub);
544         if (!subnetsReplace) {
545             String msg = "Cluster conflict: Conflict while removing ports from the subnet " + name;
546             return new Status(StatusCode.CONFLICT, msg);
547         }
548
549         // Update Configuration
550         SubnetConfig conf = confCurr.clone();
551         conf.removeNodeConnectors(switchPorts);
552         boolean result = subnetsConfigList.replace(name, confCurr, conf);
553         if (!result) {
554             // TODO: recovery using Transactionality
555             String msg = "Cluster conflict: Conflict while removing ports from " + conf;
556             return new Status(StatusCode.CONFLICT, msg);
557         }
558
559         return new Status(StatusCode.SUCCESS);
560     }
561
562     public String getContainerName() {
563         if (containerName == null) {
564             return GlobalConstants.DEFAULT.toString();
565         }
566         return containerName;
567     }
568
569     @Override
570     public Subnet getSubnetByNetworkAddress(InetAddress networkAddress) {
571         Subnet sub;
572         Set<InetAddress> indices = subnets.keySet();
573         for (InetAddress i : indices) {
574             sub = subnets.get(i);
575             if (sub.isSubnetOf(networkAddress)) {
576                 return sub;
577             }
578         }
579         return null;
580     }
581
582     @Override
583     public Object readObject(ObjectInputStream ois)
584             throws FileNotFoundException, IOException, ClassNotFoundException {
585         // Perform the class deserialization locally, from inside the package
586         // where the class is defined
587         return ois.readObject();
588     }
589
590     @SuppressWarnings("unchecked")
591     private void loadSubnetConfiguration() {
592         ObjectReader objReader = new ObjectReader();
593         ConcurrentMap<String, SubnetConfig> confList = (ConcurrentMap<String, SubnetConfig>) objReader
594                 .read(this, subnetFileName);
595
596         if (confList == null) {
597             return;
598         }
599
600         for (SubnetConfig conf : confList.values()) {
601             addSubnet(conf);
602         }
603     }
604
605     @SuppressWarnings("unchecked")
606     private void loadSpanConfiguration() {
607         ObjectReader objReader = new ObjectReader();
608         ConcurrentMap<Integer, SpanConfig> confList = (ConcurrentMap<Integer, SpanConfig>) objReader
609                 .read(this, spanFileName);
610
611         if (confList == null) {
612             return;
613         }
614
615         for (SpanConfig conf : confList.values()) {
616             addSpanConfig(conf);
617         }
618     }
619
620     @SuppressWarnings("unchecked")
621     private void loadSwitchConfiguration() {
622         ObjectReader objReader = new ObjectReader();
623         ConcurrentMap<String, SwitchConfig> confList = (ConcurrentMap<String, SwitchConfig>) objReader
624                 .read(this, switchConfigFileName);
625
626         if (confList == null) {
627             return;
628         }
629
630         for (SwitchConfig conf : confList.values()) {
631             updateNodeConfig(conf);
632         }
633     }
634
635     @Override
636     public void updateSwitchConfig(SwitchConfig cfgObject) {
637         // update default container only
638         if (!isDefaultContainer) {
639             return;
640         }
641
642         SwitchConfig sc = nodeConfigList.get(cfgObject.getNodeId());
643         if (sc == null) {
644             if (nodeConfigList.putIfAbsent(cfgObject.getNodeId(), cfgObject) != null) {
645                 return;
646             }
647         } else {
648             if (!nodeConfigList.replace(cfgObject.getNodeId(), sc, cfgObject)) {
649                 return;
650             }
651         }
652
653         boolean modeChange = false;
654
655         if ((sc == null) || !cfgObject.getMode().equals(sc.getMode())) {
656             modeChange = true;
657         }
658
659         String nodeId = cfgObject.getNodeId();
660         Node node = Node.fromString(nodeId);
661         Map<String, Property> propMapCurr = nodeProps.get(node);
662         if (propMapCurr == null) {
663             return;
664         }
665         Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
666         Property desc = new Description(cfgObject.getNodeDescription());
667         propMap.put(desc.getName(), desc);
668         Property tier = new Tier(Integer.parseInt(cfgObject.getTier()));
669         propMap.put(tier.getName(), tier);
670
671         if (!nodeProps.replace(node, propMapCurr, propMap)) {
672             // TODO rollback using Transactionality
673             return;
674         }
675
676         log.info("Set Node {}'s Mode to {}", nodeId, cfgObject.getMode());
677
678         if (modeChange) {
679             notifyModeChange(node, cfgObject.isProactive());
680         }
681     }
682
683     @Override
684     public Status updateNodeConfig(SwitchConfig switchConfig) {
685         Status status = switchConfig.validate();
686         if (!status.isSuccess()) {
687             return status;
688         }
689
690         Map<String, Property> updateProperties = switchConfig.getNodeProperties();
691         ForwardingMode mode = (ForwardingMode) updateProperties.get(ForwardingMode.name);
692         if (mode != null) {
693             if (isDefaultContainer) {
694                 if (!mode.isValid()) {
695                     return new Status(StatusCode.BADREQUEST, "Invalid Forwarding Mode Value");
696                 }
697             } else {
698                 return new Status(StatusCode.NOTACCEPTABLE,
699                         "Forwarding Mode modification is allowed only in default container");
700             }
701         }
702
703         Description description = (Description) switchConfig.getProperty(Description.propertyName);
704         String nodeId = switchConfig.getNodeId();
705         Node node = Node.fromString(nodeId);
706         NodeDescription nodeDesc = (this.statisticsManager == null) ? null : this.statisticsManager
707                 .getNodeDescription(node);
708         String advertisedDesc = (nodeDesc == null) ? "" : nodeDesc.getDescription();
709         if (description != null && description.getValue() != null) {
710             if (description.getValue().isEmpty() || description.getValue().equals(advertisedDesc)) {
711                 updateProperties.remove(Description.propertyName);
712                 switchConfig = new SwitchConfig(nodeId, updateProperties);
713             } else {
714                 // check if description is configured or was published by any other node
715                 for (Map.Entry<Node, Map<String, Property>> entry : nodeProps.entrySet()) {
716                     Node n = entry.getKey();
717                     Description desc = (Description) getNodeProp(n, Description.propertyName);
718                     NodeDescription nDesc = (this.statisticsManager == null) ? null : this.statisticsManager
719                             .getNodeDescription(n);
720                     String advDesc = (nDesc == null) ? "" : nDesc.getDescription();
721                     if ((description.equals(desc) || description.getValue().equals(advDesc)) && !node.equals(n)) {
722                         return new Status(StatusCode.CONFLICT, "Node name already in use");
723                     }
724                 }
725             }
726         }
727
728         boolean modeChange = false;
729         SwitchConfig sc = nodeConfigList.get(nodeId);
730         Map<String, Property> prevNodeProperties = new HashMap<String, Property>();
731         if (sc == null) {
732             if ((mode != null) && mode.isProactive()) {
733                 modeChange = true;
734             }
735             if (!updateProperties.isEmpty()) {
736                 if (nodeConfigList.putIfAbsent(nodeId, switchConfig) != null) {
737                     return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
738                 }
739             }
740         } else {
741             prevNodeProperties = new HashMap<String, Property>(sc.getNodeProperties());
742             ForwardingMode prevMode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
743             if (mode == null) {
744                 if ((prevMode != null) && (prevMode.isProactive())) {
745                     modeChange = true;
746                 }
747             } else {
748                 if (((prevMode != null) && (prevMode.getValue() != mode.getValue()))
749                         || (prevMode == null && mode.isProactive())) {
750                     modeChange = true;
751                 }
752             }
753             if (updateProperties.isEmpty()) {
754                 nodeConfigList.remove(nodeId);
755             } else {
756                 if (!nodeConfigList.replace(nodeId, sc, switchConfig)) {
757                     return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
758                 }
759             }
760         }
761         Map<String, Property> propMapCurr = nodeProps.get(node);
762         if (propMapCurr == null) {
763             return new Status(StatusCode.SUCCESS);
764         }
765         Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
766         for (Map.Entry<String, Property> entry : prevNodeProperties.entrySet()) {
767             String prop = entry.getKey();
768             if (!updateProperties.containsKey(prop)) {
769                 if (prop.equals(Description.propertyName)) {
770                     if (!advertisedDesc.isEmpty()) {
771                         Property desc = new Description(advertisedDesc);
772                         propMap.put(Description.propertyName, desc);
773                     }
774                     continue;
775                 }
776                 propMap.remove(prop);
777             }
778         }
779         propMap.putAll(updateProperties);
780         if (!nodeProps.replace(node, propMapCurr, propMap)) {
781             // TODO rollback using Transactionality
782             return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
783         }
784         if (modeChange) {
785             notifyModeChange(node, (mode == null) ? false : mode.isProactive());
786         }
787         return new Status(StatusCode.SUCCESS);
788     }
789
790     @Override
791     public Status removeNodeConfig(String nodeId) {
792         if ((nodeId == null) || (nodeId.isEmpty())) {
793             return new Status(StatusCode.BADREQUEST, "nodeId cannot be empty.");
794         }
795         Map<String, Property> nodeProperties = getSwitchConfig(nodeId).getNodeProperties();
796         Node node = Node.fromString(nodeId);
797         Map<String, Property> propMapCurr = nodeProps.get(node);
798         if ((propMapCurr != null) && (nodeProperties != null) && (!nodeProperties.isEmpty())) {
799             Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
800             for (Map.Entry<String, Property> entry : nodeProperties.entrySet()) {
801                 String prop = entry.getKey();
802                 if (prop.equals(Description.propertyName)) {
803                     Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
804                     if (nodeProp.get(node) != null) {
805                         propMap.put(Description.propertyName, nodeProp.get(node).get(Description.propertyName));
806                         continue;
807                     }
808                 }
809                 propMap.remove(prop);
810             }
811             if (!nodeProps.replace(node, propMapCurr, propMap)) {
812                 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration.");
813             }
814         }
815         if (nodeConfigList != null) {
816             nodeConfigList.remove(nodeId);
817         }
818         return new Status(StatusCode.SUCCESS);
819     }
820
821     @Override
822     public Status saveSwitchConfig() {
823         return saveSwitchConfigInternal();
824     }
825
826     public Status saveSwitchConfigInternal() {
827         Status retS = null, retP = null;
828         ObjectWriter objWriter = new ObjectWriter();
829
830         retS = objWriter.write(new ConcurrentHashMap<String, SubnetConfig>(
831                 subnetsConfigList), subnetFileName);
832         retP = objWriter.write(new ConcurrentHashMap<SpanConfig, SpanConfig>(
833                 spanConfigList), spanFileName);
834         retS = objWriter.write(new ConcurrentHashMap<String, SwitchConfig>(
835                 nodeConfigList), switchConfigFileName);
836         if (retS.equals(retP)) {
837             if (retS.isSuccess()) {
838                 return retS;
839             } else {
840                 return new Status(StatusCode.INTERNALERROR, "Save failed");
841             }
842         } else {
843             return new Status(StatusCode.INTERNALERROR, "Partial save failure");
844         }
845     }
846
847     @Override
848     public List<SpanConfig> getSpanConfigList() {
849         return new ArrayList<SpanConfig>(spanConfigList.values());
850     }
851
852     @Override
853     public Status addSpanConfig(SpanConfig conf) {
854         // Valid config check
855         if (!conf.isValidConfig()) {
856             String msg = "Invalid Span configuration";
857             log.warn(msg);
858             return new Status(StatusCode.BADREQUEST, msg);
859         }
860
861         // Presence check
862         if (spanConfigList.containsKey(conf)) {
863             return new Status(StatusCode.CONFLICT, "Same span config exists");
864         }
865
866         // Update configuration
867         if (spanConfigList.putIfAbsent(conf, conf) == null) {
868             // Update database and notify clients
869             addSpanPorts(conf.getNode(), conf.getPortArrayList());
870         }
871
872         return new Status(StatusCode.SUCCESS);
873     }
874
875     @Override
876     public Status removeSpanConfig(SpanConfig conf) {
877         removeSpanPorts(conf.getNode(), conf.getPortArrayList());
878
879         // Update configuration
880         spanConfigList.remove(conf);
881
882         return new Status(StatusCode.SUCCESS);
883     }
884
885     @Override
886     public List<NodeConnector> getSpanPorts(Node node) {
887         List<NodeConnector> ncList = new ArrayList<NodeConnector>();
888
889         for (NodeConnector nodeConnector : spanNodeConnectors) {
890             if (nodeConnector.getNode().equals(node)) {
891                 ncList.add(nodeConnector);
892             }
893         }
894         return ncList;
895     }
896
897     private void addNode(Node node, Set<Property> props) {
898         log.trace("{} added, props: {}", node, props);
899         if (nodeProps == null) {
900             return;
901         }
902
903         Map<String, Property> propMapCurr = nodeProps.get(node);
904         Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
905                 : new HashMap<String, Property>(propMapCurr);
906
907         // copy node properties from plugin
908         if (props != null) {
909             for (Property prop : props) {
910                 propMap.put(prop.getName(), prop);
911             }
912         }
913
914         // copy node properties from config
915         boolean proactiveForwarding = false;
916         if (nodeConfigList != null) {
917             String nodeId = node.toString();
918             SwitchConfig conf = nodeConfigList.get(nodeId);
919             if (conf != null && (conf.getNodeProperties() != null)) {
920                 Map<String, Property> nodeProperties = conf.getNodeProperties();
921                 propMap.putAll(nodeProperties);
922                 if (nodeProperties.get(ForwardingMode.name) != null) {
923                     ForwardingMode mode = (ForwardingMode) nodeProperties.get(ForwardingMode.name);
924                     proactiveForwarding = mode.isProactive();
925                 }
926             }
927         }
928
929         boolean result = false;
930         if (propMapCurr == null) {
931             if (nodeProps.putIfAbsent(node, propMap) == null) {
932                 result = true;
933             }
934         } else {
935             result = nodeProps.replace(node, propMapCurr, propMap);
936         }
937         if (!result) {
938             log.debug("Cluster conflict: Conflict while adding the node properties. Node: {}  Properties: {}",
939                     node.getID(), props);
940             addNodeProps(node, propMap);
941         }
942
943         // check if span ports are configed
944         addSpanPorts(node);
945
946         // notify node listeners
947         notifyNode(node, UpdateType.ADDED, propMap);
948
949         // notify proactive mode forwarding
950         if (proactiveForwarding) {
951             notifyModeChange(node, true);
952         }
953     }
954
955     private void removeNode(Node node) {
956         log.trace("{} removed", node);
957         if (nodeProps == null) {
958             return;
959         }
960         nodeProps.remove(node);
961         nodeConnectorNames.remove(node);
962         Set<NodeConnector> removeNodeConnectorSet = new HashSet<NodeConnector>();
963         for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
964             NodeConnector nodeConnector = entry.getKey();
965             if (nodeConnector.getNode().equals(node)) {
966                 removeNodeConnectorSet.add(nodeConnector);
967             }
968         }
969         for (NodeConnector nc : removeNodeConnectorSet) {
970             nodeConnectorProps.remove(nc);
971         }
972
973         // check if span ports need to be cleaned up
974         removeSpanPorts(node);
975
976         /* notify node listeners */
977         notifyNode(node, UpdateType.REMOVED, null);
978     }
979
980     private void updateNode(Node node, Set<Property> props) {
981         log.trace("{} updated, props: {}", node, props);
982         if (nodeProps == null || !nodeProps.containsKey(node) ||
983                 props == null || props.isEmpty()) {
984             return;
985         }
986
987         Map<String, Property> propMapCurr = nodeProps.get(node);
988         Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
989                 : new HashMap<String, Property>(propMapCurr);
990
991         // copy node properties from plugin
992         String nodeId = node.toString();
993         for (Property prop : props) {
994             if (nodeConfigList != null) {
995                 SwitchConfig conf = nodeConfigList.get(nodeId);
996                 if (conf != null && (conf.getNodeProperties() != null)
997                         && conf.getNodeProperties().containsKey(prop.getName())) {
998                     continue;
999                 }
1000             }
1001             propMap.put(prop.getName(), prop);
1002         }
1003
1004         if (propMapCurr == null) {
1005             if (nodeProps.putIfAbsent(node, propMap) != null) {
1006                 log.debug("Cluster conflict: Conflict while updating the node. Node: {}  Properties: {}",
1007                         node.getID(), props);
1008                 addNodeProps(node, propMap);
1009             }
1010         } else {
1011             if (!nodeProps.replace(node, propMapCurr, propMap)) {
1012                 log.debug("Cluster conflict: Conflict while updating the node. Node: {}  Properties: {}",
1013                         node.getID(), props);
1014                 addNodeProps(node, propMap);
1015             }
1016         }
1017
1018         /* notify node listeners */
1019         notifyNode(node, UpdateType.CHANGED, propMap);
1020     }
1021
1022     @Override
1023     public void updateNode(Node node, UpdateType type, Set<Property> props) {
1024         log.debug("updateNode: {} type {} props {} for container {}",
1025                 new Object[] { node, type, props, containerName });
1026         switch (type) {
1027         case ADDED:
1028             addNode(node, props);
1029             break;
1030         case CHANGED:
1031             updateNode(node, props);
1032             break;
1033         case REMOVED:
1034             removeNode(node);
1035             break;
1036         default:
1037             break;
1038         }
1039     }
1040
1041     @Override
1042     public void updateNodeConnector(NodeConnector nodeConnector,
1043             UpdateType type, Set<Property> props) {
1044         Map<String, Property> propMap = new HashMap<String, Property>();
1045         boolean update = true;
1046
1047         log.debug("updateNodeConnector: {} type {} props {} for container {}",
1048                 new Object[] { nodeConnector, type, props, containerName });
1049
1050         if (nodeConnectorProps == null) {
1051             return;
1052         }
1053
1054         switch (type) {
1055         case ADDED:
1056             if (props != null) {
1057                 for (Property prop : props) {
1058                     addNodeConnectorProp(nodeConnector, prop);
1059                     propMap.put(prop.getName(), prop);
1060                 }
1061             } else {
1062                 addNodeConnectorProp(nodeConnector, null);
1063             }
1064
1065             addSpanPort(nodeConnector);
1066             break;
1067         case CHANGED:
1068             if (!nodeConnectorProps.containsKey(nodeConnector) || (props == null)) {
1069                 update = false;
1070             } else {
1071                 for (Property prop : props) {
1072                     addNodeConnectorProp(nodeConnector, prop);
1073                     propMap.put(prop.getName(), prop);
1074                 }
1075             }
1076             break;
1077         case REMOVED:
1078             if (!nodeConnectorProps.containsKey(nodeConnector)) {
1079                 update = false;
1080             }
1081             removeNodeConnectorAllProps(nodeConnector);
1082
1083             // clean up span config
1084             removeSpanPort(nodeConnector);
1085             break;
1086         default:
1087             update = false;
1088             break;
1089         }
1090
1091         if (update) {
1092             notifyNodeConnector(nodeConnector, type, propMap);
1093         }
1094     }
1095
1096     @Override
1097     public Set<Node> getNodes() {
1098         return (nodeProps != null) ? new HashSet<Node>(nodeProps.keySet())
1099                 : null;
1100     }
1101
1102     /*
1103      * Returns a copy of a list of properties for a given node
1104      *
1105      * (non-Javadoc)
1106      *
1107      * @see
1108      * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps
1109      * (org.opendaylight.controller.sal.core.Node)
1110      */
1111     @Override
1112     public Map<String, Property> getNodeProps(Node node) {
1113         Map<String, Property> rv = new HashMap<String, Property>();
1114         if (this.nodeProps != null) {
1115             rv = this.nodeProps.get(node);
1116             if (rv != null) {
1117                 /* make a copy of it */
1118                 rv = new HashMap<String, Property>(rv);
1119             }
1120         }
1121         return rv;
1122     }
1123
1124     @Override
1125     public Property getNodeProp(Node node, String propName) {
1126         Map<String, Property> propMap = getNodeProps(node);
1127         return (propMap != null) ? propMap.get(propName) : null;
1128     }
1129
1130     @Override
1131     public void setNodeProp(Node node, Property prop) {
1132
1133         for (int i = 0; i <= REPLACE_RETRY; i++) {
1134             /* Get a copy of the property map */
1135             Map<String, Property> propMapCurr = getNodeProps(node);
1136             if (propMapCurr == null) {
1137                 return;
1138             }
1139
1140             Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1141             propMap.put(prop.getName(), prop);
1142
1143             if (nodeProps.replace(node, propMapCurr, propMap)) {
1144                 return;
1145             }
1146             if (!propMapCurr.get(prop.getName()).equals(nodeProps.get(node).get(prop.getName()))) {
1147                 log.debug("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1148                 return;
1149             }
1150         }
1151         log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1152     }
1153
1154     @Override
1155     public Status removeNodeProp(Node node, String propName) {
1156         for (int i = 0; i <= REPLACE_RETRY; i++) {
1157             Map<String, Property> propMapCurr = getNodeProps(node);
1158             if (propMapCurr != null) {
1159                 if (!propMapCurr.containsKey(propName)) {
1160                     return new Status(StatusCode.SUCCESS);
1161                 }
1162                 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1163                 propMap.remove(propName);
1164                 if (nodeProps.replace(node, propMapCurr, propMap)) {
1165                     return new Status(StatusCode.SUCCESS);
1166                 }
1167                 if (!propMapCurr.get(propName).equals(nodeProps.get(node).get(propName))) {
1168                     String msg = "Cluster conflict: Unable to remove property " + propName + " for node "
1169                             + node.getID();
1170                     return new Status(StatusCode.CONFLICT, msg);
1171                 }
1172
1173             } else {
1174                 return new Status(StatusCode.SUCCESS);
1175             }
1176         }
1177         String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID();
1178         return new Status(StatusCode.CONFLICT, msg);
1179     }
1180
1181     @Override
1182     public Status removeNodeAllProps(Node node) {
1183         this.nodeProps.remove(node);
1184         return new Status(StatusCode.SUCCESS);
1185     }
1186
1187     @Override
1188     public Set<NodeConnector> getUpNodeConnectors(Node node) {
1189         if (nodeConnectorProps == null) {
1190             return null;
1191         }
1192
1193         Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1194         for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1195             NodeConnector nodeConnector = entry.getKey();
1196             if (!nodeConnector.getNode().equals(node)) {
1197                 continue;
1198             }
1199             if (isNodeConnectorEnabled(nodeConnector)) {
1200                 nodeConnectorSet.add(nodeConnector);
1201             }
1202         }
1203
1204         return nodeConnectorSet;
1205     }
1206
1207     @Override
1208     public Set<NodeConnector> getNodeConnectors(Node node) {
1209         if (nodeConnectorProps == null) {
1210             return null;
1211         }
1212
1213         Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1214         for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1215             NodeConnector nodeConnector = entry.getKey();
1216             if (!nodeConnector.getNode().equals(node)) {
1217                 continue;
1218             }
1219             nodeConnectorSet.add(nodeConnector);
1220         }
1221
1222         return nodeConnectorSet;
1223     }
1224
1225     @Override
1226     public Set<NodeConnector> getPhysicalNodeConnectors(Node node) {
1227         if (nodeConnectorProps == null) {
1228             return null;
1229         }
1230
1231         Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1232         for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1233             NodeConnector nodeConnector = entry.getKey();
1234             if (!nodeConnector.getNode().equals(node)
1235                     || isSpecial(nodeConnector)) {
1236                 continue;
1237             }
1238             nodeConnectorSet.add(nodeConnector);
1239         }
1240
1241         return nodeConnectorSet;
1242     }
1243
1244     @Override
1245     public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) {
1246         Map<String, Property> rv = new HashMap<String, Property>();
1247         if (this.nodeConnectorProps != null) {
1248             rv = this.nodeConnectorProps.get(nodeConnector);
1249             if (rv != null) {
1250                 rv = new HashMap<String, Property>(rv);
1251             }
1252         }
1253         return rv;
1254     }
1255
1256     @Override
1257     public Property getNodeConnectorProp(NodeConnector nodeConnector,
1258             String propName) {
1259         Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1260         return (propMap != null) ? propMap.get(propName) : null;
1261     }
1262
1263     private byte[] getHardwareMAC() {
1264         Enumeration<NetworkInterface> nis;
1265         byte[] macAddress = null;
1266
1267         try {
1268             nis = NetworkInterface.getNetworkInterfaces();
1269         } catch (SocketException e) {
1270             log.error("Failed to acquire controller MAC: ", e);
1271             return macAddress;
1272         }
1273
1274         while (nis.hasMoreElements()) {
1275             NetworkInterface ni = nis.nextElement();
1276             try {
1277                 macAddress = ni.getHardwareAddress();
1278             } catch (SocketException e) {
1279                 log.error("Failed to acquire controller MAC: ", e);
1280             }
1281             if (macAddress != null) {
1282                 break;
1283             }
1284         }
1285         if (macAddress == null) {
1286             log.warn("Failed to acquire controller MAC: No physical interface found");
1287             // This happens when running controller on windows VM, for example
1288             // Try parsing the OS command output
1289         }
1290         return macAddress;
1291     }
1292
1293     @Override
1294     public byte[] getControllerMAC() {
1295         MacAddress macProperty = (MacAddress)controllerProps.get(MacAddress.name);
1296         return (macProperty == null) ? null : macProperty.getMacAddress();
1297     }
1298
1299     @Override
1300     public boolean isHostRefreshEnabled() {
1301         return hostRefresh;
1302     }
1303
1304     @Override
1305     public int getHostRetryCount() {
1306         return hostRetryCount;
1307     }
1308
1309     @Override
1310     public NodeConnector getNodeConnector(Node node, String nodeConnectorName) {
1311         if (nodeConnectorNames == null) {
1312             return null;
1313         }
1314
1315         Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1316         if (map == null) {
1317             return null;
1318         }
1319
1320         return map.get(nodeConnectorName);
1321     }
1322
1323     /**
1324      * Adds a node connector and its property if any
1325      *
1326      * @param nodeConnector
1327      *            {@link org.opendaylight.controller.sal.core.NodeConnector}
1328      * @param propName
1329      *            name of {@link org.opendaylight.controller.sal.core.Property}
1330      * @return success or failed reason
1331      */
1332     @Override
1333     public Status addNodeConnectorProp(NodeConnector nodeConnector,
1334             Property prop) {
1335         Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1336         Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1337                 : new HashMap<String, Property>(propMapCurr);
1338
1339         String msg = "Cluster conflict: Unable to add NodeConnector Property.";
1340         // Just add the nodeConnector if prop is not available (in a non-default
1341         // container)
1342         if (prop == null) {
1343             if (propMapCurr == null) {
1344                 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1345                     return new Status(StatusCode.CONFLICT, msg);
1346                 }
1347             } else {
1348                 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1349                     return new Status(StatusCode.CONFLICT, msg);
1350                 }
1351             }
1352             return new Status(StatusCode.SUCCESS);
1353         }
1354
1355         propMap.put(prop.getName(), prop);
1356         if (propMapCurr == null) {
1357             if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1358                 return new Status(StatusCode.CONFLICT, msg);
1359             }
1360         } else {
1361             if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1362                 return new Status(StatusCode.CONFLICT, msg);
1363             }
1364         }
1365
1366         if (prop.getName().equals(Name.NamePropName)) {
1367             if (nodeConnectorNames != null) {
1368                 Node node = nodeConnector.getNode();
1369                 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1370                 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1371                 if (mapCurr != null) {
1372                     for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1373                         String s = entry.getKey();
1374                         try {
1375                             map.put(s, new NodeConnector(entry.getValue()));
1376                         } catch (ConstructionException e) {
1377                             e.printStackTrace();
1378                         }
1379                     }
1380                 }
1381
1382                 map.put(((Name) prop).getValue(), nodeConnector);
1383                 if (mapCurr == null) {
1384                     if (nodeConnectorNames.putIfAbsent(node, map) != null) {
1385                         // TODO: recovery using Transactionality
1386                         return new Status(StatusCode.CONFLICT, msg);
1387                     }
1388                 } else {
1389                     if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1390                         // TODO: recovery using Transactionality
1391                         return new Status(StatusCode.CONFLICT, msg);
1392                     }
1393                 }
1394             }
1395         }
1396
1397         return new Status(StatusCode.SUCCESS);
1398     }
1399
1400     /**
1401      * Removes one property of a node connector
1402      *
1403      * @param nodeConnector
1404      *            {@link org.opendaylight.controller.sal.core.NodeConnector}
1405      * @param propName
1406      *            name of {@link org.opendaylight.controller.sal.core.Property}
1407      * @return success or failed reason
1408      */
1409     @Override
1410     public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) {
1411         Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1412
1413         if (propMapCurr == null) {
1414             /* Nothing to remove */
1415             return new Status(StatusCode.SUCCESS);
1416         }
1417
1418         Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1419         propMap.remove(propName);
1420         boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap);
1421         String msg = "Cluster conflict: Unable to remove NodeConnector property.";
1422         if (!result) {
1423             return new Status(StatusCode.CONFLICT, msg);
1424         }
1425
1426         if (propName.equals(Name.NamePropName)) {
1427             if (nodeConnectorNames != null) {
1428                 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1429                 if (name != null) {
1430                     Node node = nodeConnector.getNode();
1431                     Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1432                     if (mapCurr != null) {
1433                         Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1434                         for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1435                             String s = entry.getKey();
1436                             try {
1437                                 map.put(s, new NodeConnector(entry.getValue()));
1438                             } catch (ConstructionException e) {
1439                                 e.printStackTrace();
1440                             }
1441                         }
1442                         map.remove(name.getValue());
1443                         if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1444                             // TODO: recovery using Transactionality
1445                             return new Status(StatusCode.CONFLICT, msg);
1446                         }
1447                     }
1448                 }
1449             }
1450         }
1451
1452         return new Status(StatusCode.SUCCESS);
1453     }
1454
1455     /**
1456      * Removes all the properties of a node connector
1457      *
1458      * @param nodeConnector
1459      *            {@link org.opendaylight.controller.sal.core.NodeConnector}
1460      * @return success or failed reason
1461      */
1462     @Override
1463     public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) {
1464         if (nodeConnectorNames != null) {
1465             Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1466             if (name != null) {
1467                 Node node = nodeConnector.getNode();
1468                 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1469                 if (mapCurr != null) {
1470                     Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1471                     for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1472                         String s = entry.getKey();
1473                         try {
1474                             map.put(s, new NodeConnector(entry.getValue()));
1475                         } catch (ConstructionException e) {
1476                             e.printStackTrace();
1477                         }
1478                     }
1479                     map.remove(name.getValue());
1480                     if (map.isEmpty()) {
1481                         nodeConnectorNames.remove(node);
1482                     } else {
1483                         if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1484                             log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.",
1485                                     nodeConnector.getID());
1486                         }
1487                     }
1488                 }
1489
1490             }
1491         }
1492         nodeConnectorProps.remove(nodeConnector);
1493
1494         return new Status(StatusCode.SUCCESS);
1495     }
1496
1497     /**
1498      * Function called by the dependency manager when all the required
1499      * dependencies are satisfied
1500      *
1501      */
1502     void init(Component c) {
1503         Dictionary<?, ?> props = c.getServiceProperties();
1504         if (props != null) {
1505             this.containerName = (String) props.get("containerName");
1506             log.trace("Running containerName: {}", this.containerName);
1507         } else {
1508             // In the Global instance case the containerName is empty
1509             this.containerName = "";
1510         }
1511         isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT
1512                 .toString());
1513
1514         startUp();
1515     }
1516
1517     /**
1518      * Function called by the dependency manager when at least one dependency
1519      * become unsatisfied or when the component is shutting down because for
1520      * example bundle is being stopped.
1521      *
1522      */
1523     void destroy() {
1524         shutDown();
1525     }
1526
1527     /**
1528      * Function called by dependency manager after "init ()" is called and after
1529      * the services provided by the class are registered in the service registry
1530      *
1531      */
1532     void start() {
1533         // OSGI console
1534         registerWithOSGIConsole();
1535     }
1536
1537     /**
1538      * Function called after registered the service in OSGi service registry.
1539      */
1540     void started() {
1541         // solicit for existing inventories
1542         getInventories();
1543     }
1544
1545     /**
1546      * Function called by the dependency manager before the services exported by
1547      * the component are unregistered, this will be followed by a "destroy ()"
1548      * calls
1549      *
1550      */
1551     void stop() {
1552     }
1553
1554     public void setInventoryService(IInventoryService service) {
1555         log.trace("Got inventory service set request {}", service);
1556         this.inventoryService = service;
1557
1558         // solicit for existing inventories
1559         getInventories();
1560     }
1561
1562     public void unsetInventoryService(IInventoryService service) {
1563         log.trace("Got a service UNset request");
1564         this.inventoryService = null;
1565
1566         // clear existing inventories
1567         clearInventories();
1568     }
1569
1570     public void setStatisticsManager(IStatisticsManager statisticsManager) {
1571         log.trace("Got statistics manager set request {}", statisticsManager);
1572         this.statisticsManager = statisticsManager;
1573     }
1574
1575     public void unsetStatisticsManager(IStatisticsManager statisticsManager) {
1576         log.trace("Got statistics manager UNset request");
1577         this.statisticsManager = null;
1578     }
1579
1580     public void setSwitchManagerAware(ISwitchManagerAware service) {
1581         log.trace("Got inventory service set request {}", service);
1582         if (this.switchManagerAware != null) {
1583             this.switchManagerAware.add(service);
1584         }
1585
1586         // bulk update for newly joined
1587         switchManagerAwareNotify(service);
1588     }
1589
1590     public void unsetSwitchManagerAware(ISwitchManagerAware service) {
1591         log.trace("Got a service UNset request");
1592         if (this.switchManagerAware != null) {
1593             this.switchManagerAware.remove(service);
1594         }
1595     }
1596
1597     public void setInventoryListener(IInventoryListener service) {
1598         log.trace("Got inventory listener set request {}", service);
1599         if (this.inventoryListeners != null) {
1600             this.inventoryListeners.add(service);
1601         }
1602
1603         // bulk update for newly joined
1604         bulkUpdateService(service);
1605     }
1606
1607     public void unsetInventoryListener(IInventoryListener service) {
1608         log.trace("Got a service UNset request");
1609         if (this.inventoryListeners != null) {
1610             this.inventoryListeners.remove(service);
1611         }
1612     }
1613
1614     public void setSpanAware(ISpanAware service) {
1615         log.trace("Got SpanAware set request {}", service);
1616         if (this.spanAware != null) {
1617             this.spanAware.add(service);
1618         }
1619
1620         // bulk update for newly joined
1621         spanAwareNotify(service);
1622     }
1623
1624     public void unsetSpanAware(ISpanAware service) {
1625         log.trace("Got a service UNset request");
1626         if (this.spanAware != null) {
1627             this.spanAware.remove(service);
1628         }
1629     }
1630
1631     void setClusterContainerService(IClusterContainerServices s) {
1632         log.trace("Cluster Service set");
1633         this.clusterContainerService = s;
1634     }
1635
1636     void unsetClusterContainerService(IClusterContainerServices s) {
1637         if (this.clusterContainerService == s) {
1638             log.trace("Cluster Service removed!");
1639             this.clusterContainerService = null;
1640         }
1641     }
1642
1643     private void getInventories() {
1644         if (inventoryService == null) {
1645             log.trace("inventory service not avaiable");
1646             return;
1647         }
1648
1649         Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
1650         for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) {
1651             Node node = entry.getKey();
1652             log.debug("getInventories: {} added for container {}", new Object[] { node, containerName });
1653             Map<String, Property> propMap = entry.getValue();
1654             Set<Property> props = new HashSet<Property>();
1655             for (Property property : propMap.values()) {
1656                 props.add(property);
1657             }
1658             addNode(node, props);
1659         }
1660
1661         Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps();
1662         for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) {
1663             Map<String, Property> propMap = entry.getValue();
1664             for (Property property : propMap.values()) {
1665                 addNodeConnectorProp(entry.getKey(), property);
1666             }
1667         }
1668     }
1669
1670     private void clearInventories() {
1671         nodeProps.clear();
1672         nodeConnectorProps.clear();
1673         nodeConnectorNames.clear();
1674         spanNodeConnectors.clear();
1675     }
1676
1677     private void notifyNode(Node node, UpdateType type,
1678             Map<String, Property> propMap) {
1679         synchronized (inventoryListeners) {
1680             for (IInventoryListener service : inventoryListeners) {
1681                 service.notifyNode(node, type, propMap);
1682             }
1683         }
1684     }
1685
1686     private void notifyNodeConnector(NodeConnector nodeConnector,
1687             UpdateType type, Map<String, Property> propMap) {
1688         synchronized (inventoryListeners) {
1689             for (IInventoryListener service : inventoryListeners) {
1690                 service.notifyNodeConnector(nodeConnector, type, propMap);
1691             }
1692         }
1693     }
1694
1695     /*
1696      * For those joined late, bring them up-to-date.
1697      */
1698     private void switchManagerAwareNotify(ISwitchManagerAware service) {
1699         for (Subnet sub : subnets.values()) {
1700             service.subnetNotify(sub, true);
1701         }
1702
1703         for (Node node : getNodes()) {
1704             SwitchConfig sc = getSwitchConfig(node.toString());
1705             if ((sc != null) && isDefaultContainer) {
1706                 ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
1707                 service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive());
1708             }
1709         }
1710     }
1711
1712     private void bulkUpdateService(IInventoryListener service) {
1713         Map<String, Property> propMap;
1714         UpdateType type = UpdateType.ADDED;
1715
1716         for (Node node : getNodes()) {
1717             propMap = nodeProps.get(node);
1718             service.notifyNode(node, type, propMap);
1719         }
1720
1721         for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1722             NodeConnector nodeConnector = entry.getKey();
1723             propMap = nodeConnectorProps.get(nodeConnector);
1724             service.notifyNodeConnector(nodeConnector, type, propMap);
1725         }
1726     }
1727
1728     private void spanAwareNotify(ISpanAware service) {
1729         for (Node node : getNodes()) {
1730             for (SpanConfig conf : getSpanConfigList(node)) {
1731                 service.spanUpdate(node, conf.getPortArrayList(), true);
1732             }
1733         }
1734     }
1735
1736     private void registerWithOSGIConsole() {
1737         BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
1738                 .getBundleContext();
1739         bundleContext.registerService(CommandProvider.class.getName(), this,
1740                 null);
1741     }
1742
1743     @Override
1744     public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) {
1745         if (nodeConnector == null) {
1746             return false;
1747         }
1748
1749         Config config = (Config) getNodeConnectorProp(nodeConnector,
1750                 Config.ConfigPropName);
1751         State state = (State) getNodeConnectorProp(nodeConnector,
1752                 State.StatePropName);
1753         return ((config != null) && (config.getValue() == Config.ADMIN_UP)
1754                 && (state != null) && (state.getValue() == State.EDGE_UP));
1755     }
1756
1757     @Override
1758     public String getHelp() {
1759         StringBuffer help = new StringBuffer();
1760         help.append("---Switch Manager---\n");
1761         help.append("\t pns                    - Print connected nodes\n");
1762         help.append("\t pncs <node id>         - Print node connectors for a given node\n");
1763         help.append("\t pencs <node id>        - Print enabled node connectors for a given node\n");
1764         help.append("\t pdm <node id>          - Print switch ports in device map\n");
1765         help.append("\t snt <node id> <tier>   - Set node tier number\n");
1766         help.append("\t hostRefresh <on/off/?> - Enable/Disable/Query host refresh\n");
1767         help.append("\t hostRetry <count>      - Set host retry count\n");
1768         return help.toString();
1769     }
1770
1771     public void _pns(CommandInterpreter ci) {
1772         ci.println("           Node               Type           MAC            Name      Tier");
1773         if (nodeProps == null) {
1774             return;
1775         }
1776         Set<Node> nodeSet = nodeProps.keySet();
1777         if (nodeSet == null) {
1778             return;
1779         }
1780         List<String> nodeArray = new ArrayList<String>();
1781         for (Node node : nodeSet) {
1782             nodeArray.add(node.toString());
1783         }
1784         Collections.sort(nodeArray);
1785         for (String str: nodeArray) {
1786             Node node = Node.fromString(str);
1787             Description desc = ((Description) getNodeProp(node,
1788                     Description.propertyName));
1789             Tier tier = ((Tier) getNodeProp(node, Tier.TierPropName));
1790             String nodeName = (desc == null) ? "" : desc.getValue();
1791             MacAddress mac = (MacAddress) getNodeProp(node,
1792                     MacAddress.name);
1793             String macAddr = (mac == null) ? "" : HexEncode
1794                     .bytesToHexStringFormat(mac.getMacAddress());
1795             int tierNum = (tier == null) ? 0 : tier.getValue();
1796             ci.println(node + "     " + node.getType() + "     " + macAddr
1797                     + "     " + nodeName + "     " + tierNum);
1798         }
1799         ci.println("Total number of Nodes: " + nodeSet.size());
1800     }
1801
1802     public void _pencs(CommandInterpreter ci) {
1803         String st = ci.nextArgument();
1804         if (st == null) {
1805             ci.println("Please enter node id");
1806             return;
1807         }
1808
1809         Node node = Node.fromString(st);
1810         if (node == null) {
1811             ci.println("Please enter node id");
1812             return;
1813         }
1814
1815         Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node);
1816         if (nodeConnectorSet == null) {
1817             return;
1818         }
1819         for (NodeConnector nodeConnector : nodeConnectorSet) {
1820             if (nodeConnector == null) {
1821                 continue;
1822             }
1823             ci.println(nodeConnector);
1824         }
1825         ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1826     }
1827
1828     public void _pncs(CommandInterpreter ci) {
1829         String st = ci.nextArgument();
1830         if (st == null) {
1831             ci.println("Please enter node id");
1832             return;
1833         }
1834
1835         Node node = Node.fromString(st);
1836         if (node == null) {
1837             ci.println("Please enter node id");
1838             return;
1839         }
1840
1841         ci.println("          NodeConnector               BandWidth(Gbps)     Admin     State");
1842         Set<NodeConnector> nodeConnectorSet = getNodeConnectors(node);
1843         if (nodeConnectorSet == null) {
1844             return;
1845         }
1846         for (NodeConnector nodeConnector : nodeConnectorSet) {
1847             if (nodeConnector == null) {
1848                 continue;
1849             }
1850             Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1851             Bandwidth bw = (Bandwidth) propMap.get(Bandwidth.BandwidthPropName);
1852             Config config = (Config) propMap.get(Config.ConfigPropName);
1853             State state = (State) propMap.get(State.StatePropName);
1854             String out = nodeConnector + "           ";
1855             out += (bw != null) ? bw.getValue() / Math.pow(10, 9) : "    ";
1856             out += "             ";
1857             out += (config != null) ? config.getValue() : " ";
1858             out += "          ";
1859             out += (state != null) ? state.getValue() : " ";
1860             ci.println(out);
1861         }
1862         ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1863     }
1864
1865     public void _pdm(CommandInterpreter ci) {
1866         String st = ci.nextArgument();
1867         if (st == null) {
1868             ci.println("Please enter node id");
1869             return;
1870         }
1871
1872         Node node = Node.fromString(st);
1873         if (node == null) {
1874             ci.println("Please enter node id");
1875             return;
1876         }
1877
1878         Switch sw = getSwitchByNode(node);
1879
1880         ci.println("          NodeConnector                        Name");
1881         if (sw == null) {
1882             return;
1883         }
1884         Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors();
1885         String nodeConnectorName;
1886         if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
1887             for (NodeConnector nodeConnector : nodeConnectorSet) {
1888                 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1889                 nodeConnectorName = (propMap == null) ? null : ((Name) propMap
1890                         .get(Name.NamePropName)).getValue();
1891                 if (nodeConnectorName != null) {
1892                     Node nd = nodeConnector.getNode();
1893                     if (!nd.equals(node)) {
1894                         log.debug("node not match {} {}", nd, node);
1895                     }
1896                     Map<String, NodeConnector> map = nodeConnectorNames
1897                             .get(node);
1898                     if (map != null) {
1899                         NodeConnector nc = map.get(nodeConnectorName);
1900                         if (nc == null) {
1901                             log.debug("no nodeConnector named {}",
1902                                     nodeConnectorName);
1903                         } else if (!nc.equals(nodeConnector)) {
1904                             log.debug("nodeConnector not match {} {}", nc,
1905                                     nodeConnector);
1906                         }
1907                     }
1908                 }
1909
1910                 ci.println(nodeConnector
1911                         + "            "
1912                         + ((nodeConnectorName == null) ? "" : nodeConnectorName)
1913                         + "(" + nodeConnector.getID() + ")");
1914             }
1915             ci.println("Total number of NodeConnectors: "
1916                     + nodeConnectorSet.size());
1917         }
1918     }
1919
1920     public void _snt(CommandInterpreter ci) {
1921         String st = ci.nextArgument();
1922         if (st == null) {
1923             ci.println("Please enter node id");
1924             return;
1925         }
1926
1927         Node node = Node.fromString(st);
1928         if (node == null) {
1929             ci.println("Please enter node id");
1930             return;
1931         }
1932
1933         st = ci.nextArgument();
1934         if (st == null) {
1935             ci.println("Please enter tier number");
1936             return;
1937         }
1938         Integer tid = Integer.decode(st);
1939         Tier tier = new Tier(tid);
1940         setNodeProp(node, tier);
1941     }
1942
1943     public void _hostRefresh(CommandInterpreter ci) {
1944         String mode = ci.nextArgument();
1945         if (mode == null) {
1946             ci.println("expecting on/off/?");
1947             return;
1948         }
1949         if (mode.toLowerCase().equals("on")) {
1950             hostRefresh = true;
1951         } else if (mode.toLowerCase().equals("off")) {
1952             hostRefresh = false;
1953         } else if (mode.equals("?")) {
1954             if (hostRefresh) {
1955                 ci.println("host refresh is ON");
1956             } else {
1957                 ci.println("host refresh is OFF");
1958             }
1959         } else {
1960             ci.println("expecting on/off/?");
1961         }
1962         return;
1963     }
1964
1965     public void _hostRetry(CommandInterpreter ci) {
1966         String retry = ci.nextArgument();
1967         if (retry == null) {
1968             ci.println("Please enter a valid number. Current retry count is "
1969                     + hostRetryCount);
1970             return;
1971         }
1972         try {
1973             hostRetryCount = Integer.parseInt(retry);
1974         } catch (Exception e) {
1975             ci.println("Please enter a valid number");
1976         }
1977         return;
1978     }
1979
1980     @Override
1981     public byte[] getNodeMAC(Node node) {
1982         MacAddress mac = (MacAddress) this.getNodeProp(node,
1983                 MacAddress.name);
1984         return (mac != null) ? mac.getMacAddress() : null;
1985     }
1986
1987     @Override
1988     public boolean isSpecial(NodeConnector p) {
1989         if (p.getType().equals(NodeConnectorIDType.CONTROLLER)
1990                 || p.getType().equals(NodeConnectorIDType.ALL)
1991                 || p.getType().equals(NodeConnectorIDType.SWSTACK)
1992                 || p.getType().equals(NodeConnectorIDType.HWPATH)) {
1993             return true;
1994         }
1995         return false;
1996     }
1997
1998     /*
1999      * Add span configuration to local cache and notify clients
2000      */
2001     private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2002         List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2003
2004         for (NodeConnector nodeConnector : nodeConnectors) {
2005             if (!spanNodeConnectors.contains(nodeConnector)) {
2006                 ncLists.add(nodeConnector);
2007             }
2008         }
2009
2010         if (ncLists.size() > 0) {
2011             spanNodeConnectors.addAll(ncLists);
2012             notifySpanPortChange(node, ncLists, true);
2013         }
2014     }
2015
2016     private void addSpanPorts(Node node) {
2017         for (SpanConfig conf : getSpanConfigList(node)) {
2018             addSpanPorts(node, conf.getPortArrayList());
2019         }
2020     }
2021
2022     private void addSpanPort(NodeConnector nodeConnector) {
2023         // only add if span is configured on this nodeConnector
2024         for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) {
2025             if (conf.getPortArrayList().contains(nodeConnector)) {
2026                 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2027                 ncLists.add(nodeConnector);
2028                 addSpanPorts(nodeConnector.getNode(), ncLists);
2029                 return;
2030             }
2031         }
2032     }
2033
2034     /*
2035      * Remove span configuration to local cache and notify clients
2036      */
2037     private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2038         List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2039
2040         for (NodeConnector nodeConnector : nodeConnectors) {
2041             if (spanNodeConnectors.contains(nodeConnector)) {
2042                 ncLists.add(nodeConnector);
2043             }
2044         }
2045
2046         if (ncLists.size() > 0) {
2047             spanNodeConnectors.removeAll(ncLists);
2048             notifySpanPortChange(node, ncLists, false);
2049         }
2050     }
2051
2052     private void removeSpanPorts(Node node) {
2053         for (SpanConfig conf : getSpanConfigList(node)) {
2054             addSpanPorts(node, conf.getPortArrayList());
2055         }
2056     }
2057
2058     private void removeSpanPort(NodeConnector nodeConnector) {
2059         if (spanNodeConnectors.contains(nodeConnector)) {
2060             List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2061             ncLists.add(nodeConnector);
2062             removeSpanPorts(nodeConnector.getNode(), ncLists);
2063         }
2064     }
2065
2066     private void addNodeProps(Node node, Map<String, Property> propMap) {
2067         if (propMap == null) {
2068             propMap = new HashMap<String, Property>();
2069         }
2070         nodeProps.put(node, propMap);
2071     }
2072
2073     @Override
2074     public Status saveConfiguration() {
2075         return saveSwitchConfig();
2076     }
2077
2078     /**
2079      * Creates a Name/Tier/Bandwidth Property object based on given property
2080      * name and value. Other property types are not supported yet.
2081      *
2082      * @param propName
2083      *            Name of the Property
2084      * @param propValue
2085      *            Value of the Property
2086      * @return {@link org.opendaylight.controller.sal.core.Property}
2087      */
2088     @Override
2089     public Property createProperty(String propName, String propValue) {
2090         if (propName == null) {
2091             log.debug("propName is null");
2092             return null;
2093         }
2094         if (propValue == null) {
2095             log.debug("propValue is null");
2096             return null;
2097         }
2098
2099         try {
2100             if (propName.equalsIgnoreCase(Description.propertyName)) {
2101                 return new Description(propValue);
2102             } else if (propName.equalsIgnoreCase(Tier.TierPropName)) {
2103                 int tier = Integer.parseInt(propValue);
2104                 return new Tier(tier);
2105             } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) {
2106                 long bw = Long.parseLong(propValue);
2107                 return new Bandwidth(bw);
2108             } else if (propName.equalsIgnoreCase(ForwardingMode.name)) {
2109                 int mode = Integer.parseInt(propValue);
2110                 return new ForwardingMode(mode);
2111             } else {
2112                 log.debug("Not able to create {} property", propName);
2113             }
2114         } catch (Exception e) {
2115             log.debug("createProperty caught exception {}", e.getMessage());
2116         }
2117
2118         return null;
2119     }
2120
2121     @Override
2122     public String getNodeDescription(Node node) {
2123         // Check first if user configured a name
2124         SwitchConfig config = getSwitchConfig(node.toString());
2125         if (config != null) {
2126             String configuredDesc = config.getNodeDescription();
2127             if (configuredDesc != null && !configuredDesc.isEmpty()) {
2128                 return configuredDesc;
2129             }
2130         }
2131
2132         // No name configured by user, get the node advertised name
2133         Description desc = (Description) getNodeProp(node,
2134                 Description.propertyName);
2135         return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? ""
2136                 : desc.getValue();
2137     }
2138 }