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())
1186 : new HashSet<Node>();
1190 * Returns a copy of a list of properties for a given node
1195 * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps
1196 * (org.opendaylight.controller.sal.core.Node)
1199 public Map<String, Property> getNodeProps(Node node) {
1200 Map<String, Property> rv = new HashMap<String, Property>();
1201 if (this.nodeProps != null) {
1202 rv = this.nodeProps.get(node);
1204 /* make a copy of it */
1205 rv = new HashMap<String, Property>(rv);
1212 public Property getNodeProp(Node node, String propName) {
1213 Map<String, Property> propMap = getNodeProps(node);
1214 return (propMap != null) ? propMap.get(propName) : null;
1218 public void setNodeProp(Node node, Property prop) {
1220 for (int i = 0; i <= REPLACE_RETRY; i++) {
1221 /* Get a copy of the property map */
1222 Map<String, Property> propMapCurr = getNodeProps(node);
1223 if (propMapCurr == null) {
1227 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1228 propMap.put(prop.getName(), prop);
1230 if (nodeProps.replace(node, propMapCurr, propMap)) {
1233 if (!propMapCurr.get(prop.getName()).equals(nodeProps.get(node).get(prop.getName()))) {
1234 log.debug("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1238 log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1242 public Status removeNodeProp(Node node, String propName) {
1243 for (int i = 0; i <= REPLACE_RETRY; i++) {
1244 Map<String, Property> propMapCurr = getNodeProps(node);
1245 if (propMapCurr != null) {
1246 if (!propMapCurr.containsKey(propName)) {
1247 return new Status(StatusCode.SUCCESS);
1249 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1250 propMap.remove(propName);
1251 if (nodeProps.replace(node, propMapCurr, propMap)) {
1252 return new Status(StatusCode.SUCCESS);
1254 if (!propMapCurr.get(propName).equals(nodeProps.get(node).get(propName))) {
1255 String msg = "Cluster conflict: Unable to remove property " + propName + " for node "
1257 return new Status(StatusCode.CONFLICT, msg);
1261 return new Status(StatusCode.SUCCESS);
1264 String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID();
1265 return new Status(StatusCode.CONFLICT, msg);
1269 public Status removeNodeAllProps(Node node) {
1270 this.nodeProps.remove(node);
1271 return new Status(StatusCode.SUCCESS);
1275 public Set<NodeConnector> getUpNodeConnectors(Node node) {
1276 if (nodeConnectorProps == null) {
1280 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1281 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1282 NodeConnector nodeConnector = entry.getKey();
1283 if (!nodeConnector.getNode().equals(node)) {
1286 if (isNodeConnectorEnabled(nodeConnector)) {
1287 nodeConnectorSet.add(nodeConnector);
1291 return nodeConnectorSet;
1295 public Set<NodeConnector> getNodeConnectors(Node node) {
1296 if (nodeConnectorProps == null) {
1300 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1301 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1302 NodeConnector nodeConnector = entry.getKey();
1303 if (!nodeConnector.getNode().equals(node)) {
1306 nodeConnectorSet.add(nodeConnector);
1309 return nodeConnectorSet;
1313 public Set<NodeConnector> getPhysicalNodeConnectors(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)
1322 || isSpecial(nodeConnector)) {
1325 nodeConnectorSet.add(nodeConnector);
1328 return nodeConnectorSet;
1332 public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) {
1333 Map<String, Property> rv = new HashMap<String, Property>();
1334 if (this.nodeConnectorProps != null) {
1335 rv = this.nodeConnectorProps.get(nodeConnector);
1337 rv = new HashMap<String, Property>(rv);
1344 public Property getNodeConnectorProp(NodeConnector nodeConnector,
1346 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1347 return (propMap != null) ? propMap.get(propName) : null;
1350 private byte[] getHardwareMAC() {
1351 Enumeration<NetworkInterface> nis;
1352 byte[] macAddress = null;
1355 nis = NetworkInterface.getNetworkInterfaces();
1356 } catch (SocketException e) {
1357 log.error("Failed to acquire controller MAC: ", e);
1361 while (nis.hasMoreElements()) {
1362 NetworkInterface ni = nis.nextElement();
1364 macAddress = ni.getHardwareAddress();
1365 } catch (SocketException e) {
1366 log.error("Failed to acquire controller MAC: ", e);
1368 if (macAddress != null) {
1372 if (macAddress == null) {
1373 log.warn("Failed to acquire controller MAC: No physical interface found");
1374 // This happens when running controller on windows VM, for example
1375 // Try parsing the OS command output
1381 public byte[] getControllerMAC() {
1382 MacAddress macProperty = (MacAddress)controllerProps.get(MacAddress.name);
1383 return (macProperty == null) ? null : macProperty.getMacAddress();
1387 public NodeConnector getNodeConnector(Node node, String nodeConnectorName) {
1388 if (nodeConnectorNames == null) {
1392 Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1397 return map.get(nodeConnectorName);
1401 * Adds a node connector and its property if any
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 addNodeConnectorProp(NodeConnector nodeConnector,
1412 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1413 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1414 : new HashMap<String, Property>(propMapCurr);
1416 String msg = "Cluster conflict: Unable to add NodeConnector Property.";
1417 // Just add the nodeConnector if prop is not available (in a non-default
1420 if (propMapCurr == null) {
1421 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1422 return new Status(StatusCode.CONFLICT, msg);
1425 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1426 return new Status(StatusCode.CONFLICT, msg);
1429 return new Status(StatusCode.SUCCESS);
1432 propMap.put(prop.getName(), prop);
1433 if (propMapCurr == null) {
1434 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1435 return new Status(StatusCode.CONFLICT, msg);
1438 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1439 return new Status(StatusCode.CONFLICT, msg);
1443 if (prop.getName().equals(Name.NamePropName)) {
1444 if (nodeConnectorNames != null) {
1445 Node node = nodeConnector.getNode();
1446 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1447 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1448 if (mapCurr != null) {
1449 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1450 String s = entry.getKey();
1452 map.put(s, new NodeConnector(entry.getValue()));
1453 } catch (ConstructionException e) {
1454 log.error("An error occured",e);
1459 map.put(((Name) prop).getValue(), nodeConnector);
1460 if (mapCurr == null) {
1461 if (nodeConnectorNames.putIfAbsent(node, map) != null) {
1462 // TODO: recovery using Transactionality
1463 return new Status(StatusCode.CONFLICT, msg);
1466 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1467 // TODO: recovery using Transactionality
1468 return new Status(StatusCode.CONFLICT, msg);
1474 return new Status(StatusCode.SUCCESS);
1478 * Removes one property of a node connector
1480 * @param nodeConnector
1481 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1483 * name of {@link org.opendaylight.controller.sal.core.Property}
1484 * @return success or failed reason
1487 public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) {
1488 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1490 if (propMapCurr == null) {
1491 /* Nothing to remove */
1492 return new Status(StatusCode.SUCCESS);
1495 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1496 propMap.remove(propName);
1497 boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap);
1498 String msg = "Cluster conflict: Unable to remove NodeConnector property.";
1500 return new Status(StatusCode.CONFLICT, msg);
1503 if (propName.equals(Name.NamePropName)) {
1504 if (nodeConnectorNames != null) {
1505 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1507 Node node = nodeConnector.getNode();
1508 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1509 if (mapCurr != null) {
1510 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1511 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1512 String s = entry.getKey();
1514 map.put(s, new NodeConnector(entry.getValue()));
1515 } catch (ConstructionException e) {
1516 log.error("An error occured",e);
1519 map.remove(name.getValue());
1520 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1521 // TODO: recovery using Transactionality
1522 return new Status(StatusCode.CONFLICT, msg);
1529 return new Status(StatusCode.SUCCESS);
1533 * Removes all the properties of a node connector
1535 * @param nodeConnector
1536 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1537 * @return success or failed reason
1540 public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) {
1541 if (nodeConnectorNames != null) {
1542 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1544 Node node = nodeConnector.getNode();
1545 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1546 if (mapCurr != null) {
1547 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1548 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1549 String s = entry.getKey();
1551 map.put(s, new NodeConnector(entry.getValue()));
1552 } catch (ConstructionException e) {
1553 log.error("An error occured",e);
1556 map.remove(name.getValue());
1557 if (map.isEmpty()) {
1558 nodeConnectorNames.remove(node);
1560 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1561 log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.",
1562 nodeConnector.getID());
1569 nodeConnectorProps.remove(nodeConnector);
1571 return new Status(StatusCode.SUCCESS);
1575 * Function called by the dependency manager when all the required
1576 * dependencies are satisfied
1579 void init(Component c) {
1580 Dictionary<?, ?> props = c.getServiceProperties();
1581 if (props != null) {
1582 this.containerName = (String) props.get("containerName");
1583 log.trace("Running containerName: {}", this.containerName);
1585 // In the Global instance case the containerName is empty
1586 this.containerName = "";
1588 isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT
1595 * Function called by the dependency manager when at least one dependency
1596 * become unsatisfied or when the component is shutting down because for
1597 * example bundle is being stopped.
1605 * Function called by dependency manager after "init ()" is called and after
1606 * the services provided by the class are registered in the service registry
1611 registerWithOSGIConsole();
1615 * Function called after registered the service in OSGi service registry.
1618 // solicit for existing inventories
1623 * Function called by the dependency manager before the services exported by
1624 * the component are unregistered, this will be followed by a "destroy ()"
1631 public void setInventoryService(IInventoryService service) {
1632 log.trace("Got inventory service set request {}", service);
1633 this.inventoryService = service;
1635 // solicit for existing inventories
1639 public void unsetInventoryService(IInventoryService service) {
1640 log.trace("Got a service UNset request");
1641 this.inventoryService = null;
1643 // clear existing inventories
1647 public void setStatisticsManager(IStatisticsManager statisticsManager) {
1648 log.trace("Got statistics manager set request {}", statisticsManager);
1649 this.statisticsManager = statisticsManager;
1652 public void unsetStatisticsManager(IStatisticsManager statisticsManager) {
1653 log.trace("Got statistics manager UNset request");
1654 this.statisticsManager = null;
1657 public void setSwitchManagerAware(ISwitchManagerAware service) {
1658 log.trace("Got inventory service set request {}", service);
1659 if (this.switchManagerAware != null) {
1660 this.switchManagerAware.add(service);
1663 // bulk update for newly joined
1664 switchManagerAwareNotify(service);
1667 public void unsetSwitchManagerAware(ISwitchManagerAware service) {
1668 log.trace("Got a service UNset request");
1669 if (this.switchManagerAware != null) {
1670 this.switchManagerAware.remove(service);
1674 public void setInventoryListener(IInventoryListener service) {
1675 log.trace("Got inventory listener set request {}", service);
1676 if (this.inventoryListeners != null) {
1677 this.inventoryListeners.add(service);
1680 // bulk update for newly joined
1681 bulkUpdateService(service);
1684 public void unsetInventoryListener(IInventoryListener service) {
1685 log.trace("Got a service UNset request");
1686 if (this.inventoryListeners != null) {
1687 this.inventoryListeners.remove(service);
1691 public void setSpanAware(ISpanAware service) {
1692 log.trace("Got SpanAware set request {}", service);
1693 if (this.spanAware != null) {
1694 this.spanAware.add(service);
1697 // bulk update for newly joined
1698 spanAwareNotify(service);
1701 public void unsetSpanAware(ISpanAware service) {
1702 log.trace("Got a service UNset request");
1703 if (this.spanAware != null) {
1704 this.spanAware.remove(service);
1708 void setClusterContainerService(IClusterContainerServices s) {
1709 log.trace("Cluster Service set");
1710 this.clusterContainerService = s;
1713 void unsetClusterContainerService(IClusterContainerServices s) {
1714 if (this.clusterContainerService == s) {
1715 log.trace("Cluster Service removed!");
1716 this.clusterContainerService = null;
1720 private void getInventories() {
1721 if (inventoryService == null) {
1722 log.trace("inventory service not avaiable");
1726 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
1727 for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) {
1728 Node node = entry.getKey();
1729 log.debug("getInventories: {} added for container {}", new Object[] { node, containerName });
1730 Map<String, Property> propMap = entry.getValue();
1731 Set<Property> props = new HashSet<Property>();
1732 for (Property property : propMap.values()) {
1733 props.add(property);
1735 addNode(node, props);
1738 Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps();
1739 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) {
1740 Map<String, Property> propMap = entry.getValue();
1741 for (Property property : propMap.values()) {
1742 addNodeConnectorProp(entry.getKey(), property);
1747 private void clearInventories() {
1749 nodeConnectorProps.clear();
1750 nodeConnectorNames.clear();
1751 spanNodeConnectors.clear();
1754 private void notifyNode(Node node, UpdateType type,
1755 Map<String, Property> propMap) {
1756 synchronized (inventoryListeners) {
1757 for (IInventoryListener service : inventoryListeners) {
1758 service.notifyNode(node, type, propMap);
1763 private void notifyNodeConnector(NodeConnector nodeConnector,
1764 UpdateType type, Map<String, Property> propMap) {
1765 synchronized (inventoryListeners) {
1766 for (IInventoryListener service : inventoryListeners) {
1767 service.notifyNodeConnector(nodeConnector, type, propMap);
1773 * For those joined late, bring them up-to-date.
1775 private void switchManagerAwareNotify(ISwitchManagerAware service) {
1776 for (Subnet sub : subnets.values()) {
1777 service.subnetNotify(sub, true);
1780 for (Node node : getNodes()) {
1781 SwitchConfig sc = getSwitchConfig(node.toString());
1782 if ((sc != null) && isDefaultContainer) {
1783 ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
1784 service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive());
1789 private void bulkUpdateService(IInventoryListener service) {
1790 Map<String, Property> propMap;
1791 UpdateType type = UpdateType.ADDED;
1793 for (Node node : getNodes()) {
1794 propMap = nodeProps.get(node);
1795 service.notifyNode(node, type, propMap);
1798 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1799 NodeConnector nodeConnector = entry.getKey();
1800 propMap = nodeConnectorProps.get(nodeConnector);
1801 service.notifyNodeConnector(nodeConnector, type, propMap);
1805 private void spanAwareNotify(ISpanAware service) {
1806 for (Node node : getNodes()) {
1807 for (SpanConfig conf : getSpanConfigList(node)) {
1808 service.spanUpdate(node, conf.getPortArrayList(), true);
1813 private void registerWithOSGIConsole() {
1814 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
1815 .getBundleContext();
1816 bundleContext.registerService(CommandProvider.class.getName(), this,
1821 public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) {
1822 if (nodeConnector == null) {
1826 Config config = (Config) getNodeConnectorProp(nodeConnector,
1827 Config.ConfigPropName);
1828 State state = (State) getNodeConnectorProp(nodeConnector,
1829 State.StatePropName);
1830 return ((config != null) && (config.getValue() == Config.ADMIN_UP)
1831 && (state != null) && (state.getValue() == State.EDGE_UP));
1835 public boolean doesNodeConnectorExist(NodeConnector nc) {
1836 return (nc != null && nodeConnectorProps != null
1837 && nodeConnectorProps.containsKey(nc));
1841 public String getHelp() {
1842 StringBuffer help = new StringBuffer();
1843 help.append("---Switch Manager---\n");
1844 help.append("\t pencs <node id> - Print enabled node connectors for a given node\n");
1845 help.append("\t pdm <node id> - Print switch ports in device map\n");
1846 return help.toString();
1849 public void _pencs(CommandInterpreter ci) {
1850 String st = ci.nextArgument();
1852 ci.println("Please enter node id");
1856 Node node = Node.fromString(st);
1858 ci.println("Please enter node id");
1862 Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node);
1863 if (nodeConnectorSet == null) {
1866 for (NodeConnector nodeConnector : nodeConnectorSet) {
1867 if (nodeConnector == null) {
1870 ci.println(nodeConnector);
1872 ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1875 public void _pdm(CommandInterpreter ci) {
1876 String st = ci.nextArgument();
1878 ci.println("Please enter node id");
1882 Node node = Node.fromString(st);
1884 ci.println("Please enter node id");
1888 Switch sw = getSwitchByNode(node);
1890 ci.println(" NodeConnector Name");
1892 Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors();
1893 String nodeConnectorName;
1894 if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
1895 for (NodeConnector nodeConnector : nodeConnectorSet) {
1896 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1897 nodeConnectorName = (propMap == null) ? null : ((Name) propMap
1898 .get(Name.NamePropName)).getValue();
1899 if (nodeConnectorName != null) {
1900 Node nd = nodeConnector.getNode();
1901 if (!nd.equals(node)) {
1902 log.debug("node not match {} {}", nd, node);
1904 Map<String, NodeConnector> map = nodeConnectorNames
1907 NodeConnector nc = map.get(nodeConnectorName);
1909 log.debug("no nodeConnector named {}",
1911 } else if (!nc.equals(nodeConnector)) {
1912 log.debug("nodeConnector not match {} {}", nc,
1918 ci.println(nodeConnector
1920 + ((nodeConnectorName == null) ? "" : nodeConnectorName)
1921 + "(" + nodeConnector.getID() + ")");
1923 ci.println("Total number of NodeConnectors: "
1924 + nodeConnectorSet.size());
1929 public byte[] getNodeMAC(Node node) {
1930 MacAddress mac = (MacAddress) this.getNodeProp(node,
1932 return (mac != null) ? mac.getMacAddress() : null;
1936 public boolean isSpecial(NodeConnector p) {
1937 if (p.getType().equals(NodeConnectorIDType.CONTROLLER)
1938 || p.getType().equals(NodeConnectorIDType.ALL)
1939 || p.getType().equals(NodeConnectorIDType.SWSTACK)
1940 || p.getType().equals(NodeConnectorIDType.HWPATH)) {
1947 * Add span configuration to local cache and notify clients
1949 private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
1950 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1952 for (NodeConnector nodeConnector : nodeConnectors) {
1953 if (!spanNodeConnectors.contains(nodeConnector)) {
1954 ncLists.add(nodeConnector);
1958 if (ncLists.size() > 0) {
1959 spanNodeConnectors.addAll(ncLists);
1960 notifySpanPortChange(node, ncLists, true);
1964 private void addSpanPorts(Node node) {
1965 for (SpanConfig conf : getSpanConfigList(node)) {
1966 addSpanPorts(node, conf.getPortArrayList());
1970 private void addSpanPort(NodeConnector nodeConnector) {
1971 // only add if span is configured on this nodeConnector
1972 for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) {
1973 if (conf.getPortArrayList().contains(nodeConnector)) {
1974 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1975 ncLists.add(nodeConnector);
1976 addSpanPorts(nodeConnector.getNode(), ncLists);
1983 * Remove span configuration to local cache and notify clients
1985 private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
1986 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1988 for (NodeConnector nodeConnector : nodeConnectors) {
1989 if (spanNodeConnectors.contains(nodeConnector)) {
1990 ncLists.add(nodeConnector);
1994 if (ncLists.size() > 0) {
1995 spanNodeConnectors.removeAll(ncLists);
1996 notifySpanPortChange(node, ncLists, false);
2000 private void removeSpanPorts(Node node) {
2001 for (SpanConfig conf : getSpanConfigList(node)) {
2002 addSpanPorts(node, conf.getPortArrayList());
2006 private void removeSpanPort(NodeConnector nodeConnector) {
2007 if (spanNodeConnectors.contains(nodeConnector)) {
2008 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2009 ncLists.add(nodeConnector);
2010 removeSpanPorts(nodeConnector.getNode(), ncLists);
2014 private void addNodeProps(Node node, Map<String, Property> propMap) {
2015 if (propMap == null) {
2016 propMap = new HashMap<String, Property>();
2018 nodeProps.put(node, propMap);
2022 public Status saveConfiguration() {
2023 return saveSwitchConfig();
2027 * Creates a Name/Tier/Bandwidth Property object based on given property
2028 * name and value. Other property types are not supported yet.
2031 * Name of the Property
2033 * Value of the Property
2034 * @return {@link org.opendaylight.controller.sal.core.Property}
2037 public Property createProperty(String propName, String propValue) {
2038 if (propName == null) {
2039 log.debug("propName is null");
2042 if (propValue == null) {
2043 log.debug("propValue is null");
2048 if (propName.equalsIgnoreCase(Description.propertyName)) {
2049 return new Description(propValue);
2050 } else if (propName.equalsIgnoreCase(Tier.TierPropName)) {
2051 int tier = Integer.parseInt(propValue);
2052 return new Tier(tier);
2053 } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) {
2054 long bw = Long.parseLong(propValue);
2055 return new Bandwidth(bw);
2056 } else if (propName.equalsIgnoreCase(ForwardingMode.name)) {
2057 int mode = Integer.parseInt(propValue);
2058 return new ForwardingMode(mode);
2060 log.debug("Not able to create {} property", propName);
2062 } catch (Exception e) {
2063 log.debug("createProperty caught exception {}", e.getMessage());
2069 @SuppressWarnings("deprecation")
2071 public String getNodeDescription(Node node) {
2072 // Check first if user configured a name
2073 SwitchConfig config = getSwitchConfig(node.toString());
2074 if (config != null) {
2075 String configuredDesc = config.getNodeDescription();
2076 if (configuredDesc != null && !configuredDesc.isEmpty()) {
2077 return configuredDesc;
2081 // No name configured by user, get the node advertised name
2082 Description desc = (Description) getNodeProp(node,
2083 Description.propertyName);
2084 return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? ""