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.ForwardingMode;
46 import org.opendaylight.controller.sal.core.MacAddress;
47 import org.opendaylight.controller.sal.core.Name;
48 import org.opendaylight.controller.sal.core.Node;
49 import org.opendaylight.controller.sal.core.NodeConnector;
50 import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType;
51 import org.opendaylight.controller.sal.core.Property;
52 import org.opendaylight.controller.sal.core.State;
53 import org.opendaylight.controller.sal.core.Tier;
54 import org.opendaylight.controller.sal.core.UpdateType;
55 import org.opendaylight.controller.sal.inventory.IInventoryService;
56 import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates;
57 import org.opendaylight.controller.sal.utils.GlobalConstants;
58 import org.opendaylight.controller.sal.utils.HexEncode;
59 import org.opendaylight.controller.sal.utils.IObjectReader;
60 import org.opendaylight.controller.sal.utils.ObjectReader;
61 import org.opendaylight.controller.sal.utils.ObjectWriter;
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 // set of Subnets keyed by the InetAddress
98 private ConcurrentMap<InetAddress, Subnet> subnets;
99 private ConcurrentMap<String, SubnetConfig> subnetsConfigList;
100 private ConcurrentMap<SpanConfig, SpanConfig> spanConfigList;
101 // manually configured parameters for the node such as name, tier, mode
102 private ConcurrentMap<String, SwitchConfig> nodeConfigList;
103 private ConcurrentMap<Long, String> configSaveEvent;
104 private ConcurrentMap<Node, Map<String, Property>> nodeProps;
105 private ConcurrentMap<NodeConnector, Map<String, Property>> nodeConnectorProps;
106 private ConcurrentMap<Node, Map<String, NodeConnector>> nodeConnectorNames;
107 private IInventoryService inventoryService;
108 private final Set<ISwitchManagerAware> switchManagerAware = Collections
109 .synchronizedSet(new HashSet<ISwitchManagerAware>());
110 private final Set<IInventoryListener> inventoryListeners = Collections
111 .synchronizedSet(new HashSet<IInventoryListener>());
112 private final Set<ISpanAware> spanAware = Collections
113 .synchronizedSet(new HashSet<ISpanAware>());
115 private static boolean hostRefresh = true;
116 private int hostRetryCount = 5;
117 private IClusterContainerServices clusterContainerService = null;
118 private String containerName = null;
119 private boolean isDefaultContainer = true;
120 private static final int REPLACE_RETRY = 1;
122 public enum ReasonCode {
123 SUCCESS("Success"), FAILURE("Failure"), INVALID_CONF(
124 "Invalid Configuration"), EXIST("Entry Already Exist"), CONFLICT(
125 "Configuration Conflict with Existing Entry");
127 private final String name;
129 private ReasonCode(String name) {
134 public String toString() {
139 public void notifySubnetChange(Subnet sub, boolean add) {
140 synchronized (switchManagerAware) {
141 for (Object subAware : switchManagerAware) {
143 ((ISwitchManagerAware) subAware).subnetNotify(sub, add);
144 } catch (Exception e) {
145 log.error("Failed to notify Subnet change {}",
152 public void notifySpanPortChange(Node node, List<NodeConnector> ports,
154 synchronized (spanAware) {
155 for (Object sa : spanAware) {
157 ((ISpanAware) sa).spanUpdate(node, ports, add);
158 } catch (Exception e) {
159 log.error("Failed to notify Span Interface change {}",
166 private void notifyModeChange(Node node, boolean proactive) {
167 synchronized (switchManagerAware) {
168 for (ISwitchManagerAware service : switchManagerAware) {
170 service.modeChangeNotify(node, proactive);
171 } catch (Exception e) {
172 log.error("Failed to notify Subnet change {}",
179 public void startUp() {
180 // Initialize configuration file names
181 subnetFileName = ROOT + "subnets_" + this.getContainerName() + ".conf";
182 spanFileName = ROOT + "spanPorts_" + this.getContainerName() + ".conf";
183 switchConfigFileName = ROOT + "switchConfig_" + this.getContainerName()
186 // Instantiate cluster synced variables
191 * Read startup and build database if we have not already gotten the
192 * configurations synced from another node
194 if (subnetsConfigList.isEmpty()) {
195 loadSubnetConfiguration();
197 if (spanConfigList.isEmpty()) {
198 loadSpanConfiguration();
200 if (nodeConfigList.isEmpty()) {
201 loadSwitchConfiguration();
204 MAC = getHardwareMAC();
207 public void shutDown() {
210 @SuppressWarnings("deprecation")
211 private void allocateCaches() {
212 if (this.clusterContainerService == null) {
213 this.nonClusterObjectCreate();
214 log.warn("un-initialized clusterContainerService, can't create cache");
219 clusterContainerService.createCache(
220 "switchmanager.subnetsConfigList",
221 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
222 clusterContainerService.createCache("switchmanager.spanConfigList",
223 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
224 clusterContainerService.createCache("switchmanager.nodeConfigList",
225 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
226 clusterContainerService.createCache("switchmanager.subnets",
227 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
228 clusterContainerService.createCache(
229 "switchmanager.configSaveEvent",
230 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
231 clusterContainerService.createCache("switchmanager.nodeProps",
232 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
233 clusterContainerService.createCache(
234 "switchmanager.nodeConnectorProps",
235 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
236 clusterContainerService.createCache(
237 "switchmanager.nodeConnectorNames",
238 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
239 } catch (CacheConfigException cce) {
240 log.error("\nCache configuration invalid - check cache mode");
241 } catch (CacheExistException ce) {
242 log.error("\nCache already exits - destroy and recreate if needed");
246 @SuppressWarnings({ "unchecked", "deprecation" })
247 private void retrieveCaches() {
248 if (this.clusterContainerService == null) {
249 log.info("un-initialized clusterContainerService, can't create cache");
253 subnetsConfigList = (ConcurrentMap<String, SubnetConfig>) clusterContainerService
254 .getCache("switchmanager.subnetsConfigList");
255 if (subnetsConfigList == null) {
256 log.error("\nFailed to get cache for subnetsConfigList");
259 spanConfigList = (ConcurrentMap<SpanConfig, SpanConfig>) clusterContainerService
260 .getCache("switchmanager.spanConfigList");
261 if (spanConfigList == null) {
262 log.error("\nFailed to get cache for spanConfigList");
265 nodeConfigList = (ConcurrentMap<String, SwitchConfig>) clusterContainerService
266 .getCache("switchmanager.nodeConfigList");
267 if (nodeConfigList == null) {
268 log.error("\nFailed to get cache for nodeConfigList");
271 subnets = (ConcurrentMap<InetAddress, Subnet>) clusterContainerService
272 .getCache("switchmanager.subnets");
273 if (subnets == null) {
274 log.error("\nFailed to get cache for subnets");
277 configSaveEvent = (ConcurrentMap<Long, String>) clusterContainerService
278 .getCache("switchmanager.configSaveEvent");
279 if (configSaveEvent == null) {
280 log.error("\nFailed to get cache for configSaveEvent");
283 nodeProps = (ConcurrentMap<Node, Map<String, Property>>) clusterContainerService
284 .getCache("switchmanager.nodeProps");
285 if (nodeProps == null) {
286 log.error("\nFailed to get cache for nodeProps");
289 nodeConnectorProps = (ConcurrentMap<NodeConnector, Map<String, Property>>) clusterContainerService
290 .getCache("switchmanager.nodeConnectorProps");
291 if (nodeConnectorProps == null) {
292 log.error("\nFailed to get cache for nodeConnectorProps");
295 nodeConnectorNames = (ConcurrentMap<Node, Map<String, NodeConnector>>) clusterContainerService
296 .getCache("switchmanager.nodeConnectorNames");
297 if (nodeConnectorNames == null) {
298 log.error("\nFailed to get cache for nodeConnectorNames");
302 private void nonClusterObjectCreate() {
303 subnetsConfigList = new ConcurrentHashMap<String, SubnetConfig>();
304 spanConfigList = new ConcurrentHashMap<SpanConfig, SpanConfig>();
305 nodeConfigList = new ConcurrentHashMap<String, SwitchConfig>();
306 subnets = new ConcurrentHashMap<InetAddress, Subnet>();
307 configSaveEvent = new ConcurrentHashMap<Long, String>();
308 nodeProps = new ConcurrentHashMap<Node, Map<String, Property>>();
309 nodeConnectorProps = new ConcurrentHashMap<NodeConnector, Map<String, Property>>();
310 nodeConnectorNames = new ConcurrentHashMap<Node, Map<String, NodeConnector>>();
314 public List<SubnetConfig> getSubnetsConfigList() {
315 return new ArrayList<SubnetConfig>(subnetsConfigList.values());
319 public SubnetConfig getSubnetConfig(String subnet) {
320 return subnetsConfigList.get(subnet);
323 private List<SpanConfig> getSpanConfigList(Node node) {
324 List<SpanConfig> confList = new ArrayList<SpanConfig>();
325 String nodeId = node.toString();
326 for (SpanConfig conf : spanConfigList.values()) {
327 if (conf.matchNode(nodeId)) {
334 public List<SwitchConfig> getNodeConfigList() {
335 return new ArrayList<SwitchConfig>(nodeConfigList.values());
339 public SwitchConfig getSwitchConfig(String switchId) {
340 return nodeConfigList.get(switchId);
343 public Switch getSwitchByNode(Node node) {
344 Switch sw = new Switch(node);
346 MacAddress mac = (MacAddress) this.getNodeProp(node,
349 sw.setDataLayerAddress(mac.getMacAddress());
351 Set<NodeConnector> ncSet = getPhysicalNodeConnectors(node);
352 sw.setNodeConnectors(ncSet);
354 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
355 for (NodeConnector nodeConnector : ncSet) {
356 if (spanNodeConnectors.contains(nodeConnector)) {
357 ncList.add(nodeConnector);
360 sw.addSpanPorts(ncList);
366 public List<Switch> getNetworkDevices() {
367 Set<Node> nodeSet = getNodes();
368 List<Switch> swList = new ArrayList<Switch>();
369 if (nodeSet != null) {
370 for (Node node : nodeSet) {
371 swList.add(getSwitchByNode(node));
378 private Status updateConfig(SubnetConfig conf, boolean add) {
380 if(subnetsConfigList.putIfAbsent(conf.getName(), conf) != null) {
381 String msg = "Cluster conflict: Subnet with name " + conf.getName() + "already exists.";
382 return new Status(StatusCode.CONFLICT, msg);
385 subnetsConfigList.remove(conf.getName());
387 return new Status(StatusCode.SUCCESS);
390 private Status updateDatabase(SubnetConfig conf, boolean add) {
392 Subnet subnetCurr = subnets.get(conf.getIPnum());
394 if (subnetCurr == null) {
395 subnet = new Subnet(conf);
397 subnet = subnetCurr.clone();
399 // In case of API3 call we may receive the ports along with the
401 if (!conf.isGlobal()) {
402 Set<NodeConnector> sp = conf.getSubnetNodeConnectors();
403 subnet.addNodeConnectors(sp);
405 boolean result = false;
406 if(subnetCurr == null) {
407 if(subnets.putIfAbsent(conf.getIPnum(), subnet) == null) {
411 result = subnets.replace(conf.getIPnum(), subnetCurr, subnet);
414 String msg = "Cluster conflict: Conflict while adding the subnet " + conf.getIPnum();
415 return new Status(StatusCode.CONFLICT, msg);
417 } else { // This is the deletion of the whole subnet
418 subnets.remove(conf.getIPnum());
420 return new Status(StatusCode.SUCCESS);
423 private Status semanticCheck(SubnetConfig conf) {
424 Subnet newSubnet = new Subnet(conf);
425 Set<InetAddress> IPs = subnets.keySet();
427 return new Status(StatusCode.SUCCESS);
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);
436 return new Status(StatusCode.SUCCESS);
439 private Status addRemoveSubnet(SubnetConfig conf, boolean add) {
440 // Valid config check
441 if (!conf.isValidConfig()) {
442 String msg = "Invalid Subnet configuration";
444 return new Status(StatusCode.BADREQUEST, msg);
449 if (subnetsConfigList.containsKey(conf.getName())) {
450 return new Status(StatusCode.CONFLICT,
451 "Same subnet config already exists");
454 Status rc = semanticCheck(conf);
455 if (!rc.isSuccess()) {
461 Status rc = updateDatabase(conf, add);
463 if (rc.isSuccess()) {
464 // Update Configuration
465 rc = updateConfig(conf, add);
466 if(!rc.isSuccess()) {
467 updateDatabase(conf, (!add));
475 * Adds Subnet configured in GUI or API3
478 public Status addSubnet(SubnetConfig conf) {
479 return this.addRemoveSubnet(conf, true);
483 public Status removeSubnet(SubnetConfig conf) {
484 return this.addRemoveSubnet(conf, false);
488 public Status removeSubnet(String name) {
489 SubnetConfig conf = subnetsConfigList.get(name);
491 return new Status(StatusCode.SUCCESS, "Subnet not present");
493 return this.addRemoveSubnet(conf, false);
497 public Status addPortsToSubnet(String name, String switchPorts) {
498 SubnetConfig confCurr = subnetsConfigList.get(name);
499 if (confCurr == null) {
500 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
502 if (!confCurr.isValidSwitchPort(switchPorts)) {
503 return new Status(StatusCode.BADREQUEST, "Invalid switchports");
506 Subnet subCurr = subnets.get(confCurr.getIPnum());
507 if (subCurr == null) {
508 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPnum());
509 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
513 Subnet sub = subCurr.clone();
514 Set<NodeConnector> sp = confCurr.getNodeConnectors(switchPorts);
515 sub.addNodeConnectors(sp);
516 boolean subnetsReplace = subnets.replace(confCurr.getIPnum(), subCurr, sub);
517 if (!subnetsReplace) {
518 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
519 return new Status(StatusCode.CONFLICT, msg);
522 // Update Configuration
523 SubnetConfig conf = confCurr.clone();
524 conf.addNodeConnectors(switchPorts);
525 boolean result = subnetsConfigList.replace(name, confCurr, conf);
527 // TODO: recovery using Transactionality
528 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
529 return new Status(StatusCode.CONFLICT, msg);
532 return new Status(StatusCode.SUCCESS);
536 public Status removePortsFromSubnet(String name, String switchPorts) {
537 SubnetConfig confCurr = subnetsConfigList.get(name);
538 if (confCurr == null) {
539 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
542 Subnet subCurr = subnets.get(confCurr.getIPnum());
543 if (subCurr == null) {
544 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPnum());
545 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
549 Subnet sub = subCurr.clone();
550 Set<NodeConnector> sp = confCurr.getNodeConnectors(switchPorts);
551 sub.deleteNodeConnectors(sp);
552 boolean subnetsReplace = subnets.replace(confCurr.getIPnum(), subCurr, sub);
553 if (!subnetsReplace) {
554 String msg = "Cluster conflict: Conflict while removing ports from the subnet " + name;
555 return new Status(StatusCode.CONFLICT, msg);
558 // Update Configuration
559 SubnetConfig conf = confCurr.clone();
560 conf.removeNodeConnectors(switchPorts);
561 boolean result = subnetsConfigList.replace(name, confCurr, conf);
563 // TODO: recovery using Transactionality
564 String msg = "Cluster conflict: Conflict while removing ports from " + conf;
565 return new Status(StatusCode.CONFLICT, msg);
568 return new Status(StatusCode.SUCCESS);
571 public String getContainerName() {
572 if (containerName == null) {
573 return GlobalConstants.DEFAULT.toString();
575 return containerName;
579 public Subnet getSubnetByNetworkAddress(InetAddress networkAddress) {
581 Set<InetAddress> indices = subnets.keySet();
582 for (InetAddress i : indices) {
583 sub = subnets.get(i);
584 if (sub.isSubnetOf(networkAddress)) {
592 public Object readObject(ObjectInputStream ois)
593 throws FileNotFoundException, IOException, ClassNotFoundException {
594 // Perform the class deserialization locally, from inside the package
595 // where the class is defined
596 return ois.readObject();
599 @SuppressWarnings("unchecked")
600 private void loadSubnetConfiguration() {
601 ObjectReader objReader = new ObjectReader();
602 ConcurrentMap<String, SubnetConfig> confList = (ConcurrentMap<String, SubnetConfig>) objReader
603 .read(this, subnetFileName);
605 if (confList == null) {
609 for (SubnetConfig conf : confList.values()) {
614 @SuppressWarnings("unchecked")
615 private void loadSpanConfiguration() {
616 ObjectReader objReader = new ObjectReader();
617 ConcurrentMap<Integer, SpanConfig> confList = (ConcurrentMap<Integer, SpanConfig>) objReader
618 .read(this, spanFileName);
620 if (confList == null) {
624 for (SpanConfig conf : confList.values()) {
629 @SuppressWarnings("unchecked")
630 private void loadSwitchConfiguration() {
631 ObjectReader objReader = new ObjectReader();
632 ConcurrentMap<String, SwitchConfig> confList = (ConcurrentMap<String, SwitchConfig>) objReader
633 .read(this, switchConfigFileName);
635 if (confList == null) {
639 for (SwitchConfig conf : confList.values()) {
640 updateSwitchConfig(conf);
645 public void updateSwitchConfig(SwitchConfig cfgObject) {
646 // update default container only
647 if (!isDefaultContainer) {
651 SwitchConfig sc = nodeConfigList.get(cfgObject.getNodeId());
653 if (nodeConfigList.putIfAbsent(cfgObject.getNodeId(), cfgObject) != null) {
657 if (!nodeConfigList.replace(cfgObject.getNodeId(), sc, cfgObject)) {
662 boolean modeChange = false;
664 if ((sc == null) || !cfgObject.getMode().equals(sc.getMode())) {
668 String nodeId = cfgObject.getNodeId();
669 Node node = Node.fromString(nodeId);
670 Map<String, Property> propMapCurr = nodeProps.get(node);
671 if (propMapCurr == null) {
674 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
675 Property desc = new Description(cfgObject.getNodeDescription());
676 propMap.put(desc.getName(), desc);
677 Property tier = new Tier(Integer.parseInt(cfgObject.getTier()));
678 propMap.put(tier.getName(), tier);
680 if (!nodeProps.replace(node, propMapCurr, propMap)) {
681 // TODO rollback using Transactionality
685 log.info("Set Node {}'s Mode to {}", nodeId, cfgObject.getMode());
688 notifyModeChange(node, cfgObject.isProactive());
693 public Status updateNodeConfig(SwitchConfig switchConfig) {
694 Status status = switchConfig.validate();
695 if (!status.isSuccess()) {
699 Map<String, Property> updateProperties = switchConfig.getNodeProperties();
700 String nodeId = switchConfig.getNodeId();
701 ForwardingMode mode = (ForwardingMode) updateProperties.get(ForwardingMode.name);
703 if (isDefaultContainer) {
704 if (!mode.isValid()) {
705 return new Status(StatusCode.BADREQUEST, "Invalid Forwarding Mode Value.");
708 return new Status(StatusCode.NOTACCEPTABLE,
709 "Forwarding Mode modification is allowed only in default container");
712 boolean modeChange = false;
713 SwitchConfig sc = nodeConfigList.get(nodeId);
714 Map<String, Property> prevNodeProperties = new HashMap<String, Property>();
716 if ((mode != null) && mode.isProactive()) {
719 if (!updateProperties.isEmpty()) {
720 if (nodeConfigList.putIfAbsent(nodeId, switchConfig) != null) {
721 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
725 prevNodeProperties = new HashMap<String, Property>(sc.getNodeProperties());
726 ForwardingMode prevMode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
728 if ((prevMode != null) && (prevMode.isProactive())) {
732 if (((prevMode != null) && (prevMode.getValue() != mode.getValue()))
733 || (prevMode == null && mode.isProactive())) {
737 if (updateProperties.isEmpty()) {
738 nodeConfigList.remove(nodeId);
740 if (!nodeConfigList.replace(nodeId, sc, switchConfig)) {
741 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
745 Node node = Node.fromString(nodeId);
746 Map<String, Property> propMapCurr = nodeProps.get(node);
747 if (propMapCurr == null) {
748 return new Status(StatusCode.SUCCESS);
750 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
751 if (!prevNodeProperties.isEmpty()) {
752 for (String prop : prevNodeProperties.keySet()) {
753 if (!updateProperties.containsKey(prop)) {
754 if (prop.equals(Description.propertyName)) {
755 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
756 if (nodeProp.get(node) != null) {
757 propMap.put(Description.propertyName, nodeProp.get(node).get(Description.propertyName));
761 propMap.remove(prop);
765 propMap.putAll(updateProperties);
766 if (!nodeProps.replace(node, propMapCurr, propMap)) {
767 // TODO rollback using Transactionality
768 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration.");
771 notifyModeChange(node, (mode == null) ? false : mode.isProactive());
773 return new Status(StatusCode.SUCCESS);
777 public Status removeNodeConfig(String nodeId) {
778 if ((nodeId == null) || (nodeId.isEmpty())) {
779 return new Status(StatusCode.BADREQUEST, "nodeId cannot be empty.");
781 Map<String, Property> nodeProperties = getSwitchConfig(nodeId).getNodeProperties();
782 Node node = Node.fromString(nodeId);
783 Map<String, Property> propMapCurr = nodeProps.get(node);
784 if ((propMapCurr != null) && (nodeProperties != null) && (!nodeProperties.isEmpty())) {
785 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
786 for (String prop : nodeProperties.keySet()) {
787 if (prop.equals(Description.propertyName)) {
788 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
789 if (nodeProp.get(node) != null) {
790 propMap.put(Description.propertyName, nodeProp.get(node).get(Description.propertyName));
794 propMap.remove(prop);
796 if (!nodeProps.replace(node, propMapCurr, propMap)) {
797 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration.");
800 if (nodeConfigList != null) {
801 nodeConfigList.remove(nodeId);
803 return new Status(StatusCode.SUCCESS);
807 public Status saveSwitchConfig() {
808 // Publish the save config event to the cluster nodes
809 configSaveEvent.put(new Date().getTime(), SAVE);
810 return saveSwitchConfigInternal();
813 public Status saveSwitchConfigInternal() {
814 Status retS = null, retP = null;
815 ObjectWriter objWriter = new ObjectWriter();
817 retS = objWriter.write(new ConcurrentHashMap<String, SubnetConfig>(
818 subnetsConfigList), subnetFileName);
819 retP = objWriter.write(new ConcurrentHashMap<SpanConfig, SpanConfig>(
820 spanConfigList), spanFileName);
821 retS = objWriter.write(new ConcurrentHashMap<String, SwitchConfig>(
822 nodeConfigList), switchConfigFileName);
823 if (retS.equals(retP)) {
824 if (retS.isSuccess()) {
827 return new Status(StatusCode.INTERNALERROR, "Save failed");
830 return new Status(StatusCode.INTERNALERROR, "Partial save failure");
835 public List<SpanConfig> getSpanConfigList() {
836 return new ArrayList<SpanConfig>(spanConfigList.values());
840 public Status addSpanConfig(SpanConfig conf) {
841 // Valid config check
842 if (!conf.isValidConfig()) {
843 String msg = "Invalid Span configuration";
845 return new Status(StatusCode.BADREQUEST, msg);
849 if (spanConfigList.containsKey(conf)) {
850 return new Status(StatusCode.CONFLICT, "Same span config exists");
853 // Update configuration
854 if (spanConfigList.putIfAbsent(conf, conf) == null) {
855 // Update database and notify clients
856 addSpanPorts(conf.getNode(), conf.getPortArrayList());
859 return new Status(StatusCode.SUCCESS);
863 public Status removeSpanConfig(SpanConfig conf) {
864 removeSpanPorts(conf.getNode(), conf.getPortArrayList());
866 // Update configuration
867 spanConfigList.remove(conf);
869 return new Status(StatusCode.SUCCESS);
873 public List<NodeConnector> getSpanPorts(Node node) {
874 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
876 for (NodeConnector nodeConnector : spanNodeConnectors) {
877 if (nodeConnector.getNode().equals(node)) {
878 ncList.add(nodeConnector);
885 public void entryCreated(Long key, String cacheName, boolean local) {
889 public void entryUpdated(Long key, String new_value, String cacheName,
890 boolean originLocal) {
891 saveSwitchConfigInternal();
895 public void entryDeleted(Long key, String cacheName, boolean originLocal) {
898 private void addNode(Node node, Set<Property> props) {
899 log.trace("{} added, props: {}", node, props);
900 if (nodeProps == null) {
904 Map<String, Property> propMapCurr = nodeProps.get(node);
905 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
906 : new HashMap<String, Property>(propMapCurr);
908 // copy node properties from plugin
910 for (Property prop : props) {
911 propMap.put(prop.getName(), prop);
915 // copy node properties from config
916 boolean proactiveForwarding = false;
917 if (nodeConfigList != null) {
918 String nodeId = node.toString();
919 SwitchConfig conf = nodeConfigList.get(nodeId);
920 if (conf != null && (conf.getNodeProperties() != null)) {
921 Map<String, Property> nodeProperties = conf.getNodeProperties();
922 propMap.putAll(nodeProperties);
923 if (nodeProperties.get(ForwardingMode.name) != null) {
924 ForwardingMode mode = (ForwardingMode) nodeProperties.get(ForwardingMode.name);
925 proactiveForwarding = mode.isProactive();
930 boolean result = false;
931 if (propMapCurr == null) {
932 if (nodeProps.putIfAbsent(node, propMap) == null) {
936 result = nodeProps.replace(node, propMapCurr, propMap);
939 log.debug("Cluster conflict: Conflict while adding the node properties. Node: {} Properties: {}",
940 node.getID(), props);
941 addNodeProps(node, propMap);
944 // check if span ports are configed
947 // notify node listeners
948 notifyNode(node, UpdateType.ADDED, propMap);
950 // notify proactive mode forwarding
951 if (proactiveForwarding) {
952 notifyModeChange(node, true);
956 private void removeNode(Node node) {
957 log.trace("{} removed", node);
958 if (nodeProps == null) {
961 nodeProps.remove(node);
963 // check if span ports need to be cleaned up
964 removeSpanPorts(node);
966 /* notify node listeners */
967 notifyNode(node, UpdateType.REMOVED, null);
970 private void updateNode(Node node, Set<Property> props) {
971 log.trace("{} updated, props: {}", node, props);
972 if (nodeProps == null || !nodeProps.containsKey(node) ||
973 props == null || props.isEmpty()) {
977 Map<String, Property> propMapCurr = nodeProps.get(node);
978 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
979 : new HashMap<String, Property>(propMapCurr);
981 // copy node properties from plugin
982 String nodeId = node.toString();
983 for (Property prop : props) {
984 if (nodeConfigList != null) {
985 SwitchConfig conf = nodeConfigList.get(nodeId);
986 if (conf != null && (conf.getNodeProperties() != null)
987 && conf.getNodeProperties().containsKey(prop.getName())) {
991 propMap.put(prop.getName(), prop);
994 if (propMapCurr == null) {
995 if (nodeProps.putIfAbsent(node, propMap) != null) {
996 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
997 node.getID(), props);
998 addNodeProps(node, propMap);
1001 if (!nodeProps.replace(node, propMapCurr, propMap)) {
1002 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1003 node.getID(), props);
1004 addNodeProps(node, propMap);
1008 /* notify node listeners */
1009 notifyNode(node, UpdateType.CHANGED, propMap);
1013 public void updateNode(Node node, UpdateType type, Set<Property> props) {
1014 log.debug("updateNode: {} type {} props {} for container {}",
1015 new Object[] { node, type, props, containerName });
1018 addNode(node, props);
1021 updateNode(node, props);
1032 public void updateNodeConnector(NodeConnector nodeConnector,
1033 UpdateType type, Set<Property> props) {
1034 Map<String, Property> propMap = new HashMap<String, Property>();
1036 log.debug("updateNodeConnector: {} type {} props {} for container {}",
1037 new Object[] { nodeConnector, type, props, containerName });
1039 if (nodeConnectorProps == null) {
1046 if (props != null) {
1047 for (Property prop : props) {
1048 addNodeConnectorProp(nodeConnector, prop);
1049 propMap.put(prop.getName(), prop);
1052 addNodeConnectorProp(nodeConnector, null);
1055 addSpanPort(nodeConnector);
1058 removeNodeConnectorAllProps(nodeConnector);
1060 // clean up span config
1061 removeSpanPort(nodeConnector);
1067 notifyNodeConnector(nodeConnector, type, propMap);
1071 public Set<Node> getNodes() {
1072 return (nodeProps != null) ? new HashSet<Node>(nodeProps.keySet())
1077 * Returns a copy of a list of properties for a given node
1082 * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps
1083 * (org.opendaylight.controller.sal.core.Node)
1086 public Map<String, Property> getNodeProps(Node node) {
1087 Map<String, Property> rv = new HashMap<String, Property>();
1088 if (this.nodeProps != null) {
1089 rv = this.nodeProps.get(node);
1091 /* make a copy of it */
1092 rv = new HashMap<String, Property>(rv);
1099 public Property getNodeProp(Node node, String propName) {
1100 Map<String, Property> propMap = getNodeProps(node);
1101 return (propMap != null) ? propMap.get(propName) : null;
1105 public void setNodeProp(Node node, Property prop) {
1107 for (int i = 0; i <= REPLACE_RETRY; i++) {
1108 /* Get a copy of the property map */
1109 Map<String, Property> propMapCurr = getNodeProps(node);
1110 if (propMapCurr == null) {
1114 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1115 propMap.put(prop.getName(), prop);
1117 if (nodeProps.replace(node, propMapCurr, propMap)) {
1120 if (!propMapCurr.get(prop.getName()).equals(nodeProps.get(node).get(prop.getName()))) {
1121 log.debug("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1125 log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1129 public Status removeNodeProp(Node node, String propName) {
1130 for (int i = 0; i <= REPLACE_RETRY; i++) {
1131 Map<String, Property> propMapCurr = getNodeProps(node);
1132 if (propMapCurr != null) {
1133 if (!propMapCurr.containsKey(propName)) {
1134 return new Status(StatusCode.SUCCESS);
1136 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1137 propMap.remove(propName);
1138 if (nodeProps.replace(node, propMapCurr, propMap)) {
1139 return new Status(StatusCode.SUCCESS);
1141 if (!propMapCurr.get(propName).equals(nodeProps.get(node).get(propName))) {
1142 String msg = "Cluster conflict: Unable to remove property " + propName + " for node "
1144 return new Status(StatusCode.CONFLICT, msg);
1148 return new Status(StatusCode.SUCCESS);
1151 String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID();
1152 return new Status(StatusCode.CONFLICT, msg);
1156 public Status removeNodeAllProps(Node node) {
1157 this.nodeProps.remove(node);
1158 return new Status(StatusCode.SUCCESS);
1162 public Set<NodeConnector> getUpNodeConnectors(Node node) {
1163 if (nodeConnectorProps == null) {
1167 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1168 for (NodeConnector nodeConnector : nodeConnectorProps.keySet()) {
1169 if (!nodeConnector.getNode().equals(node)) {
1172 if (isNodeConnectorEnabled(nodeConnector)) {
1173 nodeConnectorSet.add(nodeConnector);
1177 return nodeConnectorSet;
1181 public Set<NodeConnector> getNodeConnectors(Node node) {
1182 if (nodeConnectorProps == null) {
1186 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1187 for (NodeConnector nodeConnector : nodeConnectorProps.keySet()) {
1188 if (!nodeConnector.getNode().equals(node)) {
1191 nodeConnectorSet.add(nodeConnector);
1194 return nodeConnectorSet;
1198 public Set<NodeConnector> getPhysicalNodeConnectors(Node node) {
1199 if (nodeConnectorProps == null) {
1203 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1204 for (NodeConnector nodeConnector : nodeConnectorProps.keySet()) {
1205 if (!nodeConnector.getNode().equals(node)
1206 || isSpecial(nodeConnector)) {
1209 nodeConnectorSet.add(nodeConnector);
1212 return nodeConnectorSet;
1216 public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) {
1217 Map<String, Property> rv = new HashMap<String, Property>();
1218 if (this.nodeConnectorProps != null) {
1219 rv = this.nodeConnectorProps.get(nodeConnector);
1221 rv = new HashMap<String, Property>(rv);
1228 public Property getNodeConnectorProp(NodeConnector nodeConnector,
1230 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1231 return (propMap != null) ? propMap.get(propName) : null;
1234 private byte[] getHardwareMAC() {
1235 Enumeration<NetworkInterface> nis;
1237 nis = NetworkInterface.getNetworkInterfaces();
1238 } catch (SocketException e1) {
1243 for (; nis.hasMoreElements();) {
1244 NetworkInterface ni = nis.nextElement();
1246 MAC = ni.getHardwareAddress();
1247 } catch (SocketException e) {
1258 public byte[] getControllerMAC() {
1263 public boolean isHostRefreshEnabled() {
1268 public int getHostRetryCount() {
1269 return hostRetryCount;
1273 public NodeConnector getNodeConnector(Node node, String nodeConnectorName) {
1274 if (nodeConnectorNames == null) {
1278 Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1283 return map.get(nodeConnectorName);
1287 * Adds a node connector and its property if any
1289 * @param nodeConnector
1290 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1292 * name of {@link org.opendaylight.controller.sal.core.Property}
1293 * @return success or failed reason
1296 public Status addNodeConnectorProp(NodeConnector nodeConnector,
1298 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1299 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1300 : new HashMap<String, Property>(propMapCurr);
1302 String msg = "Cluster conflict: Unable to add NodeConnector Property.";
1303 // Just add the nodeConnector if prop is not available (in a non-default
1306 if (propMapCurr == null) {
1307 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1308 return new Status(StatusCode.CONFLICT, msg);
1311 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1312 return new Status(StatusCode.CONFLICT, msg);
1315 return new Status(StatusCode.SUCCESS);
1318 propMap.put(prop.getName(), prop);
1319 if (propMapCurr == null) {
1320 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1321 return new Status(StatusCode.CONFLICT, msg);
1324 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1325 return new Status(StatusCode.CONFLICT, msg);
1329 if (prop.getName().equals(Name.NamePropName)) {
1330 if (nodeConnectorNames != null) {
1331 Node node = nodeConnector.getNode();
1332 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1333 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1334 if (mapCurr != null) {
1335 for (String s : mapCurr.keySet()) {
1337 map.put(s, new NodeConnector(mapCurr.get(s)));
1338 } catch (ConstructionException e) {
1339 e.printStackTrace();
1344 map.put(((Name) prop).getValue(), nodeConnector);
1345 if (mapCurr == null) {
1346 if (nodeConnectorNames.putIfAbsent(node, map) != null) {
1347 // TODO: recovery using Transactionality
1348 return new Status(StatusCode.CONFLICT, msg);
1351 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1352 // TODO: recovery using Transactionality
1353 return new Status(StatusCode.CONFLICT, msg);
1359 return new Status(StatusCode.SUCCESS);
1363 * Removes one property of a node connector
1365 * @param nodeConnector
1366 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1368 * name of {@link org.opendaylight.controller.sal.core.Property}
1369 * @return success or failed reason
1372 public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) {
1373 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1375 if (propMapCurr == null) {
1376 /* Nothing to remove */
1377 return new Status(StatusCode.SUCCESS);
1380 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1381 propMap.remove(propName);
1382 boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap);
1383 String msg = "Cluster conflict: Unable to remove NodeConnector property.";
1385 return new Status(StatusCode.CONFLICT, msg);
1388 if (propName.equals(Name.NamePropName)) {
1389 if (nodeConnectorNames != null) {
1390 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1392 Node node = nodeConnector.getNode();
1393 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1394 if (mapCurr != null) {
1395 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1396 for (String s : mapCurr.keySet()) {
1398 map.put(s, new NodeConnector(mapCurr.get(s)));
1399 } catch (ConstructionException e) {
1400 e.printStackTrace();
1403 map.remove(name.getValue());
1404 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1405 // TODO: recovery using Transactionality
1406 return new Status(StatusCode.CONFLICT, msg);
1413 return new Status(StatusCode.SUCCESS);
1417 * Removes all the properties of a node connector
1419 * @param nodeConnector
1420 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1421 * @return success or failed reason
1424 public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) {
1425 if (nodeConnectorNames != null) {
1426 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1428 Node node = nodeConnector.getNode();
1429 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1430 if (mapCurr != null) {
1431 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1432 for (String s : mapCurr.keySet()) {
1434 map.put(s, new NodeConnector(mapCurr.get(s)));
1435 } catch (ConstructionException e) {
1436 e.printStackTrace();
1439 map.remove(name.getValue());
1440 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1441 log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.",
1442 nodeConnector.getID());
1448 nodeConnectorProps.remove(nodeConnector);
1450 return new Status(StatusCode.SUCCESS);
1454 * Function called by the dependency manager when all the required
1455 * dependencies are satisfied
1458 void init(Component c) {
1459 Dictionary<?, ?> props = c.getServiceProperties();
1460 if (props != null) {
1461 this.containerName = (String) props.get("containerName");
1462 log.trace("Running containerName: {}", this.containerName);
1464 // In the Global instance case the containerName is empty
1465 this.containerName = "";
1467 isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT
1474 * Function called by the dependency manager when at least one dependency
1475 * become unsatisfied or when the component is shutting down because for
1476 * example bundle is being stopped.
1484 * Function called by dependency manager after "init ()" is called and after
1485 * the services provided by the class are registered in the service registry
1490 registerWithOSGIConsole();
1494 * Function called after registered the service in OSGi service registry.
1497 // solicit for existing inventories
1502 * Function called by the dependency manager before the services exported by
1503 * the component are unregistered, this will be followed by a "destroy ()"
1510 public void setInventoryService(IInventoryService service) {
1511 log.trace("Got inventory service set request {}", service);
1512 this.inventoryService = service;
1514 // solicit for existing inventories
1518 public void unsetInventoryService(IInventoryService service) {
1519 log.trace("Got a service UNset request");
1520 this.inventoryService = null;
1522 // clear existing inventories
1526 public void setSwitchManagerAware(ISwitchManagerAware service) {
1527 log.trace("Got inventory service set request {}", service);
1528 if (this.switchManagerAware != null) {
1529 this.switchManagerAware.add(service);
1532 // bulk update for newly joined
1533 switchManagerAwareNotify(service);
1536 public void unsetSwitchManagerAware(ISwitchManagerAware service) {
1537 log.trace("Got a service UNset request");
1538 if (this.switchManagerAware != null) {
1539 this.switchManagerAware.remove(service);
1543 public void setInventoryListener(IInventoryListener service) {
1544 log.trace("Got inventory listener set request {}", service);
1545 if (this.inventoryListeners != null) {
1546 this.inventoryListeners.add(service);
1549 // bulk update for newly joined
1550 bulkUpdateService(service);
1553 public void unsetInventoryListener(IInventoryListener service) {
1554 log.trace("Got a service UNset request");
1555 if (this.inventoryListeners != null) {
1556 this.inventoryListeners.remove(service);
1560 public void setSpanAware(ISpanAware service) {
1561 log.trace("Got SpanAware set request {}", service);
1562 if (this.spanAware != null) {
1563 this.spanAware.add(service);
1566 // bulk update for newly joined
1567 spanAwareNotify(service);
1570 public void unsetSpanAware(ISpanAware service) {
1571 log.trace("Got a service UNset request");
1572 if (this.spanAware != null) {
1573 this.spanAware.remove(service);
1577 void setClusterContainerService(IClusterContainerServices s) {
1578 log.trace("Cluster Service set");
1579 this.clusterContainerService = s;
1582 void unsetClusterContainerService(IClusterContainerServices s) {
1583 if (this.clusterContainerService == s) {
1584 log.trace("Cluster Service removed!");
1585 this.clusterContainerService = null;
1589 private void getInventories() {
1590 if (inventoryService == null) {
1591 log.trace("inventory service not avaiable");
1595 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
1596 for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) {
1597 Node node = entry.getKey();
1598 log.debug("getInventories: {} added for container {}", new Object[] { node, containerName });
1599 Map<String, Property> propMap = entry.getValue();
1600 Set<Property> props = new HashSet<Property>();
1601 for (Property property : propMap.values()) {
1602 props.add(property);
1604 addNode(node, props);
1607 Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps();
1608 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) {
1609 Map<String, Property> propMap = entry.getValue();
1610 for (Property property : propMap.values()) {
1611 addNodeConnectorProp(entry.getKey(), property);
1616 private void clearInventories() {
1618 nodeConnectorProps.clear();
1619 nodeConnectorNames.clear();
1620 spanNodeConnectors.clear();
1623 private void notifyNode(Node node, UpdateType type,
1624 Map<String, Property> propMap) {
1625 synchronized (inventoryListeners) {
1626 for (IInventoryListener service : inventoryListeners) {
1627 service.notifyNode(node, type, propMap);
1632 private void notifyNodeConnector(NodeConnector nodeConnector,
1633 UpdateType type, Map<String, Property> propMap) {
1634 synchronized (inventoryListeners) {
1635 for (IInventoryListener service : inventoryListeners) {
1636 service.notifyNodeConnector(nodeConnector, type, propMap);
1642 * For those joined late, bring them up-to-date.
1644 private void switchManagerAwareNotify(ISwitchManagerAware service) {
1645 for (Subnet sub : subnets.values()) {
1646 service.subnetNotify(sub, true);
1649 for (Node node : getNodes()) {
1650 SwitchConfig sc = getSwitchConfig(node.toString());
1651 if ((sc != null) && isDefaultContainer) {
1652 ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
1653 service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive());
1658 private void bulkUpdateService(IInventoryListener service) {
1659 Map<String, Property> propMap;
1660 UpdateType type = UpdateType.ADDED;
1662 for (Node node : getNodes()) {
1663 propMap = nodeProps.get(node);
1664 service.notifyNode(node, type, propMap);
1667 for (NodeConnector nodeConnector : nodeConnectorProps.keySet()) {
1668 propMap = nodeConnectorProps.get(nodeConnector);
1669 service.notifyNodeConnector(nodeConnector, type, propMap);
1673 private void spanAwareNotify(ISpanAware service) {
1674 for (Node node : getNodes()) {
1675 for (SpanConfig conf : getSpanConfigList(node)) {
1676 service.spanUpdate(node, conf.getPortArrayList(), true);
1681 private void registerWithOSGIConsole() {
1682 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
1683 .getBundleContext();
1684 bundleContext.registerService(CommandProvider.class.getName(), this,
1689 public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) {
1690 if (nodeConnector == null) {
1694 Config config = (Config) getNodeConnectorProp(nodeConnector,
1695 Config.ConfigPropName);
1696 State state = (State) getNodeConnectorProp(nodeConnector,
1697 State.StatePropName);
1698 return ((config != null) && (config.getValue() == Config.ADMIN_UP)
1699 && (state != null) && (state.getValue() == State.EDGE_UP));
1703 public String getHelp() {
1704 StringBuffer help = new StringBuffer();
1705 help.append("---Switch Manager---\n");
1706 help.append("\t pns - Print connected nodes\n");
1707 help.append("\t pncs <node id> - Print node connectors for a given node\n");
1708 help.append("\t pencs <node id> - Print enabled node connectors for a given node\n");
1709 help.append("\t pdm <node id> - Print switch ports in device map\n");
1710 help.append("\t snt <node id> <tier> - Set node tier number\n");
1711 help.append("\t hostRefresh <on/off/?> - Enable/Disable/Query host refresh\n");
1712 help.append("\t hostRetry <count> - Set host retry count\n");
1713 return help.toString();
1716 public void _pns(CommandInterpreter ci) {
1717 ci.println(" Node Type MAC Name Tier");
1718 if (nodeProps == null) {
1721 Set<Node> nodeSet = nodeProps.keySet();
1722 if (nodeSet == null) {
1725 List<String> nodeArray = new ArrayList<String>();
1726 for (Node node : nodeSet) {
1727 nodeArray.add(node.toString());
1729 Collections.sort(nodeArray);
1730 for (String str: nodeArray) {
1731 Node node = Node.fromString(str);
1732 Description desc = ((Description) getNodeProp(node,
1733 Description.propertyName));
1734 Tier tier = ((Tier) getNodeProp(node, Tier.TierPropName));
1735 String nodeName = (desc == null) ? "" : desc.getValue();
1736 MacAddress mac = (MacAddress) getNodeProp(node,
1738 String macAddr = (mac == null) ? "" : HexEncode
1739 .bytesToHexStringFormat(mac.getMacAddress());
1740 int tierNum = (tier == null) ? 0 : tier.getValue();
1741 ci.println(node + " " + node.getType() + " " + macAddr
1742 + " " + nodeName + " " + tierNum);
1744 ci.println("Total number of Nodes: " + nodeSet.size());
1747 public void _pencs(CommandInterpreter ci) {
1748 String st = ci.nextArgument();
1750 ci.println("Please enter node id");
1754 Node node = Node.fromString(st);
1756 ci.println("Please enter node id");
1760 Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node);
1761 if (nodeConnectorSet == null) {
1764 for (NodeConnector nodeConnector : nodeConnectorSet) {
1765 if (nodeConnector == null) {
1768 ci.println(nodeConnector);
1770 ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1773 public void _pncs(CommandInterpreter ci) {
1774 String st = ci.nextArgument();
1776 ci.println("Please enter node id");
1780 Node node = Node.fromString(st);
1782 ci.println("Please enter node id");
1786 ci.println(" NodeConnector BandWidth(Gbps) Admin State");
1787 Set<NodeConnector> nodeConnectorSet = getNodeConnectors(node);
1788 if (nodeConnectorSet == null) {
1791 for (NodeConnector nodeConnector : nodeConnectorSet) {
1792 if (nodeConnector == null) {
1795 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1796 Bandwidth bw = (Bandwidth) propMap.get(Bandwidth.BandwidthPropName);
1797 Config config = (Config) propMap.get(Config.ConfigPropName);
1798 State state = (State) propMap.get(State.StatePropName);
1799 String out = nodeConnector + " ";
1800 out += (bw != null) ? bw.getValue() / Math.pow(10, 9) : " ";
1802 out += (config != null) ? config.getValue() : " ";
1804 out += (state != null) ? state.getValue() : " ";
1807 ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1810 public void _pdm(CommandInterpreter ci) {
1811 String st = ci.nextArgument();
1813 ci.println("Please enter node id");
1817 Node node = Node.fromString(st);
1819 ci.println("Please enter node id");
1823 Switch sw = getSwitchByNode(node);
1825 ci.println(" NodeConnector Name");
1829 Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors();
1830 String nodeConnectorName;
1831 if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
1832 for (NodeConnector nodeConnector : nodeConnectorSet) {
1833 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1834 nodeConnectorName = (propMap == null) ? null : ((Name) propMap
1835 .get(Name.NamePropName)).getValue();
1836 if (nodeConnectorName != null) {
1837 Node nd = nodeConnector.getNode();
1838 if (!nd.equals(node)) {
1839 log.debug("node not match {} {}", nd, node);
1841 Map<String, NodeConnector> map = nodeConnectorNames
1844 NodeConnector nc = map.get(nodeConnectorName);
1846 log.debug("no nodeConnector named {}",
1848 } else if (!nc.equals(nodeConnector)) {
1849 log.debug("nodeConnector not match {} {}", nc,
1855 ci.println(nodeConnector
1857 + ((nodeConnectorName == null) ? "" : nodeConnectorName)
1858 + "(" + nodeConnector.getID() + ")");
1860 ci.println("Total number of NodeConnectors: "
1861 + nodeConnectorSet.size());
1865 public void _snt(CommandInterpreter ci) {
1866 String st = ci.nextArgument();
1868 ci.println("Please enter node id");
1872 Node node = Node.fromString(st);
1874 ci.println("Please enter node id");
1878 st = ci.nextArgument();
1880 ci.println("Please enter tier number");
1883 Integer tid = Integer.decode(st);
1884 Tier tier = new Tier(tid);
1885 setNodeProp(node, tier);
1888 public void _hostRefresh(CommandInterpreter ci) {
1889 String mode = ci.nextArgument();
1891 ci.println("expecting on/off/?");
1894 if (mode.toLowerCase().equals("on")) {
1896 } else if (mode.toLowerCase().equals("off")) {
1897 hostRefresh = false;
1898 } else if (mode.equals("?")) {
1900 ci.println("host refresh is ON");
1902 ci.println("host refresh is OFF");
1905 ci.println("expecting on/off/?");
1910 public void _hostRetry(CommandInterpreter ci) {
1911 String retry = ci.nextArgument();
1912 if (retry == null) {
1913 ci.println("Please enter a valid number. Current retry count is "
1918 hostRetryCount = Integer.parseInt(retry);
1919 } catch (Exception e) {
1920 ci.println("Please enter a valid number");
1926 public byte[] getNodeMAC(Node node) {
1927 MacAddress mac = (MacAddress) this.getNodeProp(node,
1929 return (mac != null) ? mac.getMacAddress() : null;
1933 public boolean isSpecial(NodeConnector p) {
1934 if (p.getType().equals(NodeConnectorIDType.CONTROLLER)
1935 || p.getType().equals(NodeConnectorIDType.ALL)
1936 || p.getType().equals(NodeConnectorIDType.SWSTACK)
1937 || p.getType().equals(NodeConnectorIDType.HWPATH)) {
1944 * Add span configuration to local cache and notify clients
1946 private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
1947 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1949 for (NodeConnector nodeConnector : nodeConnectors) {
1950 if (!spanNodeConnectors.contains(nodeConnector)) {
1951 ncLists.add(nodeConnector);
1955 if (ncLists.size() > 0) {
1956 spanNodeConnectors.addAll(ncLists);
1957 notifySpanPortChange(node, ncLists, true);
1961 private void addSpanPorts(Node node) {
1962 for (SpanConfig conf : getSpanConfigList(node)) {
1963 addSpanPorts(node, conf.getPortArrayList());
1967 private void addSpanPort(NodeConnector nodeConnector) {
1968 // only add if span is configured on this nodeConnector
1969 for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) {
1970 if (conf.getPortArrayList().contains(nodeConnector)) {
1971 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1972 ncLists.add(nodeConnector);
1973 addSpanPorts(nodeConnector.getNode(), ncLists);
1980 * Remove span configuration to local cache and notify clients
1982 private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
1983 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1985 for (NodeConnector nodeConnector : nodeConnectors) {
1986 if (spanNodeConnectors.contains(nodeConnector)) {
1987 ncLists.add(nodeConnector);
1991 if (ncLists.size() > 0) {
1992 spanNodeConnectors.removeAll(ncLists);
1993 notifySpanPortChange(node, ncLists, false);
1997 private void removeSpanPorts(Node node) {
1998 for (SpanConfig conf : getSpanConfigList(node)) {
1999 addSpanPorts(node, conf.getPortArrayList());
2003 private void removeSpanPort(NodeConnector nodeConnector) {
2004 if (spanNodeConnectors.contains(nodeConnector)) {
2005 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2006 ncLists.add(nodeConnector);
2007 removeSpanPorts(nodeConnector.getNode(), ncLists);
2011 private void addNodeProps(Node node, Map<String, Property> propMap) {
2012 if (propMap == null) {
2013 propMap = new HashMap<String, Property>();
2015 nodeProps.put(node, propMap);
2018 private void removeNodeProps(Node node) {
2019 if (getUpNodeConnectors(node).size() == 0) {
2020 nodeProps.remove(node);
2025 public Status saveConfiguration() {
2026 return saveSwitchConfig();
2030 * Creates a Name/Tier/Bandwidth Property object based on given property
2031 * name and value. Other property types are not supported yet.
2034 * Name of the Property
2036 * Value of the Property
2037 * @return {@link org.opendaylight.controller.sal.core.Property}
2040 public Property createProperty(String propName, String propValue) {
2041 if (propName == null) {
2042 log.debug("propName is null");
2045 if (propValue == null) {
2046 log.debug("propValue is null");
2051 if (propName.equalsIgnoreCase(Description.propertyName)) {
2052 return new Description(propValue);
2053 } else if (propName.equalsIgnoreCase(Tier.TierPropName)) {
2054 int tier = Integer.parseInt(propValue);
2055 return new Tier(tier);
2056 } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) {
2057 long bw = Long.parseLong(propValue);
2058 return new Bandwidth(bw);
2059 } else if (propName.equalsIgnoreCase(ForwardingMode.name)) {
2060 int mode = Integer.parseInt(propValue);
2061 return new ForwardingMode(mode);
2063 log.debug("Not able to create {} property", propName);
2065 } catch (Exception e) {
2066 log.debug("createProperty caught exception {}", e.getMessage());
2073 public String getNodeDescription(Node node) {
2074 // Check first if user configured a name
2075 SwitchConfig config = getSwitchConfig(node.toString());
2076 if (config != null) {
2077 String configuredDesc = config.getNodeDescription();
2078 if (configuredDesc != null && !configuredDesc.isEmpty()) {
2079 return configuredDesc;
2083 // No name configured by user, get the node advertised name
2084 Description desc = (Description) getNodeProp(node,
2085 Description.propertyName);
2086 return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? ""