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 are the coordinator
180 if ((clusterContainerService != null) && (clusterContainerService.amICoordinator())) {
181 loadSubnetConfiguration();
182 loadSpanConfiguration();
183 loadSwitchConfiguration();
186 // Add controller MAC, if first node in the cluster
187 if (!controllerProps.containsKey(MacAddress.name)) {
188 byte controllerMac[] = getHardwareMAC();
189 if (controllerMac != null) {
190 Property existing = controllerProps.putIfAbsent(MacAddress.name, new MacAddress(controllerMac));
191 if (existing == null && log.isTraceEnabled()) {
192 log.trace("Container {}: Setting controller MAC address in the cluster: {}", container,
193 HexEncode.bytesToHexStringFormat(controllerMac));
199 public void shutDown() {
202 private void allocateCaches() {
203 if (this.clusterContainerService == null) {
204 this.nonClusterObjectCreate();
205 log.warn("un-initialized clusterContainerService, can't create cache");
210 clusterContainerService.createCache(
211 "switchmanager.subnetsConfigList",
212 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
213 clusterContainerService.createCache("switchmanager.spanConfigList",
214 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
215 clusterContainerService.createCache("switchmanager.nodeConfigList",
216 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
217 clusterContainerService.createCache("switchmanager.subnets",
218 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
219 clusterContainerService.createCache("switchmanager.nodeProps",
220 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
221 clusterContainerService.createCache(
222 "switchmanager.nodeConnectorProps",
223 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
224 clusterContainerService.createCache(
225 "switchmanager.nodeConnectorNames",
226 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
227 clusterContainerService.createCache(
228 "switchmanager.controllerProps",
229 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
230 } catch (CacheConfigException cce) {
231 log.error("\nCache configuration invalid - check cache mode");
232 } catch (CacheExistException ce) {
233 log.error("\nCache already exits - destroy and recreate if needed");
237 @SuppressWarnings({ "unchecked" })
238 private void retrieveCaches() {
239 if (this.clusterContainerService == null) {
240 log.warn("un-initialized clusterContainerService, can't create cache");
244 subnetsConfigList = (ConcurrentMap<String, SubnetConfig>) clusterContainerService
245 .getCache("switchmanager.subnetsConfigList");
246 if (subnetsConfigList == null) {
247 log.error("\nFailed to get cache for subnetsConfigList");
250 spanConfigList = (ConcurrentMap<SpanConfig, SpanConfig>) clusterContainerService
251 .getCache("switchmanager.spanConfigList");
252 if (spanConfigList == null) {
253 log.error("\nFailed to get cache for spanConfigList");
256 nodeConfigList = (ConcurrentMap<String, SwitchConfig>) clusterContainerService
257 .getCache("switchmanager.nodeConfigList");
258 if (nodeConfigList == null) {
259 log.error("\nFailed to get cache for nodeConfigList");
262 subnets = (ConcurrentMap<InetAddress, Subnet>) clusterContainerService
263 .getCache("switchmanager.subnets");
264 if (subnets == null) {
265 log.error("\nFailed to get cache for subnets");
268 nodeProps = (ConcurrentMap<Node, Map<String, Property>>) clusterContainerService
269 .getCache("switchmanager.nodeProps");
270 if (nodeProps == null) {
271 log.error("\nFailed to get cache for nodeProps");
274 nodeConnectorProps = (ConcurrentMap<NodeConnector, Map<String, Property>>) clusterContainerService
275 .getCache("switchmanager.nodeConnectorProps");
276 if (nodeConnectorProps == null) {
277 log.error("\nFailed to get cache for nodeConnectorProps");
280 nodeConnectorNames = (ConcurrentMap<Node, Map<String, NodeConnector>>) clusterContainerService
281 .getCache("switchmanager.nodeConnectorNames");
282 if (nodeConnectorNames == null) {
283 log.error("\nFailed to get cache for nodeConnectorNames");
286 controllerProps = (ConcurrentMap<String, Property>) clusterContainerService
287 .getCache("switchmanager.controllerProps");
288 if (controllerProps == null) {
289 log.error("\nFailed to get cache for controllerProps");
293 private void nonClusterObjectCreate() {
294 subnetsConfigList = new ConcurrentHashMap<String, SubnetConfig>();
295 spanConfigList = new ConcurrentHashMap<SpanConfig, SpanConfig>();
296 nodeConfigList = new ConcurrentHashMap<String, SwitchConfig>();
297 subnets = new ConcurrentHashMap<InetAddress, Subnet>();
298 nodeProps = new ConcurrentHashMap<Node, Map<String, Property>>();
299 nodeConnectorProps = new ConcurrentHashMap<NodeConnector, Map<String, Property>>();
300 nodeConnectorNames = new ConcurrentHashMap<Node, Map<String, NodeConnector>>();
301 controllerProps = new ConcurrentHashMap<String, Property>();
305 public List<SubnetConfig> getSubnetsConfigList() {
306 // if there are no subnets, return the default subnet
307 if(subnetsConfigList.size() == 0){
308 return Collections.singletonList(DEFAULT_SUBNETCONFIG);
310 return new ArrayList<SubnetConfig>(subnetsConfigList.values());
315 public SubnetConfig getSubnetConfig(String subnet) {
316 // if there are no subnets, return the default subnet
317 if(subnetsConfigList.isEmpty() && subnet.equalsIgnoreCase(DEFAULT_SUBNET_NAME)){
318 return DEFAULT_SUBNETCONFIG;
320 return subnetsConfigList.get(subnet);
324 private List<SpanConfig> getSpanConfigList(Node node) {
325 List<SpanConfig> confList = new ArrayList<SpanConfig>();
326 String nodeId = node.toString();
327 for (SpanConfig conf : spanConfigList.values()) {
328 if (conf.matchNode(nodeId)) {
335 public List<SwitchConfig> getNodeConfigList() {
336 return new ArrayList<SwitchConfig>(nodeConfigList.values());
340 public SwitchConfig getSwitchConfig(String switchId) {
341 return nodeConfigList.get(switchId);
344 public Switch getSwitchByNode(Node node) {
345 Switch sw = new Switch(node);
347 MacAddress mac = (MacAddress) this.getNodeProp(node,
350 sw.setDataLayerAddress(mac.getMacAddress());
352 Set<NodeConnector> ncSet = getPhysicalNodeConnectors(node);
353 sw.setNodeConnectors(ncSet);
355 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
356 for (NodeConnector nodeConnector : ncSet) {
357 if (spanNodeConnectors.contains(nodeConnector)) {
358 ncList.add(nodeConnector);
361 sw.addSpanPorts(ncList);
367 public List<Switch> getNetworkDevices() {
368 Set<Node> nodeSet = getNodes();
369 List<Switch> swList = new ArrayList<Switch>();
370 if (nodeSet != null) {
371 for (Node node : nodeSet) {
372 swList.add(getSwitchByNode(node));
379 private Status updateConfig(SubnetConfig conf, boolean add) {
381 if(subnetsConfigList.putIfAbsent(conf.getName(), conf) != null) {
382 String msg = "Cluster conflict: Subnet with name " + conf.getName() + "already exists.";
383 return new Status(StatusCode.CONFLICT, msg);
386 subnetsConfigList.remove(conf.getName());
388 return new Status(StatusCode.SUCCESS);
391 private Status updateDatabase(SubnetConfig conf, boolean add) {
393 Subnet subnetCurr = subnets.get(conf.getIPAddress());
395 if (subnetCurr == null) {
396 subnet = new Subnet(conf);
398 subnet = subnetCurr.clone();
400 // In case of API3 call we may receive the ports along with the
402 if (!conf.isGlobal()) {
403 subnet.addNodeConnectors(conf.getNodeConnectors());
405 boolean putNewSubnet = false;
406 if(subnetCurr == null) {
407 if(subnets.putIfAbsent(conf.getIPAddress(), subnet) == null) {
411 putNewSubnet = subnets.replace(conf.getIPAddress(), subnetCurr, subnet);
414 String msg = "Cluster conflict: Conflict while adding the subnet " + conf.getIPAddress();
415 return new Status(StatusCode.CONFLICT, msg);
418 // Subnet removal case
420 subnets.remove(conf.getIPAddress());
422 return new Status(StatusCode.SUCCESS);
425 private Status semanticCheck(SubnetConfig conf) {
426 Set<InetAddress> IPs = subnets.keySet();
428 return new Status(StatusCode.SUCCESS);
430 Subnet newSubnet = new Subnet(conf);
431 for (InetAddress i : IPs) {
432 Subnet existingSubnet = subnets.get(i);
433 if ((existingSubnet != null) && !existingSubnet.isMutualExclusive(newSubnet)) {
434 return new Status(StatusCode.CONFLICT, "This subnet conflicts with an existing one.");
437 return new Status(StatusCode.SUCCESS);
440 private Status addRemoveSubnet(SubnetConfig conf, boolean isAdding) {
441 // Valid configuration check
442 Status status = conf.validate();
443 if (!status.isSuccess()) {
444 log.warn(status.getDescription());
450 if (subnetsConfigList.containsKey(conf.getName())) {
451 return new Status(StatusCode.CONFLICT,
452 "Subnet with the specified name already exists.");
455 status = semanticCheck(conf);
456 if (!status.isSuccess()) {
460 if (conf.getName().equalsIgnoreCase(DEFAULT_SUBNET_NAME)) {
461 return new Status(StatusCode.NOTALLOWED, "The specified subnet gateway cannot be removed");
466 status = updateDatabase(conf, isAdding);
468 if (status.isSuccess()) {
469 // Update Configuration
470 status = updateConfig(conf, isAdding);
471 if(!status.isSuccess()) {
472 updateDatabase(conf, (!isAdding));
474 // update the listeners
475 Subnet subnetCurr = subnets.get(conf.getIPAddress());
477 if (subnetCurr == null) {
478 subnet = new Subnet(conf);
480 subnet = subnetCurr.clone();
482 notifySubnetChange(subnet, isAdding);
490 * Adds Subnet configured in GUI or API3
493 public Status addSubnet(SubnetConfig conf) {
494 return this.addRemoveSubnet(conf, true);
498 public Status removeSubnet(SubnetConfig conf) {
499 return this.addRemoveSubnet(conf, false);
503 public Status removeSubnet(String name) {
504 if (name.equalsIgnoreCase(DEFAULT_SUBNET_NAME)) {
505 return new Status(StatusCode.NOTALLOWED, "The specified subnet gateway cannot be removed");
507 SubnetConfig conf = subnetsConfigList.get(name);
509 return new Status(StatusCode.SUCCESS, "Subnet not present");
511 return this.addRemoveSubnet(conf, false);
515 public Status modifySubnet(SubnetConfig conf) {
518 return new Status(StatusCode.BADREQUEST, "Invalid Subnet configuration: null");
521 // Valid configuration check
522 Status status = conf.validate();
523 if (!status.isSuccess()) {
524 log.warn(status.getDescription());
528 // If a subnet configuration with this name does not exist, consider this is a creation
529 SubnetConfig target = subnetsConfigList.get(conf.getName());
530 if (target == null) {
531 return this.addSubnet(conf);
535 if (target.equals(conf)) {
536 return new Status(StatusCode.SUCCESS);
539 // Check not allowed modifications
540 if (!target.getSubnet().equals(conf.getSubnet())) {
541 return new Status(StatusCode.BADREQUEST, "IP address change is not allowed");
544 // Derive the set of node connectors that are being removed
545 Set<NodeConnector> toRemove = target.getNodeConnectors();
546 toRemove.removeAll(conf.getNodeConnectors());
547 List<String> nodeConnectorStrings = null;
548 if (!toRemove.isEmpty()) {
549 nodeConnectorStrings = new ArrayList<String>();
550 for (NodeConnector nc : toRemove) {
551 nodeConnectorStrings.add(nc.toString());
553 status = this.removePortsFromSubnet(conf.getName(), nodeConnectorStrings);
554 if (!status.isSuccess()) {
559 // Derive the set of node connectors that are being added
560 Set<NodeConnector> toAdd = conf.getNodeConnectors();
561 toAdd.removeAll(target.getNodeConnectors());
562 if (!toAdd.isEmpty()) {
563 List<String> nodeConnectorStringRemoved = nodeConnectorStrings;
564 nodeConnectorStrings = new ArrayList<String>();
565 for (NodeConnector nc : toAdd) {
566 nodeConnectorStrings.add(nc.toString());
568 status = this.addPortsToSubnet(conf.getName(), nodeConnectorStrings);
569 if (!status.isSuccess()) {
570 // If any port was removed, add it back as a best recovery effort
571 if (!toRemove.isEmpty()) {
572 this.addPortsToSubnet(conf.getName(), nodeConnectorStringRemoved);
578 // Update Configuration
579 subnetsConfigList.put(conf.getName(), conf);
581 return new Status(StatusCode.SUCCESS);
585 public Status addPortsToSubnet(String name, List<String> switchPorts) {
587 return new Status(StatusCode.BADREQUEST, "Null subnet name");
589 SubnetConfig confCurr = subnetsConfigList.get(name);
590 if (confCurr == null) {
591 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
594 if (switchPorts == null || switchPorts.isEmpty()) {
595 return new Status(StatusCode.BADREQUEST, "Null or empty port set");
598 Subnet subCurr = subnets.get(confCurr.getIPAddress());
599 if (subCurr == null) {
600 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress());
601 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
605 Subnet sub = subCurr.clone();
606 Set<NodeConnector> sp = NodeConnector.fromString(switchPorts);
607 sub.addNodeConnectors(sp);
608 boolean subnetsReplaced = subnets.replace(confCurr.getIPAddress(), subCurr, sub);
609 if (!subnetsReplaced) {
610 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
611 return new Status(StatusCode.CONFLICT, msg);
614 // Update Configuration
615 SubnetConfig conf = confCurr.clone();
616 conf.addNodeConnectors(switchPorts);
617 boolean configReplaced = subnetsConfigList.replace(name, confCurr, conf);
618 if (!configReplaced) {
619 // TODO: recovery using Transactionality
620 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
621 return new Status(StatusCode.CONFLICT, msg);
624 return new Status(StatusCode.SUCCESS);
628 public Status removePortsFromSubnet(String name, List<String> switchPorts) {
630 return new Status(StatusCode.BADREQUEST, "Null subnet name");
632 SubnetConfig confCurr = subnetsConfigList.get(name);
633 if (confCurr == null) {
634 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
637 if (switchPorts == null || switchPorts.isEmpty()) {
638 return new Status(StatusCode.BADREQUEST, "Null or empty port set");
641 Subnet subCurr = subnets.get(confCurr.getIPAddress());
642 if (subCurr == null) {
643 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress());
644 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
648 Status status = SubnetConfig.validatePorts(switchPorts);
649 if (!status.isSuccess()) {
653 Subnet sub = subCurr.clone();
654 Set<NodeConnector> sp = NodeConnector.fromString(switchPorts);
655 sub.deleteNodeConnectors(sp);
656 boolean subnetsReplace = subnets.replace(confCurr.getIPAddress(), subCurr, sub);
657 if (!subnetsReplace) {
658 String msg = "Cluster conflict: Conflict while removing ports from the subnet " + name;
659 return new Status(StatusCode.CONFLICT, msg);
662 // Update Configuration
663 SubnetConfig conf = confCurr.clone();
664 conf.removeNodeConnectors(switchPorts);
665 boolean result = subnetsConfigList.replace(name, confCurr, conf);
667 // TODO: recovery using Transactionality
668 String msg = "Cluster conflict: Conflict while removing ports from " + conf;
669 return new Status(StatusCode.CONFLICT, msg);
672 return new Status(StatusCode.SUCCESS);
675 public String getContainerName() {
676 if (containerName == null) {
677 return GlobalConstants.DEFAULT.toString();
679 return containerName;
683 public Subnet getSubnetByNetworkAddress(InetAddress networkAddress) {
684 // if there are no subnets, return the default subnet
685 if (subnets.size() == 0) {
686 return DEFAULT_SUBNET;
689 for(Map.Entry<InetAddress,Subnet> subnetEntry : subnets.entrySet()) {
690 if(subnetEntry.getValue().isSubnetOf(networkAddress)) {
691 return subnetEntry.getValue();
698 public Object readObject(ObjectInputStream ois)
699 throws FileNotFoundException, IOException, ClassNotFoundException {
700 // Perform the class deserialization locally, from inside the package
701 // where the class is defined
702 return ois.readObject();
705 @SuppressWarnings("unchecked")
706 private void loadSubnetConfiguration() {
707 ObjectReader objReader = new ObjectReader();
708 ConcurrentMap<String, SubnetConfig> confList = (ConcurrentMap<String, SubnetConfig>) objReader
709 .read(this, subnetFileName);
711 if (confList == null) {
715 for (SubnetConfig conf : confList.values()) {
720 @SuppressWarnings("unchecked")
721 private void loadSpanConfiguration() {
722 ObjectReader objReader = new ObjectReader();
723 ConcurrentMap<Integer, SpanConfig> confList = (ConcurrentMap<Integer, SpanConfig>) objReader
724 .read(this, spanFileName);
726 if (confList == null) {
730 for (SpanConfig conf : confList.values()) {
735 @SuppressWarnings("unchecked")
736 private void loadSwitchConfiguration() {
737 ObjectReader objReader = new ObjectReader();
738 ConcurrentMap<String, SwitchConfig> confList = (ConcurrentMap<String, SwitchConfig>) objReader
739 .read(this, switchConfigFileName);
741 if (confList == null) {
745 for (SwitchConfig conf : confList.values()) {
746 updateNodeConfig(conf);
750 @SuppressWarnings("deprecation")
752 public void updateSwitchConfig(SwitchConfig cfgObject) {
753 // update default container only
754 if (!isDefaultContainer) {
758 SwitchConfig sc = nodeConfigList.get(cfgObject.getNodeId());
760 if (nodeConfigList.putIfAbsent(cfgObject.getNodeId(), cfgObject) != null) {
764 if (!nodeConfigList.replace(cfgObject.getNodeId(), sc, cfgObject)) {
769 boolean modeChange = false;
771 if ((sc == null) || !cfgObject.getMode().equals(sc.getMode())) {
775 String nodeId = cfgObject.getNodeId();
776 Node node = Node.fromString(nodeId);
777 Map<String, Property> propMapCurr = nodeProps.get(node);
778 if (propMapCurr == null) {
781 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
782 Property desc = new Description(cfgObject.getNodeDescription());
783 propMap.put(desc.getName(), desc);
784 Property tier = new Tier(Integer.parseInt(cfgObject.getTier()));
785 propMap.put(tier.getName(), tier);
787 if (!nodeProps.replace(node, propMapCurr, propMap)) {
788 // TODO rollback using Transactionality
792 log.trace("Set Node {}'s Mode to {}", nodeId, cfgObject.getMode());
795 notifyModeChange(node, cfgObject.isProactive());
800 public Status updateNodeConfig(SwitchConfig switchConfig) {
801 Status status = switchConfig.validate();
802 if (!status.isSuccess()) {
806 Map<String, Property> updateProperties = switchConfig.getNodeProperties();
807 ForwardingMode mode = (ForwardingMode) updateProperties.get(ForwardingMode.name);
809 if (isDefaultContainer) {
810 if (!mode.isValid()) {
811 return new Status(StatusCode.BADREQUEST, "Invalid Forwarding Mode Value");
814 return new Status(StatusCode.NOTACCEPTABLE,
815 "Forwarding Mode modification is allowed only in default container");
819 Description description = (Description) switchConfig.getProperty(Description.propertyName);
820 String nodeId = switchConfig.getNodeId();
821 Node node = Node.fromString(nodeId);
822 NodeDescription nodeDesc = (this.statisticsManager == null) ? null : this.statisticsManager
823 .getNodeDescription(node);
824 String advertisedDesc = (nodeDesc == null) ? "" : nodeDesc.getDescription();
825 if (description != null && description.getValue() != null) {
826 if (description.getValue().isEmpty() || description.getValue().equals(advertisedDesc)) {
827 updateProperties.remove(Description.propertyName);
828 switchConfig = new SwitchConfig(nodeId, updateProperties);
830 // check if description is configured or was published by any other node
831 for (Map.Entry<Node, Map<String, Property>> entry : nodeProps.entrySet()) {
832 Node n = entry.getKey();
833 Description desc = (Description) getNodeProp(n, Description.propertyName);
834 NodeDescription nDesc = (this.statisticsManager == null) ? null : this.statisticsManager
835 .getNodeDescription(n);
836 String advDesc = (nDesc == null) ? "" : nDesc.getDescription();
837 if ((description.equals(desc) || description.getValue().equals(advDesc)) && !node.equals(n)) {
838 return new Status(StatusCode.CONFLICT, "Node name already in use");
844 boolean modeChange = false;
845 SwitchConfig sc = nodeConfigList.get(nodeId);
846 Map<String, Property> prevNodeProperties = new HashMap<String, Property>();
848 if ((mode != null) && mode.isProactive()) {
851 if (!updateProperties.isEmpty()) {
852 if (nodeConfigList.putIfAbsent(nodeId, switchConfig) != null) {
853 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
857 prevNodeProperties = new HashMap<String, Property>(sc.getNodeProperties());
858 ForwardingMode prevMode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
860 if ((prevMode != null) && (prevMode.isProactive())) {
864 if (((prevMode != null) && (prevMode.getValue() != mode.getValue()))
865 || (prevMode == null && mode.isProactive())) {
869 if (updateProperties.isEmpty()) {
870 nodeConfigList.remove(nodeId);
872 if (!nodeConfigList.replace(nodeId, sc, switchConfig)) {
873 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
877 Map<String, Property> propMapCurr = nodeProps.get(node);
878 if (propMapCurr == null) {
879 return new Status(StatusCode.SUCCESS);
881 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
882 for (Map.Entry<String, Property> entry : prevNodeProperties.entrySet()) {
883 String prop = entry.getKey();
884 if (!updateProperties.containsKey(prop)) {
885 if (prop.equals(Description.propertyName)) {
886 if (!advertisedDesc.isEmpty()) {
887 Property desc = new Description(advertisedDesc);
888 propMap.put(Description.propertyName, desc);
891 } else if (prop.equals(ForwardingMode.name)) {
892 Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING);
893 propMap.put(ForwardingMode.name, defaultMode);
896 propMap.remove(prop);
899 propMap.putAll(updateProperties);
900 if (!nodeProps.replace(node, propMapCurr, propMap)) {
901 // TODO rollback using Transactionality
902 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
905 notifyModeChange(node, (mode == null) ? false : mode.isProactive());
907 return new Status(StatusCode.SUCCESS);
911 public Status removeNodeConfig(String nodeId) {
912 if ((nodeId == null) || (nodeId.isEmpty())) {
913 return new Status(StatusCode.BADREQUEST, "nodeId cannot be empty.");
915 Map<String, Property> nodeProperties = getSwitchConfig(nodeId).getNodeProperties();
916 Node node = Node.fromString(nodeId);
917 Map<String, Property> propMapCurr = nodeProps.get(node);
918 if ((propMapCurr != null) && (nodeProperties != null) && (!nodeProperties.isEmpty())) {
919 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
920 for (Map.Entry<String, Property> entry : nodeProperties.entrySet()) {
921 String prop = entry.getKey();
922 if (prop.equals(Description.propertyName)) {
923 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
924 if (nodeProp.get(node) != null) {
925 propMap.put(Description.propertyName, nodeProp.get(node).get(Description.propertyName));
929 propMap.remove(prop);
931 if (!nodeProps.replace(node, propMapCurr, propMap)) {
932 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration.");
935 if (nodeConfigList != null) {
936 nodeConfigList.remove(nodeId);
938 return new Status(StatusCode.SUCCESS);
942 public Status saveSwitchConfig() {
943 return saveSwitchConfigInternal();
946 public Status saveSwitchConfigInternal() {
947 Status retS = null, retP = null;
948 ObjectWriter objWriter = new ObjectWriter();
950 retS = objWriter.write(new ConcurrentHashMap<String, SubnetConfig>(
951 subnetsConfigList), subnetFileName);
952 retP = objWriter.write(new ConcurrentHashMap<SpanConfig, SpanConfig>(
953 spanConfigList), spanFileName);
954 retS = objWriter.write(new ConcurrentHashMap<String, SwitchConfig>(
955 nodeConfigList), switchConfigFileName);
956 if (retS.equals(retP)) {
957 if (retS.isSuccess()) {
960 return new Status(StatusCode.INTERNALERROR, "Save failed");
963 return new Status(StatusCode.INTERNALERROR, "Partial save failure");
968 public List<SpanConfig> getSpanConfigList() {
969 return new ArrayList<SpanConfig>(spanConfigList.values());
973 public Status addSpanConfig(SpanConfig conf) {
974 // Valid config check
975 if (!conf.isValidConfig()) {
976 String msg = "Invalid Span configuration";
978 return new Status(StatusCode.BADREQUEST, msg);
982 if (spanConfigList.containsKey(conf)) {
983 return new Status(StatusCode.CONFLICT, "Same span config exists");
986 // Update configuration
987 if (spanConfigList.putIfAbsent(conf, conf) == null) {
988 // Update database and notify clients
989 addSpanPorts(conf.getNode(), conf.getPortArrayList());
992 return new Status(StatusCode.SUCCESS);
996 public Status removeSpanConfig(SpanConfig conf) {
997 removeSpanPorts(conf.getNode(), conf.getPortArrayList());
999 // Update configuration
1000 spanConfigList.remove(conf);
1002 return new Status(StatusCode.SUCCESS);
1006 public List<NodeConnector> getSpanPorts(Node node) {
1007 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
1009 for (NodeConnector nodeConnector : spanNodeConnectors) {
1010 if (nodeConnector.getNode().equals(node)) {
1011 ncList.add(nodeConnector);
1017 private void addNode(Node node, Set<Property> props) {
1018 log.trace("{} added, props: {}", node, props);
1019 if (nodeProps == null) {
1023 Map<String, Property> propMapCurr = nodeProps.get(node);
1024 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1025 : new HashMap<String, Property>(propMapCurr);
1027 // copy node properties from plugin
1028 if (props != null) {
1029 for (Property prop : props) {
1030 propMap.put(prop.getName(), prop);
1034 boolean proactiveForwarding = false;
1035 // copy node properties from config
1036 if (nodeConfigList != null) {
1037 String nodeId = node.toString();
1038 SwitchConfig conf = nodeConfigList.get(nodeId);
1039 if (conf != null && (conf.getNodeProperties() != null)) {
1040 Map<String, Property> nodeProperties = conf.getNodeProperties();
1041 propMap.putAll(nodeProperties);
1042 if (nodeProperties.get(ForwardingMode.name) != null) {
1043 ForwardingMode mode = (ForwardingMode) nodeProperties.get(ForwardingMode.name);
1044 proactiveForwarding = mode.isProactive();
1049 if (!propMap.containsKey(ForwardingMode.name)) {
1050 Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING);
1051 propMap.put(ForwardingMode.name, defaultMode);
1053 boolean result = false;
1054 if (propMapCurr == null) {
1055 if (nodeProps.putIfAbsent(node, propMap) == null) {
1059 result = nodeProps.replace(node, propMapCurr, propMap);
1062 log.debug("Cluster conflict: Conflict while adding the node properties. Node: {} Properties: {}",
1063 node.getID(), props);
1064 addNodeProps(node, propMap);
1067 // check if span ports are configed
1070 // notify node listeners
1071 notifyNode(node, UpdateType.ADDED, propMap);
1073 // notify proactive mode forwarding
1074 if (proactiveForwarding) {
1075 notifyModeChange(node, true);
1079 private void removeNode(Node node) {
1080 log.trace("{} removed", node);
1081 if (nodeProps == null) {
1084 nodeProps.remove(node);
1085 nodeConnectorNames.remove(node);
1086 Set<NodeConnector> removeNodeConnectorSet = new HashSet<NodeConnector>();
1087 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1088 NodeConnector nodeConnector = entry.getKey();
1089 if (nodeConnector.getNode().equals(node)) {
1090 removeNodeConnectorSet.add(nodeConnector);
1093 for (NodeConnector nc : removeNodeConnectorSet) {
1094 nodeConnectorProps.remove(nc);
1097 // check if span ports need to be cleaned up
1098 removeSpanPorts(node);
1100 /* notify node listeners */
1101 notifyNode(node, UpdateType.REMOVED, null);
1104 private void updateNode(Node node, Set<Property> props) {
1105 log.trace("{} updated, props: {}", node, props);
1106 if (nodeProps == null || props == null) {
1110 Map<String, Property> propMapCurr = nodeProps.get(node);
1111 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1112 : new HashMap<String, Property>(propMapCurr);
1114 // copy node properties from plugin
1115 String nodeId = node.toString();
1116 for (Property prop : props) {
1117 if (nodeConfigList != null) {
1118 SwitchConfig conf = nodeConfigList.get(nodeId);
1119 if (conf != null && (conf.getNodeProperties() != null)
1120 && conf.getNodeProperties().containsKey(prop.getName())) {
1124 propMap.put(prop.getName(), prop);
1127 if (propMapCurr == null) {
1128 if (nodeProps.putIfAbsent(node, propMap) != null) {
1129 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1130 node.getID(), props);
1131 addNodeProps(node, propMap);
1134 if (!nodeProps.replace(node, propMapCurr, propMap)) {
1135 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1136 node.getID(), props);
1137 addNodeProps(node, propMap);
1141 /* notify node listeners */
1142 notifyNode(node, UpdateType.CHANGED, propMap);
1146 public void updateNode(Node node, UpdateType type, Set<Property> props) {
1147 log.debug("updateNode: {} type {} props {} for container {}",
1148 new Object[] { node, type, props, containerName });
1151 addNode(node, props);
1154 updateNode(node, props);
1165 public void updateNodeConnector(NodeConnector nodeConnector,
1166 UpdateType type, Set<Property> props) {
1167 Map<String, Property> propMap = new HashMap<String, Property>();
1168 boolean update = true;
1170 log.debug("updateNodeConnector: {} type {} props {} for container {}",
1171 new Object[] { nodeConnector, type, props, containerName });
1173 if (nodeConnectorProps == null) {
1179 if (props != null) {
1180 for (Property prop : props) {
1181 addNodeConnectorProp(nodeConnector, prop);
1182 propMap.put(prop.getName(), prop);
1185 addNodeConnectorProp(nodeConnector, null);
1188 addSpanPort(nodeConnector);
1191 if (!nodeConnectorProps.containsKey(nodeConnector) || (props == null)) {
1194 for (Property prop : props) {
1195 addNodeConnectorProp(nodeConnector, prop);
1196 propMap.put(prop.getName(), prop);
1201 if (!nodeConnectorProps.containsKey(nodeConnector)) {
1204 removeNodeConnectorAllProps(nodeConnector);
1206 // clean up span config
1207 removeSpanPort(nodeConnector);
1215 notifyNodeConnector(nodeConnector, type, propMap);
1220 public Set<Node> getNodes() {
1221 return (nodeProps != null) ? new HashSet<Node>(nodeProps.keySet()) : new HashSet<Node>();
1225 public Map<String, Property> getControllerProperties() {
1226 return new HashMap<String, Property>(this.controllerProps);
1230 public Property getControllerProperty(String propertyName) {
1231 if (propertyName != null) {
1232 HashMap<String, Property> propertyMap = new HashMap<String, Property>(this.controllerProps);
1233 return propertyMap.get(propertyName);
1239 public Status setControllerProperty(Property property) {
1240 if (property != null) {
1241 this.controllerProps.put(property.getName(), property);
1242 return new Status(StatusCode.SUCCESS);
1244 return new Status(StatusCode.BADREQUEST, "Invalid property provided when setting property");
1248 public Status removeControllerProperty(String propertyName) {
1249 if (propertyName != null) {
1250 if (this.controllerProps.containsKey(propertyName)) {
1251 this.controllerProps.remove(propertyName);
1252 if (!this.controllerProps.containsKey(propertyName)) {
1253 return new Status(StatusCode.SUCCESS);
1256 String msg = "Unable to remove property " + propertyName + " from Controller";
1257 return new Status(StatusCode.BADREQUEST, msg);
1259 String msg = "Invalid property provided when removing property from Controller";
1260 return new Status(StatusCode.BADREQUEST, msg);
1264 * Returns a copy of a list of properties for a given node
1269 * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps
1270 * (org.opendaylight.controller.sal.core.Node)
1273 public Map<String, Property> getNodeProps(Node node) {
1274 Map<String, Property> rv = new HashMap<String, Property>();
1275 if (this.nodeProps != null) {
1276 rv = this.nodeProps.get(node);
1278 /* make a copy of it */
1279 rv = new HashMap<String, Property>(rv);
1286 public Property getNodeProp(Node node, String propName) {
1287 Map<String, Property> propMap = getNodeProps(node);
1288 return (propMap != null) ? propMap.get(propName) : null;
1292 public void setNodeProp(Node node, Property prop) {
1294 for (int i = 0; i <= REPLACE_RETRY; i++) {
1295 /* Get a copy of the property map */
1296 Map<String, Property> propMapCurr = getNodeProps(node);
1297 if (propMapCurr == null) {
1301 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1302 propMap.put(prop.getName(), prop);
1304 if (nodeProps.replace(node, propMapCurr, propMap)) {
1308 log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1312 public Status removeNodeProp(Node node, String propName) {
1313 for (int i = 0; i <= REPLACE_RETRY; i++) {
1314 Map<String, Property> propMapCurr = getNodeProps(node);
1315 if (propMapCurr != null) {
1316 if (!propMapCurr.containsKey(propName)) {
1317 return new Status(StatusCode.SUCCESS);
1319 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1320 propMap.remove(propName);
1321 if (nodeProps.replace(node, propMapCurr, propMap)) {
1322 return new Status(StatusCode.SUCCESS);
1325 return new Status(StatusCode.SUCCESS);
1328 String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID();
1329 return new Status(StatusCode.CONFLICT, msg);
1333 public Status removeNodeAllProps(Node node) {
1334 this.nodeProps.remove(node);
1335 return new Status(StatusCode.SUCCESS);
1339 public Set<NodeConnector> getUpNodeConnectors(Node node) {
1340 if (nodeConnectorProps == null) {
1344 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1345 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1346 NodeConnector nodeConnector = entry.getKey();
1347 if (!nodeConnector.getNode().equals(node)) {
1350 if (isNodeConnectorEnabled(nodeConnector)) {
1351 nodeConnectorSet.add(nodeConnector);
1355 return nodeConnectorSet;
1359 public Set<NodeConnector> getNodeConnectors(Node node) {
1360 if (nodeConnectorProps == null) {
1364 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1365 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1366 NodeConnector nodeConnector = entry.getKey();
1367 if (!nodeConnector.getNode().equals(node)) {
1370 nodeConnectorSet.add(nodeConnector);
1373 return nodeConnectorSet;
1377 public Set<NodeConnector> getPhysicalNodeConnectors(Node node) {
1378 if (nodeConnectorProps == null) {
1382 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1383 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1384 NodeConnector nodeConnector = entry.getKey();
1385 if (!nodeConnector.getNode().equals(node)
1386 || isSpecial(nodeConnector)) {
1389 nodeConnectorSet.add(nodeConnector);
1392 return nodeConnectorSet;
1396 public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) {
1397 Map<String, Property> rv = new HashMap<String, Property>();
1398 if (this.nodeConnectorProps != null) {
1399 rv = this.nodeConnectorProps.get(nodeConnector);
1401 rv = new HashMap<String, Property>(rv);
1408 public Property getNodeConnectorProp(NodeConnector nodeConnector,
1410 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1411 return (propMap != null) ? propMap.get(propName) : null;
1414 private byte[] getHardwareMAC() {
1415 Enumeration<NetworkInterface> nis;
1416 byte[] macAddress = null;
1419 nis = NetworkInterface.getNetworkInterfaces();
1420 } catch (SocketException e) {
1421 log.error("Failed to acquire controller MAC: ", e);
1425 while (nis.hasMoreElements()) {
1426 NetworkInterface ni = nis.nextElement();
1428 macAddress = ni.getHardwareAddress();
1429 } catch (SocketException e) {
1430 log.error("Failed to acquire controller MAC: ", e);
1432 if (macAddress != null) {
1436 if (macAddress == null) {
1437 log.warn("Failed to acquire controller MAC: No physical interface found");
1438 // This happens when running controller on windows VM, for example
1439 // Try parsing the OS command output
1445 public byte[] getControllerMAC() {
1446 MacAddress macProperty = (MacAddress)controllerProps.get(MacAddress.name);
1447 return (macProperty == null) ? null : macProperty.getMacAddress();
1451 public NodeConnector getNodeConnector(Node node, String nodeConnectorName) {
1452 if (nodeConnectorNames == null) {
1456 Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1461 return map.get(nodeConnectorName);
1465 * Adds a node connector and its property if any
1467 * @param nodeConnector
1468 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1470 * name of {@link org.opendaylight.controller.sal.core.Property}
1471 * @return success or failed reason
1474 public Status addNodeConnectorProp(NodeConnector nodeConnector,
1476 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1477 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1478 : new HashMap<String, Property>(propMapCurr);
1480 String msg = "Cluster conflict: Unable to add NodeConnector Property.";
1481 // Just add the nodeConnector if prop is not available (in a non-default
1484 if (propMapCurr == null) {
1485 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1486 return new Status(StatusCode.CONFLICT, msg);
1489 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1490 return new Status(StatusCode.CONFLICT, msg);
1493 return new Status(StatusCode.SUCCESS);
1496 propMap.put(prop.getName(), prop);
1497 if (propMapCurr == null) {
1498 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1499 return new Status(StatusCode.CONFLICT, msg);
1502 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1503 return new Status(StatusCode.CONFLICT, msg);
1507 if (prop.getName().equals(Name.NamePropName)) {
1508 if (nodeConnectorNames != null) {
1509 Node node = nodeConnector.getNode();
1510 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1511 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1512 if (mapCurr != null) {
1513 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1514 String s = entry.getKey();
1516 map.put(s, new NodeConnector(entry.getValue()));
1517 } catch (ConstructionException e) {
1518 log.error("An error occured",e);
1523 map.put(((Name) prop).getValue(), nodeConnector);
1524 if (mapCurr == null) {
1525 if (nodeConnectorNames.putIfAbsent(node, map) != null) {
1526 // TODO: recovery using Transactionality
1527 return new Status(StatusCode.CONFLICT, msg);
1530 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1531 // TODO: recovery using Transactionality
1532 return new Status(StatusCode.CONFLICT, msg);
1538 return new Status(StatusCode.SUCCESS);
1542 * Removes one property of a node connector
1544 * @param nodeConnector
1545 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1547 * name of {@link org.opendaylight.controller.sal.core.Property}
1548 * @return success or failed reason
1551 public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) {
1552 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1554 if (propMapCurr == null) {
1555 /* Nothing to remove */
1556 return new Status(StatusCode.SUCCESS);
1559 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1560 propMap.remove(propName);
1561 boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap);
1562 String msg = "Cluster conflict: Unable to remove NodeConnector property.";
1564 return new Status(StatusCode.CONFLICT, msg);
1567 if (propName.equals(Name.NamePropName)) {
1568 if (nodeConnectorNames != null) {
1569 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1571 Node node = nodeConnector.getNode();
1572 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1573 if (mapCurr != null) {
1574 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1575 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1576 String s = entry.getKey();
1578 map.put(s, new NodeConnector(entry.getValue()));
1579 } catch (ConstructionException e) {
1580 log.error("An error occured",e);
1583 map.remove(name.getValue());
1584 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1585 // TODO: recovery using Transactionality
1586 return new Status(StatusCode.CONFLICT, msg);
1593 return new Status(StatusCode.SUCCESS);
1597 * Removes all the properties of a node connector
1599 * @param nodeConnector
1600 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1601 * @return success or failed reason
1604 public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) {
1605 if (nodeConnectorNames != null) {
1606 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1608 Node node = nodeConnector.getNode();
1609 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1610 if (mapCurr != null) {
1611 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1612 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1613 String s = entry.getKey();
1615 map.put(s, new NodeConnector(entry.getValue()));
1616 } catch (ConstructionException e) {
1617 log.error("An error occured",e);
1620 map.remove(name.getValue());
1621 if (map.isEmpty()) {
1622 nodeConnectorNames.remove(node);
1624 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1625 log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.",
1626 nodeConnector.getID());
1633 nodeConnectorProps.remove(nodeConnector);
1635 return new Status(StatusCode.SUCCESS);
1639 * Function called by the dependency manager when all the required
1640 * dependencies are satisfied
1643 void init(Component c) {
1644 Dictionary<?, ?> props = c.getServiceProperties();
1645 if (props != null) {
1646 this.containerName = (String) props.get("containerName");
1647 log.trace("Running containerName: {}", this.containerName);
1649 // In the Global instance case the containerName is empty
1650 this.containerName = "";
1652 isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT
1659 * Function called by the dependency manager when at least one dependency
1660 * become unsatisfied or when the component is shutting down because for
1661 * example bundle is being stopped.
1669 * Function called by dependency manager after "init ()" is called and after
1670 * the services provided by the class are registered in the service registry
1675 registerWithOSGIConsole();
1679 * Function called after registered the service in OSGi service registry.
1682 // solicit for existing inventories
1687 * Function called by the dependency manager before the services exported by
1688 * the component are unregistered, this will be followed by a "destroy ()"
1695 public void setInventoryService(IInventoryService service) {
1696 log.trace("Got inventory service set request {}", service);
1697 this.inventoryService = service;
1699 // solicit for existing inventories
1703 public void unsetInventoryService(IInventoryService service) {
1704 log.trace("Got a service UNset request");
1705 this.inventoryService = null;
1707 // clear existing inventories
1711 public void setStatisticsManager(IStatisticsManager statisticsManager) {
1712 log.trace("Got statistics manager set request {}", statisticsManager);
1713 this.statisticsManager = statisticsManager;
1716 public void unsetStatisticsManager(IStatisticsManager statisticsManager) {
1717 log.trace("Got statistics manager UNset request");
1718 this.statisticsManager = null;
1721 public void setSwitchManagerAware(ISwitchManagerAware service) {
1722 log.trace("Got inventory service set request {}", service);
1723 if (this.switchManagerAware != null) {
1724 this.switchManagerAware.add(service);
1727 // bulk update for newly joined
1728 switchManagerAwareNotify(service);
1731 public void unsetSwitchManagerAware(ISwitchManagerAware service) {
1732 log.trace("Got a service UNset request");
1733 if (this.switchManagerAware != null) {
1734 this.switchManagerAware.remove(service);
1738 public void setInventoryListener(IInventoryListener service) {
1739 log.trace("Got inventory listener set request {}", service);
1740 if (this.inventoryListeners != null) {
1741 this.inventoryListeners.add(service);
1744 // bulk update for newly joined
1745 bulkUpdateService(service);
1748 public void unsetInventoryListener(IInventoryListener service) {
1749 log.trace("Got a service UNset request");
1750 if (this.inventoryListeners != null) {
1751 this.inventoryListeners.remove(service);
1755 public void setSpanAware(ISpanAware service) {
1756 log.trace("Got SpanAware set request {}", service);
1757 if (this.spanAware != null) {
1758 this.spanAware.add(service);
1761 // bulk update for newly joined
1762 spanAwareNotify(service);
1765 public void unsetSpanAware(ISpanAware service) {
1766 log.trace("Got a service UNset request");
1767 if (this.spanAware != null) {
1768 this.spanAware.remove(service);
1772 void setClusterContainerService(IClusterContainerServices s) {
1773 log.trace("Cluster Service set");
1774 this.clusterContainerService = s;
1777 void unsetClusterContainerService(IClusterContainerServices s) {
1778 if (this.clusterContainerService == s) {
1779 log.trace("Cluster Service removed!");
1780 this.clusterContainerService = null;
1784 private void getInventories() {
1785 if (inventoryService == null) {
1786 log.trace("inventory service not avaiable");
1790 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
1791 for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) {
1792 Node node = entry.getKey();
1793 log.debug("getInventories: {} added for container {}", new Object[] { node, containerName });
1794 Map<String, Property> propMap = entry.getValue();
1795 Set<Property> props = new HashSet<Property>();
1796 for (Property property : propMap.values()) {
1797 props.add(property);
1799 addNode(node, props);
1802 Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps();
1803 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) {
1804 Map<String, Property> propMap = entry.getValue();
1805 for (Property property : propMap.values()) {
1806 addNodeConnectorProp(entry.getKey(), property);
1811 private void clearInventories() {
1813 nodeConnectorProps.clear();
1814 nodeConnectorNames.clear();
1815 spanNodeConnectors.clear();
1818 private void notifyNode(Node node, UpdateType type,
1819 Map<String, Property> propMap) {
1820 synchronized (inventoryListeners) {
1821 for (IInventoryListener service : inventoryListeners) {
1822 service.notifyNode(node, type, propMap);
1827 private void notifyNodeConnector(NodeConnector nodeConnector,
1828 UpdateType type, Map<String, Property> propMap) {
1829 synchronized (inventoryListeners) {
1830 for (IInventoryListener service : inventoryListeners) {
1831 service.notifyNodeConnector(nodeConnector, type, propMap);
1837 * For those joined late, bring them up-to-date.
1839 private void switchManagerAwareNotify(ISwitchManagerAware service) {
1840 for (Subnet sub : subnets.values()) {
1841 service.subnetNotify(sub, true);
1844 for (Node node : getNodes()) {
1845 SwitchConfig sc = getSwitchConfig(node.toString());
1846 if ((sc != null) && isDefaultContainer) {
1847 ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
1848 service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive());
1853 private void bulkUpdateService(IInventoryListener service) {
1854 Map<String, Property> propMap;
1855 UpdateType type = UpdateType.ADDED;
1857 for (Node node : getNodes()) {
1858 propMap = nodeProps.get(node);
1859 service.notifyNode(node, type, propMap);
1862 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1863 NodeConnector nodeConnector = entry.getKey();
1864 propMap = nodeConnectorProps.get(nodeConnector);
1865 service.notifyNodeConnector(nodeConnector, type, propMap);
1869 private void spanAwareNotify(ISpanAware service) {
1870 for (Node node : getNodes()) {
1871 for (SpanConfig conf : getSpanConfigList(node)) {
1872 service.spanUpdate(node, conf.getPortArrayList(), true);
1877 private void registerWithOSGIConsole() {
1878 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
1879 .getBundleContext();
1880 bundleContext.registerService(CommandProvider.class.getName(), this,
1885 public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) {
1886 if (nodeConnector == null) {
1890 Config config = (Config) getNodeConnectorProp(nodeConnector,
1891 Config.ConfigPropName);
1892 State state = (State) getNodeConnectorProp(nodeConnector,
1893 State.StatePropName);
1894 return ((config != null) && (config.getValue() == Config.ADMIN_UP)
1895 && (state != null) && (state.getValue() == State.EDGE_UP));
1899 public boolean doesNodeConnectorExist(NodeConnector nc) {
1900 return (nc != null && nodeConnectorProps != null
1901 && nodeConnectorProps.containsKey(nc));
1905 public String getHelp() {
1906 StringBuffer help = new StringBuffer();
1907 help.append("---Switch Manager---\n");
1908 help.append("\t pencs <node id> - Print enabled node connectors for a given node\n");
1909 help.append("\t pdm <node id> - Print switch ports in device map\n");
1910 return help.toString();
1913 public void _pencs(CommandInterpreter ci) {
1914 String st = ci.nextArgument();
1916 ci.println("Please enter node id");
1920 Node node = Node.fromString(st);
1922 ci.println("Please enter node id");
1926 Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node);
1927 if (nodeConnectorSet == null) {
1930 for (NodeConnector nodeConnector : nodeConnectorSet) {
1931 if (nodeConnector == null) {
1934 ci.println(nodeConnector);
1936 ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1939 public void _pdm(CommandInterpreter ci) {
1940 String st = ci.nextArgument();
1942 ci.println("Please enter node id");
1946 Node node = Node.fromString(st);
1948 ci.println("Please enter node id");
1952 Switch sw = getSwitchByNode(node);
1954 ci.println(" NodeConnector Name");
1956 Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors();
1957 String nodeConnectorName;
1958 if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
1959 for (NodeConnector nodeConnector : nodeConnectorSet) {
1960 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1961 nodeConnectorName = (propMap == null) ? null : ((Name) propMap
1962 .get(Name.NamePropName)).getValue();
1963 if (nodeConnectorName != null) {
1964 Node nd = nodeConnector.getNode();
1965 if (!nd.equals(node)) {
1966 log.debug("node not match {} {}", nd, node);
1968 Map<String, NodeConnector> map = nodeConnectorNames
1971 NodeConnector nc = map.get(nodeConnectorName);
1973 log.debug("no nodeConnector named {}",
1975 } else if (!nc.equals(nodeConnector)) {
1976 log.debug("nodeConnector not match {} {}", nc,
1982 ci.println(nodeConnector
1984 + ((nodeConnectorName == null) ? "" : nodeConnectorName)
1985 + "(" + nodeConnector.getID() + ")");
1987 ci.println("Total number of NodeConnectors: "
1988 + nodeConnectorSet.size());
1993 public byte[] getNodeMAC(Node node) {
1994 MacAddress mac = (MacAddress) this.getNodeProp(node,
1996 return (mac != null) ? mac.getMacAddress() : null;
2000 public boolean isSpecial(NodeConnector p) {
2001 if (p.getType().equals(NodeConnectorIDType.CONTROLLER)
2002 || p.getType().equals(NodeConnectorIDType.ALL)
2003 || p.getType().equals(NodeConnectorIDType.SWSTACK)
2004 || p.getType().equals(NodeConnectorIDType.HWPATH)) {
2011 * Add span configuration to local cache and notify clients
2013 private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2014 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2016 for (NodeConnector nodeConnector : nodeConnectors) {
2017 if (!spanNodeConnectors.contains(nodeConnector)) {
2018 ncLists.add(nodeConnector);
2022 if (ncLists.size() > 0) {
2023 spanNodeConnectors.addAll(ncLists);
2024 notifySpanPortChange(node, ncLists, true);
2028 private void addSpanPorts(Node node) {
2029 for (SpanConfig conf : getSpanConfigList(node)) {
2030 addSpanPorts(node, conf.getPortArrayList());
2034 private void addSpanPort(NodeConnector nodeConnector) {
2035 // only add if span is configured on this nodeConnector
2036 for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) {
2037 if (conf.getPortArrayList().contains(nodeConnector)) {
2038 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2039 ncLists.add(nodeConnector);
2040 addSpanPorts(nodeConnector.getNode(), ncLists);
2047 * Remove span configuration to local cache and notify clients
2049 private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2050 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2052 for (NodeConnector nodeConnector : nodeConnectors) {
2053 if (spanNodeConnectors.contains(nodeConnector)) {
2054 ncLists.add(nodeConnector);
2058 if (ncLists.size() > 0) {
2059 spanNodeConnectors.removeAll(ncLists);
2060 notifySpanPortChange(node, ncLists, false);
2064 private void removeSpanPorts(Node node) {
2065 for (SpanConfig conf : getSpanConfigList(node)) {
2066 addSpanPorts(node, conf.getPortArrayList());
2070 private void removeSpanPort(NodeConnector nodeConnector) {
2071 if (spanNodeConnectors.contains(nodeConnector)) {
2072 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2073 ncLists.add(nodeConnector);
2074 removeSpanPorts(nodeConnector.getNode(), ncLists);
2078 private void addNodeProps(Node node, Map<String, Property> propMap) {
2079 if (propMap == null) {
2080 propMap = new HashMap<String, Property>();
2082 nodeProps.put(node, propMap);
2086 public Status saveConfiguration() {
2087 return saveSwitchConfig();
2091 * Creates a Name/Tier/Bandwidth/MacAddress(controller property) Property
2092 * object based on given property name and value. Other property types are
2093 * not supported yet.
2096 * Name of the Property
2098 * Value of the Property
2099 * @return {@link org.opendaylight.controller.sal.core.Property}
2102 public Property createProperty(String propName, String propValue) {
2103 if (propName == null) {
2104 log.debug("propName is null");
2107 if (propValue == null) {
2108 log.debug("propValue is null");
2113 if (propName.equalsIgnoreCase(Description.propertyName)) {
2114 return new Description(propValue);
2115 } else if (propName.equalsIgnoreCase(Tier.TierPropName)) {
2116 int tier = Integer.parseInt(propValue);
2117 return new Tier(tier);
2118 } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) {
2119 long bw = Long.parseLong(propValue);
2120 return new Bandwidth(bw);
2121 } else if (propName.equalsIgnoreCase(ForwardingMode.name)) {
2122 int mode = Integer.parseInt(propValue);
2123 return new ForwardingMode(mode);
2124 } else if (propName.equalsIgnoreCase(MacAddress.name)){
2125 return new MacAddress(propValue);
2128 log.debug("Not able to create {} property", propName);
2130 } catch (Exception e) {
2131 log.debug("createProperty caught exception {}", e.getMessage());
2138 @SuppressWarnings("deprecation")
2140 public String getNodeDescription(Node node) {
2141 // Check first if user configured a name
2142 SwitchConfig config = getSwitchConfig(node.toString());
2143 if (config != null) {
2144 String configuredDesc = config.getNodeDescription();
2145 if (configuredDesc != null && !configuredDesc.isEmpty()) {
2146 return configuredDesc;
2150 // No name configured by user, get the node advertised name
2151 Description desc = (Description) getNodeProp(node,
2152 Description.propertyName);
2153 return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? ""
2158 public Set<Switch> getConfiguredNotConnectedSwitches() {
2159 Set<Switch> configuredNotConnectedSwitches = new HashSet<Switch>();
2160 if (this.inventoryService == null) {
2161 log.trace("inventory service not avaiable");
2162 return configuredNotConnectedSwitches;
2165 Set<Node> configuredNotConnectedNodes = this.inventoryService.getConfiguredNotConnectedNodes();
2166 if (configuredNotConnectedNodes != null) {
2167 for (Node node : configuredNotConnectedNodes) {
2168 Switch sw = getSwitchByNode(node);
2170 configuredNotConnectedSwitches.add(sw);
2174 return configuredNotConnectedSwitches;