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 IClusterContainerServices clusterContainerService = null;
110 private String containerName = null;
111 private boolean isDefaultContainer = true;
112 private static final int REPLACE_RETRY = 1;
114 public void notifySubnetChange(Subnet sub, boolean add) {
115 synchronized (switchManagerAware) {
116 for (Object subAware : switchManagerAware) {
118 ((ISwitchManagerAware) subAware).subnetNotify(sub, add);
119 } catch (Exception e) {
120 log.error("Failed to notify Subnet change {}",
127 public void notifySpanPortChange(Node node, List<NodeConnector> ports, boolean add) {
128 synchronized (spanAware) {
129 for (Object sa : spanAware) {
131 ((ISpanAware) sa).spanUpdate(node, ports, add);
132 } catch (Exception e) {
133 log.error("Failed to notify Span Interface change {}",
140 private void notifyModeChange(Node node, boolean proactive) {
141 synchronized (switchManagerAware) {
142 for (ISwitchManagerAware service : switchManagerAware) {
144 service.modeChangeNotify(node, proactive);
145 } catch (Exception e) {
146 log.error("Failed to notify Subnet change {}",
153 public void startUp() {
154 String container = this.getContainerName();
155 // Initialize configuration file names
156 subnetFileName = ROOT + "subnets_" + container + ".conf";
157 spanFileName = ROOT + "spanPorts_" + container + ".conf";
158 switchConfigFileName = ROOT + "switchConfig_" + container + ".conf";
160 // Instantiate cluster synced variables
165 * Read startup and build database if we have not already gotten the
166 * configurations synced from another node
168 if (subnetsConfigList.isEmpty()) {
169 loadSubnetConfiguration();
171 if (spanConfigList.isEmpty()) {
172 loadSpanConfiguration();
174 if (nodeConfigList.isEmpty()) {
175 loadSwitchConfiguration();
178 // Add controller MAC, if first node in the cluster
179 if (!controllerProps.containsKey(MacAddress.name)) {
180 byte controllerMac[] = getHardwareMAC();
181 if (controllerMac != null) {
182 Property existing = controllerProps.putIfAbsent(MacAddress.name, new MacAddress(controllerMac));
183 if (existing == null && log.isTraceEnabled()) {
184 log.trace("Container {}: Setting controller MAC address in the cluster: {}", container,
185 HexEncode.bytesToHexStringFormat(controllerMac));
191 public void shutDown() {
194 private void allocateCaches() {
195 if (this.clusterContainerService == null) {
196 this.nonClusterObjectCreate();
197 log.warn("un-initialized clusterContainerService, can't create cache");
202 clusterContainerService.createCache(
203 "switchmanager.subnetsConfigList",
204 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
205 clusterContainerService.createCache("switchmanager.spanConfigList",
206 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
207 clusterContainerService.createCache("switchmanager.nodeConfigList",
208 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
209 clusterContainerService.createCache("switchmanager.subnets",
210 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
211 clusterContainerService.createCache("switchmanager.nodeProps",
212 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
213 clusterContainerService.createCache(
214 "switchmanager.nodeConnectorProps",
215 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
216 clusterContainerService.createCache(
217 "switchmanager.nodeConnectorNames",
218 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
219 clusterContainerService.createCache(
220 "switchmanager.controllerProps",
221 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
222 } catch (CacheConfigException cce) {
223 log.error("\nCache configuration invalid - check cache mode");
224 } catch (CacheExistException ce) {
225 log.error("\nCache already exits - destroy and recreate if needed");
229 @SuppressWarnings({ "unchecked" })
230 private void retrieveCaches() {
231 if (this.clusterContainerService == null) {
232 log.info("un-initialized clusterContainerService, can't create cache");
236 subnetsConfigList = (ConcurrentMap<String, SubnetConfig>) clusterContainerService
237 .getCache("switchmanager.subnetsConfigList");
238 if (subnetsConfigList == null) {
239 log.error("\nFailed to get cache for subnetsConfigList");
242 spanConfigList = (ConcurrentMap<SpanConfig, SpanConfig>) clusterContainerService
243 .getCache("switchmanager.spanConfigList");
244 if (spanConfigList == null) {
245 log.error("\nFailed to get cache for spanConfigList");
248 nodeConfigList = (ConcurrentMap<String, SwitchConfig>) clusterContainerService
249 .getCache("switchmanager.nodeConfigList");
250 if (nodeConfigList == null) {
251 log.error("\nFailed to get cache for nodeConfigList");
254 subnets = (ConcurrentMap<InetAddress, Subnet>) clusterContainerService
255 .getCache("switchmanager.subnets");
256 if (subnets == null) {
257 log.error("\nFailed to get cache for subnets");
260 nodeProps = (ConcurrentMap<Node, Map<String, Property>>) clusterContainerService
261 .getCache("switchmanager.nodeProps");
262 if (nodeProps == null) {
263 log.error("\nFailed to get cache for nodeProps");
266 nodeConnectorProps = (ConcurrentMap<NodeConnector, Map<String, Property>>) clusterContainerService
267 .getCache("switchmanager.nodeConnectorProps");
268 if (nodeConnectorProps == null) {
269 log.error("\nFailed to get cache for nodeConnectorProps");
272 nodeConnectorNames = (ConcurrentMap<Node, Map<String, NodeConnector>>) clusterContainerService
273 .getCache("switchmanager.nodeConnectorNames");
274 if (nodeConnectorNames == null) {
275 log.error("\nFailed to get cache for nodeConnectorNames");
278 controllerProps = (ConcurrentMap<String, Property>) clusterContainerService
279 .getCache("switchmanager.controllerProps");
280 if (controllerProps == null) {
281 log.error("\nFailed to get cache for controllerProps");
285 private void nonClusterObjectCreate() {
286 subnetsConfigList = new ConcurrentHashMap<String, SubnetConfig>();
287 spanConfigList = new ConcurrentHashMap<SpanConfig, SpanConfig>();
288 nodeConfigList = new ConcurrentHashMap<String, SwitchConfig>();
289 subnets = new ConcurrentHashMap<InetAddress, Subnet>();
290 nodeProps = new ConcurrentHashMap<Node, Map<String, Property>>();
291 nodeConnectorProps = new ConcurrentHashMap<NodeConnector, Map<String, Property>>();
292 nodeConnectorNames = new ConcurrentHashMap<Node, Map<String, NodeConnector>>();
293 controllerProps = new ConcurrentHashMap<String, Property>();
297 public List<SubnetConfig> getSubnetsConfigList() {
298 return new ArrayList<SubnetConfig>(subnetsConfigList.values());
302 public SubnetConfig getSubnetConfig(String subnet) {
303 return subnetsConfigList.get(subnet);
306 private List<SpanConfig> getSpanConfigList(Node node) {
307 List<SpanConfig> confList = new ArrayList<SpanConfig>();
308 String nodeId = node.toString();
309 for (SpanConfig conf : spanConfigList.values()) {
310 if (conf.matchNode(nodeId)) {
317 public List<SwitchConfig> getNodeConfigList() {
318 return new ArrayList<SwitchConfig>(nodeConfigList.values());
322 public SwitchConfig getSwitchConfig(String switchId) {
323 return nodeConfigList.get(switchId);
326 public Switch getSwitchByNode(Node node) {
327 Switch sw = new Switch(node);
329 MacAddress mac = (MacAddress) this.getNodeProp(node,
332 sw.setDataLayerAddress(mac.getMacAddress());
334 Set<NodeConnector> ncSet = getPhysicalNodeConnectors(node);
335 sw.setNodeConnectors(ncSet);
337 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
338 for (NodeConnector nodeConnector : ncSet) {
339 if (spanNodeConnectors.contains(nodeConnector)) {
340 ncList.add(nodeConnector);
343 sw.addSpanPorts(ncList);
349 public List<Switch> getNetworkDevices() {
350 Set<Node> nodeSet = getNodes();
351 List<Switch> swList = new ArrayList<Switch>();
352 if (nodeSet != null) {
353 for (Node node : nodeSet) {
354 swList.add(getSwitchByNode(node));
361 private Status updateConfig(SubnetConfig conf, boolean add) {
363 if(subnetsConfigList.putIfAbsent(conf.getName(), conf) != null) {
364 String msg = "Cluster conflict: Subnet with name " + conf.getName() + "already exists.";
365 return new Status(StatusCode.CONFLICT, msg);
368 subnetsConfigList.remove(conf.getName());
370 return new Status(StatusCode.SUCCESS);
373 private Status updateDatabase(SubnetConfig conf, boolean add) {
375 Subnet subnetCurr = subnets.get(conf.getIPAddress());
377 if (subnetCurr == null) {
378 subnet = new Subnet(conf);
380 subnet = subnetCurr.clone();
382 // In case of API3 call we may receive the ports along with the
384 if (!conf.isGlobal()) {
385 subnet.addNodeConnectors(conf.getNodeConnectors());
387 boolean putNewSubnet = false;
388 if(subnetCurr == null) {
389 if(subnets.putIfAbsent(conf.getIPAddress(), subnet) == null) {
393 putNewSubnet = subnets.replace(conf.getIPAddress(), subnetCurr, subnet);
396 String msg = "Cluster conflict: Conflict while adding the subnet " + conf.getIPAddress();
397 return new Status(StatusCode.CONFLICT, msg);
400 // Subnet removal case
402 subnets.remove(conf.getIPAddress());
404 return new Status(StatusCode.SUCCESS);
407 private Status semanticCheck(SubnetConfig conf) {
408 Subnet newSubnet = new Subnet(conf);
409 Set<InetAddress> IPs = subnets.keySet();
411 return new Status(StatusCode.SUCCESS);
413 for (InetAddress i : IPs) {
414 Subnet existingSubnet = subnets.get(i);
415 if ((existingSubnet != null) && !existingSubnet.isMutualExclusive(newSubnet)) {
416 return new Status(StatusCode.CONFLICT, "This subnet conflicts with an existing one.");
419 return new Status(StatusCode.SUCCESS);
422 private Status addRemoveSubnet(SubnetConfig conf, boolean isAdding) {
423 // Valid configuration check
424 Status status = conf.validate();
425 if (!status.isSuccess()) {
426 log.warn(status.getDescription());
432 if (subnetsConfigList.containsKey(conf.getName())) {
433 return new Status(StatusCode.CONFLICT,
434 "Subnet with the specified name already exists.");
437 status = semanticCheck(conf);
438 if (!status.isSuccess()) {
444 status = updateDatabase(conf, isAdding);
446 if (status.isSuccess()) {
447 // Update Configuration
448 status = updateConfig(conf, isAdding);
449 if(!status.isSuccess()) {
450 updateDatabase(conf, (!isAdding));
458 * Adds Subnet configured in GUI or API3
461 public Status addSubnet(SubnetConfig conf) {
462 return this.addRemoveSubnet(conf, true);
466 public Status removeSubnet(SubnetConfig conf) {
467 return this.addRemoveSubnet(conf, false);
471 public Status removeSubnet(String name) {
472 SubnetConfig conf = subnetsConfigList.get(name);
474 return new Status(StatusCode.SUCCESS, "Subnet not present");
476 return this.addRemoveSubnet(conf, false);
480 public Status modifySubnet(SubnetConfig conf) {
483 return new Status(StatusCode.BADREQUEST, "Invalid Subnet configuration: null");
486 // Valid configuration check
487 Status status = conf.validate();
488 if (!status.isSuccess()) {
489 log.warn(status.getDescription());
493 // If a subnet configuration with this name does not exist, consider this is a creation
494 SubnetConfig target = subnetsConfigList.get(conf.getName());
495 if (target == null) {
496 return this.addSubnet(conf);
500 if (target.equals(conf)) {
501 return new Status(StatusCode.SUCCESS);
504 // Check not allowed modifications
505 if (!target.getSubnet().equals(conf.getSubnet())) {
506 return new Status(StatusCode.BADREQUEST, "IP address change is not allowed");
509 // Derive the set of node connectors that are being removed
510 Set<NodeConnector> toRemove = target.getNodeConnectors();
511 toRemove.removeAll(conf.getNodeConnectors());
512 List<String> nodeConnectorStrings = null;
513 if (!toRemove.isEmpty()) {
514 nodeConnectorStrings = new ArrayList<String>();
515 for (NodeConnector nc : toRemove) {
516 nodeConnectorStrings.add(nc.toString());
518 status = this.removePortsFromSubnet(conf.getName(), nodeConnectorStrings);
519 if (!status.isSuccess()) {
524 // Derive the set of node connectors that are being added
525 Set<NodeConnector> toAdd = conf.getNodeConnectors();
526 toAdd.removeAll(target.getNodeConnectors());
527 if (!toAdd.isEmpty()) {
528 List<String> nodeConnectorStringRemoved = nodeConnectorStrings;
529 nodeConnectorStrings = new ArrayList<String>();
530 for (NodeConnector nc : toAdd) {
531 nodeConnectorStrings.add(nc.toString());
533 status = this.addPortsToSubnet(conf.getName(), nodeConnectorStrings);
534 if (!status.isSuccess()) {
535 // If any port was removed, add it back as a best recovery effort
536 if (!toRemove.isEmpty()) {
537 this.addPortsToSubnet(conf.getName(), nodeConnectorStringRemoved);
543 // Update Configuration
544 subnetsConfigList.put(conf.getName(), conf);
546 return new Status(StatusCode.SUCCESS);
550 public Status addPortsToSubnet(String name, List<String> switchPorts) {
552 return new Status(StatusCode.BADREQUEST, "Null subnet name");
554 SubnetConfig confCurr = subnetsConfigList.get(name);
555 if (confCurr == null) {
556 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
559 if (switchPorts == null || switchPorts.isEmpty()) {
560 return new Status(StatusCode.BADREQUEST, "Null or empty port set");
563 Subnet subCurr = subnets.get(confCurr.getIPAddress());
564 if (subCurr == null) {
565 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress());
566 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
570 Subnet sub = subCurr.clone();
571 Set<NodeConnector> sp = NodeConnector.fromString(switchPorts);
572 sub.addNodeConnectors(sp);
573 boolean subnetsReplaced = subnets.replace(confCurr.getIPAddress(), subCurr, sub);
574 if (!subnetsReplaced) {
575 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
576 return new Status(StatusCode.CONFLICT, msg);
579 // Update Configuration
580 SubnetConfig conf = confCurr.clone();
581 conf.addNodeConnectors(switchPorts);
582 boolean configReplaced = subnetsConfigList.replace(name, confCurr, conf);
583 if (!configReplaced) {
584 // TODO: recovery using Transactionality
585 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
586 return new Status(StatusCode.CONFLICT, msg);
589 return new Status(StatusCode.SUCCESS);
593 public Status removePortsFromSubnet(String name, List<String> switchPorts) {
595 return new Status(StatusCode.BADREQUEST, "Null subnet name");
597 SubnetConfig confCurr = subnetsConfigList.get(name);
598 if (confCurr == null) {
599 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
602 if (switchPorts == null || switchPorts.isEmpty()) {
603 return new Status(StatusCode.BADREQUEST, "Null or empty port set");
606 Subnet subCurr = subnets.get(confCurr.getIPAddress());
607 if (subCurr == null) {
608 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress());
609 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
613 Status status = SubnetConfig.validatePorts(switchPorts);
614 if (!status.isSuccess()) {
618 Subnet sub = subCurr.clone();
619 Set<NodeConnector> sp = NodeConnector.fromString(switchPorts);
620 sub.deleteNodeConnectors(sp);
621 boolean subnetsReplace = subnets.replace(confCurr.getIPAddress(), subCurr, sub);
622 if (!subnetsReplace) {
623 String msg = "Cluster conflict: Conflict while removing ports from the subnet " + name;
624 return new Status(StatusCode.CONFLICT, msg);
627 // Update Configuration
628 SubnetConfig conf = confCurr.clone();
629 conf.removeNodeConnectors(switchPorts);
630 boolean result = subnetsConfigList.replace(name, confCurr, conf);
632 // TODO: recovery using Transactionality
633 String msg = "Cluster conflict: Conflict while removing ports from " + conf;
634 return new Status(StatusCode.CONFLICT, msg);
637 return new Status(StatusCode.SUCCESS);
640 public String getContainerName() {
641 if (containerName == null) {
642 return GlobalConstants.DEFAULT.toString();
644 return containerName;
648 public Subnet getSubnetByNetworkAddress(InetAddress networkAddress) {
650 Set<InetAddress> indices = subnets.keySet();
651 for (InetAddress i : indices) {
652 sub = subnets.get(i);
653 if (sub.isSubnetOf(networkAddress)) {
661 public Object readObject(ObjectInputStream ois)
662 throws FileNotFoundException, IOException, ClassNotFoundException {
663 // Perform the class deserialization locally, from inside the package
664 // where the class is defined
665 return ois.readObject();
668 @SuppressWarnings("unchecked")
669 private void loadSubnetConfiguration() {
670 ObjectReader objReader = new ObjectReader();
671 ConcurrentMap<String, SubnetConfig> confList = (ConcurrentMap<String, SubnetConfig>) objReader
672 .read(this, subnetFileName);
674 if (confList == null) {
678 for (SubnetConfig conf : confList.values()) {
683 @SuppressWarnings("unchecked")
684 private void loadSpanConfiguration() {
685 ObjectReader objReader = new ObjectReader();
686 ConcurrentMap<Integer, SpanConfig> confList = (ConcurrentMap<Integer, SpanConfig>) objReader
687 .read(this, spanFileName);
689 if (confList == null) {
693 for (SpanConfig conf : confList.values()) {
698 @SuppressWarnings("unchecked")
699 private void loadSwitchConfiguration() {
700 ObjectReader objReader = new ObjectReader();
701 ConcurrentMap<String, SwitchConfig> confList = (ConcurrentMap<String, SwitchConfig>) objReader
702 .read(this, switchConfigFileName);
704 if (confList == null) {
708 for (SwitchConfig conf : confList.values()) {
709 updateNodeConfig(conf);
713 @SuppressWarnings("deprecation")
715 public void updateSwitchConfig(SwitchConfig cfgObject) {
716 // update default container only
717 if (!isDefaultContainer) {
721 SwitchConfig sc = nodeConfigList.get(cfgObject.getNodeId());
723 if (nodeConfigList.putIfAbsent(cfgObject.getNodeId(), cfgObject) != null) {
727 if (!nodeConfigList.replace(cfgObject.getNodeId(), sc, cfgObject)) {
732 boolean modeChange = false;
734 if ((sc == null) || !cfgObject.getMode().equals(sc.getMode())) {
738 String nodeId = cfgObject.getNodeId();
739 Node node = Node.fromString(nodeId);
740 Map<String, Property> propMapCurr = nodeProps.get(node);
741 if (propMapCurr == null) {
744 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
745 Property desc = new Description(cfgObject.getNodeDescription());
746 propMap.put(desc.getName(), desc);
747 Property tier = new Tier(Integer.parseInt(cfgObject.getTier()));
748 propMap.put(tier.getName(), tier);
750 if (!nodeProps.replace(node, propMapCurr, propMap)) {
751 // TODO rollback using Transactionality
755 log.info("Set Node {}'s Mode to {}", nodeId, cfgObject.getMode());
758 notifyModeChange(node, cfgObject.isProactive());
763 public Status updateNodeConfig(SwitchConfig switchConfig) {
764 Status status = switchConfig.validate();
765 if (!status.isSuccess()) {
769 Map<String, Property> updateProperties = switchConfig.getNodeProperties();
770 ForwardingMode mode = (ForwardingMode) updateProperties.get(ForwardingMode.name);
772 if (isDefaultContainer) {
773 if (!mode.isValid()) {
774 return new Status(StatusCode.BADREQUEST, "Invalid Forwarding Mode Value");
777 return new Status(StatusCode.NOTACCEPTABLE,
778 "Forwarding Mode modification is allowed only in default container");
782 Description description = (Description) switchConfig.getProperty(Description.propertyName);
783 String nodeId = switchConfig.getNodeId();
784 Node node = Node.fromString(nodeId);
785 NodeDescription nodeDesc = (this.statisticsManager == null) ? null : this.statisticsManager
786 .getNodeDescription(node);
787 String advertisedDesc = (nodeDesc == null) ? "" : nodeDesc.getDescription();
788 if (description != null && description.getValue() != null) {
789 if (description.getValue().isEmpty() || description.getValue().equals(advertisedDesc)) {
790 updateProperties.remove(Description.propertyName);
791 switchConfig = new SwitchConfig(nodeId, updateProperties);
793 // check if description is configured or was published by any other node
794 for (Map.Entry<Node, Map<String, Property>> entry : nodeProps.entrySet()) {
795 Node n = entry.getKey();
796 Description desc = (Description) getNodeProp(n, Description.propertyName);
797 NodeDescription nDesc = (this.statisticsManager == null) ? null : this.statisticsManager
798 .getNodeDescription(n);
799 String advDesc = (nDesc == null) ? "" : nDesc.getDescription();
800 if ((description.equals(desc) || description.getValue().equals(advDesc)) && !node.equals(n)) {
801 return new Status(StatusCode.CONFLICT, "Node name already in use");
807 boolean modeChange = false;
808 SwitchConfig sc = nodeConfigList.get(nodeId);
809 Map<String, Property> prevNodeProperties = new HashMap<String, Property>();
811 if ((mode != null) && mode.isProactive()) {
814 if (!updateProperties.isEmpty()) {
815 if (nodeConfigList.putIfAbsent(nodeId, switchConfig) != null) {
816 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
820 prevNodeProperties = new HashMap<String, Property>(sc.getNodeProperties());
821 ForwardingMode prevMode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
823 if ((prevMode != null) && (prevMode.isProactive())) {
827 if (((prevMode != null) && (prevMode.getValue() != mode.getValue()))
828 || (prevMode == null && mode.isProactive())) {
832 if (updateProperties.isEmpty()) {
833 nodeConfigList.remove(nodeId);
835 if (!nodeConfigList.replace(nodeId, sc, switchConfig)) {
836 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
840 Map<String, Property> propMapCurr = nodeProps.get(node);
841 if (propMapCurr == null) {
842 return new Status(StatusCode.SUCCESS);
844 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
845 for (Map.Entry<String, Property> entry : prevNodeProperties.entrySet()) {
846 String prop = entry.getKey();
847 if (!updateProperties.containsKey(prop)) {
848 if (prop.equals(Description.propertyName)) {
849 if (!advertisedDesc.isEmpty()) {
850 Property desc = new Description(advertisedDesc);
851 propMap.put(Description.propertyName, desc);
854 } else if (prop.equals(ForwardingMode.name)) {
855 Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING);
856 propMap.put(ForwardingMode.name, defaultMode);
859 propMap.remove(prop);
862 propMap.putAll(updateProperties);
863 if (!nodeProps.replace(node, propMapCurr, propMap)) {
864 // TODO rollback using Transactionality
865 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
868 notifyModeChange(node, (mode == null) ? false : mode.isProactive());
870 return new Status(StatusCode.SUCCESS);
874 public Status removeNodeConfig(String nodeId) {
875 if ((nodeId == null) || (nodeId.isEmpty())) {
876 return new Status(StatusCode.BADREQUEST, "nodeId cannot be empty.");
878 Map<String, Property> nodeProperties = getSwitchConfig(nodeId).getNodeProperties();
879 Node node = Node.fromString(nodeId);
880 Map<String, Property> propMapCurr = nodeProps.get(node);
881 if ((propMapCurr != null) && (nodeProperties != null) && (!nodeProperties.isEmpty())) {
882 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
883 for (Map.Entry<String, Property> entry : nodeProperties.entrySet()) {
884 String prop = entry.getKey();
885 if (prop.equals(Description.propertyName)) {
886 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
887 if (nodeProp.get(node) != null) {
888 propMap.put(Description.propertyName, nodeProp.get(node).get(Description.propertyName));
892 propMap.remove(prop);
894 if (!nodeProps.replace(node, propMapCurr, propMap)) {
895 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration.");
898 if (nodeConfigList != null) {
899 nodeConfigList.remove(nodeId);
901 return new Status(StatusCode.SUCCESS);
905 public Status saveSwitchConfig() {
906 return saveSwitchConfigInternal();
909 public Status saveSwitchConfigInternal() {
910 Status retS = null, retP = null;
911 ObjectWriter objWriter = new ObjectWriter();
913 retS = objWriter.write(new ConcurrentHashMap<String, SubnetConfig>(
914 subnetsConfigList), subnetFileName);
915 retP = objWriter.write(new ConcurrentHashMap<SpanConfig, SpanConfig>(
916 spanConfigList), spanFileName);
917 retS = objWriter.write(new ConcurrentHashMap<String, SwitchConfig>(
918 nodeConfigList), switchConfigFileName);
919 if (retS.equals(retP)) {
920 if (retS.isSuccess()) {
923 return new Status(StatusCode.INTERNALERROR, "Save failed");
926 return new Status(StatusCode.INTERNALERROR, "Partial save failure");
931 public List<SpanConfig> getSpanConfigList() {
932 return new ArrayList<SpanConfig>(spanConfigList.values());
936 public Status addSpanConfig(SpanConfig conf) {
937 // Valid config check
938 if (!conf.isValidConfig()) {
939 String msg = "Invalid Span configuration";
941 return new Status(StatusCode.BADREQUEST, msg);
945 if (spanConfigList.containsKey(conf)) {
946 return new Status(StatusCode.CONFLICT, "Same span config exists");
949 // Update configuration
950 if (spanConfigList.putIfAbsent(conf, conf) == null) {
951 // Update database and notify clients
952 addSpanPorts(conf.getNode(), conf.getPortArrayList());
955 return new Status(StatusCode.SUCCESS);
959 public Status removeSpanConfig(SpanConfig conf) {
960 removeSpanPorts(conf.getNode(), conf.getPortArrayList());
962 // Update configuration
963 spanConfigList.remove(conf);
965 return new Status(StatusCode.SUCCESS);
969 public List<NodeConnector> getSpanPorts(Node node) {
970 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
972 for (NodeConnector nodeConnector : spanNodeConnectors) {
973 if (nodeConnector.getNode().equals(node)) {
974 ncList.add(nodeConnector);
980 private void addNode(Node node, Set<Property> props) {
981 log.trace("{} added, props: {}", node, props);
982 if (nodeProps == null) {
986 Map<String, Property> propMapCurr = nodeProps.get(node);
987 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
988 : new HashMap<String, Property>(propMapCurr);
990 // copy node properties from plugin
992 for (Property prop : props) {
993 propMap.put(prop.getName(), prop);
997 boolean proactiveForwarding = false;
998 // copy node properties from config
999 if (nodeConfigList != null) {
1000 String nodeId = node.toString();
1001 SwitchConfig conf = nodeConfigList.get(nodeId);
1002 if (conf != null && (conf.getNodeProperties() != null)) {
1003 Map<String, Property> nodeProperties = conf.getNodeProperties();
1004 propMap.putAll(nodeProperties);
1005 if (nodeProperties.get(ForwardingMode.name) != null) {
1006 ForwardingMode mode = (ForwardingMode) nodeProperties.get(ForwardingMode.name);
1007 proactiveForwarding = mode.isProactive();
1012 if (!propMap.containsKey(ForwardingMode.name)) {
1013 Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING);
1014 propMap.put(ForwardingMode.name, defaultMode);
1016 boolean result = false;
1017 if (propMapCurr == null) {
1018 if (nodeProps.putIfAbsent(node, propMap) == null) {
1022 result = nodeProps.replace(node, propMapCurr, propMap);
1025 log.debug("Cluster conflict: Conflict while adding the node properties. Node: {} Properties: {}",
1026 node.getID(), props);
1027 addNodeProps(node, propMap);
1030 // check if span ports are configed
1033 // notify node listeners
1034 notifyNode(node, UpdateType.ADDED, propMap);
1036 // notify proactive mode forwarding
1037 if (proactiveForwarding) {
1038 notifyModeChange(node, true);
1042 private void removeNode(Node node) {
1043 log.trace("{} removed", node);
1044 if (nodeProps == null) {
1047 nodeProps.remove(node);
1048 nodeConnectorNames.remove(node);
1049 Set<NodeConnector> removeNodeConnectorSet = new HashSet<NodeConnector>();
1050 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1051 NodeConnector nodeConnector = entry.getKey();
1052 if (nodeConnector.getNode().equals(node)) {
1053 removeNodeConnectorSet.add(nodeConnector);
1056 for (NodeConnector nc : removeNodeConnectorSet) {
1057 nodeConnectorProps.remove(nc);
1060 // check if span ports need to be cleaned up
1061 removeSpanPorts(node);
1063 /* notify node listeners */
1064 notifyNode(node, UpdateType.REMOVED, null);
1067 private void updateNode(Node node, Set<Property> props) {
1068 log.trace("{} updated, props: {}", node, props);
1069 if (nodeProps == null || !nodeProps.containsKey(node) ||
1070 props == null || props.isEmpty()) {
1074 Map<String, Property> propMapCurr = nodeProps.get(node);
1075 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1076 : new HashMap<String, Property>(propMapCurr);
1078 // copy node properties from plugin
1079 String nodeId = node.toString();
1080 for (Property prop : props) {
1081 if (nodeConfigList != null) {
1082 SwitchConfig conf = nodeConfigList.get(nodeId);
1083 if (conf != null && (conf.getNodeProperties() != null)
1084 && conf.getNodeProperties().containsKey(prop.getName())) {
1088 propMap.put(prop.getName(), prop);
1091 if (propMapCurr == null) {
1092 if (nodeProps.putIfAbsent(node, propMap) != null) {
1093 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1094 node.getID(), props);
1095 addNodeProps(node, propMap);
1098 if (!nodeProps.replace(node, propMapCurr, propMap)) {
1099 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1100 node.getID(), props);
1101 addNodeProps(node, propMap);
1105 /* notify node listeners */
1106 notifyNode(node, UpdateType.CHANGED, propMap);
1110 public void updateNode(Node node, UpdateType type, Set<Property> props) {
1111 log.debug("updateNode: {} type {} props {} for container {}",
1112 new Object[] { node, type, props, containerName });
1115 addNode(node, props);
1118 updateNode(node, props);
1129 public void updateNodeConnector(NodeConnector nodeConnector,
1130 UpdateType type, Set<Property> props) {
1131 Map<String, Property> propMap = new HashMap<String, Property>();
1132 boolean update = true;
1134 log.debug("updateNodeConnector: {} type {} props {} for container {}",
1135 new Object[] { nodeConnector, type, props, containerName });
1137 if (nodeConnectorProps == null) {
1143 if (props != null) {
1144 for (Property prop : props) {
1145 addNodeConnectorProp(nodeConnector, prop);
1146 propMap.put(prop.getName(), prop);
1149 addNodeConnectorProp(nodeConnector, null);
1152 addSpanPort(nodeConnector);
1155 if (!nodeConnectorProps.containsKey(nodeConnector) || (props == null)) {
1158 for (Property prop : props) {
1159 addNodeConnectorProp(nodeConnector, prop);
1160 propMap.put(prop.getName(), prop);
1165 if (!nodeConnectorProps.containsKey(nodeConnector)) {
1168 removeNodeConnectorAllProps(nodeConnector);
1170 // clean up span config
1171 removeSpanPort(nodeConnector);
1179 notifyNodeConnector(nodeConnector, type, propMap);
1184 public Set<Node> getNodes() {
1185 return (nodeProps != null) ? new HashSet<Node>(nodeProps.keySet()) : new HashSet<Node>();
1189 public Map<String, Property> getControllerProperties() {
1190 return new HashMap<String, Property>(this.controllerProps);
1194 public Property getControllerProperty(String propertyName) {
1195 if (propertyName != null) {
1196 HashMap<String, Property> propertyMap = new HashMap<String, Property>(this.controllerProps);
1197 return propertyMap.get(propertyName);
1203 public Status setControllerProperty(Property property) {
1204 if (property != null) {
1205 this.controllerProps.put(property.getName(), property);
1206 return new Status(StatusCode.SUCCESS);
1208 return new Status(StatusCode.BADREQUEST, "Invalid property provided when setting property");
1212 public Status removeControllerProperty(String propertyName) {
1213 if (propertyName != null) {
1214 if (this.controllerProps.containsKey(propertyName)) {
1215 this.controllerProps.remove(propertyName);
1216 if (!this.controllerProps.containsKey(propertyName)) {
1217 return new Status(StatusCode.SUCCESS);
1220 String msg = "Unable to remove property " + propertyName + " from Controller";
1221 return new Status(StatusCode.BADREQUEST, msg);
1223 String msg = "Invalid property provided when removing property from Controller";
1224 return new Status(StatusCode.BADREQUEST, msg);
1228 * Returns a copy of a list of properties for a given node
1233 * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps
1234 * (org.opendaylight.controller.sal.core.Node)
1237 public Map<String, Property> getNodeProps(Node node) {
1238 Map<String, Property> rv = new HashMap<String, Property>();
1239 if (this.nodeProps != null) {
1240 rv = this.nodeProps.get(node);
1242 /* make a copy of it */
1243 rv = new HashMap<String, Property>(rv);
1250 public Property getNodeProp(Node node, String propName) {
1251 Map<String, Property> propMap = getNodeProps(node);
1252 return (propMap != null) ? propMap.get(propName) : null;
1256 public void setNodeProp(Node node, Property prop) {
1258 for (int i = 0; i <= REPLACE_RETRY; i++) {
1259 /* Get a copy of the property map */
1260 Map<String, Property> propMapCurr = getNodeProps(node);
1261 if (propMapCurr == null) {
1265 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1266 propMap.put(prop.getName(), prop);
1268 if (nodeProps.replace(node, propMapCurr, propMap)) {
1271 if (!propMapCurr.get(prop.getName()).equals(nodeProps.get(node).get(prop.getName()))) {
1272 log.debug("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1276 log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1280 public Status removeNodeProp(Node node, String propName) {
1281 for (int i = 0; i <= REPLACE_RETRY; i++) {
1282 Map<String, Property> propMapCurr = getNodeProps(node);
1283 if (propMapCurr != null) {
1284 if (!propMapCurr.containsKey(propName)) {
1285 return new Status(StatusCode.SUCCESS);
1287 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1288 propMap.remove(propName);
1289 if (nodeProps.replace(node, propMapCurr, propMap)) {
1290 return new Status(StatusCode.SUCCESS);
1292 if (!propMapCurr.get(propName).equals(nodeProps.get(node).get(propName))) {
1293 String msg = "Cluster conflict: Unable to remove property " + propName + " for node "
1295 return new Status(StatusCode.CONFLICT, msg);
1299 return new Status(StatusCode.SUCCESS);
1302 String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID();
1303 return new Status(StatusCode.CONFLICT, msg);
1307 public Status removeNodeAllProps(Node node) {
1308 this.nodeProps.remove(node);
1309 return new Status(StatusCode.SUCCESS);
1313 public Set<NodeConnector> getUpNodeConnectors(Node node) {
1314 if (nodeConnectorProps == null) {
1318 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1319 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1320 NodeConnector nodeConnector = entry.getKey();
1321 if (!nodeConnector.getNode().equals(node)) {
1324 if (isNodeConnectorEnabled(nodeConnector)) {
1325 nodeConnectorSet.add(nodeConnector);
1329 return nodeConnectorSet;
1333 public Set<NodeConnector> getNodeConnectors(Node node) {
1334 if (nodeConnectorProps == null) {
1338 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1339 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1340 NodeConnector nodeConnector = entry.getKey();
1341 if (!nodeConnector.getNode().equals(node)) {
1344 nodeConnectorSet.add(nodeConnector);
1347 return nodeConnectorSet;
1351 public Set<NodeConnector> getPhysicalNodeConnectors(Node node) {
1352 if (nodeConnectorProps == null) {
1356 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1357 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1358 NodeConnector nodeConnector = entry.getKey();
1359 if (!nodeConnector.getNode().equals(node)
1360 || isSpecial(nodeConnector)) {
1363 nodeConnectorSet.add(nodeConnector);
1366 return nodeConnectorSet;
1370 public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) {
1371 Map<String, Property> rv = new HashMap<String, Property>();
1372 if (this.nodeConnectorProps != null) {
1373 rv = this.nodeConnectorProps.get(nodeConnector);
1375 rv = new HashMap<String, Property>(rv);
1382 public Property getNodeConnectorProp(NodeConnector nodeConnector,
1384 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1385 return (propMap != null) ? propMap.get(propName) : null;
1388 private byte[] getHardwareMAC() {
1389 Enumeration<NetworkInterface> nis;
1390 byte[] macAddress = null;
1393 nis = NetworkInterface.getNetworkInterfaces();
1394 } catch (SocketException e) {
1395 log.error("Failed to acquire controller MAC: ", e);
1399 while (nis.hasMoreElements()) {
1400 NetworkInterface ni = nis.nextElement();
1402 macAddress = ni.getHardwareAddress();
1403 } catch (SocketException e) {
1404 log.error("Failed to acquire controller MAC: ", e);
1406 if (macAddress != null) {
1410 if (macAddress == null) {
1411 log.warn("Failed to acquire controller MAC: No physical interface found");
1412 // This happens when running controller on windows VM, for example
1413 // Try parsing the OS command output
1419 public byte[] getControllerMAC() {
1420 MacAddress macProperty = (MacAddress)controllerProps.get(MacAddress.name);
1421 return (macProperty == null) ? null : macProperty.getMacAddress();
1425 public NodeConnector getNodeConnector(Node node, String nodeConnectorName) {
1426 if (nodeConnectorNames == null) {
1430 Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1435 return map.get(nodeConnectorName);
1439 * Adds a node connector and its property if any
1441 * @param nodeConnector
1442 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1444 * name of {@link org.opendaylight.controller.sal.core.Property}
1445 * @return success or failed reason
1448 public Status addNodeConnectorProp(NodeConnector nodeConnector,
1450 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1451 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1452 : new HashMap<String, Property>(propMapCurr);
1454 String msg = "Cluster conflict: Unable to add NodeConnector Property.";
1455 // Just add the nodeConnector if prop is not available (in a non-default
1458 if (propMapCurr == null) {
1459 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1460 return new Status(StatusCode.CONFLICT, msg);
1463 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1464 return new Status(StatusCode.CONFLICT, msg);
1467 return new Status(StatusCode.SUCCESS);
1470 propMap.put(prop.getName(), prop);
1471 if (propMapCurr == null) {
1472 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1473 return new Status(StatusCode.CONFLICT, msg);
1476 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1477 return new Status(StatusCode.CONFLICT, msg);
1481 if (prop.getName().equals(Name.NamePropName)) {
1482 if (nodeConnectorNames != null) {
1483 Node node = nodeConnector.getNode();
1484 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1485 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1486 if (mapCurr != null) {
1487 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1488 String s = entry.getKey();
1490 map.put(s, new NodeConnector(entry.getValue()));
1491 } catch (ConstructionException e) {
1492 log.error("An error occured",e);
1497 map.put(((Name) prop).getValue(), nodeConnector);
1498 if (mapCurr == null) {
1499 if (nodeConnectorNames.putIfAbsent(node, map) != null) {
1500 // TODO: recovery using Transactionality
1501 return new Status(StatusCode.CONFLICT, msg);
1504 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1505 // TODO: recovery using Transactionality
1506 return new Status(StatusCode.CONFLICT, msg);
1512 return new Status(StatusCode.SUCCESS);
1516 * Removes one property of a node connector
1518 * @param nodeConnector
1519 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1521 * name of {@link org.opendaylight.controller.sal.core.Property}
1522 * @return success or failed reason
1525 public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) {
1526 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1528 if (propMapCurr == null) {
1529 /* Nothing to remove */
1530 return new Status(StatusCode.SUCCESS);
1533 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1534 propMap.remove(propName);
1535 boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap);
1536 String msg = "Cluster conflict: Unable to remove NodeConnector property.";
1538 return new Status(StatusCode.CONFLICT, msg);
1541 if (propName.equals(Name.NamePropName)) {
1542 if (nodeConnectorNames != null) {
1543 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1545 Node node = nodeConnector.getNode();
1546 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1547 if (mapCurr != null) {
1548 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1549 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1550 String s = entry.getKey();
1552 map.put(s, new NodeConnector(entry.getValue()));
1553 } catch (ConstructionException e) {
1554 log.error("An error occured",e);
1557 map.remove(name.getValue());
1558 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1559 // TODO: recovery using Transactionality
1560 return new Status(StatusCode.CONFLICT, msg);
1567 return new Status(StatusCode.SUCCESS);
1571 * Removes all the properties of a node connector
1573 * @param nodeConnector
1574 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1575 * @return success or failed reason
1578 public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) {
1579 if (nodeConnectorNames != null) {
1580 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1582 Node node = nodeConnector.getNode();
1583 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1584 if (mapCurr != null) {
1585 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1586 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1587 String s = entry.getKey();
1589 map.put(s, new NodeConnector(entry.getValue()));
1590 } catch (ConstructionException e) {
1591 log.error("An error occured",e);
1594 map.remove(name.getValue());
1595 if (map.isEmpty()) {
1596 nodeConnectorNames.remove(node);
1598 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1599 log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.",
1600 nodeConnector.getID());
1607 nodeConnectorProps.remove(nodeConnector);
1609 return new Status(StatusCode.SUCCESS);
1613 * Function called by the dependency manager when all the required
1614 * dependencies are satisfied
1617 void init(Component c) {
1618 Dictionary<?, ?> props = c.getServiceProperties();
1619 if (props != null) {
1620 this.containerName = (String) props.get("containerName");
1621 log.trace("Running containerName: {}", this.containerName);
1623 // In the Global instance case the containerName is empty
1624 this.containerName = "";
1626 isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT
1633 * Function called by the dependency manager when at least one dependency
1634 * become unsatisfied or when the component is shutting down because for
1635 * example bundle is being stopped.
1643 * Function called by dependency manager after "init ()" is called and after
1644 * the services provided by the class are registered in the service registry
1649 registerWithOSGIConsole();
1653 * Function called after registered the service in OSGi service registry.
1656 // solicit for existing inventories
1661 * Function called by the dependency manager before the services exported by
1662 * the component are unregistered, this will be followed by a "destroy ()"
1669 public void setInventoryService(IInventoryService service) {
1670 log.trace("Got inventory service set request {}", service);
1671 this.inventoryService = service;
1673 // solicit for existing inventories
1677 public void unsetInventoryService(IInventoryService service) {
1678 log.trace("Got a service UNset request");
1679 this.inventoryService = null;
1681 // clear existing inventories
1685 public void setStatisticsManager(IStatisticsManager statisticsManager) {
1686 log.trace("Got statistics manager set request {}", statisticsManager);
1687 this.statisticsManager = statisticsManager;
1690 public void unsetStatisticsManager(IStatisticsManager statisticsManager) {
1691 log.trace("Got statistics manager UNset request");
1692 this.statisticsManager = null;
1695 public void setSwitchManagerAware(ISwitchManagerAware service) {
1696 log.trace("Got inventory service set request {}", service);
1697 if (this.switchManagerAware != null) {
1698 this.switchManagerAware.add(service);
1701 // bulk update for newly joined
1702 switchManagerAwareNotify(service);
1705 public void unsetSwitchManagerAware(ISwitchManagerAware service) {
1706 log.trace("Got a service UNset request");
1707 if (this.switchManagerAware != null) {
1708 this.switchManagerAware.remove(service);
1712 public void setInventoryListener(IInventoryListener service) {
1713 log.trace("Got inventory listener set request {}", service);
1714 if (this.inventoryListeners != null) {
1715 this.inventoryListeners.add(service);
1718 // bulk update for newly joined
1719 bulkUpdateService(service);
1722 public void unsetInventoryListener(IInventoryListener service) {
1723 log.trace("Got a service UNset request");
1724 if (this.inventoryListeners != null) {
1725 this.inventoryListeners.remove(service);
1729 public void setSpanAware(ISpanAware service) {
1730 log.trace("Got SpanAware set request {}", service);
1731 if (this.spanAware != null) {
1732 this.spanAware.add(service);
1735 // bulk update for newly joined
1736 spanAwareNotify(service);
1739 public void unsetSpanAware(ISpanAware service) {
1740 log.trace("Got a service UNset request");
1741 if (this.spanAware != null) {
1742 this.spanAware.remove(service);
1746 void setClusterContainerService(IClusterContainerServices s) {
1747 log.trace("Cluster Service set");
1748 this.clusterContainerService = s;
1751 void unsetClusterContainerService(IClusterContainerServices s) {
1752 if (this.clusterContainerService == s) {
1753 log.trace("Cluster Service removed!");
1754 this.clusterContainerService = null;
1758 private void getInventories() {
1759 if (inventoryService == null) {
1760 log.trace("inventory service not avaiable");
1764 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
1765 for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) {
1766 Node node = entry.getKey();
1767 log.debug("getInventories: {} added for container {}", new Object[] { node, containerName });
1768 Map<String, Property> propMap = entry.getValue();
1769 Set<Property> props = new HashSet<Property>();
1770 for (Property property : propMap.values()) {
1771 props.add(property);
1773 addNode(node, props);
1776 Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps();
1777 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) {
1778 Map<String, Property> propMap = entry.getValue();
1779 for (Property property : propMap.values()) {
1780 addNodeConnectorProp(entry.getKey(), property);
1785 private void clearInventories() {
1787 nodeConnectorProps.clear();
1788 nodeConnectorNames.clear();
1789 spanNodeConnectors.clear();
1792 private void notifyNode(Node node, UpdateType type,
1793 Map<String, Property> propMap) {
1794 synchronized (inventoryListeners) {
1795 for (IInventoryListener service : inventoryListeners) {
1796 service.notifyNode(node, type, propMap);
1801 private void notifyNodeConnector(NodeConnector nodeConnector,
1802 UpdateType type, Map<String, Property> propMap) {
1803 synchronized (inventoryListeners) {
1804 for (IInventoryListener service : inventoryListeners) {
1805 service.notifyNodeConnector(nodeConnector, type, propMap);
1811 * For those joined late, bring them up-to-date.
1813 private void switchManagerAwareNotify(ISwitchManagerAware service) {
1814 for (Subnet sub : subnets.values()) {
1815 service.subnetNotify(sub, true);
1818 for (Node node : getNodes()) {
1819 SwitchConfig sc = getSwitchConfig(node.toString());
1820 if ((sc != null) && isDefaultContainer) {
1821 ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
1822 service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive());
1827 private void bulkUpdateService(IInventoryListener service) {
1828 Map<String, Property> propMap;
1829 UpdateType type = UpdateType.ADDED;
1831 for (Node node : getNodes()) {
1832 propMap = nodeProps.get(node);
1833 service.notifyNode(node, type, propMap);
1836 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1837 NodeConnector nodeConnector = entry.getKey();
1838 propMap = nodeConnectorProps.get(nodeConnector);
1839 service.notifyNodeConnector(nodeConnector, type, propMap);
1843 private void spanAwareNotify(ISpanAware service) {
1844 for (Node node : getNodes()) {
1845 for (SpanConfig conf : getSpanConfigList(node)) {
1846 service.spanUpdate(node, conf.getPortArrayList(), true);
1851 private void registerWithOSGIConsole() {
1852 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
1853 .getBundleContext();
1854 bundleContext.registerService(CommandProvider.class.getName(), this,
1859 public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) {
1860 if (nodeConnector == null) {
1864 Config config = (Config) getNodeConnectorProp(nodeConnector,
1865 Config.ConfigPropName);
1866 State state = (State) getNodeConnectorProp(nodeConnector,
1867 State.StatePropName);
1868 return ((config != null) && (config.getValue() == Config.ADMIN_UP)
1869 && (state != null) && (state.getValue() == State.EDGE_UP));
1873 public boolean doesNodeConnectorExist(NodeConnector nc) {
1874 return (nc != null && nodeConnectorProps != null
1875 && nodeConnectorProps.containsKey(nc));
1879 public String getHelp() {
1880 StringBuffer help = new StringBuffer();
1881 help.append("---Switch Manager---\n");
1882 help.append("\t pencs <node id> - Print enabled node connectors for a given node\n");
1883 help.append("\t pdm <node id> - Print switch ports in device map\n");
1884 return help.toString();
1887 public void _pencs(CommandInterpreter ci) {
1888 String st = ci.nextArgument();
1890 ci.println("Please enter node id");
1894 Node node = Node.fromString(st);
1896 ci.println("Please enter node id");
1900 Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node);
1901 if (nodeConnectorSet == null) {
1904 for (NodeConnector nodeConnector : nodeConnectorSet) {
1905 if (nodeConnector == null) {
1908 ci.println(nodeConnector);
1910 ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1913 public void _pdm(CommandInterpreter ci) {
1914 String st = ci.nextArgument();
1916 ci.println("Please enter node id");
1920 Node node = Node.fromString(st);
1922 ci.println("Please enter node id");
1926 Switch sw = getSwitchByNode(node);
1928 ci.println(" NodeConnector Name");
1930 Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors();
1931 String nodeConnectorName;
1932 if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
1933 for (NodeConnector nodeConnector : nodeConnectorSet) {
1934 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1935 nodeConnectorName = (propMap == null) ? null : ((Name) propMap
1936 .get(Name.NamePropName)).getValue();
1937 if (nodeConnectorName != null) {
1938 Node nd = nodeConnector.getNode();
1939 if (!nd.equals(node)) {
1940 log.debug("node not match {} {}", nd, node);
1942 Map<String, NodeConnector> map = nodeConnectorNames
1945 NodeConnector nc = map.get(nodeConnectorName);
1947 log.debug("no nodeConnector named {}",
1949 } else if (!nc.equals(nodeConnector)) {
1950 log.debug("nodeConnector not match {} {}", nc,
1956 ci.println(nodeConnector
1958 + ((nodeConnectorName == null) ? "" : nodeConnectorName)
1959 + "(" + nodeConnector.getID() + ")");
1961 ci.println("Total number of NodeConnectors: "
1962 + nodeConnectorSet.size());
1967 public byte[] getNodeMAC(Node node) {
1968 MacAddress mac = (MacAddress) this.getNodeProp(node,
1970 return (mac != null) ? mac.getMacAddress() : null;
1974 public boolean isSpecial(NodeConnector p) {
1975 if (p.getType().equals(NodeConnectorIDType.CONTROLLER)
1976 || p.getType().equals(NodeConnectorIDType.ALL)
1977 || p.getType().equals(NodeConnectorIDType.SWSTACK)
1978 || p.getType().equals(NodeConnectorIDType.HWPATH)) {
1985 * Add span configuration to local cache and notify clients
1987 private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
1988 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1990 for (NodeConnector nodeConnector : nodeConnectors) {
1991 if (!spanNodeConnectors.contains(nodeConnector)) {
1992 ncLists.add(nodeConnector);
1996 if (ncLists.size() > 0) {
1997 spanNodeConnectors.addAll(ncLists);
1998 notifySpanPortChange(node, ncLists, true);
2002 private void addSpanPorts(Node node) {
2003 for (SpanConfig conf : getSpanConfigList(node)) {
2004 addSpanPorts(node, conf.getPortArrayList());
2008 private void addSpanPort(NodeConnector nodeConnector) {
2009 // only add if span is configured on this nodeConnector
2010 for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) {
2011 if (conf.getPortArrayList().contains(nodeConnector)) {
2012 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2013 ncLists.add(nodeConnector);
2014 addSpanPorts(nodeConnector.getNode(), ncLists);
2021 * Remove span configuration to local cache and notify clients
2023 private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2024 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2026 for (NodeConnector nodeConnector : nodeConnectors) {
2027 if (spanNodeConnectors.contains(nodeConnector)) {
2028 ncLists.add(nodeConnector);
2032 if (ncLists.size() > 0) {
2033 spanNodeConnectors.removeAll(ncLists);
2034 notifySpanPortChange(node, ncLists, false);
2038 private void removeSpanPorts(Node node) {
2039 for (SpanConfig conf : getSpanConfigList(node)) {
2040 addSpanPorts(node, conf.getPortArrayList());
2044 private void removeSpanPort(NodeConnector nodeConnector) {
2045 if (spanNodeConnectors.contains(nodeConnector)) {
2046 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2047 ncLists.add(nodeConnector);
2048 removeSpanPorts(nodeConnector.getNode(), ncLists);
2052 private void addNodeProps(Node node, Map<String, Property> propMap) {
2053 if (propMap == null) {
2054 propMap = new HashMap<String, Property>();
2056 nodeProps.put(node, propMap);
2060 public Status saveConfiguration() {
2061 return saveSwitchConfig();
2065 * Creates a Name/Tier/Bandwidth/MacAddress(controller property) Property
2066 * object based on given property name and value. Other property types are
2067 * not supported yet.
2070 * Name of the Property
2072 * Value of the Property
2073 * @return {@link org.opendaylight.controller.sal.core.Property}
2076 public Property createProperty(String propName, String propValue) {
2077 if (propName == null) {
2078 log.debug("propName is null");
2081 if (propValue == null) {
2082 log.debug("propValue is null");
2087 if (propName.equalsIgnoreCase(Description.propertyName)) {
2088 return new Description(propValue);
2089 } else if (propName.equalsIgnoreCase(Tier.TierPropName)) {
2090 int tier = Integer.parseInt(propValue);
2091 return new Tier(tier);
2092 } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) {
2093 long bw = Long.parseLong(propValue);
2094 return new Bandwidth(bw);
2095 } else if (propName.equalsIgnoreCase(ForwardingMode.name)) {
2096 int mode = Integer.parseInt(propValue);
2097 return new ForwardingMode(mode);
2098 } else if (propName.equalsIgnoreCase(MacAddress.name)){
2099 return new MacAddress(propValue);
2102 log.debug("Not able to create {} property", propName);
2104 } catch (Exception e) {
2105 log.debug("createProperty caught exception {}", e.getMessage());
2112 @SuppressWarnings("deprecation")
2114 public String getNodeDescription(Node node) {
2115 // Check first if user configured a name
2116 SwitchConfig config = getSwitchConfig(node.toString());
2117 if (config != null) {
2118 String configuredDesc = config.getNodeDescription();
2119 if (configuredDesc != null && !configuredDesc.isEmpty()) {
2120 return configuredDesc;
2124 // No name configured by user, get the node advertised name
2125 Description desc = (Description) getNodeProp(node,
2126 Description.propertyName);
2127 return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? ""