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