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