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