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