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