Move host refresh related variable from SwitchManager to HostTracker
[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())
1186                 : new HashSet<Node>();
1187     }
1188
1189     /*
1190      * Returns a copy of a list of properties for a given node
1191      *
1192      * (non-Javadoc)
1193      *
1194      * @see
1195      * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps
1196      * (org.opendaylight.controller.sal.core.Node)
1197      */
1198     @Override
1199     public Map<String, Property> getNodeProps(Node node) {
1200         Map<String, Property> rv = new HashMap<String, Property>();
1201         if (this.nodeProps != null) {
1202             rv = this.nodeProps.get(node);
1203             if (rv != null) {
1204                 /* make a copy of it */
1205                 rv = new HashMap<String, Property>(rv);
1206             }
1207         }
1208         return rv;
1209     }
1210
1211     @Override
1212     public Property getNodeProp(Node node, String propName) {
1213         Map<String, Property> propMap = getNodeProps(node);
1214         return (propMap != null) ? propMap.get(propName) : null;
1215     }
1216
1217     @Override
1218     public void setNodeProp(Node node, Property prop) {
1219
1220         for (int i = 0; i <= REPLACE_RETRY; i++) {
1221             /* Get a copy of the property map */
1222             Map<String, Property> propMapCurr = getNodeProps(node);
1223             if (propMapCurr == null) {
1224                 return;
1225             }
1226
1227             Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1228             propMap.put(prop.getName(), prop);
1229
1230             if (nodeProps.replace(node, propMapCurr, propMap)) {
1231                 return;
1232             }
1233             if (!propMapCurr.get(prop.getName()).equals(nodeProps.get(node).get(prop.getName()))) {
1234                 log.debug("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1235                 return;
1236             }
1237         }
1238         log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1239     }
1240
1241     @Override
1242     public Status removeNodeProp(Node node, String propName) {
1243         for (int i = 0; i <= REPLACE_RETRY; i++) {
1244             Map<String, Property> propMapCurr = getNodeProps(node);
1245             if (propMapCurr != null) {
1246                 if (!propMapCurr.containsKey(propName)) {
1247                     return new Status(StatusCode.SUCCESS);
1248                 }
1249                 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1250                 propMap.remove(propName);
1251                 if (nodeProps.replace(node, propMapCurr, propMap)) {
1252                     return new Status(StatusCode.SUCCESS);
1253                 }
1254                 if (!propMapCurr.get(propName).equals(nodeProps.get(node).get(propName))) {
1255                     String msg = "Cluster conflict: Unable to remove property " + propName + " for node "
1256                             + node.getID();
1257                     return new Status(StatusCode.CONFLICT, msg);
1258                 }
1259
1260             } else {
1261                 return new Status(StatusCode.SUCCESS);
1262             }
1263         }
1264         String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID();
1265         return new Status(StatusCode.CONFLICT, msg);
1266     }
1267
1268     @Override
1269     public Status removeNodeAllProps(Node node) {
1270         this.nodeProps.remove(node);
1271         return new Status(StatusCode.SUCCESS);
1272     }
1273
1274     @Override
1275     public Set<NodeConnector> getUpNodeConnectors(Node node) {
1276         if (nodeConnectorProps == null) {
1277             return null;
1278         }
1279
1280         Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1281         for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1282             NodeConnector nodeConnector = entry.getKey();
1283             if (!nodeConnector.getNode().equals(node)) {
1284                 continue;
1285             }
1286             if (isNodeConnectorEnabled(nodeConnector)) {
1287                 nodeConnectorSet.add(nodeConnector);
1288             }
1289         }
1290
1291         return nodeConnectorSet;
1292     }
1293
1294     @Override
1295     public Set<NodeConnector> getNodeConnectors(Node node) {
1296         if (nodeConnectorProps == null) {
1297             return null;
1298         }
1299
1300         Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1301         for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1302             NodeConnector nodeConnector = entry.getKey();
1303             if (!nodeConnector.getNode().equals(node)) {
1304                 continue;
1305             }
1306             nodeConnectorSet.add(nodeConnector);
1307         }
1308
1309         return nodeConnectorSet;
1310     }
1311
1312     @Override
1313     public Set<NodeConnector> getPhysicalNodeConnectors(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                     || isSpecial(nodeConnector)) {
1323                 continue;
1324             }
1325             nodeConnectorSet.add(nodeConnector);
1326         }
1327
1328         return nodeConnectorSet;
1329     }
1330
1331     @Override
1332     public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) {
1333         Map<String, Property> rv = new HashMap<String, Property>();
1334         if (this.nodeConnectorProps != null) {
1335             rv = this.nodeConnectorProps.get(nodeConnector);
1336             if (rv != null) {
1337                 rv = new HashMap<String, Property>(rv);
1338             }
1339         }
1340         return rv;
1341     }
1342
1343     @Override
1344     public Property getNodeConnectorProp(NodeConnector nodeConnector,
1345             String propName) {
1346         Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1347         return (propMap != null) ? propMap.get(propName) : null;
1348     }
1349
1350     private byte[] getHardwareMAC() {
1351         Enumeration<NetworkInterface> nis;
1352         byte[] macAddress = null;
1353
1354         try {
1355             nis = NetworkInterface.getNetworkInterfaces();
1356         } catch (SocketException e) {
1357             log.error("Failed to acquire controller MAC: ", e);
1358             return macAddress;
1359         }
1360
1361         while (nis.hasMoreElements()) {
1362             NetworkInterface ni = nis.nextElement();
1363             try {
1364                 macAddress = ni.getHardwareAddress();
1365             } catch (SocketException e) {
1366                 log.error("Failed to acquire controller MAC: ", e);
1367             }
1368             if (macAddress != null) {
1369                 break;
1370             }
1371         }
1372         if (macAddress == null) {
1373             log.warn("Failed to acquire controller MAC: No physical interface found");
1374             // This happens when running controller on windows VM, for example
1375             // Try parsing the OS command output
1376         }
1377         return macAddress;
1378     }
1379
1380     @Override
1381     public byte[] getControllerMAC() {
1382         MacAddress macProperty = (MacAddress)controllerProps.get(MacAddress.name);
1383         return (macProperty == null) ? null : macProperty.getMacAddress();
1384     }
1385
1386     @Override
1387     public NodeConnector getNodeConnector(Node node, String nodeConnectorName) {
1388         if (nodeConnectorNames == null) {
1389             return null;
1390         }
1391
1392         Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1393         if (map == null) {
1394             return null;
1395         }
1396
1397         return map.get(nodeConnectorName);
1398     }
1399
1400     /**
1401      * Adds a node connector and its property if any
1402      *
1403      * @param nodeConnector
1404      *            {@link org.opendaylight.controller.sal.core.NodeConnector}
1405      * @param propName
1406      *            name of {@link org.opendaylight.controller.sal.core.Property}
1407      * @return success or failed reason
1408      */
1409     @Override
1410     public Status addNodeConnectorProp(NodeConnector nodeConnector,
1411             Property prop) {
1412         Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1413         Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1414                 : new HashMap<String, Property>(propMapCurr);
1415
1416         String msg = "Cluster conflict: Unable to add NodeConnector Property.";
1417         // Just add the nodeConnector if prop is not available (in a non-default
1418         // container)
1419         if (prop == null) {
1420             if (propMapCurr == null) {
1421                 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1422                     return new Status(StatusCode.CONFLICT, msg);
1423                 }
1424             } else {
1425                 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1426                     return new Status(StatusCode.CONFLICT, msg);
1427                 }
1428             }
1429             return new Status(StatusCode.SUCCESS);
1430         }
1431
1432         propMap.put(prop.getName(), prop);
1433         if (propMapCurr == null) {
1434             if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1435                 return new Status(StatusCode.CONFLICT, msg);
1436             }
1437         } else {
1438             if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1439                 return new Status(StatusCode.CONFLICT, msg);
1440             }
1441         }
1442
1443         if (prop.getName().equals(Name.NamePropName)) {
1444             if (nodeConnectorNames != null) {
1445                 Node node = nodeConnector.getNode();
1446                 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1447                 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1448                 if (mapCurr != null) {
1449                     for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1450                         String s = entry.getKey();
1451                         try {
1452                             map.put(s, new NodeConnector(entry.getValue()));
1453                         } catch (ConstructionException e) {
1454                             log.error("An error occured",e);
1455                         }
1456                     }
1457                 }
1458
1459                 map.put(((Name) prop).getValue(), nodeConnector);
1460                 if (mapCurr == null) {
1461                     if (nodeConnectorNames.putIfAbsent(node, map) != null) {
1462                         // TODO: recovery using Transactionality
1463                         return new Status(StatusCode.CONFLICT, msg);
1464                     }
1465                 } else {
1466                     if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1467                         // TODO: recovery using Transactionality
1468                         return new Status(StatusCode.CONFLICT, msg);
1469                     }
1470                 }
1471             }
1472         }
1473
1474         return new Status(StatusCode.SUCCESS);
1475     }
1476
1477     /**
1478      * Removes one property of a node connector
1479      *
1480      * @param nodeConnector
1481      *            {@link org.opendaylight.controller.sal.core.NodeConnector}
1482      * @param propName
1483      *            name of {@link org.opendaylight.controller.sal.core.Property}
1484      * @return success or failed reason
1485      */
1486     @Override
1487     public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) {
1488         Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1489
1490         if (propMapCurr == null) {
1491             /* Nothing to remove */
1492             return new Status(StatusCode.SUCCESS);
1493         }
1494
1495         Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1496         propMap.remove(propName);
1497         boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap);
1498         String msg = "Cluster conflict: Unable to remove NodeConnector property.";
1499         if (!result) {
1500             return new Status(StatusCode.CONFLICT, msg);
1501         }
1502
1503         if (propName.equals(Name.NamePropName)) {
1504             if (nodeConnectorNames != null) {
1505                 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1506                 if (name != null) {
1507                     Node node = nodeConnector.getNode();
1508                     Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1509                     if (mapCurr != null) {
1510                         Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1511                         for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1512                             String s = entry.getKey();
1513                             try {
1514                                 map.put(s, new NodeConnector(entry.getValue()));
1515                             } catch (ConstructionException e) {
1516                                 log.error("An error occured",e);
1517                             }
1518                         }
1519                         map.remove(name.getValue());
1520                         if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1521                             // TODO: recovery using Transactionality
1522                             return new Status(StatusCode.CONFLICT, msg);
1523                         }
1524                     }
1525                 }
1526             }
1527         }
1528
1529         return new Status(StatusCode.SUCCESS);
1530     }
1531
1532     /**
1533      * Removes all the properties of a node connector
1534      *
1535      * @param nodeConnector
1536      *            {@link org.opendaylight.controller.sal.core.NodeConnector}
1537      * @return success or failed reason
1538      */
1539     @Override
1540     public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) {
1541         if (nodeConnectorNames != null) {
1542             Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1543             if (name != null) {
1544                 Node node = nodeConnector.getNode();
1545                 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1546                 if (mapCurr != null) {
1547                     Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1548                     for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1549                         String s = entry.getKey();
1550                         try {
1551                             map.put(s, new NodeConnector(entry.getValue()));
1552                         } catch (ConstructionException e) {
1553                             log.error("An error occured",e);
1554                         }
1555                     }
1556                     map.remove(name.getValue());
1557                     if (map.isEmpty()) {
1558                         nodeConnectorNames.remove(node);
1559                     } else {
1560                         if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1561                             log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.",
1562                                     nodeConnector.getID());
1563                         }
1564                     }
1565                 }
1566
1567             }
1568         }
1569         nodeConnectorProps.remove(nodeConnector);
1570
1571         return new Status(StatusCode.SUCCESS);
1572     }
1573
1574     /**
1575      * Function called by the dependency manager when all the required
1576      * dependencies are satisfied
1577      *
1578      */
1579     void init(Component c) {
1580         Dictionary<?, ?> props = c.getServiceProperties();
1581         if (props != null) {
1582             this.containerName = (String) props.get("containerName");
1583             log.trace("Running containerName: {}", this.containerName);
1584         } else {
1585             // In the Global instance case the containerName is empty
1586             this.containerName = "";
1587         }
1588         isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT
1589                 .toString());
1590
1591         startUp();
1592     }
1593
1594     /**
1595      * Function called by the dependency manager when at least one dependency
1596      * become unsatisfied or when the component is shutting down because for
1597      * example bundle is being stopped.
1598      *
1599      */
1600     void destroy() {
1601         shutDown();
1602     }
1603
1604     /**
1605      * Function called by dependency manager after "init ()" is called and after
1606      * the services provided by the class are registered in the service registry
1607      *
1608      */
1609     void start() {
1610         // OSGI console
1611         registerWithOSGIConsole();
1612     }
1613
1614     /**
1615      * Function called after registered the service in OSGi service registry.
1616      */
1617     void started() {
1618         // solicit for existing inventories
1619         getInventories();
1620     }
1621
1622     /**
1623      * Function called by the dependency manager before the services exported by
1624      * the component are unregistered, this will be followed by a "destroy ()"
1625      * calls
1626      *
1627      */
1628     void stop() {
1629     }
1630
1631     public void setInventoryService(IInventoryService service) {
1632         log.trace("Got inventory service set request {}", service);
1633         this.inventoryService = service;
1634
1635         // solicit for existing inventories
1636         getInventories();
1637     }
1638
1639     public void unsetInventoryService(IInventoryService service) {
1640         log.trace("Got a service UNset request");
1641         this.inventoryService = null;
1642
1643         // clear existing inventories
1644         clearInventories();
1645     }
1646
1647     public void setStatisticsManager(IStatisticsManager statisticsManager) {
1648         log.trace("Got statistics manager set request {}", statisticsManager);
1649         this.statisticsManager = statisticsManager;
1650     }
1651
1652     public void unsetStatisticsManager(IStatisticsManager statisticsManager) {
1653         log.trace("Got statistics manager UNset request");
1654         this.statisticsManager = null;
1655     }
1656
1657     public void setSwitchManagerAware(ISwitchManagerAware service) {
1658         log.trace("Got inventory service set request {}", service);
1659         if (this.switchManagerAware != null) {
1660             this.switchManagerAware.add(service);
1661         }
1662
1663         // bulk update for newly joined
1664         switchManagerAwareNotify(service);
1665     }
1666
1667     public void unsetSwitchManagerAware(ISwitchManagerAware service) {
1668         log.trace("Got a service UNset request");
1669         if (this.switchManagerAware != null) {
1670             this.switchManagerAware.remove(service);
1671         }
1672     }
1673
1674     public void setInventoryListener(IInventoryListener service) {
1675         log.trace("Got inventory listener set request {}", service);
1676         if (this.inventoryListeners != null) {
1677             this.inventoryListeners.add(service);
1678         }
1679
1680         // bulk update for newly joined
1681         bulkUpdateService(service);
1682     }
1683
1684     public void unsetInventoryListener(IInventoryListener service) {
1685         log.trace("Got a service UNset request");
1686         if (this.inventoryListeners != null) {
1687             this.inventoryListeners.remove(service);
1688         }
1689     }
1690
1691     public void setSpanAware(ISpanAware service) {
1692         log.trace("Got SpanAware set request {}", service);
1693         if (this.spanAware != null) {
1694             this.spanAware.add(service);
1695         }
1696
1697         // bulk update for newly joined
1698         spanAwareNotify(service);
1699     }
1700
1701     public void unsetSpanAware(ISpanAware service) {
1702         log.trace("Got a service UNset request");
1703         if (this.spanAware != null) {
1704             this.spanAware.remove(service);
1705         }
1706     }
1707
1708     void setClusterContainerService(IClusterContainerServices s) {
1709         log.trace("Cluster Service set");
1710         this.clusterContainerService = s;
1711     }
1712
1713     void unsetClusterContainerService(IClusterContainerServices s) {
1714         if (this.clusterContainerService == s) {
1715             log.trace("Cluster Service removed!");
1716             this.clusterContainerService = null;
1717         }
1718     }
1719
1720     private void getInventories() {
1721         if (inventoryService == null) {
1722             log.trace("inventory service not avaiable");
1723             return;
1724         }
1725
1726         Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
1727         for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) {
1728             Node node = entry.getKey();
1729             log.debug("getInventories: {} added for container {}", new Object[] { node, containerName });
1730             Map<String, Property> propMap = entry.getValue();
1731             Set<Property> props = new HashSet<Property>();
1732             for (Property property : propMap.values()) {
1733                 props.add(property);
1734             }
1735             addNode(node, props);
1736         }
1737
1738         Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps();
1739         for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) {
1740             Map<String, Property> propMap = entry.getValue();
1741             for (Property property : propMap.values()) {
1742                 addNodeConnectorProp(entry.getKey(), property);
1743             }
1744         }
1745     }
1746
1747     private void clearInventories() {
1748         nodeProps.clear();
1749         nodeConnectorProps.clear();
1750         nodeConnectorNames.clear();
1751         spanNodeConnectors.clear();
1752     }
1753
1754     private void notifyNode(Node node, UpdateType type,
1755             Map<String, Property> propMap) {
1756         synchronized (inventoryListeners) {
1757             for (IInventoryListener service : inventoryListeners) {
1758                 service.notifyNode(node, type, propMap);
1759             }
1760         }
1761     }
1762
1763     private void notifyNodeConnector(NodeConnector nodeConnector,
1764             UpdateType type, Map<String, Property> propMap) {
1765         synchronized (inventoryListeners) {
1766             for (IInventoryListener service : inventoryListeners) {
1767                 service.notifyNodeConnector(nodeConnector, type, propMap);
1768             }
1769         }
1770     }
1771
1772     /*
1773      * For those joined late, bring them up-to-date.
1774      */
1775     private void switchManagerAwareNotify(ISwitchManagerAware service) {
1776         for (Subnet sub : subnets.values()) {
1777             service.subnetNotify(sub, true);
1778         }
1779
1780         for (Node node : getNodes()) {
1781             SwitchConfig sc = getSwitchConfig(node.toString());
1782             if ((sc != null) && isDefaultContainer) {
1783                 ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
1784                 service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive());
1785             }
1786         }
1787     }
1788
1789     private void bulkUpdateService(IInventoryListener service) {
1790         Map<String, Property> propMap;
1791         UpdateType type = UpdateType.ADDED;
1792
1793         for (Node node : getNodes()) {
1794             propMap = nodeProps.get(node);
1795             service.notifyNode(node, type, propMap);
1796         }
1797
1798         for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1799             NodeConnector nodeConnector = entry.getKey();
1800             propMap = nodeConnectorProps.get(nodeConnector);
1801             service.notifyNodeConnector(nodeConnector, type, propMap);
1802         }
1803     }
1804
1805     private void spanAwareNotify(ISpanAware service) {
1806         for (Node node : getNodes()) {
1807             for (SpanConfig conf : getSpanConfigList(node)) {
1808                 service.spanUpdate(node, conf.getPortArrayList(), true);
1809             }
1810         }
1811     }
1812
1813     private void registerWithOSGIConsole() {
1814         BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
1815                 .getBundleContext();
1816         bundleContext.registerService(CommandProvider.class.getName(), this,
1817                 null);
1818     }
1819
1820     @Override
1821     public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) {
1822         if (nodeConnector == null) {
1823             return false;
1824         }
1825
1826         Config config = (Config) getNodeConnectorProp(nodeConnector,
1827                 Config.ConfigPropName);
1828         State state = (State) getNodeConnectorProp(nodeConnector,
1829                 State.StatePropName);
1830         return ((config != null) && (config.getValue() == Config.ADMIN_UP)
1831                 && (state != null) && (state.getValue() == State.EDGE_UP));
1832     }
1833
1834     @Override
1835     public String getHelp() {
1836         StringBuffer help = new StringBuffer();
1837         help.append("---Switch Manager---\n");
1838         help.append("\t pencs <node id>        - Print enabled node connectors for a given node\n");
1839         help.append("\t pdm <node id>          - Print switch ports in device map\n");
1840         help.append("\t snt <node id> <tier>   - Set node tier number\n");
1841         return help.toString();
1842     }
1843
1844     public void _pencs(CommandInterpreter ci) {
1845         String st = ci.nextArgument();
1846         if (st == null) {
1847             ci.println("Please enter node id");
1848             return;
1849         }
1850
1851         Node node = Node.fromString(st);
1852         if (node == null) {
1853             ci.println("Please enter node id");
1854             return;
1855         }
1856
1857         Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node);
1858         if (nodeConnectorSet == null) {
1859             return;
1860         }
1861         for (NodeConnector nodeConnector : nodeConnectorSet) {
1862             if (nodeConnector == null) {
1863                 continue;
1864             }
1865             ci.println(nodeConnector);
1866         }
1867         ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1868     }
1869
1870     public void _pdm(CommandInterpreter ci) {
1871         String st = ci.nextArgument();
1872         if (st == null) {
1873             ci.println("Please enter node id");
1874             return;
1875         }
1876
1877         Node node = Node.fromString(st);
1878         if (node == null) {
1879             ci.println("Please enter node id");
1880             return;
1881         }
1882
1883         Switch sw = getSwitchByNode(node);
1884
1885         ci.println("          NodeConnector                        Name");
1886
1887         Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors();
1888         String nodeConnectorName;
1889         if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
1890             for (NodeConnector nodeConnector : nodeConnectorSet) {
1891                 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1892                 nodeConnectorName = (propMap == null) ? null : ((Name) propMap
1893                         .get(Name.NamePropName)).getValue();
1894                 if (nodeConnectorName != null) {
1895                     Node nd = nodeConnector.getNode();
1896                     if (!nd.equals(node)) {
1897                         log.debug("node not match {} {}", nd, node);
1898                     }
1899                     Map<String, NodeConnector> map = nodeConnectorNames
1900                             .get(node);
1901                     if (map != null) {
1902                         NodeConnector nc = map.get(nodeConnectorName);
1903                         if (nc == null) {
1904                             log.debug("no nodeConnector named {}",
1905                                     nodeConnectorName);
1906                         } else if (!nc.equals(nodeConnector)) {
1907                             log.debug("nodeConnector not match {} {}", nc,
1908                                     nodeConnector);
1909                         }
1910                     }
1911                 }
1912
1913                 ci.println(nodeConnector
1914                         + "            "
1915                         + ((nodeConnectorName == null) ? "" : nodeConnectorName)
1916                         + "(" + nodeConnector.getID() + ")");
1917             }
1918             ci.println("Total number of NodeConnectors: "
1919                     + nodeConnectorSet.size());
1920         }
1921     }
1922
1923     public void _snt(CommandInterpreter ci) {
1924         String st = ci.nextArgument();
1925         if (st == null) {
1926             ci.println("Please enter node id");
1927             return;
1928         }
1929
1930         Node node = Node.fromString(st);
1931         if (node == null) {
1932             ci.println("Please enter node id");
1933             return;
1934         }
1935
1936         st = ci.nextArgument();
1937         if (st == null) {
1938             ci.println("Please enter tier number");
1939             return;
1940         }
1941         Integer tid = Integer.decode(st);
1942         Tier tier = new Tier(tid);
1943         setNodeProp(node, tier);
1944     }
1945
1946     @Override
1947     public byte[] getNodeMAC(Node node) {
1948         MacAddress mac = (MacAddress) this.getNodeProp(node,
1949                 MacAddress.name);
1950         return (mac != null) ? mac.getMacAddress() : null;
1951     }
1952
1953     @Override
1954     public boolean isSpecial(NodeConnector p) {
1955         if (p.getType().equals(NodeConnectorIDType.CONTROLLER)
1956                 || p.getType().equals(NodeConnectorIDType.ALL)
1957                 || p.getType().equals(NodeConnectorIDType.SWSTACK)
1958                 || p.getType().equals(NodeConnectorIDType.HWPATH)) {
1959             return true;
1960         }
1961         return false;
1962     }
1963
1964     /*
1965      * Add span configuration to local cache and notify clients
1966      */
1967     private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
1968         List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1969
1970         for (NodeConnector nodeConnector : nodeConnectors) {
1971             if (!spanNodeConnectors.contains(nodeConnector)) {
1972                 ncLists.add(nodeConnector);
1973             }
1974         }
1975
1976         if (ncLists.size() > 0) {
1977             spanNodeConnectors.addAll(ncLists);
1978             notifySpanPortChange(node, ncLists, true);
1979         }
1980     }
1981
1982     private void addSpanPorts(Node node) {
1983         for (SpanConfig conf : getSpanConfigList(node)) {
1984             addSpanPorts(node, conf.getPortArrayList());
1985         }
1986     }
1987
1988     private void addSpanPort(NodeConnector nodeConnector) {
1989         // only add if span is configured on this nodeConnector
1990         for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) {
1991             if (conf.getPortArrayList().contains(nodeConnector)) {
1992                 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1993                 ncLists.add(nodeConnector);
1994                 addSpanPorts(nodeConnector.getNode(), ncLists);
1995                 return;
1996             }
1997         }
1998     }
1999
2000     /*
2001      * Remove span configuration to local cache and notify clients
2002      */
2003     private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2004         List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2005
2006         for (NodeConnector nodeConnector : nodeConnectors) {
2007             if (spanNodeConnectors.contains(nodeConnector)) {
2008                 ncLists.add(nodeConnector);
2009             }
2010         }
2011
2012         if (ncLists.size() > 0) {
2013             spanNodeConnectors.removeAll(ncLists);
2014             notifySpanPortChange(node, ncLists, false);
2015         }
2016     }
2017
2018     private void removeSpanPorts(Node node) {
2019         for (SpanConfig conf : getSpanConfigList(node)) {
2020             addSpanPorts(node, conf.getPortArrayList());
2021         }
2022     }
2023
2024     private void removeSpanPort(NodeConnector nodeConnector) {
2025         if (spanNodeConnectors.contains(nodeConnector)) {
2026             List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2027             ncLists.add(nodeConnector);
2028             removeSpanPorts(nodeConnector.getNode(), ncLists);
2029         }
2030     }
2031
2032     private void addNodeProps(Node node, Map<String, Property> propMap) {
2033         if (propMap == null) {
2034             propMap = new HashMap<String, Property>();
2035         }
2036         nodeProps.put(node, propMap);
2037     }
2038
2039     @Override
2040     public Status saveConfiguration() {
2041         return saveSwitchConfig();
2042     }
2043
2044     /**
2045      * Creates a Name/Tier/Bandwidth Property object based on given property
2046      * name and value. Other property types are not supported yet.
2047      *
2048      * @param propName
2049      *            Name of the Property
2050      * @param propValue
2051      *            Value of the Property
2052      * @return {@link org.opendaylight.controller.sal.core.Property}
2053      */
2054     @Override
2055     public Property createProperty(String propName, String propValue) {
2056         if (propName == null) {
2057             log.debug("propName is null");
2058             return null;
2059         }
2060         if (propValue == null) {
2061             log.debug("propValue is null");
2062             return null;
2063         }
2064
2065         try {
2066             if (propName.equalsIgnoreCase(Description.propertyName)) {
2067                 return new Description(propValue);
2068             } else if (propName.equalsIgnoreCase(Tier.TierPropName)) {
2069                 int tier = Integer.parseInt(propValue);
2070                 return new Tier(tier);
2071             } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) {
2072                 long bw = Long.parseLong(propValue);
2073                 return new Bandwidth(bw);
2074             } else if (propName.equalsIgnoreCase(ForwardingMode.name)) {
2075                 int mode = Integer.parseInt(propValue);
2076                 return new ForwardingMode(mode);
2077             } else {
2078                 log.debug("Not able to create {} property", propName);
2079             }
2080         } catch (Exception e) {
2081             log.debug("createProperty caught exception {}", e.getMessage());
2082         }
2083
2084         return null;
2085     }
2086
2087     @SuppressWarnings("deprecation")
2088     @Override
2089     public String getNodeDescription(Node node) {
2090         // Check first if user configured a name
2091         SwitchConfig config = getSwitchConfig(node.toString());
2092         if (config != null) {
2093             String configuredDesc = config.getNodeDescription();
2094             if (configuredDesc != null && !configuredDesc.isEmpty()) {
2095                 return configuredDesc;
2096             }
2097         }
2098
2099         // No name configured by user, get the node advertised name
2100         Description desc = (Description) getNodeProp(node,
2101                 Description.propertyName);
2102         return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? ""
2103                 : desc.getValue();
2104     }
2105 }