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