2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.switchmanager.internal;
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;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.concurrent.ConcurrentMap;
30 import java.util.concurrent.CopyOnWriteArrayList;
32 import org.apache.felix.dm.Component;
33 import org.eclipse.osgi.framework.console.CommandInterpreter;
34 import org.eclipse.osgi.framework.console.CommandProvider;
35 import org.opendaylight.controller.clustering.services.CacheConfigException;
36 import org.opendaylight.controller.clustering.services.CacheExistException;
37 import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
38 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
39 import org.opendaylight.controller.clustering.services.IClusterServices;
40 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
41 import org.opendaylight.controller.sal.core.Bandwidth;
42 import org.opendaylight.controller.sal.core.Config;
43 import org.opendaylight.controller.sal.core.ConstructionException;
44 import org.opendaylight.controller.sal.core.Description;
45 import org.opendaylight.controller.sal.core.MacAddress;
46 import org.opendaylight.controller.sal.core.Name;
47 import org.opendaylight.controller.sal.core.Node;
48 import org.opendaylight.controller.sal.core.NodeConnector;
49 import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType;
50 import org.opendaylight.controller.sal.core.Property;
51 import org.opendaylight.controller.sal.core.State;
52 import org.opendaylight.controller.sal.core.Tier;
53 import org.opendaylight.controller.sal.core.UpdateType;
54 import org.opendaylight.controller.sal.inventory.IInventoryService;
55 import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates;
56 import org.opendaylight.controller.sal.utils.GlobalConstants;
57 import org.opendaylight.controller.sal.utils.HexEncode;
58 import org.opendaylight.controller.sal.utils.IObjectReader;
59 import org.opendaylight.controller.sal.utils.ObjectReader;
60 import org.opendaylight.controller.sal.utils.ObjectWriter;
61 import org.opendaylight.controller.sal.utils.ServiceHelper;
62 import org.opendaylight.controller.sal.utils.Status;
63 import org.opendaylight.controller.sal.utils.StatusCode;
64 import org.opendaylight.controller.switchmanager.IInventoryListener;
65 import org.opendaylight.controller.switchmanager.ISpanAware;
66 import org.opendaylight.controller.switchmanager.ISwitchManager;
67 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
68 import org.opendaylight.controller.switchmanager.SpanConfig;
69 import org.opendaylight.controller.switchmanager.Subnet;
70 import org.opendaylight.controller.switchmanager.SubnetConfig;
71 import org.opendaylight.controller.switchmanager.Switch;
72 import org.opendaylight.controller.switchmanager.SwitchConfig;
73 import org.osgi.framework.BundleContext;
74 import org.osgi.framework.FrameworkUtil;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
79 * The class describes SwitchManager which is the central repository of all the
80 * inventory data including nodes, node connectors, properties attached, Layer3
81 * configurations, Span configurations, node configurations, network device
82 * representations viewed by Controller Web applications. One SwitchManager
83 * instance per container of the network. All the node/nodeConnector properties
84 * are maintained in the default container only.
86 public class SwitchManagerImpl implements ISwitchManager,
87 IConfigurationContainerAware, IObjectReader,
88 ICacheUpdateAware<Long, String>, IListenInventoryUpdates,
90 private static Logger log = LoggerFactory
91 .getLogger(SwitchManagerImpl.class);
92 private static String ROOT = GlobalConstants.STARTUPHOME.toString();
93 private static final String SAVE = "Save";
94 private String subnetFileName = null, spanFileName = null,
95 switchConfigFileName = null;
96 private final List<NodeConnector> spanNodeConnectors = new CopyOnWriteArrayList<NodeConnector>();
97 private ConcurrentMap<InetAddress, Subnet> subnets; // set of Subnets keyed by the InetAddress
98 private ConcurrentMap<String, SubnetConfig> subnetsConfigList;
99 private ConcurrentMap<SpanConfig, SpanConfig> spanConfigList;
100 private ConcurrentMap<String, SwitchConfig> nodeConfigList; // manually configured parameters for the node like name and tier
101 private ConcurrentMap<Long, String> configSaveEvent;
102 private ConcurrentMap<Node, Map<String, Property>> nodeProps; // properties are maintained in global container only
103 private ConcurrentMap<NodeConnector, Map<String, Property>> nodeConnectorProps; // properties are maintained in global container only
104 private ConcurrentMap<Node, Map<String, NodeConnector>> nodeConnectorNames;
105 private IInventoryService inventoryService;
106 private final Set<ISwitchManagerAware> switchManagerAware = Collections
107 .synchronizedSet(new HashSet<ISwitchManagerAware>());
108 private final Set<IInventoryListener> inventoryListeners = Collections
109 .synchronizedSet(new HashSet<IInventoryListener>());
110 private final Set<ISpanAware> spanAware = Collections
111 .synchronizedSet(new HashSet<ISpanAware>());
113 private static boolean hostRefresh = true;
114 private int hostRetryCount = 5;
115 private IClusterContainerServices clusterContainerService = null;
116 private String containerName = null;
117 private boolean isDefaultContainer = true;
118 private static final int REPLACE_RETRY = 1;
120 public enum ReasonCode {
121 SUCCESS("Success"), FAILURE("Failure"), INVALID_CONF(
122 "Invalid Configuration"), EXIST("Entry Already Exist"), CONFLICT(
123 "Configuration Conflict with Existing Entry");
125 private final String name;
127 private ReasonCode(String name) {
132 public String toString() {
137 public void notifySubnetChange(Subnet sub, boolean add) {
138 synchronized (switchManagerAware) {
139 for (Object subAware : switchManagerAware) {
141 ((ISwitchManagerAware) subAware).subnetNotify(sub, add);
142 } catch (Exception e) {
143 log.error("Failed to notify Subnet change {}",
150 public void notifySpanPortChange(Node node, List<NodeConnector> ports,
152 synchronized (spanAware) {
153 for (Object sa : spanAware) {
155 ((ISpanAware) sa).spanUpdate(node, ports, add);
156 } catch (Exception e) {
157 log.error("Failed to notify Span Interface change {}",
164 private void notifyModeChange(Node node, boolean proactive) {
165 synchronized (switchManagerAware) {
166 for (ISwitchManagerAware service : switchManagerAware) {
168 service.modeChangeNotify(node, proactive);
169 } catch (Exception e) {
170 log.error("Failed to notify Subnet change {}",
177 public void startUp() {
178 // Initialize configuration file names
179 subnetFileName = ROOT + "subnets_" + this.getContainerName() + ".conf";
180 spanFileName = ROOT + "spanPorts_" + this.getContainerName() + ".conf";
181 switchConfigFileName = ROOT + "switchConfig_" + this.getContainerName()
184 // Instantiate cluster synced variables
189 * Read startup and build database if we have not already gotten the
190 * configurations synced from another node
192 if (subnetsConfigList.isEmpty()) {
193 loadSubnetConfiguration();
195 if (spanConfigList.isEmpty()) {
196 loadSpanConfiguration();
198 if (nodeConfigList.isEmpty()) {
199 loadSwitchConfiguration();
202 MAC = getHardwareMAC();
205 public void shutDown() {
208 @SuppressWarnings("deprecation")
209 private void allocateCaches() {
210 if (this.clusterContainerService == null) {
211 this.nonClusterObjectCreate();
212 log.warn("un-initialized clusterContainerService, can't create cache");
217 clusterContainerService.createCache(
218 "switchmanager.subnetsConfigList",
219 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
220 clusterContainerService.createCache("switchmanager.spanConfigList",
221 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
222 clusterContainerService.createCache("switchmanager.nodeConfigList",
223 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
224 clusterContainerService.createCache("switchmanager.subnets",
225 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
226 clusterContainerService.createCache(
227 "switchmanager.configSaveEvent",
228 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
229 clusterContainerService.createCache("switchmanager.nodeProps",
230 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
231 clusterContainerService.createCache(
232 "switchmanager.nodeConnectorProps",
233 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
234 clusterContainerService.createCache(
235 "switchmanager.nodeConnectorNames",
236 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
237 } catch (CacheConfigException cce) {
238 log.error("\nCache configuration invalid - check cache mode");
239 } catch (CacheExistException ce) {
240 log.error("\nCache already exits - destroy and recreate if needed");
244 @SuppressWarnings({ "unchecked", "deprecation" })
245 private void retrieveCaches() {
246 if (this.clusterContainerService == null) {
247 log.info("un-initialized clusterContainerService, can't create cache");
251 subnetsConfigList = (ConcurrentMap<String, SubnetConfig>) clusterContainerService
252 .getCache("switchmanager.subnetsConfigList");
253 if (subnetsConfigList == null) {
254 log.error("\nFailed to get cache for subnetsConfigList");
257 spanConfigList = (ConcurrentMap<SpanConfig, SpanConfig>) clusterContainerService
258 .getCache("switchmanager.spanConfigList");
259 if (spanConfigList == null) {
260 log.error("\nFailed to get cache for spanConfigList");
263 nodeConfigList = (ConcurrentMap<String, SwitchConfig>) clusterContainerService
264 .getCache("switchmanager.nodeConfigList");
265 if (nodeConfigList == null) {
266 log.error("\nFailed to get cache for nodeConfigList");
269 subnets = (ConcurrentMap<InetAddress, Subnet>) clusterContainerService
270 .getCache("switchmanager.subnets");
271 if (subnets == null) {
272 log.error("\nFailed to get cache for subnets");
275 configSaveEvent = (ConcurrentMap<Long, String>) clusterContainerService
276 .getCache("switchmanager.configSaveEvent");
277 if (configSaveEvent == null) {
278 log.error("\nFailed to get cache for configSaveEvent");
281 nodeProps = (ConcurrentMap<Node, Map<String, Property>>) clusterContainerService
282 .getCache("switchmanager.nodeProps");
283 if (nodeProps == null) {
284 log.error("\nFailed to get cache for nodeProps");
287 nodeConnectorProps = (ConcurrentMap<NodeConnector, Map<String, Property>>) clusterContainerService
288 .getCache("switchmanager.nodeConnectorProps");
289 if (nodeConnectorProps == null) {
290 log.error("\nFailed to get cache for nodeConnectorProps");
293 nodeConnectorNames = (ConcurrentMap<Node, Map<String, NodeConnector>>) clusterContainerService
294 .getCache("switchmanager.nodeConnectorNames");
295 if (nodeConnectorNames == null) {
296 log.error("\nFailed to get cache for nodeConnectorNames");
300 private void nonClusterObjectCreate() {
301 subnetsConfigList = new ConcurrentHashMap<String, SubnetConfig>();
302 spanConfigList = new ConcurrentHashMap<SpanConfig, SpanConfig>();
303 nodeConfigList = new ConcurrentHashMap<String, SwitchConfig>();
304 subnets = new ConcurrentHashMap<InetAddress, Subnet>();
305 configSaveEvent = new ConcurrentHashMap<Long, String>();
306 nodeProps = new ConcurrentHashMap<Node, Map<String, Property>>();
307 nodeConnectorProps = new ConcurrentHashMap<NodeConnector, Map<String, Property>>();
308 nodeConnectorNames = new ConcurrentHashMap<Node, Map<String, NodeConnector>>();
312 public List<SubnetConfig> getSubnetsConfigList() {
313 return new ArrayList<SubnetConfig>(subnetsConfigList.values());
317 public SubnetConfig getSubnetConfig(String subnet) {
318 return subnetsConfigList.get(subnet);
321 private List<SpanConfig> getSpanConfigList(Node node) {
322 List<SpanConfig> confList = new ArrayList<SpanConfig>();
323 String nodeId = node.toString();
324 for (SpanConfig conf : spanConfigList.values()) {
325 if (conf.matchNode(nodeId)) {
332 public List<SwitchConfig> getNodeConfigList() {
333 return new ArrayList<SwitchConfig>(nodeConfigList.values());
337 public SwitchConfig getSwitchConfig(String switchId) {
338 return nodeConfigList.get(switchId);
341 public Switch getSwitchByNode(Node node) {
342 Switch sw = new Switch(node);
344 MacAddress mac = (MacAddress) this.getNodeProp(node,
347 sw.setDataLayerAddress(mac.getMacAddress());
349 Set<NodeConnector> ncSet = getPhysicalNodeConnectors(node);
350 sw.setNodeConnectors(ncSet);
352 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
353 for (NodeConnector nodeConnector : ncSet) {
354 if (spanNodeConnectors.contains(nodeConnector)) {
355 ncList.add(nodeConnector);
358 sw.addSpanPorts(ncList);
364 public List<Switch> getNetworkDevices() {
365 Set<Node> nodeSet = getNodes();
366 List<Switch> swList = new ArrayList<Switch>();
367 if (nodeSet != null) {
368 for (Node node : nodeSet) {
369 swList.add(getSwitchByNode(node));
376 private Status updateConfig(SubnetConfig conf, boolean add) {
378 if(subnetsConfigList.putIfAbsent(conf.getName(), conf) != null) {
379 String msg = "Cluster conflict: Subnet with name " + conf.getName() + "already exists.";
380 return new Status(StatusCode.CONFLICT, msg);
383 subnetsConfigList.remove(conf.getName());
385 return new Status(StatusCode.SUCCESS);
388 private Status updateDatabase(SubnetConfig conf, boolean add) {
390 Subnet subnetCurr = subnets.get(conf.getIPnum());
392 if (subnetCurr == null) {
393 subnet = new Subnet(conf);
395 subnet = subnetCurr.clone();
397 // In case of API3 call we may receive the ports along with the
399 if (!conf.isGlobal()) {
400 Set<NodeConnector> sp = conf.getSubnetNodeConnectors();
401 subnet.addNodeConnectors(sp);
403 boolean result = false;
404 if(subnetCurr == null) {
405 if(subnets.putIfAbsent(conf.getIPnum(), subnet) == null) {
409 result = subnets.replace(conf.getIPnum(), subnetCurr, subnet);
412 String msg = "Cluster conflict: Conflict while adding the subnet " + conf.getIPnum();
413 return new Status(StatusCode.CONFLICT, msg);
415 } else { // This is the deletion of the whole subnet
416 subnets.remove(conf.getIPnum());
418 return new Status(StatusCode.SUCCESS);
421 private Status semanticCheck(SubnetConfig conf) {
422 Subnet newSubnet = new Subnet(conf);
423 Set<InetAddress> IPs = subnets.keySet();
425 return new Status(StatusCode.SUCCESS);
427 for (InetAddress i : IPs) {
428 Subnet existingSubnet = subnets.get(i);
429 if ((existingSubnet != null)
430 && !existingSubnet.isMutualExclusive(newSubnet)) {
431 return new Status(StatusCode.CONFLICT);
434 return new Status(StatusCode.SUCCESS);
437 private Status addRemoveSubnet(SubnetConfig conf, boolean add) {
438 // Valid config check
439 if (!conf.isValidConfig()) {
440 String msg = "Invalid Subnet configuration";
442 return new Status(StatusCode.BADREQUEST, msg);
447 if (subnetsConfigList.containsKey(conf.getName())) {
448 return new Status(StatusCode.CONFLICT,
449 "Same subnet config already exists");
452 Status rc = semanticCheck(conf);
453 if (!rc.isSuccess()) {
459 Status rc = updateDatabase(conf, add);
461 if (rc.isSuccess()) {
462 // Update Configuration
463 rc = updateConfig(conf, add);
464 if(!rc.isSuccess()) {
465 updateDatabase(conf, (!add));
473 * Adds Subnet configured in GUI or API3
476 public Status addSubnet(SubnetConfig conf) {
477 return this.addRemoveSubnet(conf, true);
481 public Status removeSubnet(SubnetConfig conf) {
482 return this.addRemoveSubnet(conf, false);
486 public Status removeSubnet(String name) {
487 SubnetConfig conf = subnetsConfigList.get(name);
489 return new Status(StatusCode.SUCCESS, "Subnet not present");
491 return this.addRemoveSubnet(conf, false);
495 public Status addPortsToSubnet(String name, String switchPorts) {
496 SubnetConfig confCurr = subnetsConfigList.get(name);
497 if (confCurr == null) {
498 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
500 if (!confCurr.isValidSwitchPort(switchPorts)) {
501 return new Status(StatusCode.BADREQUEST, "Invalid switchports");
504 Subnet subCurr = subnets.get(confCurr.getIPnum());
505 if (subCurr == null) {
506 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPnum());
507 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
511 Subnet sub = subCurr.clone();
512 Set<NodeConnector> sp = confCurr.getNodeConnectors(switchPorts);
513 sub.addNodeConnectors(sp);
514 boolean subnetsReplace = subnets.replace(confCurr.getIPnum(), subCurr, sub);
515 if (!subnetsReplace) {
516 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
517 return new Status(StatusCode.CONFLICT, msg);
520 // Update Configuration
521 SubnetConfig conf = confCurr.clone();
522 conf.addNodeConnectors(switchPorts);
523 boolean result = subnetsConfigList.replace(name, confCurr, conf);
525 // TODO: recovery using Transactionality
526 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
527 return new Status(StatusCode.CONFLICT, msg);
530 return new Status(StatusCode.SUCCESS);
534 public Status removePortsFromSubnet(String name, String switchPorts) {
535 SubnetConfig confCurr = subnetsConfigList.get(name);
536 if (confCurr == null) {
537 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
540 Subnet subCurr = subnets.get(confCurr.getIPnum());
541 if (subCurr == null) {
542 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPnum());
543 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
547 Subnet sub = subCurr.clone();
548 Set<NodeConnector> sp = confCurr.getNodeConnectors(switchPorts);
549 sub.deleteNodeConnectors(sp);
550 boolean subnetsReplace = subnets.replace(confCurr.getIPnum(), subCurr, sub);
551 if (!subnetsReplace) {
552 String msg = "Cluster conflict: Conflict while removing ports from the subnet " + name;
553 return new Status(StatusCode.CONFLICT, msg);
556 // Update Configuration
557 SubnetConfig conf = confCurr.clone();
558 conf.removeNodeConnectors(switchPorts);
559 boolean result = subnetsConfigList.replace(name, confCurr, conf);
561 // TODO: recovery using Transactionality
562 String msg = "Cluster conflict: Conflict while removing ports from " + conf;
563 return new Status(StatusCode.CONFLICT, msg);
566 return new Status(StatusCode.SUCCESS);
569 public String getContainerName() {
570 if (containerName == null) {
571 return GlobalConstants.DEFAULT.toString();
573 return containerName;
577 public Subnet getSubnetByNetworkAddress(InetAddress networkAddress) {
579 Set<InetAddress> indices = subnets.keySet();
580 for (InetAddress i : indices) {
581 sub = subnets.get(i);
582 if (sub.isSubnetOf(networkAddress)) {
590 public Object readObject(ObjectInputStream ois)
591 throws FileNotFoundException, IOException, ClassNotFoundException {
592 // Perform the class deserialization locally, from inside the package
593 // where the class is defined
594 return ois.readObject();
597 @SuppressWarnings("unchecked")
598 private void loadSubnetConfiguration() {
599 ObjectReader objReader = new ObjectReader();
600 ConcurrentMap<String, SubnetConfig> confList = (ConcurrentMap<String, SubnetConfig>) objReader
601 .read(this, subnetFileName);
603 if (confList == null) {
607 for (SubnetConfig conf : confList.values()) {
612 @SuppressWarnings("unchecked")
613 private void loadSpanConfiguration() {
614 ObjectReader objReader = new ObjectReader();
615 ConcurrentMap<Integer, SpanConfig> confList = (ConcurrentMap<Integer, SpanConfig>) objReader
616 .read(this, spanFileName);
618 if (confList == null) {
622 for (SpanConfig conf : confList.values()) {
627 @SuppressWarnings("unchecked")
628 private void loadSwitchConfiguration() {
629 ObjectReader objReader = new ObjectReader();
630 ConcurrentMap<String, SwitchConfig> confList = (ConcurrentMap<String, SwitchConfig>) objReader
631 .read(this, switchConfigFileName);
633 if (confList == null) {
637 for (SwitchConfig conf : confList.values()) {
638 updateSwitchConfig(conf);
643 public void updateSwitchConfig(SwitchConfig cfgObject) {
644 // update default container only
645 if (!isDefaultContainer) {
649 SwitchConfig sc = nodeConfigList.get(cfgObject.getNodeId());
651 if (nodeConfigList.putIfAbsent(cfgObject.getNodeId(), cfgObject) != null) {
655 if (!nodeConfigList.replace(cfgObject.getNodeId(), sc, cfgObject)) {
660 boolean modeChange = false;
662 if ((sc == null) || !cfgObject.getMode().equals(sc.getMode())) {
667 String nodeId = cfgObject.getNodeId();
668 Node node = Node.fromString(nodeId);
669 Map<String, Property> propMapCurr = nodeProps.get(node);
670 Map<String, Property> propMap = new HashMap<String, Property>();
671 if (propMapCurr != null) {
672 for (String s : propMapCurr.keySet()) {
673 propMap.put(s, propMapCurr.get(s).clone());
676 Property desc = new Description(cfgObject.getNodeDescription());
677 propMap.put(desc.getName(), desc);
678 Property tier = new Tier(Integer.parseInt(cfgObject.getTier()));
679 propMap.put(tier.getName(), tier);
681 if (propMapCurr == null) {
682 if (nodeProps.putIfAbsent(node, propMap) != null) {
683 // TODO rollback using Transactionality
687 if (!nodeProps.replace(node, propMapCurr, propMap)) {
688 // TODO rollback using Transactionality
693 log.info("Set Node {}'s Mode to {}", nodeId, cfgObject.getMode());
696 notifyModeChange(node, cfgObject.isProactive());
698 } catch (Exception e) {
699 log.debug("updateSwitchConfig: {}", e.getMessage());
704 public Status saveSwitchConfig() {
705 // Publish the save config event to the cluster nodes
706 configSaveEvent.put(new Date().getTime(), SAVE);
707 return saveSwitchConfigInternal();
710 public Status saveSwitchConfigInternal() {
711 Status retS = null, retP = null;
712 ObjectWriter objWriter = new ObjectWriter();
714 retS = objWriter.write(new ConcurrentHashMap<String, SubnetConfig>(
715 subnetsConfigList), subnetFileName);
716 retP = objWriter.write(new ConcurrentHashMap<SpanConfig, SpanConfig>(
717 spanConfigList), spanFileName);
718 retS = objWriter.write(new ConcurrentHashMap<String, SwitchConfig>(
719 nodeConfigList), switchConfigFileName);
721 if (retS.equals(retP)) {
722 if (retS.isSuccess()) {
725 return new Status(StatusCode.INTERNALERROR, "Save failed");
728 return new Status(StatusCode.INTERNALERROR, "Partial save failure");
733 public List<SpanConfig> getSpanConfigList() {
734 return new ArrayList<SpanConfig>(spanConfigList.values());
738 public Status addSpanConfig(SpanConfig conf) {
739 // Valid config check
740 if (!conf.isValidConfig()) {
741 String msg = "Invalid Span configuration";
743 return new Status(StatusCode.BADREQUEST, msg);
747 if (spanConfigList.containsKey(conf)) {
748 return new Status(StatusCode.CONFLICT, "Same span config exists");
751 // Update configuration
752 if (spanConfigList.putIfAbsent(conf, conf) == null) {
753 // Update database and notify clients
754 addSpanPorts(conf.getNode(), conf.getPortArrayList());
757 return new Status(StatusCode.SUCCESS);
761 public Status removeSpanConfig(SpanConfig conf) {
762 removeSpanPorts(conf.getNode(), conf.getPortArrayList());
764 // Update configuration
765 spanConfigList.remove(conf);
767 return new Status(StatusCode.SUCCESS);
771 public List<NodeConnector> getSpanPorts(Node node) {
772 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
774 for (NodeConnector nodeConnector : spanNodeConnectors) {
775 if (nodeConnector.getNode().equals(node)) {
776 ncList.add(nodeConnector);
783 public void entryCreated(Long key, String cacheName, boolean local) {
787 public void entryUpdated(Long key, String new_value, String cacheName,
788 boolean originLocal) {
789 saveSwitchConfigInternal();
793 public void entryDeleted(Long key, String cacheName, boolean originLocal) {
796 private void addNode(Node node, Set<Property> props) {
797 log.trace("{} added, props: {}", node, props);
798 if (nodeProps == null) {
802 Map<String, Property> propMapCurr = nodeProps.get(node);
803 Map<String, Property> propMap = new HashMap<String, Property>();
804 if (propMapCurr != null) {
805 for (String s : propMapCurr.keySet()) {
806 propMap.put(s, propMapCurr.get(s).clone());
810 // copy node properties from plugin
812 for (Property prop : props) {
813 propMap.put(prop.getName(), prop);
817 // copy node properties from config
818 boolean proactiveForwarding = false;
819 if (nodeConfigList != null) {
820 String nodeId = node.toString();
821 for (SwitchConfig conf : nodeConfigList.values()) {
822 if (conf.getNodeId().equals(nodeId)) {
823 Property description = new Description(conf.getNodeDescription());
824 propMap.put(description.getName(), description);
825 Property tier = new Tier(Integer.parseInt(conf.getTier()));
826 propMap.put(tier.getName(), tier);
827 proactiveForwarding = conf.isProactive();
833 boolean result = false;
834 if (propMapCurr == null) {
835 if (nodeProps.putIfAbsent(node, propMap) == null) {
839 result = nodeProps.replace(node, propMapCurr, propMap);
844 "Cluster conflict: Conflict while adding the node properties. Node: {} Properties: {}",
845 node.getID(), props);
846 addNodeProps(node, propMap);
849 // check if span ports are configed
852 // notify node listeners
853 notifyNode(node, UpdateType.ADDED, propMap);
855 // notify proactive mode forwarding
856 if (proactiveForwarding) {
857 notifyModeChange(node, true);
861 private void removeNode(Node node) {
862 log.trace("{} removed", node);
863 if (nodeProps == null) {
866 nodeProps.remove(node);
868 // check if span ports need to be cleaned up
869 removeSpanPorts(node);
871 /* notify node listeners */
872 notifyNode(node, UpdateType.REMOVED, null);
875 private void updateNode(Node node, Set<Property> props) {
876 log.trace("{} updated, props: {}", node, props);
877 if (nodeProps == null || !nodeProps.containsKey(node) ||
878 props == null || props.isEmpty()) {
882 Map<String, Property> propMapCurr = nodeProps.get(node);
883 Map<String, Property> propMap = new HashMap<String, Property>();
884 if (propMapCurr != null) {
885 for (String s : propMapCurr.keySet()) {
886 propMap.put(s, propMapCurr.get(s).clone());
890 // copy node properties from plugin
892 for (Property prop : props) {
893 propMap.put(prop.getName(), prop);
897 if (propMapCurr == null) {
898 if (nodeProps.putIfAbsent(node, propMap) != null) {
899 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
900 node.getID(), props);
901 addNodeProps(node, propMap);
904 if (!nodeProps.replace(node, propMapCurr, propMap)) {
905 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
906 node.getID(), props);
907 addNodeProps(node, propMap);
911 /* notify node listeners */
912 notifyNode(node, UpdateType.CHANGED, propMap);
916 public void updateNode(Node node, UpdateType type, Set<Property> props) {
917 log.debug("updateNode: {} type {} props {} for container {}",
918 new Object[] { node, type, props, containerName });
921 addNode(node, props);
924 updateNode(node, props);
935 public void updateNodeConnector(NodeConnector nodeConnector,
936 UpdateType type, Set<Property> props) {
937 Node node = nodeConnector.getNode();
938 Map<String, Property> propMap = new HashMap<String, Property>();
940 log.debug("updateNodeConnector: {} type {} props {} for container {}",
941 new Object[] { nodeConnector, type, props, containerName });
943 if (nodeConnectorProps == null) {
951 for (Property prop : props) {
952 addNodeConnectorProp(nodeConnector, prop);
953 propMap.put(prop.getName(), prop);
956 addNodeConnectorProp(nodeConnector, null);
957 addNodeProps(node, null);
960 addSpanPort(nodeConnector);
963 removeNodeConnectorAllProps(nodeConnector);
964 removeNodeProps(node);
966 // clean up span config
967 removeSpanPort(nodeConnector);
973 notifyNodeConnector(nodeConnector, type, propMap);
977 public Set<Node> getNodes() {
978 return (nodeProps != null) ? new HashSet<Node>(nodeProps.keySet())
983 * Returns a copy of a list of properties for a given node
988 * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps
989 * (org.opendaylight.controller.sal.core.Node)
992 public Map<String, Property> getNodeProps(Node node) {
993 if (isDefaultContainer) {
994 Map<String, Property> rv = null;
995 if (this.nodeProps != null) {
996 rv = this.nodeProps.get(node);
998 /* make a copy of it */
999 rv = new HashMap<String, Property>(rv);
1004 // get it from default container
1005 ISwitchManager defaultSwitchManager = (ISwitchManager) ServiceHelper
1006 .getInstance(ISwitchManager.class,
1007 GlobalConstants.DEFAULT.toString(), this);
1008 return defaultSwitchManager.getNodeProps(node);
1013 public Property getNodeProp(Node node, String propName) {
1014 Map<String, Property> propMap = getNodeProps(node);
1015 return (propMap != null) ? propMap.get(propName) : null;
1019 public void setNodeProp(Node node, Property prop) {
1021 for (int i = 0; i <= REPLACE_RETRY; i++) {
1022 /* Get a copy of the property map */
1023 Map<String, Property> propMapCurr = getNodeProps(node);
1024 if (propMapCurr == null) {
1028 Map<String, Property> propMap = new HashMap<String, Property>();
1029 for (String s : propMapCurr.keySet()) {
1030 propMap.put(s, propMapCurr.get(s).clone());
1033 propMap.put(prop.getName(), prop);
1035 if (nodeProps.replace(node, propMapCurr, propMap)) {
1038 if (!propMapCurr.get(prop.getName()).equals(nodeProps.get(node).get(prop.getName()))) {
1039 log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1043 log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1047 public Status removeNodeProp(Node node, String propName) {
1048 for (int i = 0; i <= REPLACE_RETRY; i++) {
1049 Map<String, Property> propMapCurr = getNodeProps(node);
1050 if (propMapCurr != null) {
1051 if (!propMapCurr.containsKey(propName)) {
1052 return new Status(StatusCode.SUCCESS);
1054 Map<String, Property> propMap = new HashMap<String, Property>();
1055 for (String s : propMapCurr.keySet()) {
1056 propMap.put(s, propMapCurr.get(s).clone());
1059 propMap.remove(propName);
1060 if (nodeProps.replace(node, propMapCurr, propMap)) {
1061 return new Status(StatusCode.SUCCESS);
1063 if (!propMapCurr.get(propName).equals(nodeProps.get(node).get(propName))) {
1064 String msg = "Cluster conflict: Unable to remove property " + propName + " for node "
1066 return new Status(StatusCode.CONFLICT, msg);
1070 return new Status(StatusCode.SUCCESS);
1073 String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID();
1074 return new Status(StatusCode.CONFLICT, msg);
1078 public Status removeNodeAllProps(Node node) {
1079 this.nodeProps.remove(node);
1080 return new Status(StatusCode.SUCCESS);
1084 public Set<NodeConnector> getUpNodeConnectors(Node node) {
1085 if (nodeConnectorProps == null) {
1089 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1090 for (NodeConnector nodeConnector : nodeConnectorProps.keySet()) {
1091 if (!nodeConnector.getNode().equals(node)) {
1094 if (isNodeConnectorEnabled(nodeConnector)) {
1095 nodeConnectorSet.add(nodeConnector);
1099 return nodeConnectorSet;
1103 public Set<NodeConnector> getNodeConnectors(Node node) {
1104 if (nodeConnectorProps == null) {
1108 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1109 for (NodeConnector nodeConnector : nodeConnectorProps.keySet()) {
1110 if (!nodeConnector.getNode().equals(node)) {
1113 nodeConnectorSet.add(nodeConnector);
1116 return nodeConnectorSet;
1120 public Set<NodeConnector> getPhysicalNodeConnectors(Node node) {
1121 if (nodeConnectorProps == null) {
1125 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1126 for (NodeConnector nodeConnector : nodeConnectorProps.keySet()) {
1127 if (!nodeConnector.getNode().equals(node)
1128 || isSpecial(nodeConnector)) {
1131 nodeConnectorSet.add(nodeConnector);
1134 return nodeConnectorSet;
1138 public Map<String, Property> getNodeConnectorProps(
1139 NodeConnector nodeConnector) {
1140 if (isDefaultContainer) {
1141 Map<String, Property> rv = null;
1142 if (this.nodeConnectorProps != null) {
1143 rv = this.nodeConnectorProps.get(nodeConnector);
1145 rv = new HashMap<String, Property>(rv);
1150 // get it from default container
1151 ISwitchManager defaultSwitchManager = (ISwitchManager) ServiceHelper
1152 .getInstance(ISwitchManager.class,
1153 GlobalConstants.DEFAULT.toString(), this);
1154 return defaultSwitchManager.getNodeConnectorProps(nodeConnector);
1159 public Property getNodeConnectorProp(NodeConnector nodeConnector,
1161 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1162 return (propMap != null) ? propMap.get(propName) : null;
1165 private byte[] getHardwareMAC() {
1166 Enumeration<NetworkInterface> nis;
1168 nis = NetworkInterface.getNetworkInterfaces();
1169 } catch (SocketException e1) {
1174 for (; nis.hasMoreElements();) {
1175 NetworkInterface ni = nis.nextElement();
1177 MAC = ni.getHardwareAddress();
1178 } catch (SocketException e) {
1189 public byte[] getControllerMAC() {
1194 public boolean isHostRefreshEnabled() {
1199 public int getHostRetryCount() {
1200 return hostRetryCount;
1204 public NodeConnector getNodeConnector(Node node, String nodeConnectorName) {
1205 if (nodeConnectorNames == null) {
1209 Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1214 return map.get(nodeConnectorName);
1218 * Adds a node connector and its property if any
1220 * @param nodeConnector
1221 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1223 * name of {@link org.opendaylight.controller.sal.core.Property}
1224 * @return success or failed reason
1227 public Status addNodeConnectorProp(NodeConnector nodeConnector,
1229 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1230 Map<String, Property> propMap = new HashMap<String, Property>();
1232 if (propMapCurr != null) {
1233 for (String s : propMapCurr.keySet()) {
1234 propMap.put(s, propMapCurr.get(s).clone());
1238 String msg = "Cluster conflict: Unable to add NodeConnector Property.";
1239 // Just add the nodeConnector if prop is not available (in a non-default
1242 if (propMapCurr == null) {
1243 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1244 return new Status(StatusCode.CONFLICT, msg);
1247 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1248 return new Status(StatusCode.CONFLICT, msg);
1251 return new Status(StatusCode.SUCCESS);
1254 propMap.put(prop.getName(), prop);
1255 if (propMapCurr == null) {
1256 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1257 return new Status(StatusCode.CONFLICT, msg);
1260 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1261 return new Status(StatusCode.CONFLICT, msg);
1265 if (prop.getName().equals(Name.NamePropName)) {
1266 if (nodeConnectorNames != null) {
1267 Node node = nodeConnector.getNode();
1268 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1269 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1270 if (mapCurr != null) {
1271 for (String s : mapCurr.keySet()) {
1273 map.put(s, new NodeConnector(mapCurr.get(s)));
1274 } catch (ConstructionException e) {
1275 e.printStackTrace();
1280 map.put(((Name) prop).getValue(), nodeConnector);
1281 if (mapCurr == null) {
1282 if (nodeConnectorNames.putIfAbsent(node, map) != null) {
1283 // TODO: recovery using Transactionality
1284 return new Status(StatusCode.CONFLICT, msg);
1287 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1288 // TODO: recovery using Transactionality
1289 return new Status(StatusCode.CONFLICT, msg);
1295 return new Status(StatusCode.SUCCESS);
1299 * Removes one property of a node connector
1301 * @param nodeConnector
1302 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1304 * name of {@link org.opendaylight.controller.sal.core.Property}
1305 * @return success or failed reason
1308 public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) {
1309 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1311 if (propMapCurr == null) {
1312 /* Nothing to remove */
1313 return new Status(StatusCode.SUCCESS);
1316 Map<String, Property> propMap = new HashMap<String, Property>();
1318 for (String s : propMapCurr.keySet()) {
1319 propMap.put(s, propMapCurr.get(s).clone());
1322 propMap.remove(propName);
1323 boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap);
1324 String msg = "Cluster conflict: Unable to remove NodeConnector property.";
1326 return new Status(StatusCode.CONFLICT, msg);
1329 if (propName.equals(Name.NamePropName)) {
1330 if (nodeConnectorNames != null) {
1331 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1333 Node node = nodeConnector.getNode();
1334 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1335 if (mapCurr != null) {
1336 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1337 for (String s : mapCurr.keySet()) {
1339 map.put(s, new NodeConnector(mapCurr.get(s)));
1340 } catch (ConstructionException e) {
1341 e.printStackTrace();
1344 map.remove(name.getValue());
1345 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1346 // TODO: recovery using Transactionality
1347 return new Status(StatusCode.CONFLICT, msg);
1354 return new Status(StatusCode.SUCCESS);
1358 * Removes all the properties of a node connector
1360 * @param nodeConnector
1361 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1362 * @return success or failed reason
1365 public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) {
1366 if (nodeConnectorNames != null) {
1367 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1369 Node node = nodeConnector.getNode();
1370 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1371 if (mapCurr != null) {
1372 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1373 for (String s : mapCurr.keySet()) {
1375 map.put(s, new NodeConnector(mapCurr.get(s)));
1376 } catch (ConstructionException e) {
1377 e.printStackTrace();
1380 map.remove(name.getValue());
1381 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1382 log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.",
1383 nodeConnector.getID());
1389 nodeConnectorProps.remove(nodeConnector);
1391 return new Status(StatusCode.SUCCESS);
1395 * Function called by the dependency manager when all the required
1396 * dependencies are satisfied
1399 void init(Component c) {
1400 Dictionary<?, ?> props = c.getServiceProperties();
1401 if (props != null) {
1402 this.containerName = (String) props.get("containerName");
1403 log.trace("Running containerName: {}", this.containerName);
1405 // In the Global instance case the containerName is empty
1406 this.containerName = "";
1408 isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT
1415 * Function called by the dependency manager when at least one dependency
1416 * become unsatisfied or when the component is shutting down because for
1417 * example bundle is being stopped.
1425 * Function called by dependency manager after "init ()" is called and after
1426 * the services provided by the class are registered in the service registry
1431 registerWithOSGIConsole();
1435 * Function called after registered the service in OSGi service registry.
1438 // solicit for existing inventories
1443 * Function called by the dependency manager before the services exported by
1444 * the component are unregistered, this will be followed by a "destroy ()"
1451 public void setInventoryService(IInventoryService service) {
1452 log.trace("Got inventory service set request {}", service);
1453 this.inventoryService = service;
1455 // solicit for existing inventories
1459 public void unsetInventoryService(IInventoryService service) {
1460 log.trace("Got a service UNset request");
1461 this.inventoryService = null;
1463 // clear existing inventories
1467 public void setSwitchManagerAware(ISwitchManagerAware service) {
1468 log.trace("Got inventory service set request {}", service);
1469 if (this.switchManagerAware != null) {
1470 this.switchManagerAware.add(service);
1473 // bulk update for newly joined
1474 switchManagerAwareNotify(service);
1477 public void unsetSwitchManagerAware(ISwitchManagerAware service) {
1478 log.trace("Got a service UNset request");
1479 if (this.switchManagerAware != null) {
1480 this.switchManagerAware.remove(service);
1484 public void setInventoryListener(IInventoryListener service) {
1485 log.trace("Got inventory listener set request {}", service);
1486 if (this.inventoryListeners != null) {
1487 this.inventoryListeners.add(service);
1490 // bulk update for newly joined
1491 bulkUpdateService(service);
1494 public void unsetInventoryListener(IInventoryListener service) {
1495 log.trace("Got a service UNset request");
1496 if (this.inventoryListeners != null) {
1497 this.inventoryListeners.remove(service);
1501 public void setSpanAware(ISpanAware service) {
1502 log.trace("Got SpanAware set request {}", service);
1503 if (this.spanAware != null) {
1504 this.spanAware.add(service);
1507 // bulk update for newly joined
1508 spanAwareNotify(service);
1511 public void unsetSpanAware(ISpanAware service) {
1512 log.trace("Got a service UNset request");
1513 if (this.spanAware != null) {
1514 this.spanAware.remove(service);
1518 void setClusterContainerService(IClusterContainerServices s) {
1519 log.trace("Cluster Service set");
1520 this.clusterContainerService = s;
1523 void unsetClusterContainerService(IClusterContainerServices s) {
1524 if (this.clusterContainerService == s) {
1525 log.trace("Cluster Service removed!");
1526 this.clusterContainerService = null;
1530 private void getInventories() {
1531 if (inventoryService == null) {
1532 log.trace("inventory service not avaiable");
1536 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
1537 for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) {
1538 Node node = entry.getKey();
1539 log.debug("getInventories: {} added for container {}", new Object[] { node, containerName });
1540 Map<String, Property> propMap = entry.getValue();
1541 Set<Property> props = new HashSet<Property>();
1542 for (Property property : propMap.values()) {
1543 props.add(property);
1545 addNode(node, props);
1548 Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps();
1549 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) {
1550 Map<String, Property> propMap = entry.getValue();
1551 for (Property property : propMap.values()) {
1552 addNodeConnectorProp(entry.getKey(), property);
1557 private void clearInventories() {
1559 nodeConnectorProps.clear();
1560 nodeConnectorNames.clear();
1561 spanNodeConnectors.clear();
1564 private void notifyNode(Node node, UpdateType type,
1565 Map<String, Property> propMap) {
1566 synchronized (inventoryListeners) {
1567 for (IInventoryListener service : inventoryListeners) {
1568 service.notifyNode(node, type, propMap);
1573 private void notifyNodeConnector(NodeConnector nodeConnector,
1574 UpdateType type, Map<String, Property> propMap) {
1575 synchronized (inventoryListeners) {
1576 for (IInventoryListener service : inventoryListeners) {
1577 service.notifyNodeConnector(nodeConnector, type, propMap);
1583 * For those joined late, bring them up-to-date.
1585 private void switchManagerAwareNotify(ISwitchManagerAware service) {
1586 for (Subnet sub : subnets.values()) {
1587 service.subnetNotify(sub, true);
1590 for (Node node : getNodes()) {
1591 SwitchConfig sc = getSwitchConfig(node.toString());
1592 if ((sc != null) && isDefaultContainer) {
1593 service.modeChangeNotify(node, sc.isProactive());
1598 private void bulkUpdateService(IInventoryListener service) {
1599 Map<String, Property> propMap;
1600 UpdateType type = UpdateType.ADDED;
1602 for (Node node : getNodes()) {
1603 propMap = nodeProps.get(node);
1604 service.notifyNode(node, type, propMap);
1607 for (NodeConnector nodeConnector : nodeConnectorProps.keySet()) {
1608 propMap = nodeConnectorProps.get(nodeConnector);
1609 service.notifyNodeConnector(nodeConnector, type, propMap);
1613 private void spanAwareNotify(ISpanAware service) {
1614 for (Node node : getNodes()) {
1615 for (SpanConfig conf : getSpanConfigList(node)) {
1616 service.spanUpdate(node, conf.getPortArrayList(), true);
1621 private void registerWithOSGIConsole() {
1622 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
1623 .getBundleContext();
1624 bundleContext.registerService(CommandProvider.class.getName(), this,
1629 public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) {
1630 if (nodeConnector == null) {
1634 Config config = (Config) getNodeConnectorProp(nodeConnector,
1635 Config.ConfigPropName);
1636 State state = (State) getNodeConnectorProp(nodeConnector,
1637 State.StatePropName);
1638 return ((config != null) && (config.getValue() == Config.ADMIN_UP)
1639 && (state != null) && (state.getValue() == State.EDGE_UP));
1643 public String getHelp() {
1644 StringBuffer help = new StringBuffer();
1645 help.append("---Switch Manager---\n");
1646 help.append("\t pns - Print connected nodes\n");
1647 help.append("\t pncs <node id> - Print node connectors for a given node\n");
1648 help.append("\t pencs <node id> - Print enabled node connectors for a given node\n");
1649 help.append("\t pdm <node id> - Print switch ports in device map\n");
1650 help.append("\t snt <node id> <tier> - Set node tier number\n");
1651 help.append("\t hostRefresh <on/off/?> - Enable/Disable/Query host refresh\n");
1652 help.append("\t hostRetry <count> - Set host retry count\n");
1653 return help.toString();
1656 public void _pns(CommandInterpreter ci) {
1657 ci.println(" Node Type MAC Name Tier");
1658 if (nodeProps == null) {
1661 Set<Node> nodeSet = nodeProps.keySet();
1662 if (nodeSet == null) {
1665 List<String> nodeArray = new ArrayList<String>();
1666 for (Node node : nodeSet) {
1667 nodeArray.add(node.toString());
1669 Collections.sort(nodeArray);
1670 for (String str: nodeArray) {
1671 Node node = Node.fromString(str);
1672 Description desc = ((Description) getNodeProp(node,
1673 Description.propertyName));
1674 Tier tier = ((Tier) getNodeProp(node, Tier.TierPropName));
1675 String nodeName = (desc == null) ? "" : desc.getValue();
1676 MacAddress mac = (MacAddress) getNodeProp(node,
1678 String macAddr = (mac == null) ? "" : HexEncode
1679 .bytesToHexStringFormat(mac.getMacAddress());
1680 int tierNum = (tier == null) ? 0 : tier.getValue();
1681 ci.println(node + " " + node.getType() + " " + macAddr
1682 + " " + nodeName + " " + tierNum);
1684 ci.println("Total number of Nodes: " + nodeSet.size());
1687 public void _pencs(CommandInterpreter ci) {
1688 String st = ci.nextArgument();
1690 ci.println("Please enter node id");
1694 Node node = Node.fromString(st);
1696 ci.println("Please enter node id");
1700 Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node);
1701 if (nodeConnectorSet == null) {
1704 for (NodeConnector nodeConnector : nodeConnectorSet) {
1705 if (nodeConnector == null) {
1708 ci.println(nodeConnector);
1710 ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1713 public void _pncs(CommandInterpreter ci) {
1714 String st = ci.nextArgument();
1716 ci.println("Please enter node id");
1720 Node node = Node.fromString(st);
1722 ci.println("Please enter node id");
1726 ci.println(" NodeConnector BandWidth(Gbps) Admin State");
1727 Set<NodeConnector> nodeConnectorSet = getNodeConnectors(node);
1728 if (nodeConnectorSet == null) {
1731 for (NodeConnector nodeConnector : nodeConnectorSet) {
1732 if (nodeConnector == null) {
1735 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1736 Bandwidth bw = (Bandwidth) propMap.get(Bandwidth.BandwidthPropName);
1737 Config config = (Config) propMap.get(Config.ConfigPropName);
1738 State state = (State) propMap.get(State.StatePropName);
1739 String out = nodeConnector + " ";
1740 out += (bw != null) ? bw.getValue() / Math.pow(10, 9) : " ";
1742 out += (config != null) ? config.getValue() : " ";
1744 out += (state != null) ? state.getValue() : " ";
1747 ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1750 public void _pdm(CommandInterpreter ci) {
1751 String st = ci.nextArgument();
1753 ci.println("Please enter node id");
1757 Node node = Node.fromString(st);
1759 ci.println("Please enter node id");
1763 Switch sw = getSwitchByNode(node);
1765 ci.println(" NodeConnector Name");
1769 Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors();
1770 String nodeConnectorName;
1771 if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
1772 for (NodeConnector nodeConnector : nodeConnectorSet) {
1773 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1774 nodeConnectorName = (propMap == null) ? null : ((Name) propMap
1775 .get(Name.NamePropName)).getValue();
1776 if (nodeConnectorName != null) {
1777 Node nd = nodeConnector.getNode();
1778 if (!nd.equals(node)) {
1779 log.debug("node not match {} {}", nd, node);
1781 Map<String, NodeConnector> map = nodeConnectorNames
1784 NodeConnector nc = map.get(nodeConnectorName);
1786 log.debug("no nodeConnector named {}",
1788 } else if (!nc.equals(nodeConnector)) {
1789 log.debug("nodeConnector not match {} {}", nc,
1795 ci.println(nodeConnector
1797 + ((nodeConnectorName == null) ? "" : nodeConnectorName)
1798 + "(" + nodeConnector.getID() + ")");
1800 ci.println("Total number of NodeConnectors: "
1801 + nodeConnectorSet.size());
1805 public void _snt(CommandInterpreter ci) {
1806 String st = ci.nextArgument();
1808 ci.println("Please enter node id");
1812 Node node = Node.fromString(st);
1814 ci.println("Please enter node id");
1818 st = ci.nextArgument();
1820 ci.println("Please enter tier number");
1823 Integer tid = Integer.decode(st);
1824 Tier tier = new Tier(tid);
1825 setNodeProp(node, tier);
1828 public void _hostRefresh(CommandInterpreter ci) {
1829 String mode = ci.nextArgument();
1831 ci.println("expecting on/off/?");
1834 if (mode.toLowerCase().equals("on")) {
1836 } else if (mode.toLowerCase().equals("off")) {
1837 hostRefresh = false;
1838 } else if (mode.equals("?")) {
1840 ci.println("host refresh is ON");
1842 ci.println("host refresh is OFF");
1845 ci.println("expecting on/off/?");
1850 public void _hostRetry(CommandInterpreter ci) {
1851 String retry = ci.nextArgument();
1852 if (retry == null) {
1853 ci.println("Please enter a valid number. Current retry count is "
1858 hostRetryCount = Integer.parseInt(retry);
1859 } catch (Exception e) {
1860 ci.println("Please enter a valid number");
1866 public byte[] getNodeMAC(Node node) {
1867 MacAddress mac = (MacAddress) this.getNodeProp(node,
1869 return (mac != null) ? mac.getMacAddress() : null;
1873 public boolean isSpecial(NodeConnector p) {
1874 if (p.getType().equals(NodeConnectorIDType.CONTROLLER)
1875 || p.getType().equals(NodeConnectorIDType.ALL)
1876 || p.getType().equals(NodeConnectorIDType.SWSTACK)
1877 || p.getType().equals(NodeConnectorIDType.HWPATH)) {
1884 * Add span configuration to local cache and notify clients
1886 private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
1887 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1889 for (NodeConnector nodeConnector : nodeConnectors) {
1890 if (!spanNodeConnectors.contains(nodeConnector)) {
1891 ncLists.add(nodeConnector);
1895 if (ncLists.size() > 0) {
1896 spanNodeConnectors.addAll(ncLists);
1897 notifySpanPortChange(node, ncLists, true);
1901 private void addSpanPorts(Node node) {
1902 for (SpanConfig conf : getSpanConfigList(node)) {
1903 addSpanPorts(node, conf.getPortArrayList());
1907 private void addSpanPort(NodeConnector nodeConnector) {
1908 // only add if span is configured on this nodeConnector
1909 for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) {
1910 if (conf.getPortArrayList().contains(nodeConnector)) {
1911 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1912 ncLists.add(nodeConnector);
1913 addSpanPorts(nodeConnector.getNode(), ncLists);
1920 * Remove span configuration to local cache and notify clients
1922 private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
1923 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1925 for (NodeConnector nodeConnector : nodeConnectors) {
1926 if (spanNodeConnectors.contains(nodeConnector)) {
1927 ncLists.add(nodeConnector);
1931 if (ncLists.size() > 0) {
1932 spanNodeConnectors.removeAll(ncLists);
1933 notifySpanPortChange(node, ncLists, false);
1937 private void removeSpanPorts(Node node) {
1938 for (SpanConfig conf : getSpanConfigList(node)) {
1939 addSpanPorts(node, conf.getPortArrayList());
1943 private void removeSpanPort(NodeConnector nodeConnector) {
1944 if (spanNodeConnectors.contains(nodeConnector)) {
1945 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1946 ncLists.add(nodeConnector);
1947 removeSpanPorts(nodeConnector.getNode(), ncLists);
1951 private void addNodeProps(Node node, Map<String, Property> propMap) {
1952 if (propMap == null) {
1953 propMap = new HashMap<String, Property>();
1955 nodeProps.put(node, propMap);
1958 private void removeNodeProps(Node node) {
1959 if (getUpNodeConnectors(node).size() == 0) {
1960 nodeProps.remove(node);
1965 public Status saveConfiguration() {
1966 return saveSwitchConfig();
1970 * Creates a Name/Tier/Bandwidth Property object based on given property
1971 * name and value. Other property types are not supported yet.
1974 * Name of the Property
1976 * Value of the Property
1977 * @return {@link org.opendaylight.controller.sal.core.Property}
1980 public Property createProperty(String propName, String propValue) {
1981 if (propName == null) {
1982 log.debug("propName is null");
1985 if (propValue == null) {
1986 log.debug("propValue is null");
1991 if (propName.equalsIgnoreCase(Description.propertyName)) {
1992 return new Description(propValue);
1993 } else if (propName.equalsIgnoreCase(Tier.TierPropName)) {
1994 int tier = Integer.parseInt(propValue);
1995 return new Tier(tier);
1996 } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) {
1997 long bw = Long.parseLong(propValue);
1998 return new Bandwidth(bw);
2000 log.debug("Not able to create {} property", propName);
2002 } catch (Exception e) {
2003 log.debug("createProperty caught exception {}", e.getMessage());
2010 public String getNodeDescription(Node node) {
2011 // Check first if user configured a name
2012 SwitchConfig config = getSwitchConfig(node.toString());
2013 if (config != null) {
2014 String configuredDesc = config.getNodeDescription();
2015 if (configuredDesc != null && !configuredDesc.isEmpty()) {
2016 return configuredDesc;
2020 // No name configured by user, get the node advertised name
2021 Description desc = (Description) getNodeProp(node,
2022 Description.propertyName);
2023 return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? ""