Merge "Bug 211 - Fixed codec generation when transitive dependencies (parents) are...
[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.size() == 0 && subnet == 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         Subnet newSubnet = new Subnet(conf);
432         Set<InetAddress> IPs = subnets.keySet();
433         if (IPs == null) {
434             return new Status(StatusCode.SUCCESS);
435         }
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().equals(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             }
479         }
480
481         return status;
482     }
483
484     /**
485      * Adds Subnet configured in GUI or API3
486      */
487     @Override
488     public Status addSubnet(SubnetConfig conf) {
489         return this.addRemoveSubnet(conf, true);
490     }
491
492     @Override
493     public Status removeSubnet(SubnetConfig conf) {
494         return this.addRemoveSubnet(conf, false);
495     }
496
497     @Override
498     public Status removeSubnet(String name) {
499         if (name.equals(DEFAULT_SUBNET_NAME)) {
500             return new Status(StatusCode.NOTALLOWED, "The specified subnet gateway cannot be removed");
501         }
502         SubnetConfig conf = subnetsConfigList.get(name);
503         if (conf == null) {
504             return new Status(StatusCode.SUCCESS, "Subnet not present");
505         }
506         return this.addRemoveSubnet(conf, false);
507     }
508
509     @Override
510     public Status modifySubnet(SubnetConfig conf) {
511         // Sanity check
512         if (conf == null) {
513             return new Status(StatusCode.BADREQUEST, "Invalid Subnet configuration: null");
514         }
515
516         // Valid configuration check
517         Status status = conf.validate();
518         if (!status.isSuccess()) {
519             log.warn(status.getDescription());
520             return status;
521         }
522
523         // If a subnet configuration with this name does not exist, consider this is a creation
524         SubnetConfig target = subnetsConfigList.get(conf.getName());
525         if (target == null) {
526             return this.addSubnet(conf);
527         }
528
529         // No change
530         if (target.equals(conf)) {
531             return new Status(StatusCode.SUCCESS);
532         }
533
534         // Check not allowed modifications
535         if (!target.getSubnet().equals(conf.getSubnet())) {
536             return new Status(StatusCode.BADREQUEST, "IP address change is not allowed");
537         }
538
539         // Derive the set of node connectors that are being removed
540         Set<NodeConnector> toRemove = target.getNodeConnectors();
541         toRemove.removeAll(conf.getNodeConnectors());
542         List<String> nodeConnectorStrings = null;
543         if (!toRemove.isEmpty()) {
544             nodeConnectorStrings = new ArrayList<String>();
545             for (NodeConnector nc : toRemove) {
546                 nodeConnectorStrings.add(nc.toString());
547             }
548             status = this.removePortsFromSubnet(conf.getName(), nodeConnectorStrings);
549             if (!status.isSuccess()) {
550                 return status;
551             }
552         }
553
554         // Derive the set of node connectors that are being added
555         Set<NodeConnector> toAdd = conf.getNodeConnectors();
556         toAdd.removeAll(target.getNodeConnectors());
557         if (!toAdd.isEmpty()) {
558             List<String> nodeConnectorStringRemoved = nodeConnectorStrings;
559             nodeConnectorStrings = new ArrayList<String>();
560             for (NodeConnector nc : toAdd) {
561                 nodeConnectorStrings.add(nc.toString());
562             }
563             status = this.addPortsToSubnet(conf.getName(), nodeConnectorStrings);
564             if (!status.isSuccess()) {
565                 // If any port was removed, add it back as a best recovery effort
566                 if (!toRemove.isEmpty()) {
567                     this.addPortsToSubnet(conf.getName(), nodeConnectorStringRemoved);
568                 }
569                 return status;
570             }
571         }
572
573         // Update Configuration
574         subnetsConfigList.put(conf.getName(), conf);
575
576         return new Status(StatusCode.SUCCESS);
577     }
578
579     @Override
580     public Status addPortsToSubnet(String name, List<String> switchPorts) {
581         if (name == null) {
582             return new Status(StatusCode.BADREQUEST, "Null subnet name");
583         }
584         SubnetConfig confCurr = subnetsConfigList.get(name);
585         if (confCurr == null) {
586             return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
587         }
588
589         if (switchPorts == null || switchPorts.isEmpty()) {
590             return new Status(StatusCode.BADREQUEST, "Null or empty port set");
591         }
592
593         Subnet subCurr = subnets.get(confCurr.getIPAddress());
594         if (subCurr == null) {
595             log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress());
596             return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
597         }
598
599         // Update Database
600         Subnet sub = subCurr.clone();
601         Set<NodeConnector> sp = NodeConnector.fromString(switchPorts);
602         sub.addNodeConnectors(sp);
603         boolean subnetsReplaced = subnets.replace(confCurr.getIPAddress(), subCurr, sub);
604         if (!subnetsReplaced) {
605             String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
606             return new Status(StatusCode.CONFLICT, msg);
607         }
608
609         // Update Configuration
610         SubnetConfig conf = confCurr.clone();
611         conf.addNodeConnectors(switchPorts);
612         boolean configReplaced = subnetsConfigList.replace(name, confCurr, conf);
613         if (!configReplaced) {
614             // TODO: recovery using Transactionality
615             String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
616             return new Status(StatusCode.CONFLICT, msg);
617         }
618
619         return new Status(StatusCode.SUCCESS);
620     }
621
622     @Override
623     public Status removePortsFromSubnet(String name, List<String> switchPorts) {
624         if (name == null) {
625             return new Status(StatusCode.BADREQUEST, "Null subnet name");
626         }
627         SubnetConfig confCurr = subnetsConfigList.get(name);
628         if (confCurr == null) {
629             return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
630         }
631
632         if (switchPorts == null || switchPorts.isEmpty()) {
633             return new Status(StatusCode.BADREQUEST, "Null or empty port set");
634         }
635
636         Subnet subCurr = subnets.get(confCurr.getIPAddress());
637         if (subCurr == null) {
638             log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress());
639             return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
640         }
641
642         // Validation check
643         Status status = SubnetConfig.validatePorts(switchPorts);
644         if (!status.isSuccess()) {
645             return status;
646         }
647         // Update Database
648         Subnet sub = subCurr.clone();
649         Set<NodeConnector> sp = NodeConnector.fromString(switchPorts);
650         sub.deleteNodeConnectors(sp);
651         boolean subnetsReplace = subnets.replace(confCurr.getIPAddress(), subCurr, sub);
652         if (!subnetsReplace) {
653             String msg = "Cluster conflict: Conflict while removing ports from the subnet " + name;
654             return new Status(StatusCode.CONFLICT, msg);
655         }
656
657         // Update Configuration
658         SubnetConfig conf = confCurr.clone();
659         conf.removeNodeConnectors(switchPorts);
660         boolean result = subnetsConfigList.replace(name, confCurr, conf);
661         if (!result) {
662             // TODO: recovery using Transactionality
663             String msg = "Cluster conflict: Conflict while removing ports from " + conf;
664             return new Status(StatusCode.CONFLICT, msg);
665         }
666
667         return new Status(StatusCode.SUCCESS);
668     }
669
670     public String getContainerName() {
671         if (containerName == null) {
672             return GlobalConstants.DEFAULT.toString();
673         }
674         return containerName;
675     }
676
677     @Override
678     public Subnet getSubnetByNetworkAddress(InetAddress networkAddress) {
679         // if there are no subnets, return the default subnet
680         if (subnets.size() == 0) {
681             return DEFAULT_SUBNET;
682         }
683
684         Subnet sub;
685         Set<InetAddress> indices = subnets.keySet();
686         for (InetAddress i : indices) {
687             sub = subnets.get(i);
688             if (sub.isSubnetOf(networkAddress)) {
689                 return sub;
690             }
691         }
692         return null;
693     }
694
695     @Override
696     public Object readObject(ObjectInputStream ois)
697             throws FileNotFoundException, IOException, ClassNotFoundException {
698         // Perform the class deserialization locally, from inside the package
699         // where the class is defined
700         return ois.readObject();
701     }
702
703     @SuppressWarnings("unchecked")
704     private void loadSubnetConfiguration() {
705         ObjectReader objReader = new ObjectReader();
706         ConcurrentMap<String, SubnetConfig> confList = (ConcurrentMap<String, SubnetConfig>) objReader
707                 .read(this, subnetFileName);
708
709         if (confList == null) {
710             return;
711         }
712
713         for (SubnetConfig conf : confList.values()) {
714             addSubnet(conf);
715         }
716     }
717
718     @SuppressWarnings("unchecked")
719     private void loadSpanConfiguration() {
720         ObjectReader objReader = new ObjectReader();
721         ConcurrentMap<Integer, SpanConfig> confList = (ConcurrentMap<Integer, SpanConfig>) objReader
722                 .read(this, spanFileName);
723
724         if (confList == null) {
725             return;
726         }
727
728         for (SpanConfig conf : confList.values()) {
729             addSpanConfig(conf);
730         }
731     }
732
733     @SuppressWarnings("unchecked")
734     private void loadSwitchConfiguration() {
735         ObjectReader objReader = new ObjectReader();
736         ConcurrentMap<String, SwitchConfig> confList = (ConcurrentMap<String, SwitchConfig>) objReader
737                 .read(this, switchConfigFileName);
738
739         if (confList == null) {
740             return;
741         }
742
743         for (SwitchConfig conf : confList.values()) {
744             updateNodeConfig(conf);
745         }
746     }
747
748     @SuppressWarnings("deprecation")
749     @Override
750     public void updateSwitchConfig(SwitchConfig cfgObject) {
751         // update default container only
752         if (!isDefaultContainer) {
753             return;
754         }
755
756         SwitchConfig sc = nodeConfigList.get(cfgObject.getNodeId());
757         if (sc == null) {
758             if (nodeConfigList.putIfAbsent(cfgObject.getNodeId(), cfgObject) != null) {
759                 return;
760             }
761         } else {
762             if (!nodeConfigList.replace(cfgObject.getNodeId(), sc, cfgObject)) {
763                 return;
764             }
765         }
766
767         boolean modeChange = false;
768
769         if ((sc == null) || !cfgObject.getMode().equals(sc.getMode())) {
770             modeChange = true;
771         }
772
773         String nodeId = cfgObject.getNodeId();
774         Node node = Node.fromString(nodeId);
775         Map<String, Property> propMapCurr = nodeProps.get(node);
776         if (propMapCurr == null) {
777             return;
778         }
779         Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
780         Property desc = new Description(cfgObject.getNodeDescription());
781         propMap.put(desc.getName(), desc);
782         Property tier = new Tier(Integer.parseInt(cfgObject.getTier()));
783         propMap.put(tier.getName(), tier);
784
785         if (!nodeProps.replace(node, propMapCurr, propMap)) {
786             // TODO rollback using Transactionality
787             return;
788         }
789
790         log.info("Set Node {}'s Mode to {}", nodeId, cfgObject.getMode());
791
792         if (modeChange) {
793             notifyModeChange(node, cfgObject.isProactive());
794         }
795     }
796
797     @Override
798     public Status updateNodeConfig(SwitchConfig switchConfig) {
799         Status status = switchConfig.validate();
800         if (!status.isSuccess()) {
801             return status;
802         }
803
804         Map<String, Property> updateProperties = switchConfig.getNodeProperties();
805         ForwardingMode mode = (ForwardingMode) updateProperties.get(ForwardingMode.name);
806         if (mode != null) {
807             if (isDefaultContainer) {
808                 if (!mode.isValid()) {
809                     return new Status(StatusCode.BADREQUEST, "Invalid Forwarding Mode Value");
810                 }
811             } else {
812                 return new Status(StatusCode.NOTACCEPTABLE,
813                         "Forwarding Mode modification is allowed only in default container");
814             }
815         }
816
817         Description description = (Description) switchConfig.getProperty(Description.propertyName);
818         String nodeId = switchConfig.getNodeId();
819         Node node = Node.fromString(nodeId);
820         NodeDescription nodeDesc = (this.statisticsManager == null) ? null : this.statisticsManager
821                 .getNodeDescription(node);
822         String advertisedDesc = (nodeDesc == null) ? "" : nodeDesc.getDescription();
823         if (description != null && description.getValue() != null) {
824             if (description.getValue().isEmpty() || description.getValue().equals(advertisedDesc)) {
825                 updateProperties.remove(Description.propertyName);
826                 switchConfig = new SwitchConfig(nodeId, updateProperties);
827             } else {
828                 // check if description is configured or was published by any other node
829                 for (Map.Entry<Node, Map<String, Property>> entry : nodeProps.entrySet()) {
830                     Node n = entry.getKey();
831                     Description desc = (Description) getNodeProp(n, Description.propertyName);
832                     NodeDescription nDesc = (this.statisticsManager == null) ? null : this.statisticsManager
833                             .getNodeDescription(n);
834                     String advDesc = (nDesc == null) ? "" : nDesc.getDescription();
835                     if ((description.equals(desc) || description.getValue().equals(advDesc)) && !node.equals(n)) {
836                         return new Status(StatusCode.CONFLICT, "Node name already in use");
837                     }
838                 }
839             }
840         }
841
842         boolean modeChange = false;
843         SwitchConfig sc = nodeConfigList.get(nodeId);
844         Map<String, Property> prevNodeProperties = new HashMap<String, Property>();
845         if (sc == null) {
846             if ((mode != null) && mode.isProactive()) {
847                 modeChange = true;
848             }
849             if (!updateProperties.isEmpty()) {
850                 if (nodeConfigList.putIfAbsent(nodeId, switchConfig) != null) {
851                     return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
852                 }
853             }
854         } else {
855             prevNodeProperties = new HashMap<String, Property>(sc.getNodeProperties());
856             ForwardingMode prevMode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
857             if (mode == null) {
858                 if ((prevMode != null) && (prevMode.isProactive())) {
859                     modeChange = true;
860                 }
861             } else {
862                 if (((prevMode != null) && (prevMode.getValue() != mode.getValue()))
863                         || (prevMode == null && mode.isProactive())) {
864                     modeChange = true;
865                 }
866             }
867             if (updateProperties.isEmpty()) {
868                 nodeConfigList.remove(nodeId);
869             } else {
870                 if (!nodeConfigList.replace(nodeId, sc, switchConfig)) {
871                     return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
872                 }
873             }
874         }
875         Map<String, Property> propMapCurr = nodeProps.get(node);
876         if (propMapCurr == null) {
877             return new Status(StatusCode.SUCCESS);
878         }
879         Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
880         for (Map.Entry<String, Property> entry : prevNodeProperties.entrySet()) {
881             String prop = entry.getKey();
882             if (!updateProperties.containsKey(prop)) {
883                 if (prop.equals(Description.propertyName)) {
884                     if (!advertisedDesc.isEmpty()) {
885                         Property desc = new Description(advertisedDesc);
886                         propMap.put(Description.propertyName, desc);
887                     }
888                     continue;
889                 } else if (prop.equals(ForwardingMode.name)) {
890                     Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING);
891                     propMap.put(ForwardingMode.name, defaultMode);
892                     continue;
893                 }
894                 propMap.remove(prop);
895             }
896         }
897         propMap.putAll(updateProperties);
898         if (!nodeProps.replace(node, propMapCurr, propMap)) {
899             // TODO rollback using Transactionality
900             return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
901         }
902         if (modeChange) {
903             notifyModeChange(node, (mode == null) ? false : mode.isProactive());
904         }
905         return new Status(StatusCode.SUCCESS);
906     }
907
908     @Override
909     public Status removeNodeConfig(String nodeId) {
910         if ((nodeId == null) || (nodeId.isEmpty())) {
911             return new Status(StatusCode.BADREQUEST, "nodeId cannot be empty.");
912         }
913         Map<String, Property> nodeProperties = getSwitchConfig(nodeId).getNodeProperties();
914         Node node = Node.fromString(nodeId);
915         Map<String, Property> propMapCurr = nodeProps.get(node);
916         if ((propMapCurr != null) && (nodeProperties != null) && (!nodeProperties.isEmpty())) {
917             Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
918             for (Map.Entry<String, Property> entry : nodeProperties.entrySet()) {
919                 String prop = entry.getKey();
920                 if (prop.equals(Description.propertyName)) {
921                     Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
922                     if (nodeProp.get(node) != null) {
923                         propMap.put(Description.propertyName, nodeProp.get(node).get(Description.propertyName));
924                         continue;
925                     }
926                 }
927                 propMap.remove(prop);
928             }
929             if (!nodeProps.replace(node, propMapCurr, propMap)) {
930                 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration.");
931             }
932         }
933         if (nodeConfigList != null) {
934             nodeConfigList.remove(nodeId);
935         }
936         return new Status(StatusCode.SUCCESS);
937     }
938
939     @Override
940     public Status saveSwitchConfig() {
941         return saveSwitchConfigInternal();
942     }
943
944     public Status saveSwitchConfigInternal() {
945         Status retS = null, retP = null;
946         ObjectWriter objWriter = new ObjectWriter();
947
948         retS = objWriter.write(new ConcurrentHashMap<String, SubnetConfig>(
949                 subnetsConfigList), subnetFileName);
950         retP = objWriter.write(new ConcurrentHashMap<SpanConfig, SpanConfig>(
951                 spanConfigList), spanFileName);
952         retS = objWriter.write(new ConcurrentHashMap<String, SwitchConfig>(
953                 nodeConfigList), switchConfigFileName);
954         if (retS.equals(retP)) {
955             if (retS.isSuccess()) {
956                 return retS;
957             } else {
958                 return new Status(StatusCode.INTERNALERROR, "Save failed");
959             }
960         } else {
961             return new Status(StatusCode.INTERNALERROR, "Partial save failure");
962         }
963     }
964
965     @Override
966     public List<SpanConfig> getSpanConfigList() {
967         return new ArrayList<SpanConfig>(spanConfigList.values());
968     }
969
970     @Override
971     public Status addSpanConfig(SpanConfig conf) {
972         // Valid config check
973         if (!conf.isValidConfig()) {
974             String msg = "Invalid Span configuration";
975             log.warn(msg);
976             return new Status(StatusCode.BADREQUEST, msg);
977         }
978
979         // Presence check
980         if (spanConfigList.containsKey(conf)) {
981             return new Status(StatusCode.CONFLICT, "Same span config exists");
982         }
983
984         // Update configuration
985         if (spanConfigList.putIfAbsent(conf, conf) == null) {
986             // Update database and notify clients
987             addSpanPorts(conf.getNode(), conf.getPortArrayList());
988         }
989
990         return new Status(StatusCode.SUCCESS);
991     }
992
993     @Override
994     public Status removeSpanConfig(SpanConfig conf) {
995         removeSpanPorts(conf.getNode(), conf.getPortArrayList());
996
997         // Update configuration
998         spanConfigList.remove(conf);
999
1000         return new Status(StatusCode.SUCCESS);
1001     }
1002
1003     @Override
1004     public List<NodeConnector> getSpanPorts(Node node) {
1005         List<NodeConnector> ncList = new ArrayList<NodeConnector>();
1006
1007         for (NodeConnector nodeConnector : spanNodeConnectors) {
1008             if (nodeConnector.getNode().equals(node)) {
1009                 ncList.add(nodeConnector);
1010             }
1011         }
1012         return ncList;
1013     }
1014
1015     private void addNode(Node node, Set<Property> props) {
1016         log.trace("{} added, props: {}", node, props);
1017         if (nodeProps == null) {
1018             return;
1019         }
1020
1021         Map<String, Property> propMapCurr = nodeProps.get(node);
1022         Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1023                 : new HashMap<String, Property>(propMapCurr);
1024
1025         // copy node properties from plugin
1026         if (props != null) {
1027             for (Property prop : props) {
1028                 propMap.put(prop.getName(), prop);
1029             }
1030         }
1031
1032         boolean proactiveForwarding = false;
1033         // copy node properties from config
1034         if (nodeConfigList != null) {
1035             String nodeId = node.toString();
1036             SwitchConfig conf = nodeConfigList.get(nodeId);
1037             if (conf != null && (conf.getNodeProperties() != null)) {
1038                 Map<String, Property> nodeProperties = conf.getNodeProperties();
1039                 propMap.putAll(nodeProperties);
1040                 if (nodeProperties.get(ForwardingMode.name) != null) {
1041                     ForwardingMode mode = (ForwardingMode) nodeProperties.get(ForwardingMode.name);
1042                     proactiveForwarding = mode.isProactive();
1043                 }
1044             }
1045         }
1046
1047         if (!propMap.containsKey(ForwardingMode.name)) {
1048             Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING);
1049             propMap.put(ForwardingMode.name, defaultMode);
1050         }
1051         boolean result = false;
1052         if (propMapCurr == null) {
1053             if (nodeProps.putIfAbsent(node, propMap) == null) {
1054                 result = true;
1055             }
1056         } else {
1057             result = nodeProps.replace(node, propMapCurr, propMap);
1058         }
1059         if (!result) {
1060             log.debug("Cluster conflict: Conflict while adding the node properties. Node: {}  Properties: {}",
1061                     node.getID(), props);
1062             addNodeProps(node, propMap);
1063         }
1064
1065         // check if span ports are configed
1066         addSpanPorts(node);
1067
1068         // notify node listeners
1069         notifyNode(node, UpdateType.ADDED, propMap);
1070
1071         // notify proactive mode forwarding
1072         if (proactiveForwarding) {
1073             notifyModeChange(node, true);
1074         }
1075     }
1076
1077     private void removeNode(Node node) {
1078         log.trace("{} removed", node);
1079         if (nodeProps == null) {
1080             return;
1081         }
1082         nodeProps.remove(node);
1083         nodeConnectorNames.remove(node);
1084         Set<NodeConnector> removeNodeConnectorSet = new HashSet<NodeConnector>();
1085         for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1086             NodeConnector nodeConnector = entry.getKey();
1087             if (nodeConnector.getNode().equals(node)) {
1088                 removeNodeConnectorSet.add(nodeConnector);
1089             }
1090         }
1091         for (NodeConnector nc : removeNodeConnectorSet) {
1092             nodeConnectorProps.remove(nc);
1093         }
1094
1095         // check if span ports need to be cleaned up
1096         removeSpanPorts(node);
1097
1098         /* notify node listeners */
1099         notifyNode(node, UpdateType.REMOVED, null);
1100     }
1101
1102     private void updateNode(Node node, Set<Property> props) {
1103         log.trace("{} updated, props: {}", node, props);
1104         if (nodeProps == null || !nodeProps.containsKey(node) ||
1105                 props == null || props.isEmpty()) {
1106             return;
1107         }
1108
1109         Map<String, Property> propMapCurr = nodeProps.get(node);
1110         Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1111                 : new HashMap<String, Property>(propMapCurr);
1112
1113         // copy node properties from plugin
1114         String nodeId = node.toString();
1115         for (Property prop : props) {
1116             if (nodeConfigList != null) {
1117                 SwitchConfig conf = nodeConfigList.get(nodeId);
1118                 if (conf != null && (conf.getNodeProperties() != null)
1119                         && conf.getNodeProperties().containsKey(prop.getName())) {
1120                     continue;
1121                 }
1122             }
1123             propMap.put(prop.getName(), prop);
1124         }
1125
1126         if (propMapCurr == null) {
1127             if (nodeProps.putIfAbsent(node, propMap) != null) {
1128                 log.debug("Cluster conflict: Conflict while updating the node. Node: {}  Properties: {}",
1129                         node.getID(), props);
1130                 addNodeProps(node, propMap);
1131             }
1132         } else {
1133             if (!nodeProps.replace(node, propMapCurr, propMap)) {
1134                 log.debug("Cluster conflict: Conflict while updating the node. Node: {}  Properties: {}",
1135                         node.getID(), props);
1136                 addNodeProps(node, propMap);
1137             }
1138         }
1139
1140         /* notify node listeners */
1141         notifyNode(node, UpdateType.CHANGED, propMap);
1142     }
1143
1144     @Override
1145     public void updateNode(Node node, UpdateType type, Set<Property> props) {
1146         log.debug("updateNode: {} type {} props {} for container {}",
1147                 new Object[] { node, type, props, containerName });
1148         switch (type) {
1149         case ADDED:
1150             addNode(node, props);
1151             break;
1152         case CHANGED:
1153             updateNode(node, props);
1154             break;
1155         case REMOVED:
1156             removeNode(node);
1157             break;
1158         default:
1159             break;
1160         }
1161     }
1162
1163     @Override
1164     public void updateNodeConnector(NodeConnector nodeConnector,
1165             UpdateType type, Set<Property> props) {
1166         Map<String, Property> propMap = new HashMap<String, Property>();
1167         boolean update = true;
1168
1169         log.debug("updateNodeConnector: {} type {} props {} for container {}",
1170                 new Object[] { nodeConnector, type, props, containerName });
1171
1172         if (nodeConnectorProps == null) {
1173             return;
1174         }
1175
1176         switch (type) {
1177         case ADDED:
1178             if (props != null) {
1179                 for (Property prop : props) {
1180                     addNodeConnectorProp(nodeConnector, prop);
1181                     propMap.put(prop.getName(), prop);
1182                 }
1183             } else {
1184                 addNodeConnectorProp(nodeConnector, null);
1185             }
1186
1187             addSpanPort(nodeConnector);
1188             break;
1189         case CHANGED:
1190             if (!nodeConnectorProps.containsKey(nodeConnector) || (props == null)) {
1191                 update = false;
1192             } else {
1193                 for (Property prop : props) {
1194                     addNodeConnectorProp(nodeConnector, prop);
1195                     propMap.put(prop.getName(), prop);
1196                 }
1197             }
1198             break;
1199         case REMOVED:
1200             if (!nodeConnectorProps.containsKey(nodeConnector)) {
1201                 update = false;
1202             }
1203             removeNodeConnectorAllProps(nodeConnector);
1204
1205             // clean up span config
1206             removeSpanPort(nodeConnector);
1207             break;
1208         default:
1209             update = false;
1210             break;
1211         }
1212
1213         if (update) {
1214             notifyNodeConnector(nodeConnector, type, propMap);
1215         }
1216     }
1217
1218     @Override
1219     public Set<Node> getNodes() {
1220         return (nodeProps != null) ? new HashSet<Node>(nodeProps.keySet()) : new HashSet<Node>();
1221     }
1222
1223     @Override
1224     public Map<String, Property> getControllerProperties() {
1225         return new HashMap<String, Property>(this.controllerProps);
1226     }
1227
1228     @Override
1229     public Property getControllerProperty(String propertyName) {
1230         if (propertyName != null) {
1231             HashMap<String, Property> propertyMap =  new HashMap<String, Property>(this.controllerProps);
1232             return propertyMap.get(propertyName);
1233         }
1234         return null;
1235     }
1236
1237     @Override
1238     public Status setControllerProperty(Property property) {
1239         if (property != null) {
1240             this.controllerProps.put(property.getName(), property);
1241             return new Status(StatusCode.SUCCESS);
1242         }
1243         return new Status(StatusCode.BADREQUEST, "Invalid property provided when setting property");
1244     }
1245
1246     @Override
1247     public Status removeControllerProperty(String propertyName) {
1248         if (propertyName != null) {
1249             if (this.controllerProps.containsKey(propertyName)) {
1250                 this.controllerProps.remove(propertyName);
1251                 if (!this.controllerProps.containsKey(propertyName)) {
1252                     return new Status(StatusCode.SUCCESS);
1253                 }
1254             }
1255             String msg = "Unable to remove property " + propertyName + " from Controller";
1256             return new Status(StatusCode.BADREQUEST, msg);
1257         }
1258         String msg = "Invalid property provided when removing property from Controller";
1259         return new Status(StatusCode.BADREQUEST, msg);
1260     }
1261
1262     /*
1263      * Returns a copy of a list of properties for a given node
1264      *
1265      * (non-Javadoc)
1266      *
1267      * @see
1268      * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps
1269      * (org.opendaylight.controller.sal.core.Node)
1270      */
1271     @Override
1272     public Map<String, Property> getNodeProps(Node node) {
1273         Map<String, Property> rv = new HashMap<String, Property>();
1274         if (this.nodeProps != null) {
1275             rv = this.nodeProps.get(node);
1276             if (rv != null) {
1277                 /* make a copy of it */
1278                 rv = new HashMap<String, Property>(rv);
1279             }
1280         }
1281         return rv;
1282     }
1283
1284     @Override
1285     public Property getNodeProp(Node node, String propName) {
1286         Map<String, Property> propMap = getNodeProps(node);
1287         return (propMap != null) ? propMap.get(propName) : null;
1288     }
1289
1290     @Override
1291     public void setNodeProp(Node node, Property prop) {
1292
1293         for (int i = 0; i <= REPLACE_RETRY; i++) {
1294             /* Get a copy of the property map */
1295             Map<String, Property> propMapCurr = getNodeProps(node);
1296             if (propMapCurr == null) {
1297                 return;
1298             }
1299
1300             Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1301             propMap.put(prop.getName(), prop);
1302
1303             if (nodeProps.replace(node, propMapCurr, propMap)) {
1304                 return;
1305             }
1306             if (!propMapCurr.get(prop.getName()).equals(nodeProps.get(node).get(prop.getName()))) {
1307                 log.debug("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1308                 return;
1309             }
1310         }
1311         log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1312     }
1313
1314     @Override
1315     public Status removeNodeProp(Node node, String propName) {
1316         for (int i = 0; i <= REPLACE_RETRY; i++) {
1317             Map<String, Property> propMapCurr = getNodeProps(node);
1318             if (propMapCurr != null) {
1319                 if (!propMapCurr.containsKey(propName)) {
1320                     return new Status(StatusCode.SUCCESS);
1321                 }
1322                 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1323                 propMap.remove(propName);
1324                 if (nodeProps.replace(node, propMapCurr, propMap)) {
1325                     return new Status(StatusCode.SUCCESS);
1326                 }
1327                 if (!propMapCurr.get(propName).equals(nodeProps.get(node).get(propName))) {
1328                     String msg = "Cluster conflict: Unable to remove property " + propName + " for node "
1329                             + node.getID();
1330                     return new Status(StatusCode.CONFLICT, msg);
1331                 }
1332
1333             } else {
1334                 return new Status(StatusCode.SUCCESS);
1335             }
1336         }
1337         String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID();
1338         return new Status(StatusCode.CONFLICT, msg);
1339     }
1340
1341     @Override
1342     public Status removeNodeAllProps(Node node) {
1343         this.nodeProps.remove(node);
1344         return new Status(StatusCode.SUCCESS);
1345     }
1346
1347     @Override
1348     public Set<NodeConnector> getUpNodeConnectors(Node node) {
1349         if (nodeConnectorProps == null) {
1350             return null;
1351         }
1352
1353         Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1354         for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1355             NodeConnector nodeConnector = entry.getKey();
1356             if (!nodeConnector.getNode().equals(node)) {
1357                 continue;
1358             }
1359             if (isNodeConnectorEnabled(nodeConnector)) {
1360                 nodeConnectorSet.add(nodeConnector);
1361             }
1362         }
1363
1364         return nodeConnectorSet;
1365     }
1366
1367     @Override
1368     public Set<NodeConnector> getNodeConnectors(Node node) {
1369         if (nodeConnectorProps == null) {
1370             return null;
1371         }
1372
1373         Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1374         for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1375             NodeConnector nodeConnector = entry.getKey();
1376             if (!nodeConnector.getNode().equals(node)) {
1377                 continue;
1378             }
1379             nodeConnectorSet.add(nodeConnector);
1380         }
1381
1382         return nodeConnectorSet;
1383     }
1384
1385     @Override
1386     public Set<NodeConnector> getPhysicalNodeConnectors(Node node) {
1387         if (nodeConnectorProps == null) {
1388             return null;
1389         }
1390
1391         Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1392         for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1393             NodeConnector nodeConnector = entry.getKey();
1394             if (!nodeConnector.getNode().equals(node)
1395                     || isSpecial(nodeConnector)) {
1396                 continue;
1397             }
1398             nodeConnectorSet.add(nodeConnector);
1399         }
1400
1401         return nodeConnectorSet;
1402     }
1403
1404     @Override
1405     public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) {
1406         Map<String, Property> rv = new HashMap<String, Property>();
1407         if (this.nodeConnectorProps != null) {
1408             rv = this.nodeConnectorProps.get(nodeConnector);
1409             if (rv != null) {
1410                 rv = new HashMap<String, Property>(rv);
1411             }
1412         }
1413         return rv;
1414     }
1415
1416     @Override
1417     public Property getNodeConnectorProp(NodeConnector nodeConnector,
1418             String propName) {
1419         Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1420         return (propMap != null) ? propMap.get(propName) : null;
1421     }
1422
1423     private byte[] getHardwareMAC() {
1424         Enumeration<NetworkInterface> nis;
1425         byte[] macAddress = null;
1426
1427         try {
1428             nis = NetworkInterface.getNetworkInterfaces();
1429         } catch (SocketException e) {
1430             log.error("Failed to acquire controller MAC: ", e);
1431             return macAddress;
1432         }
1433
1434         while (nis.hasMoreElements()) {
1435             NetworkInterface ni = nis.nextElement();
1436             try {
1437                 macAddress = ni.getHardwareAddress();
1438             } catch (SocketException e) {
1439                 log.error("Failed to acquire controller MAC: ", e);
1440             }
1441             if (macAddress != null) {
1442                 break;
1443             }
1444         }
1445         if (macAddress == null) {
1446             log.warn("Failed to acquire controller MAC: No physical interface found");
1447             // This happens when running controller on windows VM, for example
1448             // Try parsing the OS command output
1449         }
1450         return macAddress;
1451     }
1452
1453     @Override
1454     public byte[] getControllerMAC() {
1455         MacAddress macProperty = (MacAddress)controllerProps.get(MacAddress.name);
1456         return (macProperty == null) ? null : macProperty.getMacAddress();
1457     }
1458
1459     @Override
1460     public NodeConnector getNodeConnector(Node node, String nodeConnectorName) {
1461         if (nodeConnectorNames == null) {
1462             return null;
1463         }
1464
1465         Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1466         if (map == null) {
1467             return null;
1468         }
1469
1470         return map.get(nodeConnectorName);
1471     }
1472
1473     /**
1474      * Adds a node connector and its property if any
1475      *
1476      * @param nodeConnector
1477      *            {@link org.opendaylight.controller.sal.core.NodeConnector}
1478      * @param propName
1479      *            name of {@link org.opendaylight.controller.sal.core.Property}
1480      * @return success or failed reason
1481      */
1482     @Override
1483     public Status addNodeConnectorProp(NodeConnector nodeConnector,
1484             Property prop) {
1485         Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1486         Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1487                 : new HashMap<String, Property>(propMapCurr);
1488
1489         String msg = "Cluster conflict: Unable to add NodeConnector Property.";
1490         // Just add the nodeConnector if prop is not available (in a non-default
1491         // container)
1492         if (prop == null) {
1493             if (propMapCurr == null) {
1494                 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1495                     return new Status(StatusCode.CONFLICT, msg);
1496                 }
1497             } else {
1498                 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1499                     return new Status(StatusCode.CONFLICT, msg);
1500                 }
1501             }
1502             return new Status(StatusCode.SUCCESS);
1503         }
1504
1505         propMap.put(prop.getName(), prop);
1506         if (propMapCurr == null) {
1507             if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1508                 return new Status(StatusCode.CONFLICT, msg);
1509             }
1510         } else {
1511             if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1512                 return new Status(StatusCode.CONFLICT, msg);
1513             }
1514         }
1515
1516         if (prop.getName().equals(Name.NamePropName)) {
1517             if (nodeConnectorNames != null) {
1518                 Node node = nodeConnector.getNode();
1519                 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1520                 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1521                 if (mapCurr != null) {
1522                     for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1523                         String s = entry.getKey();
1524                         try {
1525                             map.put(s, new NodeConnector(entry.getValue()));
1526                         } catch (ConstructionException e) {
1527                             log.error("An error occured",e);
1528                         }
1529                     }
1530                 }
1531
1532                 map.put(((Name) prop).getValue(), nodeConnector);
1533                 if (mapCurr == null) {
1534                     if (nodeConnectorNames.putIfAbsent(node, map) != null) {
1535                         // TODO: recovery using Transactionality
1536                         return new Status(StatusCode.CONFLICT, msg);
1537                     }
1538                 } else {
1539                     if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1540                         // TODO: recovery using Transactionality
1541                         return new Status(StatusCode.CONFLICT, msg);
1542                     }
1543                 }
1544             }
1545         }
1546
1547         return new Status(StatusCode.SUCCESS);
1548     }
1549
1550     /**
1551      * Removes one property of a node connector
1552      *
1553      * @param nodeConnector
1554      *            {@link org.opendaylight.controller.sal.core.NodeConnector}
1555      * @param propName
1556      *            name of {@link org.opendaylight.controller.sal.core.Property}
1557      * @return success or failed reason
1558      */
1559     @Override
1560     public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) {
1561         Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1562
1563         if (propMapCurr == null) {
1564             /* Nothing to remove */
1565             return new Status(StatusCode.SUCCESS);
1566         }
1567
1568         Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1569         propMap.remove(propName);
1570         boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap);
1571         String msg = "Cluster conflict: Unable to remove NodeConnector property.";
1572         if (!result) {
1573             return new Status(StatusCode.CONFLICT, msg);
1574         }
1575
1576         if (propName.equals(Name.NamePropName)) {
1577             if (nodeConnectorNames != null) {
1578                 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1579                 if (name != null) {
1580                     Node node = nodeConnector.getNode();
1581                     Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1582                     if (mapCurr != null) {
1583                         Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1584                         for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1585                             String s = entry.getKey();
1586                             try {
1587                                 map.put(s, new NodeConnector(entry.getValue()));
1588                             } catch (ConstructionException e) {
1589                                 log.error("An error occured",e);
1590                             }
1591                         }
1592                         map.remove(name.getValue());
1593                         if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1594                             // TODO: recovery using Transactionality
1595                             return new Status(StatusCode.CONFLICT, msg);
1596                         }
1597                     }
1598                 }
1599             }
1600         }
1601
1602         return new Status(StatusCode.SUCCESS);
1603     }
1604
1605     /**
1606      * Removes all the properties of a node connector
1607      *
1608      * @param nodeConnector
1609      *            {@link org.opendaylight.controller.sal.core.NodeConnector}
1610      * @return success or failed reason
1611      */
1612     @Override
1613     public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) {
1614         if (nodeConnectorNames != null) {
1615             Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1616             if (name != null) {
1617                 Node node = nodeConnector.getNode();
1618                 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1619                 if (mapCurr != null) {
1620                     Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1621                     for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1622                         String s = entry.getKey();
1623                         try {
1624                             map.put(s, new NodeConnector(entry.getValue()));
1625                         } catch (ConstructionException e) {
1626                             log.error("An error occured",e);
1627                         }
1628                     }
1629                     map.remove(name.getValue());
1630                     if (map.isEmpty()) {
1631                         nodeConnectorNames.remove(node);
1632                     } else {
1633                         if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1634                             log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.",
1635                                     nodeConnector.getID());
1636                         }
1637                     }
1638                 }
1639
1640             }
1641         }
1642         nodeConnectorProps.remove(nodeConnector);
1643
1644         return new Status(StatusCode.SUCCESS);
1645     }
1646
1647     /**
1648      * Function called by the dependency manager when all the required
1649      * dependencies are satisfied
1650      *
1651      */
1652     void init(Component c) {
1653         Dictionary<?, ?> props = c.getServiceProperties();
1654         if (props != null) {
1655             this.containerName = (String) props.get("containerName");
1656             log.trace("Running containerName: {}", this.containerName);
1657         } else {
1658             // In the Global instance case the containerName is empty
1659             this.containerName = "";
1660         }
1661         isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT
1662                 .toString());
1663
1664         startUp();
1665     }
1666
1667     /**
1668      * Function called by the dependency manager when at least one dependency
1669      * become unsatisfied or when the component is shutting down because for
1670      * example bundle is being stopped.
1671      *
1672      */
1673     void destroy() {
1674         shutDown();
1675     }
1676
1677     /**
1678      * Function called by dependency manager after "init ()" is called and after
1679      * the services provided by the class are registered in the service registry
1680      *
1681      */
1682     void start() {
1683         // OSGI console
1684         registerWithOSGIConsole();
1685     }
1686
1687     /**
1688      * Function called after registered the service in OSGi service registry.
1689      */
1690     void started() {
1691         // solicit for existing inventories
1692         getInventories();
1693     }
1694
1695     /**
1696      * Function called by the dependency manager before the services exported by
1697      * the component are unregistered, this will be followed by a "destroy ()"
1698      * calls
1699      *
1700      */
1701     void stop() {
1702     }
1703
1704     public void setInventoryService(IInventoryService service) {
1705         log.trace("Got inventory service set request {}", service);
1706         this.inventoryService = service;
1707
1708         // solicit for existing inventories
1709         getInventories();
1710     }
1711
1712     public void unsetInventoryService(IInventoryService service) {
1713         log.trace("Got a service UNset request");
1714         this.inventoryService = null;
1715
1716         // clear existing inventories
1717         clearInventories();
1718     }
1719
1720     public void setStatisticsManager(IStatisticsManager statisticsManager) {
1721         log.trace("Got statistics manager set request {}", statisticsManager);
1722         this.statisticsManager = statisticsManager;
1723     }
1724
1725     public void unsetStatisticsManager(IStatisticsManager statisticsManager) {
1726         log.trace("Got statistics manager UNset request");
1727         this.statisticsManager = null;
1728     }
1729
1730     public void setSwitchManagerAware(ISwitchManagerAware service) {
1731         log.trace("Got inventory service set request {}", service);
1732         if (this.switchManagerAware != null) {
1733             this.switchManagerAware.add(service);
1734         }
1735
1736         // bulk update for newly joined
1737         switchManagerAwareNotify(service);
1738     }
1739
1740     public void unsetSwitchManagerAware(ISwitchManagerAware service) {
1741         log.trace("Got a service UNset request");
1742         if (this.switchManagerAware != null) {
1743             this.switchManagerAware.remove(service);
1744         }
1745     }
1746
1747     public void setInventoryListener(IInventoryListener service) {
1748         log.trace("Got inventory listener set request {}", service);
1749         if (this.inventoryListeners != null) {
1750             this.inventoryListeners.add(service);
1751         }
1752
1753         // bulk update for newly joined
1754         bulkUpdateService(service);
1755     }
1756
1757     public void unsetInventoryListener(IInventoryListener service) {
1758         log.trace("Got a service UNset request");
1759         if (this.inventoryListeners != null) {
1760             this.inventoryListeners.remove(service);
1761         }
1762     }
1763
1764     public void setSpanAware(ISpanAware service) {
1765         log.trace("Got SpanAware set request {}", service);
1766         if (this.spanAware != null) {
1767             this.spanAware.add(service);
1768         }
1769
1770         // bulk update for newly joined
1771         spanAwareNotify(service);
1772     }
1773
1774     public void unsetSpanAware(ISpanAware service) {
1775         log.trace("Got a service UNset request");
1776         if (this.spanAware != null) {
1777             this.spanAware.remove(service);
1778         }
1779     }
1780
1781     void setClusterContainerService(IClusterContainerServices s) {
1782         log.trace("Cluster Service set");
1783         this.clusterContainerService = s;
1784     }
1785
1786     void unsetClusterContainerService(IClusterContainerServices s) {
1787         if (this.clusterContainerService == s) {
1788             log.trace("Cluster Service removed!");
1789             this.clusterContainerService = null;
1790         }
1791     }
1792
1793     private void getInventories() {
1794         if (inventoryService == null) {
1795             log.trace("inventory service not avaiable");
1796             return;
1797         }
1798
1799         Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
1800         for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) {
1801             Node node = entry.getKey();
1802             log.debug("getInventories: {} added for container {}", new Object[] { node, containerName });
1803             Map<String, Property> propMap = entry.getValue();
1804             Set<Property> props = new HashSet<Property>();
1805             for (Property property : propMap.values()) {
1806                 props.add(property);
1807             }
1808             addNode(node, props);
1809         }
1810
1811         Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps();
1812         for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) {
1813             Map<String, Property> propMap = entry.getValue();
1814             for (Property property : propMap.values()) {
1815                 addNodeConnectorProp(entry.getKey(), property);
1816             }
1817         }
1818     }
1819
1820     private void clearInventories() {
1821         nodeProps.clear();
1822         nodeConnectorProps.clear();
1823         nodeConnectorNames.clear();
1824         spanNodeConnectors.clear();
1825     }
1826
1827     private void notifyNode(Node node, UpdateType type,
1828             Map<String, Property> propMap) {
1829         synchronized (inventoryListeners) {
1830             for (IInventoryListener service : inventoryListeners) {
1831                 service.notifyNode(node, type, propMap);
1832             }
1833         }
1834     }
1835
1836     private void notifyNodeConnector(NodeConnector nodeConnector,
1837             UpdateType type, Map<String, Property> propMap) {
1838         synchronized (inventoryListeners) {
1839             for (IInventoryListener service : inventoryListeners) {
1840                 service.notifyNodeConnector(nodeConnector, type, propMap);
1841             }
1842         }
1843     }
1844
1845     /*
1846      * For those joined late, bring them up-to-date.
1847      */
1848     private void switchManagerAwareNotify(ISwitchManagerAware service) {
1849         for (Subnet sub : subnets.values()) {
1850             service.subnetNotify(sub, true);
1851         }
1852
1853         for (Node node : getNodes()) {
1854             SwitchConfig sc = getSwitchConfig(node.toString());
1855             if ((sc != null) && isDefaultContainer) {
1856                 ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
1857                 service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive());
1858             }
1859         }
1860     }
1861
1862     private void bulkUpdateService(IInventoryListener service) {
1863         Map<String, Property> propMap;
1864         UpdateType type = UpdateType.ADDED;
1865
1866         for (Node node : getNodes()) {
1867             propMap = nodeProps.get(node);
1868             service.notifyNode(node, type, propMap);
1869         }
1870
1871         for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1872             NodeConnector nodeConnector = entry.getKey();
1873             propMap = nodeConnectorProps.get(nodeConnector);
1874             service.notifyNodeConnector(nodeConnector, type, propMap);
1875         }
1876     }
1877
1878     private void spanAwareNotify(ISpanAware service) {
1879         for (Node node : getNodes()) {
1880             for (SpanConfig conf : getSpanConfigList(node)) {
1881                 service.spanUpdate(node, conf.getPortArrayList(), true);
1882             }
1883         }
1884     }
1885
1886     private void registerWithOSGIConsole() {
1887         BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
1888                 .getBundleContext();
1889         bundleContext.registerService(CommandProvider.class.getName(), this,
1890                 null);
1891     }
1892
1893     @Override
1894     public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) {
1895         if (nodeConnector == null) {
1896             return false;
1897         }
1898
1899         Config config = (Config) getNodeConnectorProp(nodeConnector,
1900                 Config.ConfigPropName);
1901         State state = (State) getNodeConnectorProp(nodeConnector,
1902                 State.StatePropName);
1903         return ((config != null) && (config.getValue() == Config.ADMIN_UP)
1904                 && (state != null) && (state.getValue() == State.EDGE_UP));
1905     }
1906
1907     @Override
1908     public boolean doesNodeConnectorExist(NodeConnector nc) {
1909         return (nc != null && nodeConnectorProps != null
1910                 && nodeConnectorProps.containsKey(nc));
1911     }
1912
1913     @Override
1914     public String getHelp() {
1915         StringBuffer help = new StringBuffer();
1916         help.append("---Switch Manager---\n");
1917         help.append("\t pencs <node id>        - Print enabled node connectors for a given node\n");
1918         help.append("\t pdm <node id>          - Print switch ports in device map\n");
1919         return help.toString();
1920     }
1921
1922     public void _pencs(CommandInterpreter ci) {
1923         String st = ci.nextArgument();
1924         if (st == null) {
1925             ci.println("Please enter node id");
1926             return;
1927         }
1928
1929         Node node = Node.fromString(st);
1930         if (node == null) {
1931             ci.println("Please enter node id");
1932             return;
1933         }
1934
1935         Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node);
1936         if (nodeConnectorSet == null) {
1937             return;
1938         }
1939         for (NodeConnector nodeConnector : nodeConnectorSet) {
1940             if (nodeConnector == null) {
1941                 continue;
1942             }
1943             ci.println(nodeConnector);
1944         }
1945         ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1946     }
1947
1948     public void _pdm(CommandInterpreter ci) {
1949         String st = ci.nextArgument();
1950         if (st == null) {
1951             ci.println("Please enter node id");
1952             return;
1953         }
1954
1955         Node node = Node.fromString(st);
1956         if (node == null) {
1957             ci.println("Please enter node id");
1958             return;
1959         }
1960
1961         Switch sw = getSwitchByNode(node);
1962
1963         ci.println("          NodeConnector                        Name");
1964
1965         Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors();
1966         String nodeConnectorName;
1967         if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
1968             for (NodeConnector nodeConnector : nodeConnectorSet) {
1969                 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1970                 nodeConnectorName = (propMap == null) ? null : ((Name) propMap
1971                         .get(Name.NamePropName)).getValue();
1972                 if (nodeConnectorName != null) {
1973                     Node nd = nodeConnector.getNode();
1974                     if (!nd.equals(node)) {
1975                         log.debug("node not match {} {}", nd, node);
1976                     }
1977                     Map<String, NodeConnector> map = nodeConnectorNames
1978                             .get(node);
1979                     if (map != null) {
1980                         NodeConnector nc = map.get(nodeConnectorName);
1981                         if (nc == null) {
1982                             log.debug("no nodeConnector named {}",
1983                                     nodeConnectorName);
1984                         } else if (!nc.equals(nodeConnector)) {
1985                             log.debug("nodeConnector not match {} {}", nc,
1986                                     nodeConnector);
1987                         }
1988                     }
1989                 }
1990
1991                 ci.println(nodeConnector
1992                         + "            "
1993                         + ((nodeConnectorName == null) ? "" : nodeConnectorName)
1994                         + "(" + nodeConnector.getID() + ")");
1995             }
1996             ci.println("Total number of NodeConnectors: "
1997                     + nodeConnectorSet.size());
1998         }
1999     }
2000
2001     @Override
2002     public byte[] getNodeMAC(Node node) {
2003         MacAddress mac = (MacAddress) this.getNodeProp(node,
2004                 MacAddress.name);
2005         return (mac != null) ? mac.getMacAddress() : null;
2006     }
2007
2008     @Override
2009     public boolean isSpecial(NodeConnector p) {
2010         if (p.getType().equals(NodeConnectorIDType.CONTROLLER)
2011                 || p.getType().equals(NodeConnectorIDType.ALL)
2012                 || p.getType().equals(NodeConnectorIDType.SWSTACK)
2013                 || p.getType().equals(NodeConnectorIDType.HWPATH)) {
2014             return true;
2015         }
2016         return false;
2017     }
2018
2019     /*
2020      * Add span configuration to local cache and notify clients
2021      */
2022     private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2023         List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2024
2025         for (NodeConnector nodeConnector : nodeConnectors) {
2026             if (!spanNodeConnectors.contains(nodeConnector)) {
2027                 ncLists.add(nodeConnector);
2028             }
2029         }
2030
2031         if (ncLists.size() > 0) {
2032             spanNodeConnectors.addAll(ncLists);
2033             notifySpanPortChange(node, ncLists, true);
2034         }
2035     }
2036
2037     private void addSpanPorts(Node node) {
2038         for (SpanConfig conf : getSpanConfigList(node)) {
2039             addSpanPorts(node, conf.getPortArrayList());
2040         }
2041     }
2042
2043     private void addSpanPort(NodeConnector nodeConnector) {
2044         // only add if span is configured on this nodeConnector
2045         for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) {
2046             if (conf.getPortArrayList().contains(nodeConnector)) {
2047                 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2048                 ncLists.add(nodeConnector);
2049                 addSpanPorts(nodeConnector.getNode(), ncLists);
2050                 return;
2051             }
2052         }
2053     }
2054
2055     /*
2056      * Remove span configuration to local cache and notify clients
2057      */
2058     private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2059         List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2060
2061         for (NodeConnector nodeConnector : nodeConnectors) {
2062             if (spanNodeConnectors.contains(nodeConnector)) {
2063                 ncLists.add(nodeConnector);
2064             }
2065         }
2066
2067         if (ncLists.size() > 0) {
2068             spanNodeConnectors.removeAll(ncLists);
2069             notifySpanPortChange(node, ncLists, false);
2070         }
2071     }
2072
2073     private void removeSpanPorts(Node node) {
2074         for (SpanConfig conf : getSpanConfigList(node)) {
2075             addSpanPorts(node, conf.getPortArrayList());
2076         }
2077     }
2078
2079     private void removeSpanPort(NodeConnector nodeConnector) {
2080         if (spanNodeConnectors.contains(nodeConnector)) {
2081             List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2082             ncLists.add(nodeConnector);
2083             removeSpanPorts(nodeConnector.getNode(), ncLists);
2084         }
2085     }
2086
2087     private void addNodeProps(Node node, Map<String, Property> propMap) {
2088         if (propMap == null) {
2089             propMap = new HashMap<String, Property>();
2090         }
2091         nodeProps.put(node, propMap);
2092     }
2093
2094     @Override
2095     public Status saveConfiguration() {
2096         return saveSwitchConfig();
2097     }
2098
2099     /**
2100      * Creates a Name/Tier/Bandwidth/MacAddress(controller property) Property
2101      * object based on given property name and value. Other property types are
2102      * not supported yet.
2103      *
2104      * @param propName
2105      *            Name of the Property
2106      * @param propValue
2107      *            Value of the Property
2108      * @return {@link org.opendaylight.controller.sal.core.Property}
2109      */
2110     @Override
2111     public Property createProperty(String propName, String propValue) {
2112         if (propName == null) {
2113             log.debug("propName is null");
2114             return null;
2115         }
2116         if (propValue == null) {
2117             log.debug("propValue is null");
2118             return null;
2119         }
2120
2121         try {
2122             if (propName.equalsIgnoreCase(Description.propertyName)) {
2123                 return new Description(propValue);
2124             } else if (propName.equalsIgnoreCase(Tier.TierPropName)) {
2125                 int tier = Integer.parseInt(propValue);
2126                 return new Tier(tier);
2127             } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) {
2128                 long bw = Long.parseLong(propValue);
2129                 return new Bandwidth(bw);
2130             } else if (propName.equalsIgnoreCase(ForwardingMode.name)) {
2131                 int mode = Integer.parseInt(propValue);
2132                 return new ForwardingMode(mode);
2133             } else if (propName.equalsIgnoreCase(MacAddress.name)){
2134                 return new MacAddress(propValue);
2135             }
2136             else {
2137                 log.debug("Not able to create {} property", propName);
2138             }
2139         } catch (Exception e) {
2140             log.debug("createProperty caught exception {}", e.getMessage());
2141         }
2142
2143         return null;
2144     }
2145
2146
2147     @SuppressWarnings("deprecation")
2148     @Override
2149     public String getNodeDescription(Node node) {
2150         // Check first if user configured a name
2151         SwitchConfig config = getSwitchConfig(node.toString());
2152         if (config != null) {
2153             String configuredDesc = config.getNodeDescription();
2154             if (configuredDesc != null && !configuredDesc.isEmpty()) {
2155                 return configuredDesc;
2156             }
2157         }
2158
2159         // No name configured by user, get the node advertised name
2160         Description desc = (Description) getNodeProp(node,
2161                 Description.propertyName);
2162         return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? ""
2163                 : desc.getValue();
2164     }
2165
2166     @Override
2167     public Set<Switch> getConfiguredNotConnectedSwitches() {
2168         Set<Switch> configuredNotConnectedSwitches = new HashSet<Switch>();
2169         if (this.inventoryService == null) {
2170             log.trace("inventory service not avaiable");
2171             return configuredNotConnectedSwitches;
2172         }
2173
2174         Set<Node> configuredNotConnectedNodes = this.inventoryService.getConfiguredNotConnectedNodes();
2175         if (configuredNotConnectedNodes != null) {
2176             for (Node node : configuredNotConnectedNodes) {
2177                 Switch sw = getSwitchByNode(node);
2178                 if (sw != null) {
2179                     configuredNotConnectedSwitches.add(sw);
2180                 }
2181             }
2182         }
2183         return configuredNotConnectedSwitches;
2184     }
2185
2186 }