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