2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.switchmanager.internal;
11 import java.io.FileNotFoundException;
12 import java.io.IOException;
13 import java.io.ObjectInputStream;
14 import java.net.InetAddress;
15 import java.net.NetworkInterface;
16 import java.net.SocketException;
17 import java.util.ArrayList;
18 import java.util.Collections;
19 import java.util.Dictionary;
20 import java.util.EnumSet;
21 import java.util.Enumeration;
22 import java.util.HashMap;
23 import java.util.HashSet;
24 import java.util.List;
27 import java.util.concurrent.ConcurrentHashMap;
28 import java.util.concurrent.ConcurrentMap;
29 import java.util.concurrent.CopyOnWriteArrayList;
31 import org.apache.felix.dm.Component;
32 import org.eclipse.osgi.framework.console.CommandInterpreter;
33 import org.eclipse.osgi.framework.console.CommandProvider;
34 import org.opendaylight.controller.clustering.services.CacheConfigException;
35 import org.opendaylight.controller.clustering.services.CacheExistException;
36 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
37 import org.opendaylight.controller.clustering.services.IClusterServices;
38 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
39 import org.opendaylight.controller.sal.core.Bandwidth;
40 import org.opendaylight.controller.sal.core.Config;
41 import org.opendaylight.controller.sal.core.ConstructionException;
42 import org.opendaylight.controller.sal.core.Description;
43 import org.opendaylight.controller.sal.core.ForwardingMode;
44 import org.opendaylight.controller.sal.core.MacAddress;
45 import org.opendaylight.controller.sal.core.Name;
46 import org.opendaylight.controller.sal.core.Node;
47 import org.opendaylight.controller.sal.core.NodeConnector;
48 import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType;
49 import org.opendaylight.controller.sal.core.Property;
50 import org.opendaylight.controller.sal.core.State;
51 import org.opendaylight.controller.sal.core.Tier;
52 import org.opendaylight.controller.sal.core.UpdateType;
53 import org.opendaylight.controller.sal.inventory.IInventoryService;
54 import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates;
55 import org.opendaylight.controller.sal.reader.NodeDescription;
56 import org.opendaylight.controller.sal.utils.GlobalConstants;
57 import org.opendaylight.controller.sal.utils.HexEncode;
58 import org.opendaylight.controller.sal.utils.IObjectReader;
59 import org.opendaylight.controller.sal.utils.ObjectReader;
60 import org.opendaylight.controller.sal.utils.ObjectWriter;
61 import org.opendaylight.controller.sal.utils.Status;
62 import org.opendaylight.controller.sal.utils.StatusCode;
63 import org.opendaylight.controller.statisticsmanager.IStatisticsManager;
64 import org.opendaylight.controller.switchmanager.IInventoryListener;
65 import org.opendaylight.controller.switchmanager.ISpanAware;
66 import org.opendaylight.controller.switchmanager.ISwitchManager;
67 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
68 import org.opendaylight.controller.switchmanager.SpanConfig;
69 import org.opendaylight.controller.switchmanager.Subnet;
70 import org.opendaylight.controller.switchmanager.SubnetConfig;
71 import org.opendaylight.controller.switchmanager.Switch;
72 import org.opendaylight.controller.switchmanager.SwitchConfig;
73 import org.osgi.framework.BundleContext;
74 import org.osgi.framework.FrameworkUtil;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
79 * The class describes SwitchManager which is the central repository of all the
80 * inventory data including nodes, node connectors, properties attached, Layer3
81 * configurations, Span configurations, node configurations, network device
82 * representations viewed by Controller Web applications. One SwitchManager
83 * instance per container of the network. All the node/nodeConnector properties
84 * are maintained in the default container only.
86 public class SwitchManager implements ISwitchManager, IConfigurationContainerAware,
87 IObjectReader, IListenInventoryUpdates, CommandProvider {
88 private static Logger log = LoggerFactory.getLogger(SwitchManager.class);
89 private static String ROOT = GlobalConstants.STARTUPHOME.toString();
90 private String subnetFileName, spanFileName, switchConfigFileName;
91 private final List<NodeConnector> spanNodeConnectors = new CopyOnWriteArrayList<NodeConnector>();
92 // Collection of Subnets keyed by the InetAddress
93 private ConcurrentMap<InetAddress, Subnet> subnets;
94 private ConcurrentMap<String, SubnetConfig> subnetsConfigList;
95 private ConcurrentMap<SpanConfig, SpanConfig> spanConfigList;
96 // manually configured parameters for the node such as name, tier, mode
97 private ConcurrentMap<String, SwitchConfig> nodeConfigList;
98 private ConcurrentMap<Node, Map<String, Property>> nodeProps;
99 private ConcurrentMap<NodeConnector, Map<String, Property>> nodeConnectorProps;
100 private ConcurrentMap<Node, Map<String, NodeConnector>> nodeConnectorNames;
101 private ConcurrentMap<String, Property> controllerProps;
102 private IInventoryService inventoryService;
103 private IStatisticsManager statisticsManager;
104 private final Set<ISwitchManagerAware> switchManagerAware = Collections
105 .synchronizedSet(new HashSet<ISwitchManagerAware>());
106 private final Set<IInventoryListener> inventoryListeners = Collections
107 .synchronizedSet(new HashSet<IInventoryListener>());
108 private final Set<ISpanAware> spanAware = Collections.synchronizedSet(new HashSet<ISpanAware>());
109 private IClusterContainerServices clusterContainerService = null;
110 private String containerName = null;
111 private boolean isDefaultContainer = true;
112 private static final int REPLACE_RETRY = 1;
114 /* 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 protected static SubnetConfig DEFAULT_SUBNETCONFIG;
120 protected static Subnet DEFAULT_SUBNET;
121 protected static String DEFAULT_SUBNET_NAME = "default (cannot be modifed)";
123 DEFAULT_SUBNETCONFIG = new SubnetConfig(DEFAULT_SUBNET_NAME, "0.0.0.0/0", new ArrayList<String>());
124 DEFAULT_SUBNET = new Subnet(DEFAULT_SUBNETCONFIG);
127 public void notifySubnetChange(Subnet sub, boolean add) {
128 synchronized (switchManagerAware) {
129 for (Object subAware : switchManagerAware) {
131 ((ISwitchManagerAware) subAware).subnetNotify(sub, add);
132 } catch (Exception e) {
133 log.error("Failed to notify Subnet change {}",
140 public void notifySpanPortChange(Node node, List<NodeConnector> ports, boolean add) {
141 synchronized (spanAware) {
142 for (Object sa : spanAware) {
144 ((ISpanAware) sa).spanUpdate(node, ports, add);
145 } catch (Exception e) {
146 log.error("Failed to notify Span Interface change {}",
153 private void notifyModeChange(Node node, boolean proactive) {
154 synchronized (switchManagerAware) {
155 for (ISwitchManagerAware service : switchManagerAware) {
157 service.modeChangeNotify(node, proactive);
158 } catch (Exception e) {
159 log.error("Failed to notify Subnet change {}",
166 public void startUp() {
167 String container = this.getContainerName();
168 // Initialize configuration file names
169 subnetFileName = ROOT + "subnets_" + container + ".conf";
170 spanFileName = ROOT + "spanPorts_" + container + ".conf";
171 switchConfigFileName = ROOT + "switchConfig_" + container + ".conf";
173 // Instantiate cluster synced variables
178 * Read startup and build database if we have not already gotten the
179 * configurations synced from another node
181 if (subnetsConfigList.isEmpty()) {
182 loadSubnetConfiguration();
184 if (spanConfigList.isEmpty()) {
185 loadSpanConfiguration();
187 if (nodeConfigList.isEmpty()) {
188 loadSwitchConfiguration();
191 // Add controller MAC, if first node in the cluster
192 if (!controllerProps.containsKey(MacAddress.name)) {
193 byte controllerMac[] = getHardwareMAC();
194 if (controllerMac != null) {
195 Property existing = controllerProps.putIfAbsent(MacAddress.name, new MacAddress(controllerMac));
196 if (existing == null && log.isTraceEnabled()) {
197 log.trace("Container {}: Setting controller MAC address in the cluster: {}", container,
198 HexEncode.bytesToHexStringFormat(controllerMac));
204 public void shutDown() {
207 private void allocateCaches() {
208 if (this.clusterContainerService == null) {
209 this.nonClusterObjectCreate();
210 log.warn("un-initialized clusterContainerService, can't create cache");
215 clusterContainerService.createCache(
216 "switchmanager.subnetsConfigList",
217 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
218 clusterContainerService.createCache("switchmanager.spanConfigList",
219 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
220 clusterContainerService.createCache("switchmanager.nodeConfigList",
221 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
222 clusterContainerService.createCache("switchmanager.subnets",
223 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
224 clusterContainerService.createCache("switchmanager.nodeProps",
225 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
226 clusterContainerService.createCache(
227 "switchmanager.nodeConnectorProps",
228 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
229 clusterContainerService.createCache(
230 "switchmanager.nodeConnectorNames",
231 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
232 clusterContainerService.createCache(
233 "switchmanager.controllerProps",
234 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
235 } catch (CacheConfigException cce) {
236 log.error("\nCache configuration invalid - check cache mode");
237 } catch (CacheExistException ce) {
238 log.error("\nCache already exits - destroy and recreate if needed");
242 @SuppressWarnings({ "unchecked" })
243 private void retrieveCaches() {
244 if (this.clusterContainerService == null) {
245 log.info("un-initialized clusterContainerService, can't create cache");
249 subnetsConfigList = (ConcurrentMap<String, SubnetConfig>) clusterContainerService
250 .getCache("switchmanager.subnetsConfigList");
251 if (subnetsConfigList == null) {
252 log.error("\nFailed to get cache for subnetsConfigList");
255 spanConfigList = (ConcurrentMap<SpanConfig, SpanConfig>) clusterContainerService
256 .getCache("switchmanager.spanConfigList");
257 if (spanConfigList == null) {
258 log.error("\nFailed to get cache for spanConfigList");
261 nodeConfigList = (ConcurrentMap<String, SwitchConfig>) clusterContainerService
262 .getCache("switchmanager.nodeConfigList");
263 if (nodeConfigList == null) {
264 log.error("\nFailed to get cache for nodeConfigList");
267 subnets = (ConcurrentMap<InetAddress, Subnet>) clusterContainerService
268 .getCache("switchmanager.subnets");
269 if (subnets == null) {
270 log.error("\nFailed to get cache for subnets");
273 nodeProps = (ConcurrentMap<Node, Map<String, Property>>) clusterContainerService
274 .getCache("switchmanager.nodeProps");
275 if (nodeProps == null) {
276 log.error("\nFailed to get cache for nodeProps");
279 nodeConnectorProps = (ConcurrentMap<NodeConnector, Map<String, Property>>) clusterContainerService
280 .getCache("switchmanager.nodeConnectorProps");
281 if (nodeConnectorProps == null) {
282 log.error("\nFailed to get cache for nodeConnectorProps");
285 nodeConnectorNames = (ConcurrentMap<Node, Map<String, NodeConnector>>) clusterContainerService
286 .getCache("switchmanager.nodeConnectorNames");
287 if (nodeConnectorNames == null) {
288 log.error("\nFailed to get cache for nodeConnectorNames");
291 controllerProps = (ConcurrentMap<String, Property>) clusterContainerService
292 .getCache("switchmanager.controllerProps");
293 if (controllerProps == null) {
294 log.error("\nFailed to get cache for controllerProps");
298 private void nonClusterObjectCreate() {
299 subnetsConfigList = new ConcurrentHashMap<String, SubnetConfig>();
300 spanConfigList = new ConcurrentHashMap<SpanConfig, SpanConfig>();
301 nodeConfigList = new ConcurrentHashMap<String, SwitchConfig>();
302 subnets = new ConcurrentHashMap<InetAddress, Subnet>();
303 nodeProps = new ConcurrentHashMap<Node, Map<String, Property>>();
304 nodeConnectorProps = new ConcurrentHashMap<NodeConnector, Map<String, Property>>();
305 nodeConnectorNames = new ConcurrentHashMap<Node, Map<String, NodeConnector>>();
306 controllerProps = new ConcurrentHashMap<String, Property>();
310 public List<SubnetConfig> getSubnetsConfigList() {
311 // if there are no subnets, return the default subnet
312 if(subnetsConfigList.size() == 0){
313 return Collections.singletonList(DEFAULT_SUBNETCONFIG);
315 return new ArrayList<SubnetConfig>(subnetsConfigList.values());
320 public SubnetConfig getSubnetConfig(String subnet) {
321 // if there are no subnets, return the default subnet
322 if(subnetsConfigList.isEmpty() && subnet.equalsIgnoreCase(DEFAULT_SUBNET_NAME)){
323 return DEFAULT_SUBNETCONFIG;
325 return subnetsConfigList.get(subnet);
329 private List<SpanConfig> getSpanConfigList(Node node) {
330 List<SpanConfig> confList = new ArrayList<SpanConfig>();
331 String nodeId = node.toString();
332 for (SpanConfig conf : spanConfigList.values()) {
333 if (conf.matchNode(nodeId)) {
340 public List<SwitchConfig> getNodeConfigList() {
341 return new ArrayList<SwitchConfig>(nodeConfigList.values());
345 public SwitchConfig getSwitchConfig(String switchId) {
346 return nodeConfigList.get(switchId);
349 public Switch getSwitchByNode(Node node) {
350 Switch sw = new Switch(node);
352 MacAddress mac = (MacAddress) this.getNodeProp(node,
355 sw.setDataLayerAddress(mac.getMacAddress());
357 Set<NodeConnector> ncSet = getPhysicalNodeConnectors(node);
358 sw.setNodeConnectors(ncSet);
360 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
361 for (NodeConnector nodeConnector : ncSet) {
362 if (spanNodeConnectors.contains(nodeConnector)) {
363 ncList.add(nodeConnector);
366 sw.addSpanPorts(ncList);
372 public List<Switch> getNetworkDevices() {
373 Set<Node> nodeSet = getNodes();
374 List<Switch> swList = new ArrayList<Switch>();
375 if (nodeSet != null) {
376 for (Node node : nodeSet) {
377 swList.add(getSwitchByNode(node));
384 private Status updateConfig(SubnetConfig conf, boolean add) {
386 if(subnetsConfigList.putIfAbsent(conf.getName(), conf) != null) {
387 String msg = "Cluster conflict: Subnet with name " + conf.getName() + "already exists.";
388 return new Status(StatusCode.CONFLICT, msg);
391 subnetsConfigList.remove(conf.getName());
393 return new Status(StatusCode.SUCCESS);
396 private Status updateDatabase(SubnetConfig conf, boolean add) {
398 Subnet subnetCurr = subnets.get(conf.getIPAddress());
400 if (subnetCurr == null) {
401 subnet = new Subnet(conf);
403 subnet = subnetCurr.clone();
405 // In case of API3 call we may receive the ports along with the
407 if (!conf.isGlobal()) {
408 subnet.addNodeConnectors(conf.getNodeConnectors());
410 boolean putNewSubnet = false;
411 if(subnetCurr == null) {
412 if(subnets.putIfAbsent(conf.getIPAddress(), subnet) == null) {
416 putNewSubnet = subnets.replace(conf.getIPAddress(), subnetCurr, subnet);
419 String msg = "Cluster conflict: Conflict while adding the subnet " + conf.getIPAddress();
420 return new Status(StatusCode.CONFLICT, msg);
423 // Subnet removal case
425 subnets.remove(conf.getIPAddress());
427 return new Status(StatusCode.SUCCESS);
430 private Status semanticCheck(SubnetConfig conf) {
431 Set<InetAddress> IPs = subnets.keySet();
433 return new Status(StatusCode.SUCCESS);
435 Subnet newSubnet = new Subnet(conf);
436 for (InetAddress i : IPs) {
437 Subnet existingSubnet = subnets.get(i);
438 if ((existingSubnet != null) && !existingSubnet.isMutualExclusive(newSubnet)) {
439 return new Status(StatusCode.CONFLICT, "This subnet conflicts with an existing one.");
442 return new Status(StatusCode.SUCCESS);
445 private Status addRemoveSubnet(SubnetConfig conf, boolean isAdding) {
446 // Valid configuration check
447 Status status = conf.validate();
448 if (!status.isSuccess()) {
449 log.warn(status.getDescription());
455 if (subnetsConfigList.containsKey(conf.getName())) {
456 return new Status(StatusCode.CONFLICT,
457 "Subnet with the specified name already exists.");
460 status = semanticCheck(conf);
461 if (!status.isSuccess()) {
465 if (conf.getName().equalsIgnoreCase(DEFAULT_SUBNET_NAME)) {
466 return new Status(StatusCode.NOTALLOWED, "The specified subnet gateway cannot be removed");
471 status = updateDatabase(conf, isAdding);
473 if (status.isSuccess()) {
474 // Update Configuration
475 status = updateConfig(conf, isAdding);
476 if(!status.isSuccess()) {
477 updateDatabase(conf, (!isAdding));
479 // update the listeners
480 Subnet subnetCurr = subnets.get(conf.getIPAddress());
482 if (subnetCurr == null) {
483 subnet = new Subnet(conf);
485 subnet = subnetCurr.clone();
487 notifySubnetChange(subnet, isAdding);
495 * Adds Subnet configured in GUI or API3
498 public Status addSubnet(SubnetConfig conf) {
499 return this.addRemoveSubnet(conf, true);
503 public Status removeSubnet(SubnetConfig conf) {
504 return this.addRemoveSubnet(conf, false);
508 public Status removeSubnet(String name) {
509 if (name.equalsIgnoreCase(DEFAULT_SUBNET_NAME)) {
510 return new Status(StatusCode.NOTALLOWED, "The specified subnet gateway cannot be removed");
512 SubnetConfig conf = subnetsConfigList.get(name);
514 return new Status(StatusCode.SUCCESS, "Subnet not present");
516 return this.addRemoveSubnet(conf, false);
520 public Status modifySubnet(SubnetConfig conf) {
523 return new Status(StatusCode.BADREQUEST, "Invalid Subnet configuration: null");
526 // Valid configuration check
527 Status status = conf.validate();
528 if (!status.isSuccess()) {
529 log.warn(status.getDescription());
533 // If a subnet configuration with this name does not exist, consider this is a creation
534 SubnetConfig target = subnetsConfigList.get(conf.getName());
535 if (target == null) {
536 return this.addSubnet(conf);
540 if (target.equals(conf)) {
541 return new Status(StatusCode.SUCCESS);
544 // Check not allowed modifications
545 if (!target.getSubnet().equals(conf.getSubnet())) {
546 return new Status(StatusCode.BADREQUEST, "IP address change is not allowed");
549 // Derive the set of node connectors that are being removed
550 Set<NodeConnector> toRemove = target.getNodeConnectors();
551 toRemove.removeAll(conf.getNodeConnectors());
552 List<String> nodeConnectorStrings = null;
553 if (!toRemove.isEmpty()) {
554 nodeConnectorStrings = new ArrayList<String>();
555 for (NodeConnector nc : toRemove) {
556 nodeConnectorStrings.add(nc.toString());
558 status = this.removePortsFromSubnet(conf.getName(), nodeConnectorStrings);
559 if (!status.isSuccess()) {
564 // Derive the set of node connectors that are being added
565 Set<NodeConnector> toAdd = conf.getNodeConnectors();
566 toAdd.removeAll(target.getNodeConnectors());
567 if (!toAdd.isEmpty()) {
568 List<String> nodeConnectorStringRemoved = nodeConnectorStrings;
569 nodeConnectorStrings = new ArrayList<String>();
570 for (NodeConnector nc : toAdd) {
571 nodeConnectorStrings.add(nc.toString());
573 status = this.addPortsToSubnet(conf.getName(), nodeConnectorStrings);
574 if (!status.isSuccess()) {
575 // If any port was removed, add it back as a best recovery effort
576 if (!toRemove.isEmpty()) {
577 this.addPortsToSubnet(conf.getName(), nodeConnectorStringRemoved);
583 // Update Configuration
584 subnetsConfigList.put(conf.getName(), conf);
586 return new Status(StatusCode.SUCCESS);
590 public Status addPortsToSubnet(String name, List<String> switchPorts) {
592 return new Status(StatusCode.BADREQUEST, "Null subnet name");
594 SubnetConfig confCurr = subnetsConfigList.get(name);
595 if (confCurr == null) {
596 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
599 if (switchPorts == null || switchPorts.isEmpty()) {
600 return new Status(StatusCode.BADREQUEST, "Null or empty port set");
603 Subnet subCurr = subnets.get(confCurr.getIPAddress());
604 if (subCurr == null) {
605 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress());
606 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
610 Subnet sub = subCurr.clone();
611 Set<NodeConnector> sp = NodeConnector.fromString(switchPorts);
612 sub.addNodeConnectors(sp);
613 boolean subnetsReplaced = subnets.replace(confCurr.getIPAddress(), subCurr, sub);
614 if (!subnetsReplaced) {
615 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
616 return new Status(StatusCode.CONFLICT, msg);
619 // Update Configuration
620 SubnetConfig conf = confCurr.clone();
621 conf.addNodeConnectors(switchPorts);
622 boolean configReplaced = subnetsConfigList.replace(name, confCurr, conf);
623 if (!configReplaced) {
624 // TODO: recovery using Transactionality
625 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
626 return new Status(StatusCode.CONFLICT, msg);
629 return new Status(StatusCode.SUCCESS);
633 public Status removePortsFromSubnet(String name, List<String> switchPorts) {
635 return new Status(StatusCode.BADREQUEST, "Null subnet name");
637 SubnetConfig confCurr = subnetsConfigList.get(name);
638 if (confCurr == null) {
639 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
642 if (switchPorts == null || switchPorts.isEmpty()) {
643 return new Status(StatusCode.BADREQUEST, "Null or empty port set");
646 Subnet subCurr = subnets.get(confCurr.getIPAddress());
647 if (subCurr == null) {
648 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress());
649 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
653 Status status = SubnetConfig.validatePorts(switchPorts);
654 if (!status.isSuccess()) {
658 Subnet sub = subCurr.clone();
659 Set<NodeConnector> sp = NodeConnector.fromString(switchPorts);
660 sub.deleteNodeConnectors(sp);
661 boolean subnetsReplace = subnets.replace(confCurr.getIPAddress(), subCurr, sub);
662 if (!subnetsReplace) {
663 String msg = "Cluster conflict: Conflict while removing ports from the subnet " + name;
664 return new Status(StatusCode.CONFLICT, msg);
667 // Update Configuration
668 SubnetConfig conf = confCurr.clone();
669 conf.removeNodeConnectors(switchPorts);
670 boolean result = subnetsConfigList.replace(name, confCurr, conf);
672 // TODO: recovery using Transactionality
673 String msg = "Cluster conflict: Conflict while removing ports from " + conf;
674 return new Status(StatusCode.CONFLICT, msg);
677 return new Status(StatusCode.SUCCESS);
680 public String getContainerName() {
681 if (containerName == null) {
682 return GlobalConstants.DEFAULT.toString();
684 return containerName;
688 public Subnet getSubnetByNetworkAddress(InetAddress networkAddress) {
689 // if there are no subnets, return the default subnet
690 if (subnets.size() == 0) {
691 return DEFAULT_SUBNET;
694 for(Map.Entry<InetAddress,Subnet> subnetEntry : subnets.entrySet()) {
695 if(subnetEntry.getValue().isSubnetOf(networkAddress)) {
696 return subnetEntry.getValue();
703 public Object readObject(ObjectInputStream ois)
704 throws FileNotFoundException, IOException, ClassNotFoundException {
705 // Perform the class deserialization locally, from inside the package
706 // where the class is defined
707 return ois.readObject();
710 @SuppressWarnings("unchecked")
711 private void loadSubnetConfiguration() {
712 ObjectReader objReader = new ObjectReader();
713 ConcurrentMap<String, SubnetConfig> confList = (ConcurrentMap<String, SubnetConfig>) objReader
714 .read(this, subnetFileName);
716 if (confList == null) {
720 for (SubnetConfig conf : confList.values()) {
725 @SuppressWarnings("unchecked")
726 private void loadSpanConfiguration() {
727 ObjectReader objReader = new ObjectReader();
728 ConcurrentMap<Integer, SpanConfig> confList = (ConcurrentMap<Integer, SpanConfig>) objReader
729 .read(this, spanFileName);
731 if (confList == null) {
735 for (SpanConfig conf : confList.values()) {
740 @SuppressWarnings("unchecked")
741 private void loadSwitchConfiguration() {
742 ObjectReader objReader = new ObjectReader();
743 ConcurrentMap<String, SwitchConfig> confList = (ConcurrentMap<String, SwitchConfig>) objReader
744 .read(this, switchConfigFileName);
746 if (confList == null) {
750 for (SwitchConfig conf : confList.values()) {
751 updateNodeConfig(conf);
755 @SuppressWarnings("deprecation")
757 public void updateSwitchConfig(SwitchConfig cfgObject) {
758 // update default container only
759 if (!isDefaultContainer) {
763 SwitchConfig sc = nodeConfigList.get(cfgObject.getNodeId());
765 if (nodeConfigList.putIfAbsent(cfgObject.getNodeId(), cfgObject) != null) {
769 if (!nodeConfigList.replace(cfgObject.getNodeId(), sc, cfgObject)) {
774 boolean modeChange = false;
776 if ((sc == null) || !cfgObject.getMode().equals(sc.getMode())) {
780 String nodeId = cfgObject.getNodeId();
781 Node node = Node.fromString(nodeId);
782 Map<String, Property> propMapCurr = nodeProps.get(node);
783 if (propMapCurr == null) {
786 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
787 Property desc = new Description(cfgObject.getNodeDescription());
788 propMap.put(desc.getName(), desc);
789 Property tier = new Tier(Integer.parseInt(cfgObject.getTier()));
790 propMap.put(tier.getName(), tier);
792 if (!nodeProps.replace(node, propMapCurr, propMap)) {
793 // TODO rollback using Transactionality
797 log.info("Set Node {}'s Mode to {}", nodeId, cfgObject.getMode());
800 notifyModeChange(node, cfgObject.isProactive());
805 public Status updateNodeConfig(SwitchConfig switchConfig) {
806 Status status = switchConfig.validate();
807 if (!status.isSuccess()) {
811 Map<String, Property> updateProperties = switchConfig.getNodeProperties();
812 ForwardingMode mode = (ForwardingMode) updateProperties.get(ForwardingMode.name);
814 if (isDefaultContainer) {
815 if (!mode.isValid()) {
816 return new Status(StatusCode.BADREQUEST, "Invalid Forwarding Mode Value");
819 return new Status(StatusCode.NOTACCEPTABLE,
820 "Forwarding Mode modification is allowed only in default container");
824 Description description = (Description) switchConfig.getProperty(Description.propertyName);
825 String nodeId = switchConfig.getNodeId();
826 Node node = Node.fromString(nodeId);
827 NodeDescription nodeDesc = (this.statisticsManager == null) ? null : this.statisticsManager
828 .getNodeDescription(node);
829 String advertisedDesc = (nodeDesc == null) ? "" : nodeDesc.getDescription();
830 if (description != null && description.getValue() != null) {
831 if (description.getValue().isEmpty() || description.getValue().equals(advertisedDesc)) {
832 updateProperties.remove(Description.propertyName);
833 switchConfig = new SwitchConfig(nodeId, updateProperties);
835 // check if description is configured or was published by any other node
836 for (Map.Entry<Node, Map<String, Property>> entry : nodeProps.entrySet()) {
837 Node n = entry.getKey();
838 Description desc = (Description) getNodeProp(n, Description.propertyName);
839 NodeDescription nDesc = (this.statisticsManager == null) ? null : this.statisticsManager
840 .getNodeDescription(n);
841 String advDesc = (nDesc == null) ? "" : nDesc.getDescription();
842 if ((description.equals(desc) || description.getValue().equals(advDesc)) && !node.equals(n)) {
843 return new Status(StatusCode.CONFLICT, "Node name already in use");
849 boolean modeChange = false;
850 SwitchConfig sc = nodeConfigList.get(nodeId);
851 Map<String, Property> prevNodeProperties = new HashMap<String, Property>();
853 if ((mode != null) && mode.isProactive()) {
856 if (!updateProperties.isEmpty()) {
857 if (nodeConfigList.putIfAbsent(nodeId, switchConfig) != null) {
858 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
862 prevNodeProperties = new HashMap<String, Property>(sc.getNodeProperties());
863 ForwardingMode prevMode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
865 if ((prevMode != null) && (prevMode.isProactive())) {
869 if (((prevMode != null) && (prevMode.getValue() != mode.getValue()))
870 || (prevMode == null && mode.isProactive())) {
874 if (updateProperties.isEmpty()) {
875 nodeConfigList.remove(nodeId);
877 if (!nodeConfigList.replace(nodeId, sc, switchConfig)) {
878 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
882 Map<String, Property> propMapCurr = nodeProps.get(node);
883 if (propMapCurr == null) {
884 return new Status(StatusCode.SUCCESS);
886 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
887 for (Map.Entry<String, Property> entry : prevNodeProperties.entrySet()) {
888 String prop = entry.getKey();
889 if (!updateProperties.containsKey(prop)) {
890 if (prop.equals(Description.propertyName)) {
891 if (!advertisedDesc.isEmpty()) {
892 Property desc = new Description(advertisedDesc);
893 propMap.put(Description.propertyName, desc);
896 } else if (prop.equals(ForwardingMode.name)) {
897 Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING);
898 propMap.put(ForwardingMode.name, defaultMode);
901 propMap.remove(prop);
904 propMap.putAll(updateProperties);
905 if (!nodeProps.replace(node, propMapCurr, propMap)) {
906 // TODO rollback using Transactionality
907 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
910 notifyModeChange(node, (mode == null) ? false : mode.isProactive());
912 return new Status(StatusCode.SUCCESS);
916 public Status removeNodeConfig(String nodeId) {
917 if ((nodeId == null) || (nodeId.isEmpty())) {
918 return new Status(StatusCode.BADREQUEST, "nodeId cannot be empty.");
920 Map<String, Property> nodeProperties = getSwitchConfig(nodeId).getNodeProperties();
921 Node node = Node.fromString(nodeId);
922 Map<String, Property> propMapCurr = nodeProps.get(node);
923 if ((propMapCurr != null) && (nodeProperties != null) && (!nodeProperties.isEmpty())) {
924 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
925 for (Map.Entry<String, Property> entry : nodeProperties.entrySet()) {
926 String prop = entry.getKey();
927 if (prop.equals(Description.propertyName)) {
928 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
929 if (nodeProp.get(node) != null) {
930 propMap.put(Description.propertyName, nodeProp.get(node).get(Description.propertyName));
934 propMap.remove(prop);
936 if (!nodeProps.replace(node, propMapCurr, propMap)) {
937 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration.");
940 if (nodeConfigList != null) {
941 nodeConfigList.remove(nodeId);
943 return new Status(StatusCode.SUCCESS);
947 public Status saveSwitchConfig() {
948 return saveSwitchConfigInternal();
951 public Status saveSwitchConfigInternal() {
952 Status retS = null, retP = null;
953 ObjectWriter objWriter = new ObjectWriter();
955 retS = objWriter.write(new ConcurrentHashMap<String, SubnetConfig>(
956 subnetsConfigList), subnetFileName);
957 retP = objWriter.write(new ConcurrentHashMap<SpanConfig, SpanConfig>(
958 spanConfigList), spanFileName);
959 retS = objWriter.write(new ConcurrentHashMap<String, SwitchConfig>(
960 nodeConfigList), switchConfigFileName);
961 if (retS.equals(retP)) {
962 if (retS.isSuccess()) {
965 return new Status(StatusCode.INTERNALERROR, "Save failed");
968 return new Status(StatusCode.INTERNALERROR, "Partial save failure");
973 public List<SpanConfig> getSpanConfigList() {
974 return new ArrayList<SpanConfig>(spanConfigList.values());
978 public Status addSpanConfig(SpanConfig conf) {
979 // Valid config check
980 if (!conf.isValidConfig()) {
981 String msg = "Invalid Span configuration";
983 return new Status(StatusCode.BADREQUEST, msg);
987 if (spanConfigList.containsKey(conf)) {
988 return new Status(StatusCode.CONFLICT, "Same span config exists");
991 // Update configuration
992 if (spanConfigList.putIfAbsent(conf, conf) == null) {
993 // Update database and notify clients
994 addSpanPorts(conf.getNode(), conf.getPortArrayList());
997 return new Status(StatusCode.SUCCESS);
1001 public Status removeSpanConfig(SpanConfig conf) {
1002 removeSpanPorts(conf.getNode(), conf.getPortArrayList());
1004 // Update configuration
1005 spanConfigList.remove(conf);
1007 return new Status(StatusCode.SUCCESS);
1011 public List<NodeConnector> getSpanPorts(Node node) {
1012 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
1014 for (NodeConnector nodeConnector : spanNodeConnectors) {
1015 if (nodeConnector.getNode().equals(node)) {
1016 ncList.add(nodeConnector);
1022 private void addNode(Node node, Set<Property> props) {
1023 log.trace("{} added, props: {}", node, props);
1024 if (nodeProps == null) {
1028 Map<String, Property> propMapCurr = nodeProps.get(node);
1029 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1030 : new HashMap<String, Property>(propMapCurr);
1032 // copy node properties from plugin
1033 if (props != null) {
1034 for (Property prop : props) {
1035 propMap.put(prop.getName(), prop);
1039 boolean proactiveForwarding = false;
1040 // copy node properties from config
1041 if (nodeConfigList != null) {
1042 String nodeId = node.toString();
1043 SwitchConfig conf = nodeConfigList.get(nodeId);
1044 if (conf != null && (conf.getNodeProperties() != null)) {
1045 Map<String, Property> nodeProperties = conf.getNodeProperties();
1046 propMap.putAll(nodeProperties);
1047 if (nodeProperties.get(ForwardingMode.name) != null) {
1048 ForwardingMode mode = (ForwardingMode) nodeProperties.get(ForwardingMode.name);
1049 proactiveForwarding = mode.isProactive();
1054 if (!propMap.containsKey(ForwardingMode.name)) {
1055 Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING);
1056 propMap.put(ForwardingMode.name, defaultMode);
1058 boolean result = false;
1059 if (propMapCurr == null) {
1060 if (nodeProps.putIfAbsent(node, propMap) == null) {
1064 result = nodeProps.replace(node, propMapCurr, propMap);
1067 log.debug("Cluster conflict: Conflict while adding the node properties. Node: {} Properties: {}",
1068 node.getID(), props);
1069 addNodeProps(node, propMap);
1072 // check if span ports are configed
1075 // notify node listeners
1076 notifyNode(node, UpdateType.ADDED, propMap);
1078 // notify proactive mode forwarding
1079 if (proactiveForwarding) {
1080 notifyModeChange(node, true);
1084 private void removeNode(Node node) {
1085 log.trace("{} removed", node);
1086 if (nodeProps == null) {
1089 nodeProps.remove(node);
1090 nodeConnectorNames.remove(node);
1091 Set<NodeConnector> removeNodeConnectorSet = new HashSet<NodeConnector>();
1092 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1093 NodeConnector nodeConnector = entry.getKey();
1094 if (nodeConnector.getNode().equals(node)) {
1095 removeNodeConnectorSet.add(nodeConnector);
1098 for (NodeConnector nc : removeNodeConnectorSet) {
1099 nodeConnectorProps.remove(nc);
1102 // check if span ports need to be cleaned up
1103 removeSpanPorts(node);
1105 /* notify node listeners */
1106 notifyNode(node, UpdateType.REMOVED, null);
1109 private void updateNode(Node node, Set<Property> props) {
1110 log.trace("{} updated, props: {}", node, props);
1111 if (nodeProps == null || !nodeProps.containsKey(node) ||
1112 props == null || props.isEmpty()) {
1116 Map<String, Property> propMapCurr = nodeProps.get(node);
1117 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1118 : new HashMap<String, Property>(propMapCurr);
1120 // copy node properties from plugin
1121 String nodeId = node.toString();
1122 for (Property prop : props) {
1123 if (nodeConfigList != null) {
1124 SwitchConfig conf = nodeConfigList.get(nodeId);
1125 if (conf != null && (conf.getNodeProperties() != null)
1126 && conf.getNodeProperties().containsKey(prop.getName())) {
1130 propMap.put(prop.getName(), prop);
1133 if (propMapCurr == null) {
1134 if (nodeProps.putIfAbsent(node, propMap) != null) {
1135 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1136 node.getID(), props);
1137 addNodeProps(node, propMap);
1140 if (!nodeProps.replace(node, propMapCurr, propMap)) {
1141 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1142 node.getID(), props);
1143 addNodeProps(node, propMap);
1147 /* notify node listeners */
1148 notifyNode(node, UpdateType.CHANGED, propMap);
1152 public void updateNode(Node node, UpdateType type, Set<Property> props) {
1153 log.debug("updateNode: {} type {} props {} for container {}",
1154 new Object[] { node, type, props, containerName });
1157 addNode(node, props);
1160 updateNode(node, props);
1171 public void updateNodeConnector(NodeConnector nodeConnector,
1172 UpdateType type, Set<Property> props) {
1173 Map<String, Property> propMap = new HashMap<String, Property>();
1174 boolean update = true;
1176 log.debug("updateNodeConnector: {} type {} props {} for container {}",
1177 new Object[] { nodeConnector, type, props, containerName });
1179 if (nodeConnectorProps == null) {
1185 if (props != null) {
1186 for (Property prop : props) {
1187 addNodeConnectorProp(nodeConnector, prop);
1188 propMap.put(prop.getName(), prop);
1191 addNodeConnectorProp(nodeConnector, null);
1194 addSpanPort(nodeConnector);
1197 if (!nodeConnectorProps.containsKey(nodeConnector) || (props == null)) {
1200 for (Property prop : props) {
1201 addNodeConnectorProp(nodeConnector, prop);
1202 propMap.put(prop.getName(), prop);
1207 if (!nodeConnectorProps.containsKey(nodeConnector)) {
1210 removeNodeConnectorAllProps(nodeConnector);
1212 // clean up span config
1213 removeSpanPort(nodeConnector);
1221 notifyNodeConnector(nodeConnector, type, propMap);
1226 public Set<Node> getNodes() {
1227 return (nodeProps != null) ? new HashSet<Node>(nodeProps.keySet()) : new HashSet<Node>();
1231 public Map<String, Property> getControllerProperties() {
1232 return new HashMap<String, Property>(this.controllerProps);
1236 public Property getControllerProperty(String propertyName) {
1237 if (propertyName != null) {
1238 HashMap<String, Property> propertyMap = new HashMap<String, Property>(this.controllerProps);
1239 return propertyMap.get(propertyName);
1245 public Status setControllerProperty(Property property) {
1246 if (property != null) {
1247 this.controllerProps.put(property.getName(), property);
1248 return new Status(StatusCode.SUCCESS);
1250 return new Status(StatusCode.BADREQUEST, "Invalid property provided when setting property");
1254 public Status removeControllerProperty(String propertyName) {
1255 if (propertyName != null) {
1256 if (this.controllerProps.containsKey(propertyName)) {
1257 this.controllerProps.remove(propertyName);
1258 if (!this.controllerProps.containsKey(propertyName)) {
1259 return new Status(StatusCode.SUCCESS);
1262 String msg = "Unable to remove property " + propertyName + " from Controller";
1263 return new Status(StatusCode.BADREQUEST, msg);
1265 String msg = "Invalid property provided when removing property from Controller";
1266 return new Status(StatusCode.BADREQUEST, msg);
1270 * Returns a copy of a list of properties for a given node
1275 * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps
1276 * (org.opendaylight.controller.sal.core.Node)
1279 public Map<String, Property> getNodeProps(Node node) {
1280 Map<String, Property> rv = new HashMap<String, Property>();
1281 if (this.nodeProps != null) {
1282 rv = this.nodeProps.get(node);
1284 /* make a copy of it */
1285 rv = new HashMap<String, Property>(rv);
1292 public Property getNodeProp(Node node, String propName) {
1293 Map<String, Property> propMap = getNodeProps(node);
1294 return (propMap != null) ? propMap.get(propName) : null;
1298 public void setNodeProp(Node node, Property prop) {
1300 for (int i = 0; i <= REPLACE_RETRY; i++) {
1301 /* Get a copy of the property map */
1302 Map<String, Property> propMapCurr = getNodeProps(node);
1303 if (propMapCurr == null) {
1307 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1308 propMap.put(prop.getName(), prop);
1310 if (nodeProps.replace(node, propMapCurr, propMap)) {
1313 if (!propMapCurr.get(prop.getName()).equals(nodeProps.get(node).get(prop.getName()))) {
1314 log.debug("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1318 log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1322 public Status removeNodeProp(Node node, String propName) {
1323 for (int i = 0; i <= REPLACE_RETRY; i++) {
1324 Map<String, Property> propMapCurr = getNodeProps(node);
1325 if (propMapCurr != null) {
1326 if (!propMapCurr.containsKey(propName)) {
1327 return new Status(StatusCode.SUCCESS);
1329 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1330 propMap.remove(propName);
1331 if (nodeProps.replace(node, propMapCurr, propMap)) {
1332 return new Status(StatusCode.SUCCESS);
1334 if (!propMapCurr.get(propName).equals(nodeProps.get(node).get(propName))) {
1335 String msg = "Cluster conflict: Unable to remove property " + propName + " for node "
1337 return new Status(StatusCode.CONFLICT, msg);
1341 return new Status(StatusCode.SUCCESS);
1344 String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID();
1345 return new Status(StatusCode.CONFLICT, msg);
1349 public Status removeNodeAllProps(Node node) {
1350 this.nodeProps.remove(node);
1351 return new Status(StatusCode.SUCCESS);
1355 public Set<NodeConnector> getUpNodeConnectors(Node node) {
1356 if (nodeConnectorProps == null) {
1360 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1361 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1362 NodeConnector nodeConnector = entry.getKey();
1363 if (!nodeConnector.getNode().equals(node)) {
1366 if (isNodeConnectorEnabled(nodeConnector)) {
1367 nodeConnectorSet.add(nodeConnector);
1371 return nodeConnectorSet;
1375 public Set<NodeConnector> getNodeConnectors(Node node) {
1376 if (nodeConnectorProps == null) {
1380 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1381 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1382 NodeConnector nodeConnector = entry.getKey();
1383 if (!nodeConnector.getNode().equals(node)) {
1386 nodeConnectorSet.add(nodeConnector);
1389 return nodeConnectorSet;
1393 public Set<NodeConnector> getPhysicalNodeConnectors(Node node) {
1394 if (nodeConnectorProps == null) {
1398 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1399 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1400 NodeConnector nodeConnector = entry.getKey();
1401 if (!nodeConnector.getNode().equals(node)
1402 || isSpecial(nodeConnector)) {
1405 nodeConnectorSet.add(nodeConnector);
1408 return nodeConnectorSet;
1412 public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) {
1413 Map<String, Property> rv = new HashMap<String, Property>();
1414 if (this.nodeConnectorProps != null) {
1415 rv = this.nodeConnectorProps.get(nodeConnector);
1417 rv = new HashMap<String, Property>(rv);
1424 public Property getNodeConnectorProp(NodeConnector nodeConnector,
1426 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1427 return (propMap != null) ? propMap.get(propName) : null;
1430 private byte[] getHardwareMAC() {
1431 Enumeration<NetworkInterface> nis;
1432 byte[] macAddress = null;
1435 nis = NetworkInterface.getNetworkInterfaces();
1436 } catch (SocketException e) {
1437 log.error("Failed to acquire controller MAC: ", e);
1441 while (nis.hasMoreElements()) {
1442 NetworkInterface ni = nis.nextElement();
1444 macAddress = ni.getHardwareAddress();
1445 } catch (SocketException e) {
1446 log.error("Failed to acquire controller MAC: ", e);
1448 if (macAddress != null) {
1452 if (macAddress == null) {
1453 log.warn("Failed to acquire controller MAC: No physical interface found");
1454 // This happens when running controller on windows VM, for example
1455 // Try parsing the OS command output
1461 public byte[] getControllerMAC() {
1462 MacAddress macProperty = (MacAddress)controllerProps.get(MacAddress.name);
1463 return (macProperty == null) ? null : macProperty.getMacAddress();
1467 public NodeConnector getNodeConnector(Node node, String nodeConnectorName) {
1468 if (nodeConnectorNames == null) {
1472 Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1477 return map.get(nodeConnectorName);
1481 * Adds a node connector and its property if any
1483 * @param nodeConnector
1484 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1486 * name of {@link org.opendaylight.controller.sal.core.Property}
1487 * @return success or failed reason
1490 public Status addNodeConnectorProp(NodeConnector nodeConnector,
1492 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1493 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1494 : new HashMap<String, Property>(propMapCurr);
1496 String msg = "Cluster conflict: Unable to add NodeConnector Property.";
1497 // Just add the nodeConnector if prop is not available (in a non-default
1500 if (propMapCurr == null) {
1501 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1502 return new Status(StatusCode.CONFLICT, msg);
1505 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1506 return new Status(StatusCode.CONFLICT, msg);
1509 return new Status(StatusCode.SUCCESS);
1512 propMap.put(prop.getName(), prop);
1513 if (propMapCurr == null) {
1514 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1515 return new Status(StatusCode.CONFLICT, msg);
1518 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1519 return new Status(StatusCode.CONFLICT, msg);
1523 if (prop.getName().equals(Name.NamePropName)) {
1524 if (nodeConnectorNames != null) {
1525 Node node = nodeConnector.getNode();
1526 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1527 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1528 if (mapCurr != null) {
1529 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1530 String s = entry.getKey();
1532 map.put(s, new NodeConnector(entry.getValue()));
1533 } catch (ConstructionException e) {
1534 log.error("An error occured",e);
1539 map.put(((Name) prop).getValue(), nodeConnector);
1540 if (mapCurr == null) {
1541 if (nodeConnectorNames.putIfAbsent(node, map) != null) {
1542 // TODO: recovery using Transactionality
1543 return new Status(StatusCode.CONFLICT, msg);
1546 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1547 // TODO: recovery using Transactionality
1548 return new Status(StatusCode.CONFLICT, msg);
1554 return new Status(StatusCode.SUCCESS);
1558 * Removes one property of a node connector
1560 * @param nodeConnector
1561 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1563 * name of {@link org.opendaylight.controller.sal.core.Property}
1564 * @return success or failed reason
1567 public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) {
1568 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1570 if (propMapCurr == null) {
1571 /* Nothing to remove */
1572 return new Status(StatusCode.SUCCESS);
1575 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1576 propMap.remove(propName);
1577 boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap);
1578 String msg = "Cluster conflict: Unable to remove NodeConnector property.";
1580 return new Status(StatusCode.CONFLICT, msg);
1583 if (propName.equals(Name.NamePropName)) {
1584 if (nodeConnectorNames != null) {
1585 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1587 Node node = nodeConnector.getNode();
1588 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1589 if (mapCurr != null) {
1590 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1591 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1592 String s = entry.getKey();
1594 map.put(s, new NodeConnector(entry.getValue()));
1595 } catch (ConstructionException e) {
1596 log.error("An error occured",e);
1599 map.remove(name.getValue());
1600 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1601 // TODO: recovery using Transactionality
1602 return new Status(StatusCode.CONFLICT, msg);
1609 return new Status(StatusCode.SUCCESS);
1613 * Removes all the properties of a node connector
1615 * @param nodeConnector
1616 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1617 * @return success or failed reason
1620 public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) {
1621 if (nodeConnectorNames != null) {
1622 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1624 Node node = nodeConnector.getNode();
1625 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1626 if (mapCurr != null) {
1627 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1628 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1629 String s = entry.getKey();
1631 map.put(s, new NodeConnector(entry.getValue()));
1632 } catch (ConstructionException e) {
1633 log.error("An error occured",e);
1636 map.remove(name.getValue());
1637 if (map.isEmpty()) {
1638 nodeConnectorNames.remove(node);
1640 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1641 log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.",
1642 nodeConnector.getID());
1649 nodeConnectorProps.remove(nodeConnector);
1651 return new Status(StatusCode.SUCCESS);
1655 * Function called by the dependency manager when all the required
1656 * dependencies are satisfied
1659 void init(Component c) {
1660 Dictionary<?, ?> props = c.getServiceProperties();
1661 if (props != null) {
1662 this.containerName = (String) props.get("containerName");
1663 log.trace("Running containerName: {}", this.containerName);
1665 // In the Global instance case the containerName is empty
1666 this.containerName = "";
1668 isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT
1675 * Function called by the dependency manager when at least one dependency
1676 * become unsatisfied or when the component is shutting down because for
1677 * example bundle is being stopped.
1685 * Function called by dependency manager after "init ()" is called and after
1686 * the services provided by the class are registered in the service registry
1691 registerWithOSGIConsole();
1695 * Function called after registered the service in OSGi service registry.
1698 // solicit for existing inventories
1703 * Function called by the dependency manager before the services exported by
1704 * the component are unregistered, this will be followed by a "destroy ()"
1711 public void setInventoryService(IInventoryService service) {
1712 log.trace("Got inventory service set request {}", service);
1713 this.inventoryService = service;
1715 // solicit for existing inventories
1719 public void unsetInventoryService(IInventoryService service) {
1720 log.trace("Got a service UNset request");
1721 this.inventoryService = null;
1723 // clear existing inventories
1727 public void setStatisticsManager(IStatisticsManager statisticsManager) {
1728 log.trace("Got statistics manager set request {}", statisticsManager);
1729 this.statisticsManager = statisticsManager;
1732 public void unsetStatisticsManager(IStatisticsManager statisticsManager) {
1733 log.trace("Got statistics manager UNset request");
1734 this.statisticsManager = null;
1737 public void setSwitchManagerAware(ISwitchManagerAware service) {
1738 log.trace("Got inventory service set request {}", service);
1739 if (this.switchManagerAware != null) {
1740 this.switchManagerAware.add(service);
1743 // bulk update for newly joined
1744 switchManagerAwareNotify(service);
1747 public void unsetSwitchManagerAware(ISwitchManagerAware service) {
1748 log.trace("Got a service UNset request");
1749 if (this.switchManagerAware != null) {
1750 this.switchManagerAware.remove(service);
1754 public void setInventoryListener(IInventoryListener service) {
1755 log.trace("Got inventory listener set request {}", service);
1756 if (this.inventoryListeners != null) {
1757 this.inventoryListeners.add(service);
1760 // bulk update for newly joined
1761 bulkUpdateService(service);
1764 public void unsetInventoryListener(IInventoryListener service) {
1765 log.trace("Got a service UNset request");
1766 if (this.inventoryListeners != null) {
1767 this.inventoryListeners.remove(service);
1771 public void setSpanAware(ISpanAware service) {
1772 log.trace("Got SpanAware set request {}", service);
1773 if (this.spanAware != null) {
1774 this.spanAware.add(service);
1777 // bulk update for newly joined
1778 spanAwareNotify(service);
1781 public void unsetSpanAware(ISpanAware service) {
1782 log.trace("Got a service UNset request");
1783 if (this.spanAware != null) {
1784 this.spanAware.remove(service);
1788 void setClusterContainerService(IClusterContainerServices s) {
1789 log.trace("Cluster Service set");
1790 this.clusterContainerService = s;
1793 void unsetClusterContainerService(IClusterContainerServices s) {
1794 if (this.clusterContainerService == s) {
1795 log.trace("Cluster Service removed!");
1796 this.clusterContainerService = null;
1800 private void getInventories() {
1801 if (inventoryService == null) {
1802 log.trace("inventory service not avaiable");
1806 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
1807 for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) {
1808 Node node = entry.getKey();
1809 log.debug("getInventories: {} added for container {}", new Object[] { node, containerName });
1810 Map<String, Property> propMap = entry.getValue();
1811 Set<Property> props = new HashSet<Property>();
1812 for (Property property : propMap.values()) {
1813 props.add(property);
1815 addNode(node, props);
1818 Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps();
1819 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) {
1820 Map<String, Property> propMap = entry.getValue();
1821 for (Property property : propMap.values()) {
1822 addNodeConnectorProp(entry.getKey(), property);
1827 private void clearInventories() {
1829 nodeConnectorProps.clear();
1830 nodeConnectorNames.clear();
1831 spanNodeConnectors.clear();
1834 private void notifyNode(Node node, UpdateType type,
1835 Map<String, Property> propMap) {
1836 synchronized (inventoryListeners) {
1837 for (IInventoryListener service : inventoryListeners) {
1838 service.notifyNode(node, type, propMap);
1843 private void notifyNodeConnector(NodeConnector nodeConnector,
1844 UpdateType type, Map<String, Property> propMap) {
1845 synchronized (inventoryListeners) {
1846 for (IInventoryListener service : inventoryListeners) {
1847 service.notifyNodeConnector(nodeConnector, type, propMap);
1853 * For those joined late, bring them up-to-date.
1855 private void switchManagerAwareNotify(ISwitchManagerAware service) {
1856 for (Subnet sub : subnets.values()) {
1857 service.subnetNotify(sub, true);
1860 for (Node node : getNodes()) {
1861 SwitchConfig sc = getSwitchConfig(node.toString());
1862 if ((sc != null) && isDefaultContainer) {
1863 ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
1864 service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive());
1869 private void bulkUpdateService(IInventoryListener service) {
1870 Map<String, Property> propMap;
1871 UpdateType type = UpdateType.ADDED;
1873 for (Node node : getNodes()) {
1874 propMap = nodeProps.get(node);
1875 service.notifyNode(node, type, propMap);
1878 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1879 NodeConnector nodeConnector = entry.getKey();
1880 propMap = nodeConnectorProps.get(nodeConnector);
1881 service.notifyNodeConnector(nodeConnector, type, propMap);
1885 private void spanAwareNotify(ISpanAware service) {
1886 for (Node node : getNodes()) {
1887 for (SpanConfig conf : getSpanConfigList(node)) {
1888 service.spanUpdate(node, conf.getPortArrayList(), true);
1893 private void registerWithOSGIConsole() {
1894 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
1895 .getBundleContext();
1896 bundleContext.registerService(CommandProvider.class.getName(), this,
1901 public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) {
1902 if (nodeConnector == null) {
1906 Config config = (Config) getNodeConnectorProp(nodeConnector,
1907 Config.ConfigPropName);
1908 State state = (State) getNodeConnectorProp(nodeConnector,
1909 State.StatePropName);
1910 return ((config != null) && (config.getValue() == Config.ADMIN_UP)
1911 && (state != null) && (state.getValue() == State.EDGE_UP));
1915 public boolean doesNodeConnectorExist(NodeConnector nc) {
1916 return (nc != null && nodeConnectorProps != null
1917 && nodeConnectorProps.containsKey(nc));
1921 public String getHelp() {
1922 StringBuffer help = new StringBuffer();
1923 help.append("---Switch Manager---\n");
1924 help.append("\t pencs <node id> - Print enabled node connectors for a given node\n");
1925 help.append("\t pdm <node id> - Print switch ports in device map\n");
1926 return help.toString();
1929 public void _pencs(CommandInterpreter ci) {
1930 String st = ci.nextArgument();
1932 ci.println("Please enter node id");
1936 Node node = Node.fromString(st);
1938 ci.println("Please enter node id");
1942 Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node);
1943 if (nodeConnectorSet == null) {
1946 for (NodeConnector nodeConnector : nodeConnectorSet) {
1947 if (nodeConnector == null) {
1950 ci.println(nodeConnector);
1952 ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1955 public void _pdm(CommandInterpreter ci) {
1956 String st = ci.nextArgument();
1958 ci.println("Please enter node id");
1962 Node node = Node.fromString(st);
1964 ci.println("Please enter node id");
1968 Switch sw = getSwitchByNode(node);
1970 ci.println(" NodeConnector Name");
1972 Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors();
1973 String nodeConnectorName;
1974 if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
1975 for (NodeConnector nodeConnector : nodeConnectorSet) {
1976 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1977 nodeConnectorName = (propMap == null) ? null : ((Name) propMap
1978 .get(Name.NamePropName)).getValue();
1979 if (nodeConnectorName != null) {
1980 Node nd = nodeConnector.getNode();
1981 if (!nd.equals(node)) {
1982 log.debug("node not match {} {}", nd, node);
1984 Map<String, NodeConnector> map = nodeConnectorNames
1987 NodeConnector nc = map.get(nodeConnectorName);
1989 log.debug("no nodeConnector named {}",
1991 } else if (!nc.equals(nodeConnector)) {
1992 log.debug("nodeConnector not match {} {}", nc,
1998 ci.println(nodeConnector
2000 + ((nodeConnectorName == null) ? "" : nodeConnectorName)
2001 + "(" + nodeConnector.getID() + ")");
2003 ci.println("Total number of NodeConnectors: "
2004 + nodeConnectorSet.size());
2009 public byte[] getNodeMAC(Node node) {
2010 MacAddress mac = (MacAddress) this.getNodeProp(node,
2012 return (mac != null) ? mac.getMacAddress() : null;
2016 public boolean isSpecial(NodeConnector p) {
2017 if (p.getType().equals(NodeConnectorIDType.CONTROLLER)
2018 || p.getType().equals(NodeConnectorIDType.ALL)
2019 || p.getType().equals(NodeConnectorIDType.SWSTACK)
2020 || p.getType().equals(NodeConnectorIDType.HWPATH)) {
2027 * Add span configuration to local cache and notify clients
2029 private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2030 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2032 for (NodeConnector nodeConnector : nodeConnectors) {
2033 if (!spanNodeConnectors.contains(nodeConnector)) {
2034 ncLists.add(nodeConnector);
2038 if (ncLists.size() > 0) {
2039 spanNodeConnectors.addAll(ncLists);
2040 notifySpanPortChange(node, ncLists, true);
2044 private void addSpanPorts(Node node) {
2045 for (SpanConfig conf : getSpanConfigList(node)) {
2046 addSpanPorts(node, conf.getPortArrayList());
2050 private void addSpanPort(NodeConnector nodeConnector) {
2051 // only add if span is configured on this nodeConnector
2052 for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) {
2053 if (conf.getPortArrayList().contains(nodeConnector)) {
2054 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2055 ncLists.add(nodeConnector);
2056 addSpanPorts(nodeConnector.getNode(), ncLists);
2063 * Remove span configuration to local cache and notify clients
2065 private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2066 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2068 for (NodeConnector nodeConnector : nodeConnectors) {
2069 if (spanNodeConnectors.contains(nodeConnector)) {
2070 ncLists.add(nodeConnector);
2074 if (ncLists.size() > 0) {
2075 spanNodeConnectors.removeAll(ncLists);
2076 notifySpanPortChange(node, ncLists, false);
2080 private void removeSpanPorts(Node node) {
2081 for (SpanConfig conf : getSpanConfigList(node)) {
2082 addSpanPorts(node, conf.getPortArrayList());
2086 private void removeSpanPort(NodeConnector nodeConnector) {
2087 if (spanNodeConnectors.contains(nodeConnector)) {
2088 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2089 ncLists.add(nodeConnector);
2090 removeSpanPorts(nodeConnector.getNode(), ncLists);
2094 private void addNodeProps(Node node, Map<String, Property> propMap) {
2095 if (propMap == null) {
2096 propMap = new HashMap<String, Property>();
2098 nodeProps.put(node, propMap);
2102 public Status saveConfiguration() {
2103 return saveSwitchConfig();
2107 * Creates a Name/Tier/Bandwidth/MacAddress(controller property) Property
2108 * object based on given property name and value. Other property types are
2109 * not supported yet.
2112 * Name of the Property
2114 * Value of the Property
2115 * @return {@link org.opendaylight.controller.sal.core.Property}
2118 public Property createProperty(String propName, String propValue) {
2119 if (propName == null) {
2120 log.debug("propName is null");
2123 if (propValue == null) {
2124 log.debug("propValue is null");
2129 if (propName.equalsIgnoreCase(Description.propertyName)) {
2130 return new Description(propValue);
2131 } else if (propName.equalsIgnoreCase(Tier.TierPropName)) {
2132 int tier = Integer.parseInt(propValue);
2133 return new Tier(tier);
2134 } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) {
2135 long bw = Long.parseLong(propValue);
2136 return new Bandwidth(bw);
2137 } else if (propName.equalsIgnoreCase(ForwardingMode.name)) {
2138 int mode = Integer.parseInt(propValue);
2139 return new ForwardingMode(mode);
2140 } else if (propName.equalsIgnoreCase(MacAddress.name)){
2141 return new MacAddress(propValue);
2144 log.debug("Not able to create {} property", propName);
2146 } catch (Exception e) {
2147 log.debug("createProperty caught exception {}", e.getMessage());
2154 @SuppressWarnings("deprecation")
2156 public String getNodeDescription(Node node) {
2157 // Check first if user configured a name
2158 SwitchConfig config = getSwitchConfig(node.toString());
2159 if (config != null) {
2160 String configuredDesc = config.getNodeDescription();
2161 if (configuredDesc != null && !configuredDesc.isEmpty()) {
2162 return configuredDesc;
2166 // No name configured by user, get the node advertised name
2167 Description desc = (Description) getNodeProp(node,
2168 Description.propertyName);
2169 return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? ""
2174 public Set<Switch> getConfiguredNotConnectedSwitches() {
2175 Set<Switch> configuredNotConnectedSwitches = new HashSet<Switch>();
2176 if (this.inventoryService == null) {
2177 log.trace("inventory service not avaiable");
2178 return configuredNotConnectedSwitches;
2181 Set<Node> configuredNotConnectedNodes = this.inventoryService.getConfiguredNotConnectedNodes();
2182 if (configuredNotConnectedNodes != null) {
2183 for (Node node : configuredNotConnectedNodes) {
2184 Switch sw = getSwitchByNode(node);
2186 configuredNotConnectedSwitches.add(sw);
2190 return configuredNotConnectedSwitches;