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