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.Dictionary;
20 import java.util.EnumSet;
21 import java.util.Enumeration;
22 import java.util.HashMap;
23 import java.util.HashSet;
24 import java.util.List;
27 import java.util.concurrent.ConcurrentHashMap;
28 import java.util.concurrent.ConcurrentMap;
29 import java.util.concurrent.CopyOnWriteArrayList;
31 import org.apache.felix.dm.Component;
32 import org.eclipse.osgi.framework.console.CommandInterpreter;
33 import org.eclipse.osgi.framework.console.CommandProvider;
34 import org.opendaylight.controller.clustering.services.CacheConfigException;
35 import org.opendaylight.controller.clustering.services.CacheExistException;
36 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
37 import org.opendaylight.controller.clustering.services.IClusterServices;
38 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
39 import org.opendaylight.controller.sal.core.Bandwidth;
40 import org.opendaylight.controller.sal.core.Config;
41 import org.opendaylight.controller.sal.core.ConstructionException;
42 import org.opendaylight.controller.sal.core.Description;
43 import org.opendaylight.controller.sal.core.ForwardingMode;
44 import org.opendaylight.controller.sal.core.MacAddress;
45 import org.opendaylight.controller.sal.core.Name;
46 import org.opendaylight.controller.sal.core.Node;
47 import org.opendaylight.controller.sal.core.NodeConnector;
48 import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType;
49 import org.opendaylight.controller.sal.core.Property;
50 import org.opendaylight.controller.sal.core.State;
51 import org.opendaylight.controller.sal.core.Tier;
52 import org.opendaylight.controller.sal.core.UpdateType;
53 import org.opendaylight.controller.sal.inventory.IInventoryService;
54 import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates;
55 import org.opendaylight.controller.sal.reader.NodeDescription;
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.Status;
62 import org.opendaylight.controller.sal.utils.StatusCode;
63 import org.opendaylight.controller.statisticsmanager.IStatisticsManager;
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 SwitchManager implements ISwitchManager, IConfigurationContainerAware,
87 IObjectReader, IListenInventoryUpdates, CommandProvider {
88 private static Logger log = LoggerFactory.getLogger(SwitchManager.class);
89 private static String ROOT = GlobalConstants.STARTUPHOME.toString();
90 private String subnetFileName, spanFileName, switchConfigFileName;
91 private final List<NodeConnector> spanNodeConnectors = new CopyOnWriteArrayList<NodeConnector>();
92 // Collection of Subnets keyed by the InetAddress
93 private ConcurrentMap<InetAddress, Subnet> subnets;
94 private ConcurrentMap<String, SubnetConfig> subnetsConfigList;
95 private ConcurrentMap<SpanConfig, SpanConfig> spanConfigList;
96 // manually configured parameters for the node such as name, tier, mode
97 private ConcurrentMap<String, SwitchConfig> nodeConfigList;
98 private ConcurrentMap<Node, Map<String, Property>> nodeProps;
99 private ConcurrentMap<NodeConnector, Map<String, Property>> nodeConnectorProps;
100 private ConcurrentMap<Node, Map<String, NodeConnector>> nodeConnectorNames;
101 private ConcurrentMap<String, Property> controllerProps;
102 private IInventoryService inventoryService;
103 private IStatisticsManager statisticsManager;
104 private final Set<ISwitchManagerAware> switchManagerAware = Collections
105 .synchronizedSet(new HashSet<ISwitchManagerAware>());
106 private final Set<IInventoryListener> inventoryListeners = Collections
107 .synchronizedSet(new HashSet<IInventoryListener>());
108 private final Set<ISpanAware> spanAware = Collections.synchronizedSet(new HashSet<ISpanAware>());
109 private static boolean hostRefresh = true;
110 private int hostRetryCount = 5;
111 private IClusterContainerServices clusterContainerService = null;
112 private String containerName = null;
113 private boolean isDefaultContainer = true;
114 private static final int REPLACE_RETRY = 1;
116 public void notifySubnetChange(Subnet sub, boolean add) {
117 synchronized (switchManagerAware) {
118 for (Object subAware : switchManagerAware) {
120 ((ISwitchManagerAware) subAware).subnetNotify(sub, add);
121 } catch (Exception e) {
122 log.error("Failed to notify Subnet change {}",
129 public void notifySpanPortChange(Node node, List<NodeConnector> ports, boolean add) {
130 synchronized (spanAware) {
131 for (Object sa : spanAware) {
133 ((ISpanAware) sa).spanUpdate(node, ports, add);
134 } catch (Exception e) {
135 log.error("Failed to notify Span Interface change {}",
142 private void notifyModeChange(Node node, boolean proactive) {
143 synchronized (switchManagerAware) {
144 for (ISwitchManagerAware service : switchManagerAware) {
146 service.modeChangeNotify(node, proactive);
147 } catch (Exception e) {
148 log.error("Failed to notify Subnet change {}",
155 public void startUp() {
156 String container = this.getContainerName();
157 // Initialize configuration file names
158 subnetFileName = ROOT + "subnets_" + container + ".conf";
159 spanFileName = ROOT + "spanPorts_" + container + ".conf";
160 switchConfigFileName = ROOT + "switchConfig_" + container + ".conf";
162 // Instantiate cluster synced variables
167 * Read startup and build database if we have not already gotten the
168 * configurations synced from another node
170 if (subnetsConfigList.isEmpty()) {
171 loadSubnetConfiguration();
173 if (spanConfigList.isEmpty()) {
174 loadSpanConfiguration();
176 if (nodeConfigList.isEmpty()) {
177 loadSwitchConfiguration();
180 // Add controller MAC, if first node in the cluster
181 if (!controllerProps.containsKey(MacAddress.name)) {
182 byte controllerMac[] = getHardwareMAC();
183 if (controllerMac != null) {
184 Property existing = controllerProps.putIfAbsent(MacAddress.name, new MacAddress(controllerMac));
185 if (existing == null && log.isTraceEnabled()) {
186 log.trace("Container {}: Setting controller MAC address in the cluster: {}", container,
187 HexEncode.bytesToHexStringFormat(controllerMac));
193 public void shutDown() {
196 @SuppressWarnings("deprecation")
197 private void allocateCaches() {
198 if (this.clusterContainerService == null) {
199 this.nonClusterObjectCreate();
200 log.warn("un-initialized clusterContainerService, can't create cache");
205 clusterContainerService.createCache(
206 "switchmanager.subnetsConfigList",
207 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
208 clusterContainerService.createCache("switchmanager.spanConfigList",
209 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
210 clusterContainerService.createCache("switchmanager.nodeConfigList",
211 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
212 clusterContainerService.createCache("switchmanager.subnets",
213 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
214 clusterContainerService.createCache(
215 "switchmanager.configSaveEvent",
216 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
217 clusterContainerService.createCache("switchmanager.nodeProps",
218 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
219 clusterContainerService.createCache(
220 "switchmanager.nodeConnectorProps",
221 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
222 clusterContainerService.createCache(
223 "switchmanager.nodeConnectorNames",
224 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
225 clusterContainerService.createCache(
226 "switchmanager.controllerProps",
227 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
228 } catch (CacheConfigException cce) {
229 log.error("\nCache configuration invalid - check cache mode");
230 } catch (CacheExistException ce) {
231 log.error("\nCache already exits - destroy and recreate if needed");
235 @SuppressWarnings({ "unchecked", "deprecation" })
236 private void retrieveCaches() {
237 if (this.clusterContainerService == null) {
238 log.info("un-initialized clusterContainerService, can't create cache");
242 subnetsConfigList = (ConcurrentMap<String, SubnetConfig>) clusterContainerService
243 .getCache("switchmanager.subnetsConfigList");
244 if (subnetsConfigList == null) {
245 log.error("\nFailed to get cache for subnetsConfigList");
248 spanConfigList = (ConcurrentMap<SpanConfig, SpanConfig>) clusterContainerService
249 .getCache("switchmanager.spanConfigList");
250 if (spanConfigList == null) {
251 log.error("\nFailed to get cache for spanConfigList");
254 nodeConfigList = (ConcurrentMap<String, SwitchConfig>) clusterContainerService
255 .getCache("switchmanager.nodeConfigList");
256 if (nodeConfigList == null) {
257 log.error("\nFailed to get cache for nodeConfigList");
260 subnets = (ConcurrentMap<InetAddress, Subnet>) clusterContainerService
261 .getCache("switchmanager.subnets");
262 if (subnets == null) {
263 log.error("\nFailed to get cache for subnets");
266 nodeProps = (ConcurrentMap<Node, Map<String, Property>>) clusterContainerService
267 .getCache("switchmanager.nodeProps");
268 if (nodeProps == null) {
269 log.error("\nFailed to get cache for nodeProps");
272 nodeConnectorProps = (ConcurrentMap<NodeConnector, Map<String, Property>>) clusterContainerService
273 .getCache("switchmanager.nodeConnectorProps");
274 if (nodeConnectorProps == null) {
275 log.error("\nFailed to get cache for nodeConnectorProps");
278 nodeConnectorNames = (ConcurrentMap<Node, Map<String, NodeConnector>>) clusterContainerService
279 .getCache("switchmanager.nodeConnectorNames");
280 if (nodeConnectorNames == null) {
281 log.error("\nFailed to get cache for nodeConnectorNames");
284 controllerProps = (ConcurrentMap<String, Property>) clusterContainerService
285 .getCache("switchmanager.controllerProps");
286 if (controllerProps == null) {
287 log.error("\nFailed to get cache for controllerProps");
291 private void nonClusterObjectCreate() {
292 subnetsConfigList = new ConcurrentHashMap<String, SubnetConfig>();
293 spanConfigList = new ConcurrentHashMap<SpanConfig, SpanConfig>();
294 nodeConfigList = new ConcurrentHashMap<String, SwitchConfig>();
295 subnets = new ConcurrentHashMap<InetAddress, Subnet>();
296 nodeProps = new ConcurrentHashMap<Node, Map<String, Property>>();
297 nodeConnectorProps = new ConcurrentHashMap<NodeConnector, Map<String, Property>>();
298 nodeConnectorNames = new ConcurrentHashMap<Node, Map<String, NodeConnector>>();
299 controllerProps = new ConcurrentHashMap<String, Property>();
303 public List<SubnetConfig> getSubnetsConfigList() {
304 return new ArrayList<SubnetConfig>(subnetsConfigList.values());
308 public SubnetConfig getSubnetConfig(String subnet) {
309 return subnetsConfigList.get(subnet);
312 private List<SpanConfig> getSpanConfigList(Node node) {
313 List<SpanConfig> confList = new ArrayList<SpanConfig>();
314 String nodeId = node.toString();
315 for (SpanConfig conf : spanConfigList.values()) {
316 if (conf.matchNode(nodeId)) {
323 public List<SwitchConfig> getNodeConfigList() {
324 return new ArrayList<SwitchConfig>(nodeConfigList.values());
328 public SwitchConfig getSwitchConfig(String switchId) {
329 return nodeConfigList.get(switchId);
332 public Switch getSwitchByNode(Node node) {
333 Switch sw = new Switch(node);
335 MacAddress mac = (MacAddress) this.getNodeProp(node,
338 sw.setDataLayerAddress(mac.getMacAddress());
340 Set<NodeConnector> ncSet = getPhysicalNodeConnectors(node);
341 sw.setNodeConnectors(ncSet);
343 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
344 for (NodeConnector nodeConnector : ncSet) {
345 if (spanNodeConnectors.contains(nodeConnector)) {
346 ncList.add(nodeConnector);
349 sw.addSpanPorts(ncList);
355 public List<Switch> getNetworkDevices() {
356 Set<Node> nodeSet = getNodes();
357 List<Switch> swList = new ArrayList<Switch>();
358 if (nodeSet != null) {
359 for (Node node : nodeSet) {
360 swList.add(getSwitchByNode(node));
367 private Status updateConfig(SubnetConfig conf, boolean add) {
369 if(subnetsConfigList.putIfAbsent(conf.getName(), conf) != null) {
370 String msg = "Cluster conflict: Subnet with name " + conf.getName() + "already exists.";
371 return new Status(StatusCode.CONFLICT, msg);
374 subnetsConfigList.remove(conf.getName());
376 return new Status(StatusCode.SUCCESS);
379 private Status updateDatabase(SubnetConfig conf, boolean add) {
381 Subnet subnetCurr = subnets.get(conf.getIPnum());
383 if (subnetCurr == null) {
384 subnet = new Subnet(conf);
386 subnet = subnetCurr.clone();
388 // In case of API3 call we may receive the ports along with the
390 if (!conf.isGlobal()) {
391 Set<NodeConnector> sp = conf.getSubnetNodeConnectors();
392 subnet.addNodeConnectors(sp);
394 boolean putNewSubnet = false;
395 if(subnetCurr == null) {
396 if(subnets.putIfAbsent(conf.getIPnum(), subnet) == null) {
400 putNewSubnet = subnets.replace(conf.getIPnum(), subnetCurr, subnet);
403 String msg = "Cluster conflict: Conflict while adding the subnet " + conf.getIPnum();
404 return new Status(StatusCode.CONFLICT, msg);
407 // Subnet removal case
409 subnets.remove(conf.getIPnum());
411 return new Status(StatusCode.SUCCESS);
414 private Status semanticCheck(SubnetConfig conf) {
415 Subnet newSubnet = new Subnet(conf);
416 Set<InetAddress> IPs = subnets.keySet();
418 return new Status(StatusCode.SUCCESS);
420 for (InetAddress i : IPs) {
421 Subnet existingSubnet = subnets.get(i);
422 if ((existingSubnet != null)
423 && !existingSubnet.isMutualExclusive(newSubnet)) {
424 return new Status(StatusCode.CONFLICT);
427 return new Status(StatusCode.SUCCESS);
430 private Status addRemoveSubnet(SubnetConfig conf, boolean isAdding) {
431 // Valid config check
432 if (!conf.isValidConfig()) {
433 String msg = "Invalid Subnet configuration";
435 return new Status(StatusCode.BADREQUEST, msg);
440 if (subnetsConfigList.containsKey(conf.getName())) {
441 return new Status(StatusCode.CONFLICT,
442 "Subnet with the specified name already configured.");
445 Status rc = semanticCheck(conf);
446 if (!rc.isSuccess()) {
452 Status rc = updateDatabase(conf, isAdding);
454 if (rc.isSuccess()) {
455 // Update Configuration
456 rc = updateConfig(conf, isAdding);
457 if(!rc.isSuccess()) {
458 updateDatabase(conf, (!isAdding));
466 * Adds Subnet configured in GUI or API3
469 public Status addSubnet(SubnetConfig conf) {
470 return this.addRemoveSubnet(conf, true);
474 public Status removeSubnet(SubnetConfig conf) {
475 return this.addRemoveSubnet(conf, false);
479 public Status removeSubnet(String name) {
480 SubnetConfig conf = subnetsConfigList.get(name);
482 return new Status(StatusCode.SUCCESS, "Subnet not present");
484 return this.addRemoveSubnet(conf, false);
488 public Status addPortsToSubnet(String name, String switchPorts) {
489 SubnetConfig confCurr = subnetsConfigList.get(name);
490 if (confCurr == null) {
491 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
493 if (!confCurr.isValidSwitchPort(switchPorts)) {
494 return new Status(StatusCode.BADREQUEST, "Invalid switchports");
497 Subnet subCurr = subnets.get(confCurr.getIPnum());
498 if (subCurr == null) {
499 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPnum());
500 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
504 Subnet sub = subCurr.clone();
505 Set<NodeConnector> sp = confCurr.getNodeConnectors(switchPorts);
506 sub.addNodeConnectors(sp);
507 boolean subnetsReplaced = subnets.replace(confCurr.getIPnum(), subCurr, sub);
508 if (!subnetsReplaced) {
509 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
510 return new Status(StatusCode.CONFLICT, msg);
513 // Update Configuration
514 SubnetConfig conf = confCurr.clone();
515 conf.addNodeConnectors(switchPorts);
516 boolean configReplaced = subnetsConfigList.replace(name, confCurr, conf);
517 if (!configReplaced) {
518 // TODO: recovery using Transactionality
519 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
520 return new Status(StatusCode.CONFLICT, msg);
523 return new Status(StatusCode.SUCCESS);
527 public Status removePortsFromSubnet(String name, String switchPorts) {
528 SubnetConfig confCurr = subnetsConfigList.get(name);
529 if (confCurr == null) {
530 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
533 Subnet subCurr = subnets.get(confCurr.getIPnum());
534 if (subCurr == null) {
535 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPnum());
536 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
540 Subnet sub = subCurr.clone();
541 Set<NodeConnector> sp = confCurr.getNodeConnectors(switchPorts);
542 sub.deleteNodeConnectors(sp);
543 boolean subnetsReplace = subnets.replace(confCurr.getIPnum(), subCurr, sub);
544 if (!subnetsReplace) {
545 String msg = "Cluster conflict: Conflict while removing ports from the subnet " + name;
546 return new Status(StatusCode.CONFLICT, msg);
549 // Update Configuration
550 SubnetConfig conf = confCurr.clone();
551 conf.removeNodeConnectors(switchPorts);
552 boolean result = subnetsConfigList.replace(name, confCurr, conf);
554 // TODO: recovery using Transactionality
555 String msg = "Cluster conflict: Conflict while removing ports from " + conf;
556 return new Status(StatusCode.CONFLICT, msg);
559 return new Status(StatusCode.SUCCESS);
562 public String getContainerName() {
563 if (containerName == null) {
564 return GlobalConstants.DEFAULT.toString();
566 return containerName;
570 public Subnet getSubnetByNetworkAddress(InetAddress networkAddress) {
572 Set<InetAddress> indices = subnets.keySet();
573 for (InetAddress i : indices) {
574 sub = subnets.get(i);
575 if (sub.isSubnetOf(networkAddress)) {
583 public Object readObject(ObjectInputStream ois)
584 throws FileNotFoundException, IOException, ClassNotFoundException {
585 // Perform the class deserialization locally, from inside the package
586 // where the class is defined
587 return ois.readObject();
590 @SuppressWarnings("unchecked")
591 private void loadSubnetConfiguration() {
592 ObjectReader objReader = new ObjectReader();
593 ConcurrentMap<String, SubnetConfig> confList = (ConcurrentMap<String, SubnetConfig>) objReader
594 .read(this, subnetFileName);
596 if (confList == null) {
600 for (SubnetConfig conf : confList.values()) {
605 @SuppressWarnings("unchecked")
606 private void loadSpanConfiguration() {
607 ObjectReader objReader = new ObjectReader();
608 ConcurrentMap<Integer, SpanConfig> confList = (ConcurrentMap<Integer, SpanConfig>) objReader
609 .read(this, spanFileName);
611 if (confList == null) {
615 for (SpanConfig conf : confList.values()) {
620 @SuppressWarnings("unchecked")
621 private void loadSwitchConfiguration() {
622 ObjectReader objReader = new ObjectReader();
623 ConcurrentMap<String, SwitchConfig> confList = (ConcurrentMap<String, SwitchConfig>) objReader
624 .read(this, switchConfigFileName);
626 if (confList == null) {
630 for (SwitchConfig conf : confList.values()) {
631 updateNodeConfig(conf);
636 public void updateSwitchConfig(SwitchConfig cfgObject) {
637 // update default container only
638 if (!isDefaultContainer) {
642 SwitchConfig sc = nodeConfigList.get(cfgObject.getNodeId());
644 if (nodeConfigList.putIfAbsent(cfgObject.getNodeId(), cfgObject) != null) {
648 if (!nodeConfigList.replace(cfgObject.getNodeId(), sc, cfgObject)) {
653 boolean modeChange = false;
655 if ((sc == null) || !cfgObject.getMode().equals(sc.getMode())) {
659 String nodeId = cfgObject.getNodeId();
660 Node node = Node.fromString(nodeId);
661 Map<String, Property> propMapCurr = nodeProps.get(node);
662 if (propMapCurr == null) {
665 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
666 Property desc = new Description(cfgObject.getNodeDescription());
667 propMap.put(desc.getName(), desc);
668 Property tier = new Tier(Integer.parseInt(cfgObject.getTier()));
669 propMap.put(tier.getName(), tier);
671 if (!nodeProps.replace(node, propMapCurr, propMap)) {
672 // TODO rollback using Transactionality
676 log.info("Set Node {}'s Mode to {}", nodeId, cfgObject.getMode());
679 notifyModeChange(node, cfgObject.isProactive());
684 public Status updateNodeConfig(SwitchConfig switchConfig) {
685 Status status = switchConfig.validate();
686 if (!status.isSuccess()) {
690 Map<String, Property> updateProperties = switchConfig.getNodeProperties();
691 ForwardingMode mode = (ForwardingMode) updateProperties.get(ForwardingMode.name);
693 if (isDefaultContainer) {
694 if (!mode.isValid()) {
695 return new Status(StatusCode.BADREQUEST, "Invalid Forwarding Mode Value");
698 return new Status(StatusCode.NOTACCEPTABLE,
699 "Forwarding Mode modification is allowed only in default container");
703 Description description = (Description) switchConfig.getProperty(Description.propertyName);
704 String nodeId = switchConfig.getNodeId();
705 Node node = Node.fromString(nodeId);
706 NodeDescription nodeDesc = (this.statisticsManager == null) ? null : this.statisticsManager
707 .getNodeDescription(node);
708 String advertisedDesc = (nodeDesc == null) ? "" : nodeDesc.getDescription();
709 if (description != null && description.getValue() != null) {
710 if (description.getValue().isEmpty() || description.getValue().equals(advertisedDesc)) {
711 updateProperties.remove(Description.propertyName);
712 switchConfig = new SwitchConfig(nodeId, updateProperties);
714 // check if description is configured or was published by any other node
715 for (Map.Entry<Node, Map<String, Property>> entry : nodeProps.entrySet()) {
716 Node n = entry.getKey();
717 Description desc = (Description) getNodeProp(n, Description.propertyName);
718 NodeDescription nDesc = (this.statisticsManager == null) ? null : this.statisticsManager
719 .getNodeDescription(n);
720 String advDesc = (nDesc == null) ? "" : nDesc.getDescription();
721 if ((description.equals(desc) || description.getValue().equals(advDesc)) && !node.equals(n)) {
722 return new Status(StatusCode.CONFLICT, "Node name already in use");
728 boolean modeChange = false;
729 SwitchConfig sc = nodeConfigList.get(nodeId);
730 Map<String, Property> prevNodeProperties = new HashMap<String, Property>();
732 if ((mode != null) && mode.isProactive()) {
735 if (!updateProperties.isEmpty()) {
736 if (nodeConfigList.putIfAbsent(nodeId, switchConfig) != null) {
737 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
741 prevNodeProperties = new HashMap<String, Property>(sc.getNodeProperties());
742 ForwardingMode prevMode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
744 if ((prevMode != null) && (prevMode.isProactive())) {
748 if (((prevMode != null) && (prevMode.getValue() != mode.getValue()))
749 || (prevMode == null && mode.isProactive())) {
753 if (updateProperties.isEmpty()) {
754 nodeConfigList.remove(nodeId);
756 if (!nodeConfigList.replace(nodeId, sc, switchConfig)) {
757 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
761 Map<String, Property> propMapCurr = nodeProps.get(node);
762 if (propMapCurr == null) {
763 return new Status(StatusCode.SUCCESS);
765 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
766 for (Map.Entry<String, Property> entry : prevNodeProperties.entrySet()) {
767 String prop = entry.getKey();
768 if (!updateProperties.containsKey(prop)) {
769 if (prop.equals(Description.propertyName)) {
770 if (!advertisedDesc.isEmpty()) {
771 Property desc = new Description(advertisedDesc);
772 propMap.put(Description.propertyName, desc);
776 propMap.remove(prop);
779 propMap.putAll(updateProperties);
780 if (!nodeProps.replace(node, propMapCurr, propMap)) {
781 // TODO rollback using Transactionality
782 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
785 notifyModeChange(node, (mode == null) ? false : mode.isProactive());
787 return new Status(StatusCode.SUCCESS);
791 public Status removeNodeConfig(String nodeId) {
792 if ((nodeId == null) || (nodeId.isEmpty())) {
793 return new Status(StatusCode.BADREQUEST, "nodeId cannot be empty.");
795 Map<String, Property> nodeProperties = getSwitchConfig(nodeId).getNodeProperties();
796 Node node = Node.fromString(nodeId);
797 Map<String, Property> propMapCurr = nodeProps.get(node);
798 if ((propMapCurr != null) && (nodeProperties != null) && (!nodeProperties.isEmpty())) {
799 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
800 for (Map.Entry<String, Property> entry : nodeProperties.entrySet()) {
801 String prop = entry.getKey();
802 if (prop.equals(Description.propertyName)) {
803 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
804 if (nodeProp.get(node) != null) {
805 propMap.put(Description.propertyName, nodeProp.get(node).get(Description.propertyName));
809 propMap.remove(prop);
811 if (!nodeProps.replace(node, propMapCurr, propMap)) {
812 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration.");
815 if (nodeConfigList != null) {
816 nodeConfigList.remove(nodeId);
818 return new Status(StatusCode.SUCCESS);
822 public Status saveSwitchConfig() {
823 return saveSwitchConfigInternal();
826 public Status saveSwitchConfigInternal() {
827 Status retS = null, retP = null;
828 ObjectWriter objWriter = new ObjectWriter();
830 retS = objWriter.write(new ConcurrentHashMap<String, SubnetConfig>(
831 subnetsConfigList), subnetFileName);
832 retP = objWriter.write(new ConcurrentHashMap<SpanConfig, SpanConfig>(
833 spanConfigList), spanFileName);
834 retS = objWriter.write(new ConcurrentHashMap<String, SwitchConfig>(
835 nodeConfigList), switchConfigFileName);
836 if (retS.equals(retP)) {
837 if (retS.isSuccess()) {
840 return new Status(StatusCode.INTERNALERROR, "Save failed");
843 return new Status(StatusCode.INTERNALERROR, "Partial save failure");
848 public List<SpanConfig> getSpanConfigList() {
849 return new ArrayList<SpanConfig>(spanConfigList.values());
853 public Status addSpanConfig(SpanConfig conf) {
854 // Valid config check
855 if (!conf.isValidConfig()) {
856 String msg = "Invalid Span configuration";
858 return new Status(StatusCode.BADREQUEST, msg);
862 if (spanConfigList.containsKey(conf)) {
863 return new Status(StatusCode.CONFLICT, "Same span config exists");
866 // Update configuration
867 if (spanConfigList.putIfAbsent(conf, conf) == null) {
868 // Update database and notify clients
869 addSpanPorts(conf.getNode(), conf.getPortArrayList());
872 return new Status(StatusCode.SUCCESS);
876 public Status removeSpanConfig(SpanConfig conf) {
877 removeSpanPorts(conf.getNode(), conf.getPortArrayList());
879 // Update configuration
880 spanConfigList.remove(conf);
882 return new Status(StatusCode.SUCCESS);
886 public List<NodeConnector> getSpanPorts(Node node) {
887 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
889 for (NodeConnector nodeConnector : spanNodeConnectors) {
890 if (nodeConnector.getNode().equals(node)) {
891 ncList.add(nodeConnector);
897 private void addNode(Node node, Set<Property> props) {
898 log.trace("{} added, props: {}", node, props);
899 if (nodeProps == null) {
903 Map<String, Property> propMapCurr = nodeProps.get(node);
904 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
905 : new HashMap<String, Property>(propMapCurr);
907 // copy node properties from plugin
909 for (Property prop : props) {
910 propMap.put(prop.getName(), prop);
914 // copy node properties from config
915 boolean proactiveForwarding = false;
916 if (nodeConfigList != null) {
917 String nodeId = node.toString();
918 SwitchConfig conf = nodeConfigList.get(nodeId);
919 if (conf != null && (conf.getNodeProperties() != null)) {
920 Map<String, Property> nodeProperties = conf.getNodeProperties();
921 propMap.putAll(nodeProperties);
922 if (nodeProperties.get(ForwardingMode.name) != null) {
923 ForwardingMode mode = (ForwardingMode) nodeProperties.get(ForwardingMode.name);
924 proactiveForwarding = mode.isProactive();
929 boolean result = false;
930 if (propMapCurr == null) {
931 if (nodeProps.putIfAbsent(node, propMap) == null) {
935 result = nodeProps.replace(node, propMapCurr, propMap);
938 log.debug("Cluster conflict: Conflict while adding the node properties. Node: {} Properties: {}",
939 node.getID(), props);
940 addNodeProps(node, propMap);
943 // check if span ports are configed
946 // notify node listeners
947 notifyNode(node, UpdateType.ADDED, propMap);
949 // notify proactive mode forwarding
950 if (proactiveForwarding) {
951 notifyModeChange(node, true);
955 private void removeNode(Node node) {
956 log.trace("{} removed", node);
957 if (nodeProps == null) {
960 nodeProps.remove(node);
961 nodeConnectorNames.remove(node);
962 Set<NodeConnector> removeNodeConnectorSet = new HashSet<NodeConnector>();
963 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
964 NodeConnector nodeConnector = entry.getKey();
965 if (nodeConnector.getNode().equals(node)) {
966 removeNodeConnectorSet.add(nodeConnector);
969 for (NodeConnector nc : removeNodeConnectorSet) {
970 nodeConnectorProps.remove(nc);
973 // check if span ports need to be cleaned up
974 removeSpanPorts(node);
976 /* notify node listeners */
977 notifyNode(node, UpdateType.REMOVED, null);
980 private void updateNode(Node node, Set<Property> props) {
981 log.trace("{} updated, props: {}", node, props);
982 if (nodeProps == null || !nodeProps.containsKey(node) ||
983 props == null || props.isEmpty()) {
987 Map<String, Property> propMapCurr = nodeProps.get(node);
988 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
989 : new HashMap<String, Property>(propMapCurr);
991 // copy node properties from plugin
992 String nodeId = node.toString();
993 for (Property prop : props) {
994 if (nodeConfigList != null) {
995 SwitchConfig conf = nodeConfigList.get(nodeId);
996 if (conf != null && (conf.getNodeProperties() != null)
997 && conf.getNodeProperties().containsKey(prop.getName())) {
1001 propMap.put(prop.getName(), prop);
1004 if (propMapCurr == null) {
1005 if (nodeProps.putIfAbsent(node, propMap) != null) {
1006 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1007 node.getID(), props);
1008 addNodeProps(node, propMap);
1011 if (!nodeProps.replace(node, propMapCurr, propMap)) {
1012 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1013 node.getID(), props);
1014 addNodeProps(node, propMap);
1018 /* notify node listeners */
1019 notifyNode(node, UpdateType.CHANGED, propMap);
1023 public void updateNode(Node node, UpdateType type, Set<Property> props) {
1024 log.debug("updateNode: {} type {} props {} for container {}",
1025 new Object[] { node, type, props, containerName });
1028 addNode(node, props);
1031 updateNode(node, props);
1042 public void updateNodeConnector(NodeConnector nodeConnector,
1043 UpdateType type, Set<Property> props) {
1044 Map<String, Property> propMap = new HashMap<String, Property>();
1045 boolean update = true;
1047 log.debug("updateNodeConnector: {} type {} props {} for container {}",
1048 new Object[] { nodeConnector, type, props, containerName });
1050 if (nodeConnectorProps == null) {
1056 if (props != null) {
1057 for (Property prop : props) {
1058 addNodeConnectorProp(nodeConnector, prop);
1059 propMap.put(prop.getName(), prop);
1062 addNodeConnectorProp(nodeConnector, null);
1065 addSpanPort(nodeConnector);
1068 if (!nodeConnectorProps.containsKey(nodeConnector) || (props == null)) {
1071 for (Property prop : props) {
1072 addNodeConnectorProp(nodeConnector, prop);
1073 propMap.put(prop.getName(), prop);
1078 if (!nodeConnectorProps.containsKey(nodeConnector)) {
1081 removeNodeConnectorAllProps(nodeConnector);
1083 // clean up span config
1084 removeSpanPort(nodeConnector);
1092 notifyNodeConnector(nodeConnector, type, propMap);
1097 public Set<Node> getNodes() {
1098 return (nodeProps != null) ? new HashSet<Node>(nodeProps.keySet())
1103 * Returns a copy of a list of properties for a given node
1108 * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps
1109 * (org.opendaylight.controller.sal.core.Node)
1112 public Map<String, Property> getNodeProps(Node node) {
1113 Map<String, Property> rv = new HashMap<String, Property>();
1114 if (this.nodeProps != null) {
1115 rv = this.nodeProps.get(node);
1117 /* make a copy of it */
1118 rv = new HashMap<String, Property>(rv);
1125 public Property getNodeProp(Node node, String propName) {
1126 Map<String, Property> propMap = getNodeProps(node);
1127 return (propMap != null) ? propMap.get(propName) : null;
1131 public void setNodeProp(Node node, Property prop) {
1133 for (int i = 0; i <= REPLACE_RETRY; i++) {
1134 /* Get a copy of the property map */
1135 Map<String, Property> propMapCurr = getNodeProps(node);
1136 if (propMapCurr == null) {
1140 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1141 propMap.put(prop.getName(), prop);
1143 if (nodeProps.replace(node, propMapCurr, propMap)) {
1146 if (!propMapCurr.get(prop.getName()).equals(nodeProps.get(node).get(prop.getName()))) {
1147 log.debug("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1151 log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1155 public Status removeNodeProp(Node node, String propName) {
1156 for (int i = 0; i <= REPLACE_RETRY; i++) {
1157 Map<String, Property> propMapCurr = getNodeProps(node);
1158 if (propMapCurr != null) {
1159 if (!propMapCurr.containsKey(propName)) {
1160 return new Status(StatusCode.SUCCESS);
1162 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1163 propMap.remove(propName);
1164 if (nodeProps.replace(node, propMapCurr, propMap)) {
1165 return new Status(StatusCode.SUCCESS);
1167 if (!propMapCurr.get(propName).equals(nodeProps.get(node).get(propName))) {
1168 String msg = "Cluster conflict: Unable to remove property " + propName + " for node "
1170 return new Status(StatusCode.CONFLICT, msg);
1174 return new Status(StatusCode.SUCCESS);
1177 String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID();
1178 return new Status(StatusCode.CONFLICT, msg);
1182 public Status removeNodeAllProps(Node node) {
1183 this.nodeProps.remove(node);
1184 return new Status(StatusCode.SUCCESS);
1188 public Set<NodeConnector> getUpNodeConnectors(Node node) {
1189 if (nodeConnectorProps == null) {
1193 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1194 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1195 NodeConnector nodeConnector = entry.getKey();
1196 if (!nodeConnector.getNode().equals(node)) {
1199 if (isNodeConnectorEnabled(nodeConnector)) {
1200 nodeConnectorSet.add(nodeConnector);
1204 return nodeConnectorSet;
1208 public Set<NodeConnector> getNodeConnectors(Node node) {
1209 if (nodeConnectorProps == null) {
1213 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1214 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1215 NodeConnector nodeConnector = entry.getKey();
1216 if (!nodeConnector.getNode().equals(node)) {
1219 nodeConnectorSet.add(nodeConnector);
1222 return nodeConnectorSet;
1226 public Set<NodeConnector> getPhysicalNodeConnectors(Node node) {
1227 if (nodeConnectorProps == null) {
1231 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1232 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1233 NodeConnector nodeConnector = entry.getKey();
1234 if (!nodeConnector.getNode().equals(node)
1235 || isSpecial(nodeConnector)) {
1238 nodeConnectorSet.add(nodeConnector);
1241 return nodeConnectorSet;
1245 public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) {
1246 Map<String, Property> rv = new HashMap<String, Property>();
1247 if (this.nodeConnectorProps != null) {
1248 rv = this.nodeConnectorProps.get(nodeConnector);
1250 rv = new HashMap<String, Property>(rv);
1257 public Property getNodeConnectorProp(NodeConnector nodeConnector,
1259 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1260 return (propMap != null) ? propMap.get(propName) : null;
1263 private byte[] getHardwareMAC() {
1264 Enumeration<NetworkInterface> nis;
1265 byte[] macAddress = null;
1268 nis = NetworkInterface.getNetworkInterfaces();
1269 } catch (SocketException e) {
1270 log.error("Failed to acquire controller MAC: ", e);
1274 while (nis.hasMoreElements()) {
1275 NetworkInterface ni = nis.nextElement();
1277 macAddress = ni.getHardwareAddress();
1278 } catch (SocketException e) {
1279 log.error("Failed to acquire controller MAC: ", e);
1281 if (macAddress != null) {
1285 if (macAddress == null) {
1286 log.warn("Failed to acquire controller MAC: No physical interface found");
1287 // This happens when running controller on windows VM, for example
1288 // Try parsing the OS command output
1294 public byte[] getControllerMAC() {
1295 MacAddress macProperty = (MacAddress)controllerProps.get(MacAddress.name);
1296 return (macProperty == null) ? null : macProperty.getMacAddress();
1300 public boolean isHostRefreshEnabled() {
1305 public int getHostRetryCount() {
1306 return hostRetryCount;
1310 public NodeConnector getNodeConnector(Node node, String nodeConnectorName) {
1311 if (nodeConnectorNames == null) {
1315 Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1320 return map.get(nodeConnectorName);
1324 * Adds a node connector and its property if any
1326 * @param nodeConnector
1327 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1329 * name of {@link org.opendaylight.controller.sal.core.Property}
1330 * @return success or failed reason
1333 public Status addNodeConnectorProp(NodeConnector nodeConnector,
1335 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1336 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1337 : new HashMap<String, Property>(propMapCurr);
1339 String msg = "Cluster conflict: Unable to add NodeConnector Property.";
1340 // Just add the nodeConnector if prop is not available (in a non-default
1343 if (propMapCurr == null) {
1344 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1345 return new Status(StatusCode.CONFLICT, msg);
1348 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1349 return new Status(StatusCode.CONFLICT, msg);
1352 return new Status(StatusCode.SUCCESS);
1355 propMap.put(prop.getName(), prop);
1356 if (propMapCurr == null) {
1357 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1358 return new Status(StatusCode.CONFLICT, msg);
1361 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1362 return new Status(StatusCode.CONFLICT, msg);
1366 if (prop.getName().equals(Name.NamePropName)) {
1367 if (nodeConnectorNames != null) {
1368 Node node = nodeConnector.getNode();
1369 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1370 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1371 if (mapCurr != null) {
1372 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1373 String s = entry.getKey();
1375 map.put(s, new NodeConnector(entry.getValue()));
1376 } catch (ConstructionException e) {
1377 e.printStackTrace();
1382 map.put(((Name) prop).getValue(), nodeConnector);
1383 if (mapCurr == null) {
1384 if (nodeConnectorNames.putIfAbsent(node, map) != null) {
1385 // TODO: recovery using Transactionality
1386 return new Status(StatusCode.CONFLICT, msg);
1389 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1390 // TODO: recovery using Transactionality
1391 return new Status(StatusCode.CONFLICT, msg);
1397 return new Status(StatusCode.SUCCESS);
1401 * Removes one property of a node connector
1403 * @param nodeConnector
1404 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1406 * name of {@link org.opendaylight.controller.sal.core.Property}
1407 * @return success or failed reason
1410 public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) {
1411 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1413 if (propMapCurr == null) {
1414 /* Nothing to remove */
1415 return new Status(StatusCode.SUCCESS);
1418 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1419 propMap.remove(propName);
1420 boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap);
1421 String msg = "Cluster conflict: Unable to remove NodeConnector property.";
1423 return new Status(StatusCode.CONFLICT, msg);
1426 if (propName.equals(Name.NamePropName)) {
1427 if (nodeConnectorNames != null) {
1428 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1430 Node node = nodeConnector.getNode();
1431 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1432 if (mapCurr != null) {
1433 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1434 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1435 String s = entry.getKey();
1437 map.put(s, new NodeConnector(entry.getValue()));
1438 } catch (ConstructionException e) {
1439 e.printStackTrace();
1442 map.remove(name.getValue());
1443 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1444 // TODO: recovery using Transactionality
1445 return new Status(StatusCode.CONFLICT, msg);
1452 return new Status(StatusCode.SUCCESS);
1456 * Removes all the properties of a node connector
1458 * @param nodeConnector
1459 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1460 * @return success or failed reason
1463 public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) {
1464 if (nodeConnectorNames != null) {
1465 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1467 Node node = nodeConnector.getNode();
1468 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1469 if (mapCurr != null) {
1470 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1471 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1472 String s = entry.getKey();
1474 map.put(s, new NodeConnector(entry.getValue()));
1475 } catch (ConstructionException e) {
1476 e.printStackTrace();
1479 map.remove(name.getValue());
1480 if (map.isEmpty()) {
1481 nodeConnectorNames.remove(node);
1483 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1484 log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.",
1485 nodeConnector.getID());
1492 nodeConnectorProps.remove(nodeConnector);
1494 return new Status(StatusCode.SUCCESS);
1498 * Function called by the dependency manager when all the required
1499 * dependencies are satisfied
1502 void init(Component c) {
1503 Dictionary<?, ?> props = c.getServiceProperties();
1504 if (props != null) {
1505 this.containerName = (String) props.get("containerName");
1506 log.trace("Running containerName: {}", this.containerName);
1508 // In the Global instance case the containerName is empty
1509 this.containerName = "";
1511 isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT
1518 * Function called by the dependency manager when at least one dependency
1519 * become unsatisfied or when the component is shutting down because for
1520 * example bundle is being stopped.
1528 * Function called by dependency manager after "init ()" is called and after
1529 * the services provided by the class are registered in the service registry
1534 registerWithOSGIConsole();
1538 * Function called after registered the service in OSGi service registry.
1541 // solicit for existing inventories
1546 * Function called by the dependency manager before the services exported by
1547 * the component are unregistered, this will be followed by a "destroy ()"
1554 public void setInventoryService(IInventoryService service) {
1555 log.trace("Got inventory service set request {}", service);
1556 this.inventoryService = service;
1558 // solicit for existing inventories
1562 public void unsetInventoryService(IInventoryService service) {
1563 log.trace("Got a service UNset request");
1564 this.inventoryService = null;
1566 // clear existing inventories
1570 public void setStatisticsManager(IStatisticsManager statisticsManager) {
1571 log.trace("Got statistics manager set request {}", statisticsManager);
1572 this.statisticsManager = statisticsManager;
1575 public void unsetStatisticsManager(IStatisticsManager statisticsManager) {
1576 log.trace("Got statistics manager UNset request");
1577 this.statisticsManager = null;
1580 public void setSwitchManagerAware(ISwitchManagerAware service) {
1581 log.trace("Got inventory service set request {}", service);
1582 if (this.switchManagerAware != null) {
1583 this.switchManagerAware.add(service);
1586 // bulk update for newly joined
1587 switchManagerAwareNotify(service);
1590 public void unsetSwitchManagerAware(ISwitchManagerAware service) {
1591 log.trace("Got a service UNset request");
1592 if (this.switchManagerAware != null) {
1593 this.switchManagerAware.remove(service);
1597 public void setInventoryListener(IInventoryListener service) {
1598 log.trace("Got inventory listener set request {}", service);
1599 if (this.inventoryListeners != null) {
1600 this.inventoryListeners.add(service);
1603 // bulk update for newly joined
1604 bulkUpdateService(service);
1607 public void unsetInventoryListener(IInventoryListener service) {
1608 log.trace("Got a service UNset request");
1609 if (this.inventoryListeners != null) {
1610 this.inventoryListeners.remove(service);
1614 public void setSpanAware(ISpanAware service) {
1615 log.trace("Got SpanAware set request {}", service);
1616 if (this.spanAware != null) {
1617 this.spanAware.add(service);
1620 // bulk update for newly joined
1621 spanAwareNotify(service);
1624 public void unsetSpanAware(ISpanAware service) {
1625 log.trace("Got a service UNset request");
1626 if (this.spanAware != null) {
1627 this.spanAware.remove(service);
1631 void setClusterContainerService(IClusterContainerServices s) {
1632 log.trace("Cluster Service set");
1633 this.clusterContainerService = s;
1636 void unsetClusterContainerService(IClusterContainerServices s) {
1637 if (this.clusterContainerService == s) {
1638 log.trace("Cluster Service removed!");
1639 this.clusterContainerService = null;
1643 private void getInventories() {
1644 if (inventoryService == null) {
1645 log.trace("inventory service not avaiable");
1649 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
1650 for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) {
1651 Node node = entry.getKey();
1652 log.debug("getInventories: {} added for container {}", new Object[] { node, containerName });
1653 Map<String, Property> propMap = entry.getValue();
1654 Set<Property> props = new HashSet<Property>();
1655 for (Property property : propMap.values()) {
1656 props.add(property);
1658 addNode(node, props);
1661 Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps();
1662 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) {
1663 Map<String, Property> propMap = entry.getValue();
1664 for (Property property : propMap.values()) {
1665 addNodeConnectorProp(entry.getKey(), property);
1670 private void clearInventories() {
1672 nodeConnectorProps.clear();
1673 nodeConnectorNames.clear();
1674 spanNodeConnectors.clear();
1677 private void notifyNode(Node node, UpdateType type,
1678 Map<String, Property> propMap) {
1679 synchronized (inventoryListeners) {
1680 for (IInventoryListener service : inventoryListeners) {
1681 service.notifyNode(node, type, propMap);
1686 private void notifyNodeConnector(NodeConnector nodeConnector,
1687 UpdateType type, Map<String, Property> propMap) {
1688 synchronized (inventoryListeners) {
1689 for (IInventoryListener service : inventoryListeners) {
1690 service.notifyNodeConnector(nodeConnector, type, propMap);
1696 * For those joined late, bring them up-to-date.
1698 private void switchManagerAwareNotify(ISwitchManagerAware service) {
1699 for (Subnet sub : subnets.values()) {
1700 service.subnetNotify(sub, true);
1703 for (Node node : getNodes()) {
1704 SwitchConfig sc = getSwitchConfig(node.toString());
1705 if ((sc != null) && isDefaultContainer) {
1706 ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
1707 service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive());
1712 private void bulkUpdateService(IInventoryListener service) {
1713 Map<String, Property> propMap;
1714 UpdateType type = UpdateType.ADDED;
1716 for (Node node : getNodes()) {
1717 propMap = nodeProps.get(node);
1718 service.notifyNode(node, type, propMap);
1721 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1722 NodeConnector nodeConnector = entry.getKey();
1723 propMap = nodeConnectorProps.get(nodeConnector);
1724 service.notifyNodeConnector(nodeConnector, type, propMap);
1728 private void spanAwareNotify(ISpanAware service) {
1729 for (Node node : getNodes()) {
1730 for (SpanConfig conf : getSpanConfigList(node)) {
1731 service.spanUpdate(node, conf.getPortArrayList(), true);
1736 private void registerWithOSGIConsole() {
1737 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
1738 .getBundleContext();
1739 bundleContext.registerService(CommandProvider.class.getName(), this,
1744 public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) {
1745 if (nodeConnector == null) {
1749 Config config = (Config) getNodeConnectorProp(nodeConnector,
1750 Config.ConfigPropName);
1751 State state = (State) getNodeConnectorProp(nodeConnector,
1752 State.StatePropName);
1753 return ((config != null) && (config.getValue() == Config.ADMIN_UP)
1754 && (state != null) && (state.getValue() == State.EDGE_UP));
1758 public String getHelp() {
1759 StringBuffer help = new StringBuffer();
1760 help.append("---Switch Manager---\n");
1761 help.append("\t pns - Print connected nodes\n");
1762 help.append("\t pncs <node id> - Print node connectors for a given node\n");
1763 help.append("\t pencs <node id> - Print enabled node connectors for a given node\n");
1764 help.append("\t pdm <node id> - Print switch ports in device map\n");
1765 help.append("\t snt <node id> <tier> - Set node tier number\n");
1766 help.append("\t hostRefresh <on/off/?> - Enable/Disable/Query host refresh\n");
1767 help.append("\t hostRetry <count> - Set host retry count\n");
1768 return help.toString();
1771 public void _pns(CommandInterpreter ci) {
1772 ci.println(" Node Type MAC Name Tier");
1773 if (nodeProps == null) {
1776 Set<Node> nodeSet = nodeProps.keySet();
1777 if (nodeSet == null) {
1780 List<String> nodeArray = new ArrayList<String>();
1781 for (Node node : nodeSet) {
1782 nodeArray.add(node.toString());
1784 Collections.sort(nodeArray);
1785 for (String str: nodeArray) {
1786 Node node = Node.fromString(str);
1787 Description desc = ((Description) getNodeProp(node,
1788 Description.propertyName));
1789 Tier tier = ((Tier) getNodeProp(node, Tier.TierPropName));
1790 String nodeName = (desc == null) ? "" : desc.getValue();
1791 MacAddress mac = (MacAddress) getNodeProp(node,
1793 String macAddr = (mac == null) ? "" : HexEncode
1794 .bytesToHexStringFormat(mac.getMacAddress());
1795 int tierNum = (tier == null) ? 0 : tier.getValue();
1796 ci.println(node + " " + node.getType() + " " + macAddr
1797 + " " + nodeName + " " + tierNum);
1799 ci.println("Total number of Nodes: " + nodeSet.size());
1802 public void _pencs(CommandInterpreter ci) {
1803 String st = ci.nextArgument();
1805 ci.println("Please enter node id");
1809 Node node = Node.fromString(st);
1811 ci.println("Please enter node id");
1815 Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node);
1816 if (nodeConnectorSet == null) {
1819 for (NodeConnector nodeConnector : nodeConnectorSet) {
1820 if (nodeConnector == null) {
1823 ci.println(nodeConnector);
1825 ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1828 public void _pncs(CommandInterpreter ci) {
1829 String st = ci.nextArgument();
1831 ci.println("Please enter node id");
1835 Node node = Node.fromString(st);
1837 ci.println("Please enter node id");
1841 ci.println(" NodeConnector BandWidth(Gbps) Admin State");
1842 Set<NodeConnector> nodeConnectorSet = getNodeConnectors(node);
1843 if (nodeConnectorSet == null) {
1846 for (NodeConnector nodeConnector : nodeConnectorSet) {
1847 if (nodeConnector == null) {
1850 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1851 Bandwidth bw = (Bandwidth) propMap.get(Bandwidth.BandwidthPropName);
1852 Config config = (Config) propMap.get(Config.ConfigPropName);
1853 State state = (State) propMap.get(State.StatePropName);
1854 String out = nodeConnector + " ";
1855 out += (bw != null) ? bw.getValue() / Math.pow(10, 9) : " ";
1857 out += (config != null) ? config.getValue() : " ";
1859 out += (state != null) ? state.getValue() : " ";
1862 ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1865 public void _pdm(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 Switch sw = getSwitchByNode(node);
1880 ci.println(" NodeConnector Name");
1884 Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors();
1885 String nodeConnectorName;
1886 if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
1887 for (NodeConnector nodeConnector : nodeConnectorSet) {
1888 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1889 nodeConnectorName = (propMap == null) ? null : ((Name) propMap
1890 .get(Name.NamePropName)).getValue();
1891 if (nodeConnectorName != null) {
1892 Node nd = nodeConnector.getNode();
1893 if (!nd.equals(node)) {
1894 log.debug("node not match {} {}", nd, node);
1896 Map<String, NodeConnector> map = nodeConnectorNames
1899 NodeConnector nc = map.get(nodeConnectorName);
1901 log.debug("no nodeConnector named {}",
1903 } else if (!nc.equals(nodeConnector)) {
1904 log.debug("nodeConnector not match {} {}", nc,
1910 ci.println(nodeConnector
1912 + ((nodeConnectorName == null) ? "" : nodeConnectorName)
1913 + "(" + nodeConnector.getID() + ")");
1915 ci.println("Total number of NodeConnectors: "
1916 + nodeConnectorSet.size());
1920 public void _snt(CommandInterpreter ci) {
1921 String st = ci.nextArgument();
1923 ci.println("Please enter node id");
1927 Node node = Node.fromString(st);
1929 ci.println("Please enter node id");
1933 st = ci.nextArgument();
1935 ci.println("Please enter tier number");
1938 Integer tid = Integer.decode(st);
1939 Tier tier = new Tier(tid);
1940 setNodeProp(node, tier);
1943 public void _hostRefresh(CommandInterpreter ci) {
1944 String mode = ci.nextArgument();
1946 ci.println("expecting on/off/?");
1949 if (mode.toLowerCase().equals("on")) {
1951 } else if (mode.toLowerCase().equals("off")) {
1952 hostRefresh = false;
1953 } else if (mode.equals("?")) {
1955 ci.println("host refresh is ON");
1957 ci.println("host refresh is OFF");
1960 ci.println("expecting on/off/?");
1965 public void _hostRetry(CommandInterpreter ci) {
1966 String retry = ci.nextArgument();
1967 if (retry == null) {
1968 ci.println("Please enter a valid number. Current retry count is "
1973 hostRetryCount = Integer.parseInt(retry);
1974 } catch (Exception e) {
1975 ci.println("Please enter a valid number");
1981 public byte[] getNodeMAC(Node node) {
1982 MacAddress mac = (MacAddress) this.getNodeProp(node,
1984 return (mac != null) ? mac.getMacAddress() : null;
1988 public boolean isSpecial(NodeConnector p) {
1989 if (p.getType().equals(NodeConnectorIDType.CONTROLLER)
1990 || p.getType().equals(NodeConnectorIDType.ALL)
1991 || p.getType().equals(NodeConnectorIDType.SWSTACK)
1992 || p.getType().equals(NodeConnectorIDType.HWPATH)) {
1999 * Add span configuration to local cache and notify clients
2001 private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2002 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2004 for (NodeConnector nodeConnector : nodeConnectors) {
2005 if (!spanNodeConnectors.contains(nodeConnector)) {
2006 ncLists.add(nodeConnector);
2010 if (ncLists.size() > 0) {
2011 spanNodeConnectors.addAll(ncLists);
2012 notifySpanPortChange(node, ncLists, true);
2016 private void addSpanPorts(Node node) {
2017 for (SpanConfig conf : getSpanConfigList(node)) {
2018 addSpanPorts(node, conf.getPortArrayList());
2022 private void addSpanPort(NodeConnector nodeConnector) {
2023 // only add if span is configured on this nodeConnector
2024 for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) {
2025 if (conf.getPortArrayList().contains(nodeConnector)) {
2026 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2027 ncLists.add(nodeConnector);
2028 addSpanPorts(nodeConnector.getNode(), ncLists);
2035 * Remove span configuration to local cache and notify clients
2037 private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2038 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2040 for (NodeConnector nodeConnector : nodeConnectors) {
2041 if (spanNodeConnectors.contains(nodeConnector)) {
2042 ncLists.add(nodeConnector);
2046 if (ncLists.size() > 0) {
2047 spanNodeConnectors.removeAll(ncLists);
2048 notifySpanPortChange(node, ncLists, false);
2052 private void removeSpanPorts(Node node) {
2053 for (SpanConfig conf : getSpanConfigList(node)) {
2054 addSpanPorts(node, conf.getPortArrayList());
2058 private void removeSpanPort(NodeConnector nodeConnector) {
2059 if (spanNodeConnectors.contains(nodeConnector)) {
2060 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2061 ncLists.add(nodeConnector);
2062 removeSpanPorts(nodeConnector.getNode(), ncLists);
2066 private void addNodeProps(Node node, Map<String, Property> propMap) {
2067 if (propMap == null) {
2068 propMap = new HashMap<String, Property>();
2070 nodeProps.put(node, propMap);
2074 public Status saveConfiguration() {
2075 return saveSwitchConfig();
2079 * Creates a Name/Tier/Bandwidth Property object based on given property
2080 * name and value. Other property types are not supported yet.
2083 * Name of the Property
2085 * Value of the Property
2086 * @return {@link org.opendaylight.controller.sal.core.Property}
2089 public Property createProperty(String propName, String propValue) {
2090 if (propName == null) {
2091 log.debug("propName is null");
2094 if (propValue == null) {
2095 log.debug("propValue is null");
2100 if (propName.equalsIgnoreCase(Description.propertyName)) {
2101 return new Description(propValue);
2102 } else if (propName.equalsIgnoreCase(Tier.TierPropName)) {
2103 int tier = Integer.parseInt(propValue);
2104 return new Tier(tier);
2105 } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) {
2106 long bw = Long.parseLong(propValue);
2107 return new Bandwidth(bw);
2108 } else if (propName.equalsIgnoreCase(ForwardingMode.name)) {
2109 int mode = Integer.parseInt(propValue);
2110 return new ForwardingMode(mode);
2112 log.debug("Not able to create {} property", propName);
2114 } catch (Exception e) {
2115 log.debug("createProperty caught exception {}", e.getMessage());
2122 public String getNodeDescription(Node node) {
2123 // Check first if user configured a name
2124 SwitchConfig config = getSwitchConfig(node.toString());
2125 if (config != null) {
2126 String configuredDesc = config.getNodeDescription();
2127 if (configuredDesc != null && !configuredDesc.isEmpty()) {
2128 return configuredDesc;
2132 // No name configured by user, get the node advertised name
2133 Description desc = (Description) getNodeProp(node,
2134 Description.propertyName);
2135 return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? ""