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) && !existingSubnet.isMutualExclusive(newSubnet)) {
418 return new Status(StatusCode.CONFLICT, "This subnet conflicts with an existing one.");
421 return new Status(StatusCode.SUCCESS);
424 private Status addRemoveSubnet(SubnetConfig conf, boolean isAdding) {
425 // Valid configuration check
426 Status status = conf.validate();
427 if (!status.isSuccess()) {
428 log.warn(status.getDescription());
434 if (subnetsConfigList.containsKey(conf.getName())) {
435 return new Status(StatusCode.CONFLICT,
436 "Subnet with the specified name already exists.");
439 status = semanticCheck(conf);
440 if (!status.isSuccess()) {
446 status = updateDatabase(conf, isAdding);
448 if (status.isSuccess()) {
449 // Update Configuration
450 status = updateConfig(conf, isAdding);
451 if(!status.isSuccess()) {
452 updateDatabase(conf, (!isAdding));
460 * Adds Subnet configured in GUI or API3
463 public Status addSubnet(SubnetConfig conf) {
464 return this.addRemoveSubnet(conf, true);
468 public Status removeSubnet(SubnetConfig conf) {
469 return this.addRemoveSubnet(conf, false);
473 public Status removeSubnet(String name) {
474 SubnetConfig conf = subnetsConfigList.get(name);
476 return new Status(StatusCode.SUCCESS, "Subnet not present");
478 return this.addRemoveSubnet(conf, false);
482 public Status modifySubnet(SubnetConfig conf) {
485 return new Status(StatusCode.BADREQUEST, "Invalid Subnet configuration: null");
488 // Valid configuration check
489 Status status = conf.validate();
490 if (!status.isSuccess()) {
491 log.warn(status.getDescription());
495 // If a subnet configuration with this name does not exist, consider this is a creation
496 SubnetConfig target = subnetsConfigList.get(conf.getName());
497 if (target == null) {
498 return this.addSubnet(conf);
502 if (target.equals(conf)) {
503 return new Status(StatusCode.SUCCESS);
506 // Check not allowed modifications
507 if (!target.getSubnet().equals(conf.getSubnet())) {
508 return new Status(StatusCode.BADREQUEST, "IP address change is not allowed");
511 // Derive the set of node connectors that are being removed
512 Set<NodeConnector> toRemove = target.getNodeConnectors();
513 toRemove.removeAll(conf.getNodeConnectors());
514 List<String> nodeConnectorStrings = null;
515 if (!toRemove.isEmpty()) {
516 nodeConnectorStrings = new ArrayList<String>();
517 for (NodeConnector nc : toRemove) {
518 nodeConnectorStrings.add(nc.toString());
520 status = this.removePortsFromSubnet(conf.getName(), nodeConnectorStrings);
521 if (!status.isSuccess()) {
526 // Derive the set of node connectors that are being added
527 Set<NodeConnector> toAdd = conf.getNodeConnectors();
528 toAdd.removeAll(target.getNodeConnectors());
529 if (!toAdd.isEmpty()) {
530 List<String> nodeConnectorStringRemoved = nodeConnectorStrings;
531 nodeConnectorStrings = new ArrayList<String>();
532 for (NodeConnector nc : toAdd) {
533 nodeConnectorStrings.add(nc.toString());
535 status = this.addPortsToSubnet(conf.getName(), nodeConnectorStrings);
536 if (!status.isSuccess()) {
537 // If any port was removed, add it back as a best recovery effort
538 if (!toRemove.isEmpty()) {
539 this.addPortsToSubnet(conf.getName(), nodeConnectorStringRemoved);
545 // Update Configuration
546 subnetsConfigList.put(conf.getName(), conf);
548 return new Status(StatusCode.SUCCESS);
552 public Status addPortsToSubnet(String name, List<String> switchPorts) {
554 return new Status(StatusCode.BADREQUEST, "Null subnet name");
556 SubnetConfig confCurr = subnetsConfigList.get(name);
557 if (confCurr == null) {
558 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
561 if (switchPorts == null || switchPorts.isEmpty()) {
562 return new Status(StatusCode.BADREQUEST, "Null or empty port set");
565 Subnet subCurr = subnets.get(confCurr.getIPAddress());
566 if (subCurr == null) {
567 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress());
568 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
572 Subnet sub = subCurr.clone();
573 Set<NodeConnector> sp = NodeConnector.fromString(switchPorts);
574 sub.addNodeConnectors(sp);
575 boolean subnetsReplaced = subnets.replace(confCurr.getIPAddress(), subCurr, sub);
576 if (!subnetsReplaced) {
577 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
578 return new Status(StatusCode.CONFLICT, msg);
581 // Update Configuration
582 SubnetConfig conf = confCurr.clone();
583 conf.addNodeConnectors(switchPorts);
584 boolean configReplaced = subnetsConfigList.replace(name, confCurr, conf);
585 if (!configReplaced) {
586 // TODO: recovery using Transactionality
587 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
588 return new Status(StatusCode.CONFLICT, msg);
591 return new Status(StatusCode.SUCCESS);
595 public Status removePortsFromSubnet(String name, List<String> switchPorts) {
597 return new Status(StatusCode.BADREQUEST, "Null subnet name");
599 SubnetConfig confCurr = subnetsConfigList.get(name);
600 if (confCurr == null) {
601 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
604 if (switchPorts == null || switchPorts.isEmpty()) {
605 return new Status(StatusCode.BADREQUEST, "Null or empty port set");
608 Subnet subCurr = subnets.get(confCurr.getIPAddress());
609 if (subCurr == null) {
610 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress());
611 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
615 Status status = SubnetConfig.validatePorts(switchPorts);
616 if (!status.isSuccess()) {
620 Subnet sub = subCurr.clone();
621 Set<NodeConnector> sp = NodeConnector.fromString(switchPorts);
622 sub.deleteNodeConnectors(sp);
623 boolean subnetsReplace = subnets.replace(confCurr.getIPAddress(), subCurr, sub);
624 if (!subnetsReplace) {
625 String msg = "Cluster conflict: Conflict while removing ports from the subnet " + name;
626 return new Status(StatusCode.CONFLICT, msg);
629 // Update Configuration
630 SubnetConfig conf = confCurr.clone();
631 conf.removeNodeConnectors(switchPorts);
632 boolean result = subnetsConfigList.replace(name, confCurr, conf);
634 // TODO: recovery using Transactionality
635 String msg = "Cluster conflict: Conflict while removing ports from " + conf;
636 return new Status(StatusCode.CONFLICT, msg);
639 return new Status(StatusCode.SUCCESS);
642 public String getContainerName() {
643 if (containerName == null) {
644 return GlobalConstants.DEFAULT.toString();
646 return containerName;
650 public Subnet getSubnetByNetworkAddress(InetAddress networkAddress) {
652 Set<InetAddress> indices = subnets.keySet();
653 for (InetAddress i : indices) {
654 sub = subnets.get(i);
655 if (sub.isSubnetOf(networkAddress)) {
663 public Object readObject(ObjectInputStream ois)
664 throws FileNotFoundException, IOException, ClassNotFoundException {
665 // Perform the class deserialization locally, from inside the package
666 // where the class is defined
667 return ois.readObject();
670 @SuppressWarnings("unchecked")
671 private void loadSubnetConfiguration() {
672 ObjectReader objReader = new ObjectReader();
673 ConcurrentMap<String, SubnetConfig> confList = (ConcurrentMap<String, SubnetConfig>) objReader
674 .read(this, subnetFileName);
676 if (confList == null) {
680 for (SubnetConfig conf : confList.values()) {
685 @SuppressWarnings("unchecked")
686 private void loadSpanConfiguration() {
687 ObjectReader objReader = new ObjectReader();
688 ConcurrentMap<Integer, SpanConfig> confList = (ConcurrentMap<Integer, SpanConfig>) objReader
689 .read(this, spanFileName);
691 if (confList == null) {
695 for (SpanConfig conf : confList.values()) {
700 @SuppressWarnings("unchecked")
701 private void loadSwitchConfiguration() {
702 ObjectReader objReader = new ObjectReader();
703 ConcurrentMap<String, SwitchConfig> confList = (ConcurrentMap<String, SwitchConfig>) objReader
704 .read(this, switchConfigFileName);
706 if (confList == null) {
710 for (SwitchConfig conf : confList.values()) {
711 updateNodeConfig(conf);
715 @SuppressWarnings("deprecation")
717 public void updateSwitchConfig(SwitchConfig cfgObject) {
718 // update default container only
719 if (!isDefaultContainer) {
723 SwitchConfig sc = nodeConfigList.get(cfgObject.getNodeId());
725 if (nodeConfigList.putIfAbsent(cfgObject.getNodeId(), cfgObject) != null) {
729 if (!nodeConfigList.replace(cfgObject.getNodeId(), sc, cfgObject)) {
734 boolean modeChange = false;
736 if ((sc == null) || !cfgObject.getMode().equals(sc.getMode())) {
740 String nodeId = cfgObject.getNodeId();
741 Node node = Node.fromString(nodeId);
742 Map<String, Property> propMapCurr = nodeProps.get(node);
743 if (propMapCurr == null) {
746 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
747 Property desc = new Description(cfgObject.getNodeDescription());
748 propMap.put(desc.getName(), desc);
749 Property tier = new Tier(Integer.parseInt(cfgObject.getTier()));
750 propMap.put(tier.getName(), tier);
752 if (!nodeProps.replace(node, propMapCurr, propMap)) {
753 // TODO rollback using Transactionality
757 log.info("Set Node {}'s Mode to {}", nodeId, cfgObject.getMode());
760 notifyModeChange(node, cfgObject.isProactive());
765 public Status updateNodeConfig(SwitchConfig switchConfig) {
766 Status status = switchConfig.validate();
767 if (!status.isSuccess()) {
771 Map<String, Property> updateProperties = switchConfig.getNodeProperties();
772 ForwardingMode mode = (ForwardingMode) updateProperties.get(ForwardingMode.name);
774 if (isDefaultContainer) {
775 if (!mode.isValid()) {
776 return new Status(StatusCode.BADREQUEST, "Invalid Forwarding Mode Value");
779 return new Status(StatusCode.NOTACCEPTABLE,
780 "Forwarding Mode modification is allowed only in default container");
784 Description description = (Description) switchConfig.getProperty(Description.propertyName);
785 String nodeId = switchConfig.getNodeId();
786 Node node = Node.fromString(nodeId);
787 NodeDescription nodeDesc = (this.statisticsManager == null) ? null : this.statisticsManager
788 .getNodeDescription(node);
789 String advertisedDesc = (nodeDesc == null) ? "" : nodeDesc.getDescription();
790 if (description != null && description.getValue() != null) {
791 if (description.getValue().isEmpty() || description.getValue().equals(advertisedDesc)) {
792 updateProperties.remove(Description.propertyName);
793 switchConfig = new SwitchConfig(nodeId, updateProperties);
795 // check if description is configured or was published by any other node
796 for (Map.Entry<Node, Map<String, Property>> entry : nodeProps.entrySet()) {
797 Node n = entry.getKey();
798 Description desc = (Description) getNodeProp(n, Description.propertyName);
799 NodeDescription nDesc = (this.statisticsManager == null) ? null : this.statisticsManager
800 .getNodeDescription(n);
801 String advDesc = (nDesc == null) ? "" : nDesc.getDescription();
802 if ((description.equals(desc) || description.getValue().equals(advDesc)) && !node.equals(n)) {
803 return new Status(StatusCode.CONFLICT, "Node name already in use");
809 boolean modeChange = false;
810 SwitchConfig sc = nodeConfigList.get(nodeId);
811 Map<String, Property> prevNodeProperties = new HashMap<String, Property>();
813 if ((mode != null) && mode.isProactive()) {
816 if (!updateProperties.isEmpty()) {
817 if (nodeConfigList.putIfAbsent(nodeId, switchConfig) != null) {
818 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
822 prevNodeProperties = new HashMap<String, Property>(sc.getNodeProperties());
823 ForwardingMode prevMode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
825 if ((prevMode != null) && (prevMode.isProactive())) {
829 if (((prevMode != null) && (prevMode.getValue() != mode.getValue()))
830 || (prevMode == null && mode.isProactive())) {
834 if (updateProperties.isEmpty()) {
835 nodeConfigList.remove(nodeId);
837 if (!nodeConfigList.replace(nodeId, sc, switchConfig)) {
838 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
842 Map<String, Property> propMapCurr = nodeProps.get(node);
843 if (propMapCurr == null) {
844 return new Status(StatusCode.SUCCESS);
846 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
847 for (Map.Entry<String, Property> entry : prevNodeProperties.entrySet()) {
848 String prop = entry.getKey();
849 if (!updateProperties.containsKey(prop)) {
850 if (prop.equals(Description.propertyName)) {
851 if (!advertisedDesc.isEmpty()) {
852 Property desc = new Description(advertisedDesc);
853 propMap.put(Description.propertyName, desc);
856 } else if (prop.equals(ForwardingMode.name)) {
857 Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING);
858 propMap.put(ForwardingMode.name, defaultMode);
861 propMap.remove(prop);
864 propMap.putAll(updateProperties);
865 if (!nodeProps.replace(node, propMapCurr, propMap)) {
866 // TODO rollback using Transactionality
867 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
870 notifyModeChange(node, (mode == null) ? false : mode.isProactive());
872 return new Status(StatusCode.SUCCESS);
876 public Status removeNodeConfig(String nodeId) {
877 if ((nodeId == null) || (nodeId.isEmpty())) {
878 return new Status(StatusCode.BADREQUEST, "nodeId cannot be empty.");
880 Map<String, Property> nodeProperties = getSwitchConfig(nodeId).getNodeProperties();
881 Node node = Node.fromString(nodeId);
882 Map<String, Property> propMapCurr = nodeProps.get(node);
883 if ((propMapCurr != null) && (nodeProperties != null) && (!nodeProperties.isEmpty())) {
884 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
885 for (Map.Entry<String, Property> entry : nodeProperties.entrySet()) {
886 String prop = entry.getKey();
887 if (prop.equals(Description.propertyName)) {
888 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
889 if (nodeProp.get(node) != null) {
890 propMap.put(Description.propertyName, nodeProp.get(node).get(Description.propertyName));
894 propMap.remove(prop);
896 if (!nodeProps.replace(node, propMapCurr, propMap)) {
897 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration.");
900 if (nodeConfigList != null) {
901 nodeConfigList.remove(nodeId);
903 return new Status(StatusCode.SUCCESS);
907 public Status saveSwitchConfig() {
908 return saveSwitchConfigInternal();
911 public Status saveSwitchConfigInternal() {
912 Status retS = null, retP = null;
913 ObjectWriter objWriter = new ObjectWriter();
915 retS = objWriter.write(new ConcurrentHashMap<String, SubnetConfig>(
916 subnetsConfigList), subnetFileName);
917 retP = objWriter.write(new ConcurrentHashMap<SpanConfig, SpanConfig>(
918 spanConfigList), spanFileName);
919 retS = objWriter.write(new ConcurrentHashMap<String, SwitchConfig>(
920 nodeConfigList), switchConfigFileName);
921 if (retS.equals(retP)) {
922 if (retS.isSuccess()) {
925 return new Status(StatusCode.INTERNALERROR, "Save failed");
928 return new Status(StatusCode.INTERNALERROR, "Partial save failure");
933 public List<SpanConfig> getSpanConfigList() {
934 return new ArrayList<SpanConfig>(spanConfigList.values());
938 public Status addSpanConfig(SpanConfig conf) {
939 // Valid config check
940 if (!conf.isValidConfig()) {
941 String msg = "Invalid Span configuration";
943 return new Status(StatusCode.BADREQUEST, msg);
947 if (spanConfigList.containsKey(conf)) {
948 return new Status(StatusCode.CONFLICT, "Same span config exists");
951 // Update configuration
952 if (spanConfigList.putIfAbsent(conf, conf) == null) {
953 // Update database and notify clients
954 addSpanPorts(conf.getNode(), conf.getPortArrayList());
957 return new Status(StatusCode.SUCCESS);
961 public Status removeSpanConfig(SpanConfig conf) {
962 removeSpanPorts(conf.getNode(), conf.getPortArrayList());
964 // Update configuration
965 spanConfigList.remove(conf);
967 return new Status(StatusCode.SUCCESS);
971 public List<NodeConnector> getSpanPorts(Node node) {
972 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
974 for (NodeConnector nodeConnector : spanNodeConnectors) {
975 if (nodeConnector.getNode().equals(node)) {
976 ncList.add(nodeConnector);
982 private void addNode(Node node, Set<Property> props) {
983 log.trace("{} added, props: {}", node, props);
984 if (nodeProps == null) {
988 Map<String, Property> propMapCurr = nodeProps.get(node);
989 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
990 : new HashMap<String, Property>(propMapCurr);
992 // copy node properties from plugin
994 for (Property prop : props) {
995 propMap.put(prop.getName(), prop);
999 boolean proactiveForwarding = false;
1000 // copy node properties from config
1001 if (nodeConfigList != null) {
1002 String nodeId = node.toString();
1003 SwitchConfig conf = nodeConfigList.get(nodeId);
1004 if (conf != null && (conf.getNodeProperties() != null)) {
1005 Map<String, Property> nodeProperties = conf.getNodeProperties();
1006 propMap.putAll(nodeProperties);
1007 if (nodeProperties.get(ForwardingMode.name) != null) {
1008 ForwardingMode mode = (ForwardingMode) nodeProperties.get(ForwardingMode.name);
1009 proactiveForwarding = mode.isProactive();
1014 if (!propMap.containsKey(ForwardingMode.name)) {
1015 Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING);
1016 propMap.put(ForwardingMode.name, defaultMode);
1018 boolean result = false;
1019 if (propMapCurr == null) {
1020 if (nodeProps.putIfAbsent(node, propMap) == null) {
1024 result = nodeProps.replace(node, propMapCurr, propMap);
1027 log.debug("Cluster conflict: Conflict while adding the node properties. Node: {} Properties: {}",
1028 node.getID(), props);
1029 addNodeProps(node, propMap);
1032 // check if span ports are configed
1035 // notify node listeners
1036 notifyNode(node, UpdateType.ADDED, propMap);
1038 // notify proactive mode forwarding
1039 if (proactiveForwarding) {
1040 notifyModeChange(node, true);
1044 private void removeNode(Node node) {
1045 log.trace("{} removed", node);
1046 if (nodeProps == null) {
1049 nodeProps.remove(node);
1050 nodeConnectorNames.remove(node);
1051 Set<NodeConnector> removeNodeConnectorSet = new HashSet<NodeConnector>();
1052 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1053 NodeConnector nodeConnector = entry.getKey();
1054 if (nodeConnector.getNode().equals(node)) {
1055 removeNodeConnectorSet.add(nodeConnector);
1058 for (NodeConnector nc : removeNodeConnectorSet) {
1059 nodeConnectorProps.remove(nc);
1062 // check if span ports need to be cleaned up
1063 removeSpanPorts(node);
1065 /* notify node listeners */
1066 notifyNode(node, UpdateType.REMOVED, null);
1069 private void updateNode(Node node, Set<Property> props) {
1070 log.trace("{} updated, props: {}", node, props);
1071 if (nodeProps == null || !nodeProps.containsKey(node) ||
1072 props == null || props.isEmpty()) {
1076 Map<String, Property> propMapCurr = nodeProps.get(node);
1077 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1078 : new HashMap<String, Property>(propMapCurr);
1080 // copy node properties from plugin
1081 String nodeId = node.toString();
1082 for (Property prop : props) {
1083 if (nodeConfigList != null) {
1084 SwitchConfig conf = nodeConfigList.get(nodeId);
1085 if (conf != null && (conf.getNodeProperties() != null)
1086 && conf.getNodeProperties().containsKey(prop.getName())) {
1090 propMap.put(prop.getName(), prop);
1093 if (propMapCurr == null) {
1094 if (nodeProps.putIfAbsent(node, propMap) != null) {
1095 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1096 node.getID(), props);
1097 addNodeProps(node, propMap);
1100 if (!nodeProps.replace(node, propMapCurr, propMap)) {
1101 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1102 node.getID(), props);
1103 addNodeProps(node, propMap);
1107 /* notify node listeners */
1108 notifyNode(node, UpdateType.CHANGED, propMap);
1112 public void updateNode(Node node, UpdateType type, Set<Property> props) {
1113 log.debug("updateNode: {} type {} props {} for container {}",
1114 new Object[] { node, type, props, containerName });
1117 addNode(node, props);
1120 updateNode(node, props);
1131 public void updateNodeConnector(NodeConnector nodeConnector,
1132 UpdateType type, Set<Property> props) {
1133 Map<String, Property> propMap = new HashMap<String, Property>();
1134 boolean update = true;
1136 log.debug("updateNodeConnector: {} type {} props {} for container {}",
1137 new Object[] { nodeConnector, type, props, containerName });
1139 if (nodeConnectorProps == null) {
1145 if (props != null) {
1146 for (Property prop : props) {
1147 addNodeConnectorProp(nodeConnector, prop);
1148 propMap.put(prop.getName(), prop);
1151 addNodeConnectorProp(nodeConnector, null);
1154 addSpanPort(nodeConnector);
1157 if (!nodeConnectorProps.containsKey(nodeConnector) || (props == null)) {
1160 for (Property prop : props) {
1161 addNodeConnectorProp(nodeConnector, prop);
1162 propMap.put(prop.getName(), prop);
1167 if (!nodeConnectorProps.containsKey(nodeConnector)) {
1170 removeNodeConnectorAllProps(nodeConnector);
1172 // clean up span config
1173 removeSpanPort(nodeConnector);
1181 notifyNodeConnector(nodeConnector, type, propMap);
1186 public Set<Node> getNodes() {
1187 return (nodeProps != null) ? new HashSet<Node>(nodeProps.keySet())
1188 : new HashSet<Node>();
1192 * Returns a copy of a list of properties for a given node
1197 * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps
1198 * (org.opendaylight.controller.sal.core.Node)
1201 public Map<String, Property> getNodeProps(Node node) {
1202 Map<String, Property> rv = new HashMap<String, Property>();
1203 if (this.nodeProps != null) {
1204 rv = this.nodeProps.get(node);
1206 /* make a copy of it */
1207 rv = new HashMap<String, Property>(rv);
1214 public Property getNodeProp(Node node, String propName) {
1215 Map<String, Property> propMap = getNodeProps(node);
1216 return (propMap != null) ? propMap.get(propName) : null;
1220 public void setNodeProp(Node node, Property prop) {
1222 for (int i = 0; i <= REPLACE_RETRY; i++) {
1223 /* Get a copy of the property map */
1224 Map<String, Property> propMapCurr = getNodeProps(node);
1225 if (propMapCurr == null) {
1229 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1230 propMap.put(prop.getName(), prop);
1232 if (nodeProps.replace(node, propMapCurr, propMap)) {
1235 if (!propMapCurr.get(prop.getName()).equals(nodeProps.get(node).get(prop.getName()))) {
1236 log.debug("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1240 log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1244 public Status removeNodeProp(Node node, String propName) {
1245 for (int i = 0; i <= REPLACE_RETRY; i++) {
1246 Map<String, Property> propMapCurr = getNodeProps(node);
1247 if (propMapCurr != null) {
1248 if (!propMapCurr.containsKey(propName)) {
1249 return new Status(StatusCode.SUCCESS);
1251 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1252 propMap.remove(propName);
1253 if (nodeProps.replace(node, propMapCurr, propMap)) {
1254 return new Status(StatusCode.SUCCESS);
1256 if (!propMapCurr.get(propName).equals(nodeProps.get(node).get(propName))) {
1257 String msg = "Cluster conflict: Unable to remove property " + propName + " for node "
1259 return new Status(StatusCode.CONFLICT, msg);
1263 return new Status(StatusCode.SUCCESS);
1266 String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID();
1267 return new Status(StatusCode.CONFLICT, msg);
1271 public Status removeNodeAllProps(Node node) {
1272 this.nodeProps.remove(node);
1273 return new Status(StatusCode.SUCCESS);
1277 public Set<NodeConnector> getUpNodeConnectors(Node node) {
1278 if (nodeConnectorProps == null) {
1282 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1283 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1284 NodeConnector nodeConnector = entry.getKey();
1285 if (!nodeConnector.getNode().equals(node)) {
1288 if (isNodeConnectorEnabled(nodeConnector)) {
1289 nodeConnectorSet.add(nodeConnector);
1293 return nodeConnectorSet;
1297 public Set<NodeConnector> getNodeConnectors(Node node) {
1298 if (nodeConnectorProps == null) {
1302 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1303 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1304 NodeConnector nodeConnector = entry.getKey();
1305 if (!nodeConnector.getNode().equals(node)) {
1308 nodeConnectorSet.add(nodeConnector);
1311 return nodeConnectorSet;
1315 public Set<NodeConnector> getPhysicalNodeConnectors(Node node) {
1316 if (nodeConnectorProps == null) {
1320 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1321 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1322 NodeConnector nodeConnector = entry.getKey();
1323 if (!nodeConnector.getNode().equals(node)
1324 || isSpecial(nodeConnector)) {
1327 nodeConnectorSet.add(nodeConnector);
1330 return nodeConnectorSet;
1334 public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) {
1335 Map<String, Property> rv = new HashMap<String, Property>();
1336 if (this.nodeConnectorProps != null) {
1337 rv = this.nodeConnectorProps.get(nodeConnector);
1339 rv = new HashMap<String, Property>(rv);
1346 public Property getNodeConnectorProp(NodeConnector nodeConnector,
1348 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1349 return (propMap != null) ? propMap.get(propName) : null;
1352 private byte[] getHardwareMAC() {
1353 Enumeration<NetworkInterface> nis;
1354 byte[] macAddress = null;
1357 nis = NetworkInterface.getNetworkInterfaces();
1358 } catch (SocketException e) {
1359 log.error("Failed to acquire controller MAC: ", e);
1363 while (nis.hasMoreElements()) {
1364 NetworkInterface ni = nis.nextElement();
1366 macAddress = ni.getHardwareAddress();
1367 } catch (SocketException e) {
1368 log.error("Failed to acquire controller MAC: ", e);
1370 if (macAddress != null) {
1374 if (macAddress == null) {
1375 log.warn("Failed to acquire controller MAC: No physical interface found");
1376 // This happens when running controller on windows VM, for example
1377 // Try parsing the OS command output
1383 public byte[] getControllerMAC() {
1384 MacAddress macProperty = (MacAddress)controllerProps.get(MacAddress.name);
1385 return (macProperty == null) ? null : macProperty.getMacAddress();
1389 public boolean isHostRefreshEnabled() {
1394 public int getHostRetryCount() {
1395 return hostRetryCount;
1399 public NodeConnector getNodeConnector(Node node, String nodeConnectorName) {
1400 if (nodeConnectorNames == null) {
1404 Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1409 return map.get(nodeConnectorName);
1413 * Adds a node connector and its property if any
1415 * @param nodeConnector
1416 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1418 * name of {@link org.opendaylight.controller.sal.core.Property}
1419 * @return success or failed reason
1422 public Status addNodeConnectorProp(NodeConnector nodeConnector,
1424 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1425 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1426 : new HashMap<String, Property>(propMapCurr);
1428 String msg = "Cluster conflict: Unable to add NodeConnector Property.";
1429 // Just add the nodeConnector if prop is not available (in a non-default
1432 if (propMapCurr == null) {
1433 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1434 return new Status(StatusCode.CONFLICT, msg);
1437 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1438 return new Status(StatusCode.CONFLICT, msg);
1441 return new Status(StatusCode.SUCCESS);
1444 propMap.put(prop.getName(), prop);
1445 if (propMapCurr == null) {
1446 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1447 return new Status(StatusCode.CONFLICT, msg);
1450 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1451 return new Status(StatusCode.CONFLICT, msg);
1455 if (prop.getName().equals(Name.NamePropName)) {
1456 if (nodeConnectorNames != null) {
1457 Node node = nodeConnector.getNode();
1458 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1459 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1460 if (mapCurr != null) {
1461 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1462 String s = entry.getKey();
1464 map.put(s, new NodeConnector(entry.getValue()));
1465 } catch (ConstructionException e) {
1466 log.error("An error occured",e);
1471 map.put(((Name) prop).getValue(), nodeConnector);
1472 if (mapCurr == null) {
1473 if (nodeConnectorNames.putIfAbsent(node, map) != null) {
1474 // TODO: recovery using Transactionality
1475 return new Status(StatusCode.CONFLICT, msg);
1478 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1479 // TODO: recovery using Transactionality
1480 return new Status(StatusCode.CONFLICT, msg);
1486 return new Status(StatusCode.SUCCESS);
1490 * Removes one property of a node connector
1492 * @param nodeConnector
1493 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1495 * name of {@link org.opendaylight.controller.sal.core.Property}
1496 * @return success or failed reason
1499 public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) {
1500 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1502 if (propMapCurr == null) {
1503 /* Nothing to remove */
1504 return new Status(StatusCode.SUCCESS);
1507 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1508 propMap.remove(propName);
1509 boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap);
1510 String msg = "Cluster conflict: Unable to remove NodeConnector property.";
1512 return new Status(StatusCode.CONFLICT, msg);
1515 if (propName.equals(Name.NamePropName)) {
1516 if (nodeConnectorNames != null) {
1517 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1519 Node node = nodeConnector.getNode();
1520 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1521 if (mapCurr != null) {
1522 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1523 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1524 String s = entry.getKey();
1526 map.put(s, new NodeConnector(entry.getValue()));
1527 } catch (ConstructionException e) {
1528 log.error("An error occured",e);
1531 map.remove(name.getValue());
1532 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1533 // TODO: recovery using Transactionality
1534 return new Status(StatusCode.CONFLICT, msg);
1541 return new Status(StatusCode.SUCCESS);
1545 * Removes all the properties of a node connector
1547 * @param nodeConnector
1548 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1549 * @return success or failed reason
1552 public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) {
1553 if (nodeConnectorNames != null) {
1554 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1556 Node node = nodeConnector.getNode();
1557 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1558 if (mapCurr != null) {
1559 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1560 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1561 String s = entry.getKey();
1563 map.put(s, new NodeConnector(entry.getValue()));
1564 } catch (ConstructionException e) {
1565 log.error("An error occured",e);
1568 map.remove(name.getValue());
1569 if (map.isEmpty()) {
1570 nodeConnectorNames.remove(node);
1572 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1573 log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.",
1574 nodeConnector.getID());
1581 nodeConnectorProps.remove(nodeConnector);
1583 return new Status(StatusCode.SUCCESS);
1587 * Function called by the dependency manager when all the required
1588 * dependencies are satisfied
1591 void init(Component c) {
1592 Dictionary<?, ?> props = c.getServiceProperties();
1593 if (props != null) {
1594 this.containerName = (String) props.get("containerName");
1595 log.trace("Running containerName: {}", this.containerName);
1597 // In the Global instance case the containerName is empty
1598 this.containerName = "";
1600 isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT
1607 * Function called by the dependency manager when at least one dependency
1608 * become unsatisfied or when the component is shutting down because for
1609 * example bundle is being stopped.
1617 * Function called by dependency manager after "init ()" is called and after
1618 * the services provided by the class are registered in the service registry
1623 registerWithOSGIConsole();
1627 * Function called after registered the service in OSGi service registry.
1630 // solicit for existing inventories
1635 * Function called by the dependency manager before the services exported by
1636 * the component are unregistered, this will be followed by a "destroy ()"
1643 public void setInventoryService(IInventoryService service) {
1644 log.trace("Got inventory service set request {}", service);
1645 this.inventoryService = service;
1647 // solicit for existing inventories
1651 public void unsetInventoryService(IInventoryService service) {
1652 log.trace("Got a service UNset request");
1653 this.inventoryService = null;
1655 // clear existing inventories
1659 public void setStatisticsManager(IStatisticsManager statisticsManager) {
1660 log.trace("Got statistics manager set request {}", statisticsManager);
1661 this.statisticsManager = statisticsManager;
1664 public void unsetStatisticsManager(IStatisticsManager statisticsManager) {
1665 log.trace("Got statistics manager UNset request");
1666 this.statisticsManager = null;
1669 public void setSwitchManagerAware(ISwitchManagerAware service) {
1670 log.trace("Got inventory service set request {}", service);
1671 if (this.switchManagerAware != null) {
1672 this.switchManagerAware.add(service);
1675 // bulk update for newly joined
1676 switchManagerAwareNotify(service);
1679 public void unsetSwitchManagerAware(ISwitchManagerAware service) {
1680 log.trace("Got a service UNset request");
1681 if (this.switchManagerAware != null) {
1682 this.switchManagerAware.remove(service);
1686 public void setInventoryListener(IInventoryListener service) {
1687 log.trace("Got inventory listener set request {}", service);
1688 if (this.inventoryListeners != null) {
1689 this.inventoryListeners.add(service);
1692 // bulk update for newly joined
1693 bulkUpdateService(service);
1696 public void unsetInventoryListener(IInventoryListener service) {
1697 log.trace("Got a service UNset request");
1698 if (this.inventoryListeners != null) {
1699 this.inventoryListeners.remove(service);
1703 public void setSpanAware(ISpanAware service) {
1704 log.trace("Got SpanAware set request {}", service);
1705 if (this.spanAware != null) {
1706 this.spanAware.add(service);
1709 // bulk update for newly joined
1710 spanAwareNotify(service);
1713 public void unsetSpanAware(ISpanAware service) {
1714 log.trace("Got a service UNset request");
1715 if (this.spanAware != null) {
1716 this.spanAware.remove(service);
1720 void setClusterContainerService(IClusterContainerServices s) {
1721 log.trace("Cluster Service set");
1722 this.clusterContainerService = s;
1725 void unsetClusterContainerService(IClusterContainerServices s) {
1726 if (this.clusterContainerService == s) {
1727 log.trace("Cluster Service removed!");
1728 this.clusterContainerService = null;
1732 private void getInventories() {
1733 if (inventoryService == null) {
1734 log.trace("inventory service not avaiable");
1738 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
1739 for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) {
1740 Node node = entry.getKey();
1741 log.debug("getInventories: {} added for container {}", new Object[] { node, containerName });
1742 Map<String, Property> propMap = entry.getValue();
1743 Set<Property> props = new HashSet<Property>();
1744 for (Property property : propMap.values()) {
1745 props.add(property);
1747 addNode(node, props);
1750 Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps();
1751 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) {
1752 Map<String, Property> propMap = entry.getValue();
1753 for (Property property : propMap.values()) {
1754 addNodeConnectorProp(entry.getKey(), property);
1759 private void clearInventories() {
1761 nodeConnectorProps.clear();
1762 nodeConnectorNames.clear();
1763 spanNodeConnectors.clear();
1766 private void notifyNode(Node node, UpdateType type,
1767 Map<String, Property> propMap) {
1768 synchronized (inventoryListeners) {
1769 for (IInventoryListener service : inventoryListeners) {
1770 service.notifyNode(node, type, propMap);
1775 private void notifyNodeConnector(NodeConnector nodeConnector,
1776 UpdateType type, Map<String, Property> propMap) {
1777 synchronized (inventoryListeners) {
1778 for (IInventoryListener service : inventoryListeners) {
1779 service.notifyNodeConnector(nodeConnector, type, propMap);
1785 * For those joined late, bring them up-to-date.
1787 private void switchManagerAwareNotify(ISwitchManagerAware service) {
1788 for (Subnet sub : subnets.values()) {
1789 service.subnetNotify(sub, true);
1792 for (Node node : getNodes()) {
1793 SwitchConfig sc = getSwitchConfig(node.toString());
1794 if ((sc != null) && isDefaultContainer) {
1795 ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
1796 service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive());
1801 private void bulkUpdateService(IInventoryListener service) {
1802 Map<String, Property> propMap;
1803 UpdateType type = UpdateType.ADDED;
1805 for (Node node : getNodes()) {
1806 propMap = nodeProps.get(node);
1807 service.notifyNode(node, type, propMap);
1810 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1811 NodeConnector nodeConnector = entry.getKey();
1812 propMap = nodeConnectorProps.get(nodeConnector);
1813 service.notifyNodeConnector(nodeConnector, type, propMap);
1817 private void spanAwareNotify(ISpanAware service) {
1818 for (Node node : getNodes()) {
1819 for (SpanConfig conf : getSpanConfigList(node)) {
1820 service.spanUpdate(node, conf.getPortArrayList(), true);
1825 private void registerWithOSGIConsole() {
1826 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
1827 .getBundleContext();
1828 bundleContext.registerService(CommandProvider.class.getName(), this,
1833 public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) {
1834 if (nodeConnector == null) {
1838 Config config = (Config) getNodeConnectorProp(nodeConnector,
1839 Config.ConfigPropName);
1840 State state = (State) getNodeConnectorProp(nodeConnector,
1841 State.StatePropName);
1842 return ((config != null) && (config.getValue() == Config.ADMIN_UP)
1843 && (state != null) && (state.getValue() == State.EDGE_UP));
1847 public String getHelp() {
1848 StringBuffer help = new StringBuffer();
1849 help.append("---Switch Manager---\n");
1850 help.append("\t pencs <node id> - Print enabled node connectors for a given node\n");
1851 help.append("\t pdm <node id> - Print switch ports in device map\n");
1852 help.append("\t snt <node id> <tier> - Set node tier number\n");
1853 help.append("\t hostRefresh <on/off/?> - Enable/Disable/Query host refresh\n");
1854 help.append("\t hostRetry <count> - Set host retry count\n");
1855 return help.toString();
1858 public void _pencs(CommandInterpreter ci) {
1859 String st = ci.nextArgument();
1861 ci.println("Please enter node id");
1865 Node node = Node.fromString(st);
1867 ci.println("Please enter node id");
1871 Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node);
1872 if (nodeConnectorSet == null) {
1875 for (NodeConnector nodeConnector : nodeConnectorSet) {
1876 if (nodeConnector == null) {
1879 ci.println(nodeConnector);
1881 ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1884 public void _pdm(CommandInterpreter ci) {
1885 String st = ci.nextArgument();
1887 ci.println("Please enter node id");
1891 Node node = Node.fromString(st);
1893 ci.println("Please enter node id");
1897 Switch sw = getSwitchByNode(node);
1899 ci.println(" NodeConnector Name");
1901 Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors();
1902 String nodeConnectorName;
1903 if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
1904 for (NodeConnector nodeConnector : nodeConnectorSet) {
1905 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1906 nodeConnectorName = (propMap == null) ? null : ((Name) propMap
1907 .get(Name.NamePropName)).getValue();
1908 if (nodeConnectorName != null) {
1909 Node nd = nodeConnector.getNode();
1910 if (!nd.equals(node)) {
1911 log.debug("node not match {} {}", nd, node);
1913 Map<String, NodeConnector> map = nodeConnectorNames
1916 NodeConnector nc = map.get(nodeConnectorName);
1918 log.debug("no nodeConnector named {}",
1920 } else if (!nc.equals(nodeConnector)) {
1921 log.debug("nodeConnector not match {} {}", nc,
1927 ci.println(nodeConnector
1929 + ((nodeConnectorName == null) ? "" : nodeConnectorName)
1930 + "(" + nodeConnector.getID() + ")");
1932 ci.println("Total number of NodeConnectors: "
1933 + nodeConnectorSet.size());
1937 public void _snt(CommandInterpreter ci) {
1938 String st = ci.nextArgument();
1940 ci.println("Please enter node id");
1944 Node node = Node.fromString(st);
1946 ci.println("Please enter node id");
1950 st = ci.nextArgument();
1952 ci.println("Please enter tier number");
1955 Integer tid = Integer.decode(st);
1956 Tier tier = new Tier(tid);
1957 setNodeProp(node, tier);
1960 public void _hostRefresh(CommandInterpreter ci) {
1961 String mode = ci.nextArgument();
1963 ci.println("expecting on/off/?");
1966 if (mode.toLowerCase().equals("on")) {
1968 } else if (mode.toLowerCase().equals("off")) {
1969 hostRefresh = false;
1970 } else if (mode.equals("?")) {
1972 ci.println("host refresh is ON");
1974 ci.println("host refresh is OFF");
1977 ci.println("expecting on/off/?");
1982 public void _hostRetry(CommandInterpreter ci) {
1983 String retry = ci.nextArgument();
1984 if (retry == null) {
1985 ci.println("Please enter a valid number. Current retry count is "
1990 hostRetryCount = Integer.parseInt(retry);
1991 } catch (Exception e) {
1992 ci.println("Please enter a valid number");
1998 public byte[] getNodeMAC(Node node) {
1999 MacAddress mac = (MacAddress) this.getNodeProp(node,
2001 return (mac != null) ? mac.getMacAddress() : null;
2005 public boolean isSpecial(NodeConnector p) {
2006 if (p.getType().equals(NodeConnectorIDType.CONTROLLER)
2007 || p.getType().equals(NodeConnectorIDType.ALL)
2008 || p.getType().equals(NodeConnectorIDType.SWSTACK)
2009 || p.getType().equals(NodeConnectorIDType.HWPATH)) {
2016 * Add span configuration to local cache and notify clients
2018 private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2019 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2021 for (NodeConnector nodeConnector : nodeConnectors) {
2022 if (!spanNodeConnectors.contains(nodeConnector)) {
2023 ncLists.add(nodeConnector);
2027 if (ncLists.size() > 0) {
2028 spanNodeConnectors.addAll(ncLists);
2029 notifySpanPortChange(node, ncLists, true);
2033 private void addSpanPorts(Node node) {
2034 for (SpanConfig conf : getSpanConfigList(node)) {
2035 addSpanPorts(node, conf.getPortArrayList());
2039 private void addSpanPort(NodeConnector nodeConnector) {
2040 // only add if span is configured on this nodeConnector
2041 for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) {
2042 if (conf.getPortArrayList().contains(nodeConnector)) {
2043 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2044 ncLists.add(nodeConnector);
2045 addSpanPorts(nodeConnector.getNode(), ncLists);
2052 * Remove span configuration to local cache and notify clients
2054 private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2055 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2057 for (NodeConnector nodeConnector : nodeConnectors) {
2058 if (spanNodeConnectors.contains(nodeConnector)) {
2059 ncLists.add(nodeConnector);
2063 if (ncLists.size() > 0) {
2064 spanNodeConnectors.removeAll(ncLists);
2065 notifySpanPortChange(node, ncLists, false);
2069 private void removeSpanPorts(Node node) {
2070 for (SpanConfig conf : getSpanConfigList(node)) {
2071 addSpanPorts(node, conf.getPortArrayList());
2075 private void removeSpanPort(NodeConnector nodeConnector) {
2076 if (spanNodeConnectors.contains(nodeConnector)) {
2077 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2078 ncLists.add(nodeConnector);
2079 removeSpanPorts(nodeConnector.getNode(), ncLists);
2083 private void addNodeProps(Node node, Map<String, Property> propMap) {
2084 if (propMap == null) {
2085 propMap = new HashMap<String, Property>();
2087 nodeProps.put(node, propMap);
2091 public Status saveConfiguration() {
2092 return saveSwitchConfig();
2096 * Creates a Name/Tier/Bandwidth Property object based on given property
2097 * name and value. Other property types are not supported yet.
2100 * Name of the Property
2102 * Value of the Property
2103 * @return {@link org.opendaylight.controller.sal.core.Property}
2106 public Property createProperty(String propName, String propValue) {
2107 if (propName == null) {
2108 log.debug("propName is null");
2111 if (propValue == null) {
2112 log.debug("propValue is null");
2117 if (propName.equalsIgnoreCase(Description.propertyName)) {
2118 return new Description(propValue);
2119 } else if (propName.equalsIgnoreCase(Tier.TierPropName)) {
2120 int tier = Integer.parseInt(propValue);
2121 return new Tier(tier);
2122 } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) {
2123 long bw = Long.parseLong(propValue);
2124 return new Bandwidth(bw);
2125 } else if (propName.equalsIgnoreCase(ForwardingMode.name)) {
2126 int mode = Integer.parseInt(propValue);
2127 return new ForwardingMode(mode);
2129 log.debug("Not able to create {} property", propName);
2131 } catch (Exception e) {
2132 log.debug("createProperty caught exception {}", e.getMessage());
2138 @SuppressWarnings("deprecation")
2140 public String getNodeDescription(Node node) {
2141 // Check first if user configured a name
2142 SwitchConfig config = getSwitchConfig(node.toString());
2143 if (config != null) {
2144 String configuredDesc = config.getNodeDescription();
2145 if (configuredDesc != null && !configuredDesc.isEmpty()) {
2146 return configuredDesc;
2150 // No name configured by user, get the node advertised name
2151 Description desc = (Description) getNodeProp(node,
2152 Description.propertyName);
2153 return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? ""