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