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