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