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)) {
1314 log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1318 public Status removeNodeProp(Node node, String propName) {
1319 for (int i = 0; i <= REPLACE_RETRY; i++) {
1320 Map<String, Property> propMapCurr = getNodeProps(node);
1321 if (propMapCurr != null) {
1322 if (!propMapCurr.containsKey(propName)) {
1323 return new Status(StatusCode.SUCCESS);
1325 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1326 propMap.remove(propName);
1327 if (nodeProps.replace(node, propMapCurr, propMap)) {
1328 return new Status(StatusCode.SUCCESS);
1331 return new Status(StatusCode.SUCCESS);
1334 String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID();
1335 return new Status(StatusCode.CONFLICT, msg);
1339 public Status removeNodeAllProps(Node node) {
1340 this.nodeProps.remove(node);
1341 return new Status(StatusCode.SUCCESS);
1345 public Set<NodeConnector> getUpNodeConnectors(Node node) {
1346 if (nodeConnectorProps == null) {
1350 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1351 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1352 NodeConnector nodeConnector = entry.getKey();
1353 if (!nodeConnector.getNode().equals(node)) {
1356 if (isNodeConnectorEnabled(nodeConnector)) {
1357 nodeConnectorSet.add(nodeConnector);
1361 return nodeConnectorSet;
1365 public Set<NodeConnector> getNodeConnectors(Node node) {
1366 if (nodeConnectorProps == null) {
1370 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1371 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1372 NodeConnector nodeConnector = entry.getKey();
1373 if (!nodeConnector.getNode().equals(node)) {
1376 nodeConnectorSet.add(nodeConnector);
1379 return nodeConnectorSet;
1383 public Set<NodeConnector> getPhysicalNodeConnectors(Node node) {
1384 if (nodeConnectorProps == null) {
1388 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1389 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1390 NodeConnector nodeConnector = entry.getKey();
1391 if (!nodeConnector.getNode().equals(node)
1392 || isSpecial(nodeConnector)) {
1395 nodeConnectorSet.add(nodeConnector);
1398 return nodeConnectorSet;
1402 public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) {
1403 Map<String, Property> rv = new HashMap<String, Property>();
1404 if (this.nodeConnectorProps != null) {
1405 rv = this.nodeConnectorProps.get(nodeConnector);
1407 rv = new HashMap<String, Property>(rv);
1414 public Property getNodeConnectorProp(NodeConnector nodeConnector,
1416 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1417 return (propMap != null) ? propMap.get(propName) : null;
1420 private byte[] getHardwareMAC() {
1421 Enumeration<NetworkInterface> nis;
1422 byte[] macAddress = null;
1425 nis = NetworkInterface.getNetworkInterfaces();
1426 } catch (SocketException e) {
1427 log.error("Failed to acquire controller MAC: ", e);
1431 while (nis.hasMoreElements()) {
1432 NetworkInterface ni = nis.nextElement();
1434 macAddress = ni.getHardwareAddress();
1435 } catch (SocketException e) {
1436 log.error("Failed to acquire controller MAC: ", e);
1438 if (macAddress != null) {
1442 if (macAddress == null) {
1443 log.warn("Failed to acquire controller MAC: No physical interface found");
1444 // This happens when running controller on windows VM, for example
1445 // Try parsing the OS command output
1451 public byte[] getControllerMAC() {
1452 MacAddress macProperty = (MacAddress)controllerProps.get(MacAddress.name);
1453 return (macProperty == null) ? null : macProperty.getMacAddress();
1457 public NodeConnector getNodeConnector(Node node, String nodeConnectorName) {
1458 if (nodeConnectorNames == null) {
1462 Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1467 return map.get(nodeConnectorName);
1471 * Adds a node connector and its property if any
1473 * @param nodeConnector
1474 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1476 * name of {@link org.opendaylight.controller.sal.core.Property}
1477 * @return success or failed reason
1480 public Status addNodeConnectorProp(NodeConnector nodeConnector,
1482 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1483 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1484 : new HashMap<String, Property>(propMapCurr);
1486 String msg = "Cluster conflict: Unable to add NodeConnector Property.";
1487 // Just add the nodeConnector if prop is not available (in a non-default
1490 if (propMapCurr == null) {
1491 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1492 return new Status(StatusCode.CONFLICT, msg);
1495 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1496 return new Status(StatusCode.CONFLICT, msg);
1499 return new Status(StatusCode.SUCCESS);
1502 propMap.put(prop.getName(), prop);
1503 if (propMapCurr == null) {
1504 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1505 return new Status(StatusCode.CONFLICT, msg);
1508 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1509 return new Status(StatusCode.CONFLICT, msg);
1513 if (prop.getName().equals(Name.NamePropName)) {
1514 if (nodeConnectorNames != null) {
1515 Node node = nodeConnector.getNode();
1516 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1517 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1518 if (mapCurr != null) {
1519 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1520 String s = entry.getKey();
1522 map.put(s, new NodeConnector(entry.getValue()));
1523 } catch (ConstructionException e) {
1524 log.error("An error occured",e);
1529 map.put(((Name) prop).getValue(), nodeConnector);
1530 if (mapCurr == null) {
1531 if (nodeConnectorNames.putIfAbsent(node, map) != null) {
1532 // TODO: recovery using Transactionality
1533 return new Status(StatusCode.CONFLICT, msg);
1536 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1537 // TODO: recovery using Transactionality
1538 return new Status(StatusCode.CONFLICT, msg);
1544 return new Status(StatusCode.SUCCESS);
1548 * Removes one property of a node connector
1550 * @param nodeConnector
1551 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1553 * name of {@link org.opendaylight.controller.sal.core.Property}
1554 * @return success or failed reason
1557 public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) {
1558 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1560 if (propMapCurr == null) {
1561 /* Nothing to remove */
1562 return new Status(StatusCode.SUCCESS);
1565 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1566 propMap.remove(propName);
1567 boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap);
1568 String msg = "Cluster conflict: Unable to remove NodeConnector property.";
1570 return new Status(StatusCode.CONFLICT, msg);
1573 if (propName.equals(Name.NamePropName)) {
1574 if (nodeConnectorNames != null) {
1575 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1577 Node node = nodeConnector.getNode();
1578 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1579 if (mapCurr != null) {
1580 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1581 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1582 String s = entry.getKey();
1584 map.put(s, new NodeConnector(entry.getValue()));
1585 } catch (ConstructionException e) {
1586 log.error("An error occured",e);
1589 map.remove(name.getValue());
1590 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1591 // TODO: recovery using Transactionality
1592 return new Status(StatusCode.CONFLICT, msg);
1599 return new Status(StatusCode.SUCCESS);
1603 * Removes all the properties of a node connector
1605 * @param nodeConnector
1606 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1607 * @return success or failed reason
1610 public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) {
1611 if (nodeConnectorNames != null) {
1612 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1614 Node node = nodeConnector.getNode();
1615 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1616 if (mapCurr != null) {
1617 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1618 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1619 String s = entry.getKey();
1621 map.put(s, new NodeConnector(entry.getValue()));
1622 } catch (ConstructionException e) {
1623 log.error("An error occured",e);
1626 map.remove(name.getValue());
1627 if (map.isEmpty()) {
1628 nodeConnectorNames.remove(node);
1630 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1631 log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.",
1632 nodeConnector.getID());
1639 nodeConnectorProps.remove(nodeConnector);
1641 return new Status(StatusCode.SUCCESS);
1645 * Function called by the dependency manager when all the required
1646 * dependencies are satisfied
1649 void init(Component c) {
1650 Dictionary<?, ?> props = c.getServiceProperties();
1651 if (props != null) {
1652 this.containerName = (String) props.get("containerName");
1653 log.trace("Running containerName: {}", this.containerName);
1655 // In the Global instance case the containerName is empty
1656 this.containerName = "";
1658 isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT
1665 * Function called by the dependency manager when at least one dependency
1666 * become unsatisfied or when the component is shutting down because for
1667 * example bundle is being stopped.
1675 * Function called by dependency manager after "init ()" is called and after
1676 * the services provided by the class are registered in the service registry
1681 registerWithOSGIConsole();
1685 * Function called after registered the service in OSGi service registry.
1688 // solicit for existing inventories
1693 * Function called by the dependency manager before the services exported by
1694 * the component are unregistered, this will be followed by a "destroy ()"
1701 public void setInventoryService(IInventoryService service) {
1702 log.trace("Got inventory service set request {}", service);
1703 this.inventoryService = service;
1705 // solicit for existing inventories
1709 public void unsetInventoryService(IInventoryService service) {
1710 log.trace("Got a service UNset request");
1711 this.inventoryService = null;
1713 // clear existing inventories
1717 public void setStatisticsManager(IStatisticsManager statisticsManager) {
1718 log.trace("Got statistics manager set request {}", statisticsManager);
1719 this.statisticsManager = statisticsManager;
1722 public void unsetStatisticsManager(IStatisticsManager statisticsManager) {
1723 log.trace("Got statistics manager UNset request");
1724 this.statisticsManager = null;
1727 public void setSwitchManagerAware(ISwitchManagerAware service) {
1728 log.trace("Got inventory service set request {}", service);
1729 if (this.switchManagerAware != null) {
1730 this.switchManagerAware.add(service);
1733 // bulk update for newly joined
1734 switchManagerAwareNotify(service);
1737 public void unsetSwitchManagerAware(ISwitchManagerAware service) {
1738 log.trace("Got a service UNset request");
1739 if (this.switchManagerAware != null) {
1740 this.switchManagerAware.remove(service);
1744 public void setInventoryListener(IInventoryListener service) {
1745 log.trace("Got inventory listener set request {}", service);
1746 if (this.inventoryListeners != null) {
1747 this.inventoryListeners.add(service);
1750 // bulk update for newly joined
1751 bulkUpdateService(service);
1754 public void unsetInventoryListener(IInventoryListener service) {
1755 log.trace("Got a service UNset request");
1756 if (this.inventoryListeners != null) {
1757 this.inventoryListeners.remove(service);
1761 public void setSpanAware(ISpanAware service) {
1762 log.trace("Got SpanAware set request {}", service);
1763 if (this.spanAware != null) {
1764 this.spanAware.add(service);
1767 // bulk update for newly joined
1768 spanAwareNotify(service);
1771 public void unsetSpanAware(ISpanAware service) {
1772 log.trace("Got a service UNset request");
1773 if (this.spanAware != null) {
1774 this.spanAware.remove(service);
1778 void setClusterContainerService(IClusterContainerServices s) {
1779 log.trace("Cluster Service set");
1780 this.clusterContainerService = s;
1783 void unsetClusterContainerService(IClusterContainerServices s) {
1784 if (this.clusterContainerService == s) {
1785 log.trace("Cluster Service removed!");
1786 this.clusterContainerService = null;
1790 private void getInventories() {
1791 if (inventoryService == null) {
1792 log.trace("inventory service not avaiable");
1796 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
1797 for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) {
1798 Node node = entry.getKey();
1799 log.debug("getInventories: {} added for container {}", new Object[] { node, containerName });
1800 Map<String, Property> propMap = entry.getValue();
1801 Set<Property> props = new HashSet<Property>();
1802 for (Property property : propMap.values()) {
1803 props.add(property);
1805 addNode(node, props);
1808 Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps();
1809 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) {
1810 Map<String, Property> propMap = entry.getValue();
1811 for (Property property : propMap.values()) {
1812 addNodeConnectorProp(entry.getKey(), property);
1817 private void clearInventories() {
1819 nodeConnectorProps.clear();
1820 nodeConnectorNames.clear();
1821 spanNodeConnectors.clear();
1824 private void notifyNode(Node node, UpdateType type,
1825 Map<String, Property> propMap) {
1826 synchronized (inventoryListeners) {
1827 for (IInventoryListener service : inventoryListeners) {
1828 service.notifyNode(node, type, propMap);
1833 private void notifyNodeConnector(NodeConnector nodeConnector,
1834 UpdateType type, Map<String, Property> propMap) {
1835 synchronized (inventoryListeners) {
1836 for (IInventoryListener service : inventoryListeners) {
1837 service.notifyNodeConnector(nodeConnector, type, propMap);
1843 * For those joined late, bring them up-to-date.
1845 private void switchManagerAwareNotify(ISwitchManagerAware service) {
1846 for (Subnet sub : subnets.values()) {
1847 service.subnetNotify(sub, true);
1850 for (Node node : getNodes()) {
1851 SwitchConfig sc = getSwitchConfig(node.toString());
1852 if ((sc != null) && isDefaultContainer) {
1853 ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
1854 service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive());
1859 private void bulkUpdateService(IInventoryListener service) {
1860 Map<String, Property> propMap;
1861 UpdateType type = UpdateType.ADDED;
1863 for (Node node : getNodes()) {
1864 propMap = nodeProps.get(node);
1865 service.notifyNode(node, type, propMap);
1868 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1869 NodeConnector nodeConnector = entry.getKey();
1870 propMap = nodeConnectorProps.get(nodeConnector);
1871 service.notifyNodeConnector(nodeConnector, type, propMap);
1875 private void spanAwareNotify(ISpanAware service) {
1876 for (Node node : getNodes()) {
1877 for (SpanConfig conf : getSpanConfigList(node)) {
1878 service.spanUpdate(node, conf.getPortArrayList(), true);
1883 private void registerWithOSGIConsole() {
1884 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
1885 .getBundleContext();
1886 bundleContext.registerService(CommandProvider.class.getName(), this,
1891 public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) {
1892 if (nodeConnector == null) {
1896 Config config = (Config) getNodeConnectorProp(nodeConnector,
1897 Config.ConfigPropName);
1898 State state = (State) getNodeConnectorProp(nodeConnector,
1899 State.StatePropName);
1900 return ((config != null) && (config.getValue() == Config.ADMIN_UP)
1901 && (state != null) && (state.getValue() == State.EDGE_UP));
1905 public boolean doesNodeConnectorExist(NodeConnector nc) {
1906 return (nc != null && nodeConnectorProps != null
1907 && nodeConnectorProps.containsKey(nc));
1911 public String getHelp() {
1912 StringBuffer help = new StringBuffer();
1913 help.append("---Switch Manager---\n");
1914 help.append("\t pencs <node id> - Print enabled node connectors for a given node\n");
1915 help.append("\t pdm <node id> - Print switch ports in device map\n");
1916 return help.toString();
1919 public void _pencs(CommandInterpreter ci) {
1920 String st = ci.nextArgument();
1922 ci.println("Please enter node id");
1926 Node node = Node.fromString(st);
1928 ci.println("Please enter node id");
1932 Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node);
1933 if (nodeConnectorSet == null) {
1936 for (NodeConnector nodeConnector : nodeConnectorSet) {
1937 if (nodeConnector == null) {
1940 ci.println(nodeConnector);
1942 ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1945 public void _pdm(CommandInterpreter ci) {
1946 String st = ci.nextArgument();
1948 ci.println("Please enter node id");
1952 Node node = Node.fromString(st);
1954 ci.println("Please enter node id");
1958 Switch sw = getSwitchByNode(node);
1960 ci.println(" NodeConnector Name");
1962 Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors();
1963 String nodeConnectorName;
1964 if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
1965 for (NodeConnector nodeConnector : nodeConnectorSet) {
1966 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1967 nodeConnectorName = (propMap == null) ? null : ((Name) propMap
1968 .get(Name.NamePropName)).getValue();
1969 if (nodeConnectorName != null) {
1970 Node nd = nodeConnector.getNode();
1971 if (!nd.equals(node)) {
1972 log.debug("node not match {} {}", nd, node);
1974 Map<String, NodeConnector> map = nodeConnectorNames
1977 NodeConnector nc = map.get(nodeConnectorName);
1979 log.debug("no nodeConnector named {}",
1981 } else if (!nc.equals(nodeConnector)) {
1982 log.debug("nodeConnector not match {} {}", nc,
1988 ci.println(nodeConnector
1990 + ((nodeConnectorName == null) ? "" : nodeConnectorName)
1991 + "(" + nodeConnector.getID() + ")");
1993 ci.println("Total number of NodeConnectors: "
1994 + nodeConnectorSet.size());
1999 public byte[] getNodeMAC(Node node) {
2000 MacAddress mac = (MacAddress) this.getNodeProp(node,
2002 return (mac != null) ? mac.getMacAddress() : null;
2006 public boolean isSpecial(NodeConnector p) {
2007 if (p.getType().equals(NodeConnectorIDType.CONTROLLER)
2008 || p.getType().equals(NodeConnectorIDType.ALL)
2009 || p.getType().equals(NodeConnectorIDType.SWSTACK)
2010 || p.getType().equals(NodeConnectorIDType.HWPATH)) {
2017 * Add span configuration to local cache and notify clients
2019 private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2020 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2022 for (NodeConnector nodeConnector : nodeConnectors) {
2023 if (!spanNodeConnectors.contains(nodeConnector)) {
2024 ncLists.add(nodeConnector);
2028 if (ncLists.size() > 0) {
2029 spanNodeConnectors.addAll(ncLists);
2030 notifySpanPortChange(node, ncLists, true);
2034 private void addSpanPorts(Node node) {
2035 for (SpanConfig conf : getSpanConfigList(node)) {
2036 addSpanPorts(node, conf.getPortArrayList());
2040 private void addSpanPort(NodeConnector nodeConnector) {
2041 // only add if span is configured on this nodeConnector
2042 for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) {
2043 if (conf.getPortArrayList().contains(nodeConnector)) {
2044 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2045 ncLists.add(nodeConnector);
2046 addSpanPorts(nodeConnector.getNode(), ncLists);
2053 * Remove span configuration to local cache and notify clients
2055 private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2056 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2058 for (NodeConnector nodeConnector : nodeConnectors) {
2059 if (spanNodeConnectors.contains(nodeConnector)) {
2060 ncLists.add(nodeConnector);
2064 if (ncLists.size() > 0) {
2065 spanNodeConnectors.removeAll(ncLists);
2066 notifySpanPortChange(node, ncLists, false);
2070 private void removeSpanPorts(Node node) {
2071 for (SpanConfig conf : getSpanConfigList(node)) {
2072 addSpanPorts(node, conf.getPortArrayList());
2076 private void removeSpanPort(NodeConnector nodeConnector) {
2077 if (spanNodeConnectors.contains(nodeConnector)) {
2078 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2079 ncLists.add(nodeConnector);
2080 removeSpanPorts(nodeConnector.getNode(), ncLists);
2084 private void addNodeProps(Node node, Map<String, Property> propMap) {
2085 if (propMap == null) {
2086 propMap = new HashMap<String, Property>();
2088 nodeProps.put(node, propMap);
2092 public Status saveConfiguration() {
2093 return saveSwitchConfig();
2097 * Creates a Name/Tier/Bandwidth/MacAddress(controller property) Property
2098 * object based on given property name and value. Other property types are
2099 * not supported yet.
2102 * Name of the Property
2104 * Value of the Property
2105 * @return {@link org.opendaylight.controller.sal.core.Property}
2108 public Property createProperty(String propName, String propValue) {
2109 if (propName == null) {
2110 log.debug("propName is null");
2113 if (propValue == null) {
2114 log.debug("propValue is null");
2119 if (propName.equalsIgnoreCase(Description.propertyName)) {
2120 return new Description(propValue);
2121 } else if (propName.equalsIgnoreCase(Tier.TierPropName)) {
2122 int tier = Integer.parseInt(propValue);
2123 return new Tier(tier);
2124 } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) {
2125 long bw = Long.parseLong(propValue);
2126 return new Bandwidth(bw);
2127 } else if (propName.equalsIgnoreCase(ForwardingMode.name)) {
2128 int mode = Integer.parseInt(propValue);
2129 return new ForwardingMode(mode);
2130 } else if (propName.equalsIgnoreCase(MacAddress.name)){
2131 return new MacAddress(propValue);
2134 log.debug("Not able to create {} property", propName);
2136 } catch (Exception e) {
2137 log.debug("createProperty caught exception {}", e.getMessage());
2144 @SuppressWarnings("deprecation")
2146 public String getNodeDescription(Node node) {
2147 // Check first if user configured a name
2148 SwitchConfig config = getSwitchConfig(node.toString());
2149 if (config != null) {
2150 String configuredDesc = config.getNodeDescription();
2151 if (configuredDesc != null && !configuredDesc.isEmpty()) {
2152 return configuredDesc;
2156 // No name configured by user, get the node advertised name
2157 Description desc = (Description) getNodeProp(node,
2158 Description.propertyName);
2159 return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? ""
2164 public Set<Switch> getConfiguredNotConnectedSwitches() {
2165 Set<Switch> configuredNotConnectedSwitches = new HashSet<Switch>();
2166 if (this.inventoryService == null) {
2167 log.trace("inventory service not avaiable");
2168 return configuredNotConnectedSwitches;
2171 Set<Node> configuredNotConnectedNodes = this.inventoryService.getConfiguredNotConnectedNodes();
2172 if (configuredNotConnectedNodes != null) {
2173 for (Node node : configuredNotConnectedNodes) {
2174 Switch sw = getSwitchByNode(node);
2176 configuredNotConnectedSwitches.add(sw);
2180 return configuredNotConnectedSwitches;