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