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