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