Enhancement in switch configuration
[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.NOTACCEPTABLE, "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         Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
748         if (propMapCurr == null) {
749             return new Status(StatusCode.SUCCESS);
750         }
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
824         if (retS.equals(retP)) {
825             if (retS.isSuccess()) {
826                 return retS;
827             } else {
828                 return new Status(StatusCode.INTERNALERROR, "Save failed");
829             }
830         } else {
831             return new Status(StatusCode.INTERNALERROR, "Partial save failure");
832         }
833     }
834
835     @Override
836     public List<SpanConfig> getSpanConfigList() {
837         return new ArrayList<SpanConfig>(spanConfigList.values());
838     }
839
840     @Override
841     public Status addSpanConfig(SpanConfig conf) {
842         // Valid config check
843         if (!conf.isValidConfig()) {
844             String msg = "Invalid Span configuration";
845             log.warn(msg);
846             return new Status(StatusCode.BADREQUEST, msg);
847         }
848
849         // Presence check
850         if (spanConfigList.containsKey(conf)) {
851             return new Status(StatusCode.CONFLICT, "Same span config exists");
852         }
853
854         // Update configuration
855         if (spanConfigList.putIfAbsent(conf, conf) == null) {
856             // Update database and notify clients
857             addSpanPorts(conf.getNode(), conf.getPortArrayList());
858         }
859
860         return new Status(StatusCode.SUCCESS);
861     }
862
863     @Override
864     public Status removeSpanConfig(SpanConfig conf) {
865         removeSpanPorts(conf.getNode(), conf.getPortArrayList());
866
867         // Update configuration
868         spanConfigList.remove(conf);
869
870         return new Status(StatusCode.SUCCESS);
871     }
872
873     @Override
874     public List<NodeConnector> getSpanPorts(Node node) {
875         List<NodeConnector> ncList = new ArrayList<NodeConnector>();
876
877         for (NodeConnector nodeConnector : spanNodeConnectors) {
878             if (nodeConnector.getNode().equals(node)) {
879                 ncList.add(nodeConnector);
880             }
881         }
882         return ncList;
883     }
884
885     @Override
886     public void entryCreated(Long key, String cacheName, boolean local) {
887     }
888
889     @Override
890     public void entryUpdated(Long key, String new_value, String cacheName,
891             boolean originLocal) {
892         saveSwitchConfigInternal();
893     }
894
895     @Override
896     public void entryDeleted(Long key, String cacheName, boolean originLocal) {
897     }
898
899     private void addNode(Node node, Set<Property> props) {
900         log.trace("{} added, props: {}", node, props);
901         if (nodeProps == null) {
902             return;
903         }
904
905         Map<String, Property> propMapCurr = nodeProps.get(node);
906         Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
907                 : new HashMap<String, Property>(propMapCurr);
908
909         // copy node properties from plugin
910         if (props != null) {
911             for (Property prop : props) {
912                 propMap.put(prop.getName(), prop);
913             }
914         }
915
916         // copy node properties from config
917         boolean proactiveForwarding = false;
918         if (nodeConfigList != null) {
919             String nodeId = node.toString();
920             SwitchConfig conf = nodeConfigList.get(nodeId);
921             if (conf != null && (conf.getNodeProperties() != null)) {
922                 Map<String, Property> nodeProperties = conf.getNodeProperties();
923                 propMap.putAll(nodeProperties);
924                 if (nodeProperties.get(ForwardingMode.name) != null) {
925                     ForwardingMode mode = (ForwardingMode) nodeProperties.get(ForwardingMode.name);
926                     proactiveForwarding = mode.isProactive();
927                 }
928             }
929         }
930
931         boolean result = false;
932         if (propMapCurr == null) {
933             if (nodeProps.putIfAbsent(node, propMap) == null) {
934                 result = true;
935             }
936         } else {
937             result = nodeProps.replace(node, propMapCurr, propMap);
938         }
939
940         if (!result) {
941             log.debug("Cluster conflict: Conflict while adding the node properties. Node: {}  Properties: {}",
942                     node.getID(), props);
943             addNodeProps(node, propMap);
944         }
945
946         // check if span ports are configed
947         addSpanPorts(node);
948
949         // notify node listeners
950         notifyNode(node, UpdateType.ADDED, propMap);
951
952         // notify proactive mode forwarding
953         if (proactiveForwarding) {
954             notifyModeChange(node, true);
955         }
956     }
957
958     private void removeNode(Node node) {
959         log.trace("{} removed", node);
960         if (nodeProps == null) {
961             return;
962         }
963         nodeProps.remove(node);
964
965         // check if span ports need to be cleaned up
966         removeSpanPorts(node);
967
968         /* notify node listeners */
969         notifyNode(node, UpdateType.REMOVED, null);
970     }
971
972     private void updateNode(Node node, Set<Property> props) {
973         log.trace("{} updated, props: {}", node, props);
974         if (nodeProps == null || !nodeProps.containsKey(node) ||
975                 props == null || props.isEmpty()) {
976             return;
977         }
978
979         Map<String, Property> propMapCurr = nodeProps.get(node);
980         Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
981                 : new HashMap<String, Property>(propMapCurr);
982
983         // copy node properties from plugin
984         for (Property prop : props) {
985             propMap.put(prop.getName(), prop);
986         }
987
988         if (propMapCurr == null) {
989             if (nodeProps.putIfAbsent(node, propMap) != null) {
990                 log.debug("Cluster conflict: Conflict while updating the node. Node: {}  Properties: {}",
991                         node.getID(), props);
992                 addNodeProps(node, propMap);
993             }
994         } else {
995             if (!nodeProps.replace(node, propMapCurr, propMap)) {
996                 log.debug("Cluster conflict: Conflict while updating the node. Node: {}  Properties: {}",
997                         node.getID(), props);
998                 addNodeProps(node, propMap);
999             }
1000         }
1001
1002         /* notify node listeners */
1003         notifyNode(node, UpdateType.CHANGED, propMap);
1004     }
1005
1006     @Override
1007     public void updateNode(Node node, UpdateType type, Set<Property> props) {
1008         log.debug("updateNode: {} type {} props {} for container {}",
1009                 new Object[] { node, type, props, containerName });
1010         switch (type) {
1011         case ADDED:
1012             addNode(node, props);
1013             break;
1014         case CHANGED:
1015             updateNode(node, props);
1016             break;
1017         case REMOVED:
1018             removeNode(node);
1019             break;
1020         default:
1021             break;
1022         }
1023     }
1024
1025     @Override
1026     public void updateNodeConnector(NodeConnector nodeConnector,
1027             UpdateType type, Set<Property> props) {
1028         Map<String, Property> propMap = new HashMap<String, Property>();
1029
1030         log.debug("updateNodeConnector: {} type {} props {} for container {}",
1031                 new Object[] { nodeConnector, type, props, containerName });
1032
1033         if (nodeConnectorProps == null) {
1034             return;
1035         }
1036
1037         switch (type) {
1038         case ADDED:
1039         case CHANGED:
1040             if (props != null) {
1041                 for (Property prop : props) {
1042                     addNodeConnectorProp(nodeConnector, prop);
1043                     propMap.put(prop.getName(), prop);
1044                 }
1045             } else {
1046                 addNodeConnectorProp(nodeConnector, null);
1047             }
1048
1049             addSpanPort(nodeConnector);
1050             break;
1051         case REMOVED:
1052             removeNodeConnectorAllProps(nodeConnector);
1053
1054             // clean up span config
1055             removeSpanPort(nodeConnector);
1056             break;
1057         default:
1058             break;
1059         }
1060
1061         notifyNodeConnector(nodeConnector, type, propMap);
1062     }
1063
1064     @Override
1065     public Set<Node> getNodes() {
1066         return (nodeProps != null) ? new HashSet<Node>(nodeProps.keySet())
1067                 : null;
1068     }
1069
1070     /*
1071      * Returns a copy of a list of properties for a given node
1072      *
1073      * (non-Javadoc)
1074      *
1075      * @see
1076      * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps
1077      * (org.opendaylight.controller.sal.core.Node)
1078      */
1079     @Override
1080     public Map<String, Property> getNodeProps(Node node) {
1081         Map<String, Property> rv = new HashMap<String, Property>();
1082         if (this.nodeProps != null) {
1083             rv = this.nodeProps.get(node);
1084             if (rv != null) {
1085                 /* make a copy of it */
1086                 rv = new HashMap<String, Property>(rv);
1087             }
1088         }
1089         return rv;
1090     }
1091
1092     @Override
1093     public Property getNodeProp(Node node, String propName) {
1094         Map<String, Property> propMap = getNodeProps(node);
1095         return (propMap != null) ? propMap.get(propName) : null;
1096     }
1097
1098     @Override
1099     public void setNodeProp(Node node, Property prop) {
1100
1101         for (int i = 0; i <= REPLACE_RETRY; i++) {
1102             /* Get a copy of the property map */
1103             Map<String, Property> propMapCurr = getNodeProps(node);
1104             if (propMapCurr == null) {
1105                 return;
1106             }
1107
1108             Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1109             propMap.put(prop.getName(), prop);
1110
1111             if (nodeProps.replace(node, propMapCurr, propMap)) {
1112                 return;
1113             }
1114             if (!propMapCurr.get(prop.getName()).equals(nodeProps.get(node).get(prop.getName()))) {
1115                 log.debug("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1116                 return;
1117             }
1118         }
1119         log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1120     }
1121
1122     @Override
1123     public Status removeNodeProp(Node node, String propName) {
1124         for (int i = 0; i <= REPLACE_RETRY; i++) {
1125             Map<String, Property> propMapCurr = getNodeProps(node);
1126             if (propMapCurr != null) {
1127                 if (!propMapCurr.containsKey(propName)) {
1128                     return new Status(StatusCode.SUCCESS);
1129                 }
1130                 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1131                 propMap.remove(propName);
1132                 if (nodeProps.replace(node, propMapCurr, propMap)) {
1133                     return new Status(StatusCode.SUCCESS);
1134                 }
1135                 if (!propMapCurr.get(propName).equals(nodeProps.get(node).get(propName))) {
1136                     String msg = "Cluster conflict: Unable to remove property " + propName + " for node "
1137                             + node.getID();
1138                     return new Status(StatusCode.CONFLICT, msg);
1139                 }
1140
1141             } else {
1142                 return new Status(StatusCode.SUCCESS);
1143             }
1144         }
1145         String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID();
1146         return new Status(StatusCode.CONFLICT, msg);
1147     }
1148
1149     @Override
1150     public Status removeNodeAllProps(Node node) {
1151         this.nodeProps.remove(node);
1152         return new Status(StatusCode.SUCCESS);
1153     }
1154
1155     @Override
1156     public Set<NodeConnector> getUpNodeConnectors(Node node) {
1157         if (nodeConnectorProps == null) {
1158             return null;
1159         }
1160
1161         Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1162         for (NodeConnector nodeConnector : nodeConnectorProps.keySet()) {
1163             if (!nodeConnector.getNode().equals(node)) {
1164                 continue;
1165             }
1166             if (isNodeConnectorEnabled(nodeConnector)) {
1167                 nodeConnectorSet.add(nodeConnector);
1168             }
1169         }
1170
1171         return nodeConnectorSet;
1172     }
1173
1174     @Override
1175     public Set<NodeConnector> getNodeConnectors(Node node) {
1176         if (nodeConnectorProps == null) {
1177             return null;
1178         }
1179
1180         Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1181         for (NodeConnector nodeConnector : nodeConnectorProps.keySet()) {
1182             if (!nodeConnector.getNode().equals(node)) {
1183                 continue;
1184             }
1185             nodeConnectorSet.add(nodeConnector);
1186         }
1187
1188         return nodeConnectorSet;
1189     }
1190
1191     @Override
1192     public Set<NodeConnector> getPhysicalNodeConnectors(Node node) {
1193         if (nodeConnectorProps == null) {
1194             return null;
1195         }
1196
1197         Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1198         for (NodeConnector nodeConnector : nodeConnectorProps.keySet()) {
1199             if (!nodeConnector.getNode().equals(node)
1200                     || isSpecial(nodeConnector)) {
1201                 continue;
1202             }
1203             nodeConnectorSet.add(nodeConnector);
1204         }
1205
1206         return nodeConnectorSet;
1207     }
1208
1209     @Override
1210     public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) {
1211         Map<String, Property> rv = new HashMap<String, Property>();
1212         if (this.nodeConnectorProps != null) {
1213             rv = this.nodeConnectorProps.get(nodeConnector);
1214             if (rv != null) {
1215                 rv = new HashMap<String, Property>(rv);
1216             }
1217         }
1218         return rv;
1219     }
1220
1221     @Override
1222     public Property getNodeConnectorProp(NodeConnector nodeConnector,
1223             String propName) {
1224         Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1225         return (propMap != null) ? propMap.get(propName) : null;
1226     }
1227
1228     private byte[] getHardwareMAC() {
1229         Enumeration<NetworkInterface> nis;
1230         try {
1231             nis = NetworkInterface.getNetworkInterfaces();
1232         } catch (SocketException e1) {
1233             log.error("",e1);
1234             return null;
1235         }
1236         byte[] MAC = null;
1237         for (; nis.hasMoreElements();) {
1238             NetworkInterface ni = nis.nextElement();
1239             try {
1240                 MAC = ni.getHardwareAddress();
1241             } catch (SocketException e) {
1242                 log.error("",e);
1243             }
1244             if (MAC != null) {
1245                 return MAC;
1246             }
1247         }
1248         return null;
1249     }
1250
1251     @Override
1252     public byte[] getControllerMAC() {
1253         return MAC;
1254     }
1255
1256     @Override
1257     public boolean isHostRefreshEnabled() {
1258         return hostRefresh;
1259     }
1260
1261     @Override
1262     public int getHostRetryCount() {
1263         return hostRetryCount;
1264     }
1265
1266     @Override
1267     public NodeConnector getNodeConnector(Node node, String nodeConnectorName) {
1268         if (nodeConnectorNames == null) {
1269             return null;
1270         }
1271
1272         Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1273         if (map == null) {
1274             return null;
1275         }
1276
1277         return map.get(nodeConnectorName);
1278     }
1279
1280     /**
1281      * Adds a node connector and its property if any
1282      *
1283      * @param nodeConnector
1284      *            {@link org.opendaylight.controller.sal.core.NodeConnector}
1285      * @param propName
1286      *            name of {@link org.opendaylight.controller.sal.core.Property}
1287      * @return success or failed reason
1288      */
1289     @Override
1290     public Status addNodeConnectorProp(NodeConnector nodeConnector,
1291             Property prop) {
1292         Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1293         Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1294                 : new HashMap<String, Property>(propMapCurr);
1295
1296         String msg = "Cluster conflict: Unable to add NodeConnector Property.";
1297         // Just add the nodeConnector if prop is not available (in a non-default
1298         // container)
1299         if (prop == null) {
1300             if (propMapCurr == null) {
1301                 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1302                     return new Status(StatusCode.CONFLICT, msg);
1303                 }
1304             } else {
1305                 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1306                     return new Status(StatusCode.CONFLICT, msg);
1307                 }
1308             }
1309             return new Status(StatusCode.SUCCESS);
1310         }
1311
1312         propMap.put(prop.getName(), prop);
1313         if (propMapCurr == null) {
1314             if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1315                 return new Status(StatusCode.CONFLICT, msg);
1316             }
1317         } else {
1318             if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1319                 return new Status(StatusCode.CONFLICT, msg);
1320             }
1321         }
1322
1323         if (prop.getName().equals(Name.NamePropName)) {
1324             if (nodeConnectorNames != null) {
1325                 Node node = nodeConnector.getNode();
1326                 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1327                 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1328                 if (mapCurr != null) {
1329                     for (String s : mapCurr.keySet()) {
1330                         try {
1331                             map.put(s, new NodeConnector(mapCurr.get(s)));
1332                         } catch (ConstructionException e) {
1333                             e.printStackTrace();
1334                         }
1335                     }
1336                 }
1337
1338                 map.put(((Name) prop).getValue(), nodeConnector);
1339                 if (mapCurr == null) {
1340                     if (nodeConnectorNames.putIfAbsent(node, map) != null) {
1341                         // TODO: recovery using Transactionality
1342                         return new Status(StatusCode.CONFLICT, msg);
1343                     }
1344                 } else {
1345                     if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1346                         // TODO: recovery using Transactionality
1347                         return new Status(StatusCode.CONFLICT, msg);
1348                     }
1349                 }
1350             }
1351         }
1352
1353         return new Status(StatusCode.SUCCESS);
1354     }
1355
1356     /**
1357      * Removes one property of a node connector
1358      *
1359      * @param nodeConnector
1360      *            {@link org.opendaylight.controller.sal.core.NodeConnector}
1361      * @param propName
1362      *            name of {@link org.opendaylight.controller.sal.core.Property}
1363      * @return success or failed reason
1364      */
1365     @Override
1366     public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) {
1367         Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1368
1369         if (propMapCurr == null) {
1370             /* Nothing to remove */
1371             return new Status(StatusCode.SUCCESS);
1372         }
1373
1374         Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1375         propMap.remove(propName);
1376         boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap);
1377         String msg = "Cluster conflict: Unable to remove NodeConnector property.";
1378         if (!result) {
1379             return new Status(StatusCode.CONFLICT, msg);
1380         }
1381
1382         if (propName.equals(Name.NamePropName)) {
1383             if (nodeConnectorNames != null) {
1384                 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1385                 if (name != null) {
1386                     Node node = nodeConnector.getNode();
1387                     Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1388                     if (mapCurr != null) {
1389                         Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1390                         for (String s : mapCurr.keySet()) {
1391                             try {
1392                                 map.put(s, new NodeConnector(mapCurr.get(s)));
1393                             } catch (ConstructionException e) {
1394                                 e.printStackTrace();
1395                             }
1396                         }
1397                         map.remove(name.getValue());
1398                         if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1399                             // TODO: recovery using Transactionality
1400                             return new Status(StatusCode.CONFLICT, msg);
1401                         }
1402                     }
1403                 }
1404             }
1405         }
1406
1407         return new Status(StatusCode.SUCCESS);
1408     }
1409
1410     /**
1411      * Removes all the properties of a node connector
1412      *
1413      * @param nodeConnector
1414      *            {@link org.opendaylight.controller.sal.core.NodeConnector}
1415      * @return success or failed reason
1416      */
1417     @Override
1418     public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) {
1419         if (nodeConnectorNames != null) {
1420             Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1421             if (name != null) {
1422                 Node node = nodeConnector.getNode();
1423                 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1424                 if (mapCurr != null) {
1425                     Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1426                     for (String s : mapCurr.keySet()) {
1427                         try {
1428                             map.put(s, new NodeConnector(mapCurr.get(s)));
1429                         } catch (ConstructionException e) {
1430                             e.printStackTrace();
1431                         }
1432                     }
1433                     map.remove(name.getValue());
1434                     if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1435                         log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.",
1436                                 nodeConnector.getID());
1437                     }
1438                 }
1439
1440             }
1441         }
1442         nodeConnectorProps.remove(nodeConnector);
1443
1444         return new Status(StatusCode.SUCCESS);
1445     }
1446
1447     /**
1448      * Function called by the dependency manager when all the required
1449      * dependencies are satisfied
1450      *
1451      */
1452     void init(Component c) {
1453         Dictionary<?, ?> props = c.getServiceProperties();
1454         if (props != null) {
1455             this.containerName = (String) props.get("containerName");
1456             log.trace("Running containerName: {}", this.containerName);
1457         } else {
1458             // In the Global instance case the containerName is empty
1459             this.containerName = "";
1460         }
1461         isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT
1462                 .toString());
1463
1464         startUp();
1465     }
1466
1467     /**
1468      * Function called by the dependency manager when at least one dependency
1469      * become unsatisfied or when the component is shutting down because for
1470      * example bundle is being stopped.
1471      *
1472      */
1473     void destroy() {
1474         shutDown();
1475     }
1476
1477     /**
1478      * Function called by dependency manager after "init ()" is called and after
1479      * the services provided by the class are registered in the service registry
1480      *
1481      */
1482     void start() {
1483         // OSGI console
1484         registerWithOSGIConsole();
1485     }
1486
1487     /**
1488      * Function called after registered the service in OSGi service registry.
1489      */
1490     void started() {
1491         // solicit for existing inventories
1492         getInventories();
1493     }
1494
1495     /**
1496      * Function called by the dependency manager before the services exported by
1497      * the component are unregistered, this will be followed by a "destroy ()"
1498      * calls
1499      *
1500      */
1501     void stop() {
1502     }
1503
1504     public void setInventoryService(IInventoryService service) {
1505         log.trace("Got inventory service set request {}", service);
1506         this.inventoryService = service;
1507
1508         // solicit for existing inventories
1509         getInventories();
1510     }
1511
1512     public void unsetInventoryService(IInventoryService service) {
1513         log.trace("Got a service UNset request");
1514         this.inventoryService = null;
1515
1516         // clear existing inventories
1517         clearInventories();
1518     }
1519
1520     public void setSwitchManagerAware(ISwitchManagerAware service) {
1521         log.trace("Got inventory service set request {}", service);
1522         if (this.switchManagerAware != null) {
1523             this.switchManagerAware.add(service);
1524         }
1525
1526         // bulk update for newly joined
1527         switchManagerAwareNotify(service);
1528     }
1529
1530     public void unsetSwitchManagerAware(ISwitchManagerAware service) {
1531         log.trace("Got a service UNset request");
1532         if (this.switchManagerAware != null) {
1533             this.switchManagerAware.remove(service);
1534         }
1535     }
1536
1537     public void setInventoryListener(IInventoryListener service) {
1538         log.trace("Got inventory listener set request {}", service);
1539         if (this.inventoryListeners != null) {
1540             this.inventoryListeners.add(service);
1541         }
1542
1543         // bulk update for newly joined
1544         bulkUpdateService(service);
1545     }
1546
1547     public void unsetInventoryListener(IInventoryListener service) {
1548         log.trace("Got a service UNset request");
1549         if (this.inventoryListeners != null) {
1550             this.inventoryListeners.remove(service);
1551         }
1552     }
1553
1554     public void setSpanAware(ISpanAware service) {
1555         log.trace("Got SpanAware set request {}", service);
1556         if (this.spanAware != null) {
1557             this.spanAware.add(service);
1558         }
1559
1560         // bulk update for newly joined
1561         spanAwareNotify(service);
1562     }
1563
1564     public void unsetSpanAware(ISpanAware service) {
1565         log.trace("Got a service UNset request");
1566         if (this.spanAware != null) {
1567             this.spanAware.remove(service);
1568         }
1569     }
1570
1571     void setClusterContainerService(IClusterContainerServices s) {
1572         log.trace("Cluster Service set");
1573         this.clusterContainerService = s;
1574     }
1575
1576     void unsetClusterContainerService(IClusterContainerServices s) {
1577         if (this.clusterContainerService == s) {
1578             log.trace("Cluster Service removed!");
1579             this.clusterContainerService = null;
1580         }
1581     }
1582
1583     private void getInventories() {
1584         if (inventoryService == null) {
1585             log.trace("inventory service not avaiable");
1586             return;
1587         }
1588
1589         Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
1590         for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) {
1591             Node node = entry.getKey();
1592             log.debug("getInventories: {} added for container {}", new Object[] { node, containerName });
1593             Map<String, Property> propMap = entry.getValue();
1594             Set<Property> props = new HashSet<Property>();
1595             for (Property property : propMap.values()) {
1596                 props.add(property);
1597             }
1598             addNode(node, props);
1599         }
1600
1601         Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps();
1602         for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) {
1603             Map<String, Property> propMap = entry.getValue();
1604             for (Property property : propMap.values()) {
1605                 addNodeConnectorProp(entry.getKey(), property);
1606             }
1607         }
1608     }
1609
1610     private void clearInventories() {
1611         nodeProps.clear();
1612         nodeConnectorProps.clear();
1613         nodeConnectorNames.clear();
1614         spanNodeConnectors.clear();
1615     }
1616
1617     private void notifyNode(Node node, UpdateType type,
1618             Map<String, Property> propMap) {
1619         synchronized (inventoryListeners) {
1620             for (IInventoryListener service : inventoryListeners) {
1621                 service.notifyNode(node, type, propMap);
1622             }
1623         }
1624     }
1625
1626     private void notifyNodeConnector(NodeConnector nodeConnector,
1627             UpdateType type, Map<String, Property> propMap) {
1628         synchronized (inventoryListeners) {
1629             for (IInventoryListener service : inventoryListeners) {
1630                 service.notifyNodeConnector(nodeConnector, type, propMap);
1631             }
1632         }
1633     }
1634
1635     /*
1636      * For those joined late, bring them up-to-date.
1637      */
1638     private void switchManagerAwareNotify(ISwitchManagerAware service) {
1639         for (Subnet sub : subnets.values()) {
1640             service.subnetNotify(sub, true);
1641         }
1642
1643         for (Node node : getNodes()) {
1644             SwitchConfig sc = getSwitchConfig(node.toString());
1645             if ((sc != null) && isDefaultContainer) {
1646                 ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
1647                 service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive());
1648             }
1649         }
1650     }
1651
1652     private void bulkUpdateService(IInventoryListener service) {
1653         Map<String, Property> propMap;
1654         UpdateType type = UpdateType.ADDED;
1655
1656         for (Node node : getNodes()) {
1657             propMap = nodeProps.get(node);
1658             service.notifyNode(node, type, propMap);
1659         }
1660
1661         for (NodeConnector nodeConnector : nodeConnectorProps.keySet()) {
1662             propMap = nodeConnectorProps.get(nodeConnector);
1663             service.notifyNodeConnector(nodeConnector, type, propMap);
1664         }
1665     }
1666
1667     private void spanAwareNotify(ISpanAware service) {
1668         for (Node node : getNodes()) {
1669             for (SpanConfig conf : getSpanConfigList(node)) {
1670                 service.spanUpdate(node, conf.getPortArrayList(), true);
1671             }
1672         }
1673     }
1674
1675     private void registerWithOSGIConsole() {
1676         BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
1677                 .getBundleContext();
1678         bundleContext.registerService(CommandProvider.class.getName(), this,
1679                 null);
1680     }
1681
1682     @Override
1683     public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) {
1684         if (nodeConnector == null) {
1685             return false;
1686         }
1687
1688         Config config = (Config) getNodeConnectorProp(nodeConnector,
1689                 Config.ConfigPropName);
1690         State state = (State) getNodeConnectorProp(nodeConnector,
1691                 State.StatePropName);
1692         return ((config != null) && (config.getValue() == Config.ADMIN_UP)
1693                 && (state != null) && (state.getValue() == State.EDGE_UP));
1694     }
1695
1696     @Override
1697     public String getHelp() {
1698         StringBuffer help = new StringBuffer();
1699         help.append("---Switch Manager---\n");
1700         help.append("\t pns                    - Print connected nodes\n");
1701         help.append("\t pncs <node id>         - Print node connectors for a given node\n");
1702         help.append("\t pencs <node id>        - Print enabled node connectors for a given node\n");
1703         help.append("\t pdm <node id>          - Print switch ports in device map\n");
1704         help.append("\t snt <node id> <tier>   - Set node tier number\n");
1705         help.append("\t hostRefresh <on/off/?> - Enable/Disable/Query host refresh\n");
1706         help.append("\t hostRetry <count>      - Set host retry count\n");
1707         return help.toString();
1708     }
1709
1710     public void _pns(CommandInterpreter ci) {
1711         ci.println("           Node               Type           MAC            Name      Tier");
1712         if (nodeProps == null) {
1713             return;
1714         }
1715         Set<Node> nodeSet = nodeProps.keySet();
1716         if (nodeSet == null) {
1717             return;
1718         }
1719         List<String> nodeArray = new ArrayList<String>();
1720         for (Node node : nodeSet) {
1721             nodeArray.add(node.toString());
1722         }
1723         Collections.sort(nodeArray);
1724         for (String str: nodeArray) {
1725             Node node = Node.fromString(str);
1726             Description desc = ((Description) getNodeProp(node,
1727                     Description.propertyName));
1728             Tier tier = ((Tier) getNodeProp(node, Tier.TierPropName));
1729             String nodeName = (desc == null) ? "" : desc.getValue();
1730             MacAddress mac = (MacAddress) getNodeProp(node,
1731                     MacAddress.name);
1732             String macAddr = (mac == null) ? "" : HexEncode
1733                     .bytesToHexStringFormat(mac.getMacAddress());
1734             int tierNum = (tier == null) ? 0 : tier.getValue();
1735             ci.println(node + "     " + node.getType() + "     " + macAddr
1736                     + "     " + nodeName + "     " + tierNum);
1737         }
1738         ci.println("Total number of Nodes: " + nodeSet.size());
1739     }
1740
1741     public void _pencs(CommandInterpreter ci) {
1742         String st = ci.nextArgument();
1743         if (st == null) {
1744             ci.println("Please enter node id");
1745             return;
1746         }
1747
1748         Node node = Node.fromString(st);
1749         if (node == null) {
1750             ci.println("Please enter node id");
1751             return;
1752         }
1753
1754         Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node);
1755         if (nodeConnectorSet == null) {
1756             return;
1757         }
1758         for (NodeConnector nodeConnector : nodeConnectorSet) {
1759             if (nodeConnector == null) {
1760                 continue;
1761             }
1762             ci.println(nodeConnector);
1763         }
1764         ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1765     }
1766
1767     public void _pncs(CommandInterpreter ci) {
1768         String st = ci.nextArgument();
1769         if (st == null) {
1770             ci.println("Please enter node id");
1771             return;
1772         }
1773
1774         Node node = Node.fromString(st);
1775         if (node == null) {
1776             ci.println("Please enter node id");
1777             return;
1778         }
1779
1780         ci.println("          NodeConnector               BandWidth(Gbps)     Admin     State");
1781         Set<NodeConnector> nodeConnectorSet = getNodeConnectors(node);
1782         if (nodeConnectorSet == null) {
1783             return;
1784         }
1785         for (NodeConnector nodeConnector : nodeConnectorSet) {
1786             if (nodeConnector == null) {
1787                 continue;
1788             }
1789             Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1790             Bandwidth bw = (Bandwidth) propMap.get(Bandwidth.BandwidthPropName);
1791             Config config = (Config) propMap.get(Config.ConfigPropName);
1792             State state = (State) propMap.get(State.StatePropName);
1793             String out = nodeConnector + "           ";
1794             out += (bw != null) ? bw.getValue() / Math.pow(10, 9) : "    ";
1795             out += "             ";
1796             out += (config != null) ? config.getValue() : " ";
1797             out += "          ";
1798             out += (state != null) ? state.getValue() : " ";
1799             ci.println(out);
1800         }
1801         ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1802     }
1803
1804     public void _pdm(CommandInterpreter ci) {
1805         String st = ci.nextArgument();
1806         if (st == null) {
1807             ci.println("Please enter node id");
1808             return;
1809         }
1810
1811         Node node = Node.fromString(st);
1812         if (node == null) {
1813             ci.println("Please enter node id");
1814             return;
1815         }
1816
1817         Switch sw = getSwitchByNode(node);
1818
1819         ci.println("          NodeConnector                        Name");
1820         if (sw == null) {
1821             return;
1822         }
1823         Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors();
1824         String nodeConnectorName;
1825         if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
1826             for (NodeConnector nodeConnector : nodeConnectorSet) {
1827                 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1828                 nodeConnectorName = (propMap == null) ? null : ((Name) propMap
1829                         .get(Name.NamePropName)).getValue();
1830                 if (nodeConnectorName != null) {
1831                     Node nd = nodeConnector.getNode();
1832                     if (!nd.equals(node)) {
1833                         log.debug("node not match {} {}", nd, node);
1834                     }
1835                     Map<String, NodeConnector> map = nodeConnectorNames
1836                             .get(node);
1837                     if (map != null) {
1838                         NodeConnector nc = map.get(nodeConnectorName);
1839                         if (nc == null) {
1840                             log.debug("no nodeConnector named {}",
1841                                     nodeConnectorName);
1842                         } else if (!nc.equals(nodeConnector)) {
1843                             log.debug("nodeConnector not match {} {}", nc,
1844                                     nodeConnector);
1845                         }
1846                     }
1847                 }
1848
1849                 ci.println(nodeConnector
1850                         + "            "
1851                         + ((nodeConnectorName == null) ? "" : nodeConnectorName)
1852                         + "(" + nodeConnector.getID() + ")");
1853             }
1854             ci.println("Total number of NodeConnectors: "
1855                     + nodeConnectorSet.size());
1856         }
1857     }
1858
1859     public void _snt(CommandInterpreter ci) {
1860         String st = ci.nextArgument();
1861         if (st == null) {
1862             ci.println("Please enter node id");
1863             return;
1864         }
1865
1866         Node node = Node.fromString(st);
1867         if (node == null) {
1868             ci.println("Please enter node id");
1869             return;
1870         }
1871
1872         st = ci.nextArgument();
1873         if (st == null) {
1874             ci.println("Please enter tier number");
1875             return;
1876         }
1877         Integer tid = Integer.decode(st);
1878         Tier tier = new Tier(tid);
1879         setNodeProp(node, tier);
1880     }
1881
1882     public void _hostRefresh(CommandInterpreter ci) {
1883         String mode = ci.nextArgument();
1884         if (mode == null) {
1885             ci.println("expecting on/off/?");
1886             return;
1887         }
1888         if (mode.toLowerCase().equals("on")) {
1889             hostRefresh = true;
1890         } else if (mode.toLowerCase().equals("off")) {
1891             hostRefresh = false;
1892         } else if (mode.equals("?")) {
1893             if (hostRefresh) {
1894                 ci.println("host refresh is ON");
1895             } else {
1896                 ci.println("host refresh is OFF");
1897             }
1898         } else {
1899             ci.println("expecting on/off/?");
1900         }
1901         return;
1902     }
1903
1904     public void _hostRetry(CommandInterpreter ci) {
1905         String retry = ci.nextArgument();
1906         if (retry == null) {
1907             ci.println("Please enter a valid number. Current retry count is "
1908                     + hostRetryCount);
1909             return;
1910         }
1911         try {
1912             hostRetryCount = Integer.parseInt(retry);
1913         } catch (Exception e) {
1914             ci.println("Please enter a valid number");
1915         }
1916         return;
1917     }
1918
1919     @Override
1920     public byte[] getNodeMAC(Node node) {
1921         MacAddress mac = (MacAddress) this.getNodeProp(node,
1922                 MacAddress.name);
1923         return (mac != null) ? mac.getMacAddress() : null;
1924     }
1925
1926     @Override
1927     public boolean isSpecial(NodeConnector p) {
1928         if (p.getType().equals(NodeConnectorIDType.CONTROLLER)
1929                 || p.getType().equals(NodeConnectorIDType.ALL)
1930                 || p.getType().equals(NodeConnectorIDType.SWSTACK)
1931                 || p.getType().equals(NodeConnectorIDType.HWPATH)) {
1932             return true;
1933         }
1934         return false;
1935     }
1936
1937     /*
1938      * Add span configuration to local cache and notify clients
1939      */
1940     private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
1941         List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1942
1943         for (NodeConnector nodeConnector : nodeConnectors) {
1944             if (!spanNodeConnectors.contains(nodeConnector)) {
1945                 ncLists.add(nodeConnector);
1946             }
1947         }
1948
1949         if (ncLists.size() > 0) {
1950             spanNodeConnectors.addAll(ncLists);
1951             notifySpanPortChange(node, ncLists, true);
1952         }
1953     }
1954
1955     private void addSpanPorts(Node node) {
1956         for (SpanConfig conf : getSpanConfigList(node)) {
1957             addSpanPorts(node, conf.getPortArrayList());
1958         }
1959     }
1960
1961     private void addSpanPort(NodeConnector nodeConnector) {
1962         // only add if span is configured on this nodeConnector
1963         for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) {
1964             if (conf.getPortArrayList().contains(nodeConnector)) {
1965                 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1966                 ncLists.add(nodeConnector);
1967                 addSpanPorts(nodeConnector.getNode(), ncLists);
1968                 return;
1969             }
1970         }
1971     }
1972
1973     /*
1974      * Remove span configuration to local cache and notify clients
1975      */
1976     private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
1977         List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1978
1979         for (NodeConnector nodeConnector : nodeConnectors) {
1980             if (spanNodeConnectors.contains(nodeConnector)) {
1981                 ncLists.add(nodeConnector);
1982             }
1983         }
1984
1985         if (ncLists.size() > 0) {
1986             spanNodeConnectors.removeAll(ncLists);
1987             notifySpanPortChange(node, ncLists, false);
1988         }
1989     }
1990
1991     private void removeSpanPorts(Node node) {
1992         for (SpanConfig conf : getSpanConfigList(node)) {
1993             addSpanPorts(node, conf.getPortArrayList());
1994         }
1995     }
1996
1997     private void removeSpanPort(NodeConnector nodeConnector) {
1998         if (spanNodeConnectors.contains(nodeConnector)) {
1999             List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2000             ncLists.add(nodeConnector);
2001             removeSpanPorts(nodeConnector.getNode(), ncLists);
2002         }
2003     }
2004
2005     private void addNodeProps(Node node, Map<String, Property> propMap) {
2006         if (propMap == null) {
2007             propMap = new HashMap<String, Property>();
2008         }
2009         nodeProps.put(node, propMap);
2010     }
2011
2012     private void removeNodeProps(Node node) {
2013         if (getUpNodeConnectors(node).size() == 0) {
2014             nodeProps.remove(node);
2015         }
2016     }
2017
2018     @Override
2019     public Status saveConfiguration() {
2020         return saveSwitchConfig();
2021     }
2022
2023     /**
2024      * Creates a Name/Tier/Bandwidth Property object based on given property
2025      * name and value. Other property types are not supported yet.
2026      *
2027      * @param propName
2028      *            Name of the Property
2029      * @param propValue
2030      *            Value of the Property
2031      * @return {@link org.opendaylight.controller.sal.core.Property}
2032      */
2033     @Override
2034     public Property createProperty(String propName, String propValue) {
2035         if (propName == null) {
2036             log.debug("propName is null");
2037             return null;
2038         }
2039         if (propValue == null) {
2040             log.debug("propValue is null");
2041             return null;
2042         }
2043
2044         try {
2045             if (propName.equalsIgnoreCase(Description.propertyName)) {
2046                 return new Description(propValue);
2047             } else if (propName.equalsIgnoreCase(Tier.TierPropName)) {
2048                 int tier = Integer.parseInt(propValue);
2049                 return new Tier(tier);
2050             } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) {
2051                 long bw = Long.parseLong(propValue);
2052                 return new Bandwidth(bw);
2053             } else if (propName.equalsIgnoreCase(ForwardingMode.name)) {
2054                 int mode = Integer.parseInt(propValue);
2055                 return new ForwardingMode(mode);
2056             } else {
2057                 log.debug("Not able to create {} property", propName);
2058             }
2059         } catch (Exception e) {
2060             log.debug("createProperty caught exception {}", e.getMessage());
2061         }
2062
2063         return null;
2064     }
2065
2066     @Override
2067     public String getNodeDescription(Node node) {
2068         // Check first if user configured a name
2069         SwitchConfig config = getSwitchConfig(node.toString());
2070         if (config != null) {
2071             String configuredDesc = config.getNodeDescription();
2072             if (configuredDesc != null && !configuredDesc.isEmpty()) {
2073                 return configuredDesc;
2074             }
2075         }
2076
2077         // No name configured by user, get the node advertised name
2078         Description desc = (Description) getNodeProp(node,
2079                 Description.propertyName);
2080         return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? ""
2081                 : desc.getValue();
2082     }
2083 }