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.size() == 0 && subnet == 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 Subnet newSubnet = new Subnet(conf);
432 Set<InetAddress> IPs = subnets.keySet();
434 return new Status(StatusCode.SUCCESS);
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().equals(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.equals(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;
695 Set<InetAddress> indices = subnets.keySet();
696 for (InetAddress i : indices) {
697 sub = subnets.get(i);
698 if (sub.isSubnetOf(networkAddress)) {
706 public Object readObject(ObjectInputStream ois)
707 throws FileNotFoundException, IOException, ClassNotFoundException {
708 // Perform the class deserialization locally, from inside the package
709 // where the class is defined
710 return ois.readObject();
713 @SuppressWarnings("unchecked")
714 private void loadSubnetConfiguration() {
715 ObjectReader objReader = new ObjectReader();
716 ConcurrentMap<String, SubnetConfig> confList = (ConcurrentMap<String, SubnetConfig>) objReader
717 .read(this, subnetFileName);
719 if (confList == null) {
723 for (SubnetConfig conf : confList.values()) {
728 @SuppressWarnings("unchecked")
729 private void loadSpanConfiguration() {
730 ObjectReader objReader = new ObjectReader();
731 ConcurrentMap<Integer, SpanConfig> confList = (ConcurrentMap<Integer, SpanConfig>) objReader
732 .read(this, spanFileName);
734 if (confList == null) {
738 for (SpanConfig conf : confList.values()) {
743 @SuppressWarnings("unchecked")
744 private void loadSwitchConfiguration() {
745 ObjectReader objReader = new ObjectReader();
746 ConcurrentMap<String, SwitchConfig> confList = (ConcurrentMap<String, SwitchConfig>) objReader
747 .read(this, switchConfigFileName);
749 if (confList == null) {
753 for (SwitchConfig conf : confList.values()) {
754 updateNodeConfig(conf);
758 @SuppressWarnings("deprecation")
760 public void updateSwitchConfig(SwitchConfig cfgObject) {
761 // update default container only
762 if (!isDefaultContainer) {
766 SwitchConfig sc = nodeConfigList.get(cfgObject.getNodeId());
768 if (nodeConfigList.putIfAbsent(cfgObject.getNodeId(), cfgObject) != null) {
772 if (!nodeConfigList.replace(cfgObject.getNodeId(), sc, cfgObject)) {
777 boolean modeChange = false;
779 if ((sc == null) || !cfgObject.getMode().equals(sc.getMode())) {
783 String nodeId = cfgObject.getNodeId();
784 Node node = Node.fromString(nodeId);
785 Map<String, Property> propMapCurr = nodeProps.get(node);
786 if (propMapCurr == null) {
789 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
790 Property desc = new Description(cfgObject.getNodeDescription());
791 propMap.put(desc.getName(), desc);
792 Property tier = new Tier(Integer.parseInt(cfgObject.getTier()));
793 propMap.put(tier.getName(), tier);
795 if (!nodeProps.replace(node, propMapCurr, propMap)) {
796 // TODO rollback using Transactionality
800 log.info("Set Node {}'s Mode to {}", nodeId, cfgObject.getMode());
803 notifyModeChange(node, cfgObject.isProactive());
808 public Status updateNodeConfig(SwitchConfig switchConfig) {
809 Status status = switchConfig.validate();
810 if (!status.isSuccess()) {
814 Map<String, Property> updateProperties = switchConfig.getNodeProperties();
815 ForwardingMode mode = (ForwardingMode) updateProperties.get(ForwardingMode.name);
817 if (isDefaultContainer) {
818 if (!mode.isValid()) {
819 return new Status(StatusCode.BADREQUEST, "Invalid Forwarding Mode Value");
822 return new Status(StatusCode.NOTACCEPTABLE,
823 "Forwarding Mode modification is allowed only in default container");
827 Description description = (Description) switchConfig.getProperty(Description.propertyName);
828 String nodeId = switchConfig.getNodeId();
829 Node node = Node.fromString(nodeId);
830 NodeDescription nodeDesc = (this.statisticsManager == null) ? null : this.statisticsManager
831 .getNodeDescription(node);
832 String advertisedDesc = (nodeDesc == null) ? "" : nodeDesc.getDescription();
833 if (description != null && description.getValue() != null) {
834 if (description.getValue().isEmpty() || description.getValue().equals(advertisedDesc)) {
835 updateProperties.remove(Description.propertyName);
836 switchConfig = new SwitchConfig(nodeId, updateProperties);
838 // check if description is configured or was published by any other node
839 for (Map.Entry<Node, Map<String, Property>> entry : nodeProps.entrySet()) {
840 Node n = entry.getKey();
841 Description desc = (Description) getNodeProp(n, Description.propertyName);
842 NodeDescription nDesc = (this.statisticsManager == null) ? null : this.statisticsManager
843 .getNodeDescription(n);
844 String advDesc = (nDesc == null) ? "" : nDesc.getDescription();
845 if ((description.equals(desc) || description.getValue().equals(advDesc)) && !node.equals(n)) {
846 return new Status(StatusCode.CONFLICT, "Node name already in use");
852 boolean modeChange = false;
853 SwitchConfig sc = nodeConfigList.get(nodeId);
854 Map<String, Property> prevNodeProperties = new HashMap<String, Property>();
856 if ((mode != null) && mode.isProactive()) {
859 if (!updateProperties.isEmpty()) {
860 if (nodeConfigList.putIfAbsent(nodeId, switchConfig) != null) {
861 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
865 prevNodeProperties = new HashMap<String, Property>(sc.getNodeProperties());
866 ForwardingMode prevMode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
868 if ((prevMode != null) && (prevMode.isProactive())) {
872 if (((prevMode != null) && (prevMode.getValue() != mode.getValue()))
873 || (prevMode == null && mode.isProactive())) {
877 if (updateProperties.isEmpty()) {
878 nodeConfigList.remove(nodeId);
880 if (!nodeConfigList.replace(nodeId, sc, switchConfig)) {
881 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
885 Map<String, Property> propMapCurr = nodeProps.get(node);
886 if (propMapCurr == null) {
887 return new Status(StatusCode.SUCCESS);
889 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
890 for (Map.Entry<String, Property> entry : prevNodeProperties.entrySet()) {
891 String prop = entry.getKey();
892 if (!updateProperties.containsKey(prop)) {
893 if (prop.equals(Description.propertyName)) {
894 if (!advertisedDesc.isEmpty()) {
895 Property desc = new Description(advertisedDesc);
896 propMap.put(Description.propertyName, desc);
899 } else if (prop.equals(ForwardingMode.name)) {
900 Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING);
901 propMap.put(ForwardingMode.name, defaultMode);
904 propMap.remove(prop);
907 propMap.putAll(updateProperties);
908 if (!nodeProps.replace(node, propMapCurr, propMap)) {
909 // TODO rollback using Transactionality
910 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
913 notifyModeChange(node, (mode == null) ? false : mode.isProactive());
915 return new Status(StatusCode.SUCCESS);
919 public Status removeNodeConfig(String nodeId) {
920 if ((nodeId == null) || (nodeId.isEmpty())) {
921 return new Status(StatusCode.BADREQUEST, "nodeId cannot be empty.");
923 Map<String, Property> nodeProperties = getSwitchConfig(nodeId).getNodeProperties();
924 Node node = Node.fromString(nodeId);
925 Map<String, Property> propMapCurr = nodeProps.get(node);
926 if ((propMapCurr != null) && (nodeProperties != null) && (!nodeProperties.isEmpty())) {
927 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
928 for (Map.Entry<String, Property> entry : nodeProperties.entrySet()) {
929 String prop = entry.getKey();
930 if (prop.equals(Description.propertyName)) {
931 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
932 if (nodeProp.get(node) != null) {
933 propMap.put(Description.propertyName, nodeProp.get(node).get(Description.propertyName));
937 propMap.remove(prop);
939 if (!nodeProps.replace(node, propMapCurr, propMap)) {
940 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration.");
943 if (nodeConfigList != null) {
944 nodeConfigList.remove(nodeId);
946 return new Status(StatusCode.SUCCESS);
950 public Status saveSwitchConfig() {
951 return saveSwitchConfigInternal();
954 public Status saveSwitchConfigInternal() {
955 Status retS = null, retP = null;
956 ObjectWriter objWriter = new ObjectWriter();
958 retS = objWriter.write(new ConcurrentHashMap<String, SubnetConfig>(
959 subnetsConfigList), subnetFileName);
960 retP = objWriter.write(new ConcurrentHashMap<SpanConfig, SpanConfig>(
961 spanConfigList), spanFileName);
962 retS = objWriter.write(new ConcurrentHashMap<String, SwitchConfig>(
963 nodeConfigList), switchConfigFileName);
964 if (retS.equals(retP)) {
965 if (retS.isSuccess()) {
968 return new Status(StatusCode.INTERNALERROR, "Save failed");
971 return new Status(StatusCode.INTERNALERROR, "Partial save failure");
976 public List<SpanConfig> getSpanConfigList() {
977 return new ArrayList<SpanConfig>(spanConfigList.values());
981 public Status addSpanConfig(SpanConfig conf) {
982 // Valid config check
983 if (!conf.isValidConfig()) {
984 String msg = "Invalid Span configuration";
986 return new Status(StatusCode.BADREQUEST, msg);
990 if (spanConfigList.containsKey(conf)) {
991 return new Status(StatusCode.CONFLICT, "Same span config exists");
994 // Update configuration
995 if (spanConfigList.putIfAbsent(conf, conf) == null) {
996 // Update database and notify clients
997 addSpanPorts(conf.getNode(), conf.getPortArrayList());
1000 return new Status(StatusCode.SUCCESS);
1004 public Status removeSpanConfig(SpanConfig conf) {
1005 removeSpanPorts(conf.getNode(), conf.getPortArrayList());
1007 // Update configuration
1008 spanConfigList.remove(conf);
1010 return new Status(StatusCode.SUCCESS);
1014 public List<NodeConnector> getSpanPorts(Node node) {
1015 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
1017 for (NodeConnector nodeConnector : spanNodeConnectors) {
1018 if (nodeConnector.getNode().equals(node)) {
1019 ncList.add(nodeConnector);
1025 private void addNode(Node node, Set<Property> props) {
1026 log.trace("{} added, props: {}", node, props);
1027 if (nodeProps == null) {
1031 Map<String, Property> propMapCurr = nodeProps.get(node);
1032 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1033 : new HashMap<String, Property>(propMapCurr);
1035 // copy node properties from plugin
1036 if (props != null) {
1037 for (Property prop : props) {
1038 propMap.put(prop.getName(), prop);
1042 boolean proactiveForwarding = false;
1043 // copy node properties from config
1044 if (nodeConfigList != null) {
1045 String nodeId = node.toString();
1046 SwitchConfig conf = nodeConfigList.get(nodeId);
1047 if (conf != null && (conf.getNodeProperties() != null)) {
1048 Map<String, Property> nodeProperties = conf.getNodeProperties();
1049 propMap.putAll(nodeProperties);
1050 if (nodeProperties.get(ForwardingMode.name) != null) {
1051 ForwardingMode mode = (ForwardingMode) nodeProperties.get(ForwardingMode.name);
1052 proactiveForwarding = mode.isProactive();
1057 if (!propMap.containsKey(ForwardingMode.name)) {
1058 Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING);
1059 propMap.put(ForwardingMode.name, defaultMode);
1061 boolean result = false;
1062 if (propMapCurr == null) {
1063 if (nodeProps.putIfAbsent(node, propMap) == null) {
1067 result = nodeProps.replace(node, propMapCurr, propMap);
1070 log.debug("Cluster conflict: Conflict while adding the node properties. Node: {} Properties: {}",
1071 node.getID(), props);
1072 addNodeProps(node, propMap);
1075 // check if span ports are configed
1078 // notify node listeners
1079 notifyNode(node, UpdateType.ADDED, propMap);
1081 // notify proactive mode forwarding
1082 if (proactiveForwarding) {
1083 notifyModeChange(node, true);
1087 private void removeNode(Node node) {
1088 log.trace("{} removed", node);
1089 if (nodeProps == null) {
1092 nodeProps.remove(node);
1093 nodeConnectorNames.remove(node);
1094 Set<NodeConnector> removeNodeConnectorSet = new HashSet<NodeConnector>();
1095 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1096 NodeConnector nodeConnector = entry.getKey();
1097 if (nodeConnector.getNode().equals(node)) {
1098 removeNodeConnectorSet.add(nodeConnector);
1101 for (NodeConnector nc : removeNodeConnectorSet) {
1102 nodeConnectorProps.remove(nc);
1105 // check if span ports need to be cleaned up
1106 removeSpanPorts(node);
1108 /* notify node listeners */
1109 notifyNode(node, UpdateType.REMOVED, null);
1112 private void updateNode(Node node, Set<Property> props) {
1113 log.trace("{} updated, props: {}", node, props);
1114 if (nodeProps == null || !nodeProps.containsKey(node) ||
1115 props == null || props.isEmpty()) {
1119 Map<String, Property> propMapCurr = nodeProps.get(node);
1120 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1121 : new HashMap<String, Property>(propMapCurr);
1123 // copy node properties from plugin
1124 String nodeId = node.toString();
1125 for (Property prop : props) {
1126 if (nodeConfigList != null) {
1127 SwitchConfig conf = nodeConfigList.get(nodeId);
1128 if (conf != null && (conf.getNodeProperties() != null)
1129 && conf.getNodeProperties().containsKey(prop.getName())) {
1133 propMap.put(prop.getName(), prop);
1136 if (propMapCurr == null) {
1137 if (nodeProps.putIfAbsent(node, propMap) != null) {
1138 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1139 node.getID(), props);
1140 addNodeProps(node, propMap);
1143 if (!nodeProps.replace(node, propMapCurr, propMap)) {
1144 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1145 node.getID(), props);
1146 addNodeProps(node, propMap);
1150 /* notify node listeners */
1151 notifyNode(node, UpdateType.CHANGED, propMap);
1155 public void updateNode(Node node, UpdateType type, Set<Property> props) {
1156 log.debug("updateNode: {} type {} props {} for container {}",
1157 new Object[] { node, type, props, containerName });
1160 addNode(node, props);
1163 updateNode(node, props);
1174 public void updateNodeConnector(NodeConnector nodeConnector,
1175 UpdateType type, Set<Property> props) {
1176 Map<String, Property> propMap = new HashMap<String, Property>();
1177 boolean update = true;
1179 log.debug("updateNodeConnector: {} type {} props {} for container {}",
1180 new Object[] { nodeConnector, type, props, containerName });
1182 if (nodeConnectorProps == null) {
1188 if (props != null) {
1189 for (Property prop : props) {
1190 addNodeConnectorProp(nodeConnector, prop);
1191 propMap.put(prop.getName(), prop);
1194 addNodeConnectorProp(nodeConnector, null);
1197 addSpanPort(nodeConnector);
1200 if (!nodeConnectorProps.containsKey(nodeConnector) || (props == null)) {
1203 for (Property prop : props) {
1204 addNodeConnectorProp(nodeConnector, prop);
1205 propMap.put(prop.getName(), prop);
1210 if (!nodeConnectorProps.containsKey(nodeConnector)) {
1213 removeNodeConnectorAllProps(nodeConnector);
1215 // clean up span config
1216 removeSpanPort(nodeConnector);
1224 notifyNodeConnector(nodeConnector, type, propMap);
1229 public Set<Node> getNodes() {
1230 return (nodeProps != null) ? new HashSet<Node>(nodeProps.keySet()) : new HashSet<Node>();
1234 public Map<String, Property> getControllerProperties() {
1235 return new HashMap<String, Property>(this.controllerProps);
1239 public Property getControllerProperty(String propertyName) {
1240 if (propertyName != null) {
1241 HashMap<String, Property> propertyMap = new HashMap<String, Property>(this.controllerProps);
1242 return propertyMap.get(propertyName);
1248 public Status setControllerProperty(Property property) {
1249 if (property != null) {
1250 this.controllerProps.put(property.getName(), property);
1251 return new Status(StatusCode.SUCCESS);
1253 return new Status(StatusCode.BADREQUEST, "Invalid property provided when setting property");
1257 public Status removeControllerProperty(String propertyName) {
1258 if (propertyName != null) {
1259 if (this.controllerProps.containsKey(propertyName)) {
1260 this.controllerProps.remove(propertyName);
1261 if (!this.controllerProps.containsKey(propertyName)) {
1262 return new Status(StatusCode.SUCCESS);
1265 String msg = "Unable to remove property " + propertyName + " from Controller";
1266 return new Status(StatusCode.BADREQUEST, msg);
1268 String msg = "Invalid property provided when removing property from Controller";
1269 return new Status(StatusCode.BADREQUEST, msg);
1273 * Returns a copy of a list of properties for a given node
1278 * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps
1279 * (org.opendaylight.controller.sal.core.Node)
1282 public Map<String, Property> getNodeProps(Node node) {
1283 Map<String, Property> rv = new HashMap<String, Property>();
1284 if (this.nodeProps != null) {
1285 rv = this.nodeProps.get(node);
1287 /* make a copy of it */
1288 rv = new HashMap<String, Property>(rv);
1295 public Property getNodeProp(Node node, String propName) {
1296 Map<String, Property> propMap = getNodeProps(node);
1297 return (propMap != null) ? propMap.get(propName) : null;
1301 public void setNodeProp(Node node, Property prop) {
1303 for (int i = 0; i <= REPLACE_RETRY; i++) {
1304 /* Get a copy of the property map */
1305 Map<String, Property> propMapCurr = getNodeProps(node);
1306 if (propMapCurr == null) {
1310 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1311 propMap.put(prop.getName(), prop);
1313 if (nodeProps.replace(node, propMapCurr, propMap)) {
1316 if (!propMapCurr.get(prop.getName()).equals(nodeProps.get(node).get(prop.getName()))) {
1317 log.debug("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1321 log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1325 public Status removeNodeProp(Node node, String propName) {
1326 for (int i = 0; i <= REPLACE_RETRY; i++) {
1327 Map<String, Property> propMapCurr = getNodeProps(node);
1328 if (propMapCurr != null) {
1329 if (!propMapCurr.containsKey(propName)) {
1330 return new Status(StatusCode.SUCCESS);
1332 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1333 propMap.remove(propName);
1334 if (nodeProps.replace(node, propMapCurr, propMap)) {
1335 return new Status(StatusCode.SUCCESS);
1337 if (!propMapCurr.get(propName).equals(nodeProps.get(node).get(propName))) {
1338 String msg = "Cluster conflict: Unable to remove property " + propName + " for node "
1340 return new Status(StatusCode.CONFLICT, msg);
1344 return new Status(StatusCode.SUCCESS);
1347 String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID();
1348 return new Status(StatusCode.CONFLICT, msg);
1352 public Status removeNodeAllProps(Node node) {
1353 this.nodeProps.remove(node);
1354 return new Status(StatusCode.SUCCESS);
1358 public Set<NodeConnector> getUpNodeConnectors(Node node) {
1359 if (nodeConnectorProps == null) {
1363 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1364 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1365 NodeConnector nodeConnector = entry.getKey();
1366 if (!nodeConnector.getNode().equals(node)) {
1369 if (isNodeConnectorEnabled(nodeConnector)) {
1370 nodeConnectorSet.add(nodeConnector);
1374 return nodeConnectorSet;
1378 public Set<NodeConnector> getNodeConnectors(Node node) {
1379 if (nodeConnectorProps == null) {
1383 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1384 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1385 NodeConnector nodeConnector = entry.getKey();
1386 if (!nodeConnector.getNode().equals(node)) {
1389 nodeConnectorSet.add(nodeConnector);
1392 return nodeConnectorSet;
1396 public Set<NodeConnector> getPhysicalNodeConnectors(Node node) {
1397 if (nodeConnectorProps == null) {
1401 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1402 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1403 NodeConnector nodeConnector = entry.getKey();
1404 if (!nodeConnector.getNode().equals(node)
1405 || isSpecial(nodeConnector)) {
1408 nodeConnectorSet.add(nodeConnector);
1411 return nodeConnectorSet;
1415 public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) {
1416 Map<String, Property> rv = new HashMap<String, Property>();
1417 if (this.nodeConnectorProps != null) {
1418 rv = this.nodeConnectorProps.get(nodeConnector);
1420 rv = new HashMap<String, Property>(rv);
1427 public Property getNodeConnectorProp(NodeConnector nodeConnector,
1429 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1430 return (propMap != null) ? propMap.get(propName) : null;
1433 private byte[] getHardwareMAC() {
1434 Enumeration<NetworkInterface> nis;
1435 byte[] macAddress = null;
1438 nis = NetworkInterface.getNetworkInterfaces();
1439 } catch (SocketException e) {
1440 log.error("Failed to acquire controller MAC: ", e);
1444 while (nis.hasMoreElements()) {
1445 NetworkInterface ni = nis.nextElement();
1447 macAddress = ni.getHardwareAddress();
1448 } catch (SocketException e) {
1449 log.error("Failed to acquire controller MAC: ", e);
1451 if (macAddress != null) {
1455 if (macAddress == null) {
1456 log.warn("Failed to acquire controller MAC: No physical interface found");
1457 // This happens when running controller on windows VM, for example
1458 // Try parsing the OS command output
1464 public byte[] getControllerMAC() {
1465 MacAddress macProperty = (MacAddress)controllerProps.get(MacAddress.name);
1466 return (macProperty == null) ? null : macProperty.getMacAddress();
1470 public NodeConnector getNodeConnector(Node node, String nodeConnectorName) {
1471 if (nodeConnectorNames == null) {
1475 Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1480 return map.get(nodeConnectorName);
1484 * Adds a node connector and its property if any
1486 * @param nodeConnector
1487 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1489 * name of {@link org.opendaylight.controller.sal.core.Property}
1490 * @return success or failed reason
1493 public Status addNodeConnectorProp(NodeConnector nodeConnector,
1495 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1496 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1497 : new HashMap<String, Property>(propMapCurr);
1499 String msg = "Cluster conflict: Unable to add NodeConnector Property.";
1500 // Just add the nodeConnector if prop is not available (in a non-default
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);
1512 return new Status(StatusCode.SUCCESS);
1515 propMap.put(prop.getName(), prop);
1516 if (propMapCurr == null) {
1517 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1518 return new Status(StatusCode.CONFLICT, msg);
1521 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1522 return new Status(StatusCode.CONFLICT, msg);
1526 if (prop.getName().equals(Name.NamePropName)) {
1527 if (nodeConnectorNames != null) {
1528 Node node = nodeConnector.getNode();
1529 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1530 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1531 if (mapCurr != null) {
1532 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1533 String s = entry.getKey();
1535 map.put(s, new NodeConnector(entry.getValue()));
1536 } catch (ConstructionException e) {
1537 log.error("An error occured",e);
1542 map.put(((Name) prop).getValue(), nodeConnector);
1543 if (mapCurr == null) {
1544 if (nodeConnectorNames.putIfAbsent(node, map) != null) {
1545 // TODO: recovery using Transactionality
1546 return new Status(StatusCode.CONFLICT, msg);
1549 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1550 // TODO: recovery using Transactionality
1551 return new Status(StatusCode.CONFLICT, msg);
1557 return new Status(StatusCode.SUCCESS);
1561 * Removes one property of a node connector
1563 * @param nodeConnector
1564 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1566 * name of {@link org.opendaylight.controller.sal.core.Property}
1567 * @return success or failed reason
1570 public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) {
1571 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1573 if (propMapCurr == null) {
1574 /* Nothing to remove */
1575 return new Status(StatusCode.SUCCESS);
1578 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1579 propMap.remove(propName);
1580 boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap);
1581 String msg = "Cluster conflict: Unable to remove NodeConnector property.";
1583 return new Status(StatusCode.CONFLICT, msg);
1586 if (propName.equals(Name.NamePropName)) {
1587 if (nodeConnectorNames != null) {
1588 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1590 Node node = nodeConnector.getNode();
1591 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1592 if (mapCurr != null) {
1593 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1594 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1595 String s = entry.getKey();
1597 map.put(s, new NodeConnector(entry.getValue()));
1598 } catch (ConstructionException e) {
1599 log.error("An error occured",e);
1602 map.remove(name.getValue());
1603 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1604 // TODO: recovery using Transactionality
1605 return new Status(StatusCode.CONFLICT, msg);
1612 return new Status(StatusCode.SUCCESS);
1616 * Removes all the properties of a node connector
1618 * @param nodeConnector
1619 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1620 * @return success or failed reason
1623 public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) {
1624 if (nodeConnectorNames != null) {
1625 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1627 Node node = nodeConnector.getNode();
1628 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1629 if (mapCurr != null) {
1630 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1631 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1632 String s = entry.getKey();
1634 map.put(s, new NodeConnector(entry.getValue()));
1635 } catch (ConstructionException e) {
1636 log.error("An error occured",e);
1639 map.remove(name.getValue());
1640 if (map.isEmpty()) {
1641 nodeConnectorNames.remove(node);
1643 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1644 log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.",
1645 nodeConnector.getID());
1652 nodeConnectorProps.remove(nodeConnector);
1654 return new Status(StatusCode.SUCCESS);
1658 * Function called by the dependency manager when all the required
1659 * dependencies are satisfied
1662 void init(Component c) {
1663 Dictionary<?, ?> props = c.getServiceProperties();
1664 if (props != null) {
1665 this.containerName = (String) props.get("containerName");
1666 log.trace("Running containerName: {}", this.containerName);
1668 // In the Global instance case the containerName is empty
1669 this.containerName = "";
1671 isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT
1678 * Function called by the dependency manager when at least one dependency
1679 * become unsatisfied or when the component is shutting down because for
1680 * example bundle is being stopped.
1688 * Function called by dependency manager after "init ()" is called and after
1689 * the services provided by the class are registered in the service registry
1694 registerWithOSGIConsole();
1698 * Function called after registered the service in OSGi service registry.
1701 // solicit for existing inventories
1706 * Function called by the dependency manager before the services exported by
1707 * the component are unregistered, this will be followed by a "destroy ()"
1714 public void setInventoryService(IInventoryService service) {
1715 log.trace("Got inventory service set request {}", service);
1716 this.inventoryService = service;
1718 // solicit for existing inventories
1722 public void unsetInventoryService(IInventoryService service) {
1723 log.trace("Got a service UNset request");
1724 this.inventoryService = null;
1726 // clear existing inventories
1730 public void setStatisticsManager(IStatisticsManager statisticsManager) {
1731 log.trace("Got statistics manager set request {}", statisticsManager);
1732 this.statisticsManager = statisticsManager;
1735 public void unsetStatisticsManager(IStatisticsManager statisticsManager) {
1736 log.trace("Got statistics manager UNset request");
1737 this.statisticsManager = null;
1740 public void setSwitchManagerAware(ISwitchManagerAware service) {
1741 log.trace("Got inventory service set request {}", service);
1742 if (this.switchManagerAware != null) {
1743 this.switchManagerAware.add(service);
1746 // bulk update for newly joined
1747 switchManagerAwareNotify(service);
1750 public void unsetSwitchManagerAware(ISwitchManagerAware service) {
1751 log.trace("Got a service UNset request");
1752 if (this.switchManagerAware != null) {
1753 this.switchManagerAware.remove(service);
1757 public void setInventoryListener(IInventoryListener service) {
1758 log.trace("Got inventory listener set request {}", service);
1759 if (this.inventoryListeners != null) {
1760 this.inventoryListeners.add(service);
1763 // bulk update for newly joined
1764 bulkUpdateService(service);
1767 public void unsetInventoryListener(IInventoryListener service) {
1768 log.trace("Got a service UNset request");
1769 if (this.inventoryListeners != null) {
1770 this.inventoryListeners.remove(service);
1774 public void setSpanAware(ISpanAware service) {
1775 log.trace("Got SpanAware set request {}", service);
1776 if (this.spanAware != null) {
1777 this.spanAware.add(service);
1780 // bulk update for newly joined
1781 spanAwareNotify(service);
1784 public void unsetSpanAware(ISpanAware service) {
1785 log.trace("Got a service UNset request");
1786 if (this.spanAware != null) {
1787 this.spanAware.remove(service);
1791 void setClusterContainerService(IClusterContainerServices s) {
1792 log.trace("Cluster Service set");
1793 this.clusterContainerService = s;
1796 void unsetClusterContainerService(IClusterContainerServices s) {
1797 if (this.clusterContainerService == s) {
1798 log.trace("Cluster Service removed!");
1799 this.clusterContainerService = null;
1803 private void getInventories() {
1804 if (inventoryService == null) {
1805 log.trace("inventory service not avaiable");
1809 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
1810 for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) {
1811 Node node = entry.getKey();
1812 log.debug("getInventories: {} added for container {}", new Object[] { node, containerName });
1813 Map<String, Property> propMap = entry.getValue();
1814 Set<Property> props = new HashSet<Property>();
1815 for (Property property : propMap.values()) {
1816 props.add(property);
1818 addNode(node, props);
1821 Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps();
1822 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) {
1823 Map<String, Property> propMap = entry.getValue();
1824 for (Property property : propMap.values()) {
1825 addNodeConnectorProp(entry.getKey(), property);
1830 private void clearInventories() {
1832 nodeConnectorProps.clear();
1833 nodeConnectorNames.clear();
1834 spanNodeConnectors.clear();
1837 private void notifyNode(Node node, UpdateType type,
1838 Map<String, Property> propMap) {
1839 synchronized (inventoryListeners) {
1840 for (IInventoryListener service : inventoryListeners) {
1841 service.notifyNode(node, type, propMap);
1846 private void notifyNodeConnector(NodeConnector nodeConnector,
1847 UpdateType type, Map<String, Property> propMap) {
1848 synchronized (inventoryListeners) {
1849 for (IInventoryListener service : inventoryListeners) {
1850 service.notifyNodeConnector(nodeConnector, type, propMap);
1856 * For those joined late, bring them up-to-date.
1858 private void switchManagerAwareNotify(ISwitchManagerAware service) {
1859 for (Subnet sub : subnets.values()) {
1860 service.subnetNotify(sub, true);
1863 for (Node node : getNodes()) {
1864 SwitchConfig sc = getSwitchConfig(node.toString());
1865 if ((sc != null) && isDefaultContainer) {
1866 ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
1867 service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive());
1872 private void bulkUpdateService(IInventoryListener service) {
1873 Map<String, Property> propMap;
1874 UpdateType type = UpdateType.ADDED;
1876 for (Node node : getNodes()) {
1877 propMap = nodeProps.get(node);
1878 service.notifyNode(node, type, propMap);
1881 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1882 NodeConnector nodeConnector = entry.getKey();
1883 propMap = nodeConnectorProps.get(nodeConnector);
1884 service.notifyNodeConnector(nodeConnector, type, propMap);
1888 private void spanAwareNotify(ISpanAware service) {
1889 for (Node node : getNodes()) {
1890 for (SpanConfig conf : getSpanConfigList(node)) {
1891 service.spanUpdate(node, conf.getPortArrayList(), true);
1896 private void registerWithOSGIConsole() {
1897 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
1898 .getBundleContext();
1899 bundleContext.registerService(CommandProvider.class.getName(), this,
1904 public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) {
1905 if (nodeConnector == null) {
1909 Config config = (Config) getNodeConnectorProp(nodeConnector,
1910 Config.ConfigPropName);
1911 State state = (State) getNodeConnectorProp(nodeConnector,
1912 State.StatePropName);
1913 return ((config != null) && (config.getValue() == Config.ADMIN_UP)
1914 && (state != null) && (state.getValue() == State.EDGE_UP));
1918 public boolean doesNodeConnectorExist(NodeConnector nc) {
1919 return (nc != null && nodeConnectorProps != null
1920 && nodeConnectorProps.containsKey(nc));
1924 public String getHelp() {
1925 StringBuffer help = new StringBuffer();
1926 help.append("---Switch Manager---\n");
1927 help.append("\t pencs <node id> - Print enabled node connectors for a given node\n");
1928 help.append("\t pdm <node id> - Print switch ports in device map\n");
1929 return help.toString();
1932 public void _pencs(CommandInterpreter ci) {
1933 String st = ci.nextArgument();
1935 ci.println("Please enter node id");
1939 Node node = Node.fromString(st);
1941 ci.println("Please enter node id");
1945 Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node);
1946 if (nodeConnectorSet == null) {
1949 for (NodeConnector nodeConnector : nodeConnectorSet) {
1950 if (nodeConnector == null) {
1953 ci.println(nodeConnector);
1955 ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1958 public void _pdm(CommandInterpreter ci) {
1959 String st = ci.nextArgument();
1961 ci.println("Please enter node id");
1965 Node node = Node.fromString(st);
1967 ci.println("Please enter node id");
1971 Switch sw = getSwitchByNode(node);
1973 ci.println(" NodeConnector Name");
1975 Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors();
1976 String nodeConnectorName;
1977 if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
1978 for (NodeConnector nodeConnector : nodeConnectorSet) {
1979 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1980 nodeConnectorName = (propMap == null) ? null : ((Name) propMap
1981 .get(Name.NamePropName)).getValue();
1982 if (nodeConnectorName != null) {
1983 Node nd = nodeConnector.getNode();
1984 if (!nd.equals(node)) {
1985 log.debug("node not match {} {}", nd, node);
1987 Map<String, NodeConnector> map = nodeConnectorNames
1990 NodeConnector nc = map.get(nodeConnectorName);
1992 log.debug("no nodeConnector named {}",
1994 } else if (!nc.equals(nodeConnector)) {
1995 log.debug("nodeConnector not match {} {}", nc,
2001 ci.println(nodeConnector
2003 + ((nodeConnectorName == null) ? "" : nodeConnectorName)
2004 + "(" + nodeConnector.getID() + ")");
2006 ci.println("Total number of NodeConnectors: "
2007 + nodeConnectorSet.size());
2012 public byte[] getNodeMAC(Node node) {
2013 MacAddress mac = (MacAddress) this.getNodeProp(node,
2015 return (mac != null) ? mac.getMacAddress() : null;
2019 public boolean isSpecial(NodeConnector p) {
2020 if (p.getType().equals(NodeConnectorIDType.CONTROLLER)
2021 || p.getType().equals(NodeConnectorIDType.ALL)
2022 || p.getType().equals(NodeConnectorIDType.SWSTACK)
2023 || p.getType().equals(NodeConnectorIDType.HWPATH)) {
2030 * Add span configuration to local cache and notify clients
2032 private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2033 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2035 for (NodeConnector nodeConnector : nodeConnectors) {
2036 if (!spanNodeConnectors.contains(nodeConnector)) {
2037 ncLists.add(nodeConnector);
2041 if (ncLists.size() > 0) {
2042 spanNodeConnectors.addAll(ncLists);
2043 notifySpanPortChange(node, ncLists, true);
2047 private void addSpanPorts(Node node) {
2048 for (SpanConfig conf : getSpanConfigList(node)) {
2049 addSpanPorts(node, conf.getPortArrayList());
2053 private void addSpanPort(NodeConnector nodeConnector) {
2054 // only add if span is configured on this nodeConnector
2055 for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) {
2056 if (conf.getPortArrayList().contains(nodeConnector)) {
2057 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2058 ncLists.add(nodeConnector);
2059 addSpanPorts(nodeConnector.getNode(), ncLists);
2066 * Remove span configuration to local cache and notify clients
2068 private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2069 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2071 for (NodeConnector nodeConnector : nodeConnectors) {
2072 if (spanNodeConnectors.contains(nodeConnector)) {
2073 ncLists.add(nodeConnector);
2077 if (ncLists.size() > 0) {
2078 spanNodeConnectors.removeAll(ncLists);
2079 notifySpanPortChange(node, ncLists, false);
2083 private void removeSpanPorts(Node node) {
2084 for (SpanConfig conf : getSpanConfigList(node)) {
2085 addSpanPorts(node, conf.getPortArrayList());
2089 private void removeSpanPort(NodeConnector nodeConnector) {
2090 if (spanNodeConnectors.contains(nodeConnector)) {
2091 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2092 ncLists.add(nodeConnector);
2093 removeSpanPorts(nodeConnector.getNode(), ncLists);
2097 private void addNodeProps(Node node, Map<String, Property> propMap) {
2098 if (propMap == null) {
2099 propMap = new HashMap<String, Property>();
2101 nodeProps.put(node, propMap);
2105 public Status saveConfiguration() {
2106 return saveSwitchConfig();
2110 * Creates a Name/Tier/Bandwidth/MacAddress(controller property) Property
2111 * object based on given property name and value. Other property types are
2112 * not supported yet.
2115 * Name of the Property
2117 * Value of the Property
2118 * @return {@link org.opendaylight.controller.sal.core.Property}
2121 public Property createProperty(String propName, String propValue) {
2122 if (propName == null) {
2123 log.debug("propName is null");
2126 if (propValue == null) {
2127 log.debug("propValue is null");
2132 if (propName.equalsIgnoreCase(Description.propertyName)) {
2133 return new Description(propValue);
2134 } else if (propName.equalsIgnoreCase(Tier.TierPropName)) {
2135 int tier = Integer.parseInt(propValue);
2136 return new Tier(tier);
2137 } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) {
2138 long bw = Long.parseLong(propValue);
2139 return new Bandwidth(bw);
2140 } else if (propName.equalsIgnoreCase(ForwardingMode.name)) {
2141 int mode = Integer.parseInt(propValue);
2142 return new ForwardingMode(mode);
2143 } else if (propName.equalsIgnoreCase(MacAddress.name)){
2144 return new MacAddress(propValue);
2147 log.debug("Not able to create {} property", propName);
2149 } catch (Exception e) {
2150 log.debug("createProperty caught exception {}", e.getMessage());
2157 @SuppressWarnings("deprecation")
2159 public String getNodeDescription(Node node) {
2160 // Check first if user configured a name
2161 SwitchConfig config = getSwitchConfig(node.toString());
2162 if (config != null) {
2163 String configuredDesc = config.getNodeDescription();
2164 if (configuredDesc != null && !configuredDesc.isEmpty()) {
2165 return configuredDesc;
2169 // No name configured by user, get the node advertised name
2170 Description desc = (Description) getNodeProp(node,
2171 Description.propertyName);
2172 return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? ""
2177 public Set<Switch> getConfiguredNotConnectedSwitches() {
2178 Set<Switch> configuredNotConnectedSwitches = new HashSet<Switch>();
2179 if (this.inventoryService == null) {
2180 log.trace("inventory service not avaiable");
2181 return configuredNotConnectedSwitches;
2184 Set<Node> configuredNotConnectedNodes = this.inventoryService.getConfiguredNotConnectedNodes();
2185 if (configuredNotConnectedNodes != null) {
2186 for (Node node : configuredNotConnectedNodes) {
2187 Switch sw = getSwitchByNode(node);
2189 configuredNotConnectedSwitches.add(sw);
2193 return configuredNotConnectedSwitches;