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