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 static boolean hostRefresh = true;
110 private int hostRetryCount = 5;
111 private IClusterContainerServices clusterContainerService = null;
112 private String containerName = null;
113 private boolean isDefaultContainer = true;
114 private static final int REPLACE_RETRY = 1;
116 public void notifySubnetChange(Subnet sub, boolean add) {
117 synchronized (switchManagerAware) {
118 for (Object subAware : switchManagerAware) {
120 ((ISwitchManagerAware) subAware).subnetNotify(sub, add);
121 } catch (Exception e) {
122 log.error("Failed to notify Subnet change {}",
129 public void notifySpanPortChange(Node node, List<NodeConnector> ports, boolean add) {
130 synchronized (spanAware) {
131 for (Object sa : spanAware) {
133 ((ISpanAware) sa).spanUpdate(node, ports, add);
134 } catch (Exception e) {
135 log.error("Failed to notify Span Interface change {}",
142 private void notifyModeChange(Node node, boolean proactive) {
143 synchronized (switchManagerAware) {
144 for (ISwitchManagerAware service : switchManagerAware) {
146 service.modeChangeNotify(node, proactive);
147 } catch (Exception e) {
148 log.error("Failed to notify Subnet change {}",
155 public void startUp() {
156 String container = this.getContainerName();
157 // Initialize configuration file names
158 subnetFileName = ROOT + "subnets_" + container + ".conf";
159 spanFileName = ROOT + "spanPorts_" + container + ".conf";
160 switchConfigFileName = ROOT + "switchConfig_" + container + ".conf";
162 // Instantiate cluster synced variables
167 * Read startup and build database if we have not already gotten the
168 * configurations synced from another node
170 if (subnetsConfigList.isEmpty()) {
171 loadSubnetConfiguration();
173 if (spanConfigList.isEmpty()) {
174 loadSpanConfiguration();
176 if (nodeConfigList.isEmpty()) {
177 loadSwitchConfiguration();
180 // Add controller MAC, if first node in the cluster
181 if (!controllerProps.containsKey(MacAddress.name)) {
182 byte controllerMac[] = getHardwareMAC();
183 if (controllerMac != null) {
184 Property existing = controllerProps.putIfAbsent(MacAddress.name, new MacAddress(controllerMac));
185 if (existing == null && log.isTraceEnabled()) {
186 log.trace("Container {}: Setting controller MAC address in the cluster: {}", container,
187 HexEncode.bytesToHexStringFormat(controllerMac));
193 public void shutDown() {
196 private void allocateCaches() {
197 if (this.clusterContainerService == null) {
198 this.nonClusterObjectCreate();
199 log.warn("un-initialized clusterContainerService, can't create cache");
204 clusterContainerService.createCache(
205 "switchmanager.subnetsConfigList",
206 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
207 clusterContainerService.createCache("switchmanager.spanConfigList",
208 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
209 clusterContainerService.createCache("switchmanager.nodeConfigList",
210 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
211 clusterContainerService.createCache("switchmanager.subnets",
212 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
213 clusterContainerService.createCache("switchmanager.nodeProps",
214 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
215 clusterContainerService.createCache(
216 "switchmanager.nodeConnectorProps",
217 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
218 clusterContainerService.createCache(
219 "switchmanager.nodeConnectorNames",
220 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
221 clusterContainerService.createCache(
222 "switchmanager.controllerProps",
223 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
224 } catch (CacheConfigException cce) {
225 log.error("\nCache configuration invalid - check cache mode");
226 } catch (CacheExistException ce) {
227 log.error("\nCache already exits - destroy and recreate if needed");
231 @SuppressWarnings({ "unchecked" })
232 private void retrieveCaches() {
233 if (this.clusterContainerService == null) {
234 log.info("un-initialized clusterContainerService, can't create cache");
238 subnetsConfigList = (ConcurrentMap<String, SubnetConfig>) clusterContainerService
239 .getCache("switchmanager.subnetsConfigList");
240 if (subnetsConfigList == null) {
241 log.error("\nFailed to get cache for subnetsConfigList");
244 spanConfigList = (ConcurrentMap<SpanConfig, SpanConfig>) clusterContainerService
245 .getCache("switchmanager.spanConfigList");
246 if (spanConfigList == null) {
247 log.error("\nFailed to get cache for spanConfigList");
250 nodeConfigList = (ConcurrentMap<String, SwitchConfig>) clusterContainerService
251 .getCache("switchmanager.nodeConfigList");
252 if (nodeConfigList == null) {
253 log.error("\nFailed to get cache for nodeConfigList");
256 subnets = (ConcurrentMap<InetAddress, Subnet>) clusterContainerService
257 .getCache("switchmanager.subnets");
258 if (subnets == null) {
259 log.error("\nFailed to get cache for subnets");
262 nodeProps = (ConcurrentMap<Node, Map<String, Property>>) clusterContainerService
263 .getCache("switchmanager.nodeProps");
264 if (nodeProps == null) {
265 log.error("\nFailed to get cache for nodeProps");
268 nodeConnectorProps = (ConcurrentMap<NodeConnector, Map<String, Property>>) clusterContainerService
269 .getCache("switchmanager.nodeConnectorProps");
270 if (nodeConnectorProps == null) {
271 log.error("\nFailed to get cache for nodeConnectorProps");
274 nodeConnectorNames = (ConcurrentMap<Node, Map<String, NodeConnector>>) clusterContainerService
275 .getCache("switchmanager.nodeConnectorNames");
276 if (nodeConnectorNames == null) {
277 log.error("\nFailed to get cache for nodeConnectorNames");
280 controllerProps = (ConcurrentMap<String, Property>) clusterContainerService
281 .getCache("switchmanager.controllerProps");
282 if (controllerProps == null) {
283 log.error("\nFailed to get cache for controllerProps");
287 private void nonClusterObjectCreate() {
288 subnetsConfigList = new ConcurrentHashMap<String, SubnetConfig>();
289 spanConfigList = new ConcurrentHashMap<SpanConfig, SpanConfig>();
290 nodeConfigList = new ConcurrentHashMap<String, SwitchConfig>();
291 subnets = new ConcurrentHashMap<InetAddress, Subnet>();
292 nodeProps = new ConcurrentHashMap<Node, Map<String, Property>>();
293 nodeConnectorProps = new ConcurrentHashMap<NodeConnector, Map<String, Property>>();
294 nodeConnectorNames = new ConcurrentHashMap<Node, Map<String, NodeConnector>>();
295 controllerProps = new ConcurrentHashMap<String, Property>();
299 public List<SubnetConfig> getSubnetsConfigList() {
300 return new ArrayList<SubnetConfig>(subnetsConfigList.values());
304 public SubnetConfig getSubnetConfig(String subnet) {
305 return subnetsConfigList.get(subnet);
308 private List<SpanConfig> getSpanConfigList(Node node) {
309 List<SpanConfig> confList = new ArrayList<SpanConfig>();
310 String nodeId = node.toString();
311 for (SpanConfig conf : spanConfigList.values()) {
312 if (conf.matchNode(nodeId)) {
319 public List<SwitchConfig> getNodeConfigList() {
320 return new ArrayList<SwitchConfig>(nodeConfigList.values());
324 public SwitchConfig getSwitchConfig(String switchId) {
325 return nodeConfigList.get(switchId);
328 public Switch getSwitchByNode(Node node) {
329 Switch sw = new Switch(node);
331 MacAddress mac = (MacAddress) this.getNodeProp(node,
334 sw.setDataLayerAddress(mac.getMacAddress());
336 Set<NodeConnector> ncSet = getPhysicalNodeConnectors(node);
337 sw.setNodeConnectors(ncSet);
339 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
340 for (NodeConnector nodeConnector : ncSet) {
341 if (spanNodeConnectors.contains(nodeConnector)) {
342 ncList.add(nodeConnector);
345 sw.addSpanPorts(ncList);
351 public List<Switch> getNetworkDevices() {
352 Set<Node> nodeSet = getNodes();
353 List<Switch> swList = new ArrayList<Switch>();
354 if (nodeSet != null) {
355 for (Node node : nodeSet) {
356 swList.add(getSwitchByNode(node));
363 private Status updateConfig(SubnetConfig conf, boolean add) {
365 if(subnetsConfigList.putIfAbsent(conf.getName(), conf) != null) {
366 String msg = "Cluster conflict: Subnet with name " + conf.getName() + "already exists.";
367 return new Status(StatusCode.CONFLICT, msg);
370 subnetsConfigList.remove(conf.getName());
372 return new Status(StatusCode.SUCCESS);
375 private Status updateDatabase(SubnetConfig conf, boolean add) {
377 Subnet subnetCurr = subnets.get(conf.getIPAddress());
379 if (subnetCurr == null) {
380 subnet = new Subnet(conf);
382 subnet = subnetCurr.clone();
384 // In case of API3 call we may receive the ports along with the
386 if (!conf.isGlobal()) {
387 subnet.addNodeConnectors(conf.getNodeConnectors());
389 boolean putNewSubnet = false;
390 if(subnetCurr == null) {
391 if(subnets.putIfAbsent(conf.getIPAddress(), subnet) == null) {
395 putNewSubnet = subnets.replace(conf.getIPAddress(), subnetCurr, subnet);
398 String msg = "Cluster conflict: Conflict while adding the subnet " + conf.getIPAddress();
399 return new Status(StatusCode.CONFLICT, msg);
402 // Subnet removal case
404 subnets.remove(conf.getIPAddress());
406 return new Status(StatusCode.SUCCESS);
409 private Status semanticCheck(SubnetConfig conf) {
410 Subnet newSubnet = new Subnet(conf);
411 Set<InetAddress> IPs = subnets.keySet();
413 return new Status(StatusCode.SUCCESS);
415 for (InetAddress i : IPs) {
416 Subnet existingSubnet = subnets.get(i);
417 if ((existingSubnet != null)
418 && !existingSubnet.isMutualExclusive(newSubnet)) {
419 return new Status(StatusCode.CONFLICT);
422 return new Status(StatusCode.SUCCESS);
425 private Status addRemoveSubnet(SubnetConfig conf, boolean isAdding) {
426 // Valid configuration check
427 Status status = conf.validate();
428 if (!status.isSuccess()) {
429 log.warn(status.getDescription());
435 if (subnetsConfigList.containsKey(conf.getName())) {
436 return new Status(StatusCode.CONFLICT,
437 "Subnet with the specified name already configured.");
440 status = semanticCheck(conf);
441 if (!status.isSuccess()) {
447 status = updateDatabase(conf, isAdding);
449 if (status.isSuccess()) {
450 // Update Configuration
451 status = updateConfig(conf, isAdding);
452 if(!status.isSuccess()) {
453 updateDatabase(conf, (!isAdding));
461 * Adds Subnet configured in GUI or API3
464 public Status addSubnet(SubnetConfig conf) {
465 return this.addRemoveSubnet(conf, true);
469 public Status removeSubnet(SubnetConfig conf) {
470 return this.addRemoveSubnet(conf, false);
474 public Status removeSubnet(String name) {
475 SubnetConfig conf = subnetsConfigList.get(name);
477 return new Status(StatusCode.SUCCESS, "Subnet not present");
479 return this.addRemoveSubnet(conf, false);
483 public Status modifySubnet(SubnetConfig conf) {
486 return new Status(StatusCode.BADREQUEST, "Invalid Subnet configuration: null");
489 // Valid configuration check
490 Status status = conf.validate();
491 if (!status.isSuccess()) {
492 log.warn(status.getDescription());
496 // If a subnet configuration with this name does not exist, consider this is a creation
497 SubnetConfig target = subnetsConfigList.get(conf.getName());
498 if (target == null) {
499 return this.addSubnet(conf);
503 if (target.equals(conf)) {
504 return new Status(StatusCode.SUCCESS);
507 // Check not allowed modifications
508 if (!target.getSubnet().equals(conf.getSubnet())) {
509 return new Status(StatusCode.BADREQUEST, "IP address change is not allowed");
512 // Derive the set of node connectors that are being removed
513 Set<NodeConnector> toRemove = target.getNodeConnectors();
514 toRemove.removeAll(conf.getNodeConnectors());
515 List<String> nodeConnectorStrings = null;
516 if (!toRemove.isEmpty()) {
517 nodeConnectorStrings = new ArrayList<String>();
518 for (NodeConnector nc : toRemove) {
519 nodeConnectorStrings.add(nc.toString());
521 status = this.removePortsFromSubnet(conf.getName(), nodeConnectorStrings);
522 if (!status.isSuccess()) {
527 // Derive the set of node connectors that are being added
528 Set<NodeConnector> toAdd = conf.getNodeConnectors();
529 toAdd.removeAll(target.getNodeConnectors());
530 if (!toAdd.isEmpty()) {
531 List<String> nodeConnectorStringRemoved = nodeConnectorStrings;
532 nodeConnectorStrings = new ArrayList<String>();
533 for (NodeConnector nc : toAdd) {
534 nodeConnectorStrings.add(nc.toString());
536 status = this.addPortsToSubnet(conf.getName(), nodeConnectorStrings);
537 if (!status.isSuccess()) {
538 // If any port was removed, add it back as a best recovery effort
539 if (!toRemove.isEmpty()) {
540 this.addPortsToSubnet(conf.getName(), nodeConnectorStringRemoved);
546 // Update Configuration
547 subnetsConfigList.put(conf.getName(), conf);
549 return new Status(StatusCode.SUCCESS);
553 public Status addPortsToSubnet(String name, List<String> switchPorts) {
555 return new Status(StatusCode.BADREQUEST, "Null subnet name");
557 SubnetConfig confCurr = subnetsConfigList.get(name);
558 if (confCurr == null) {
559 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
562 if (switchPorts == null || switchPorts.isEmpty()) {
563 return new Status(StatusCode.BADREQUEST, "Null or empty port set");
566 Subnet subCurr = subnets.get(confCurr.getIPAddress());
567 if (subCurr == null) {
568 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress());
569 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
573 Subnet sub = subCurr.clone();
574 Set<NodeConnector> sp = NodeConnector.fromString(switchPorts);
575 sub.addNodeConnectors(sp);
576 boolean subnetsReplaced = subnets.replace(confCurr.getIPAddress(), subCurr, sub);
577 if (!subnetsReplaced) {
578 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
579 return new Status(StatusCode.CONFLICT, msg);
582 // Update Configuration
583 SubnetConfig conf = confCurr.clone();
584 conf.addNodeConnectors(switchPorts);
585 boolean configReplaced = subnetsConfigList.replace(name, confCurr, conf);
586 if (!configReplaced) {
587 // TODO: recovery using Transactionality
588 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
589 return new Status(StatusCode.CONFLICT, msg);
592 return new Status(StatusCode.SUCCESS);
596 public Status removePortsFromSubnet(String name, List<String> switchPorts) {
598 return new Status(StatusCode.BADREQUEST, "Null subnet name");
600 SubnetConfig confCurr = subnetsConfigList.get(name);
601 if (confCurr == null) {
602 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
605 if (switchPorts == null || switchPorts.isEmpty()) {
606 return new Status(StatusCode.BADREQUEST, "Null or empty port set");
609 Subnet subCurr = subnets.get(confCurr.getIPAddress());
610 if (subCurr == null) {
611 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress());
612 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
616 Status status = SubnetConfig.validatePorts(switchPorts);
617 if (!status.isSuccess()) {
621 Subnet sub = subCurr.clone();
622 Set<NodeConnector> sp = NodeConnector.fromString(switchPorts);
623 sub.deleteNodeConnectors(sp);
624 boolean subnetsReplace = subnets.replace(confCurr.getIPAddress(), subCurr, sub);
625 if (!subnetsReplace) {
626 String msg = "Cluster conflict: Conflict while removing ports from the subnet " + name;
627 return new Status(StatusCode.CONFLICT, msg);
630 // Update Configuration
631 SubnetConfig conf = confCurr.clone();
632 conf.removeNodeConnectors(switchPorts);
633 boolean result = subnetsConfigList.replace(name, confCurr, conf);
635 // TODO: recovery using Transactionality
636 String msg = "Cluster conflict: Conflict while removing ports from " + conf;
637 return new Status(StatusCode.CONFLICT, msg);
640 return new Status(StatusCode.SUCCESS);
643 public String getContainerName() {
644 if (containerName == null) {
645 return GlobalConstants.DEFAULT.toString();
647 return containerName;
651 public Subnet getSubnetByNetworkAddress(InetAddress networkAddress) {
653 Set<InetAddress> indices = subnets.keySet();
654 for (InetAddress i : indices) {
655 sub = subnets.get(i);
656 if (sub.isSubnetOf(networkAddress)) {
664 public Object readObject(ObjectInputStream ois)
665 throws FileNotFoundException, IOException, ClassNotFoundException {
666 // Perform the class deserialization locally, from inside the package
667 // where the class is defined
668 return ois.readObject();
671 @SuppressWarnings("unchecked")
672 private void loadSubnetConfiguration() {
673 ObjectReader objReader = new ObjectReader();
674 ConcurrentMap<String, SubnetConfig> confList = (ConcurrentMap<String, SubnetConfig>) objReader
675 .read(this, subnetFileName);
677 if (confList == null) {
681 for (SubnetConfig conf : confList.values()) {
686 @SuppressWarnings("unchecked")
687 private void loadSpanConfiguration() {
688 ObjectReader objReader = new ObjectReader();
689 ConcurrentMap<Integer, SpanConfig> confList = (ConcurrentMap<Integer, SpanConfig>) objReader
690 .read(this, spanFileName);
692 if (confList == null) {
696 for (SpanConfig conf : confList.values()) {
701 @SuppressWarnings("unchecked")
702 private void loadSwitchConfiguration() {
703 ObjectReader objReader = new ObjectReader();
704 ConcurrentMap<String, SwitchConfig> confList = (ConcurrentMap<String, SwitchConfig>) objReader
705 .read(this, switchConfigFileName);
707 if (confList == null) {
711 for (SwitchConfig conf : confList.values()) {
712 updateNodeConfig(conf);
716 @SuppressWarnings("deprecation")
718 public void updateSwitchConfig(SwitchConfig cfgObject) {
719 // update default container only
720 if (!isDefaultContainer) {
724 SwitchConfig sc = nodeConfigList.get(cfgObject.getNodeId());
726 if (nodeConfigList.putIfAbsent(cfgObject.getNodeId(), cfgObject) != null) {
730 if (!nodeConfigList.replace(cfgObject.getNodeId(), sc, cfgObject)) {
735 boolean modeChange = false;
737 if ((sc == null) || !cfgObject.getMode().equals(sc.getMode())) {
741 String nodeId = cfgObject.getNodeId();
742 Node node = Node.fromString(nodeId);
743 Map<String, Property> propMapCurr = nodeProps.get(node);
744 if (propMapCurr == null) {
747 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
748 Property desc = new Description(cfgObject.getNodeDescription());
749 propMap.put(desc.getName(), desc);
750 Property tier = new Tier(Integer.parseInt(cfgObject.getTier()));
751 propMap.put(tier.getName(), tier);
753 if (!nodeProps.replace(node, propMapCurr, propMap)) {
754 // TODO rollback using Transactionality
758 log.info("Set Node {}'s Mode to {}", nodeId, cfgObject.getMode());
761 notifyModeChange(node, cfgObject.isProactive());
766 public Status updateNodeConfig(SwitchConfig switchConfig) {
767 Status status = switchConfig.validate();
768 if (!status.isSuccess()) {
772 Map<String, Property> updateProperties = switchConfig.getNodeProperties();
773 ForwardingMode mode = (ForwardingMode) updateProperties.get(ForwardingMode.name);
775 if (isDefaultContainer) {
776 if (!mode.isValid()) {
777 return new Status(StatusCode.BADREQUEST, "Invalid Forwarding Mode Value");
780 return new Status(StatusCode.NOTACCEPTABLE,
781 "Forwarding Mode modification is allowed only in default container");
785 Description description = (Description) switchConfig.getProperty(Description.propertyName);
786 String nodeId = switchConfig.getNodeId();
787 Node node = Node.fromString(nodeId);
788 NodeDescription nodeDesc = (this.statisticsManager == null) ? null : this.statisticsManager
789 .getNodeDescription(node);
790 String advertisedDesc = (nodeDesc == null) ? "" : nodeDesc.getDescription();
791 if (description != null && description.getValue() != null) {
792 if (description.getValue().isEmpty() || description.getValue().equals(advertisedDesc)) {
793 updateProperties.remove(Description.propertyName);
794 switchConfig = new SwitchConfig(nodeId, updateProperties);
796 // check if description is configured or was published by any other node
797 for (Map.Entry<Node, Map<String, Property>> entry : nodeProps.entrySet()) {
798 Node n = entry.getKey();
799 Description desc = (Description) getNodeProp(n, Description.propertyName);
800 NodeDescription nDesc = (this.statisticsManager == null) ? null : this.statisticsManager
801 .getNodeDescription(n);
802 String advDesc = (nDesc == null) ? "" : nDesc.getDescription();
803 if ((description.equals(desc) || description.getValue().equals(advDesc)) && !node.equals(n)) {
804 return new Status(StatusCode.CONFLICT, "Node name already in use");
810 boolean modeChange = false;
811 SwitchConfig sc = nodeConfigList.get(nodeId);
812 Map<String, Property> prevNodeProperties = new HashMap<String, Property>();
814 if ((mode != null) && mode.isProactive()) {
817 if (!updateProperties.isEmpty()) {
818 if (nodeConfigList.putIfAbsent(nodeId, switchConfig) != null) {
819 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
823 prevNodeProperties = new HashMap<String, Property>(sc.getNodeProperties());
824 ForwardingMode prevMode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
826 if ((prevMode != null) && (prevMode.isProactive())) {
830 if (((prevMode != null) && (prevMode.getValue() != mode.getValue()))
831 || (prevMode == null && mode.isProactive())) {
835 if (updateProperties.isEmpty()) {
836 nodeConfigList.remove(nodeId);
838 if (!nodeConfigList.replace(nodeId, sc, switchConfig)) {
839 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
843 Map<String, Property> propMapCurr = nodeProps.get(node);
844 if (propMapCurr == null) {
845 return new Status(StatusCode.SUCCESS);
847 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
848 for (Map.Entry<String, Property> entry : prevNodeProperties.entrySet()) {
849 String prop = entry.getKey();
850 if (!updateProperties.containsKey(prop)) {
851 if (prop.equals(Description.propertyName)) {
852 if (!advertisedDesc.isEmpty()) {
853 Property desc = new Description(advertisedDesc);
854 propMap.put(Description.propertyName, desc);
857 } else if (prop.equals(ForwardingMode.name)) {
858 Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING);
859 propMap.put(ForwardingMode.name, defaultMode);
862 propMap.remove(prop);
865 propMap.putAll(updateProperties);
866 if (!nodeProps.replace(node, propMapCurr, propMap)) {
867 // TODO rollback using Transactionality
868 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
871 notifyModeChange(node, (mode == null) ? false : mode.isProactive());
873 return new Status(StatusCode.SUCCESS);
877 public Status removeNodeConfig(String nodeId) {
878 if ((nodeId == null) || (nodeId.isEmpty())) {
879 return new Status(StatusCode.BADREQUEST, "nodeId cannot be empty.");
881 Map<String, Property> nodeProperties = getSwitchConfig(nodeId).getNodeProperties();
882 Node node = Node.fromString(nodeId);
883 Map<String, Property> propMapCurr = nodeProps.get(node);
884 if ((propMapCurr != null) && (nodeProperties != null) && (!nodeProperties.isEmpty())) {
885 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
886 for (Map.Entry<String, Property> entry : nodeProperties.entrySet()) {
887 String prop = entry.getKey();
888 if (prop.equals(Description.propertyName)) {
889 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
890 if (nodeProp.get(node) != null) {
891 propMap.put(Description.propertyName, nodeProp.get(node).get(Description.propertyName));
895 propMap.remove(prop);
897 if (!nodeProps.replace(node, propMapCurr, propMap)) {
898 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration.");
901 if (nodeConfigList != null) {
902 nodeConfigList.remove(nodeId);
904 return new Status(StatusCode.SUCCESS);
908 public Status saveSwitchConfig() {
909 return saveSwitchConfigInternal();
912 public Status saveSwitchConfigInternal() {
913 Status retS = null, retP = null;
914 ObjectWriter objWriter = new ObjectWriter();
916 retS = objWriter.write(new ConcurrentHashMap<String, SubnetConfig>(
917 subnetsConfigList), subnetFileName);
918 retP = objWriter.write(new ConcurrentHashMap<SpanConfig, SpanConfig>(
919 spanConfigList), spanFileName);
920 retS = objWriter.write(new ConcurrentHashMap<String, SwitchConfig>(
921 nodeConfigList), switchConfigFileName);
922 if (retS.equals(retP)) {
923 if (retS.isSuccess()) {
926 return new Status(StatusCode.INTERNALERROR, "Save failed");
929 return new Status(StatusCode.INTERNALERROR, "Partial save failure");
934 public List<SpanConfig> getSpanConfigList() {
935 return new ArrayList<SpanConfig>(spanConfigList.values());
939 public Status addSpanConfig(SpanConfig conf) {
940 // Valid config check
941 if (!conf.isValidConfig()) {
942 String msg = "Invalid Span configuration";
944 return new Status(StatusCode.BADREQUEST, msg);
948 if (spanConfigList.containsKey(conf)) {
949 return new Status(StatusCode.CONFLICT, "Same span config exists");
952 // Update configuration
953 if (spanConfigList.putIfAbsent(conf, conf) == null) {
954 // Update database and notify clients
955 addSpanPorts(conf.getNode(), conf.getPortArrayList());
958 return new Status(StatusCode.SUCCESS);
962 public Status removeSpanConfig(SpanConfig conf) {
963 removeSpanPorts(conf.getNode(), conf.getPortArrayList());
965 // Update configuration
966 spanConfigList.remove(conf);
968 return new Status(StatusCode.SUCCESS);
972 public List<NodeConnector> getSpanPorts(Node node) {
973 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
975 for (NodeConnector nodeConnector : spanNodeConnectors) {
976 if (nodeConnector.getNode().equals(node)) {
977 ncList.add(nodeConnector);
983 private void addNode(Node node, Set<Property> props) {
984 log.trace("{} added, props: {}", node, props);
985 if (nodeProps == null) {
989 Map<String, Property> propMapCurr = nodeProps.get(node);
990 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
991 : new HashMap<String, Property>(propMapCurr);
993 // copy node properties from plugin
995 for (Property prop : props) {
996 propMap.put(prop.getName(), prop);
1000 boolean proactiveForwarding = false;
1001 // copy node properties from config
1002 if (nodeConfigList != null) {
1003 String nodeId = node.toString();
1004 SwitchConfig conf = nodeConfigList.get(nodeId);
1005 if (conf != null && (conf.getNodeProperties() != null)) {
1006 Map<String, Property> nodeProperties = conf.getNodeProperties();
1007 propMap.putAll(nodeProperties);
1008 if (nodeProperties.get(ForwardingMode.name) != null) {
1009 ForwardingMode mode = (ForwardingMode) nodeProperties.get(ForwardingMode.name);
1010 proactiveForwarding = mode.isProactive();
1015 if (!propMap.containsKey(ForwardingMode.name)) {
1016 Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING);
1017 propMap.put(ForwardingMode.name, defaultMode);
1019 boolean result = false;
1020 if (propMapCurr == null) {
1021 if (nodeProps.putIfAbsent(node, propMap) == null) {
1025 result = nodeProps.replace(node, propMapCurr, propMap);
1028 log.debug("Cluster conflict: Conflict while adding the node properties. Node: {} Properties: {}",
1029 node.getID(), props);
1030 addNodeProps(node, propMap);
1033 // check if span ports are configed
1036 // notify node listeners
1037 notifyNode(node, UpdateType.ADDED, propMap);
1039 // notify proactive mode forwarding
1040 if (proactiveForwarding) {
1041 notifyModeChange(node, true);
1045 private void removeNode(Node node) {
1046 log.trace("{} removed", node);
1047 if (nodeProps == null) {
1050 nodeProps.remove(node);
1051 nodeConnectorNames.remove(node);
1052 Set<NodeConnector> removeNodeConnectorSet = new HashSet<NodeConnector>();
1053 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1054 NodeConnector nodeConnector = entry.getKey();
1055 if (nodeConnector.getNode().equals(node)) {
1056 removeNodeConnectorSet.add(nodeConnector);
1059 for (NodeConnector nc : removeNodeConnectorSet) {
1060 nodeConnectorProps.remove(nc);
1063 // check if span ports need to be cleaned up
1064 removeSpanPorts(node);
1066 /* notify node listeners */
1067 notifyNode(node, UpdateType.REMOVED, null);
1070 private void updateNode(Node node, Set<Property> props) {
1071 log.trace("{} updated, props: {}", node, props);
1072 if (nodeProps == null || !nodeProps.containsKey(node) ||
1073 props == null || props.isEmpty()) {
1077 Map<String, Property> propMapCurr = nodeProps.get(node);
1078 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1079 : new HashMap<String, Property>(propMapCurr);
1081 // copy node properties from plugin
1082 String nodeId = node.toString();
1083 for (Property prop : props) {
1084 if (nodeConfigList != null) {
1085 SwitchConfig conf = nodeConfigList.get(nodeId);
1086 if (conf != null && (conf.getNodeProperties() != null)
1087 && conf.getNodeProperties().containsKey(prop.getName())) {
1091 propMap.put(prop.getName(), prop);
1094 if (propMapCurr == null) {
1095 if (nodeProps.putIfAbsent(node, propMap) != null) {
1096 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1097 node.getID(), props);
1098 addNodeProps(node, propMap);
1101 if (!nodeProps.replace(node, propMapCurr, propMap)) {
1102 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1103 node.getID(), props);
1104 addNodeProps(node, propMap);
1108 /* notify node listeners */
1109 notifyNode(node, UpdateType.CHANGED, propMap);
1113 public void updateNode(Node node, UpdateType type, Set<Property> props) {
1114 log.debug("updateNode: {} type {} props {} for container {}",
1115 new Object[] { node, type, props, containerName });
1118 addNode(node, props);
1121 updateNode(node, props);
1132 public void updateNodeConnector(NodeConnector nodeConnector,
1133 UpdateType type, Set<Property> props) {
1134 Map<String, Property> propMap = new HashMap<String, Property>();
1135 boolean update = true;
1137 log.debug("updateNodeConnector: {} type {} props {} for container {}",
1138 new Object[] { nodeConnector, type, props, containerName });
1140 if (nodeConnectorProps == null) {
1146 if (props != null) {
1147 for (Property prop : props) {
1148 addNodeConnectorProp(nodeConnector, prop);
1149 propMap.put(prop.getName(), prop);
1152 addNodeConnectorProp(nodeConnector, null);
1155 addSpanPort(nodeConnector);
1158 if (!nodeConnectorProps.containsKey(nodeConnector) || (props == null)) {
1161 for (Property prop : props) {
1162 addNodeConnectorProp(nodeConnector, prop);
1163 propMap.put(prop.getName(), prop);
1168 if (!nodeConnectorProps.containsKey(nodeConnector)) {
1171 removeNodeConnectorAllProps(nodeConnector);
1173 // clean up span config
1174 removeSpanPort(nodeConnector);
1182 notifyNodeConnector(nodeConnector, type, propMap);
1187 public Set<Node> getNodes() {
1188 return (nodeProps != null) ? new HashSet<Node>(nodeProps.keySet())
1189 : new HashSet<Node>();
1193 * Returns a copy of a list of properties for a given node
1198 * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps
1199 * (org.opendaylight.controller.sal.core.Node)
1202 public Map<String, Property> getNodeProps(Node node) {
1203 Map<String, Property> rv = new HashMap<String, Property>();
1204 if (this.nodeProps != null) {
1205 rv = this.nodeProps.get(node);
1207 /* make a copy of it */
1208 rv = new HashMap<String, Property>(rv);
1215 public Property getNodeProp(Node node, String propName) {
1216 Map<String, Property> propMap = getNodeProps(node);
1217 return (propMap != null) ? propMap.get(propName) : null;
1221 public void setNodeProp(Node node, Property prop) {
1223 for (int i = 0; i <= REPLACE_RETRY; i++) {
1224 /* Get a copy of the property map */
1225 Map<String, Property> propMapCurr = getNodeProps(node);
1226 if (propMapCurr == null) {
1230 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1231 propMap.put(prop.getName(), prop);
1233 if (nodeProps.replace(node, propMapCurr, propMap)) {
1236 if (!propMapCurr.get(prop.getName()).equals(nodeProps.get(node).get(prop.getName()))) {
1237 log.debug("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1241 log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1245 public Status removeNodeProp(Node node, String propName) {
1246 for (int i = 0; i <= REPLACE_RETRY; i++) {
1247 Map<String, Property> propMapCurr = getNodeProps(node);
1248 if (propMapCurr != null) {
1249 if (!propMapCurr.containsKey(propName)) {
1250 return new Status(StatusCode.SUCCESS);
1252 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1253 propMap.remove(propName);
1254 if (nodeProps.replace(node, propMapCurr, propMap)) {
1255 return new Status(StatusCode.SUCCESS);
1257 if (!propMapCurr.get(propName).equals(nodeProps.get(node).get(propName))) {
1258 String msg = "Cluster conflict: Unable to remove property " + propName + " for node "
1260 return new Status(StatusCode.CONFLICT, msg);
1264 return new Status(StatusCode.SUCCESS);
1267 String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID();
1268 return new Status(StatusCode.CONFLICT, msg);
1272 public Status removeNodeAllProps(Node node) {
1273 this.nodeProps.remove(node);
1274 return new Status(StatusCode.SUCCESS);
1278 public Set<NodeConnector> getUpNodeConnectors(Node node) {
1279 if (nodeConnectorProps == null) {
1283 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1284 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1285 NodeConnector nodeConnector = entry.getKey();
1286 if (!nodeConnector.getNode().equals(node)) {
1289 if (isNodeConnectorEnabled(nodeConnector)) {
1290 nodeConnectorSet.add(nodeConnector);
1294 return nodeConnectorSet;
1298 public Set<NodeConnector> getNodeConnectors(Node node) {
1299 if (nodeConnectorProps == null) {
1303 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1304 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1305 NodeConnector nodeConnector = entry.getKey();
1306 if (!nodeConnector.getNode().equals(node)) {
1309 nodeConnectorSet.add(nodeConnector);
1312 return nodeConnectorSet;
1316 public Set<NodeConnector> getPhysicalNodeConnectors(Node node) {
1317 if (nodeConnectorProps == null) {
1321 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1322 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1323 NodeConnector nodeConnector = entry.getKey();
1324 if (!nodeConnector.getNode().equals(node)
1325 || isSpecial(nodeConnector)) {
1328 nodeConnectorSet.add(nodeConnector);
1331 return nodeConnectorSet;
1335 public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) {
1336 Map<String, Property> rv = new HashMap<String, Property>();
1337 if (this.nodeConnectorProps != null) {
1338 rv = this.nodeConnectorProps.get(nodeConnector);
1340 rv = new HashMap<String, Property>(rv);
1347 public Property getNodeConnectorProp(NodeConnector nodeConnector,
1349 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1350 return (propMap != null) ? propMap.get(propName) : null;
1353 private byte[] getHardwareMAC() {
1354 Enumeration<NetworkInterface> nis;
1355 byte[] macAddress = null;
1358 nis = NetworkInterface.getNetworkInterfaces();
1359 } catch (SocketException e) {
1360 log.error("Failed to acquire controller MAC: ", e);
1364 while (nis.hasMoreElements()) {
1365 NetworkInterface ni = nis.nextElement();
1367 macAddress = ni.getHardwareAddress();
1368 } catch (SocketException e) {
1369 log.error("Failed to acquire controller MAC: ", e);
1371 if (macAddress != null) {
1375 if (macAddress == null) {
1376 log.warn("Failed to acquire controller MAC: No physical interface found");
1377 // This happens when running controller on windows VM, for example
1378 // Try parsing the OS command output
1384 public byte[] getControllerMAC() {
1385 MacAddress macProperty = (MacAddress)controllerProps.get(MacAddress.name);
1386 return (macProperty == null) ? null : macProperty.getMacAddress();
1390 public boolean isHostRefreshEnabled() {
1395 public int getHostRetryCount() {
1396 return hostRetryCount;
1400 public NodeConnector getNodeConnector(Node node, String nodeConnectorName) {
1401 if (nodeConnectorNames == null) {
1405 Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1410 return map.get(nodeConnectorName);
1414 * Adds a node connector and its property if any
1416 * @param nodeConnector
1417 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1419 * name of {@link org.opendaylight.controller.sal.core.Property}
1420 * @return success or failed reason
1423 public Status addNodeConnectorProp(NodeConnector nodeConnector,
1425 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1426 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1427 : new HashMap<String, Property>(propMapCurr);
1429 String msg = "Cluster conflict: Unable to add NodeConnector Property.";
1430 // Just add the nodeConnector if prop is not available (in a non-default
1433 if (propMapCurr == null) {
1434 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1435 return new Status(StatusCode.CONFLICT, msg);
1438 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1439 return new Status(StatusCode.CONFLICT, msg);
1442 return new Status(StatusCode.SUCCESS);
1445 propMap.put(prop.getName(), prop);
1446 if (propMapCurr == null) {
1447 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1448 return new Status(StatusCode.CONFLICT, msg);
1451 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1452 return new Status(StatusCode.CONFLICT, msg);
1456 if (prop.getName().equals(Name.NamePropName)) {
1457 if (nodeConnectorNames != null) {
1458 Node node = nodeConnector.getNode();
1459 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1460 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1461 if (mapCurr != null) {
1462 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1463 String s = entry.getKey();
1465 map.put(s, new NodeConnector(entry.getValue()));
1466 } catch (ConstructionException e) {
1467 log.error("An error occured",e);
1472 map.put(((Name) prop).getValue(), nodeConnector);
1473 if (mapCurr == null) {
1474 if (nodeConnectorNames.putIfAbsent(node, map) != null) {
1475 // TODO: recovery using Transactionality
1476 return new Status(StatusCode.CONFLICT, msg);
1479 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1480 // TODO: recovery using Transactionality
1481 return new Status(StatusCode.CONFLICT, msg);
1487 return new Status(StatusCode.SUCCESS);
1491 * Removes one property of a node connector
1493 * @param nodeConnector
1494 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1496 * name of {@link org.opendaylight.controller.sal.core.Property}
1497 * @return success or failed reason
1500 public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) {
1501 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1503 if (propMapCurr == null) {
1504 /* Nothing to remove */
1505 return new Status(StatusCode.SUCCESS);
1508 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1509 propMap.remove(propName);
1510 boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap);
1511 String msg = "Cluster conflict: Unable to remove NodeConnector property.";
1513 return new Status(StatusCode.CONFLICT, msg);
1516 if (propName.equals(Name.NamePropName)) {
1517 if (nodeConnectorNames != null) {
1518 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1520 Node node = nodeConnector.getNode();
1521 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1522 if (mapCurr != null) {
1523 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1524 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1525 String s = entry.getKey();
1527 map.put(s, new NodeConnector(entry.getValue()));
1528 } catch (ConstructionException e) {
1529 log.error("An error occured",e);
1532 map.remove(name.getValue());
1533 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1534 // TODO: recovery using Transactionality
1535 return new Status(StatusCode.CONFLICT, msg);
1542 return new Status(StatusCode.SUCCESS);
1546 * Removes all the properties of a node connector
1548 * @param nodeConnector
1549 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1550 * @return success or failed reason
1553 public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) {
1554 if (nodeConnectorNames != null) {
1555 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1557 Node node = nodeConnector.getNode();
1558 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1559 if (mapCurr != null) {
1560 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1561 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1562 String s = entry.getKey();
1564 map.put(s, new NodeConnector(entry.getValue()));
1565 } catch (ConstructionException e) {
1566 log.error("An error occured",e);
1569 map.remove(name.getValue());
1570 if (map.isEmpty()) {
1571 nodeConnectorNames.remove(node);
1573 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1574 log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.",
1575 nodeConnector.getID());
1582 nodeConnectorProps.remove(nodeConnector);
1584 return new Status(StatusCode.SUCCESS);
1588 * Function called by the dependency manager when all the required
1589 * dependencies are satisfied
1592 void init(Component c) {
1593 Dictionary<?, ?> props = c.getServiceProperties();
1594 if (props != null) {
1595 this.containerName = (String) props.get("containerName");
1596 log.trace("Running containerName: {}", this.containerName);
1598 // In the Global instance case the containerName is empty
1599 this.containerName = "";
1601 isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT
1608 * Function called by the dependency manager when at least one dependency
1609 * become unsatisfied or when the component is shutting down because for
1610 * example bundle is being stopped.
1618 * Function called by dependency manager after "init ()" is called and after
1619 * the services provided by the class are registered in the service registry
1624 registerWithOSGIConsole();
1628 * Function called after registered the service in OSGi service registry.
1631 // solicit for existing inventories
1636 * Function called by the dependency manager before the services exported by
1637 * the component are unregistered, this will be followed by a "destroy ()"
1644 public void setInventoryService(IInventoryService service) {
1645 log.trace("Got inventory service set request {}", service);
1646 this.inventoryService = service;
1648 // solicit for existing inventories
1652 public void unsetInventoryService(IInventoryService service) {
1653 log.trace("Got a service UNset request");
1654 this.inventoryService = null;
1656 // clear existing inventories
1660 public void setStatisticsManager(IStatisticsManager statisticsManager) {
1661 log.trace("Got statistics manager set request {}", statisticsManager);
1662 this.statisticsManager = statisticsManager;
1665 public void unsetStatisticsManager(IStatisticsManager statisticsManager) {
1666 log.trace("Got statistics manager UNset request");
1667 this.statisticsManager = null;
1670 public void setSwitchManagerAware(ISwitchManagerAware service) {
1671 log.trace("Got inventory service set request {}", service);
1672 if (this.switchManagerAware != null) {
1673 this.switchManagerAware.add(service);
1676 // bulk update for newly joined
1677 switchManagerAwareNotify(service);
1680 public void unsetSwitchManagerAware(ISwitchManagerAware service) {
1681 log.trace("Got a service UNset request");
1682 if (this.switchManagerAware != null) {
1683 this.switchManagerAware.remove(service);
1687 public void setInventoryListener(IInventoryListener service) {
1688 log.trace("Got inventory listener set request {}", service);
1689 if (this.inventoryListeners != null) {
1690 this.inventoryListeners.add(service);
1693 // bulk update for newly joined
1694 bulkUpdateService(service);
1697 public void unsetInventoryListener(IInventoryListener service) {
1698 log.trace("Got a service UNset request");
1699 if (this.inventoryListeners != null) {
1700 this.inventoryListeners.remove(service);
1704 public void setSpanAware(ISpanAware service) {
1705 log.trace("Got SpanAware set request {}", service);
1706 if (this.spanAware != null) {
1707 this.spanAware.add(service);
1710 // bulk update for newly joined
1711 spanAwareNotify(service);
1714 public void unsetSpanAware(ISpanAware service) {
1715 log.trace("Got a service UNset request");
1716 if (this.spanAware != null) {
1717 this.spanAware.remove(service);
1721 void setClusterContainerService(IClusterContainerServices s) {
1722 log.trace("Cluster Service set");
1723 this.clusterContainerService = s;
1726 void unsetClusterContainerService(IClusterContainerServices s) {
1727 if (this.clusterContainerService == s) {
1728 log.trace("Cluster Service removed!");
1729 this.clusterContainerService = null;
1733 private void getInventories() {
1734 if (inventoryService == null) {
1735 log.trace("inventory service not avaiable");
1739 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
1740 for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) {
1741 Node node = entry.getKey();
1742 log.debug("getInventories: {} added for container {}", new Object[] { node, containerName });
1743 Map<String, Property> propMap = entry.getValue();
1744 Set<Property> props = new HashSet<Property>();
1745 for (Property property : propMap.values()) {
1746 props.add(property);
1748 addNode(node, props);
1751 Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps();
1752 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) {
1753 Map<String, Property> propMap = entry.getValue();
1754 for (Property property : propMap.values()) {
1755 addNodeConnectorProp(entry.getKey(), property);
1760 private void clearInventories() {
1762 nodeConnectorProps.clear();
1763 nodeConnectorNames.clear();
1764 spanNodeConnectors.clear();
1767 private void notifyNode(Node node, UpdateType type,
1768 Map<String, Property> propMap) {
1769 synchronized (inventoryListeners) {
1770 for (IInventoryListener service : inventoryListeners) {
1771 service.notifyNode(node, type, propMap);
1776 private void notifyNodeConnector(NodeConnector nodeConnector,
1777 UpdateType type, Map<String, Property> propMap) {
1778 synchronized (inventoryListeners) {
1779 for (IInventoryListener service : inventoryListeners) {
1780 service.notifyNodeConnector(nodeConnector, type, propMap);
1786 * For those joined late, bring them up-to-date.
1788 private void switchManagerAwareNotify(ISwitchManagerAware service) {
1789 for (Subnet sub : subnets.values()) {
1790 service.subnetNotify(sub, true);
1793 for (Node node : getNodes()) {
1794 SwitchConfig sc = getSwitchConfig(node.toString());
1795 if ((sc != null) && isDefaultContainer) {
1796 ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
1797 service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive());
1802 private void bulkUpdateService(IInventoryListener service) {
1803 Map<String, Property> propMap;
1804 UpdateType type = UpdateType.ADDED;
1806 for (Node node : getNodes()) {
1807 propMap = nodeProps.get(node);
1808 service.notifyNode(node, type, propMap);
1811 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1812 NodeConnector nodeConnector = entry.getKey();
1813 propMap = nodeConnectorProps.get(nodeConnector);
1814 service.notifyNodeConnector(nodeConnector, type, propMap);
1818 private void spanAwareNotify(ISpanAware service) {
1819 for (Node node : getNodes()) {
1820 for (SpanConfig conf : getSpanConfigList(node)) {
1821 service.spanUpdate(node, conf.getPortArrayList(), true);
1826 private void registerWithOSGIConsole() {
1827 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
1828 .getBundleContext();
1829 bundleContext.registerService(CommandProvider.class.getName(), this,
1834 public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) {
1835 if (nodeConnector == null) {
1839 Config config = (Config) getNodeConnectorProp(nodeConnector,
1840 Config.ConfigPropName);
1841 State state = (State) getNodeConnectorProp(nodeConnector,
1842 State.StatePropName);
1843 return ((config != null) && (config.getValue() == Config.ADMIN_UP)
1844 && (state != null) && (state.getValue() == State.EDGE_UP));
1848 public String getHelp() {
1849 StringBuffer help = new StringBuffer();
1850 help.append("---Switch Manager---\n");
1851 help.append("\t pencs <node id> - Print enabled node connectors for a given node\n");
1852 help.append("\t pdm <node id> - Print switch ports in device map\n");
1853 help.append("\t snt <node id> <tier> - Set node tier number\n");
1854 help.append("\t hostRefresh <on/off/?> - Enable/Disable/Query host refresh\n");
1855 help.append("\t hostRetry <count> - Set host retry count\n");
1856 return help.toString();
1859 public void _pencs(CommandInterpreter ci) {
1860 String st = ci.nextArgument();
1862 ci.println("Please enter node id");
1866 Node node = Node.fromString(st);
1868 ci.println("Please enter node id");
1872 Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node);
1873 if (nodeConnectorSet == null) {
1876 for (NodeConnector nodeConnector : nodeConnectorSet) {
1877 if (nodeConnector == null) {
1880 ci.println(nodeConnector);
1882 ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1885 public void _pdm(CommandInterpreter ci) {
1886 String st = ci.nextArgument();
1888 ci.println("Please enter node id");
1892 Node node = Node.fromString(st);
1894 ci.println("Please enter node id");
1898 Switch sw = getSwitchByNode(node);
1900 ci.println(" NodeConnector Name");
1902 Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors();
1903 String nodeConnectorName;
1904 if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
1905 for (NodeConnector nodeConnector : nodeConnectorSet) {
1906 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1907 nodeConnectorName = (propMap == null) ? null : ((Name) propMap
1908 .get(Name.NamePropName)).getValue();
1909 if (nodeConnectorName != null) {
1910 Node nd = nodeConnector.getNode();
1911 if (!nd.equals(node)) {
1912 log.debug("node not match {} {}", nd, node);
1914 Map<String, NodeConnector> map = nodeConnectorNames
1917 NodeConnector nc = map.get(nodeConnectorName);
1919 log.debug("no nodeConnector named {}",
1921 } else if (!nc.equals(nodeConnector)) {
1922 log.debug("nodeConnector not match {} {}", nc,
1928 ci.println(nodeConnector
1930 + ((nodeConnectorName == null) ? "" : nodeConnectorName)
1931 + "(" + nodeConnector.getID() + ")");
1933 ci.println("Total number of NodeConnectors: "
1934 + nodeConnectorSet.size());
1938 public void _snt(CommandInterpreter ci) {
1939 String st = ci.nextArgument();
1941 ci.println("Please enter node id");
1945 Node node = Node.fromString(st);
1947 ci.println("Please enter node id");
1951 st = ci.nextArgument();
1953 ci.println("Please enter tier number");
1956 Integer tid = Integer.decode(st);
1957 Tier tier = new Tier(tid);
1958 setNodeProp(node, tier);
1961 public void _hostRefresh(CommandInterpreter ci) {
1962 String mode = ci.nextArgument();
1964 ci.println("expecting on/off/?");
1967 if (mode.toLowerCase().equals("on")) {
1969 } else if (mode.toLowerCase().equals("off")) {
1970 hostRefresh = false;
1971 } else if (mode.equals("?")) {
1973 ci.println("host refresh is ON");
1975 ci.println("host refresh is OFF");
1978 ci.println("expecting on/off/?");
1983 public void _hostRetry(CommandInterpreter ci) {
1984 String retry = ci.nextArgument();
1985 if (retry == null) {
1986 ci.println("Please enter a valid number. Current retry count is "
1991 hostRetryCount = Integer.parseInt(retry);
1992 } catch (Exception e) {
1993 ci.println("Please enter a valid number");
1999 public byte[] getNodeMAC(Node node) {
2000 MacAddress mac = (MacAddress) this.getNodeProp(node,
2002 return (mac != null) ? mac.getMacAddress() : null;
2006 public boolean isSpecial(NodeConnector p) {
2007 if (p.getType().equals(NodeConnectorIDType.CONTROLLER)
2008 || p.getType().equals(NodeConnectorIDType.ALL)
2009 || p.getType().equals(NodeConnectorIDType.SWSTACK)
2010 || p.getType().equals(NodeConnectorIDType.HWPATH)) {
2017 * Add span configuration to local cache and notify clients
2019 private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2020 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2022 for (NodeConnector nodeConnector : nodeConnectors) {
2023 if (!spanNodeConnectors.contains(nodeConnector)) {
2024 ncLists.add(nodeConnector);
2028 if (ncLists.size() > 0) {
2029 spanNodeConnectors.addAll(ncLists);
2030 notifySpanPortChange(node, ncLists, true);
2034 private void addSpanPorts(Node node) {
2035 for (SpanConfig conf : getSpanConfigList(node)) {
2036 addSpanPorts(node, conf.getPortArrayList());
2040 private void addSpanPort(NodeConnector nodeConnector) {
2041 // only add if span is configured on this nodeConnector
2042 for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) {
2043 if (conf.getPortArrayList().contains(nodeConnector)) {
2044 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2045 ncLists.add(nodeConnector);
2046 addSpanPorts(nodeConnector.getNode(), ncLists);
2053 * Remove span configuration to local cache and notify clients
2055 private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2056 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2058 for (NodeConnector nodeConnector : nodeConnectors) {
2059 if (spanNodeConnectors.contains(nodeConnector)) {
2060 ncLists.add(nodeConnector);
2064 if (ncLists.size() > 0) {
2065 spanNodeConnectors.removeAll(ncLists);
2066 notifySpanPortChange(node, ncLists, false);
2070 private void removeSpanPorts(Node node) {
2071 for (SpanConfig conf : getSpanConfigList(node)) {
2072 addSpanPorts(node, conf.getPortArrayList());
2076 private void removeSpanPort(NodeConnector nodeConnector) {
2077 if (spanNodeConnectors.contains(nodeConnector)) {
2078 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2079 ncLists.add(nodeConnector);
2080 removeSpanPorts(nodeConnector.getNode(), ncLists);
2084 private void addNodeProps(Node node, Map<String, Property> propMap) {
2085 if (propMap == null) {
2086 propMap = new HashMap<String, Property>();
2088 nodeProps.put(node, propMap);
2092 public Status saveConfiguration() {
2093 return saveSwitchConfig();
2097 * Creates a Name/Tier/Bandwidth Property object based on given property
2098 * name and value. Other property types are not supported yet.
2101 * Name of the Property
2103 * Value of the Property
2104 * @return {@link org.opendaylight.controller.sal.core.Property}
2107 public Property createProperty(String propName, String propValue) {
2108 if (propName == null) {
2109 log.debug("propName is null");
2112 if (propValue == null) {
2113 log.debug("propValue is null");
2118 if (propName.equalsIgnoreCase(Description.propertyName)) {
2119 return new Description(propValue);
2120 } else if (propName.equalsIgnoreCase(Tier.TierPropName)) {
2121 int tier = Integer.parseInt(propValue);
2122 return new Tier(tier);
2123 } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) {
2124 long bw = Long.parseLong(propValue);
2125 return new Bandwidth(bw);
2126 } else if (propName.equalsIgnoreCase(ForwardingMode.name)) {
2127 int mode = Integer.parseInt(propValue);
2128 return new ForwardingMode(mode);
2130 log.debug("Not able to create {} property", propName);
2132 } catch (Exception e) {
2133 log.debug("createProperty caught exception {}", e.getMessage());
2139 @SuppressWarnings("deprecation")
2141 public String getNodeDescription(Node node) {
2142 // Check first if user configured a name
2143 SwitchConfig config = getSwitchConfig(node.toString());
2144 if (config != null) {
2145 String configuredDesc = config.getNodeDescription();
2146 if (configuredDesc != null && !configuredDesc.isEmpty()) {
2147 return configuredDesc;
2151 // No name configured by user, get the node advertised name
2152 Description desc = (Description) getNodeProp(node,
2153 Description.propertyName);
2154 return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? ""