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