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.Status;
58 import org.opendaylight.controller.sal.utils.StatusCode;
59 import org.opendaylight.controller.statisticsmanager.IStatisticsManager;
60 import org.opendaylight.controller.switchmanager.IInventoryListener;
61 import org.opendaylight.controller.switchmanager.ISpanAware;
62 import org.opendaylight.controller.switchmanager.ISwitchManager;
63 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
64 import org.opendaylight.controller.switchmanager.SpanConfig;
65 import org.opendaylight.controller.switchmanager.Subnet;
66 import org.opendaylight.controller.switchmanager.SubnetConfig;
67 import org.opendaylight.controller.switchmanager.Switch;
68 import org.opendaylight.controller.switchmanager.SwitchConfig;
69 import org.osgi.framework.BundleContext;
70 import org.osgi.framework.FrameworkUtil;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
75 * The class describes SwitchManager which is the central repository of all the
76 * inventory data including nodes, node connectors, properties attached, Layer3
77 * configurations, Span configurations, node configurations, network device
78 * representations viewed by Controller Web applications. One SwitchManager
79 * instance per container of the network. All the node/nodeConnector properties
80 * are maintained in the default container only.
82 public class SwitchManager implements ISwitchManager, IConfigurationContainerAware,
83 IObjectReader, IListenInventoryUpdates, CommandProvider {
84 private static Logger log = LoggerFactory.getLogger(SwitchManager.class);
85 private static final String SUBNETS_FILE_NAME = "subnets.conf";
86 private static final String SPAN_FILE_NAME = "spanPorts.conf";
87 private static final String SWITCH_CONFIG_FILE_NAME = "switchConfig.conf";
88 private final List<NodeConnector> spanNodeConnectors = new CopyOnWriteArrayList<NodeConnector>();
89 // Collection of Subnets keyed by the InetAddress
90 private ConcurrentMap<InetAddress, Subnet> subnets;
91 private ConcurrentMap<String, SubnetConfig> subnetsConfigList;
92 private ConcurrentMap<SpanConfig, SpanConfig> spanConfigList;
93 // manually configured parameters for the node such as name, tier, mode
94 private ConcurrentMap<String, SwitchConfig> nodeConfigList;
95 private ConcurrentMap<Node, Map<String, Property>> nodeProps;
96 private ConcurrentMap<NodeConnector, Map<String, Property>> nodeConnectorProps;
97 private ConcurrentMap<Node, Map<String, NodeConnector>> nodeConnectorNames;
98 private ConcurrentMap<String, Property> controllerProps;
99 private IInventoryService inventoryService;
100 private IStatisticsManager statisticsManager;
101 private IControllerProperties controllerProperties;
102 private IConfigurationContainerService configurationService;
103 private final Set<ISwitchManagerAware> switchManagerAware = Collections
104 .synchronizedSet(new HashSet<ISwitchManagerAware>());
105 private final Set<IInventoryListener> inventoryListeners = Collections
106 .synchronizedSet(new HashSet<IInventoryListener>());
107 private final Set<ISpanAware> spanAware = Collections.synchronizedSet(new HashSet<ISpanAware>());
108 private IClusterContainerServices clusterContainerService = null;
109 private String containerName = null;
110 private boolean isDefaultContainer = true;
111 private static final int REPLACE_RETRY = 1;
113 /* Information about the default subnet. If there have been no configured subnets, i.e.,
114 * subnets.size() == 0 or subnetsConfigList.size() == 0, then this subnet will be the
115 * only subnet returned. As soon as a user-configured subnet is created this one will
118 protected static final SubnetConfig DEFAULT_SUBNETCONFIG;
119 protected static final Subnet DEFAULT_SUBNET;
120 protected static final String DEFAULT_SUBNET_NAME = "default (cannot be modifed)";
122 DEFAULT_SUBNETCONFIG = new SubnetConfig(DEFAULT_SUBNET_NAME, "0.0.0.0/0", new ArrayList<String>());
123 DEFAULT_SUBNET = new Subnet(DEFAULT_SUBNETCONFIG);
126 public void notifySubnetChange(Subnet sub, boolean add) {
127 synchronized (switchManagerAware) {
128 for (Object subAware : switchManagerAware) {
130 ((ISwitchManagerAware) subAware).subnetNotify(sub, add);
131 } catch (Exception e) {
132 log.error("Failed to notify Subnet change {}",
139 public void notifySpanPortChange(Node node, List<NodeConnector> ports, boolean add) {
140 synchronized (spanAware) {
141 for (Object sa : spanAware) {
143 ((ISpanAware) sa).spanUpdate(node, ports, add);
144 } catch (Exception e) {
145 log.error("Failed to notify Span Interface change {}",
152 private void notifyModeChange(Node node, boolean proactive) {
153 synchronized (switchManagerAware) {
154 for (ISwitchManagerAware service : switchManagerAware) {
156 service.modeChangeNotify(node, proactive);
157 } catch (Exception e) {
158 log.error("Failed to notify Subnet change {}",
165 public void startUp() {
166 // Instantiate cluster synced variables
170 // Add controller MAC, if first node in the cluster
171 if ((!controllerProps.containsKey(MacAddress.name)) && (controllerProperties != null)) {
172 Property controllerMac = controllerProperties.getControllerProperty(MacAddress.name);
173 if (controllerMac != null) {
174 Property existing = controllerProps.putIfAbsent(MacAddress.name, controllerMac);
175 if (existing == null && log.isTraceEnabled()) {
176 log.trace("Container {}: Setting controller MAC address in the cluster: {}", getContainerName(),
183 public void shutDown() {
186 private void allocateCaches() {
187 if (this.clusterContainerService == null) {
188 this.nonClusterObjectCreate();
189 log.warn("un-initialized clusterContainerService, can't create cache");
194 clusterContainerService.createCache(
195 "switchmanager.subnetsConfigList",
196 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
197 clusterContainerService.createCache("switchmanager.spanConfigList",
198 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
199 clusterContainerService.createCache("switchmanager.nodeConfigList",
200 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
201 clusterContainerService.createCache("switchmanager.subnets",
202 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
203 clusterContainerService.createCache("switchmanager.nodeProps",
204 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
205 clusterContainerService.createCache(
206 "switchmanager.nodeConnectorProps",
207 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
208 clusterContainerService.createCache(
209 "switchmanager.nodeConnectorNames",
210 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
211 clusterContainerService.createCache(
212 "switchmanager.controllerProps",
213 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
214 } catch (CacheConfigException cce) {
215 log.error("\nCache configuration invalid - check cache mode");
216 } catch (CacheExistException ce) {
217 log.error("\nCache already exits - destroy and recreate if needed");
221 @SuppressWarnings({ "unchecked" })
222 private void retrieveCaches() {
223 if (this.clusterContainerService == null) {
224 log.warn("un-initialized clusterContainerService, can't create cache");
228 subnetsConfigList = (ConcurrentMap<String, SubnetConfig>) clusterContainerService
229 .getCache("switchmanager.subnetsConfigList");
230 if (subnetsConfigList == null) {
231 log.error("\nFailed to get cache for subnetsConfigList");
234 spanConfigList = (ConcurrentMap<SpanConfig, SpanConfig>) clusterContainerService
235 .getCache("switchmanager.spanConfigList");
236 if (spanConfigList == null) {
237 log.error("\nFailed to get cache for spanConfigList");
240 nodeConfigList = (ConcurrentMap<String, SwitchConfig>) clusterContainerService
241 .getCache("switchmanager.nodeConfigList");
242 if (nodeConfigList == null) {
243 log.error("\nFailed to get cache for nodeConfigList");
246 subnets = (ConcurrentMap<InetAddress, Subnet>) clusterContainerService
247 .getCache("switchmanager.subnets");
248 if (subnets == null) {
249 log.error("\nFailed to get cache for subnets");
252 nodeProps = (ConcurrentMap<Node, Map<String, Property>>) clusterContainerService
253 .getCache("switchmanager.nodeProps");
254 if (nodeProps == null) {
255 log.error("\nFailed to get cache for nodeProps");
258 nodeConnectorProps = (ConcurrentMap<NodeConnector, Map<String, Property>>) clusterContainerService
259 .getCache("switchmanager.nodeConnectorProps");
260 if (nodeConnectorProps == null) {
261 log.error("\nFailed to get cache for nodeConnectorProps");
264 nodeConnectorNames = (ConcurrentMap<Node, Map<String, NodeConnector>>) clusterContainerService
265 .getCache("switchmanager.nodeConnectorNames");
266 if (nodeConnectorNames == null) {
267 log.error("\nFailed to get cache for nodeConnectorNames");
270 controllerProps = (ConcurrentMap<String, Property>) clusterContainerService
271 .getCache("switchmanager.controllerProps");
272 if (controllerProps == null) {
273 log.error("\nFailed to get cache for controllerProps");
277 private void nonClusterObjectCreate() {
278 subnetsConfigList = new ConcurrentHashMap<String, SubnetConfig>();
279 spanConfigList = new ConcurrentHashMap<SpanConfig, SpanConfig>();
280 nodeConfigList = new ConcurrentHashMap<String, SwitchConfig>();
281 subnets = new ConcurrentHashMap<InetAddress, Subnet>();
282 nodeProps = new ConcurrentHashMap<Node, Map<String, Property>>();
283 nodeConnectorProps = new ConcurrentHashMap<NodeConnector, Map<String, Property>>();
284 nodeConnectorNames = new ConcurrentHashMap<Node, Map<String, NodeConnector>>();
285 controllerProps = new ConcurrentHashMap<String, Property>();
289 public List<SubnetConfig> getSubnetsConfigList() {
290 // if there are no subnets, return the default subnet
291 if(subnetsConfigList.size() == 0){
292 return Collections.singletonList(DEFAULT_SUBNETCONFIG);
294 return new ArrayList<SubnetConfig>(subnetsConfigList.values());
299 public SubnetConfig getSubnetConfig(String subnet) {
300 // if there are no subnets, return the default subnet
301 if(subnetsConfigList.isEmpty() && subnet.equalsIgnoreCase(DEFAULT_SUBNET_NAME)){
302 return DEFAULT_SUBNETCONFIG;
304 return subnetsConfigList.get(subnet);
308 private List<SpanConfig> getSpanConfigList(Node node) {
309 List<SpanConfig> confList = new ArrayList<SpanConfig>();
310 String nodeId = node.toString();
311 for (SpanConfig conf : spanConfigList.values()) {
312 if (conf.matchNode(nodeId)) {
319 public List<SwitchConfig> getNodeConfigList() {
320 return new ArrayList<SwitchConfig>(nodeConfigList.values());
324 public SwitchConfig getSwitchConfig(String switchId) {
325 return nodeConfigList.get(switchId);
328 public Switch getSwitchByNode(Node node) {
329 Switch sw = new Switch(node);
331 MacAddress mac = (MacAddress) this.getNodeProp(node,
334 sw.setDataLayerAddress(mac.getMacAddress());
336 Set<NodeConnector> ncSet = getPhysicalNodeConnectors(node);
337 sw.setNodeConnectors(ncSet);
339 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
340 for (NodeConnector nodeConnector : ncSet) {
341 if (spanNodeConnectors.contains(nodeConnector)) {
342 ncList.add(nodeConnector);
345 sw.addSpanPorts(ncList);
351 public List<Switch> getNetworkDevices() {
352 List<Switch> swList = new ArrayList<Switch>();
353 for (Node node : getNodes()) {
354 swList.add(getSwitchByNode(node));
359 private Status updateConfig(SubnetConfig conf, boolean add) {
361 if(subnetsConfigList.putIfAbsent(conf.getName(), conf) != null) {
362 String msg = "Cluster conflict: Subnet with name " + conf.getName() + "already exists.";
363 return new Status(StatusCode.CONFLICT, msg);
366 subnetsConfigList.remove(conf.getName());
368 return new Status(StatusCode.SUCCESS);
371 private Status updateDatabase(SubnetConfig conf, boolean add) {
373 Subnet subnetCurr = subnets.get(conf.getIPAddress());
375 if (subnetCurr == null) {
376 subnet = new Subnet(conf);
378 subnet = subnetCurr.clone();
380 // In case of API3 call we may receive the ports along with the
382 if (!conf.isGlobal()) {
383 subnet.addNodeConnectors(conf.getNodeConnectors());
385 boolean putNewSubnet = false;
386 if(subnetCurr == null) {
387 if(subnets.putIfAbsent(conf.getIPAddress(), subnet) == null) {
391 putNewSubnet = subnets.replace(conf.getIPAddress(), subnetCurr, subnet);
394 String msg = "Cluster conflict: Conflict while adding the subnet " + conf.getIPAddress();
395 return new Status(StatusCode.CONFLICT, msg);
398 // Subnet removal case
400 subnets.remove(conf.getIPAddress());
402 return new Status(StatusCode.SUCCESS);
405 private Status semanticCheck(SubnetConfig conf) {
406 Set<InetAddress> IPs = subnets.keySet();
408 return new Status(StatusCode.SUCCESS);
410 Subnet newSubnet = new Subnet(conf);
411 for (InetAddress i : IPs) {
412 Subnet existingSubnet = subnets.get(i);
413 if ((existingSubnet != null) && !existingSubnet.isMutualExclusive(newSubnet)) {
414 return new Status(StatusCode.CONFLICT, "This subnet conflicts with an existing one.");
417 return new Status(StatusCode.SUCCESS);
420 private Status addRemoveSubnet(SubnetConfig conf, boolean isAdding) {
421 // Valid configuration check
422 Status status = conf.validate();
423 if (!status.isSuccess()) {
424 log.warn(status.getDescription());
430 if (subnetsConfigList.containsKey(conf.getName())) {
431 return new Status(StatusCode.CONFLICT,
432 "Subnet with the specified name already exists.");
435 status = semanticCheck(conf);
436 if (!status.isSuccess()) {
440 if (conf.getName().equalsIgnoreCase(DEFAULT_SUBNET_NAME)) {
441 return new Status(StatusCode.NOTALLOWED, "The specified subnet gateway cannot be removed");
446 status = updateDatabase(conf, isAdding);
448 if (status.isSuccess()) {
449 // Update Configuration
450 status = updateConfig(conf, isAdding);
451 if(!status.isSuccess()) {
452 updateDatabase(conf, (!isAdding));
454 // update the listeners
455 Subnet subnetCurr = subnets.get(conf.getIPAddress());
457 if (subnetCurr == null) {
458 subnet = new Subnet(conf);
460 subnet = subnetCurr.clone();
462 notifySubnetChange(subnet, isAdding);
470 * Adds Subnet configured in GUI or API3
473 public Status addSubnet(SubnetConfig conf) {
474 return this.addRemoveSubnet(conf, true);
478 public Status removeSubnet(SubnetConfig conf) {
479 return this.addRemoveSubnet(conf, false);
483 public Status removeSubnet(String name) {
484 if (name.equalsIgnoreCase(DEFAULT_SUBNET_NAME)) {
485 return new Status(StatusCode.NOTALLOWED, "The specified subnet gateway cannot be removed");
487 SubnetConfig conf = subnetsConfigList.get(name);
489 return new Status(StatusCode.SUCCESS, "Subnet not present");
491 return this.addRemoveSubnet(conf, false);
495 public Status modifySubnet(SubnetConfig conf) {
498 return new Status(StatusCode.BADREQUEST, "Invalid Subnet configuration: null");
501 // Valid configuration check
502 Status status = conf.validate();
503 if (!status.isSuccess()) {
504 log.warn(status.getDescription());
508 // If a subnet configuration with this name does not exist, consider this is a creation
509 SubnetConfig target = subnetsConfigList.get(conf.getName());
510 if (target == null) {
511 return this.addSubnet(conf);
515 if (target.equals(conf)) {
516 return new Status(StatusCode.SUCCESS);
519 // Check not allowed modifications
520 if (!target.getSubnet().equals(conf.getSubnet())) {
521 return new Status(StatusCode.BADREQUEST, "IP address change is not allowed");
524 // Derive the set of node connectors that are being removed
525 Set<NodeConnector> toRemove = target.getNodeConnectors();
526 toRemove.removeAll(conf.getNodeConnectors());
527 List<String> nodeConnectorStrings = null;
528 if (!toRemove.isEmpty()) {
529 nodeConnectorStrings = new ArrayList<String>();
530 for (NodeConnector nc : toRemove) {
531 nodeConnectorStrings.add(nc.toString());
533 status = this.removePortsFromSubnet(conf.getName(), nodeConnectorStrings);
534 if (!status.isSuccess()) {
539 // Derive the set of node connectors that are being added
540 Set<NodeConnector> toAdd = conf.getNodeConnectors();
541 toAdd.removeAll(target.getNodeConnectors());
542 if (!toAdd.isEmpty()) {
543 List<String> nodeConnectorStringRemoved = nodeConnectorStrings;
544 nodeConnectorStrings = new ArrayList<String>();
545 for (NodeConnector nc : toAdd) {
546 nodeConnectorStrings.add(nc.toString());
548 status = this.addPortsToSubnet(conf.getName(), nodeConnectorStrings);
549 if (!status.isSuccess()) {
550 // If any port was removed, add it back as a best recovery effort
551 if (!toRemove.isEmpty()) {
552 this.addPortsToSubnet(conf.getName(), nodeConnectorStringRemoved);
558 // Update Configuration
559 subnetsConfigList.put(conf.getName(), conf);
561 return new Status(StatusCode.SUCCESS);
565 public Status addPortsToSubnet(String name, List<String> switchPorts) {
567 return new Status(StatusCode.BADREQUEST, "Null subnet name");
569 SubnetConfig confCurr = subnetsConfigList.get(name);
570 if (confCurr == null) {
571 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
574 if (switchPorts == null || switchPorts.isEmpty()) {
575 return new Status(StatusCode.BADREQUEST, "Null or empty port set");
578 Subnet subCurr = subnets.get(confCurr.getIPAddress());
579 if (subCurr == null) {
580 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress());
581 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
585 Subnet sub = subCurr.clone();
586 Set<NodeConnector> sp = NodeConnector.fromString(switchPorts);
587 sub.addNodeConnectors(sp);
588 boolean subnetsReplaced = subnets.replace(confCurr.getIPAddress(), subCurr, sub);
589 if (!subnetsReplaced) {
590 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
591 return new Status(StatusCode.CONFLICT, msg);
594 // Update Configuration
595 SubnetConfig conf = confCurr.clone();
596 conf.addNodeConnectors(switchPorts);
597 boolean configReplaced = subnetsConfigList.replace(name, confCurr, conf);
598 if (!configReplaced) {
599 // TODO: recovery using Transactionality
600 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
601 return new Status(StatusCode.CONFLICT, msg);
604 return new Status(StatusCode.SUCCESS);
608 public Status removePortsFromSubnet(String name, List<String> switchPorts) {
610 return new Status(StatusCode.BADREQUEST, "Null subnet name");
612 SubnetConfig confCurr = subnetsConfigList.get(name);
613 if (confCurr == null) {
614 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
617 if (switchPorts == null || switchPorts.isEmpty()) {
618 return new Status(StatusCode.BADREQUEST, "Null or empty port set");
621 Subnet subCurr = subnets.get(confCurr.getIPAddress());
622 if (subCurr == null) {
623 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress());
624 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
628 Status status = SubnetConfig.validatePorts(switchPorts);
629 if (!status.isSuccess()) {
633 Subnet sub = subCurr.clone();
634 Set<NodeConnector> sp = NodeConnector.fromString(switchPorts);
635 sub.deleteNodeConnectors(sp);
636 boolean subnetsReplace = subnets.replace(confCurr.getIPAddress(), subCurr, sub);
637 if (!subnetsReplace) {
638 String msg = "Cluster conflict: Conflict while removing ports from the subnet " + name;
639 return new Status(StatusCode.CONFLICT, msg);
642 // Update Configuration
643 SubnetConfig conf = confCurr.clone();
644 conf.removeNodeConnectors(switchPorts);
645 boolean result = subnetsConfigList.replace(name, confCurr, conf);
647 // TODO: recovery using Transactionality
648 String msg = "Cluster conflict: Conflict while removing ports from " + conf;
649 return new Status(StatusCode.CONFLICT, msg);
652 return new Status(StatusCode.SUCCESS);
655 public String getContainerName() {
656 if (containerName == null) {
657 return GlobalConstants.DEFAULT.toString();
659 return containerName;
663 public Subnet getSubnetByNetworkAddress(InetAddress networkAddress) {
664 // if there are no subnets, return the default subnet
665 if (subnets.size() == 0) {
666 return DEFAULT_SUBNET;
669 for(Map.Entry<InetAddress,Subnet> subnetEntry : subnets.entrySet()) {
670 if(subnetEntry.getValue().isSubnetOf(networkAddress)) {
671 return subnetEntry.getValue();
678 public Object readObject(ObjectInputStream ois)
679 throws FileNotFoundException, IOException, ClassNotFoundException {
680 // Perform the class deserialization locally, from inside the package
681 // where the class is defined
682 return ois.readObject();
685 private void loadSubnetConfiguration() {
686 for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, SUBNETS_FILE_NAME)) {
687 addSubnet((SubnetConfig) conf);
691 private void loadSpanConfiguration() {
692 for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, SPAN_FILE_NAME)) {
693 addSpanConfig((SpanConfig) conf);
697 private void loadSwitchConfiguration() {
698 for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, SWITCH_CONFIG_FILE_NAME)) {
699 updateNodeConfig((SwitchConfig) conf);
703 @SuppressWarnings("deprecation")
705 public void updateSwitchConfig(SwitchConfig cfgObject) {
706 // update default container only
707 if (!isDefaultContainer) {
711 SwitchConfig sc = nodeConfigList.get(cfgObject.getNodeId());
713 if (nodeConfigList.putIfAbsent(cfgObject.getNodeId(), cfgObject) != null) {
717 if (!nodeConfigList.replace(cfgObject.getNodeId(), sc, cfgObject)) {
722 boolean modeChange = false;
724 if ((sc == null) || !cfgObject.getMode().equals(sc.getMode())) {
728 String nodeId = cfgObject.getNodeId();
729 Node node = Node.fromString(nodeId);
730 Map<String, Property> propMapCurr = nodeProps.get(node);
731 if (propMapCurr == null) {
734 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
735 Property desc = new Description(cfgObject.getNodeDescription());
736 propMap.put(desc.getName(), desc);
737 Property tier = new Tier(Integer.parseInt(cfgObject.getTier()));
738 propMap.put(tier.getName(), tier);
740 if (!nodeProps.replace(node, propMapCurr, propMap)) {
741 // TODO rollback using Transactionality
745 log.trace("Set Node {}'s Mode to {}", nodeId, cfgObject.getMode());
748 notifyModeChange(node, cfgObject.isProactive());
753 public Status updateNodeConfig(SwitchConfig switchConfig) {
754 Status status = switchConfig.validate();
755 if (!status.isSuccess()) {
759 Map<String, Property> updateProperties = switchConfig.getNodeProperties();
760 ForwardingMode mode = (ForwardingMode) updateProperties.get(ForwardingMode.name);
762 if (isDefaultContainer) {
763 if (!mode.isValid()) {
764 return new Status(StatusCode.BADREQUEST, "Invalid Forwarding Mode Value");
767 return new Status(StatusCode.NOTACCEPTABLE,
768 "Forwarding Mode modification is allowed only in default container");
772 Description description = (Description) switchConfig.getProperty(Description.propertyName);
773 String nodeId = switchConfig.getNodeId();
774 Node node = Node.fromString(nodeId);
775 NodeDescription nodeDesc = (this.statisticsManager == null) ? null : this.statisticsManager
776 .getNodeDescription(node);
777 String advertisedDesc = (nodeDesc == null) ? "" : nodeDesc.getDescription();
778 if (description != null && description.getValue() != null) {
779 if (description.getValue().isEmpty() || description.getValue().equals(advertisedDesc)) {
780 updateProperties.remove(Description.propertyName);
781 switchConfig = new SwitchConfig(nodeId, updateProperties);
783 // check if description is configured or was published by any other node
784 for (Map.Entry<Node, Map<String, Property>> entry : nodeProps.entrySet()) {
785 Node n = entry.getKey();
786 Description desc = (Description) getNodeProp(n, Description.propertyName);
787 NodeDescription nDesc = (this.statisticsManager == null) ? null : this.statisticsManager
788 .getNodeDescription(n);
789 String advDesc = (nDesc == null) ? "" : nDesc.getDescription();
790 if ((description.equals(desc) || description.getValue().equals(advDesc)) && !node.equals(n)) {
791 return new Status(StatusCode.CONFLICT, "Node name already in use");
797 boolean modeChange = false;
798 SwitchConfig sc = nodeConfigList.get(nodeId);
799 Map<String, Property> prevNodeProperties = new HashMap<String, Property>();
801 if ((mode != null) && mode.isProactive()) {
804 if (!updateProperties.isEmpty()) {
805 if (nodeConfigList.putIfAbsent(nodeId, switchConfig) != null) {
806 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
810 prevNodeProperties = new HashMap<String, Property>(sc.getNodeProperties());
811 ForwardingMode prevMode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
813 if ((prevMode != null) && (prevMode.isProactive())) {
817 if (((prevMode != null) && (prevMode.getValue() != mode.getValue()))
818 || (prevMode == null && mode.isProactive())) {
822 if (updateProperties.isEmpty()) {
823 nodeConfigList.remove(nodeId);
825 if (!nodeConfigList.replace(nodeId, sc, switchConfig)) {
826 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
830 Map<String, Property> propMapCurr = nodeProps.get(node);
831 if (propMapCurr == null) {
832 return new Status(StatusCode.SUCCESS);
834 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
835 for (Map.Entry<String, Property> entry : prevNodeProperties.entrySet()) {
836 String prop = entry.getKey();
837 if (!updateProperties.containsKey(prop)) {
838 if (prop.equals(Description.propertyName)) {
839 if (advertisedDesc != null) {
840 if (!advertisedDesc.isEmpty()) {
841 Property desc = new Description(advertisedDesc);
842 propMap.put(Description.propertyName, desc);
846 propMap.remove(prop);
849 } else if (prop.equals(ForwardingMode.name)) {
850 Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING);
851 propMap.put(ForwardingMode.name, defaultMode);
854 propMap.remove(prop);
857 propMap.putAll(updateProperties);
858 if (!nodeProps.replace(node, propMapCurr, propMap)) {
859 // TODO rollback using Transactionality
860 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
863 notifyModeChange(node, (mode == null) ? false : mode.isProactive());
865 return new Status(StatusCode.SUCCESS);
869 public Status removeNodeConfig(String nodeId) {
870 if ((nodeId == null) || (nodeId.isEmpty())) {
871 return new Status(StatusCode.BADREQUEST, "nodeId cannot be empty.");
873 Map<String, Property> nodeProperties = getSwitchConfig(nodeId).getNodeProperties();
874 Node node = Node.fromString(nodeId);
875 Map<String, Property> propMapCurr = nodeProps.get(node);
876 if ((propMapCurr != null) && (nodeProperties != null) && (!nodeProperties.isEmpty())) {
877 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
878 for (Map.Entry<String, Property> entry : nodeProperties.entrySet()) {
879 String prop = entry.getKey();
880 if (prop.equals(Description.propertyName)) {
881 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
882 if (nodeProp.get(node) != null) {
883 propMap.put(Description.propertyName, nodeProp.get(node).get(Description.propertyName));
887 propMap.remove(prop);
889 if (!nodeProps.replace(node, propMapCurr, propMap)) {
890 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration.");
893 if (nodeConfigList != null) {
894 nodeConfigList.remove(nodeId);
896 return new Status(StatusCode.SUCCESS);
900 public Status saveSwitchConfig() {
901 return saveSwitchConfigInternal();
904 public Status saveSwitchConfigInternal() {
907 status = configurationService.persistConfiguration(
908 new ArrayList<ConfigurationObject>(subnetsConfigList.values()), SUBNETS_FILE_NAME);
909 if (status.isSuccess()) {
912 log.warn("Failed to save subnet gateway configurations: " + status.getDescription());
914 status = configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(spanConfigList.values()),
916 if (status.isSuccess()) {
919 log.warn("Failed to save span port configurations: " + status.getDescription());
921 status = configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(nodeConfigList.values()),
922 SWITCH_CONFIG_FILE_NAME);
923 if (status.isSuccess()) {
926 log.warn("Failed to save node configurations: " + status.getDescription());
929 return new Status(StatusCode.INTERNALERROR, "Save failed");
932 return new Status(StatusCode.INTERNALERROR, "Partial save failure");
938 public List<SpanConfig> getSpanConfigList() {
939 return new ArrayList<SpanConfig>(spanConfigList.values());
943 public Status addSpanConfig(SpanConfig conf) {
944 // Valid config check
945 if (!conf.isValidConfig()) {
946 String msg = "Invalid Span configuration";
948 return new Status(StatusCode.BADREQUEST, msg);
952 if (spanConfigList.containsKey(conf)) {
953 return new Status(StatusCode.CONFLICT, "Same span config exists");
956 // Update configuration
957 if (spanConfigList.putIfAbsent(conf, conf) == null) {
958 // Update database and notify clients
959 addSpanPorts(conf.getNode(), conf.getPortArrayList());
962 return new Status(StatusCode.SUCCESS);
966 public Status removeSpanConfig(SpanConfig conf) {
967 removeSpanPorts(conf.getNode(), conf.getPortArrayList());
969 // Update configuration
970 spanConfigList.remove(conf);
972 return new Status(StatusCode.SUCCESS);
976 public List<NodeConnector> getSpanPorts(Node node) {
977 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
979 for (NodeConnector nodeConnector : spanNodeConnectors) {
980 if (nodeConnector.getNode().equals(node)) {
981 ncList.add(nodeConnector);
987 private void addNode(Node node, Set<Property> props) {
988 log.trace("{} added, props: {}", node, props);
989 if (nodeProps == null) {
993 Map<String, Property> propMapCurr = nodeProps.get(node);
994 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
995 : new HashMap<String, Property>(propMapCurr);
997 // copy node properties from plugin
999 for (Property prop : props) {
1000 propMap.put(prop.getName(), prop);
1004 boolean forwardingModeChanged = false;
1006 // copy node properties from config
1007 if (nodeConfigList != null) {
1008 String nodeId = node.toString();
1009 SwitchConfig conf = nodeConfigList.get(nodeId);
1010 if (conf != null && (conf.getNodeProperties() != null)) {
1011 Map<String, Property> nodeProperties = conf.getNodeProperties();
1012 propMap.putAll(nodeProperties);
1013 if (nodeProperties.get(ForwardingMode.name) != null) {
1014 ForwardingMode mode = (ForwardingMode) nodeProperties.get(ForwardingMode.name);
1015 forwardingModeChanged = mode.isProactive();
1020 if (!propMap.containsKey(ForwardingMode.name)) {
1021 Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING);
1022 propMap.put(ForwardingMode.name, defaultMode);
1025 boolean propsAdded = false;
1026 // Attempt initial add
1027 if (nodeProps.putIfAbsent(node, propMap) == null) {
1030 /* Notify listeners only for initial node addition
1031 * to avoid expensive tasks triggered by redundant notifications
1033 notifyNode(node, UpdateType.ADDED, propMap);
1036 propsAdded = nodeProps.replace(node, propMapCurr, propMap);
1038 // check whether forwarding mode changed
1039 if (propMapCurr.get(ForwardingMode.name) != null) {
1040 ForwardingMode mode = (ForwardingMode) propMapCurr.get(ForwardingMode.name);
1041 forwardingModeChanged ^= mode.isProactive();
1045 log.debug("Cluster conflict while adding node {}. Overwriting with latest props: {}", node.getID(), props);
1046 addNodeProps(node, propMap);
1049 // check if span ports are configured
1051 // notify proactive mode forwarding
1052 if (forwardingModeChanged) {
1053 notifyModeChange(node, true);
1057 private void removeNode(Node node) {
1058 log.trace("{} removed", node);
1059 if (nodeProps == null) {
1063 if (nodeProps.remove(node) == null) {
1064 log.debug("Received redundant node REMOVED udate for {}. Skipping..", node);
1068 nodeConnectorNames.remove(node);
1069 Set<NodeConnector> removeNodeConnectorSet = new HashSet<NodeConnector>();
1070 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1071 NodeConnector nodeConnector = entry.getKey();
1072 if (nodeConnector.getNode().equals(node)) {
1073 removeNodeConnectorSet.add(nodeConnector);
1076 for (NodeConnector nc : removeNodeConnectorSet) {
1077 nodeConnectorProps.remove(nc);
1080 // check if span ports need to be cleaned up
1081 removeSpanPorts(node);
1083 /* notify node listeners */
1084 notifyNode(node, UpdateType.REMOVED, null);
1087 private void updateNode(Node node, Set<Property> props) {
1088 log.trace("{} updated, props: {}", node, props);
1089 if (nodeProps == null || props == null) {
1093 Map<String, Property> propMapCurr = nodeProps.get(node);
1094 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1095 : new HashMap<String, Property>(propMapCurr);
1097 // copy node properties from plugin
1098 String nodeId = node.toString();
1099 for (Property prop : props) {
1100 if (nodeConfigList != null) {
1101 SwitchConfig conf = nodeConfigList.get(nodeId);
1102 if (conf != null && (conf.getNodeProperties() != null)
1103 && conf.getNodeProperties().containsKey(prop.getName())) {
1107 propMap.put(prop.getName(), prop);
1110 if (propMapCurr == null) {
1111 if (nodeProps.putIfAbsent(node, propMap) != null) {
1112 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1113 node.getID(), props);
1114 addNodeProps(node, propMap);
1117 if (!nodeProps.replace(node, propMapCurr, propMap)) {
1118 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1119 node.getID(), props);
1120 addNodeProps(node, propMap);
1124 /* notify node listeners */
1125 notifyNode(node, UpdateType.CHANGED, propMap);
1129 public void updateNode(Node node, UpdateType type, Set<Property> props) {
1130 log.debug("updateNode: {} type {} props {} for container {}",
1131 new Object[] { node, type, props, containerName });
1134 addNode(node, props);
1137 updateNode(node, props);
1148 public void updateNodeConnector(NodeConnector nodeConnector,
1149 UpdateType type, Set<Property> props) {
1150 Map<String, Property> propMap = new HashMap<String, Property>();
1151 boolean update = true;
1153 log.debug("updateNodeConnector: {} type {} props {} for container {}",
1154 new Object[] { nodeConnector, type, props, containerName });
1156 if (nodeConnectorProps == null) {
1162 // Skip redundant ADDED update (e.g. cluster switch-over)
1163 if (nodeConnectorProps.containsKey(nodeConnector)) {
1164 log.debug("Redundant nodeconnector ADDED for {}, props {} for container {}",
1165 nodeConnector, props, containerName);
1169 if (props != null) {
1170 for (Property prop : props) {
1171 addNodeConnectorProp(nodeConnector, prop);
1172 propMap.put(prop.getName(), prop);
1175 addNodeConnectorProp(nodeConnector, null);
1179 addSpanPort(nodeConnector);
1182 if (!nodeConnectorProps.containsKey(nodeConnector) || (props == null)) {
1185 for (Property prop : props) {
1186 addNodeConnectorProp(nodeConnector, prop);
1187 propMap.put(prop.getName(), prop);
1192 if (!nodeConnectorProps.containsKey(nodeConnector)) {
1195 removeNodeConnectorAllProps(nodeConnector);
1197 // clean up span config
1198 removeSpanPort(nodeConnector);
1206 notifyNodeConnector(nodeConnector, type, propMap);
1211 public Set<Node> getNodes() {
1212 return (nodeProps != null) ? new HashSet<Node>(nodeProps.keySet()) : new HashSet<Node>();
1216 public Map<String, Property> getControllerProperties() {
1217 return new HashMap<String, Property>(this.controllerProps);
1221 public Property getControllerProperty(String propertyName) {
1222 if (propertyName != null) {
1223 HashMap<String, Property> propertyMap = new HashMap<String, Property>(this.controllerProps);
1224 return propertyMap.get(propertyName);
1230 public Status setControllerProperty(Property property) {
1231 if (property != null) {
1232 this.controllerProps.put(property.getName(), property);
1233 return new Status(StatusCode.SUCCESS);
1235 return new Status(StatusCode.BADREQUEST, "Invalid property provided when setting property");
1239 public Status removeControllerProperty(String propertyName) {
1240 if (propertyName != null) {
1241 if (this.controllerProps.containsKey(propertyName)) {
1242 this.controllerProps.remove(propertyName);
1243 if (!this.controllerProps.containsKey(propertyName)) {
1244 return new Status(StatusCode.SUCCESS);
1247 String msg = "Unable to remove property " + propertyName + " from Controller";
1248 return new Status(StatusCode.BADREQUEST, msg);
1250 String msg = "Invalid property provided when removing property from Controller";
1251 return new Status(StatusCode.BADREQUEST, msg);
1255 * Returns a copy of a list of properties for a given node
1260 * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps
1261 * (org.opendaylight.controller.sal.core.Node)
1264 public Map<String, Property> getNodeProps(Node node) {
1265 Map<String, Property> rv = new HashMap<String, Property>();
1266 if (this.nodeProps != null) {
1267 rv = this.nodeProps.get(node);
1269 /* make a copy of it */
1270 rv = new HashMap<String, Property>(rv);
1277 public Property getNodeProp(Node node, String propName) {
1278 Map<String, Property> propMap = getNodeProps(node);
1279 return (propMap != null) ? propMap.get(propName) : null;
1283 public void setNodeProp(Node node, Property prop) {
1285 for (int i = 0; i <= REPLACE_RETRY; i++) {
1286 /* Get a copy of the property map */
1287 Map<String, Property> propMapCurr = getNodeProps(node);
1288 if (propMapCurr == null) {
1292 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1293 propMap.put(prop.getName(), prop);
1295 if (nodeProps.replace(node, propMapCurr, propMap)) {
1299 log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1303 public Status removeNodeProp(Node node, String propName) {
1304 for (int i = 0; i <= REPLACE_RETRY; i++) {
1305 Map<String, Property> propMapCurr = getNodeProps(node);
1306 if (propMapCurr != null) {
1307 if (!propMapCurr.containsKey(propName)) {
1308 return new Status(StatusCode.SUCCESS);
1310 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1311 propMap.remove(propName);
1312 if (nodeProps.replace(node, propMapCurr, propMap)) {
1313 return new Status(StatusCode.SUCCESS);
1316 return new Status(StatusCode.SUCCESS);
1319 String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID();
1320 return new Status(StatusCode.CONFLICT, msg);
1324 public Status removeNodeAllProps(Node node) {
1325 this.nodeProps.remove(node);
1326 return new Status(StatusCode.SUCCESS);
1330 public Set<NodeConnector> getUpNodeConnectors(Node node) {
1331 if (nodeConnectorProps == null) {
1335 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1336 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1337 NodeConnector nodeConnector = entry.getKey();
1338 if (!nodeConnector.getNode().equals(node)) {
1341 if (isNodeConnectorEnabled(nodeConnector)) {
1342 nodeConnectorSet.add(nodeConnector);
1346 return nodeConnectorSet;
1350 public Set<NodeConnector> getNodeConnectors(Node node) {
1351 if (nodeConnectorProps == null) {
1355 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1356 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1357 NodeConnector nodeConnector = entry.getKey();
1358 if (!nodeConnector.getNode().equals(node)) {
1361 nodeConnectorSet.add(nodeConnector);
1364 return nodeConnectorSet;
1368 public Set<NodeConnector> getPhysicalNodeConnectors(Node node) {
1369 if (nodeConnectorProps == null) {
1373 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1374 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1375 NodeConnector nodeConnector = entry.getKey();
1376 if (!nodeConnector.getNode().equals(node)
1377 || isSpecial(nodeConnector)) {
1380 nodeConnectorSet.add(nodeConnector);
1383 return nodeConnectorSet;
1387 public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) {
1388 Map<String, Property> rv = new HashMap<String, Property>();
1389 if (this.nodeConnectorProps != null) {
1390 rv = this.nodeConnectorProps.get(nodeConnector);
1392 rv = new HashMap<String, Property>(rv);
1399 public Property getNodeConnectorProp(NodeConnector nodeConnector,
1401 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1402 return (propMap != null) ? propMap.get(propName) : null;
1406 public byte[] getControllerMAC() {
1407 MacAddress macProperty = (MacAddress)controllerProps.get(MacAddress.name);
1408 return (macProperty == null) ? null : macProperty.getMacAddress();
1412 public NodeConnector getNodeConnector(Node node, String nodeConnectorName) {
1413 if (nodeConnectorNames == null) {
1417 Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1422 return map.get(nodeConnectorName);
1426 * Adds a node connector and its property if any
1428 * @param nodeConnector
1429 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1431 * name of {@link org.opendaylight.controller.sal.core.Property}
1432 * @return success or failed reason
1435 public Status addNodeConnectorProp(NodeConnector nodeConnector,
1437 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1438 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1439 : new HashMap<String, Property>(propMapCurr);
1441 String msg = "Cluster conflict: Unable to add NodeConnector Property.";
1442 // Just add the nodeConnector if prop is not available (in a non-default
1445 if (propMapCurr == null) {
1446 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1447 return new Status(StatusCode.CONFLICT, msg);
1450 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1451 return new Status(StatusCode.CONFLICT, msg);
1454 return new Status(StatusCode.SUCCESS);
1457 propMap.put(prop.getName(), prop);
1458 if (propMapCurr == null) {
1459 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1460 return new Status(StatusCode.CONFLICT, msg);
1463 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1464 return new Status(StatusCode.CONFLICT, msg);
1468 if (prop.getName().equals(Name.NamePropName)) {
1469 if (nodeConnectorNames != null) {
1470 Node node = nodeConnector.getNode();
1471 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1472 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1473 if (mapCurr != null) {
1474 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1475 String s = entry.getKey();
1477 map.put(s, new NodeConnector(entry.getValue()));
1478 } catch (ConstructionException e) {
1479 log.error("An error occured",e);
1484 map.put(((Name) prop).getValue(), nodeConnector);
1485 if (mapCurr == null) {
1486 if (nodeConnectorNames.putIfAbsent(node, map) != null) {
1487 // TODO: recovery using Transactionality
1488 return new Status(StatusCode.CONFLICT, msg);
1491 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1492 // TODO: recovery using Transactionality
1493 return new Status(StatusCode.CONFLICT, msg);
1499 return new Status(StatusCode.SUCCESS);
1503 * Removes one property of a node connector
1505 * @param nodeConnector
1506 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1508 * name of {@link org.opendaylight.controller.sal.core.Property}
1509 * @return success or failed reason
1512 public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) {
1513 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1515 if (propMapCurr == null) {
1516 /* Nothing to remove */
1517 return new Status(StatusCode.SUCCESS);
1520 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1521 propMap.remove(propName);
1522 boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap);
1523 String msg = "Cluster conflict: Unable to remove NodeConnector property.";
1525 return new Status(StatusCode.CONFLICT, msg);
1528 if (propName.equals(Name.NamePropName)) {
1529 if (nodeConnectorNames != null) {
1530 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1532 Node node = nodeConnector.getNode();
1533 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1534 if (mapCurr != null) {
1535 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1536 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1537 String s = entry.getKey();
1539 map.put(s, new NodeConnector(entry.getValue()));
1540 } catch (ConstructionException e) {
1541 log.error("An error occured",e);
1544 map.remove(name.getValue());
1545 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1546 // TODO: recovery using Transactionality
1547 return new Status(StatusCode.CONFLICT, msg);
1554 return new Status(StatusCode.SUCCESS);
1558 * Removes all the properties of a node connector
1560 * @param nodeConnector
1561 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1562 * @return success or failed reason
1565 public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) {
1566 if (nodeConnectorNames != null) {
1567 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1569 Node node = nodeConnector.getNode();
1570 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1571 if (mapCurr != null) {
1572 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1573 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1574 String s = entry.getKey();
1576 map.put(s, new NodeConnector(entry.getValue()));
1577 } catch (ConstructionException e) {
1578 log.error("An error occured",e);
1581 map.remove(name.getValue());
1582 if (map.isEmpty()) {
1583 nodeConnectorNames.remove(node);
1585 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1586 log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.",
1587 nodeConnector.getID());
1594 nodeConnectorProps.remove(nodeConnector);
1596 return new Status(StatusCode.SUCCESS);
1600 * Function called by the dependency manager when all the required
1601 * dependencies are satisfied
1604 void init(Component c) {
1605 Dictionary<?, ?> props = c.getServiceProperties();
1606 if (props != null) {
1607 this.containerName = (String) props.get("containerName");
1608 log.trace("Running containerName: {}", this.containerName);
1610 // In the Global instance case the containerName is empty
1611 this.containerName = "";
1613 isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT
1619 * Function called by the dependency manager when at least one dependency
1620 * become unsatisfied or when the component is shutting down because for
1621 * example bundle is being stopped.
1629 * Function called by dependency manager after "init ()" is called and after
1630 * the services provided by the class are registered in the service registry
1637 * Read startup and build database if we are the coordinator
1639 loadSubnetConfiguration();
1640 loadSpanConfiguration();
1641 loadSwitchConfiguration();
1644 registerWithOSGIConsole();
1648 * Function called after registered the service in OSGi service registry.
1651 // solicit for existing inventories
1656 * Function called by the dependency manager before the services exported by
1657 * the component are unregistered, this will be followed by a "destroy ()"
1664 public void setConfigurationContainerService(IConfigurationContainerService service) {
1665 log.trace("Got configuration service set request {}", service);
1666 this.configurationService = service;
1669 public void unsetConfigurationContainerService(IConfigurationContainerService service) {
1670 log.trace("Got configuration service UNset request");
1671 this.configurationService = null;
1674 public void setInventoryService(IInventoryService service) {
1675 log.trace("Got inventory service set request {}", service);
1676 this.inventoryService = service;
1678 // solicit for existing inventories
1682 public void unsetInventoryService(IInventoryService service) {
1683 log.trace("Got a service UNset request");
1684 this.inventoryService = null;
1686 // clear existing inventories
1690 public void setStatisticsManager(IStatisticsManager statisticsManager) {
1691 log.trace("Got statistics manager set request {}", statisticsManager);
1692 this.statisticsManager = statisticsManager;
1695 public void unsetStatisticsManager(IStatisticsManager statisticsManager) {
1696 log.trace("Got statistics manager UNset request");
1697 this.statisticsManager = null;
1700 public void setSwitchManagerAware(ISwitchManagerAware service) {
1701 log.trace("Got inventory service set request {}", service);
1702 if (this.switchManagerAware != null) {
1703 this.switchManagerAware.add(service);
1706 // bulk update for newly joined
1707 switchManagerAwareNotify(service);
1710 public void unsetSwitchManagerAware(ISwitchManagerAware service) {
1711 log.trace("Got a service UNset request");
1712 if (this.switchManagerAware != null) {
1713 this.switchManagerAware.remove(service);
1717 public void setInventoryListener(IInventoryListener service) {
1718 log.trace("Got inventory listener set request {}", service);
1719 if (this.inventoryListeners != null) {
1720 this.inventoryListeners.add(service);
1723 // bulk update for newly joined
1724 bulkUpdateService(service);
1727 public void unsetInventoryListener(IInventoryListener service) {
1728 log.trace("Got a service UNset request");
1729 if (this.inventoryListeners != null) {
1730 this.inventoryListeners.remove(service);
1734 public void setSpanAware(ISpanAware service) {
1735 log.trace("Got SpanAware set request {}", service);
1736 if (this.spanAware != null) {
1737 this.spanAware.add(service);
1740 // bulk update for newly joined
1741 spanAwareNotify(service);
1744 public void unsetSpanAware(ISpanAware service) {
1745 log.trace("Got a service UNset request");
1746 if (this.spanAware != null) {
1747 this.spanAware.remove(service);
1751 void setClusterContainerService(IClusterContainerServices s) {
1752 log.trace("Cluster Service set");
1753 this.clusterContainerService = s;
1756 void unsetClusterContainerService(IClusterContainerServices s) {
1757 if (this.clusterContainerService == s) {
1758 log.trace("Cluster Service removed!");
1759 this.clusterContainerService = null;
1763 public void setControllerProperties(IControllerProperties controllerProperties) {
1764 log.trace("Got controller properties set request {}", controllerProperties);
1765 this.controllerProperties = controllerProperties;
1768 public void unsetControllerProperties(IControllerProperties controllerProperties) {
1769 log.trace("Got controller properties UNset request");
1770 this.controllerProperties = null;
1773 private void getInventories() {
1774 if (inventoryService == null) {
1775 log.trace("inventory service not avaiable");
1779 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
1780 for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) {
1781 Node node = entry.getKey();
1782 log.debug("getInventories: {} added for container {}", new Object[] { node, containerName });
1783 Map<String, Property> propMap = entry.getValue();
1784 Set<Property> props = new HashSet<Property>();
1785 for (Property property : propMap.values()) {
1786 props.add(property);
1788 addNode(node, props);
1791 Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps();
1792 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) {
1793 Map<String, Property> propMap = entry.getValue();
1794 for (Property property : propMap.values()) {
1795 addNodeConnectorProp(entry.getKey(), property);
1800 private void clearInventories() {
1802 nodeConnectorProps.clear();
1803 nodeConnectorNames.clear();
1804 spanNodeConnectors.clear();
1807 private void notifyNode(Node node, UpdateType type,
1808 Map<String, Property> propMap) {
1809 synchronized (inventoryListeners) {
1810 for (IInventoryListener service : inventoryListeners) {
1811 service.notifyNode(node, type, propMap);
1816 private void notifyNodeConnector(NodeConnector nodeConnector,
1817 UpdateType type, Map<String, Property> propMap) {
1818 synchronized (inventoryListeners) {
1819 for (IInventoryListener service : inventoryListeners) {
1820 service.notifyNodeConnector(nodeConnector, type, propMap);
1826 * For those joined late, bring them up-to-date.
1828 private void switchManagerAwareNotify(ISwitchManagerAware service) {
1829 for (Subnet sub : subnets.values()) {
1830 service.subnetNotify(sub, true);
1833 for (Node node : getNodes()) {
1834 SwitchConfig sc = getSwitchConfig(node.toString());
1835 if ((sc != null) && isDefaultContainer) {
1836 ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
1837 service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive());
1842 private void bulkUpdateService(IInventoryListener service) {
1843 Map<String, Property> propMap;
1844 UpdateType type = UpdateType.ADDED;
1846 for (Node node : getNodes()) {
1847 propMap = nodeProps.get(node);
1848 service.notifyNode(node, type, propMap);
1851 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1852 NodeConnector nodeConnector = entry.getKey();
1853 propMap = nodeConnectorProps.get(nodeConnector);
1854 service.notifyNodeConnector(nodeConnector, type, propMap);
1858 private void spanAwareNotify(ISpanAware service) {
1859 for (Node node : getNodes()) {
1860 for (SpanConfig conf : getSpanConfigList(node)) {
1861 service.spanUpdate(node, conf.getPortArrayList(), true);
1866 private void registerWithOSGIConsole() {
1867 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
1868 .getBundleContext();
1869 bundleContext.registerService(CommandProvider.class.getName(), this,
1874 public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) {
1875 if (nodeConnector == null) {
1879 Config config = (Config) getNodeConnectorProp(nodeConnector,
1880 Config.ConfigPropName);
1881 State state = (State) getNodeConnectorProp(nodeConnector,
1882 State.StatePropName);
1883 return ((config != null) && (config.getValue() == Config.ADMIN_UP)
1884 && (state != null) && (state.getValue() == State.EDGE_UP));
1888 public boolean doesNodeConnectorExist(NodeConnector nc) {
1889 return (nc != null && nodeConnectorProps != null
1890 && nodeConnectorProps.containsKey(nc));
1894 public String getHelp() {
1895 StringBuffer help = new StringBuffer();
1896 help.append("---Switch Manager---\n");
1897 help.append("\t pencs <node id> - Print enabled node connectors for a given node\n");
1898 help.append("\t pdm <node id> - Print switch ports in device map\n");
1899 return help.toString();
1902 public void _pencs(CommandInterpreter ci) {
1903 String st = ci.nextArgument();
1905 ci.println("Please enter node id");
1909 Node node = Node.fromString(st);
1911 ci.println("Please enter node id");
1915 Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node);
1916 if (nodeConnectorSet == null) {
1919 for (NodeConnector nodeConnector : nodeConnectorSet) {
1920 if (nodeConnector == null) {
1923 ci.println(nodeConnector);
1925 ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1928 public void _pdm(CommandInterpreter ci) {
1929 String st = ci.nextArgument();
1931 ci.println("Please enter node id");
1935 Node node = Node.fromString(st);
1937 ci.println("Please enter node id");
1941 Switch sw = getSwitchByNode(node);
1943 ci.println(" NodeConnector Name");
1945 Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors();
1946 String nodeConnectorName;
1947 if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
1948 for (NodeConnector nodeConnector : nodeConnectorSet) {
1949 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1950 nodeConnectorName = (propMap == null) ? null : ((Name) propMap
1951 .get(Name.NamePropName)).getValue();
1952 if (nodeConnectorName != null) {
1953 Node nd = nodeConnector.getNode();
1954 if (!nd.equals(node)) {
1955 log.debug("node not match {} {}", nd, node);
1957 Map<String, NodeConnector> map = nodeConnectorNames
1960 NodeConnector nc = map.get(nodeConnectorName);
1962 log.debug("no nodeConnector named {}",
1964 } else if (!nc.equals(nodeConnector)) {
1965 log.debug("nodeConnector not match {} {}", nc,
1971 ci.println(nodeConnector
1973 + ((nodeConnectorName == null) ? "" : nodeConnectorName)
1974 + "(" + nodeConnector.getID() + ")");
1976 ci.println("Total number of NodeConnectors: "
1977 + nodeConnectorSet.size());
1982 public byte[] getNodeMAC(Node node) {
1983 MacAddress mac = (MacAddress) this.getNodeProp(node,
1985 return (mac != null) ? mac.getMacAddress() : null;
1989 public boolean isSpecial(NodeConnector p) {
1990 if (p.getType().equals(NodeConnectorIDType.CONTROLLER)
1991 || p.getType().equals(NodeConnectorIDType.ALL)
1992 || p.getType().equals(NodeConnectorIDType.SWSTACK)
1993 || p.getType().equals(NodeConnectorIDType.HWPATH)) {
2000 * Add span configuration to local cache and notify clients
2002 private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2003 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2005 for (NodeConnector nodeConnector : nodeConnectors) {
2006 if (!spanNodeConnectors.contains(nodeConnector)) {
2007 ncLists.add(nodeConnector);
2011 if (ncLists.size() > 0) {
2012 spanNodeConnectors.addAll(ncLists);
2013 notifySpanPortChange(node, ncLists, true);
2017 private void addSpanPorts(Node node) {
2018 for (SpanConfig conf : getSpanConfigList(node)) {
2019 addSpanPorts(node, conf.getPortArrayList());
2023 private void addSpanPort(NodeConnector nodeConnector) {
2024 // only add if span is configured on this nodeConnector
2025 for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) {
2026 if (conf.getPortArrayList().contains(nodeConnector)) {
2027 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
2028 ncList.add(nodeConnector);
2029 addSpanPorts(nodeConnector.getNode(), ncList);
2036 * Remove span configuration to local cache and notify clients
2038 private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2039 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2041 for (NodeConnector nodeConnector : nodeConnectors) {
2042 if (spanNodeConnectors.contains(nodeConnector)) {
2043 ncLists.add(nodeConnector);
2047 if (ncLists.size() > 0) {
2048 spanNodeConnectors.removeAll(ncLists);
2049 notifySpanPortChange(node, ncLists, false);
2053 private void removeSpanPorts(Node node) {
2054 for (SpanConfig conf : getSpanConfigList(node)) {
2055 addSpanPorts(node, conf.getPortArrayList());
2059 private void removeSpanPort(NodeConnector nodeConnector) {
2060 if (spanNodeConnectors.contains(nodeConnector)) {
2061 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2062 ncLists.add(nodeConnector);
2063 removeSpanPorts(nodeConnector.getNode(), ncLists);
2067 private void addNodeProps(Node node, Map<String, Property> propMap) {
2068 if (propMap == null) {
2069 propMap = new HashMap<String, Property>();
2071 nodeProps.put(node, propMap);
2075 public Status saveConfiguration() {
2076 return saveSwitchConfig();
2080 * Creates a Name/Tier/Bandwidth/MacAddress(controller property) Property
2081 * object based on given property name and value. Other property types are
2082 * not supported yet.
2085 * Name of the Property
2087 * Value of the Property
2088 * @return {@link org.opendaylight.controller.sal.core.Property}
2091 public Property createProperty(String propName, String propValue) {
2092 if (propName == null) {
2093 log.debug("propName is null");
2096 if (propValue == null) {
2097 log.debug("propValue is null");
2102 if (propName.equalsIgnoreCase(Description.propertyName)) {
2103 return new Description(propValue);
2104 } else if (propName.equalsIgnoreCase(Tier.TierPropName)) {
2105 int tier = Integer.parseInt(propValue);
2106 return new Tier(tier);
2107 } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) {
2108 long bw = Long.parseLong(propValue);
2109 return new Bandwidth(bw);
2110 } else if (propName.equalsIgnoreCase(ForwardingMode.name)) {
2111 int mode = Integer.parseInt(propValue);
2112 return new ForwardingMode(mode);
2113 } else if (propName.equalsIgnoreCase(MacAddress.name)){
2114 return new MacAddress(propValue);
2117 log.debug("Not able to create {} property", propName);
2119 } catch (Exception e) {
2120 log.debug("createProperty caught exception {}", e.getMessage());
2127 @SuppressWarnings("deprecation")
2129 public String getNodeDescription(Node node) {
2130 // Check first if user configured a name
2131 SwitchConfig config = getSwitchConfig(node.toString());
2132 if (config != null) {
2133 String configuredDesc = config.getNodeDescription();
2134 if (configuredDesc != null && !configuredDesc.isEmpty()) {
2135 return configuredDesc;
2139 // No name configured by user, get the node advertised name
2140 Description desc = (Description) getNodeProp(node,
2141 Description.propertyName);
2142 return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? ""
2147 public Set<Switch> getConfiguredNotConnectedSwitches() {
2148 Set<Switch> configuredNotConnectedSwitches = new HashSet<Switch>();
2149 if (this.inventoryService == null) {
2150 log.trace("inventory service not available");
2151 return configuredNotConnectedSwitches;
2154 Set<Node> configuredNotConnectedNodes = this.inventoryService.getConfiguredNotConnectedNodes();
2155 if (configuredNotConnectedNodes != null) {
2156 for (Node node : configuredNotConnectedNodes) {
2157 Switch sw = getSwitchByNode(node);
2158 configuredNotConnectedSwitches.add(sw);
2161 return configuredNotConnectedSwitches;