Fix bulk sync in SwitchMananger.
[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         log.debug("updateNode: {} type {} props {} for container {}",
824                 new Object[] { node, type, props, containerName });
825         switch (type) {
826         case ADDED:
827             addNode(node, props);
828             break;
829         case CHANGED:
830             updateNode(node, props);
831             break;
832         case REMOVED:
833             removeNode(node);
834             break;
835         default:
836             break;
837         }
838     }
839
840     @Override
841     public void updateNodeConnector(NodeConnector nodeConnector,
842             UpdateType type, Set<Property> props) {
843         Node node = nodeConnector.getNode();
844         Map<String, Property> propMap = new HashMap<String, Property>();
845
846         log.debug("updateNodeConnector: {} type {} props {} for container {}",
847                 new Object[] { nodeConnector, type, props, containerName });
848
849         if (nodeConnectorProps == null) {
850             return;
851         }
852
853         switch (type) {
854         case ADDED:
855         case CHANGED:
856             if (props != null) {
857                 for (Property prop : props) {
858                     addNodeConnectorProp(nodeConnector, prop);
859                     propMap.put(prop.getName(), prop);
860                 }
861             } else {
862                 addNodeConnectorProp(nodeConnector, null);
863                 addNodeProps(node, null);
864             }
865
866             // check if span is configed
867             addSpanPort(nodeConnector);
868             break;
869         case REMOVED:
870             removeNodeConnectorAllProps(nodeConnector);
871             removeNodeProps(node);
872
873             // clean up span config
874             removeSpanPort(nodeConnector);
875             break;
876         default:
877             break;
878         }
879
880         notifyNodeConnector(nodeConnector, type, propMap);
881     }
882
883     @Override
884     public Set<Node> getNodes() {
885         return (nodeProps != null) ? new HashSet<Node>(nodeProps.keySet())
886                 : null;
887     }
888
889     /*
890      * Returns a copy of a list of properties for a given node
891      *
892      * (non-Javadoc)
893      *
894      * @see
895      * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps
896      * (org.opendaylight.controller.sal.core.Node)
897      */
898     @Override
899     public Map<String, Property> getNodeProps(Node node) {
900         if (isDefaultContainer) {
901             Map<String, Property> rv = null;
902             if (this.nodeProps != null) {
903                 rv = this.nodeProps.get(node);
904                 if (rv != null) {
905                     /* make a copy of it */
906                     rv = new HashMap<String, Property>(rv);
907                 }
908             }
909             return rv;
910         } else {
911             // get it from default container
912             ISwitchManager defaultSwitchManager = (ISwitchManager) ServiceHelper
913                     .getInstance(ISwitchManager.class,
914                             GlobalConstants.DEFAULT.toString(), this);
915             return defaultSwitchManager.getNodeProps(node);
916         }
917     }
918
919     @Override
920     public Property getNodeProp(Node node, String propName) {
921         Map<String, Property> propMap = getNodeProps(node);
922         return (propMap != null) ? propMap.get(propName) : null;
923     }
924
925     @Override
926     public void setNodeProp(Node node, Property prop) {
927         /* Get a copy of the property map */
928         Map<String, Property> propMap = getNodeProps(node);
929         if (propMap == null) {
930             return;
931         }
932
933         propMap.put(prop.getName(), prop);
934         this.nodeProps.put(node, propMap);
935     }
936
937     @Override
938     public Status removeNodeProp(Node node, String propName) {
939         Map<String, Property> propMap = getNodeProps(node);
940         if (propMap != null) {
941             propMap.remove(propName);
942             this.nodeProps.put(node, propMap);
943         }
944         return new Status(StatusCode.SUCCESS, null);
945     }
946
947     @Override
948     public Status removeNodeAllProps(Node node) {
949         this.nodeProps.remove(node);
950         return new Status(StatusCode.SUCCESS, null);
951     }
952
953     @Override
954     public Set<NodeConnector> getUpNodeConnectors(Node node) {
955         if (nodeConnectorProps == null) {
956             return null;
957         }
958
959         Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
960         for (NodeConnector nodeConnector : nodeConnectorProps.keySet()) {
961             if (!nodeConnector.getNode().equals(node)) {
962                 continue;
963             }
964             if (isNodeConnectorEnabled(nodeConnector)) {
965                 nodeConnectorSet.add(nodeConnector);
966             }
967         }
968
969         return nodeConnectorSet;
970     }
971
972     @Override
973     public Set<NodeConnector> getNodeConnectors(Node node) {
974         if (nodeConnectorProps == null) {
975             return null;
976         }
977
978         Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
979         for (NodeConnector nodeConnector : nodeConnectorProps.keySet()) {
980             if (!nodeConnector.getNode().equals(node)) {
981                 continue;
982             }
983             nodeConnectorSet.add(nodeConnector);
984         }
985
986         return nodeConnectorSet;
987     }
988
989     @Override
990     public Set<NodeConnector> getPhysicalNodeConnectors(Node node) {
991         if (nodeConnectorProps == null) {
992             return null;
993         }
994
995         Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
996         for (NodeConnector nodeConnector : nodeConnectorProps.keySet()) {
997             if (!nodeConnector.getNode().equals(node)
998                     || isSpecial(nodeConnector)) {
999                 continue;
1000             }
1001             nodeConnectorSet.add(nodeConnector);
1002         }
1003
1004         return nodeConnectorSet;
1005     }
1006
1007     @Override
1008     public Map<String, Property> getNodeConnectorProps(
1009             NodeConnector nodeConnector) {
1010         if (isDefaultContainer) {
1011             Map<String, Property> rv = null;
1012             if (this.nodeConnectorProps != null) {
1013                 rv = this.nodeConnectorProps.get(nodeConnector);
1014                 if (rv != null) {
1015                     rv = new HashMap<String, Property>(rv);
1016                 }
1017             }
1018             return rv;
1019         } else {
1020             // get it from default container
1021             ISwitchManager defaultSwitchManager = (ISwitchManager) ServiceHelper
1022                     .getInstance(ISwitchManager.class,
1023                             GlobalConstants.DEFAULT.toString(), this);
1024             return defaultSwitchManager.getNodeConnectorProps(nodeConnector);
1025         }
1026     }
1027
1028     @Override
1029     public Property getNodeConnectorProp(NodeConnector nodeConnector,
1030             String propName) {
1031         Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1032         return (propMap != null) ? propMap.get(propName) : null;
1033     }
1034
1035     private byte[] getHardwareMAC() {
1036         Enumeration<NetworkInterface> nis;
1037         try {
1038             nis = NetworkInterface.getNetworkInterfaces();
1039         } catch (SocketException e1) {
1040             log.error("",e1);
1041             return null;
1042         }
1043         byte[] MAC = null;
1044         for (; nis.hasMoreElements();) {
1045             NetworkInterface ni = nis.nextElement();
1046             try {
1047                 MAC = ni.getHardwareAddress();
1048             } catch (SocketException e) {
1049                 log.error("",e);
1050             }
1051             if (MAC != null) {
1052                 return MAC;
1053             }
1054         }
1055         return null;
1056     }
1057
1058     @Override
1059     public byte[] getControllerMAC() {
1060         return MAC;
1061     }
1062
1063     @Override
1064     public boolean isHostRefreshEnabled() {
1065         return hostRefresh;
1066     }
1067
1068     @Override
1069     public int getHostRetryCount() {
1070         return hostRetryCount;
1071     }
1072
1073     @Override
1074     public NodeConnector getNodeConnector(Node node, String nodeConnectorName) {
1075         if (nodeConnectorNames == null) {
1076             return null;
1077         }
1078
1079         Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1080         if (map == null) {
1081             return null;
1082         }
1083
1084         return map.get(nodeConnectorName);
1085     }
1086
1087     /**
1088      * Adds a node connector and its property if any
1089      *
1090      * @param nodeConnector
1091      *            {@link org.opendaylight.controller.sal.core.NodeConnector}
1092      * @param propName
1093      *            name of {@link org.opendaylight.controller.sal.core.Property}
1094      * @return success or failed reason
1095      */
1096     @Override
1097     public Status addNodeConnectorProp(NodeConnector nodeConnector,
1098             Property prop) {
1099         Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1100
1101         if (propMap == null) {
1102             propMap = new HashMap<String, Property>();
1103         }
1104
1105         // Just add the nodeConnector if prop is not available (in a non-default
1106         // container)
1107         if (prop == null) {
1108             nodeConnectorProps.put(nodeConnector, propMap);
1109             return new Status(StatusCode.SUCCESS, null);
1110         }
1111
1112         propMap.put(prop.getName(), prop);
1113         nodeConnectorProps.put(nodeConnector, propMap);
1114
1115         if (prop.getName().equals(Name.NamePropName)) {
1116             if (nodeConnectorNames != null) {
1117                 Node node = nodeConnector.getNode();
1118                 Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1119                 if (map == null) {
1120                     map = new HashMap<String, NodeConnector>();
1121                 }
1122
1123                 map.put(((Name) prop).getValue(), nodeConnector);
1124                 nodeConnectorNames.put(node, map);
1125             }
1126         }
1127
1128         return new Status(StatusCode.SUCCESS, null);
1129     }
1130
1131     /**
1132      * Removes one property of a node connector
1133      *
1134      * @param nodeConnector
1135      *            {@link org.opendaylight.controller.sal.core.NodeConnector}
1136      * @param propName
1137      *            name of {@link org.opendaylight.controller.sal.core.Property}
1138      * @return success or failed reason
1139      */
1140     @Override
1141     public Status removeNodeConnectorProp(NodeConnector nodeConnector,
1142             String propName) {
1143         Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1144
1145         if (propMap == null) {
1146             /* Nothing to remove */
1147             return new Status(StatusCode.SUCCESS, null);
1148         }
1149
1150         propMap.remove(propName);
1151         nodeConnectorProps.put(nodeConnector, propMap);
1152
1153         if (nodeConnectorNames != null) {
1154             Name name = ((Name) getNodeConnectorProp(nodeConnector,
1155                     Name.NamePropName));
1156             if (name != null) {
1157                 Node node = nodeConnector.getNode();
1158                 Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1159                 if (map != null) {
1160                     map.remove(name.getValue());
1161                     nodeConnectorNames.put(node, map);
1162                 }
1163             }
1164         }
1165
1166         return new Status(StatusCode.SUCCESS, null);
1167     }
1168
1169     /**
1170      * Removes all the properties of a node connector
1171      *
1172      * @param nodeConnector
1173      *            {@link org.opendaylight.controller.sal.core.NodeConnector}
1174      * @return success or failed reason
1175      */
1176     @Override
1177     public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) {
1178         if (nodeConnectorNames != null) {
1179             Name name = ((Name) getNodeConnectorProp(nodeConnector,
1180                     Name.NamePropName));
1181             if (name != null) {
1182                 Node node = nodeConnector.getNode();
1183                 Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1184                 if (map != null) {
1185                     map.remove(name.getValue());
1186                     nodeConnectorNames.put(node, map);
1187                 }
1188             }
1189         }
1190         nodeConnectorProps.remove(nodeConnector);
1191
1192         return new Status(StatusCode.SUCCESS, null);
1193     }
1194
1195     /**
1196      * Function called by the dependency manager when all the required
1197      * dependencies are satisfied
1198      *
1199      */
1200     void init(Component c) {
1201         Dictionary<?, ?> props = c.getServiceProperties();
1202         if (props != null) {
1203             this.containerName = (String) props.get("containerName");
1204             log.trace("Running containerName: {}", this.containerName);
1205         } else {
1206             // In the Global instance case the containerName is empty
1207             this.containerName = "";
1208         }
1209         isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT
1210                 .toString());
1211
1212         startUp();
1213     }
1214
1215     /**
1216      * Function called by the dependency manager when at least one dependency
1217      * become unsatisfied or when the component is shutting down because for
1218      * example bundle is being stopped.
1219      *
1220      */
1221     void destroy() {
1222         shutDown();
1223     }
1224
1225     /**
1226      * Function called by dependency manager after "init ()" is called and after
1227      * the services provided by the class are registered in the service registry
1228      *
1229      */
1230     void start() {
1231         // OSGI console
1232         registerWithOSGIConsole();
1233     }
1234
1235     /**
1236      * Function called after registered the service in OSGi service registry.
1237      */
1238     void started() {
1239         // solicit for existing inventories
1240         getInventories();
1241     }
1242
1243     /**
1244      * Function called by the dependency manager before the services exported by
1245      * the component are unregistered, this will be followed by a "destroy ()"
1246      * calls
1247      *
1248      */
1249     void stop() {
1250     }
1251
1252     public void setInventoryService(IInventoryService service) {
1253         log.trace("Got inventory service set request {}", service);
1254         this.inventoryService = service;
1255
1256         // solicit for existing inventories
1257         getInventories();
1258     }
1259
1260     public void unsetInventoryService(IInventoryService service) {
1261         log.trace("Got a service UNset request");
1262         this.inventoryService = null;
1263
1264         // clear existing inventories
1265         clearInventories();
1266     }
1267
1268     public void setSwitchManagerAware(ISwitchManagerAware service) {
1269         log.trace("Got inventory service set request {}", service);
1270         if (this.switchManagerAware != null) {
1271             this.switchManagerAware.add(service);
1272         }
1273
1274         // bulk update for newly joined
1275         switchManagerAwareNotify(service);
1276     }
1277
1278     public void unsetSwitchManagerAware(ISwitchManagerAware service) {
1279         log.trace("Got a service UNset request");
1280         if (this.switchManagerAware != null) {
1281             this.switchManagerAware.remove(service);
1282         }
1283     }
1284
1285     public void setInventoryListener(IInventoryListener service) {
1286         log.trace("Got inventory listener set request {}", service);
1287         if (this.inventoryListeners != null) {
1288             this.inventoryListeners.add(service);
1289         }
1290
1291         // bulk update for newly joined
1292         bulkUpdateService(service);
1293     }
1294
1295     public void unsetInventoryListener(IInventoryListener service) {
1296         log.trace("Got a service UNset request");
1297         if (this.inventoryListeners != null) {
1298             this.inventoryListeners.remove(service);
1299         }
1300     }
1301
1302     public void setSpanAware(ISpanAware service) {
1303         log.trace("Got SpanAware set request {}", service);
1304         if (this.spanAware != null) {
1305             this.spanAware.add(service);
1306         }
1307
1308         // bulk update for newly joined
1309         spanAwareNotify(service);
1310     }
1311
1312     public void unsetSpanAware(ISpanAware service) {
1313         log.trace("Got a service UNset request");
1314         if (this.spanAware != null) {
1315             this.spanAware.remove(service);
1316         }
1317     }
1318
1319     void setClusterContainerService(IClusterContainerServices s) {
1320         log.trace("Cluster Service set");
1321         this.clusterContainerService = s;
1322     }
1323
1324     void unsetClusterContainerService(IClusterContainerServices s) {
1325         if (this.clusterContainerService == s) {
1326             log.trace("Cluster Service removed!");
1327             this.clusterContainerService = null;
1328         }
1329     }
1330
1331     private void getInventories() {
1332         if (inventoryService == null) {
1333             log.trace("inventory service not avaiable");
1334             return;
1335         }
1336
1337         nodeProps = this.inventoryService.getNodeProps();
1338         Set<Node> nodeSet = nodeProps.keySet();
1339         if (nodeSet != null) {
1340             for (Node node : nodeSet) {
1341                 log.debug("getInventories: {} added for container {}",
1342                         new Object[] { node, containerName });
1343                 addNode(node, null);
1344             }
1345         }
1346
1347         nodeConnectorProps = inventoryService.getNodeConnectorProps();
1348     }
1349
1350     private void clearInventories() {
1351         nodeProps.clear();
1352         nodeConnectorProps.clear();
1353         nodeConnectorNames.clear();
1354         spanNodeConnectors.clear();
1355     }
1356
1357     private void notifyNode(Node node, UpdateType type,
1358             Map<String, Property> propMap) {
1359         synchronized (inventoryListeners) {
1360             for (IInventoryListener service : inventoryListeners) {
1361                 service.notifyNode(node, type, propMap);
1362             }
1363         }
1364     }
1365
1366     private void notifyNodeConnector(NodeConnector nodeConnector,
1367             UpdateType type, Map<String, Property> propMap) {
1368         synchronized (inventoryListeners) {
1369             for (IInventoryListener service : inventoryListeners) {
1370                 service.notifyNodeConnector(nodeConnector, type, propMap);
1371             }
1372         }
1373     }
1374
1375     /*
1376      * For those joined late, bring them up-to-date.
1377      */
1378     private void switchManagerAwareNotify(ISwitchManagerAware service) {
1379         for (Subnet sub : subnets.values()) {
1380             service.subnetNotify(sub, true);
1381         }
1382
1383         for (Node node : getNodes()) {
1384             SwitchConfig sc = getSwitchConfig(node.toString());
1385             if ((sc != null) && isDefaultContainer) {
1386                 service.modeChangeNotify(node, sc.isProactive());
1387             }
1388         }
1389     }
1390
1391     private void bulkUpdateService(IInventoryListener service) {
1392         Map<String, Property> propMap;
1393         UpdateType type = UpdateType.ADDED;
1394
1395         for (Node node : getNodes()) {
1396             propMap = nodeProps.get(node);
1397             service.notifyNode(node, type, propMap);
1398         }
1399
1400         for (NodeConnector nodeConnector : nodeConnectorProps.keySet()) {
1401             propMap = nodeConnectorProps.get(nodeConnector);
1402             service.notifyNodeConnector(nodeConnector, type, propMap);
1403         }
1404     }
1405
1406     private void spanAwareNotify(ISpanAware service) {
1407         for (Node node : getNodes()) {
1408             for (SpanConfig conf : getSpanConfigList(node)) {
1409                 service.spanUpdate(node, conf.getPortArrayList(), true);
1410             }
1411         }
1412     }
1413
1414     private void registerWithOSGIConsole() {
1415         BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
1416                 .getBundleContext();
1417         bundleContext.registerService(CommandProvider.class.getName(), this,
1418                 null);
1419     }
1420
1421     @Override
1422     public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) {
1423         if (nodeConnector == null) {
1424             return false;
1425         }
1426
1427         Config config = (Config) getNodeConnectorProp(nodeConnector,
1428                 Config.ConfigPropName);
1429         State state = (State) getNodeConnectorProp(nodeConnector,
1430                 State.StatePropName);
1431         return ((config != null) && (config.getValue() == Config.ADMIN_UP)
1432                 && (state != null) && (state.getValue() == State.EDGE_UP));
1433     }
1434
1435     @Override
1436     public String getHelp() {
1437         StringBuffer help = new StringBuffer();
1438         help.append("---Switch Manager---\n");
1439         help.append("\t pns                    - Print connected nodes\n");
1440         help.append("\t pncs <node id>         - Print node connectors for a given node\n");
1441         help.append("\t pencs <node id>        - Print enabled node connectors for a given node\n");
1442         help.append("\t pdm <node id>          - Print switch ports in device map\n");
1443         help.append("\t snt <node id> <tier>   - Set node tier number\n");
1444         help.append("\t hostRefresh <on/off/?> - Enable/Disable/Query host refresh\n");
1445         help.append("\t hostRetry <count>      - Set host retry count\n");
1446         return help.toString();
1447     }
1448
1449     public void _pns(CommandInterpreter ci) {
1450         ci.println("           Node               Type           MAC            Name      Tier");
1451         if (nodeProps == null) {
1452             return;
1453         }
1454         Set<Node> nodeSet = nodeProps.keySet();
1455         if (nodeSet == null) {
1456             return;
1457         }
1458         for (Node node : nodeSet) {
1459             Description desc = ((Description) getNodeProp(node,
1460                     Description.propertyName));
1461             Tier tier = ((Tier) getNodeProp(node, Tier.TierPropName));
1462             String nodeName = (desc == null) ? "" : desc.getValue();
1463             MacAddress mac = (MacAddress) getNodeProp(node,
1464                     MacAddress.name);
1465             String macAddr = (mac == null) ? "" : HexEncode
1466                     .bytesToHexStringFormat(mac.getMacAddress());
1467             int tierNum = (tier == null) ? 0 : tier.getValue();
1468             ci.println(node + "     " + node.getType() + "     " + macAddr
1469                     + "     " + nodeName + "     " + tierNum);
1470         }
1471         ci.println("Total number of Nodes: " + nodeSet.size());
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
1481         Node node = Node.fromString(st);
1482         if (node == null) {
1483             ci.println("Please enter node id");
1484             return;
1485         }
1486
1487         Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node);
1488         if (nodeConnectorSet == null) {
1489             return;
1490         }
1491         for (NodeConnector nodeConnector : nodeConnectorSet) {
1492             if (nodeConnector == null) {
1493                 continue;
1494             }
1495             ci.println(nodeConnector);
1496         }
1497         ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1498     }
1499
1500     public void _pncs(CommandInterpreter ci) {
1501         String st = ci.nextArgument();
1502         if (st == null) {
1503             ci.println("Please enter node id");
1504             return;
1505         }
1506
1507         Node node = Node.fromString(st);
1508         if (node == null) {
1509             ci.println("Please enter node id");
1510             return;
1511         }
1512
1513         ci.println("          NodeConnector               BandWidth(Gbps)     Admin     State");
1514         Set<NodeConnector> nodeConnectorSet = getNodeConnectors(node);
1515         if (nodeConnectorSet == null) {
1516             return;
1517         }
1518         for (NodeConnector nodeConnector : nodeConnectorSet) {
1519             if (nodeConnector == null) {
1520                 continue;
1521             }
1522             Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1523             Bandwidth bw = (Bandwidth) propMap.get(Bandwidth.BandwidthPropName);
1524             Config config = (Config) propMap.get(Config.ConfigPropName);
1525             State state = (State) propMap.get(State.StatePropName);
1526             String out = nodeConnector + "           ";
1527             out += (bw != null) ? bw.getValue() / Math.pow(10, 9) : "    ";
1528             out += "             ";
1529             out += (config != null) ? config.getValue() : " ";
1530             out += "          ";
1531             out += (state != null) ? state.getValue() : " ";
1532             ci.println(out);
1533         }
1534         ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1535     }
1536
1537     public void _pdm(CommandInterpreter ci) {
1538         String st = ci.nextArgument();
1539         if (st == null) {
1540             ci.println("Please enter node id");
1541             return;
1542         }
1543
1544         Node node = Node.fromString(st);
1545         if (node == null) {
1546             ci.println("Please enter node id");
1547             return;
1548         }
1549
1550         Switch sw = getSwitchByNode(node);
1551
1552         ci.println("          NodeConnector                        Name");
1553         if (sw == null) {
1554             return;
1555         }
1556         Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors();
1557         String nodeConnectorName;
1558         if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
1559             for (NodeConnector nodeConnector : nodeConnectorSet) {
1560                 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1561                 nodeConnectorName = (propMap == null) ? null : ((Name) propMap
1562                         .get(Name.NamePropName)).getValue();
1563                 if (nodeConnectorName != null) {
1564                     Node nd = nodeConnector.getNode();
1565                     if (!nd.equals(node)) {
1566                         log.debug("node not match {} {}", nd, node);
1567                     }
1568                     Map<String, NodeConnector> map = nodeConnectorNames
1569                             .get(node);
1570                     if (map != null) {
1571                         NodeConnector nc = map.get(nodeConnectorName);
1572                         if (nc == null) {
1573                             log.debug("no nodeConnector named {}",
1574                                     nodeConnectorName);
1575                         } else if (!nc.equals(nodeConnector)) {
1576                             log.debug("nodeConnector not match {} {}", nc,
1577                                     nodeConnector);
1578                         }
1579                     }
1580                 }
1581
1582                 ci.println(nodeConnector
1583                         + "            "
1584                         + ((nodeConnectorName == null) ? "" : nodeConnectorName)
1585                         + "(" + nodeConnector.getID() + ")");
1586             }
1587             ci.println("Total number of NodeConnectors: "
1588                     + nodeConnectorSet.size());
1589         }
1590     }
1591
1592     public void _snt(CommandInterpreter ci) {
1593         String st = ci.nextArgument();
1594         if (st == null) {
1595             ci.println("Please enter node id");
1596             return;
1597         }
1598
1599         Node node = Node.fromString(st);
1600         if (node == null) {
1601             ci.println("Please enter node id");
1602             return;
1603         }
1604
1605         st = ci.nextArgument();
1606         if (st == null) {
1607             ci.println("Please enter tier number");
1608             return;
1609         }
1610         Integer tid = Integer.decode(st);
1611         Tier tier = new Tier(tid);
1612         setNodeProp(node, tier);
1613     }
1614
1615     public void _hostRefresh(CommandInterpreter ci) {
1616         String mode = ci.nextArgument();
1617         if (mode == null) {
1618             ci.println("expecting on/off/?");
1619             return;
1620         }
1621         if (mode.toLowerCase().equals("on")) {
1622             hostRefresh = true;
1623         } else if (mode.toLowerCase().equals("off")) {
1624             hostRefresh = false;
1625         } else if (mode.equals("?")) {
1626             if (hostRefresh) {
1627                 ci.println("host refresh is ON");
1628             } else {
1629                 ci.println("host refresh is OFF");
1630             }
1631         } else {
1632             ci.println("expecting on/off/?");
1633         }
1634         return;
1635     }
1636
1637     public void _hostRetry(CommandInterpreter ci) {
1638         String retry = ci.nextArgument();
1639         if (retry == null) {
1640             ci.println("Please enter a valid number. Current retry count is "
1641                     + hostRetryCount);
1642             return;
1643         }
1644         try {
1645             hostRetryCount = Integer.parseInt(retry);
1646         } catch (Exception e) {
1647             ci.println("Please enter a valid number");
1648         }
1649         return;
1650     }
1651
1652     @Override
1653     public byte[] getNodeMAC(Node node) {
1654         MacAddress mac = (MacAddress) this.getNodeProp(node,
1655                 MacAddress.name);
1656         return (mac != null) ? mac.getMacAddress() : null;
1657     }
1658
1659     @Override
1660     public boolean isSpecial(NodeConnector p) {
1661         if (p.getType().equals(NodeConnectorIDType.CONTROLLER)
1662                 || p.getType().equals(NodeConnectorIDType.ALL)
1663                 || p.getType().equals(NodeConnectorIDType.SWSTACK)
1664                 || p.getType().equals(NodeConnectorIDType.HWPATH)) {
1665             return true;
1666         }
1667         return false;
1668     }
1669
1670     /*
1671      * Add span configuration to local cache and notify clients
1672      */
1673     private void addSpanPorts(Node node, List<NodeConnector> nodeConncetors) {
1674         List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1675
1676         for (NodeConnector nodeConnector : nodeConncetors) {
1677             if (!spanNodeConnectors.contains(nodeConnector)) {
1678                 ncLists.add(nodeConnector);
1679             }
1680         }
1681
1682         if (ncLists.size() > 0) {
1683             spanNodeConnectors.addAll(ncLists);
1684             notifySpanPortChange(node, ncLists, true);
1685         }
1686     }
1687
1688     private void addSpanPorts(Node node) {
1689         for (SpanConfig conf : getSpanConfigList(node)) {
1690             addSpanPorts(node, conf.getPortArrayList());
1691         }
1692     }
1693
1694     private void addSpanPort(NodeConnector nodeConncetor) {
1695         List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1696         ncLists.add(nodeConncetor);
1697         addSpanPorts(nodeConncetor.getNode(), ncLists);
1698     }
1699
1700     /*
1701      * Remove span configuration to local cache and notify clients
1702      */
1703     private void removeSpanPorts(Node node, List<NodeConnector> nodeConncetors) {
1704         List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1705
1706         for (NodeConnector nodeConnector : nodeConncetors) {
1707             if (spanNodeConnectors.contains(nodeConnector)) {
1708                 ncLists.add(nodeConnector);
1709             }
1710         }
1711
1712         if (ncLists.size() > 0) {
1713             spanNodeConnectors.removeAll(ncLists);
1714             notifySpanPortChange(node, ncLists, false);
1715         }
1716     }
1717
1718     private void removeSpanPorts(Node node) {
1719         for (SpanConfig conf : getSpanConfigList(node)) {
1720             addSpanPorts(node, conf.getPortArrayList());
1721         }
1722     }
1723
1724     private void removeSpanPort(NodeConnector nodeConncetor) {
1725         List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1726         ncLists.add(nodeConncetor);
1727         removeSpanPorts(nodeConncetor.getNode(), ncLists);
1728     }
1729
1730     private void addNodeProps(Node node, Map<String, Property> propMap) {
1731         if (propMap == null) {
1732             propMap = new HashMap<String, Property>();
1733         }
1734         nodeProps.put(node, propMap);
1735     }
1736
1737     private void removeNodeProps(Node node) {
1738         if (getUpNodeConnectors(node).size() == 0) {
1739             nodeProps.remove(node);
1740         }
1741     }
1742
1743     @Override
1744     public Status saveConfiguration() {
1745         return saveSwitchConfig();
1746     }
1747
1748     /**
1749      * Creates a Name/Tier/Bandwidth Property object based on given property
1750      * name and value. Other property types are not supported yet.
1751      *
1752      * @param propName
1753      *            Name of the Property
1754      * @param propValue
1755      *            Value of the Property
1756      * @return {@link org.opendaylight.controller.sal.core.Property}
1757      */
1758     @Override
1759     public Property createProperty(String propName, String propValue) {
1760         if (propName == null) {
1761             log.debug("propName is null");
1762             return null;
1763         }
1764         if (propValue == null) {
1765             log.debug("propValue is null");
1766             return null;
1767         }
1768
1769         try {
1770             if (propName.equalsIgnoreCase(Description.propertyName)) {
1771                 return new Description(propValue);
1772             } else if (propName.equalsIgnoreCase(Tier.TierPropName)) {
1773                 int tier = Integer.parseInt(propValue);
1774                 return new Tier(tier);
1775             } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) {
1776                 long bw = Long.parseLong(propValue);
1777                 return new Bandwidth(bw);
1778             } else {
1779                 log.debug("Not able to create {} property", propName);
1780             }
1781         } catch (Exception e) {
1782             log.debug("createProperty caught exception {}", e.getMessage());
1783         }
1784
1785         return null;
1786     }
1787
1788     @Override
1789     public String getNodeDescription(Node node) {
1790         // Check first if user configured a name
1791         SwitchConfig config = getSwitchConfig(node.toString());
1792         if (config != null) {
1793             String configuredDesc = config.getNodeDescription();
1794             if (configuredDesc != null && !configuredDesc.isEmpty()) {
1795                 return configuredDesc;
1796             }
1797         }
1798
1799         // No name configured by user, get the node advertised name
1800         Description desc = (Description) getNodeProp(node,
1801                 Description.propertyName);
1802         return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? ""
1803                 : desc.getValue();
1804     }
1805 }