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.ConfigurationObject;
39 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
40 import org.opendaylight.controller.configuration.IConfigurationContainerService;
41 import org.opendaylight.controller.sal.core.Bandwidth;
42 import org.opendaylight.controller.sal.core.Config;
43 import org.opendaylight.controller.sal.core.ConstructionException;
44 import org.opendaylight.controller.sal.core.Description;
45 import org.opendaylight.controller.sal.core.ForwardingMode;
46 import org.opendaylight.controller.sal.core.MacAddress;
47 import org.opendaylight.controller.sal.core.Name;
48 import org.opendaylight.controller.sal.core.Node;
49 import org.opendaylight.controller.sal.core.NodeConnector;
50 import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType;
51 import org.opendaylight.controller.sal.core.Property;
52 import org.opendaylight.controller.sal.core.State;
53 import org.opendaylight.controller.sal.core.Tier;
54 import org.opendaylight.controller.sal.core.UpdateType;
55 import org.opendaylight.controller.sal.inventory.IInventoryService;
56 import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates;
57 import org.opendaylight.controller.sal.reader.NodeDescription;
58 import org.opendaylight.controller.sal.utils.GlobalConstants;
59 import org.opendaylight.controller.sal.utils.HexEncode;
60 import org.opendaylight.controller.sal.utils.IObjectReader;
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 final String SUBNETS_FILE_NAME = "subnets.conf";
90 private static final String SPAN_FILE_NAME = "spanPorts.conf";
91 private static final String SWITCH_CONFIG_FILE_NAME = "switchConfig.conf";
92 private final List<NodeConnector> spanNodeConnectors = new CopyOnWriteArrayList<NodeConnector>();
93 // Collection of Subnets keyed by the InetAddress
94 private ConcurrentMap<InetAddress, Subnet> subnets;
95 private ConcurrentMap<String, SubnetConfig> subnetsConfigList;
96 private ConcurrentMap<SpanConfig, SpanConfig> spanConfigList;
97 // manually configured parameters for the node such as name, tier, mode
98 private ConcurrentMap<String, SwitchConfig> nodeConfigList;
99 private ConcurrentMap<Node, Map<String, Property>> nodeProps;
100 private ConcurrentMap<NodeConnector, Map<String, Property>> nodeConnectorProps;
101 private ConcurrentMap<Node, Map<String, NodeConnector>> nodeConnectorNames;
102 private ConcurrentMap<String, Property> controllerProps;
103 private IInventoryService inventoryService;
104 private IStatisticsManager statisticsManager;
105 private IConfigurationContainerService configurationService;
106 private final Set<ISwitchManagerAware> switchManagerAware = Collections
107 .synchronizedSet(new HashSet<ISwitchManagerAware>());
108 private final Set<IInventoryListener> inventoryListeners = Collections
109 .synchronizedSet(new HashSet<IInventoryListener>());
110 private final Set<ISpanAware> spanAware = Collections.synchronizedSet(new HashSet<ISpanAware>());
111 private IClusterContainerServices clusterContainerService = null;
112 private String containerName = null;
113 private boolean isDefaultContainer = true;
114 private static final int REPLACE_RETRY = 1;
116 /* Information about the default subnet. If there have been no configured subnets, i.e.,
117 * subnets.size() == 0 or subnetsConfigList.size() == 0, then this subnet will be the
118 * only subnet returned. As soon as a user-configured subnet is created this one will
121 protected static final SubnetConfig DEFAULT_SUBNETCONFIG;
122 protected static final Subnet DEFAULT_SUBNET;
123 protected static final String DEFAULT_SUBNET_NAME = "default (cannot be modifed)";
125 DEFAULT_SUBNETCONFIG = new SubnetConfig(DEFAULT_SUBNET_NAME, "0.0.0.0/0", new ArrayList<String>());
126 DEFAULT_SUBNET = new Subnet(DEFAULT_SUBNETCONFIG);
129 public void notifySubnetChange(Subnet sub, boolean add) {
130 synchronized (switchManagerAware) {
131 for (Object subAware : switchManagerAware) {
133 ((ISwitchManagerAware) subAware).subnetNotify(sub, add);
134 } catch (Exception e) {
135 log.error("Failed to notify Subnet change {}",
142 public void notifySpanPortChange(Node node, List<NodeConnector> ports, boolean add) {
143 synchronized (spanAware) {
144 for (Object sa : spanAware) {
146 ((ISpanAware) sa).spanUpdate(node, ports, add);
147 } catch (Exception e) {
148 log.error("Failed to notify Span Interface change {}",
155 private void notifyModeChange(Node node, boolean proactive) {
156 synchronized (switchManagerAware) {
157 for (ISwitchManagerAware service : switchManagerAware) {
159 service.modeChangeNotify(node, proactive);
160 } catch (Exception e) {
161 log.error("Failed to notify Subnet change {}",
168 public void startUp() {
169 // Instantiate cluster synced variables
173 // Add controller MAC, if first node in the cluster
174 if (!controllerProps.containsKey(MacAddress.name)) {
175 byte controllerMac[] = getHardwareMAC();
176 if (controllerMac != null) {
177 Property existing = controllerProps.putIfAbsent(MacAddress.name, new MacAddress(controllerMac));
178 if (existing == null && log.isTraceEnabled()) {
179 log.trace("Container {}: Setting controller MAC address in the cluster: {}", getContainerName(),
180 HexEncode.bytesToHexStringFormat(controllerMac));
186 public void shutDown() {
189 private void allocateCaches() {
190 if (this.clusterContainerService == null) {
191 this.nonClusterObjectCreate();
192 log.warn("un-initialized clusterContainerService, can't create cache");
197 clusterContainerService.createCache(
198 "switchmanager.subnetsConfigList",
199 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
200 clusterContainerService.createCache("switchmanager.spanConfigList",
201 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
202 clusterContainerService.createCache("switchmanager.nodeConfigList",
203 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
204 clusterContainerService.createCache("switchmanager.subnets",
205 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
206 clusterContainerService.createCache("switchmanager.nodeProps",
207 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
208 clusterContainerService.createCache(
209 "switchmanager.nodeConnectorProps",
210 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
211 clusterContainerService.createCache(
212 "switchmanager.nodeConnectorNames",
213 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
214 clusterContainerService.createCache(
215 "switchmanager.controllerProps",
216 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
217 } catch (CacheConfigException cce) {
218 log.error("\nCache configuration invalid - check cache mode");
219 } catch (CacheExistException ce) {
220 log.error("\nCache already exits - destroy and recreate if needed");
224 @SuppressWarnings({ "unchecked" })
225 private void retrieveCaches() {
226 if (this.clusterContainerService == null) {
227 log.warn("un-initialized clusterContainerService, can't create cache");
231 subnetsConfigList = (ConcurrentMap<String, SubnetConfig>) clusterContainerService
232 .getCache("switchmanager.subnetsConfigList");
233 if (subnetsConfigList == null) {
234 log.error("\nFailed to get cache for subnetsConfigList");
237 spanConfigList = (ConcurrentMap<SpanConfig, SpanConfig>) clusterContainerService
238 .getCache("switchmanager.spanConfigList");
239 if (spanConfigList == null) {
240 log.error("\nFailed to get cache for spanConfigList");
243 nodeConfigList = (ConcurrentMap<String, SwitchConfig>) clusterContainerService
244 .getCache("switchmanager.nodeConfigList");
245 if (nodeConfigList == null) {
246 log.error("\nFailed to get cache for nodeConfigList");
249 subnets = (ConcurrentMap<InetAddress, Subnet>) clusterContainerService
250 .getCache("switchmanager.subnets");
251 if (subnets == null) {
252 log.error("\nFailed to get cache for subnets");
255 nodeProps = (ConcurrentMap<Node, Map<String, Property>>) clusterContainerService
256 .getCache("switchmanager.nodeProps");
257 if (nodeProps == null) {
258 log.error("\nFailed to get cache for nodeProps");
261 nodeConnectorProps = (ConcurrentMap<NodeConnector, Map<String, Property>>) clusterContainerService
262 .getCache("switchmanager.nodeConnectorProps");
263 if (nodeConnectorProps == null) {
264 log.error("\nFailed to get cache for nodeConnectorProps");
267 nodeConnectorNames = (ConcurrentMap<Node, Map<String, NodeConnector>>) clusterContainerService
268 .getCache("switchmanager.nodeConnectorNames");
269 if (nodeConnectorNames == null) {
270 log.error("\nFailed to get cache for nodeConnectorNames");
273 controllerProps = (ConcurrentMap<String, Property>) clusterContainerService
274 .getCache("switchmanager.controllerProps");
275 if (controllerProps == null) {
276 log.error("\nFailed to get cache for controllerProps");
280 private void nonClusterObjectCreate() {
281 subnetsConfigList = new ConcurrentHashMap<String, SubnetConfig>();
282 spanConfigList = new ConcurrentHashMap<SpanConfig, SpanConfig>();
283 nodeConfigList = new ConcurrentHashMap<String, SwitchConfig>();
284 subnets = new ConcurrentHashMap<InetAddress, Subnet>();
285 nodeProps = new ConcurrentHashMap<Node, Map<String, Property>>();
286 nodeConnectorProps = new ConcurrentHashMap<NodeConnector, Map<String, Property>>();
287 nodeConnectorNames = new ConcurrentHashMap<Node, Map<String, NodeConnector>>();
288 controllerProps = new ConcurrentHashMap<String, Property>();
292 public List<SubnetConfig> getSubnetsConfigList() {
293 // if there are no subnets, return the default subnet
294 if(subnetsConfigList.size() == 0){
295 return Collections.singletonList(DEFAULT_SUBNETCONFIG);
297 return new ArrayList<SubnetConfig>(subnetsConfigList.values());
302 public SubnetConfig getSubnetConfig(String subnet) {
303 // if there are no subnets, return the default subnet
304 if(subnetsConfigList.isEmpty() && subnet.equalsIgnoreCase(DEFAULT_SUBNET_NAME)){
305 return DEFAULT_SUBNETCONFIG;
307 return subnetsConfigList.get(subnet);
311 private List<SpanConfig> getSpanConfigList(Node node) {
312 List<SpanConfig> confList = new ArrayList<SpanConfig>();
313 String nodeId = node.toString();
314 for (SpanConfig conf : spanConfigList.values()) {
315 if (conf.matchNode(nodeId)) {
322 public List<SwitchConfig> getNodeConfigList() {
323 return new ArrayList<SwitchConfig>(nodeConfigList.values());
327 public SwitchConfig getSwitchConfig(String switchId) {
328 return nodeConfigList.get(switchId);
331 public Switch getSwitchByNode(Node node) {
332 Switch sw = new Switch(node);
334 MacAddress mac = (MacAddress) this.getNodeProp(node,
337 sw.setDataLayerAddress(mac.getMacAddress());
339 Set<NodeConnector> ncSet = getPhysicalNodeConnectors(node);
340 sw.setNodeConnectors(ncSet);
342 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
343 for (NodeConnector nodeConnector : ncSet) {
344 if (spanNodeConnectors.contains(nodeConnector)) {
345 ncList.add(nodeConnector);
348 sw.addSpanPorts(ncList);
354 public List<Switch> getNetworkDevices() {
355 List<Switch> swList = new ArrayList<Switch>();
356 for (Node node : getNodes()) {
357 swList.add(getSwitchByNode(node));
362 private Status updateConfig(SubnetConfig conf, boolean add) {
364 if(subnetsConfigList.putIfAbsent(conf.getName(), conf) != null) {
365 String msg = "Cluster conflict: Subnet with name " + conf.getName() + "already exists.";
366 return new Status(StatusCode.CONFLICT, msg);
369 subnetsConfigList.remove(conf.getName());
371 return new Status(StatusCode.SUCCESS);
374 private Status updateDatabase(SubnetConfig conf, boolean add) {
376 Subnet subnetCurr = subnets.get(conf.getIPAddress());
378 if (subnetCurr == null) {
379 subnet = new Subnet(conf);
381 subnet = subnetCurr.clone();
383 // In case of API3 call we may receive the ports along with the
385 if (!conf.isGlobal()) {
386 subnet.addNodeConnectors(conf.getNodeConnectors());
388 boolean putNewSubnet = false;
389 if(subnetCurr == null) {
390 if(subnets.putIfAbsent(conf.getIPAddress(), subnet) == null) {
394 putNewSubnet = subnets.replace(conf.getIPAddress(), subnetCurr, subnet);
397 String msg = "Cluster conflict: Conflict while adding the subnet " + conf.getIPAddress();
398 return new Status(StatusCode.CONFLICT, msg);
401 // Subnet removal case
403 subnets.remove(conf.getIPAddress());
405 return new Status(StatusCode.SUCCESS);
408 private Status semanticCheck(SubnetConfig conf) {
409 Set<InetAddress> IPs = subnets.keySet();
411 return new Status(StatusCode.SUCCESS);
413 Subnet newSubnet = new Subnet(conf);
414 for (InetAddress i : IPs) {
415 Subnet existingSubnet = subnets.get(i);
416 if ((existingSubnet != null) && !existingSubnet.isMutualExclusive(newSubnet)) {
417 return new Status(StatusCode.CONFLICT, "This subnet conflicts with an existing one.");
420 return new Status(StatusCode.SUCCESS);
423 private Status addRemoveSubnet(SubnetConfig conf, boolean isAdding) {
424 // Valid configuration check
425 Status status = conf.validate();
426 if (!status.isSuccess()) {
427 log.warn(status.getDescription());
433 if (subnetsConfigList.containsKey(conf.getName())) {
434 return new Status(StatusCode.CONFLICT,
435 "Subnet with the specified name already exists.");
438 status = semanticCheck(conf);
439 if (!status.isSuccess()) {
443 if (conf.getName().equalsIgnoreCase(DEFAULT_SUBNET_NAME)) {
444 return new Status(StatusCode.NOTALLOWED, "The specified subnet gateway cannot be removed");
449 status = updateDatabase(conf, isAdding);
451 if (status.isSuccess()) {
452 // Update Configuration
453 status = updateConfig(conf, isAdding);
454 if(!status.isSuccess()) {
455 updateDatabase(conf, (!isAdding));
457 // update the listeners
458 Subnet subnetCurr = subnets.get(conf.getIPAddress());
460 if (subnetCurr == null) {
461 subnet = new Subnet(conf);
463 subnet = subnetCurr.clone();
465 notifySubnetChange(subnet, isAdding);
473 * Adds Subnet configured in GUI or API3
476 public Status addSubnet(SubnetConfig conf) {
477 return this.addRemoveSubnet(conf, true);
481 public Status removeSubnet(SubnetConfig conf) {
482 return this.addRemoveSubnet(conf, false);
486 public Status removeSubnet(String name) {
487 if (name.equalsIgnoreCase(DEFAULT_SUBNET_NAME)) {
488 return new Status(StatusCode.NOTALLOWED, "The specified subnet gateway cannot be removed");
490 SubnetConfig conf = subnetsConfigList.get(name);
492 return new Status(StatusCode.SUCCESS, "Subnet not present");
494 return this.addRemoveSubnet(conf, false);
498 public Status modifySubnet(SubnetConfig conf) {
501 return new Status(StatusCode.BADREQUEST, "Invalid Subnet configuration: null");
504 // Valid configuration check
505 Status status = conf.validate();
506 if (!status.isSuccess()) {
507 log.warn(status.getDescription());
511 // If a subnet configuration with this name does not exist, consider this is a creation
512 SubnetConfig target = subnetsConfigList.get(conf.getName());
513 if (target == null) {
514 return this.addSubnet(conf);
518 if (target.equals(conf)) {
519 return new Status(StatusCode.SUCCESS);
522 // Check not allowed modifications
523 if (!target.getSubnet().equals(conf.getSubnet())) {
524 return new Status(StatusCode.BADREQUEST, "IP address change is not allowed");
527 // Derive the set of node connectors that are being removed
528 Set<NodeConnector> toRemove = target.getNodeConnectors();
529 toRemove.removeAll(conf.getNodeConnectors());
530 List<String> nodeConnectorStrings = null;
531 if (!toRemove.isEmpty()) {
532 nodeConnectorStrings = new ArrayList<String>();
533 for (NodeConnector nc : toRemove) {
534 nodeConnectorStrings.add(nc.toString());
536 status = this.removePortsFromSubnet(conf.getName(), nodeConnectorStrings);
537 if (!status.isSuccess()) {
542 // Derive the set of node connectors that are being added
543 Set<NodeConnector> toAdd = conf.getNodeConnectors();
544 toAdd.removeAll(target.getNodeConnectors());
545 if (!toAdd.isEmpty()) {
546 List<String> nodeConnectorStringRemoved = nodeConnectorStrings;
547 nodeConnectorStrings = new ArrayList<String>();
548 for (NodeConnector nc : toAdd) {
549 nodeConnectorStrings.add(nc.toString());
551 status = this.addPortsToSubnet(conf.getName(), nodeConnectorStrings);
552 if (!status.isSuccess()) {
553 // If any port was removed, add it back as a best recovery effort
554 if (!toRemove.isEmpty()) {
555 this.addPortsToSubnet(conf.getName(), nodeConnectorStringRemoved);
561 // Update Configuration
562 subnetsConfigList.put(conf.getName(), conf);
564 return new Status(StatusCode.SUCCESS);
568 public Status addPortsToSubnet(String name, List<String> switchPorts) {
570 return new Status(StatusCode.BADREQUEST, "Null subnet name");
572 SubnetConfig confCurr = subnetsConfigList.get(name);
573 if (confCurr == null) {
574 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
577 if (switchPorts == null || switchPorts.isEmpty()) {
578 return new Status(StatusCode.BADREQUEST, "Null or empty port set");
581 Subnet subCurr = subnets.get(confCurr.getIPAddress());
582 if (subCurr == null) {
583 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress());
584 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
588 Subnet sub = subCurr.clone();
589 Set<NodeConnector> sp = NodeConnector.fromString(switchPorts);
590 sub.addNodeConnectors(sp);
591 boolean subnetsReplaced = subnets.replace(confCurr.getIPAddress(), subCurr, sub);
592 if (!subnetsReplaced) {
593 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
594 return new Status(StatusCode.CONFLICT, msg);
597 // Update Configuration
598 SubnetConfig conf = confCurr.clone();
599 conf.addNodeConnectors(switchPorts);
600 boolean configReplaced = subnetsConfigList.replace(name, confCurr, conf);
601 if (!configReplaced) {
602 // TODO: recovery using Transactionality
603 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
604 return new Status(StatusCode.CONFLICT, msg);
607 return new Status(StatusCode.SUCCESS);
611 public Status removePortsFromSubnet(String name, List<String> switchPorts) {
613 return new Status(StatusCode.BADREQUEST, "Null subnet name");
615 SubnetConfig confCurr = subnetsConfigList.get(name);
616 if (confCurr == null) {
617 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
620 if (switchPorts == null || switchPorts.isEmpty()) {
621 return new Status(StatusCode.BADREQUEST, "Null or empty port set");
624 Subnet subCurr = subnets.get(confCurr.getIPAddress());
625 if (subCurr == null) {
626 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress());
627 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
631 Status status = SubnetConfig.validatePorts(switchPorts);
632 if (!status.isSuccess()) {
636 Subnet sub = subCurr.clone();
637 Set<NodeConnector> sp = NodeConnector.fromString(switchPorts);
638 sub.deleteNodeConnectors(sp);
639 boolean subnetsReplace = subnets.replace(confCurr.getIPAddress(), subCurr, sub);
640 if (!subnetsReplace) {
641 String msg = "Cluster conflict: Conflict while removing ports from the subnet " + name;
642 return new Status(StatusCode.CONFLICT, msg);
645 // Update Configuration
646 SubnetConfig conf = confCurr.clone();
647 conf.removeNodeConnectors(switchPorts);
648 boolean result = subnetsConfigList.replace(name, confCurr, conf);
650 // TODO: recovery using Transactionality
651 String msg = "Cluster conflict: Conflict while removing ports from " + conf;
652 return new Status(StatusCode.CONFLICT, msg);
655 return new Status(StatusCode.SUCCESS);
658 public String getContainerName() {
659 if (containerName == null) {
660 return GlobalConstants.DEFAULT.toString();
662 return containerName;
666 public Subnet getSubnetByNetworkAddress(InetAddress networkAddress) {
667 // if there are no subnets, return the default subnet
668 if (subnets.size() == 0) {
669 return DEFAULT_SUBNET;
672 for(Map.Entry<InetAddress,Subnet> subnetEntry : subnets.entrySet()) {
673 if(subnetEntry.getValue().isSubnetOf(networkAddress)) {
674 return subnetEntry.getValue();
681 public Object readObject(ObjectInputStream ois)
682 throws FileNotFoundException, IOException, ClassNotFoundException {
683 // Perform the class deserialization locally, from inside the package
684 // where the class is defined
685 return ois.readObject();
688 private void loadSubnetConfiguration() {
689 for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, SUBNETS_FILE_NAME)) {
690 addSubnet((SubnetConfig) conf);
694 private void loadSpanConfiguration() {
695 for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, SPAN_FILE_NAME)) {
696 addSpanConfig((SpanConfig) conf);
700 private void loadSwitchConfiguration() {
701 for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, SWITCH_CONFIG_FILE_NAME)) {
702 updateNodeConfig((SwitchConfig) conf);
706 @SuppressWarnings("deprecation")
708 public void updateSwitchConfig(SwitchConfig cfgObject) {
709 // update default container only
710 if (!isDefaultContainer) {
714 SwitchConfig sc = nodeConfigList.get(cfgObject.getNodeId());
716 if (nodeConfigList.putIfAbsent(cfgObject.getNodeId(), cfgObject) != null) {
720 if (!nodeConfigList.replace(cfgObject.getNodeId(), sc, cfgObject)) {
725 boolean modeChange = false;
727 if ((sc == null) || !cfgObject.getMode().equals(sc.getMode())) {
731 String nodeId = cfgObject.getNodeId();
732 Node node = Node.fromString(nodeId);
733 Map<String, Property> propMapCurr = nodeProps.get(node);
734 if (propMapCurr == null) {
737 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
738 Property desc = new Description(cfgObject.getNodeDescription());
739 propMap.put(desc.getName(), desc);
740 Property tier = new Tier(Integer.parseInt(cfgObject.getTier()));
741 propMap.put(tier.getName(), tier);
743 if (!nodeProps.replace(node, propMapCurr, propMap)) {
744 // TODO rollback using Transactionality
748 log.trace("Set Node {}'s Mode to {}", nodeId, cfgObject.getMode());
751 notifyModeChange(node, cfgObject.isProactive());
756 public Status updateNodeConfig(SwitchConfig switchConfig) {
757 Status status = switchConfig.validate();
758 if (!status.isSuccess()) {
762 Map<String, Property> updateProperties = switchConfig.getNodeProperties();
763 ForwardingMode mode = (ForwardingMode) updateProperties.get(ForwardingMode.name);
765 if (isDefaultContainer) {
766 if (!mode.isValid()) {
767 return new Status(StatusCode.BADREQUEST, "Invalid Forwarding Mode Value");
770 return new Status(StatusCode.NOTACCEPTABLE,
771 "Forwarding Mode modification is allowed only in default container");
775 Description description = (Description) switchConfig.getProperty(Description.propertyName);
776 String nodeId = switchConfig.getNodeId();
777 Node node = Node.fromString(nodeId);
778 NodeDescription nodeDesc = (this.statisticsManager == null) ? null : this.statisticsManager
779 .getNodeDescription(node);
780 String advertisedDesc = (nodeDesc == null) ? "" : nodeDesc.getDescription();
781 if (description != null && description.getValue() != null) {
782 if (description.getValue().isEmpty() || description.getValue().equals(advertisedDesc)) {
783 updateProperties.remove(Description.propertyName);
784 switchConfig = new SwitchConfig(nodeId, updateProperties);
786 // check if description is configured or was published by any other node
787 for (Map.Entry<Node, Map<String, Property>> entry : nodeProps.entrySet()) {
788 Node n = entry.getKey();
789 Description desc = (Description) getNodeProp(n, Description.propertyName);
790 NodeDescription nDesc = (this.statisticsManager == null) ? null : this.statisticsManager
791 .getNodeDescription(n);
792 String advDesc = (nDesc == null) ? "" : nDesc.getDescription();
793 if ((description.equals(desc) || description.getValue().equals(advDesc)) && !node.equals(n)) {
794 return new Status(StatusCode.CONFLICT, "Node name already in use");
800 boolean modeChange = false;
801 SwitchConfig sc = nodeConfigList.get(nodeId);
802 Map<String, Property> prevNodeProperties = new HashMap<String, Property>();
804 if ((mode != null) && mode.isProactive()) {
807 if (!updateProperties.isEmpty()) {
808 if (nodeConfigList.putIfAbsent(nodeId, switchConfig) != null) {
809 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
813 prevNodeProperties = new HashMap<String, Property>(sc.getNodeProperties());
814 ForwardingMode prevMode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
816 if ((prevMode != null) && (prevMode.isProactive())) {
820 if (((prevMode != null) && (prevMode.getValue() != mode.getValue()))
821 || (prevMode == null && mode.isProactive())) {
825 if (updateProperties.isEmpty()) {
826 nodeConfigList.remove(nodeId);
828 if (!nodeConfigList.replace(nodeId, sc, switchConfig)) {
829 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
833 Map<String, Property> propMapCurr = nodeProps.get(node);
834 if (propMapCurr == null) {
835 return new Status(StatusCode.SUCCESS);
837 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
838 for (Map.Entry<String, Property> entry : prevNodeProperties.entrySet()) {
839 String prop = entry.getKey();
840 if (!updateProperties.containsKey(prop)) {
841 if (prop.equals(Description.propertyName)) {
842 if (advertisedDesc != null) {
843 if (!advertisedDesc.isEmpty()) {
844 Property desc = new Description(advertisedDesc);
845 propMap.put(Description.propertyName, desc);
849 propMap.remove(prop);
852 } else if (prop.equals(ForwardingMode.name)) {
853 Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING);
854 propMap.put(ForwardingMode.name, defaultMode);
857 propMap.remove(prop);
860 propMap.putAll(updateProperties);
861 if (!nodeProps.replace(node, propMapCurr, propMap)) {
862 // TODO rollback using Transactionality
863 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
866 notifyModeChange(node, (mode == null) ? false : mode.isProactive());
868 return new Status(StatusCode.SUCCESS);
872 public Status removeNodeConfig(String nodeId) {
873 if ((nodeId == null) || (nodeId.isEmpty())) {
874 return new Status(StatusCode.BADREQUEST, "nodeId cannot be empty.");
876 Map<String, Property> nodeProperties = getSwitchConfig(nodeId).getNodeProperties();
877 Node node = Node.fromString(nodeId);
878 Map<String, Property> propMapCurr = nodeProps.get(node);
879 if ((propMapCurr != null) && (nodeProperties != null) && (!nodeProperties.isEmpty())) {
880 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
881 for (Map.Entry<String, Property> entry : nodeProperties.entrySet()) {
882 String prop = entry.getKey();
883 if (prop.equals(Description.propertyName)) {
884 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
885 if (nodeProp.get(node) != null) {
886 propMap.put(Description.propertyName, nodeProp.get(node).get(Description.propertyName));
890 propMap.remove(prop);
892 if (!nodeProps.replace(node, propMapCurr, propMap)) {
893 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration.");
896 if (nodeConfigList != null) {
897 nodeConfigList.remove(nodeId);
899 return new Status(StatusCode.SUCCESS);
903 public Status saveSwitchConfig() {
904 return saveSwitchConfigInternal();
907 public Status saveSwitchConfigInternal() {
910 status = configurationService.persistConfiguration(
911 new ArrayList<ConfigurationObject>(subnetsConfigList.values()), SUBNETS_FILE_NAME);
912 if (status.isSuccess()) {
915 log.warn("Failed to save subnet gateway configurations: " + status.getDescription());
917 status = configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(spanConfigList.values()),
919 if (status.isSuccess()) {
922 log.warn("Failed to save span port configurations: " + status.getDescription());
924 status = configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(nodeConfigList.values()),
925 SWITCH_CONFIG_FILE_NAME);
926 if (status.isSuccess()) {
929 log.warn("Failed to save node configurations: " + status.getDescription());
932 return new Status(StatusCode.INTERNALERROR, "Save failed");
935 return new Status(StatusCode.INTERNALERROR, "Partial save failure");
941 public List<SpanConfig> getSpanConfigList() {
942 return new ArrayList<SpanConfig>(spanConfigList.values());
946 public Status addSpanConfig(SpanConfig conf) {
947 // Valid config check
948 if (!conf.isValidConfig()) {
949 String msg = "Invalid Span configuration";
951 return new Status(StatusCode.BADREQUEST, msg);
955 if (spanConfigList.containsKey(conf)) {
956 return new Status(StatusCode.CONFLICT, "Same span config exists");
959 // Update configuration
960 if (spanConfigList.putIfAbsent(conf, conf) == null) {
961 // Update database and notify clients
962 addSpanPorts(conf.getNode(), conf.getPortArrayList());
965 return new Status(StatusCode.SUCCESS);
969 public Status removeSpanConfig(SpanConfig conf) {
970 removeSpanPorts(conf.getNode(), conf.getPortArrayList());
972 // Update configuration
973 spanConfigList.remove(conf);
975 return new Status(StatusCode.SUCCESS);
979 public List<NodeConnector> getSpanPorts(Node node) {
980 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
982 for (NodeConnector nodeConnector : spanNodeConnectors) {
983 if (nodeConnector.getNode().equals(node)) {
984 ncList.add(nodeConnector);
990 private void addNode(Node node, Set<Property> props) {
991 log.trace("{} added, props: {}", node, props);
992 if (nodeProps == null) {
996 Map<String, Property> propMapCurr = nodeProps.get(node);
997 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
998 : new HashMap<String, Property>(propMapCurr);
1000 // copy node properties from plugin
1001 if (props != null) {
1002 for (Property prop : props) {
1003 propMap.put(prop.getName(), prop);
1007 boolean proactiveForwarding = false;
1008 // copy node properties from config
1009 if (nodeConfigList != null) {
1010 String nodeId = node.toString();
1011 SwitchConfig conf = nodeConfigList.get(nodeId);
1012 if (conf != null && (conf.getNodeProperties() != null)) {
1013 Map<String, Property> nodeProperties = conf.getNodeProperties();
1014 propMap.putAll(nodeProperties);
1015 if (nodeProperties.get(ForwardingMode.name) != null) {
1016 ForwardingMode mode = (ForwardingMode) nodeProperties.get(ForwardingMode.name);
1017 proactiveForwarding = mode.isProactive();
1022 if (!propMap.containsKey(ForwardingMode.name)) {
1023 Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING);
1024 propMap.put(ForwardingMode.name, defaultMode);
1026 boolean result = false;
1027 if (propMapCurr == null) {
1028 if (nodeProps.putIfAbsent(node, propMap) == null) {
1032 result = nodeProps.replace(node, propMapCurr, propMap);
1035 log.debug("Cluster conflict: Conflict while adding the node properties. Node: {} Properties: {}",
1036 node.getID(), props);
1037 addNodeProps(node, propMap);
1040 // check if span ports are configed
1043 // notify node listeners
1044 notifyNode(node, UpdateType.ADDED, propMap);
1046 // notify proactive mode forwarding
1047 if (proactiveForwarding) {
1048 notifyModeChange(node, true);
1052 private void removeNode(Node node) {
1053 log.trace("{} removed", node);
1054 if (nodeProps == null) {
1057 nodeProps.remove(node);
1058 nodeConnectorNames.remove(node);
1059 Set<NodeConnector> removeNodeConnectorSet = new HashSet<NodeConnector>();
1060 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1061 NodeConnector nodeConnector = entry.getKey();
1062 if (nodeConnector.getNode().equals(node)) {
1063 removeNodeConnectorSet.add(nodeConnector);
1066 for (NodeConnector nc : removeNodeConnectorSet) {
1067 nodeConnectorProps.remove(nc);
1070 // check if span ports need to be cleaned up
1071 removeSpanPorts(node);
1073 /* notify node listeners */
1074 notifyNode(node, UpdateType.REMOVED, null);
1077 private void updateNode(Node node, Set<Property> props) {
1078 log.trace("{} updated, props: {}", node, props);
1079 if (nodeProps == null || props == null) {
1083 Map<String, Property> propMapCurr = nodeProps.get(node);
1084 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1085 : new HashMap<String, Property>(propMapCurr);
1087 // copy node properties from plugin
1088 String nodeId = node.toString();
1089 for (Property prop : props) {
1090 if (nodeConfigList != null) {
1091 SwitchConfig conf = nodeConfigList.get(nodeId);
1092 if (conf != null && (conf.getNodeProperties() != null)
1093 && conf.getNodeProperties().containsKey(prop.getName())) {
1097 propMap.put(prop.getName(), prop);
1100 if (propMapCurr == null) {
1101 if (nodeProps.putIfAbsent(node, propMap) != null) {
1102 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1103 node.getID(), props);
1104 addNodeProps(node, propMap);
1107 if (!nodeProps.replace(node, propMapCurr, propMap)) {
1108 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1109 node.getID(), props);
1110 addNodeProps(node, propMap);
1114 /* notify node listeners */
1115 notifyNode(node, UpdateType.CHANGED, propMap);
1119 public void updateNode(Node node, UpdateType type, Set<Property> props) {
1120 log.debug("updateNode: {} type {} props {} for container {}",
1121 new Object[] { node, type, props, containerName });
1124 addNode(node, props);
1127 updateNode(node, props);
1138 public void updateNodeConnector(NodeConnector nodeConnector,
1139 UpdateType type, Set<Property> props) {
1140 Map<String, Property> propMap = new HashMap<String, Property>();
1141 boolean update = true;
1143 log.debug("updateNodeConnector: {} type {} props {} for container {}",
1144 new Object[] { nodeConnector, type, props, containerName });
1146 if (nodeConnectorProps == null) {
1152 if (props != null) {
1153 for (Property prop : props) {
1154 addNodeConnectorProp(nodeConnector, prop);
1155 propMap.put(prop.getName(), prop);
1158 addNodeConnectorProp(nodeConnector, null);
1161 addSpanPort(nodeConnector);
1164 if (!nodeConnectorProps.containsKey(nodeConnector) || (props == null)) {
1167 for (Property prop : props) {
1168 addNodeConnectorProp(nodeConnector, prop);
1169 propMap.put(prop.getName(), prop);
1174 if (!nodeConnectorProps.containsKey(nodeConnector)) {
1177 removeNodeConnectorAllProps(nodeConnector);
1179 // clean up span config
1180 removeSpanPort(nodeConnector);
1188 notifyNodeConnector(nodeConnector, type, propMap);
1193 public Set<Node> getNodes() {
1194 return (nodeProps != null) ? new HashSet<Node>(nodeProps.keySet()) : new HashSet<Node>();
1198 public Map<String, Property> getControllerProperties() {
1199 return new HashMap<String, Property>(this.controllerProps);
1203 public Property getControllerProperty(String propertyName) {
1204 if (propertyName != null) {
1205 HashMap<String, Property> propertyMap = new HashMap<String, Property>(this.controllerProps);
1206 return propertyMap.get(propertyName);
1212 public Status setControllerProperty(Property property) {
1213 if (property != null) {
1214 this.controllerProps.put(property.getName(), property);
1215 return new Status(StatusCode.SUCCESS);
1217 return new Status(StatusCode.BADREQUEST, "Invalid property provided when setting property");
1221 public Status removeControllerProperty(String propertyName) {
1222 if (propertyName != null) {
1223 if (this.controllerProps.containsKey(propertyName)) {
1224 this.controllerProps.remove(propertyName);
1225 if (!this.controllerProps.containsKey(propertyName)) {
1226 return new Status(StatusCode.SUCCESS);
1229 String msg = "Unable to remove property " + propertyName + " from Controller";
1230 return new Status(StatusCode.BADREQUEST, msg);
1232 String msg = "Invalid property provided when removing property from Controller";
1233 return new Status(StatusCode.BADREQUEST, msg);
1237 * Returns a copy of a list of properties for a given node
1242 * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps
1243 * (org.opendaylight.controller.sal.core.Node)
1246 public Map<String, Property> getNodeProps(Node node) {
1247 Map<String, Property> rv = new HashMap<String, Property>();
1248 if (this.nodeProps != null) {
1249 rv = this.nodeProps.get(node);
1251 /* make a copy of it */
1252 rv = new HashMap<String, Property>(rv);
1259 public Property getNodeProp(Node node, String propName) {
1260 Map<String, Property> propMap = getNodeProps(node);
1261 return (propMap != null) ? propMap.get(propName) : null;
1265 public void setNodeProp(Node node, Property prop) {
1267 for (int i = 0; i <= REPLACE_RETRY; i++) {
1268 /* Get a copy of the property map */
1269 Map<String, Property> propMapCurr = getNodeProps(node);
1270 if (propMapCurr == null) {
1274 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1275 propMap.put(prop.getName(), prop);
1277 if (nodeProps.replace(node, propMapCurr, propMap)) {
1281 log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1285 public Status removeNodeProp(Node node, String propName) {
1286 for (int i = 0; i <= REPLACE_RETRY; i++) {
1287 Map<String, Property> propMapCurr = getNodeProps(node);
1288 if (propMapCurr != null) {
1289 if (!propMapCurr.containsKey(propName)) {
1290 return new Status(StatusCode.SUCCESS);
1292 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1293 propMap.remove(propName);
1294 if (nodeProps.replace(node, propMapCurr, propMap)) {
1295 return new Status(StatusCode.SUCCESS);
1298 return new Status(StatusCode.SUCCESS);
1301 String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID();
1302 return new Status(StatusCode.CONFLICT, msg);
1306 public Status removeNodeAllProps(Node node) {
1307 this.nodeProps.remove(node);
1308 return new Status(StatusCode.SUCCESS);
1312 public Set<NodeConnector> getUpNodeConnectors(Node node) {
1313 if (nodeConnectorProps == null) {
1317 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1318 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1319 NodeConnector nodeConnector = entry.getKey();
1320 if (!nodeConnector.getNode().equals(node)) {
1323 if (isNodeConnectorEnabled(nodeConnector)) {
1324 nodeConnectorSet.add(nodeConnector);
1328 return nodeConnectorSet;
1332 public Set<NodeConnector> getNodeConnectors(Node node) {
1333 if (nodeConnectorProps == null) {
1337 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1338 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1339 NodeConnector nodeConnector = entry.getKey();
1340 if (!nodeConnector.getNode().equals(node)) {
1343 nodeConnectorSet.add(nodeConnector);
1346 return nodeConnectorSet;
1350 public Set<NodeConnector> getPhysicalNodeConnectors(Node node) {
1351 if (nodeConnectorProps == null) {
1355 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1356 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1357 NodeConnector nodeConnector = entry.getKey();
1358 if (!nodeConnector.getNode().equals(node)
1359 || isSpecial(nodeConnector)) {
1362 nodeConnectorSet.add(nodeConnector);
1365 return nodeConnectorSet;
1369 public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) {
1370 Map<String, Property> rv = new HashMap<String, Property>();
1371 if (this.nodeConnectorProps != null) {
1372 rv = this.nodeConnectorProps.get(nodeConnector);
1374 rv = new HashMap<String, Property>(rv);
1381 public Property getNodeConnectorProp(NodeConnector nodeConnector,
1383 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1384 return (propMap != null) ? propMap.get(propName) : null;
1387 private byte[] getHardwareMAC() {
1388 Enumeration<NetworkInterface> nis;
1389 byte[] macAddress = null;
1392 nis = NetworkInterface.getNetworkInterfaces();
1393 } catch (SocketException e) {
1394 log.error("Failed to acquire controller MAC: ", e);
1398 while (nis.hasMoreElements()) {
1399 NetworkInterface ni = nis.nextElement();
1401 macAddress = ni.getHardwareAddress();
1402 } catch (SocketException e) {
1403 log.error("Failed to acquire controller MAC: ", e);
1405 if (macAddress != null) {
1409 if (macAddress == null) {
1410 log.warn("Failed to acquire controller MAC: No physical interface found");
1411 // This happens when running controller on windows VM, for example
1412 // Try parsing the OS command output
1418 public byte[] getControllerMAC() {
1419 MacAddress macProperty = (MacAddress)controllerProps.get(MacAddress.name);
1420 return (macProperty == null) ? null : macProperty.getMacAddress();
1424 public NodeConnector getNodeConnector(Node node, String nodeConnectorName) {
1425 if (nodeConnectorNames == null) {
1429 Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1434 return map.get(nodeConnectorName);
1438 * Adds a node connector and its property if any
1440 * @param nodeConnector
1441 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1443 * name of {@link org.opendaylight.controller.sal.core.Property}
1444 * @return success or failed reason
1447 public Status addNodeConnectorProp(NodeConnector nodeConnector,
1449 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1450 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1451 : new HashMap<String, Property>(propMapCurr);
1453 String msg = "Cluster conflict: Unable to add NodeConnector Property.";
1454 // Just add the nodeConnector if prop is not available (in a non-default
1457 if (propMapCurr == null) {
1458 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1459 return new Status(StatusCode.CONFLICT, msg);
1462 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1463 return new Status(StatusCode.CONFLICT, msg);
1466 return new Status(StatusCode.SUCCESS);
1469 propMap.put(prop.getName(), prop);
1470 if (propMapCurr == null) {
1471 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1472 return new Status(StatusCode.CONFLICT, msg);
1475 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1476 return new Status(StatusCode.CONFLICT, msg);
1480 if (prop.getName().equals(Name.NamePropName)) {
1481 if (nodeConnectorNames != null) {
1482 Node node = nodeConnector.getNode();
1483 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1484 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1485 if (mapCurr != null) {
1486 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1487 String s = entry.getKey();
1489 map.put(s, new NodeConnector(entry.getValue()));
1490 } catch (ConstructionException e) {
1491 log.error("An error occured",e);
1496 map.put(((Name) prop).getValue(), nodeConnector);
1497 if (mapCurr == null) {
1498 if (nodeConnectorNames.putIfAbsent(node, map) != null) {
1499 // TODO: recovery using Transactionality
1500 return new Status(StatusCode.CONFLICT, msg);
1503 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1504 // TODO: recovery using Transactionality
1505 return new Status(StatusCode.CONFLICT, msg);
1511 return new Status(StatusCode.SUCCESS);
1515 * Removes one property of a node connector
1517 * @param nodeConnector
1518 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1520 * name of {@link org.opendaylight.controller.sal.core.Property}
1521 * @return success or failed reason
1524 public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) {
1525 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1527 if (propMapCurr == null) {
1528 /* Nothing to remove */
1529 return new Status(StatusCode.SUCCESS);
1532 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1533 propMap.remove(propName);
1534 boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap);
1535 String msg = "Cluster conflict: Unable to remove NodeConnector property.";
1537 return new Status(StatusCode.CONFLICT, msg);
1540 if (propName.equals(Name.NamePropName)) {
1541 if (nodeConnectorNames != null) {
1542 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1544 Node node = nodeConnector.getNode();
1545 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1546 if (mapCurr != null) {
1547 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1548 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1549 String s = entry.getKey();
1551 map.put(s, new NodeConnector(entry.getValue()));
1552 } catch (ConstructionException e) {
1553 log.error("An error occured",e);
1556 map.remove(name.getValue());
1557 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1558 // TODO: recovery using Transactionality
1559 return new Status(StatusCode.CONFLICT, msg);
1566 return new Status(StatusCode.SUCCESS);
1570 * Removes all the properties of a node connector
1572 * @param nodeConnector
1573 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1574 * @return success or failed reason
1577 public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) {
1578 if (nodeConnectorNames != null) {
1579 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1581 Node node = nodeConnector.getNode();
1582 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1583 if (mapCurr != null) {
1584 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1585 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1586 String s = entry.getKey();
1588 map.put(s, new NodeConnector(entry.getValue()));
1589 } catch (ConstructionException e) {
1590 log.error("An error occured",e);
1593 map.remove(name.getValue());
1594 if (map.isEmpty()) {
1595 nodeConnectorNames.remove(node);
1597 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1598 log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.",
1599 nodeConnector.getID());
1606 nodeConnectorProps.remove(nodeConnector);
1608 return new Status(StatusCode.SUCCESS);
1612 * Function called by the dependency manager when all the required
1613 * dependencies are satisfied
1616 void init(Component c) {
1617 Dictionary<?, ?> props = c.getServiceProperties();
1618 if (props != null) {
1619 this.containerName = (String) props.get("containerName");
1620 log.trace("Running containerName: {}", this.containerName);
1622 // In the Global instance case the containerName is empty
1623 this.containerName = "";
1625 isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT
1631 * Function called by the dependency manager when at least one dependency
1632 * become unsatisfied or when the component is shutting down because for
1633 * example bundle is being stopped.
1641 * Function called by dependency manager after "init ()" is called and after
1642 * the services provided by the class are registered in the service registry
1649 * Read startup and build database if we are the coordinator
1651 loadSubnetConfiguration();
1652 loadSpanConfiguration();
1653 loadSwitchConfiguration();
1656 registerWithOSGIConsole();
1660 * Function called after registered the service in OSGi service registry.
1663 // solicit for existing inventories
1668 * Function called by the dependency manager before the services exported by
1669 * the component are unregistered, this will be followed by a "destroy ()"
1676 public void setConfigurationContainerService(IConfigurationContainerService service) {
1677 log.trace("Got configuration service set request {}", service);
1678 this.configurationService = service;
1681 public void unsetConfigurationContainerService(IConfigurationContainerService service) {
1682 log.trace("Got configuration service UNset request");
1683 this.configurationService = null;
1686 public void setInventoryService(IInventoryService service) {
1687 log.trace("Got inventory service set request {}", service);
1688 this.inventoryService = service;
1690 // solicit for existing inventories
1694 public void unsetInventoryService(IInventoryService service) {
1695 log.trace("Got a service UNset request");
1696 this.inventoryService = null;
1698 // clear existing inventories
1702 public void setStatisticsManager(IStatisticsManager statisticsManager) {
1703 log.trace("Got statistics manager set request {}", statisticsManager);
1704 this.statisticsManager = statisticsManager;
1707 public void unsetStatisticsManager(IStatisticsManager statisticsManager) {
1708 log.trace("Got statistics manager UNset request");
1709 this.statisticsManager = null;
1712 public void setSwitchManagerAware(ISwitchManagerAware service) {
1713 log.trace("Got inventory service set request {}", service);
1714 if (this.switchManagerAware != null) {
1715 this.switchManagerAware.add(service);
1718 // bulk update for newly joined
1719 switchManagerAwareNotify(service);
1722 public void unsetSwitchManagerAware(ISwitchManagerAware service) {
1723 log.trace("Got a service UNset request");
1724 if (this.switchManagerAware != null) {
1725 this.switchManagerAware.remove(service);
1729 public void setInventoryListener(IInventoryListener service) {
1730 log.trace("Got inventory listener set request {}", service);
1731 if (this.inventoryListeners != null) {
1732 this.inventoryListeners.add(service);
1735 // bulk update for newly joined
1736 bulkUpdateService(service);
1739 public void unsetInventoryListener(IInventoryListener service) {
1740 log.trace("Got a service UNset request");
1741 if (this.inventoryListeners != null) {
1742 this.inventoryListeners.remove(service);
1746 public void setSpanAware(ISpanAware service) {
1747 log.trace("Got SpanAware set request {}", service);
1748 if (this.spanAware != null) {
1749 this.spanAware.add(service);
1752 // bulk update for newly joined
1753 spanAwareNotify(service);
1756 public void unsetSpanAware(ISpanAware service) {
1757 log.trace("Got a service UNset request");
1758 if (this.spanAware != null) {
1759 this.spanAware.remove(service);
1763 void setClusterContainerService(IClusterContainerServices s) {
1764 log.trace("Cluster Service set");
1765 this.clusterContainerService = s;
1768 void unsetClusterContainerService(IClusterContainerServices s) {
1769 if (this.clusterContainerService == s) {
1770 log.trace("Cluster Service removed!");
1771 this.clusterContainerService = null;
1775 private void getInventories() {
1776 if (inventoryService == null) {
1777 log.trace("inventory service not avaiable");
1781 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
1782 for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) {
1783 Node node = entry.getKey();
1784 log.debug("getInventories: {} added for container {}", new Object[] { node, containerName });
1785 Map<String, Property> propMap = entry.getValue();
1786 Set<Property> props = new HashSet<Property>();
1787 for (Property property : propMap.values()) {
1788 props.add(property);
1790 addNode(node, props);
1793 Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps();
1794 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) {
1795 Map<String, Property> propMap = entry.getValue();
1796 for (Property property : propMap.values()) {
1797 addNodeConnectorProp(entry.getKey(), property);
1802 private void clearInventories() {
1804 nodeConnectorProps.clear();
1805 nodeConnectorNames.clear();
1806 spanNodeConnectors.clear();
1809 private void notifyNode(Node node, UpdateType type,
1810 Map<String, Property> propMap) {
1811 synchronized (inventoryListeners) {
1812 for (IInventoryListener service : inventoryListeners) {
1813 service.notifyNode(node, type, propMap);
1818 private void notifyNodeConnector(NodeConnector nodeConnector,
1819 UpdateType type, Map<String, Property> propMap) {
1820 synchronized (inventoryListeners) {
1821 for (IInventoryListener service : inventoryListeners) {
1822 service.notifyNodeConnector(nodeConnector, type, propMap);
1828 * For those joined late, bring them up-to-date.
1830 private void switchManagerAwareNotify(ISwitchManagerAware service) {
1831 for (Subnet sub : subnets.values()) {
1832 service.subnetNotify(sub, true);
1835 for (Node node : getNodes()) {
1836 SwitchConfig sc = getSwitchConfig(node.toString());
1837 if ((sc != null) && isDefaultContainer) {
1838 ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
1839 service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive());
1844 private void bulkUpdateService(IInventoryListener service) {
1845 Map<String, Property> propMap;
1846 UpdateType type = UpdateType.ADDED;
1848 for (Node node : getNodes()) {
1849 propMap = nodeProps.get(node);
1850 service.notifyNode(node, type, propMap);
1853 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1854 NodeConnector nodeConnector = entry.getKey();
1855 propMap = nodeConnectorProps.get(nodeConnector);
1856 service.notifyNodeConnector(nodeConnector, type, propMap);
1860 private void spanAwareNotify(ISpanAware service) {
1861 for (Node node : getNodes()) {
1862 for (SpanConfig conf : getSpanConfigList(node)) {
1863 service.spanUpdate(node, conf.getPortArrayList(), true);
1868 private void registerWithOSGIConsole() {
1869 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
1870 .getBundleContext();
1871 bundleContext.registerService(CommandProvider.class.getName(), this,
1876 public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) {
1877 if (nodeConnector == null) {
1881 Config config = (Config) getNodeConnectorProp(nodeConnector,
1882 Config.ConfigPropName);
1883 State state = (State) getNodeConnectorProp(nodeConnector,
1884 State.StatePropName);
1885 return ((config != null) && (config.getValue() == Config.ADMIN_UP)
1886 && (state != null) && (state.getValue() == State.EDGE_UP));
1890 public boolean doesNodeConnectorExist(NodeConnector nc) {
1891 return (nc != null && nodeConnectorProps != null
1892 && nodeConnectorProps.containsKey(nc));
1896 public String getHelp() {
1897 StringBuffer help = new StringBuffer();
1898 help.append("---Switch Manager---\n");
1899 help.append("\t pencs <node id> - Print enabled node connectors for a given node\n");
1900 help.append("\t pdm <node id> - Print switch ports in device map\n");
1901 return help.toString();
1904 public void _pencs(CommandInterpreter ci) {
1905 String st = ci.nextArgument();
1907 ci.println("Please enter node id");
1911 Node node = Node.fromString(st);
1913 ci.println("Please enter node id");
1917 Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node);
1918 if (nodeConnectorSet == null) {
1921 for (NodeConnector nodeConnector : nodeConnectorSet) {
1922 if (nodeConnector == null) {
1925 ci.println(nodeConnector);
1927 ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1930 public void _pdm(CommandInterpreter ci) {
1931 String st = ci.nextArgument();
1933 ci.println("Please enter node id");
1937 Node node = Node.fromString(st);
1939 ci.println("Please enter node id");
1943 Switch sw = getSwitchByNode(node);
1945 ci.println(" NodeConnector Name");
1947 Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors();
1948 String nodeConnectorName;
1949 if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
1950 for (NodeConnector nodeConnector : nodeConnectorSet) {
1951 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1952 nodeConnectorName = (propMap == null) ? null : ((Name) propMap
1953 .get(Name.NamePropName)).getValue();
1954 if (nodeConnectorName != null) {
1955 Node nd = nodeConnector.getNode();
1956 if (!nd.equals(node)) {
1957 log.debug("node not match {} {}", nd, node);
1959 Map<String, NodeConnector> map = nodeConnectorNames
1962 NodeConnector nc = map.get(nodeConnectorName);
1964 log.debug("no nodeConnector named {}",
1966 } else if (!nc.equals(nodeConnector)) {
1967 log.debug("nodeConnector not match {} {}", nc,
1973 ci.println(nodeConnector
1975 + ((nodeConnectorName == null) ? "" : nodeConnectorName)
1976 + "(" + nodeConnector.getID() + ")");
1978 ci.println("Total number of NodeConnectors: "
1979 + nodeConnectorSet.size());
1984 public byte[] getNodeMAC(Node node) {
1985 MacAddress mac = (MacAddress) this.getNodeProp(node,
1987 return (mac != null) ? mac.getMacAddress() : null;
1991 public boolean isSpecial(NodeConnector p) {
1992 if (p.getType().equals(NodeConnectorIDType.CONTROLLER)
1993 || p.getType().equals(NodeConnectorIDType.ALL)
1994 || p.getType().equals(NodeConnectorIDType.SWSTACK)
1995 || p.getType().equals(NodeConnectorIDType.HWPATH)) {
2002 * Add span configuration to local cache and notify clients
2004 private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2005 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2007 for (NodeConnector nodeConnector : nodeConnectors) {
2008 if (!spanNodeConnectors.contains(nodeConnector)) {
2009 ncLists.add(nodeConnector);
2013 if (ncLists.size() > 0) {
2014 spanNodeConnectors.addAll(ncLists);
2015 notifySpanPortChange(node, ncLists, true);
2019 private void addSpanPorts(Node node) {
2020 for (SpanConfig conf : getSpanConfigList(node)) {
2021 addSpanPorts(node, conf.getPortArrayList());
2025 private void addSpanPort(NodeConnector nodeConnector) {
2026 // only add if span is configured on this nodeConnector
2027 for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) {
2028 if (conf.getPortArrayList().contains(nodeConnector)) {
2029 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2030 ncLists.add(nodeConnector);
2031 addSpanPorts(nodeConnector.getNode(), ncLists);
2038 * Remove span configuration to local cache and notify clients
2040 private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2041 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2043 for (NodeConnector nodeConnector : nodeConnectors) {
2044 if (spanNodeConnectors.contains(nodeConnector)) {
2045 ncLists.add(nodeConnector);
2049 if (ncLists.size() > 0) {
2050 spanNodeConnectors.removeAll(ncLists);
2051 notifySpanPortChange(node, ncLists, false);
2055 private void removeSpanPorts(Node node) {
2056 for (SpanConfig conf : getSpanConfigList(node)) {
2057 addSpanPorts(node, conf.getPortArrayList());
2061 private void removeSpanPort(NodeConnector nodeConnector) {
2062 if (spanNodeConnectors.contains(nodeConnector)) {
2063 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2064 ncLists.add(nodeConnector);
2065 removeSpanPorts(nodeConnector.getNode(), ncLists);
2069 private void addNodeProps(Node node, Map<String, Property> propMap) {
2070 if (propMap == null) {
2071 propMap = new HashMap<String, Property>();
2073 nodeProps.put(node, propMap);
2077 public Status saveConfiguration() {
2078 return saveSwitchConfig();
2082 * Creates a Name/Tier/Bandwidth/MacAddress(controller property) Property
2083 * object based on given property name and value. Other property types are
2084 * not supported yet.
2087 * Name of the Property
2089 * Value of the Property
2090 * @return {@link org.opendaylight.controller.sal.core.Property}
2093 public Property createProperty(String propName, String propValue) {
2094 if (propName == null) {
2095 log.debug("propName is null");
2098 if (propValue == null) {
2099 log.debug("propValue is null");
2104 if (propName.equalsIgnoreCase(Description.propertyName)) {
2105 return new Description(propValue);
2106 } else if (propName.equalsIgnoreCase(Tier.TierPropName)) {
2107 int tier = Integer.parseInt(propValue);
2108 return new Tier(tier);
2109 } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) {
2110 long bw = Long.parseLong(propValue);
2111 return new Bandwidth(bw);
2112 } else if (propName.equalsIgnoreCase(ForwardingMode.name)) {
2113 int mode = Integer.parseInt(propValue);
2114 return new ForwardingMode(mode);
2115 } else if (propName.equalsIgnoreCase(MacAddress.name)){
2116 return new MacAddress(propValue);
2119 log.debug("Not able to create {} property", propName);
2121 } catch (Exception e) {
2122 log.debug("createProperty caught exception {}", e.getMessage());
2129 @SuppressWarnings("deprecation")
2131 public String getNodeDescription(Node node) {
2132 // Check first if user configured a name
2133 SwitchConfig config = getSwitchConfig(node.toString());
2134 if (config != null) {
2135 String configuredDesc = config.getNodeDescription();
2136 if (configuredDesc != null && !configuredDesc.isEmpty()) {
2137 return configuredDesc;
2141 // No name configured by user, get the node advertised name
2142 Description desc = (Description) getNodeProp(node,
2143 Description.propertyName);
2144 return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? ""
2149 public Set<Switch> getConfiguredNotConnectedSwitches() {
2150 Set<Switch> configuredNotConnectedSwitches = new HashSet<Switch>();
2151 if (this.inventoryService == null) {
2152 log.trace("inventory service not avaiable");
2153 return configuredNotConnectedSwitches;
2156 Set<Node> configuredNotConnectedNodes = this.inventoryService.getConfiguredNotConnectedNodes();
2157 if (configuredNotConnectedNodes != null) {
2158 for (Node node : configuredNotConnectedNodes) {
2159 Switch sw = getSwitchByNode(node);
2160 configuredNotConnectedSwitches.add(sw);
2163 return configuredNotConnectedSwitches;