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.util.ArrayList;
16 import java.util.Collections;
17 import java.util.Dictionary;
18 import java.util.EnumSet;
19 import java.util.HashMap;
20 import java.util.HashSet;
21 import java.util.List;
24 import java.util.concurrent.ConcurrentHashMap;
25 import java.util.concurrent.ConcurrentMap;
26 import java.util.concurrent.CopyOnWriteArrayList;
28 import org.apache.felix.dm.Component;
29 import org.eclipse.osgi.framework.console.CommandInterpreter;
30 import org.eclipse.osgi.framework.console.CommandProvider;
31 import org.opendaylight.controller.clustering.services.CacheConfigException;
32 import org.opendaylight.controller.clustering.services.CacheExistException;
33 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
34 import org.opendaylight.controller.clustering.services.IClusterServices;
35 import org.opendaylight.controller.configuration.ConfigurationObject;
36 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
37 import org.opendaylight.controller.configuration.IConfigurationContainerService;
38 import org.opendaylight.controller.sal.core.Bandwidth;
39 import org.opendaylight.controller.sal.core.Config;
40 import org.opendaylight.controller.sal.core.ConstructionException;
41 import org.opendaylight.controller.sal.core.Description;
42 import org.opendaylight.controller.sal.core.ForwardingMode;
43 import org.opendaylight.controller.sal.core.MacAddress;
44 import org.opendaylight.controller.sal.core.Name;
45 import org.opendaylight.controller.sal.core.Node;
46 import org.opendaylight.controller.sal.core.NodeConnector;
47 import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType;
48 import org.opendaylight.controller.sal.core.Property;
49 import org.opendaylight.controller.sal.core.State;
50 import org.opendaylight.controller.sal.core.Tier;
51 import org.opendaylight.controller.sal.core.UpdateType;
52 import org.opendaylight.controller.sal.inventory.IInventoryService;
53 import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates;
54 import org.opendaylight.controller.sal.reader.NodeDescription;
55 import org.opendaylight.controller.sal.utils.GlobalConstants;
56 import org.opendaylight.controller.sal.utils.IObjectReader;
57 import org.opendaylight.controller.sal.utils.ServiceHelper;
58 import org.opendaylight.controller.sal.utils.Status;
59 import org.opendaylight.controller.sal.utils.StatusCode;
60 import org.opendaylight.controller.statisticsmanager.IStatisticsManager;
61 import org.opendaylight.controller.switchmanager.IInventoryListener;
62 import org.opendaylight.controller.switchmanager.ISpanAware;
63 import org.opendaylight.controller.switchmanager.ISwitchManager;
64 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
65 import org.opendaylight.controller.switchmanager.SpanConfig;
66 import org.opendaylight.controller.switchmanager.Subnet;
67 import org.opendaylight.controller.switchmanager.SubnetConfig;
68 import org.opendaylight.controller.switchmanager.Switch;
69 import org.opendaylight.controller.switchmanager.SwitchConfig;
70 import org.osgi.framework.BundleContext;
71 import org.osgi.framework.FrameworkUtil;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
76 * The class describes SwitchManager which is the central repository of all the
77 * inventory data including nodes, node connectors, properties attached, Layer3
78 * configurations, Span configurations, node configurations, network device
79 * representations viewed by Controller Web applications. One SwitchManager
80 * instance per container of the network. All the node/nodeConnector properties
81 * are maintained in the default container only.
83 public class SwitchManager implements ISwitchManager, IConfigurationContainerAware,
84 IObjectReader, IListenInventoryUpdates, CommandProvider {
85 private static Logger log = LoggerFactory.getLogger(SwitchManager.class);
86 private static final String SUBNETS_FILE_NAME = "subnets.conf";
87 private static final String SPAN_FILE_NAME = "spanPorts.conf";
88 private static final String SWITCH_CONFIG_FILE_NAME = "switchConfig.conf";
89 private final List<NodeConnector> spanNodeConnectors = new CopyOnWriteArrayList<NodeConnector>();
90 // Collection of Subnets keyed by the InetAddress
91 private ConcurrentMap<InetAddress, Subnet> subnets;
92 private ConcurrentMap<String, SubnetConfig> subnetsConfigList;
93 private ConcurrentMap<SpanConfig, SpanConfig> spanConfigList;
94 // manually configured parameters for the node such as name, tier, mode
95 private ConcurrentMap<String, SwitchConfig> nodeConfigList;
96 private ConcurrentMap<Node, Map<String, Property>> nodeProps;
97 private ConcurrentMap<NodeConnector, Map<String, Property>> nodeConnectorProps;
98 private ConcurrentMap<Node, Map<String, NodeConnector>> nodeConnectorNames;
99 private ConcurrentMap<String, Property> controllerProps;
100 private IInventoryService inventoryService;
101 private IStatisticsManager statisticsManager;
102 private IControllerProperties controllerProperties;
103 private IConfigurationContainerService configurationService;
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 /* Information about the default subnet. If there have been no configured subnets, i.e.,
115 * subnets.size() == 0 or subnetsConfigList.size() == 0, then this subnet will be the
116 * only subnet returned. As soon as a user-configured subnet is created this one will
119 private static final String DISABLE_DEFAULT_SUBNET_PROP = "switchmanager.disableDefaultSubnetGateway";
120 private static final String DISABLE_DEFAULT_SUBNET_PROP_VAL = System.getProperty(DISABLE_DEFAULT_SUBNET_PROP);
121 private static final boolean USE_DEFAULT_SUBNET_GW = !Boolean.valueOf(DISABLE_DEFAULT_SUBNET_PROP_VAL);
122 protected static final SubnetConfig DEFAULT_SUBNETCONFIG;
123 protected static final Subnet DEFAULT_SUBNET;
124 protected static final String DEFAULT_SUBNET_NAME = "default (cannot be modifed)";
126 DEFAULT_SUBNETCONFIG = new SubnetConfig(DEFAULT_SUBNET_NAME, "0.0.0.0/0", new ArrayList<String>());
127 DEFAULT_SUBNET = new Subnet(DEFAULT_SUBNETCONFIG);
130 public void notifySubnetChange(Subnet sub, boolean add) {
131 synchronized (switchManagerAware) {
132 for (Object subAware : switchManagerAware) {
134 ((ISwitchManagerAware) subAware).subnetNotify(sub, add);
135 } catch (Exception e) {
136 log.error("Failed to notify Subnet change {}",
143 public void notifySpanPortChange(Node node, List<NodeConnector> ports, boolean add) {
144 synchronized (spanAware) {
145 for (Object sa : spanAware) {
147 ((ISpanAware) sa).spanUpdate(node, ports, add);
148 } catch (Exception e) {
149 log.error("Failed to notify Span Interface change {}",
156 private void notifyModeChange(Node node, boolean proactive) {
157 synchronized (switchManagerAware) {
158 for (ISwitchManagerAware service : switchManagerAware) {
160 service.modeChangeNotify(node, proactive);
161 } catch (Exception e) {
162 log.error("Failed to notify Subnet change {}",
169 public void startUp() {
170 // Instantiate cluster synced variables
174 // Add controller MAC, if first node in the cluster
175 if ((!controllerProps.containsKey(MacAddress.name)) && (controllerProperties != null)) {
176 Property controllerMac = controllerProperties.getControllerProperty(MacAddress.name);
177 if (controllerMac != null) {
178 Property existing = controllerProps.putIfAbsent(MacAddress.name, controllerMac);
179 if (existing == null && log.isTraceEnabled()) {
180 log.trace("Container {}: Setting controller MAC address in the cluster: {}", getContainerName(),
187 public void shutDown() {
190 private void allocateCaches() {
191 if (this.clusterContainerService == null) {
192 this.nonClusterObjectCreate();
193 log.warn("un-initialized clusterContainerService, can't create cache");
198 clusterContainerService.createCache(
199 "switchmanager.subnetsConfigList",
200 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
201 clusterContainerService.createCache("switchmanager.spanConfigList",
202 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
203 clusterContainerService.createCache("switchmanager.nodeConfigList",
204 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
205 clusterContainerService.createCache("switchmanager.subnets",
206 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
207 clusterContainerService.createCache("switchmanager.nodeProps",
208 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
209 clusterContainerService.createCache(
210 "switchmanager.nodeConnectorProps",
211 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
212 clusterContainerService.createCache(
213 "switchmanager.nodeConnectorNames",
214 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
215 clusterContainerService.createCache(
216 "switchmanager.controllerProps",
217 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
218 } catch (CacheConfigException cce) {
219 log.error("\nCache configuration invalid - check cache mode");
220 } catch (CacheExistException ce) {
221 log.error("\nCache already exits - destroy and recreate if needed");
225 @SuppressWarnings({ "unchecked" })
226 private void retrieveCaches() {
227 if (this.clusterContainerService == null) {
228 log.warn("un-initialized clusterContainerService, can't create cache");
232 subnetsConfigList = (ConcurrentMap<String, SubnetConfig>) clusterContainerService
233 .getCache("switchmanager.subnetsConfigList");
234 if (subnetsConfigList == null) {
235 log.error("\nFailed to get cache for subnetsConfigList");
238 spanConfigList = (ConcurrentMap<SpanConfig, SpanConfig>) clusterContainerService
239 .getCache("switchmanager.spanConfigList");
240 if (spanConfigList == null) {
241 log.error("\nFailed to get cache for spanConfigList");
244 nodeConfigList = (ConcurrentMap<String, SwitchConfig>) clusterContainerService
245 .getCache("switchmanager.nodeConfigList");
246 if (nodeConfigList == null) {
247 log.error("\nFailed to get cache for nodeConfigList");
250 subnets = (ConcurrentMap<InetAddress, Subnet>) clusterContainerService
251 .getCache("switchmanager.subnets");
252 if (subnets == null) {
253 log.error("\nFailed to get cache for subnets");
256 nodeProps = (ConcurrentMap<Node, Map<String, Property>>) clusterContainerService
257 .getCache("switchmanager.nodeProps");
258 if (nodeProps == null) {
259 log.error("\nFailed to get cache for nodeProps");
262 nodeConnectorProps = (ConcurrentMap<NodeConnector, Map<String, Property>>) clusterContainerService
263 .getCache("switchmanager.nodeConnectorProps");
264 if (nodeConnectorProps == null) {
265 log.error("\nFailed to get cache for nodeConnectorProps");
268 nodeConnectorNames = (ConcurrentMap<Node, Map<String, NodeConnector>>) clusterContainerService
269 .getCache("switchmanager.nodeConnectorNames");
270 if (nodeConnectorNames == null) {
271 log.error("\nFailed to get cache for nodeConnectorNames");
274 controllerProps = (ConcurrentMap<String, Property>) clusterContainerService
275 .getCache("switchmanager.controllerProps");
276 if (controllerProps == null) {
277 log.error("\nFailed to get cache for controllerProps");
281 private void nonClusterObjectCreate() {
282 subnetsConfigList = new ConcurrentHashMap<String, SubnetConfig>();
283 spanConfigList = new ConcurrentHashMap<SpanConfig, SpanConfig>();
284 nodeConfigList = new ConcurrentHashMap<String, SwitchConfig>();
285 subnets = new ConcurrentHashMap<InetAddress, Subnet>();
286 nodeProps = new ConcurrentHashMap<Node, Map<String, Property>>();
287 nodeConnectorProps = new ConcurrentHashMap<NodeConnector, Map<String, Property>>();
288 nodeConnectorNames = new ConcurrentHashMap<Node, Map<String, NodeConnector>>();
289 controllerProps = new ConcurrentHashMap<String, Property>();
293 public List<SubnetConfig> getSubnetsConfigList() {
294 // if there are no subnets, return the default subnet
295 if (USE_DEFAULT_SUBNET_GW && subnetsConfigList.isEmpty()) {
296 return Collections.singletonList(DEFAULT_SUBNETCONFIG);
298 return new ArrayList<SubnetConfig>(subnetsConfigList.values());
303 public SubnetConfig getSubnetConfig(String subnet) {
304 // if there are no subnets, return the default subnet
305 if (USE_DEFAULT_SUBNET_GW && subnetsConfigList.isEmpty() && subnet.equalsIgnoreCase(DEFAULT_SUBNET_NAME)) {
306 return DEFAULT_SUBNETCONFIG;
308 return subnetsConfigList.get(subnet);
312 private List<SpanConfig> getSpanConfigList(Node node) {
313 List<SpanConfig> confList = new ArrayList<SpanConfig>();
314 String nodeId = node.toString();
315 for (SpanConfig conf : spanConfigList.values()) {
316 if (conf.matchNode(nodeId)) {
323 public List<SwitchConfig> getNodeConfigList() {
324 return new ArrayList<SwitchConfig>(nodeConfigList.values());
328 public SwitchConfig getSwitchConfig(String switchId) {
329 return nodeConfigList.get(switchId);
332 public Switch getSwitchByNode(Node node) {
333 Switch sw = new Switch(node);
335 MacAddress mac = (MacAddress) this.getNodeProp(node,
338 sw.setDataLayerAddress(mac.getMacAddress());
340 Set<NodeConnector> ncSet = getPhysicalNodeConnectors(node);
341 sw.setNodeConnectors(ncSet);
343 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
344 for (NodeConnector nodeConnector : ncSet) {
345 if (spanNodeConnectors.contains(nodeConnector)) {
346 ncList.add(nodeConnector);
349 sw.addSpanPorts(ncList);
355 public List<Switch> getNetworkDevices() {
356 List<Switch> swList = new ArrayList<Switch>();
357 for (Node node : getNodes()) {
358 swList.add(getSwitchByNode(node));
363 private Status updateConfig(SubnetConfig conf, boolean add) {
365 if(subnetsConfigList.putIfAbsent(conf.getName(), conf) != null) {
366 String msg = "Cluster conflict: Subnet with name " + conf.getName() + "already exists.";
367 return new Status(StatusCode.CONFLICT, msg);
370 subnetsConfigList.remove(conf.getName());
372 return new Status(StatusCode.SUCCESS);
375 private Status updateDatabase(SubnetConfig conf, boolean add) {
377 Subnet subnetCurr = subnets.get(conf.getIPAddress());
379 if (subnetCurr == null) {
380 subnet = new Subnet(conf);
382 subnet = subnetCurr.clone();
384 // In case of API3 call we may receive the ports along with the
386 if (!conf.isGlobal()) {
387 subnet.addNodeConnectors(conf.getNodeConnectors());
389 boolean putNewSubnet = false;
390 if(subnetCurr == null) {
391 if(subnets.putIfAbsent(conf.getIPAddress(), subnet) == null) {
395 putNewSubnet = subnets.replace(conf.getIPAddress(), subnetCurr, subnet);
398 String msg = "Cluster conflict: Conflict while adding the subnet " + conf.getIPAddress();
399 return new Status(StatusCode.CONFLICT, msg);
402 // Subnet removal case
404 subnets.remove(conf.getIPAddress());
406 return new Status(StatusCode.SUCCESS);
409 private Status semanticCheck(SubnetConfig conf) {
410 Set<InetAddress> IPs = subnets.keySet();
412 return new Status(StatusCode.SUCCESS);
414 Subnet newSubnet = new Subnet(conf);
415 for (InetAddress i : IPs) {
416 Subnet existingSubnet = subnets.get(i);
417 if ((existingSubnet != null) && !existingSubnet.isMutualExclusive(newSubnet)) {
418 return new Status(StatusCode.CONFLICT, "This subnet conflicts with an existing one.");
421 return new Status(StatusCode.SUCCESS);
424 private Status addRemoveSubnet(SubnetConfig conf, boolean isAdding) {
425 // Valid configuration check
426 Status status = conf.validate();
427 if (!status.isSuccess()) {
428 log.warn(status.getDescription());
434 if (subnetsConfigList.containsKey(conf.getName())) {
435 return new Status(StatusCode.CONFLICT,
436 "Subnet with the specified name already exists.");
439 status = semanticCheck(conf);
440 if (!status.isSuccess()) {
444 if (conf.getName().equalsIgnoreCase(DEFAULT_SUBNET_NAME)) {
445 return new Status(StatusCode.NOTALLOWED, "The specified subnet gateway cannot be removed");
450 status = updateDatabase(conf, isAdding);
452 if (status.isSuccess()) {
453 // Update Configuration
454 status = updateConfig(conf, isAdding);
455 if(!status.isSuccess()) {
456 updateDatabase(conf, (!isAdding));
458 // update the listeners
459 Subnet subnetCurr = subnets.get(conf.getIPAddress());
461 if (subnetCurr == null) {
462 subnet = new Subnet(conf);
464 subnet = subnetCurr.clone();
466 notifySubnetChange(subnet, isAdding);
474 * Adds Subnet configured in GUI or API3
477 public Status addSubnet(SubnetConfig conf) {
478 return this.addRemoveSubnet(conf, true);
482 public Status removeSubnet(SubnetConfig conf) {
483 return this.addRemoveSubnet(conf, false);
487 public Status removeSubnet(String name) {
488 if (name.equalsIgnoreCase(DEFAULT_SUBNET_NAME)) {
489 return new Status(StatusCode.NOTALLOWED, "The specified subnet gateway cannot be removed");
491 SubnetConfig conf = subnetsConfigList.get(name);
493 return new Status(StatusCode.SUCCESS, "Subnet not present");
495 return this.addRemoveSubnet(conf, false);
499 public Status modifySubnet(SubnetConfig conf) {
502 return new Status(StatusCode.BADREQUEST, "Invalid Subnet configuration: null");
505 // Valid configuration check
506 Status status = conf.validate();
507 if (!status.isSuccess()) {
508 log.warn(status.getDescription());
512 // If a subnet configuration with this name does not exist, consider this is a creation
513 SubnetConfig target = subnetsConfigList.get(conf.getName());
514 if (target == null) {
515 return this.addSubnet(conf);
519 if (target.equals(conf)) {
520 return new Status(StatusCode.SUCCESS);
523 // Check not allowed modifications
524 if (!target.getSubnet().equals(conf.getSubnet())) {
525 return new Status(StatusCode.BADREQUEST, "IP address change is not allowed");
528 // Derive the set of node connectors that are being removed
529 Set<NodeConnector> toRemove = target.getNodeConnectors();
530 toRemove.removeAll(conf.getNodeConnectors());
531 List<String> nodeConnectorStrings = null;
532 if (!toRemove.isEmpty()) {
533 nodeConnectorStrings = new ArrayList<String>();
534 for (NodeConnector nc : toRemove) {
535 nodeConnectorStrings.add(nc.toString());
537 status = this.removePortsFromSubnet(conf.getName(), nodeConnectorStrings);
538 if (!status.isSuccess()) {
543 // Derive the set of node connectors that are being added
544 Set<NodeConnector> toAdd = conf.getNodeConnectors();
545 toAdd.removeAll(target.getNodeConnectors());
546 if (!toAdd.isEmpty()) {
547 List<String> nodeConnectorStringRemoved = nodeConnectorStrings;
548 nodeConnectorStrings = new ArrayList<String>();
549 for (NodeConnector nc : toAdd) {
550 nodeConnectorStrings.add(nc.toString());
552 status = this.addPortsToSubnet(conf.getName(), nodeConnectorStrings);
553 if (!status.isSuccess()) {
554 // If any port was removed, add it back as a best recovery effort
555 if (!toRemove.isEmpty()) {
556 this.addPortsToSubnet(conf.getName(), nodeConnectorStringRemoved);
562 // Update Configuration
563 subnetsConfigList.put(conf.getName(), conf);
565 return new Status(StatusCode.SUCCESS);
569 public Status addPortsToSubnet(String name, List<String> switchPorts) {
571 return new Status(StatusCode.BADREQUEST, "Null subnet name");
573 SubnetConfig confCurr = subnetsConfigList.get(name);
574 if (confCurr == null) {
575 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
578 if (switchPorts == null || switchPorts.isEmpty()) {
579 return new Status(StatusCode.BADREQUEST, "Null or empty port set");
582 Subnet subCurr = subnets.get(confCurr.getIPAddress());
583 if (subCurr == null) {
584 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress());
585 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
589 Subnet sub = subCurr.clone();
590 Set<NodeConnector> sp = NodeConnector.fromString(switchPorts);
591 sub.addNodeConnectors(sp);
592 boolean subnetsReplaced = subnets.replace(confCurr.getIPAddress(), subCurr, sub);
593 if (!subnetsReplaced) {
594 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
595 return new Status(StatusCode.CONFLICT, msg);
598 // Update Configuration
599 SubnetConfig conf = confCurr.clone();
600 conf.addNodeConnectors(switchPorts);
601 boolean configReplaced = subnetsConfigList.replace(name, confCurr, conf);
602 if (!configReplaced) {
603 // TODO: recovery using Transactionality
604 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
605 return new Status(StatusCode.CONFLICT, msg);
608 return new Status(StatusCode.SUCCESS);
612 public Status removePortsFromSubnet(String name, List<String> switchPorts) {
614 return new Status(StatusCode.BADREQUEST, "Null subnet name");
616 SubnetConfig confCurr = subnetsConfigList.get(name);
617 if (confCurr == null) {
618 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
621 if (switchPorts == null || switchPorts.isEmpty()) {
622 return new Status(StatusCode.BADREQUEST, "Null or empty port set");
625 Subnet subCurr = subnets.get(confCurr.getIPAddress());
626 if (subCurr == null) {
627 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress());
628 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
632 Status status = SubnetConfig.validatePorts(switchPorts);
633 if (!status.isSuccess()) {
637 Subnet sub = subCurr.clone();
638 Set<NodeConnector> sp = NodeConnector.fromString(switchPorts);
639 sub.deleteNodeConnectors(sp);
640 boolean subnetsReplace = subnets.replace(confCurr.getIPAddress(), subCurr, sub);
641 if (!subnetsReplace) {
642 String msg = "Cluster conflict: Conflict while removing ports from the subnet " + name;
643 return new Status(StatusCode.CONFLICT, msg);
646 // Update Configuration
647 SubnetConfig conf = confCurr.clone();
648 conf.removeNodeConnectors(switchPorts);
649 boolean result = subnetsConfigList.replace(name, confCurr, conf);
651 // TODO: recovery using Transactionality
652 String msg = "Cluster conflict: Conflict while removing ports from " + conf;
653 return new Status(StatusCode.CONFLICT, msg);
656 return new Status(StatusCode.SUCCESS);
659 public String getContainerName() {
660 if (containerName == null) {
661 return GlobalConstants.DEFAULT.toString();
663 return containerName;
667 public Subnet getSubnetByNetworkAddress(InetAddress networkAddress) {
668 // if there are no subnets, return the default subnet
669 if (subnets.size() == 0) {
670 return DEFAULT_SUBNET;
673 for(Map.Entry<InetAddress,Subnet> subnetEntry : subnets.entrySet()) {
674 if(subnetEntry.getValue().isSubnetOf(networkAddress)) {
675 return subnetEntry.getValue();
682 public Object readObject(ObjectInputStream ois)
683 throws FileNotFoundException, IOException, ClassNotFoundException {
684 // Perform the class deserialization locally, from inside the package
685 // where the class is defined
686 return ois.readObject();
689 private void loadSubnetConfiguration() {
690 for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, SUBNETS_FILE_NAME)) {
691 addSubnet((SubnetConfig) conf);
695 private void loadSpanConfiguration() {
696 for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, SPAN_FILE_NAME)) {
697 addSpanConfig((SpanConfig) conf);
701 private void loadSwitchConfiguration() {
702 for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, SWITCH_CONFIG_FILE_NAME)) {
703 updateNodeConfig((SwitchConfig) conf);
707 @SuppressWarnings("deprecation")
709 public void updateSwitchConfig(SwitchConfig cfgObject) {
710 // update default container only
711 if (!isDefaultContainer) {
715 SwitchConfig sc = nodeConfigList.get(cfgObject.getNodeId());
717 if (nodeConfigList.putIfAbsent(cfgObject.getNodeId(), cfgObject) != null) {
721 if (!nodeConfigList.replace(cfgObject.getNodeId(), sc, cfgObject)) {
726 boolean modeChange = false;
728 if ((sc == null) || !cfgObject.getMode().equals(sc.getMode())) {
732 String nodeId = cfgObject.getNodeId();
733 Node node = Node.fromString(nodeId);
734 Map<String, Property> propMapCurr = nodeProps.get(node);
735 if (propMapCurr == null) {
738 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
739 Property desc = new Description(cfgObject.getNodeDescription());
740 propMap.put(desc.getName(), desc);
741 Property tier = new Tier(Integer.parseInt(cfgObject.getTier()));
742 propMap.put(tier.getName(), tier);
744 if (!nodeProps.replace(node, propMapCurr, propMap)) {
745 // TODO rollback using Transactionality
749 log.trace("Set Node {}'s Mode to {}", nodeId, cfgObject.getMode());
752 notifyModeChange(node, cfgObject.isProactive());
757 public Status updateNodeConfig(SwitchConfig switchConfig) {
758 Status status = switchConfig.validate();
759 if (!status.isSuccess()) {
763 Map<String, Property> updateProperties = switchConfig.getNodeProperties();
764 ForwardingMode mode = (ForwardingMode) updateProperties.get(ForwardingMode.name);
766 if (isDefaultContainer) {
767 if (!mode.isValid()) {
768 return new Status(StatusCode.BADREQUEST, "Invalid Forwarding Mode Value");
771 return new Status(StatusCode.NOTACCEPTABLE,
772 "Forwarding Mode modification is allowed only in default container");
776 Description description = (Description) switchConfig.getProperty(Description.propertyName);
777 String nodeId = switchConfig.getNodeId();
778 Node node = Node.fromString(nodeId);
779 NodeDescription nodeDesc = (this.statisticsManager == null) ? null : this.statisticsManager
780 .getNodeDescription(node);
781 String advertisedDesc = (nodeDesc == null) ? "" : nodeDesc.getDescription();
782 if (description != null && description.getValue() != null) {
783 if (description.getValue().isEmpty() || description.getValue().equals(advertisedDesc)) {
784 updateProperties.remove(Description.propertyName);
785 switchConfig = new SwitchConfig(nodeId, updateProperties);
787 // check if description is configured or was published by any other node
788 for (Map.Entry<Node, Map<String, Property>> entry : nodeProps.entrySet()) {
789 Node n = entry.getKey();
790 Description desc = (Description) getNodeProp(n, Description.propertyName);
791 NodeDescription nDesc = (this.statisticsManager == null) ? null : this.statisticsManager
792 .getNodeDescription(n);
793 String advDesc = (nDesc == null) ? "" : nDesc.getDescription();
794 if ((description.equals(desc) || description.getValue().equals(advDesc)) && !node.equals(n)) {
795 return new Status(StatusCode.CONFLICT, "Node name already in use");
801 boolean modeChange = false;
802 SwitchConfig sc = nodeConfigList.get(nodeId);
803 Map<String, Property> prevNodeProperties = new HashMap<String, Property>();
805 if ((mode != null) && mode.isProactive()) {
808 if (!updateProperties.isEmpty()) {
809 if (nodeConfigList.putIfAbsent(nodeId, switchConfig) != null) {
810 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
814 prevNodeProperties = new HashMap<String, Property>(sc.getNodeProperties());
815 ForwardingMode prevMode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
817 if ((prevMode != null) && (prevMode.isProactive())) {
821 if (((prevMode != null) && (prevMode.getValue() != mode.getValue()))
822 || (prevMode == null && mode.isProactive())) {
826 if (updateProperties.isEmpty()) {
827 nodeConfigList.remove(nodeId);
829 if (!nodeConfigList.replace(nodeId, sc, switchConfig)) {
830 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
834 Map<String, Property> propMapCurr = nodeProps.get(node);
835 if (propMapCurr == null) {
836 return new Status(StatusCode.SUCCESS);
838 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
839 for (Map.Entry<String, Property> entry : prevNodeProperties.entrySet()) {
840 String prop = entry.getKey();
841 if (!updateProperties.containsKey(prop)) {
842 if (prop.equals(Description.propertyName)) {
843 if (advertisedDesc != null) {
844 if (!advertisedDesc.isEmpty()) {
845 Property desc = new Description(advertisedDesc);
846 propMap.put(Description.propertyName, desc);
850 propMap.remove(prop);
853 } else if (prop.equals(ForwardingMode.name)) {
854 Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING);
855 propMap.put(ForwardingMode.name, defaultMode);
858 propMap.remove(prop);
861 propMap.putAll(updateProperties);
862 if (!nodeProps.replace(node, propMapCurr, propMap)) {
863 // TODO rollback using Transactionality
864 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
867 notifyModeChange(node, (mode == null) ? false : mode.isProactive());
869 return new Status(StatusCode.SUCCESS);
873 public Status removeNodeConfig(String nodeId) {
874 if ((nodeId == null) || (nodeId.isEmpty())) {
875 return new Status(StatusCode.BADREQUEST, "nodeId cannot be empty.");
877 Map<String, Property> nodeProperties = getSwitchConfig(nodeId).getNodeProperties();
878 Node node = Node.fromString(nodeId);
879 Map<String, Property> propMapCurr = nodeProps.get(node);
880 if ((propMapCurr != null) && (nodeProperties != null) && (!nodeProperties.isEmpty())) {
881 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
882 for (Map.Entry<String, Property> entry : nodeProperties.entrySet()) {
883 String prop = entry.getKey();
884 if (prop.equals(Description.propertyName)) {
885 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
886 if (nodeProp.get(node) != null) {
887 propMap.put(Description.propertyName, nodeProp.get(node).get(Description.propertyName));
891 propMap.remove(prop);
893 if (!nodeProps.replace(node, propMapCurr, propMap)) {
894 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration.");
897 if (nodeConfigList != null) {
898 nodeConfigList.remove(nodeId);
900 return new Status(StatusCode.SUCCESS);
904 public Status saveSwitchConfig() {
905 return saveSwitchConfigInternal();
908 public Status saveSwitchConfigInternal() {
911 status = configurationService.persistConfiguration(
912 new ArrayList<ConfigurationObject>(subnetsConfigList.values()), SUBNETS_FILE_NAME);
913 if (status.isSuccess()) {
916 log.warn("Failed to save subnet gateway configurations: " + status.getDescription());
918 status = configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(spanConfigList.values()),
920 if (status.isSuccess()) {
923 log.warn("Failed to save span port configurations: " + status.getDescription());
925 status = configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(nodeConfigList.values()),
926 SWITCH_CONFIG_FILE_NAME);
927 if (status.isSuccess()) {
930 log.warn("Failed to save node configurations: " + status.getDescription());
933 return new Status(StatusCode.INTERNALERROR, "Save failed");
936 return new Status(StatusCode.INTERNALERROR, "Partial save failure");
942 public List<SpanConfig> getSpanConfigList() {
943 return new ArrayList<SpanConfig>(spanConfigList.values());
947 public Status addSpanConfig(SpanConfig conf) {
948 // Valid config check
949 if (!conf.isValidConfig()) {
950 String msg = "Invalid Span configuration";
952 return new Status(StatusCode.BADREQUEST, msg);
956 if (spanConfigList.containsKey(conf)) {
957 return new Status(StatusCode.CONFLICT, "Same span config exists");
960 // Update configuration
961 if (spanConfigList.putIfAbsent(conf, conf) == null) {
962 // Update database and notify clients
963 addSpanPorts(conf.getNode(), conf.getPortArrayList());
966 return new Status(StatusCode.SUCCESS);
970 public Status removeSpanConfig(SpanConfig conf) {
971 removeSpanPorts(conf.getNode(), conf.getPortArrayList());
973 // Update configuration
974 spanConfigList.remove(conf);
976 return new Status(StatusCode.SUCCESS);
980 public List<NodeConnector> getSpanPorts(Node node) {
981 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
983 for (NodeConnector nodeConnector : spanNodeConnectors) {
984 if (nodeConnector.getNode().equals(node)) {
985 ncList.add(nodeConnector);
991 private void addNode(Node node, Set<Property> props) {
992 log.trace("{} added, props: {}", node, props);
993 if (nodeProps == null) {
997 Map<String, Property> propMapCurr = nodeProps.get(node);
998 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
999 : new HashMap<String, Property>(propMapCurr);
1001 // copy node properties from plugin
1002 if (props != null) {
1003 for (Property prop : props) {
1004 propMap.put(prop.getName(), prop);
1008 boolean forwardingModeChanged = false;
1010 // copy node properties from config
1011 if (nodeConfigList != null) {
1012 String nodeId = node.toString();
1013 SwitchConfig conf = nodeConfigList.get(nodeId);
1014 if (conf != null && (conf.getNodeProperties() != null)) {
1015 Map<String, Property> nodeProperties = conf.getNodeProperties();
1016 propMap.putAll(nodeProperties);
1017 if (nodeProperties.get(ForwardingMode.name) != null) {
1018 ForwardingMode mode = (ForwardingMode) nodeProperties.get(ForwardingMode.name);
1019 forwardingModeChanged = mode.isProactive();
1021 } else if ((conf == null) && !(GlobalConstants.DEFAULT.toString().equals(containerName))) {
1022 ISwitchManager defaultSwitchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, GlobalConstants.DEFAULT.toString(), this);
1023 if (defaultSwitchManager != null) {
1024 Property defaultContainerSwitchDesc = (Description) defaultSwitchManager.getNodeProp(node, Description.propertyName);
1025 if (defaultContainerSwitchDesc != null) {
1026 Map<String, Property> descPropMap = new HashMap<String, Property>();
1027 descPropMap.put(Description.propertyName, defaultContainerSwitchDesc);
1028 conf = new SwitchConfig(nodeId, descPropMap);
1029 updateNodeConfig(conf);
1030 propMap.put(Description.propertyName, defaultContainerSwitchDesc);
1036 if (!propMap.containsKey(ForwardingMode.name)) {
1037 Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING);
1038 propMap.put(ForwardingMode.name, defaultMode);
1041 boolean propsAdded = false;
1042 // Attempt initial add
1043 if (nodeProps.putIfAbsent(node, propMap) == null) {
1046 /* Notify listeners only for initial node addition
1047 * to avoid expensive tasks triggered by redundant notifications
1049 notifyNode(node, UpdateType.ADDED, propMap);
1052 propsAdded = nodeProps.replace(node, propMapCurr, propMap);
1054 // check whether forwarding mode changed
1055 if (propMapCurr.get(ForwardingMode.name) != null) {
1056 ForwardingMode mode = (ForwardingMode) propMapCurr.get(ForwardingMode.name);
1057 forwardingModeChanged ^= mode.isProactive();
1061 log.debug("Cluster conflict while adding node {}. Overwriting with latest props: {}", node.getID(), props);
1062 addNodeProps(node, propMap);
1065 // check if span ports are configured
1067 // notify proactive mode forwarding
1068 if (forwardingModeChanged) {
1069 notifyModeChange(node, true);
1073 private void removeNode(Node node) {
1074 log.trace("{} removed", node);
1075 if (nodeProps == null) {
1079 if (nodeProps.remove(node) == null) {
1080 log.debug("Received redundant node REMOVED udate for {}. Skipping..", node);
1084 nodeConnectorNames.remove(node);
1085 Set<NodeConnector> removeNodeConnectorSet = new HashSet<NodeConnector>();
1086 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1087 NodeConnector nodeConnector = entry.getKey();
1088 if (nodeConnector.getNode().equals(node)) {
1089 removeNodeConnectorSet.add(nodeConnector);
1092 for (NodeConnector nc : removeNodeConnectorSet) {
1093 nodeConnectorProps.remove(nc);
1096 // check if span ports need to be cleaned up
1097 removeSpanPorts(node);
1099 /* notify node listeners */
1100 notifyNode(node, UpdateType.REMOVED, null);
1103 private void updateNode(Node node, Set<Property> props) {
1104 log.trace("{} updated, props: {}", node, props);
1105 if (nodeProps == null || props == null) {
1109 Map<String, Property> propMapCurr = nodeProps.get(node);
1110 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1111 : new HashMap<String, Property>(propMapCurr);
1113 // copy node properties from plugin
1114 String nodeId = node.toString();
1115 for (Property prop : props) {
1116 if (nodeConfigList != null) {
1117 SwitchConfig conf = nodeConfigList.get(nodeId);
1118 if (conf != null && (conf.getNodeProperties() != null)
1119 && conf.getNodeProperties().containsKey(prop.getName())) {
1123 propMap.put(prop.getName(), prop);
1126 if (propMapCurr == null) {
1127 if (nodeProps.putIfAbsent(node, propMap) != null) {
1128 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1129 node.getID(), props);
1130 addNodeProps(node, propMap);
1133 if (!nodeProps.replace(node, propMapCurr, propMap)) {
1134 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1135 node.getID(), props);
1136 addNodeProps(node, propMap);
1140 /* notify node listeners */
1141 notifyNode(node, UpdateType.CHANGED, propMap);
1145 public void updateNode(Node node, UpdateType type, Set<Property> props) {
1146 log.debug("updateNode: {} type {} props {} for container {}",
1147 new Object[] { node, type, props, containerName });
1150 addNode(node, props);
1153 updateNode(node, props);
1164 public void updateNodeConnector(NodeConnector nodeConnector,
1165 UpdateType type, Set<Property> props) {
1166 Map<String, Property> propMap = new HashMap<String, Property>();
1167 boolean update = true;
1169 log.debug("updateNodeConnector: {} type {} props {} for container {}",
1170 new Object[] { nodeConnector, type, props, containerName });
1172 if (nodeConnectorProps == null) {
1178 // Skip redundant ADDED update (e.g. cluster switch-over)
1179 if (nodeConnectorProps.containsKey(nodeConnector)) {
1180 log.debug("Redundant nodeconnector ADDED for {}, props {} for container {}",
1181 nodeConnector, props, containerName);
1185 if (props != null) {
1186 for (Property prop : props) {
1187 addNodeConnectorProp(nodeConnector, prop);
1188 propMap.put(prop.getName(), prop);
1191 addNodeConnectorProp(nodeConnector, null);
1195 addSpanPort(nodeConnector);
1198 if (!nodeConnectorProps.containsKey(nodeConnector) || (props == null)) {
1201 for (Property prop : props) {
1202 addNodeConnectorProp(nodeConnector, prop);
1203 propMap.put(prop.getName(), prop);
1208 if (!nodeConnectorProps.containsKey(nodeConnector)) {
1211 removeNodeConnectorAllProps(nodeConnector);
1213 // clean up span config
1214 removeSpanPort(nodeConnector);
1222 notifyNodeConnector(nodeConnector, type, propMap);
1227 public Set<Node> getNodes() {
1228 return (nodeProps != null) ? new HashSet<Node>(nodeProps.keySet()) : new HashSet<Node>();
1232 public Map<String, Property> getControllerProperties() {
1233 return new HashMap<String, Property>(this.controllerProps);
1237 public Property getControllerProperty(String propertyName) {
1238 if (propertyName != null) {
1239 HashMap<String, Property> propertyMap = new HashMap<String, Property>(this.controllerProps);
1240 return propertyMap.get(propertyName);
1246 public Status setControllerProperty(Property property) {
1247 if (property != null) {
1248 this.controllerProps.put(property.getName(), property);
1249 return new Status(StatusCode.SUCCESS);
1251 return new Status(StatusCode.BADREQUEST, "Invalid property provided when setting property");
1255 public Status removeControllerProperty(String propertyName) {
1256 if (propertyName != null) {
1257 if (this.controllerProps.containsKey(propertyName)) {
1258 this.controllerProps.remove(propertyName);
1259 if (!this.controllerProps.containsKey(propertyName)) {
1260 return new Status(StatusCode.SUCCESS);
1263 String msg = "Unable to remove property " + propertyName + " from Controller";
1264 return new Status(StatusCode.BADREQUEST, msg);
1266 String msg = "Invalid property provided when removing property from Controller";
1267 return new Status(StatusCode.BADREQUEST, msg);
1271 * Returns a copy of a list of properties for a given node
1276 * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps
1277 * (org.opendaylight.controller.sal.core.Node)
1280 public Map<String, Property> getNodeProps(Node node) {
1281 Map<String, Property> rv = new HashMap<String, Property>();
1282 if (this.nodeProps != null) {
1283 rv = this.nodeProps.get(node);
1285 /* make a copy of it */
1286 rv = new HashMap<String, Property>(rv);
1293 public Property getNodeProp(Node node, String propName) {
1294 Map<String, Property> propMap = getNodeProps(node);
1295 return (propMap != null) ? propMap.get(propName) : null;
1299 public void setNodeProp(Node node, Property prop) {
1301 for (int i = 0; i <= REPLACE_RETRY; i++) {
1302 /* Get a copy of the property map */
1303 Map<String, Property> propMapCurr = getNodeProps(node);
1304 if (propMapCurr == null) {
1308 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1309 propMap.put(prop.getName(), prop);
1311 if (nodeProps.replace(node, propMapCurr, propMap)) {
1315 log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1319 public Status removeNodeProp(Node node, String propName) {
1320 for (int i = 0; i <= REPLACE_RETRY; i++) {
1321 Map<String, Property> propMapCurr = getNodeProps(node);
1322 if (propMapCurr != null) {
1323 if (!propMapCurr.containsKey(propName)) {
1324 return new Status(StatusCode.SUCCESS);
1326 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1327 propMap.remove(propName);
1328 if (nodeProps.replace(node, propMapCurr, propMap)) {
1329 return new Status(StatusCode.SUCCESS);
1332 return new Status(StatusCode.SUCCESS);
1335 String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID();
1336 return new Status(StatusCode.CONFLICT, msg);
1340 public Status removeNodeAllProps(Node node) {
1341 this.nodeProps.remove(node);
1342 return new Status(StatusCode.SUCCESS);
1346 public Set<NodeConnector> getUpNodeConnectors(Node node) {
1347 if (nodeConnectorProps == null) {
1351 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1352 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1353 NodeConnector nodeConnector = entry.getKey();
1354 if (!nodeConnector.getNode().equals(node)) {
1357 if (isNodeConnectorEnabled(nodeConnector)) {
1358 nodeConnectorSet.add(nodeConnector);
1362 return nodeConnectorSet;
1366 public Set<NodeConnector> getNodeConnectors(Node node) {
1367 if (nodeConnectorProps == null) {
1371 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1372 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1373 NodeConnector nodeConnector = entry.getKey();
1374 if (!nodeConnector.getNode().equals(node)) {
1377 nodeConnectorSet.add(nodeConnector);
1380 return nodeConnectorSet;
1384 public Set<NodeConnector> getPhysicalNodeConnectors(Node node) {
1385 if (nodeConnectorProps == null) {
1389 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1390 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1391 NodeConnector nodeConnector = entry.getKey();
1392 if (!nodeConnector.getNode().equals(node)
1393 || isSpecial(nodeConnector)) {
1396 nodeConnectorSet.add(nodeConnector);
1399 return nodeConnectorSet;
1403 public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) {
1404 Map<String, Property> rv = new HashMap<String, Property>();
1405 if (this.nodeConnectorProps != null) {
1406 rv = this.nodeConnectorProps.get(nodeConnector);
1408 rv = new HashMap<String, Property>(rv);
1415 public Property getNodeConnectorProp(NodeConnector nodeConnector,
1417 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1418 return (propMap != null) ? propMap.get(propName) : null;
1422 public byte[] getControllerMAC() {
1423 MacAddress macProperty = (MacAddress)controllerProps.get(MacAddress.name);
1424 return (macProperty == null) ? null : macProperty.getMacAddress();
1428 public NodeConnector getNodeConnector(Node node, String nodeConnectorName) {
1429 if (nodeConnectorNames == null) {
1433 Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1438 return map.get(nodeConnectorName);
1442 * Adds a node connector and its property if any
1444 * @param nodeConnector
1445 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1447 * name of {@link org.opendaylight.controller.sal.core.Property}
1448 * @return success or failed reason
1451 public Status addNodeConnectorProp(NodeConnector nodeConnector,
1453 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1454 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1455 : new HashMap<String, Property>(propMapCurr);
1457 String msg = "Cluster conflict: Unable to add NodeConnector Property.";
1458 // Just add the nodeConnector if prop is not available (in a non-default
1461 if (propMapCurr == null) {
1462 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1463 return new Status(StatusCode.CONFLICT, msg);
1466 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1467 return new Status(StatusCode.CONFLICT, msg);
1470 return new Status(StatusCode.SUCCESS);
1473 propMap.put(prop.getName(), prop);
1474 if (propMapCurr == null) {
1475 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1476 return new Status(StatusCode.CONFLICT, msg);
1479 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1480 return new Status(StatusCode.CONFLICT, msg);
1484 if (prop.getName().equals(Name.NamePropName)) {
1485 if (nodeConnectorNames != null) {
1486 Node node = nodeConnector.getNode();
1487 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1488 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1489 if (mapCurr != null) {
1490 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1491 String s = entry.getKey();
1493 map.put(s, new NodeConnector(entry.getValue()));
1494 } catch (ConstructionException e) {
1495 log.error("An error occured",e);
1500 map.put(((Name) prop).getValue(), nodeConnector);
1501 if (mapCurr == null) {
1502 if (nodeConnectorNames.putIfAbsent(node, map) != null) {
1503 // TODO: recovery using Transactionality
1504 return new Status(StatusCode.CONFLICT, msg);
1507 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1508 // TODO: recovery using Transactionality
1509 return new Status(StatusCode.CONFLICT, msg);
1515 return new Status(StatusCode.SUCCESS);
1519 * Removes one property of a node connector
1521 * @param nodeConnector
1522 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1524 * name of {@link org.opendaylight.controller.sal.core.Property}
1525 * @return success or failed reason
1528 public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) {
1529 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1531 if (propMapCurr == null) {
1532 /* Nothing to remove */
1533 return new Status(StatusCode.SUCCESS);
1536 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1537 propMap.remove(propName);
1538 boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap);
1539 String msg = "Cluster conflict: Unable to remove NodeConnector property.";
1541 return new Status(StatusCode.CONFLICT, msg);
1544 if (propName.equals(Name.NamePropName)) {
1545 if (nodeConnectorNames != null) {
1546 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1548 Node node = nodeConnector.getNode();
1549 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1550 if (mapCurr != null) {
1551 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1552 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1553 String s = entry.getKey();
1555 map.put(s, new NodeConnector(entry.getValue()));
1556 } catch (ConstructionException e) {
1557 log.error("An error occured",e);
1560 map.remove(name.getValue());
1561 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1562 // TODO: recovery using Transactionality
1563 return new Status(StatusCode.CONFLICT, msg);
1570 return new Status(StatusCode.SUCCESS);
1574 * Removes all the properties of a node connector
1576 * @param nodeConnector
1577 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1578 * @return success or failed reason
1581 public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) {
1582 if (nodeConnectorNames != null) {
1583 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1585 Node node = nodeConnector.getNode();
1586 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1587 if (mapCurr != null) {
1588 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1589 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1590 String s = entry.getKey();
1592 map.put(s, new NodeConnector(entry.getValue()));
1593 } catch (ConstructionException e) {
1594 log.error("An error occured",e);
1597 map.remove(name.getValue());
1598 if (map.isEmpty()) {
1599 nodeConnectorNames.remove(node);
1601 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1602 log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.",
1603 nodeConnector.getID());
1610 nodeConnectorProps.remove(nodeConnector);
1612 return new Status(StatusCode.SUCCESS);
1616 * Function called by the dependency manager when all the required
1617 * dependencies are satisfied
1620 void init(Component c) {
1621 Dictionary<?, ?> props = c.getServiceProperties();
1622 if (props != null) {
1623 this.containerName = (String) props.get("containerName");
1624 log.trace("Running containerName: {}", this.containerName);
1626 // In the Global instance case the containerName is empty
1627 this.containerName = "";
1629 isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT
1635 * Function called by the dependency manager when at least one dependency
1636 * become unsatisfied or when the component is shutting down because for
1637 * example bundle is being stopped.
1645 * Function called by dependency manager after "init ()" is called and after
1646 * the services provided by the class are registered in the service registry
1653 * Read startup and build database if we are the coordinator
1655 loadSubnetConfiguration();
1656 loadSpanConfiguration();
1657 loadSwitchConfiguration();
1660 registerWithOSGIConsole();
1664 * Function called after registered the service in OSGi service registry.
1667 // solicit for existing inventories
1672 * Function called by the dependency manager before the services exported by
1673 * the component are unregistered, this will be followed by a "destroy ()"
1680 public void setConfigurationContainerService(IConfigurationContainerService service) {
1681 log.trace("Got configuration service set request {}", service);
1682 this.configurationService = service;
1685 public void unsetConfigurationContainerService(IConfigurationContainerService service) {
1686 log.trace("Got configuration service UNset request");
1687 this.configurationService = null;
1690 public void setInventoryService(IInventoryService service) {
1691 log.trace("Got inventory service set request {}", service);
1692 this.inventoryService = service;
1694 // solicit for existing inventories
1698 public void unsetInventoryService(IInventoryService service) {
1699 log.trace("Got a service UNset request");
1700 this.inventoryService = null;
1702 // clear existing inventories
1706 public void setStatisticsManager(IStatisticsManager statisticsManager) {
1707 log.trace("Got statistics manager set request {}", statisticsManager);
1708 this.statisticsManager = statisticsManager;
1711 public void unsetStatisticsManager(IStatisticsManager statisticsManager) {
1712 log.trace("Got statistics manager UNset request");
1713 this.statisticsManager = null;
1716 public void setSwitchManagerAware(ISwitchManagerAware service) {
1717 log.trace("Got inventory service set request {}", service);
1718 if (this.switchManagerAware != null) {
1719 this.switchManagerAware.add(service);
1722 // bulk update for newly joined
1723 switchManagerAwareNotify(service);
1726 public void unsetSwitchManagerAware(ISwitchManagerAware service) {
1727 log.trace("Got a service UNset request");
1728 if (this.switchManagerAware != null) {
1729 this.switchManagerAware.remove(service);
1733 public void setInventoryListener(IInventoryListener service) {
1734 log.trace("Got inventory listener set request {}", service);
1735 if (this.inventoryListeners != null) {
1736 this.inventoryListeners.add(service);
1739 // bulk update for newly joined
1740 bulkUpdateService(service);
1743 public void unsetInventoryListener(IInventoryListener service) {
1744 log.trace("Got a service UNset request");
1745 if (this.inventoryListeners != null) {
1746 this.inventoryListeners.remove(service);
1750 public void setSpanAware(ISpanAware service) {
1751 log.trace("Got SpanAware set request {}", service);
1752 if (this.spanAware != null) {
1753 this.spanAware.add(service);
1756 // bulk update for newly joined
1757 spanAwareNotify(service);
1760 public void unsetSpanAware(ISpanAware service) {
1761 log.trace("Got a service UNset request");
1762 if (this.spanAware != null) {
1763 this.spanAware.remove(service);
1767 void setClusterContainerService(IClusterContainerServices s) {
1768 log.trace("Cluster Service set");
1769 this.clusterContainerService = s;
1772 void unsetClusterContainerService(IClusterContainerServices s) {
1773 if (this.clusterContainerService == s) {
1774 log.trace("Cluster Service removed!");
1775 this.clusterContainerService = null;
1779 public void setControllerProperties(IControllerProperties controllerProperties) {
1780 log.trace("Got controller properties set request {}", controllerProperties);
1781 this.controllerProperties = controllerProperties;
1784 public void unsetControllerProperties(IControllerProperties controllerProperties) {
1785 log.trace("Got controller properties UNset request");
1786 this.controllerProperties = null;
1789 private void getInventories() {
1790 if (inventoryService == null) {
1791 log.trace("inventory service not avaiable");
1795 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
1796 for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) {
1797 Node node = entry.getKey();
1798 log.debug("getInventories: {} added for container {}", new Object[] { node, containerName });
1799 Map<String, Property> propMap = entry.getValue();
1800 Set<Property> props = new HashSet<Property>();
1801 for (Property property : propMap.values()) {
1802 props.add(property);
1804 addNode(node, props);
1807 Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps();
1808 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) {
1809 Map<String, Property> propMap = entry.getValue();
1810 for (Property property : propMap.values()) {
1811 addNodeConnectorProp(entry.getKey(), property);
1816 private void clearInventories() {
1818 nodeConnectorProps.clear();
1819 nodeConnectorNames.clear();
1820 spanNodeConnectors.clear();
1823 private void notifyNode(Node node, UpdateType type,
1824 Map<String, Property> propMap) {
1825 synchronized (inventoryListeners) {
1826 for (IInventoryListener service : inventoryListeners) {
1827 service.notifyNode(node, type, propMap);
1832 private void notifyNodeConnector(NodeConnector nodeConnector,
1833 UpdateType type, Map<String, Property> propMap) {
1834 synchronized (inventoryListeners) {
1835 for (IInventoryListener service : inventoryListeners) {
1836 service.notifyNodeConnector(nodeConnector, type, propMap);
1842 * For those joined late, bring them up-to-date.
1844 private void switchManagerAwareNotify(ISwitchManagerAware service) {
1845 for (Subnet sub : subnets.values()) {
1846 service.subnetNotify(sub, true);
1849 for (Node node : getNodes()) {
1850 SwitchConfig sc = getSwitchConfig(node.toString());
1851 if ((sc != null) && isDefaultContainer) {
1852 ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
1853 service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive());
1858 private void bulkUpdateService(IInventoryListener service) {
1859 Map<String, Property> propMap;
1860 UpdateType type = UpdateType.ADDED;
1862 for (Node node : getNodes()) {
1863 propMap = nodeProps.get(node);
1864 service.notifyNode(node, type, propMap);
1867 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1868 NodeConnector nodeConnector = entry.getKey();
1869 propMap = nodeConnectorProps.get(nodeConnector);
1870 service.notifyNodeConnector(nodeConnector, type, propMap);
1874 private void spanAwareNotify(ISpanAware service) {
1875 for (Node node : getNodes()) {
1876 for (SpanConfig conf : getSpanConfigList(node)) {
1877 service.spanUpdate(node, conf.getPortArrayList(), true);
1882 private void registerWithOSGIConsole() {
1883 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
1884 .getBundleContext();
1885 bundleContext.registerService(CommandProvider.class.getName(), this,
1890 public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) {
1891 if (nodeConnector == null) {
1895 Config config = (Config) getNodeConnectorProp(nodeConnector,
1896 Config.ConfigPropName);
1897 State state = (State) getNodeConnectorProp(nodeConnector,
1898 State.StatePropName);
1899 return ((config != null) && (config.getValue() == Config.ADMIN_UP)
1900 && (state != null) && (state.getValue() == State.EDGE_UP));
1904 public boolean doesNodeConnectorExist(NodeConnector nc) {
1905 return (nc != null && nodeConnectorProps != null
1906 && nodeConnectorProps.containsKey(nc));
1910 public String getHelp() {
1911 StringBuffer help = new StringBuffer();
1912 help.append("---Switch Manager---\n");
1913 help.append("\t pencs <node id> - Print enabled node connectors for a given node\n");
1914 help.append("\t pdm <node id> - Print switch ports in device map\n");
1915 return help.toString();
1918 public void _pencs(CommandInterpreter ci) {
1919 String st = ci.nextArgument();
1921 ci.println("Please enter node id");
1925 Node node = Node.fromString(st);
1927 ci.println("Please enter node id");
1931 Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node);
1932 if (nodeConnectorSet == null) {
1935 for (NodeConnector nodeConnector : nodeConnectorSet) {
1936 if (nodeConnector == null) {
1939 ci.println(nodeConnector);
1941 ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1944 public void _pdm(CommandInterpreter ci) {
1945 String st = ci.nextArgument();
1947 ci.println("Please enter node id");
1951 Node node = Node.fromString(st);
1953 ci.println("Please enter node id");
1957 Switch sw = getSwitchByNode(node);
1959 ci.println(" NodeConnector Name");
1961 Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors();
1962 String nodeConnectorName;
1963 if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
1964 for (NodeConnector nodeConnector : nodeConnectorSet) {
1965 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1966 nodeConnectorName = (propMap == null) ? null : ((Name) propMap
1967 .get(Name.NamePropName)).getValue();
1968 if (nodeConnectorName != null) {
1969 Node nd = nodeConnector.getNode();
1970 if (!nd.equals(node)) {
1971 log.debug("node not match {} {}", nd, node);
1973 Map<String, NodeConnector> map = nodeConnectorNames
1976 NodeConnector nc = map.get(nodeConnectorName);
1978 log.debug("no nodeConnector named {}",
1980 } else if (!nc.equals(nodeConnector)) {
1981 log.debug("nodeConnector not match {} {}", nc,
1987 ci.println(nodeConnector
1989 + ((nodeConnectorName == null) ? "" : nodeConnectorName)
1990 + "(" + nodeConnector.getID() + ")");
1992 ci.println("Total number of NodeConnectors: "
1993 + nodeConnectorSet.size());
1998 public byte[] getNodeMAC(Node node) {
1999 MacAddress mac = (MacAddress) this.getNodeProp(node,
2001 return (mac != null) ? mac.getMacAddress() : null;
2005 public boolean isSpecial(NodeConnector p) {
2006 if (p.getType().equals(NodeConnectorIDType.CONTROLLER)
2007 || p.getType().equals(NodeConnectorIDType.ALL)
2008 || p.getType().equals(NodeConnectorIDType.SWSTACK)
2009 || p.getType().equals(NodeConnectorIDType.HWPATH)) {
2016 * Add span configuration to local cache and notify clients
2018 private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2019 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2021 for (NodeConnector nodeConnector : nodeConnectors) {
2022 if (!spanNodeConnectors.contains(nodeConnector)) {
2023 ncLists.add(nodeConnector);
2027 if (ncLists.size() > 0) {
2028 spanNodeConnectors.addAll(ncLists);
2029 notifySpanPortChange(node, ncLists, true);
2033 private void addSpanPorts(Node node) {
2034 for (SpanConfig conf : getSpanConfigList(node)) {
2035 addSpanPorts(node, conf.getPortArrayList());
2039 private void addSpanPort(NodeConnector nodeConnector) {
2040 // only add if span is configured on this nodeConnector
2041 for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) {
2042 if (conf.getPortArrayList().contains(nodeConnector)) {
2043 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
2044 ncList.add(nodeConnector);
2045 addSpanPorts(nodeConnector.getNode(), ncList);
2052 * Remove span configuration to local cache and notify clients
2054 private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2055 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2057 for (NodeConnector nodeConnector : nodeConnectors) {
2058 if (spanNodeConnectors.contains(nodeConnector)) {
2059 ncLists.add(nodeConnector);
2063 if (ncLists.size() > 0) {
2064 spanNodeConnectors.removeAll(ncLists);
2065 notifySpanPortChange(node, ncLists, false);
2069 private void removeSpanPorts(Node node) {
2070 for (SpanConfig conf : getSpanConfigList(node)) {
2071 addSpanPorts(node, conf.getPortArrayList());
2075 private void removeSpanPort(NodeConnector nodeConnector) {
2076 if (spanNodeConnectors.contains(nodeConnector)) {
2077 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2078 ncLists.add(nodeConnector);
2079 removeSpanPorts(nodeConnector.getNode(), ncLists);
2083 private void addNodeProps(Node node, Map<String, Property> propMap) {
2084 if (propMap == null) {
2085 propMap = new HashMap<String, Property>();
2087 nodeProps.put(node, propMap);
2091 public Status saveConfiguration() {
2092 return saveSwitchConfig();
2096 * Creates a Name/Tier/Bandwidth/MacAddress(controller property) Property
2097 * object based on given property name and value. Other property types are
2098 * not supported yet.
2101 * Name of the Property
2103 * Value of the Property
2104 * @return {@link org.opendaylight.controller.sal.core.Property}
2107 public Property createProperty(String propName, String propValue) {
2108 if (propName == null) {
2109 log.debug("propName is null");
2112 if (propValue == null) {
2113 log.debug("propValue is null");
2118 if (propName.equalsIgnoreCase(Description.propertyName)) {
2119 return new Description(propValue);
2120 } else if (propName.equalsIgnoreCase(Tier.TierPropName)) {
2121 int tier = Integer.parseInt(propValue);
2122 return new Tier(tier);
2123 } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) {
2124 long bw = Long.parseLong(propValue);
2125 return new Bandwidth(bw);
2126 } else if (propName.equalsIgnoreCase(ForwardingMode.name)) {
2127 int mode = Integer.parseInt(propValue);
2128 return new ForwardingMode(mode);
2129 } else if (propName.equalsIgnoreCase(MacAddress.name)){
2130 return new MacAddress(propValue);
2133 log.debug("Not able to create {} property", propName);
2135 } catch (Exception e) {
2136 log.debug("createProperty caught exception {}", e.getMessage());
2143 @SuppressWarnings("deprecation")
2145 public String getNodeDescription(Node node) {
2146 // Check first if user configured a name
2147 SwitchConfig config = getSwitchConfig(node.toString());
2148 if (config != null) {
2149 String configuredDesc = config.getNodeDescription();
2150 if (configuredDesc != null && !configuredDesc.isEmpty()) {
2151 return configuredDesc;
2155 // No name configured by user, get the node advertised name
2156 Description desc = (Description) getNodeProp(node,
2157 Description.propertyName);
2158 return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? ""
2163 public Set<Switch> getConfiguredNotConnectedSwitches() {
2164 Set<Switch> configuredNotConnectedSwitches = new HashSet<Switch>();
2165 if (this.inventoryService == null) {
2166 log.trace("inventory service not available");
2167 return configuredNotConnectedSwitches;
2170 Set<Node> configuredNotConnectedNodes = this.inventoryService.getConfiguredNotConnectedNodes();
2171 if (configuredNotConnectedNodes != null) {
2172 for (Node node : configuredNotConnectedNodes) {
2173 Switch sw = getSwitchByNode(node);
2174 configuredNotConnectedSwitches.add(sw);
2177 return configuredNotConnectedSwitches;