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