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.Date;
20 import java.util.Dictionary;
21 import java.util.EnumSet;
22 import java.util.Enumeration;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.concurrent.ConcurrentMap;
30 import java.util.concurrent.CopyOnWriteArrayList;
32 import org.apache.felix.dm.Component;
33 import org.eclipse.osgi.framework.console.CommandInterpreter;
34 import org.eclipse.osgi.framework.console.CommandProvider;
35 import org.opendaylight.controller.clustering.services.CacheConfigException;
36 import org.opendaylight.controller.clustering.services.CacheExistException;
37 import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
38 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
39 import org.opendaylight.controller.clustering.services.IClusterServices;
40 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
41 import org.opendaylight.controller.sal.core.Bandwidth;
42 import org.opendaylight.controller.sal.core.Config;
43 import org.opendaylight.controller.sal.core.ConstructionException;
44 import org.opendaylight.controller.sal.core.Description;
45 import org.opendaylight.controller.sal.core.ForwardingMode;
46 import org.opendaylight.controller.sal.core.MacAddress;
47 import org.opendaylight.controller.sal.core.Name;
48 import org.opendaylight.controller.sal.core.Node;
49 import org.opendaylight.controller.sal.core.NodeConnector;
50 import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType;
51 import org.opendaylight.controller.sal.core.Property;
52 import org.opendaylight.controller.sal.core.State;
53 import org.opendaylight.controller.sal.core.Tier;
54 import org.opendaylight.controller.sal.core.UpdateType;
55 import org.opendaylight.controller.sal.inventory.IInventoryService;
56 import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates;
57 import org.opendaylight.controller.sal.utils.GlobalConstants;
58 import org.opendaylight.controller.sal.utils.HexEncode;
59 import org.opendaylight.controller.sal.utils.IObjectReader;
60 import org.opendaylight.controller.sal.utils.ObjectReader;
61 import org.opendaylight.controller.sal.utils.ObjectWriter;
62 import org.opendaylight.controller.sal.utils.Status;
63 import org.opendaylight.controller.sal.utils.StatusCode;
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 SwitchManagerImpl implements ISwitchManager,
87 IConfigurationContainerAware, IObjectReader,
88 ICacheUpdateAware<Long, String>, IListenInventoryUpdates,
90 private static Logger log = LoggerFactory
91 .getLogger(SwitchManagerImpl.class);
92 private static String ROOT = GlobalConstants.STARTUPHOME.toString();
93 private static final String SAVE = "Save";
94 private String subnetFileName = null, spanFileName = null,
95 switchConfigFileName = null;
96 private final List<NodeConnector> spanNodeConnectors = new CopyOnWriteArrayList<NodeConnector>();
97 // set of Subnets keyed by the InetAddress
98 private ConcurrentMap<InetAddress, Subnet> subnets;
99 private ConcurrentMap<String, SubnetConfig> subnetsConfigList;
100 private ConcurrentMap<SpanConfig, SpanConfig> spanConfigList;
101 // manually configured parameters for the node such as name, tier, mode
102 private ConcurrentMap<String, SwitchConfig> nodeConfigList;
103 private ConcurrentMap<Long, String> configSaveEvent;
104 private ConcurrentMap<Node, Map<String, Property>> nodeProps;
105 private ConcurrentMap<NodeConnector, Map<String, Property>> nodeConnectorProps;
106 private ConcurrentMap<Node, Map<String, NodeConnector>> nodeConnectorNames;
107 private IInventoryService inventoryService;
108 private final Set<ISwitchManagerAware> switchManagerAware = Collections
109 .synchronizedSet(new HashSet<ISwitchManagerAware>());
110 private final Set<IInventoryListener> inventoryListeners = Collections
111 .synchronizedSet(new HashSet<IInventoryListener>());
112 private final Set<ISpanAware> spanAware = Collections
113 .synchronizedSet(new HashSet<ISpanAware>());
115 private static boolean hostRefresh = true;
116 private int hostRetryCount = 5;
117 private IClusterContainerServices clusterContainerService = null;
118 private String containerName = null;
119 private boolean isDefaultContainer = true;
120 private static final int REPLACE_RETRY = 1;
122 public enum ReasonCode {
123 SUCCESS("Success"), FAILURE("Failure"), INVALID_CONF(
124 "Invalid Configuration"), EXIST("Entry Already Exist"), CONFLICT(
125 "Configuration Conflict with Existing Entry");
127 private final String name;
129 private ReasonCode(String name) {
134 public String toString() {
139 public void notifySubnetChange(Subnet sub, boolean add) {
140 synchronized (switchManagerAware) {
141 for (Object subAware : switchManagerAware) {
143 ((ISwitchManagerAware) subAware).subnetNotify(sub, add);
144 } catch (Exception e) {
145 log.error("Failed to notify Subnet change {}",
152 public void notifySpanPortChange(Node node, List<NodeConnector> ports,
154 synchronized (spanAware) {
155 for (Object sa : spanAware) {
157 ((ISpanAware) sa).spanUpdate(node, ports, add);
158 } catch (Exception e) {
159 log.error("Failed to notify Span Interface change {}",
166 private void notifyModeChange(Node node, boolean proactive) {
167 synchronized (switchManagerAware) {
168 for (ISwitchManagerAware service : switchManagerAware) {
170 service.modeChangeNotify(node, proactive);
171 } catch (Exception e) {
172 log.error("Failed to notify Subnet change {}",
179 public void startUp() {
180 // Initialize configuration file names
181 subnetFileName = ROOT + "subnets_" + this.getContainerName() + ".conf";
182 spanFileName = ROOT + "spanPorts_" + this.getContainerName() + ".conf";
183 switchConfigFileName = ROOT + "switchConfig_" + this.getContainerName()
186 // Instantiate cluster synced variables
191 * Read startup and build database if we have not already gotten the
192 * configurations synced from another node
194 if (subnetsConfigList.isEmpty()) {
195 loadSubnetConfiguration();
197 if (spanConfigList.isEmpty()) {
198 loadSpanConfiguration();
200 if (nodeConfigList.isEmpty()) {
201 loadSwitchConfiguration();
204 MAC = getHardwareMAC();
207 public void shutDown() {
210 @SuppressWarnings("deprecation")
211 private void allocateCaches() {
212 if (this.clusterContainerService == null) {
213 this.nonClusterObjectCreate();
214 log.warn("un-initialized clusterContainerService, can't create cache");
219 clusterContainerService.createCache(
220 "switchmanager.subnetsConfigList",
221 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
222 clusterContainerService.createCache("switchmanager.spanConfigList",
223 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
224 clusterContainerService.createCache("switchmanager.nodeConfigList",
225 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
226 clusterContainerService.createCache("switchmanager.subnets",
227 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
228 clusterContainerService.createCache(
229 "switchmanager.configSaveEvent",
230 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
231 clusterContainerService.createCache("switchmanager.nodeProps",
232 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
233 clusterContainerService.createCache(
234 "switchmanager.nodeConnectorProps",
235 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
236 clusterContainerService.createCache(
237 "switchmanager.nodeConnectorNames",
238 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
239 } catch (CacheConfigException cce) {
240 log.error("\nCache configuration invalid - check cache mode");
241 } catch (CacheExistException ce) {
242 log.error("\nCache already exits - destroy and recreate if needed");
246 @SuppressWarnings({ "unchecked", "deprecation" })
247 private void retrieveCaches() {
248 if (this.clusterContainerService == null) {
249 log.info("un-initialized clusterContainerService, can't create cache");
253 subnetsConfigList = (ConcurrentMap<String, SubnetConfig>) clusterContainerService
254 .getCache("switchmanager.subnetsConfigList");
255 if (subnetsConfigList == null) {
256 log.error("\nFailed to get cache for subnetsConfigList");
259 spanConfigList = (ConcurrentMap<SpanConfig, SpanConfig>) clusterContainerService
260 .getCache("switchmanager.spanConfigList");
261 if (spanConfigList == null) {
262 log.error("\nFailed to get cache for spanConfigList");
265 nodeConfigList = (ConcurrentMap<String, SwitchConfig>) clusterContainerService
266 .getCache("switchmanager.nodeConfigList");
267 if (nodeConfigList == null) {
268 log.error("\nFailed to get cache for nodeConfigList");
271 subnets = (ConcurrentMap<InetAddress, Subnet>) clusterContainerService
272 .getCache("switchmanager.subnets");
273 if (subnets == null) {
274 log.error("\nFailed to get cache for subnets");
277 configSaveEvent = (ConcurrentMap<Long, String>) clusterContainerService
278 .getCache("switchmanager.configSaveEvent");
279 if (configSaveEvent == null) {
280 log.error("\nFailed to get cache for configSaveEvent");
283 nodeProps = (ConcurrentMap<Node, Map<String, Property>>) clusterContainerService
284 .getCache("switchmanager.nodeProps");
285 if (nodeProps == null) {
286 log.error("\nFailed to get cache for nodeProps");
289 nodeConnectorProps = (ConcurrentMap<NodeConnector, Map<String, Property>>) clusterContainerService
290 .getCache("switchmanager.nodeConnectorProps");
291 if (nodeConnectorProps == null) {
292 log.error("\nFailed to get cache for nodeConnectorProps");
295 nodeConnectorNames = (ConcurrentMap<Node, Map<String, NodeConnector>>) clusterContainerService
296 .getCache("switchmanager.nodeConnectorNames");
297 if (nodeConnectorNames == null) {
298 log.error("\nFailed to get cache for nodeConnectorNames");
302 private void nonClusterObjectCreate() {
303 subnetsConfigList = new ConcurrentHashMap<String, SubnetConfig>();
304 spanConfigList = new ConcurrentHashMap<SpanConfig, SpanConfig>();
305 nodeConfigList = new ConcurrentHashMap<String, SwitchConfig>();
306 subnets = new ConcurrentHashMap<InetAddress, Subnet>();
307 configSaveEvent = new ConcurrentHashMap<Long, String>();
308 nodeProps = new ConcurrentHashMap<Node, Map<String, Property>>();
309 nodeConnectorProps = new ConcurrentHashMap<NodeConnector, Map<String, Property>>();
310 nodeConnectorNames = new ConcurrentHashMap<Node, Map<String, NodeConnector>>();
314 public List<SubnetConfig> getSubnetsConfigList() {
315 return new ArrayList<SubnetConfig>(subnetsConfigList.values());
319 public SubnetConfig getSubnetConfig(String subnet) {
320 return subnetsConfigList.get(subnet);
323 private List<SpanConfig> getSpanConfigList(Node node) {
324 List<SpanConfig> confList = new ArrayList<SpanConfig>();
325 String nodeId = node.toString();
326 for (SpanConfig conf : spanConfigList.values()) {
327 if (conf.matchNode(nodeId)) {
334 public List<SwitchConfig> getNodeConfigList() {
335 return new ArrayList<SwitchConfig>(nodeConfigList.values());
339 public SwitchConfig getSwitchConfig(String switchId) {
340 return nodeConfigList.get(switchId);
343 public Switch getSwitchByNode(Node node) {
344 Switch sw = new Switch(node);
346 MacAddress mac = (MacAddress) this.getNodeProp(node,
349 sw.setDataLayerAddress(mac.getMacAddress());
351 Set<NodeConnector> ncSet = getPhysicalNodeConnectors(node);
352 sw.setNodeConnectors(ncSet);
354 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
355 for (NodeConnector nodeConnector : ncSet) {
356 if (spanNodeConnectors.contains(nodeConnector)) {
357 ncList.add(nodeConnector);
360 sw.addSpanPorts(ncList);
366 public List<Switch> getNetworkDevices() {
367 Set<Node> nodeSet = getNodes();
368 List<Switch> swList = new ArrayList<Switch>();
369 if (nodeSet != null) {
370 for (Node node : nodeSet) {
371 swList.add(getSwitchByNode(node));
378 private Status updateConfig(SubnetConfig conf, boolean add) {
380 if(subnetsConfigList.putIfAbsent(conf.getName(), conf) != null) {
381 String msg = "Cluster conflict: Subnet with name " + conf.getName() + "already exists.";
382 return new Status(StatusCode.CONFLICT, msg);
385 subnetsConfigList.remove(conf.getName());
387 return new Status(StatusCode.SUCCESS);
390 private Status updateDatabase(SubnetConfig conf, boolean add) {
392 Subnet subnetCurr = subnets.get(conf.getIPnum());
394 if (subnetCurr == null) {
395 subnet = new Subnet(conf);
397 subnet = subnetCurr.clone();
399 // In case of API3 call we may receive the ports along with the
401 if (!conf.isGlobal()) {
402 Set<NodeConnector> sp = conf.getSubnetNodeConnectors();
403 subnet.addNodeConnectors(sp);
405 boolean result = false;
406 if(subnetCurr == null) {
407 if(subnets.putIfAbsent(conf.getIPnum(), subnet) == null) {
411 result = subnets.replace(conf.getIPnum(), subnetCurr, subnet);
414 String msg = "Cluster conflict: Conflict while adding the subnet " + conf.getIPnum();
415 return new Status(StatusCode.CONFLICT, msg);
417 } else { // This is the deletion of the whole subnet
418 subnets.remove(conf.getIPnum());
420 return new Status(StatusCode.SUCCESS);
423 private Status semanticCheck(SubnetConfig conf) {
424 Subnet newSubnet = new Subnet(conf);
425 Set<InetAddress> IPs = subnets.keySet();
427 return new Status(StatusCode.SUCCESS);
429 for (InetAddress i : IPs) {
430 Subnet existingSubnet = subnets.get(i);
431 if ((existingSubnet != null)
432 && !existingSubnet.isMutualExclusive(newSubnet)) {
433 return new Status(StatusCode.CONFLICT);
436 return new Status(StatusCode.SUCCESS);
439 private Status addRemoveSubnet(SubnetConfig conf, boolean add) {
440 // Valid config check
441 if (!conf.isValidConfig()) {
442 String msg = "Invalid Subnet configuration";
444 return new Status(StatusCode.BADREQUEST, msg);
449 if (subnetsConfigList.containsKey(conf.getName())) {
450 return new Status(StatusCode.CONFLICT,
451 "Same subnet config already exists");
454 Status rc = semanticCheck(conf);
455 if (!rc.isSuccess()) {
461 Status rc = updateDatabase(conf, add);
463 if (rc.isSuccess()) {
464 // Update Configuration
465 rc = updateConfig(conf, add);
466 if(!rc.isSuccess()) {
467 updateDatabase(conf, (!add));
475 * Adds Subnet configured in GUI or API3
478 public Status addSubnet(SubnetConfig conf) {
479 return this.addRemoveSubnet(conf, true);
483 public Status removeSubnet(SubnetConfig conf) {
484 return this.addRemoveSubnet(conf, false);
488 public Status removeSubnet(String name) {
489 SubnetConfig conf = subnetsConfigList.get(name);
491 return new Status(StatusCode.SUCCESS, "Subnet not present");
493 return this.addRemoveSubnet(conf, false);
497 public Status addPortsToSubnet(String name, String switchPorts) {
498 SubnetConfig confCurr = subnetsConfigList.get(name);
499 if (confCurr == null) {
500 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
502 if (!confCurr.isValidSwitchPort(switchPorts)) {
503 return new Status(StatusCode.BADREQUEST, "Invalid switchports");
506 Subnet subCurr = subnets.get(confCurr.getIPnum());
507 if (subCurr == null) {
508 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPnum());
509 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
513 Subnet sub = subCurr.clone();
514 Set<NodeConnector> sp = confCurr.getNodeConnectors(switchPorts);
515 sub.addNodeConnectors(sp);
516 boolean subnetsReplace = subnets.replace(confCurr.getIPnum(), subCurr, sub);
517 if (!subnetsReplace) {
518 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
519 return new Status(StatusCode.CONFLICT, msg);
522 // Update Configuration
523 SubnetConfig conf = confCurr.clone();
524 conf.addNodeConnectors(switchPorts);
525 boolean result = subnetsConfigList.replace(name, confCurr, conf);
527 // TODO: recovery using Transactionality
528 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
529 return new Status(StatusCode.CONFLICT, msg);
532 return new Status(StatusCode.SUCCESS);
536 public Status removePortsFromSubnet(String name, String switchPorts) {
537 SubnetConfig confCurr = subnetsConfigList.get(name);
538 if (confCurr == null) {
539 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
542 Subnet subCurr = subnets.get(confCurr.getIPnum());
543 if (subCurr == null) {
544 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPnum());
545 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
549 Subnet sub = subCurr.clone();
550 Set<NodeConnector> sp = confCurr.getNodeConnectors(switchPorts);
551 sub.deleteNodeConnectors(sp);
552 boolean subnetsReplace = subnets.replace(confCurr.getIPnum(), subCurr, sub);
553 if (!subnetsReplace) {
554 String msg = "Cluster conflict: Conflict while removing ports from the subnet " + name;
555 return new Status(StatusCode.CONFLICT, msg);
558 // Update Configuration
559 SubnetConfig conf = confCurr.clone();
560 conf.removeNodeConnectors(switchPorts);
561 boolean result = subnetsConfigList.replace(name, confCurr, conf);
563 // TODO: recovery using Transactionality
564 String msg = "Cluster conflict: Conflict while removing ports from " + conf;
565 return new Status(StatusCode.CONFLICT, msg);
568 return new Status(StatusCode.SUCCESS);
571 public String getContainerName() {
572 if (containerName == null) {
573 return GlobalConstants.DEFAULT.toString();
575 return containerName;
579 public Subnet getSubnetByNetworkAddress(InetAddress networkAddress) {
581 Set<InetAddress> indices = subnets.keySet();
582 for (InetAddress i : indices) {
583 sub = subnets.get(i);
584 if (sub.isSubnetOf(networkAddress)) {
592 public Object readObject(ObjectInputStream ois)
593 throws FileNotFoundException, IOException, ClassNotFoundException {
594 // Perform the class deserialization locally, from inside the package
595 // where the class is defined
596 return ois.readObject();
599 @SuppressWarnings("unchecked")
600 private void loadSubnetConfiguration() {
601 ObjectReader objReader = new ObjectReader();
602 ConcurrentMap<String, SubnetConfig> confList = (ConcurrentMap<String, SubnetConfig>) objReader
603 .read(this, subnetFileName);
605 if (confList == null) {
609 for (SubnetConfig conf : confList.values()) {
614 @SuppressWarnings("unchecked")
615 private void loadSpanConfiguration() {
616 ObjectReader objReader = new ObjectReader();
617 ConcurrentMap<Integer, SpanConfig> confList = (ConcurrentMap<Integer, SpanConfig>) objReader
618 .read(this, spanFileName);
620 if (confList == null) {
624 for (SpanConfig conf : confList.values()) {
629 @SuppressWarnings("unchecked")
630 private void loadSwitchConfiguration() {
631 ObjectReader objReader = new ObjectReader();
632 ConcurrentMap<String, SwitchConfig> confList = (ConcurrentMap<String, SwitchConfig>) objReader
633 .read(this, switchConfigFileName);
635 if (confList == null) {
639 for (SwitchConfig conf : confList.values()) {
640 updateSwitchConfig(conf);
645 public void updateSwitchConfig(SwitchConfig cfgObject) {
646 // update default container only
647 if (!isDefaultContainer) {
651 SwitchConfig sc = nodeConfigList.get(cfgObject.getNodeId());
653 if (nodeConfigList.putIfAbsent(cfgObject.getNodeId(), cfgObject) != null) {
657 if (!nodeConfigList.replace(cfgObject.getNodeId(), sc, cfgObject)) {
662 boolean modeChange = false;
664 if ((sc == null) || !cfgObject.getMode().equals(sc.getMode())) {
668 String nodeId = cfgObject.getNodeId();
669 Node node = Node.fromString(nodeId);
670 Map<String, Property> propMapCurr = nodeProps.get(node);
671 if (propMapCurr == null) {
674 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
675 Property desc = new Description(cfgObject.getNodeDescription());
676 propMap.put(desc.getName(), desc);
677 Property tier = new Tier(Integer.parseInt(cfgObject.getTier()));
678 propMap.put(tier.getName(), tier);
680 if (!nodeProps.replace(node, propMapCurr, propMap)) {
681 // TODO rollback using Transactionality
685 log.info("Set Node {}'s Mode to {}", nodeId, cfgObject.getMode());
688 notifyModeChange(node, cfgObject.isProactive());
693 public Status updateNodeConfig(SwitchConfig switchConfig) {
694 Status status = switchConfig.validate();
695 if (!status.isSuccess()) {
699 Map<String, Property> updateProperties = switchConfig.getNodeProperties();
700 String nodeId = switchConfig.getNodeId();
701 ForwardingMode mode = (ForwardingMode) updateProperties.get(ForwardingMode.name);
703 if (isDefaultContainer) {
704 if (!mode.isValid()) {
705 return new Status(StatusCode.NOTACCEPTABLE, "Invalid Forwarding Mode Value.");
708 return new Status(StatusCode.NOTACCEPTABLE,
709 "Forwarding Mode modification is allowed only in default container");
712 boolean modeChange = false;
713 SwitchConfig sc = nodeConfigList.get(nodeId);
714 Map<String, Property> prevNodeProperties = new HashMap<String, Property>();
716 if ((mode != null) && mode.isProactive()) {
719 if (!updateProperties.isEmpty()) {
720 if (nodeConfigList.putIfAbsent(nodeId, switchConfig) != null) {
721 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
725 prevNodeProperties = new HashMap<String, Property>(sc.getNodeProperties());
726 ForwardingMode prevMode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
728 if ((prevMode != null) && (prevMode.isProactive())) {
732 if (((prevMode != null) && (prevMode.getValue() != mode.getValue()))
733 || (prevMode == null && mode.isProactive())) {
737 if (updateProperties.isEmpty()) {
738 nodeConfigList.remove(nodeId);
740 if (!nodeConfigList.replace(nodeId, sc, switchConfig)) {
741 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
745 Node node = Node.fromString(nodeId);
746 Map<String, Property> propMapCurr = nodeProps.get(node);
747 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
748 if (propMapCurr == null) {
749 return new Status(StatusCode.SUCCESS);
751 if (!prevNodeProperties.isEmpty()) {
752 for (String prop : prevNodeProperties.keySet()) {
753 if (!updateProperties.containsKey(prop)) {
754 if (prop.equals(Description.propertyName)) {
755 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
756 if (nodeProp.get(node) != null) {
757 propMap.put(Description.propertyName, nodeProp.get(node).get(Description.propertyName));
761 propMap.remove(prop);
765 propMap.putAll(updateProperties);
766 if (!nodeProps.replace(node, propMapCurr, propMap)) {
767 // TODO rollback using Transactionality
768 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration.");
771 notifyModeChange(node, (mode == null) ? false : mode.isProactive());
773 return new Status(StatusCode.SUCCESS);
777 public Status removeNodeConfig(String nodeId) {
778 if ((nodeId == null) || (nodeId.isEmpty())) {
779 return new Status(StatusCode.BADREQUEST, "nodeId cannot be empty.");
781 Map<String, Property> nodeProperties = getSwitchConfig(nodeId).getNodeProperties();
782 Node node = Node.fromString(nodeId);
783 Map<String, Property> propMapCurr = nodeProps.get(node);
784 if ((propMapCurr != null) && (nodeProperties != null) && (!nodeProperties.isEmpty())) {
785 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
786 for (String prop : nodeProperties.keySet()) {
787 if (prop.equals(Description.propertyName)) {
788 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
789 if (nodeProp.get(node) != null) {
790 propMap.put(Description.propertyName, nodeProp.get(node).get(Description.propertyName));
794 propMap.remove(prop);
796 if (!nodeProps.replace(node, propMapCurr, propMap)) {
797 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration.");
800 if (nodeConfigList != null) {
801 nodeConfigList.remove(nodeId);
803 return new Status(StatusCode.SUCCESS);
807 public Status saveSwitchConfig() {
808 // Publish the save config event to the cluster nodes
809 configSaveEvent.put(new Date().getTime(), SAVE);
810 return saveSwitchConfigInternal();
813 public Status saveSwitchConfigInternal() {
814 Status retS = null, retP = null;
815 ObjectWriter objWriter = new ObjectWriter();
817 retS = objWriter.write(new ConcurrentHashMap<String, SubnetConfig>(
818 subnetsConfigList), subnetFileName);
819 retP = objWriter.write(new ConcurrentHashMap<SpanConfig, SpanConfig>(
820 spanConfigList), spanFileName);
821 retS = objWriter.write(new ConcurrentHashMap<String, SwitchConfig>(
822 nodeConfigList), switchConfigFileName);
824 if (retS.equals(retP)) {
825 if (retS.isSuccess()) {
828 return new Status(StatusCode.INTERNALERROR, "Save failed");
831 return new Status(StatusCode.INTERNALERROR, "Partial save failure");
836 public List<SpanConfig> getSpanConfigList() {
837 return new ArrayList<SpanConfig>(spanConfigList.values());
841 public Status addSpanConfig(SpanConfig conf) {
842 // Valid config check
843 if (!conf.isValidConfig()) {
844 String msg = "Invalid Span configuration";
846 return new Status(StatusCode.BADREQUEST, msg);
850 if (spanConfigList.containsKey(conf)) {
851 return new Status(StatusCode.CONFLICT, "Same span config exists");
854 // Update configuration
855 if (spanConfigList.putIfAbsent(conf, conf) == null) {
856 // Update database and notify clients
857 addSpanPorts(conf.getNode(), conf.getPortArrayList());
860 return new Status(StatusCode.SUCCESS);
864 public Status removeSpanConfig(SpanConfig conf) {
865 removeSpanPorts(conf.getNode(), conf.getPortArrayList());
867 // Update configuration
868 spanConfigList.remove(conf);
870 return new Status(StatusCode.SUCCESS);
874 public List<NodeConnector> getSpanPorts(Node node) {
875 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
877 for (NodeConnector nodeConnector : spanNodeConnectors) {
878 if (nodeConnector.getNode().equals(node)) {
879 ncList.add(nodeConnector);
886 public void entryCreated(Long key, String cacheName, boolean local) {
890 public void entryUpdated(Long key, String new_value, String cacheName,
891 boolean originLocal) {
892 saveSwitchConfigInternal();
896 public void entryDeleted(Long key, String cacheName, boolean originLocal) {
899 private void addNode(Node node, Set<Property> props) {
900 log.trace("{} added, props: {}", node, props);
901 if (nodeProps == null) {
905 Map<String, Property> propMapCurr = nodeProps.get(node);
906 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
907 : new HashMap<String, Property>(propMapCurr);
909 // copy node properties from plugin
911 for (Property prop : props) {
912 propMap.put(prop.getName(), prop);
916 // copy node properties from config
917 boolean proactiveForwarding = false;
918 if (nodeConfigList != null) {
919 String nodeId = node.toString();
920 SwitchConfig conf = nodeConfigList.get(nodeId);
921 if (conf != null && (conf.getNodeProperties() != null)) {
922 Map<String, Property> nodeProperties = conf.getNodeProperties();
923 propMap.putAll(nodeProperties);
924 if (nodeProperties.get(ForwardingMode.name) != null) {
925 ForwardingMode mode = (ForwardingMode) nodeProperties.get(ForwardingMode.name);
926 proactiveForwarding = mode.isProactive();
931 boolean result = false;
932 if (propMapCurr == null) {
933 if (nodeProps.putIfAbsent(node, propMap) == null) {
937 result = nodeProps.replace(node, propMapCurr, propMap);
941 log.debug("Cluster conflict: Conflict while adding the node properties. Node: {} Properties: {}",
942 node.getID(), props);
943 addNodeProps(node, propMap);
946 // check if span ports are configed
949 // notify node listeners
950 notifyNode(node, UpdateType.ADDED, propMap);
952 // notify proactive mode forwarding
953 if (proactiveForwarding) {
954 notifyModeChange(node, true);
958 private void removeNode(Node node) {
959 log.trace("{} removed", node);
960 if (nodeProps == null) {
963 nodeProps.remove(node);
965 // check if span ports need to be cleaned up
966 removeSpanPorts(node);
968 /* notify node listeners */
969 notifyNode(node, UpdateType.REMOVED, null);
972 private void updateNode(Node node, Set<Property> props) {
973 log.trace("{} updated, props: {}", node, props);
974 if (nodeProps == null || !nodeProps.containsKey(node) ||
975 props == null || props.isEmpty()) {
979 Map<String, Property> propMapCurr = nodeProps.get(node);
980 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
981 : new HashMap<String, Property>(propMapCurr);
983 // copy node properties from plugin
984 for (Property prop : props) {
985 propMap.put(prop.getName(), prop);
988 if (propMapCurr == null) {
989 if (nodeProps.putIfAbsent(node, propMap) != null) {
990 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
991 node.getID(), props);
992 addNodeProps(node, propMap);
995 if (!nodeProps.replace(node, propMapCurr, propMap)) {
996 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
997 node.getID(), props);
998 addNodeProps(node, propMap);
1002 /* notify node listeners */
1003 notifyNode(node, UpdateType.CHANGED, propMap);
1007 public void updateNode(Node node, UpdateType type, Set<Property> props) {
1008 log.debug("updateNode: {} type {} props {} for container {}",
1009 new Object[] { node, type, props, containerName });
1012 addNode(node, props);
1015 updateNode(node, props);
1026 public void updateNodeConnector(NodeConnector nodeConnector,
1027 UpdateType type, Set<Property> props) {
1028 Map<String, Property> propMap = new HashMap<String, Property>();
1030 log.debug("updateNodeConnector: {} type {} props {} for container {}",
1031 new Object[] { nodeConnector, type, props, containerName });
1033 if (nodeConnectorProps == null) {
1040 if (props != null) {
1041 for (Property prop : props) {
1042 addNodeConnectorProp(nodeConnector, prop);
1043 propMap.put(prop.getName(), prop);
1046 addNodeConnectorProp(nodeConnector, null);
1049 addSpanPort(nodeConnector);
1052 removeNodeConnectorAllProps(nodeConnector);
1054 // clean up span config
1055 removeSpanPort(nodeConnector);
1061 notifyNodeConnector(nodeConnector, type, propMap);
1065 public Set<Node> getNodes() {
1066 return (nodeProps != null) ? new HashSet<Node>(nodeProps.keySet())
1071 * Returns a copy of a list of properties for a given node
1076 * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps
1077 * (org.opendaylight.controller.sal.core.Node)
1080 public Map<String, Property> getNodeProps(Node node) {
1081 Map<String, Property> rv = new HashMap<String, Property>();
1082 if (this.nodeProps != null) {
1083 rv = this.nodeProps.get(node);
1085 /* make a copy of it */
1086 rv = new HashMap<String, Property>(rv);
1093 public Property getNodeProp(Node node, String propName) {
1094 Map<String, Property> propMap = getNodeProps(node);
1095 return (propMap != null) ? propMap.get(propName) : null;
1099 public void setNodeProp(Node node, Property prop) {
1101 for (int i = 0; i <= REPLACE_RETRY; i++) {
1102 /* Get a copy of the property map */
1103 Map<String, Property> propMapCurr = getNodeProps(node);
1104 if (propMapCurr == null) {
1108 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1109 propMap.put(prop.getName(), prop);
1111 if (nodeProps.replace(node, propMapCurr, propMap)) {
1114 if (!propMapCurr.get(prop.getName()).equals(nodeProps.get(node).get(prop.getName()))) {
1115 log.debug("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1119 log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1123 public Status removeNodeProp(Node node, String propName) {
1124 for (int i = 0; i <= REPLACE_RETRY; i++) {
1125 Map<String, Property> propMapCurr = getNodeProps(node);
1126 if (propMapCurr != null) {
1127 if (!propMapCurr.containsKey(propName)) {
1128 return new Status(StatusCode.SUCCESS);
1130 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1131 propMap.remove(propName);
1132 if (nodeProps.replace(node, propMapCurr, propMap)) {
1133 return new Status(StatusCode.SUCCESS);
1135 if (!propMapCurr.get(propName).equals(nodeProps.get(node).get(propName))) {
1136 String msg = "Cluster conflict: Unable to remove property " + propName + " for node "
1138 return new Status(StatusCode.CONFLICT, msg);
1142 return new Status(StatusCode.SUCCESS);
1145 String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID();
1146 return new Status(StatusCode.CONFLICT, msg);
1150 public Status removeNodeAllProps(Node node) {
1151 this.nodeProps.remove(node);
1152 return new Status(StatusCode.SUCCESS);
1156 public Set<NodeConnector> getUpNodeConnectors(Node node) {
1157 if (nodeConnectorProps == null) {
1161 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1162 for (NodeConnector nodeConnector : nodeConnectorProps.keySet()) {
1163 if (!nodeConnector.getNode().equals(node)) {
1166 if (isNodeConnectorEnabled(nodeConnector)) {
1167 nodeConnectorSet.add(nodeConnector);
1171 return nodeConnectorSet;
1175 public Set<NodeConnector> getNodeConnectors(Node node) {
1176 if (nodeConnectorProps == null) {
1180 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1181 for (NodeConnector nodeConnector : nodeConnectorProps.keySet()) {
1182 if (!nodeConnector.getNode().equals(node)) {
1185 nodeConnectorSet.add(nodeConnector);
1188 return nodeConnectorSet;
1192 public Set<NodeConnector> getPhysicalNodeConnectors(Node node) {
1193 if (nodeConnectorProps == null) {
1197 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1198 for (NodeConnector nodeConnector : nodeConnectorProps.keySet()) {
1199 if (!nodeConnector.getNode().equals(node)
1200 || isSpecial(nodeConnector)) {
1203 nodeConnectorSet.add(nodeConnector);
1206 return nodeConnectorSet;
1210 public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) {
1211 Map<String, Property> rv = new HashMap<String, Property>();
1212 if (this.nodeConnectorProps != null) {
1213 rv = this.nodeConnectorProps.get(nodeConnector);
1215 rv = new HashMap<String, Property>(rv);
1222 public Property getNodeConnectorProp(NodeConnector nodeConnector,
1224 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1225 return (propMap != null) ? propMap.get(propName) : null;
1228 private byte[] getHardwareMAC() {
1229 Enumeration<NetworkInterface> nis;
1231 nis = NetworkInterface.getNetworkInterfaces();
1232 } catch (SocketException e1) {
1237 for (; nis.hasMoreElements();) {
1238 NetworkInterface ni = nis.nextElement();
1240 MAC = ni.getHardwareAddress();
1241 } catch (SocketException e) {
1252 public byte[] getControllerMAC() {
1257 public boolean isHostRefreshEnabled() {
1262 public int getHostRetryCount() {
1263 return hostRetryCount;
1267 public NodeConnector getNodeConnector(Node node, String nodeConnectorName) {
1268 if (nodeConnectorNames == null) {
1272 Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1277 return map.get(nodeConnectorName);
1281 * Adds a node connector and its property if any
1283 * @param nodeConnector
1284 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1286 * name of {@link org.opendaylight.controller.sal.core.Property}
1287 * @return success or failed reason
1290 public Status addNodeConnectorProp(NodeConnector nodeConnector,
1292 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1293 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1294 : new HashMap<String, Property>(propMapCurr);
1296 String msg = "Cluster conflict: Unable to add NodeConnector Property.";
1297 // Just add the nodeConnector if prop is not available (in a non-default
1300 if (propMapCurr == null) {
1301 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1302 return new Status(StatusCode.CONFLICT, msg);
1305 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1306 return new Status(StatusCode.CONFLICT, msg);
1309 return new Status(StatusCode.SUCCESS);
1312 propMap.put(prop.getName(), prop);
1313 if (propMapCurr == null) {
1314 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1315 return new Status(StatusCode.CONFLICT, msg);
1318 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1319 return new Status(StatusCode.CONFLICT, msg);
1323 if (prop.getName().equals(Name.NamePropName)) {
1324 if (nodeConnectorNames != null) {
1325 Node node = nodeConnector.getNode();
1326 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1327 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1328 if (mapCurr != null) {
1329 for (String s : mapCurr.keySet()) {
1331 map.put(s, new NodeConnector(mapCurr.get(s)));
1332 } catch (ConstructionException e) {
1333 e.printStackTrace();
1338 map.put(((Name) prop).getValue(), nodeConnector);
1339 if (mapCurr == null) {
1340 if (nodeConnectorNames.putIfAbsent(node, map) != null) {
1341 // TODO: recovery using Transactionality
1342 return new Status(StatusCode.CONFLICT, msg);
1345 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1346 // TODO: recovery using Transactionality
1347 return new Status(StatusCode.CONFLICT, msg);
1353 return new Status(StatusCode.SUCCESS);
1357 * Removes one property of a node connector
1359 * @param nodeConnector
1360 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1362 * name of {@link org.opendaylight.controller.sal.core.Property}
1363 * @return success or failed reason
1366 public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) {
1367 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1369 if (propMapCurr == null) {
1370 /* Nothing to remove */
1371 return new Status(StatusCode.SUCCESS);
1374 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1375 propMap.remove(propName);
1376 boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap);
1377 String msg = "Cluster conflict: Unable to remove NodeConnector property.";
1379 return new Status(StatusCode.CONFLICT, msg);
1382 if (propName.equals(Name.NamePropName)) {
1383 if (nodeConnectorNames != null) {
1384 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1386 Node node = nodeConnector.getNode();
1387 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1388 if (mapCurr != null) {
1389 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1390 for (String s : mapCurr.keySet()) {
1392 map.put(s, new NodeConnector(mapCurr.get(s)));
1393 } catch (ConstructionException e) {
1394 e.printStackTrace();
1397 map.remove(name.getValue());
1398 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1399 // TODO: recovery using Transactionality
1400 return new Status(StatusCode.CONFLICT, msg);
1407 return new Status(StatusCode.SUCCESS);
1411 * Removes all the properties of a node connector
1413 * @param nodeConnector
1414 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1415 * @return success or failed reason
1418 public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) {
1419 if (nodeConnectorNames != null) {
1420 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1422 Node node = nodeConnector.getNode();
1423 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1424 if (mapCurr != null) {
1425 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1426 for (String s : mapCurr.keySet()) {
1428 map.put(s, new NodeConnector(mapCurr.get(s)));
1429 } catch (ConstructionException e) {
1430 e.printStackTrace();
1433 map.remove(name.getValue());
1434 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1435 log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.",
1436 nodeConnector.getID());
1442 nodeConnectorProps.remove(nodeConnector);
1444 return new Status(StatusCode.SUCCESS);
1448 * Function called by the dependency manager when all the required
1449 * dependencies are satisfied
1452 void init(Component c) {
1453 Dictionary<?, ?> props = c.getServiceProperties();
1454 if (props != null) {
1455 this.containerName = (String) props.get("containerName");
1456 log.trace("Running containerName: {}", this.containerName);
1458 // In the Global instance case the containerName is empty
1459 this.containerName = "";
1461 isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT
1468 * Function called by the dependency manager when at least one dependency
1469 * become unsatisfied or when the component is shutting down because for
1470 * example bundle is being stopped.
1478 * Function called by dependency manager after "init ()" is called and after
1479 * the services provided by the class are registered in the service registry
1484 registerWithOSGIConsole();
1488 * Function called after registered the service in OSGi service registry.
1491 // solicit for existing inventories
1496 * Function called by the dependency manager before the services exported by
1497 * the component are unregistered, this will be followed by a "destroy ()"
1504 public void setInventoryService(IInventoryService service) {
1505 log.trace("Got inventory service set request {}", service);
1506 this.inventoryService = service;
1508 // solicit for existing inventories
1512 public void unsetInventoryService(IInventoryService service) {
1513 log.trace("Got a service UNset request");
1514 this.inventoryService = null;
1516 // clear existing inventories
1520 public void setSwitchManagerAware(ISwitchManagerAware service) {
1521 log.trace("Got inventory service set request {}", service);
1522 if (this.switchManagerAware != null) {
1523 this.switchManagerAware.add(service);
1526 // bulk update for newly joined
1527 switchManagerAwareNotify(service);
1530 public void unsetSwitchManagerAware(ISwitchManagerAware service) {
1531 log.trace("Got a service UNset request");
1532 if (this.switchManagerAware != null) {
1533 this.switchManagerAware.remove(service);
1537 public void setInventoryListener(IInventoryListener service) {
1538 log.trace("Got inventory listener set request {}", service);
1539 if (this.inventoryListeners != null) {
1540 this.inventoryListeners.add(service);
1543 // bulk update for newly joined
1544 bulkUpdateService(service);
1547 public void unsetInventoryListener(IInventoryListener service) {
1548 log.trace("Got a service UNset request");
1549 if (this.inventoryListeners != null) {
1550 this.inventoryListeners.remove(service);
1554 public void setSpanAware(ISpanAware service) {
1555 log.trace("Got SpanAware set request {}", service);
1556 if (this.spanAware != null) {
1557 this.spanAware.add(service);
1560 // bulk update for newly joined
1561 spanAwareNotify(service);
1564 public void unsetSpanAware(ISpanAware service) {
1565 log.trace("Got a service UNset request");
1566 if (this.spanAware != null) {
1567 this.spanAware.remove(service);
1571 void setClusterContainerService(IClusterContainerServices s) {
1572 log.trace("Cluster Service set");
1573 this.clusterContainerService = s;
1576 void unsetClusterContainerService(IClusterContainerServices s) {
1577 if (this.clusterContainerService == s) {
1578 log.trace("Cluster Service removed!");
1579 this.clusterContainerService = null;
1583 private void getInventories() {
1584 if (inventoryService == null) {
1585 log.trace("inventory service not avaiable");
1589 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
1590 for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) {
1591 Node node = entry.getKey();
1592 log.debug("getInventories: {} added for container {}", new Object[] { node, containerName });
1593 Map<String, Property> propMap = entry.getValue();
1594 Set<Property> props = new HashSet<Property>();
1595 for (Property property : propMap.values()) {
1596 props.add(property);
1598 addNode(node, props);
1601 Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps();
1602 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) {
1603 Map<String, Property> propMap = entry.getValue();
1604 for (Property property : propMap.values()) {
1605 addNodeConnectorProp(entry.getKey(), property);
1610 private void clearInventories() {
1612 nodeConnectorProps.clear();
1613 nodeConnectorNames.clear();
1614 spanNodeConnectors.clear();
1617 private void notifyNode(Node node, UpdateType type,
1618 Map<String, Property> propMap) {
1619 synchronized (inventoryListeners) {
1620 for (IInventoryListener service : inventoryListeners) {
1621 service.notifyNode(node, type, propMap);
1626 private void notifyNodeConnector(NodeConnector nodeConnector,
1627 UpdateType type, Map<String, Property> propMap) {
1628 synchronized (inventoryListeners) {
1629 for (IInventoryListener service : inventoryListeners) {
1630 service.notifyNodeConnector(nodeConnector, type, propMap);
1636 * For those joined late, bring them up-to-date.
1638 private void switchManagerAwareNotify(ISwitchManagerAware service) {
1639 for (Subnet sub : subnets.values()) {
1640 service.subnetNotify(sub, true);
1643 for (Node node : getNodes()) {
1644 SwitchConfig sc = getSwitchConfig(node.toString());
1645 if ((sc != null) && isDefaultContainer) {
1646 ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
1647 service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive());
1652 private void bulkUpdateService(IInventoryListener service) {
1653 Map<String, Property> propMap;
1654 UpdateType type = UpdateType.ADDED;
1656 for (Node node : getNodes()) {
1657 propMap = nodeProps.get(node);
1658 service.notifyNode(node, type, propMap);
1661 for (NodeConnector nodeConnector : nodeConnectorProps.keySet()) {
1662 propMap = nodeConnectorProps.get(nodeConnector);
1663 service.notifyNodeConnector(nodeConnector, type, propMap);
1667 private void spanAwareNotify(ISpanAware service) {
1668 for (Node node : getNodes()) {
1669 for (SpanConfig conf : getSpanConfigList(node)) {
1670 service.spanUpdate(node, conf.getPortArrayList(), true);
1675 private void registerWithOSGIConsole() {
1676 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
1677 .getBundleContext();
1678 bundleContext.registerService(CommandProvider.class.getName(), this,
1683 public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) {
1684 if (nodeConnector == null) {
1688 Config config = (Config) getNodeConnectorProp(nodeConnector,
1689 Config.ConfigPropName);
1690 State state = (State) getNodeConnectorProp(nodeConnector,
1691 State.StatePropName);
1692 return ((config != null) && (config.getValue() == Config.ADMIN_UP)
1693 && (state != null) && (state.getValue() == State.EDGE_UP));
1697 public String getHelp() {
1698 StringBuffer help = new StringBuffer();
1699 help.append("---Switch Manager---\n");
1700 help.append("\t pns - Print connected nodes\n");
1701 help.append("\t pncs <node id> - Print node connectors for a given node\n");
1702 help.append("\t pencs <node id> - Print enabled node connectors for a given node\n");
1703 help.append("\t pdm <node id> - Print switch ports in device map\n");
1704 help.append("\t snt <node id> <tier> - Set node tier number\n");
1705 help.append("\t hostRefresh <on/off/?> - Enable/Disable/Query host refresh\n");
1706 help.append("\t hostRetry <count> - Set host retry count\n");
1707 return help.toString();
1710 public void _pns(CommandInterpreter ci) {
1711 ci.println(" Node Type MAC Name Tier");
1712 if (nodeProps == null) {
1715 Set<Node> nodeSet = nodeProps.keySet();
1716 if (nodeSet == null) {
1719 List<String> nodeArray = new ArrayList<String>();
1720 for (Node node : nodeSet) {
1721 nodeArray.add(node.toString());
1723 Collections.sort(nodeArray);
1724 for (String str: nodeArray) {
1725 Node node = Node.fromString(str);
1726 Description desc = ((Description) getNodeProp(node,
1727 Description.propertyName));
1728 Tier tier = ((Tier) getNodeProp(node, Tier.TierPropName));
1729 String nodeName = (desc == null) ? "" : desc.getValue();
1730 MacAddress mac = (MacAddress) getNodeProp(node,
1732 String macAddr = (mac == null) ? "" : HexEncode
1733 .bytesToHexStringFormat(mac.getMacAddress());
1734 int tierNum = (tier == null) ? 0 : tier.getValue();
1735 ci.println(node + " " + node.getType() + " " + macAddr
1736 + " " + nodeName + " " + tierNum);
1738 ci.println("Total number of Nodes: " + nodeSet.size());
1741 public void _pencs(CommandInterpreter ci) {
1742 String st = ci.nextArgument();
1744 ci.println("Please enter node id");
1748 Node node = Node.fromString(st);
1750 ci.println("Please enter node id");
1754 Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node);
1755 if (nodeConnectorSet == null) {
1758 for (NodeConnector nodeConnector : nodeConnectorSet) {
1759 if (nodeConnector == null) {
1762 ci.println(nodeConnector);
1764 ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1767 public void _pncs(CommandInterpreter ci) {
1768 String st = ci.nextArgument();
1770 ci.println("Please enter node id");
1774 Node node = Node.fromString(st);
1776 ci.println("Please enter node id");
1780 ci.println(" NodeConnector BandWidth(Gbps) Admin State");
1781 Set<NodeConnector> nodeConnectorSet = getNodeConnectors(node);
1782 if (nodeConnectorSet == null) {
1785 for (NodeConnector nodeConnector : nodeConnectorSet) {
1786 if (nodeConnector == null) {
1789 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1790 Bandwidth bw = (Bandwidth) propMap.get(Bandwidth.BandwidthPropName);
1791 Config config = (Config) propMap.get(Config.ConfigPropName);
1792 State state = (State) propMap.get(State.StatePropName);
1793 String out = nodeConnector + " ";
1794 out += (bw != null) ? bw.getValue() / Math.pow(10, 9) : " ";
1796 out += (config != null) ? config.getValue() : " ";
1798 out += (state != null) ? state.getValue() : " ";
1801 ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1804 public void _pdm(CommandInterpreter ci) {
1805 String st = ci.nextArgument();
1807 ci.println("Please enter node id");
1811 Node node = Node.fromString(st);
1813 ci.println("Please enter node id");
1817 Switch sw = getSwitchByNode(node);
1819 ci.println(" NodeConnector Name");
1823 Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors();
1824 String nodeConnectorName;
1825 if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
1826 for (NodeConnector nodeConnector : nodeConnectorSet) {
1827 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1828 nodeConnectorName = (propMap == null) ? null : ((Name) propMap
1829 .get(Name.NamePropName)).getValue();
1830 if (nodeConnectorName != null) {
1831 Node nd = nodeConnector.getNode();
1832 if (!nd.equals(node)) {
1833 log.debug("node not match {} {}", nd, node);
1835 Map<String, NodeConnector> map = nodeConnectorNames
1838 NodeConnector nc = map.get(nodeConnectorName);
1840 log.debug("no nodeConnector named {}",
1842 } else if (!nc.equals(nodeConnector)) {
1843 log.debug("nodeConnector not match {} {}", nc,
1849 ci.println(nodeConnector
1851 + ((nodeConnectorName == null) ? "" : nodeConnectorName)
1852 + "(" + nodeConnector.getID() + ")");
1854 ci.println("Total number of NodeConnectors: "
1855 + nodeConnectorSet.size());
1859 public void _snt(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 st = ci.nextArgument();
1874 ci.println("Please enter tier number");
1877 Integer tid = Integer.decode(st);
1878 Tier tier = new Tier(tid);
1879 setNodeProp(node, tier);
1882 public void _hostRefresh(CommandInterpreter ci) {
1883 String mode = ci.nextArgument();
1885 ci.println("expecting on/off/?");
1888 if (mode.toLowerCase().equals("on")) {
1890 } else if (mode.toLowerCase().equals("off")) {
1891 hostRefresh = false;
1892 } else if (mode.equals("?")) {
1894 ci.println("host refresh is ON");
1896 ci.println("host refresh is OFF");
1899 ci.println("expecting on/off/?");
1904 public void _hostRetry(CommandInterpreter ci) {
1905 String retry = ci.nextArgument();
1906 if (retry == null) {
1907 ci.println("Please enter a valid number. Current retry count is "
1912 hostRetryCount = Integer.parseInt(retry);
1913 } catch (Exception e) {
1914 ci.println("Please enter a valid number");
1920 public byte[] getNodeMAC(Node node) {
1921 MacAddress mac = (MacAddress) this.getNodeProp(node,
1923 return (mac != null) ? mac.getMacAddress() : null;
1927 public boolean isSpecial(NodeConnector p) {
1928 if (p.getType().equals(NodeConnectorIDType.CONTROLLER)
1929 || p.getType().equals(NodeConnectorIDType.ALL)
1930 || p.getType().equals(NodeConnectorIDType.SWSTACK)
1931 || p.getType().equals(NodeConnectorIDType.HWPATH)) {
1938 * Add span configuration to local cache and notify clients
1940 private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
1941 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1943 for (NodeConnector nodeConnector : nodeConnectors) {
1944 if (!spanNodeConnectors.contains(nodeConnector)) {
1945 ncLists.add(nodeConnector);
1949 if (ncLists.size() > 0) {
1950 spanNodeConnectors.addAll(ncLists);
1951 notifySpanPortChange(node, ncLists, true);
1955 private void addSpanPorts(Node node) {
1956 for (SpanConfig conf : getSpanConfigList(node)) {
1957 addSpanPorts(node, conf.getPortArrayList());
1961 private void addSpanPort(NodeConnector nodeConnector) {
1962 // only add if span is configured on this nodeConnector
1963 for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) {
1964 if (conf.getPortArrayList().contains(nodeConnector)) {
1965 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1966 ncLists.add(nodeConnector);
1967 addSpanPorts(nodeConnector.getNode(), ncLists);
1974 * Remove span configuration to local cache and notify clients
1976 private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
1977 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
1979 for (NodeConnector nodeConnector : nodeConnectors) {
1980 if (spanNodeConnectors.contains(nodeConnector)) {
1981 ncLists.add(nodeConnector);
1985 if (ncLists.size() > 0) {
1986 spanNodeConnectors.removeAll(ncLists);
1987 notifySpanPortChange(node, ncLists, false);
1991 private void removeSpanPorts(Node node) {
1992 for (SpanConfig conf : getSpanConfigList(node)) {
1993 addSpanPorts(node, conf.getPortArrayList());
1997 private void removeSpanPort(NodeConnector nodeConnector) {
1998 if (spanNodeConnectors.contains(nodeConnector)) {
1999 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2000 ncLists.add(nodeConnector);
2001 removeSpanPorts(nodeConnector.getNode(), ncLists);
2005 private void addNodeProps(Node node, Map<String, Property> propMap) {
2006 if (propMap == null) {
2007 propMap = new HashMap<String, Property>();
2009 nodeProps.put(node, propMap);
2012 private void removeNodeProps(Node node) {
2013 if (getUpNodeConnectors(node).size() == 0) {
2014 nodeProps.remove(node);
2019 public Status saveConfiguration() {
2020 return saveSwitchConfig();
2024 * Creates a Name/Tier/Bandwidth Property object based on given property
2025 * name and value. Other property types are not supported yet.
2028 * Name of the Property
2030 * Value of the Property
2031 * @return {@link org.opendaylight.controller.sal.core.Property}
2034 public Property createProperty(String propName, String propValue) {
2035 if (propName == null) {
2036 log.debug("propName is null");
2039 if (propValue == null) {
2040 log.debug("propValue is null");
2045 if (propName.equalsIgnoreCase(Description.propertyName)) {
2046 return new Description(propValue);
2047 } else if (propName.equalsIgnoreCase(Tier.TierPropName)) {
2048 int tier = Integer.parseInt(propValue);
2049 return new Tier(tier);
2050 } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) {
2051 long bw = Long.parseLong(propValue);
2052 return new Bandwidth(bw);
2053 } else if (propName.equalsIgnoreCase(ForwardingMode.name)) {
2054 int mode = Integer.parseInt(propValue);
2055 return new ForwardingMode(mode);
2057 log.debug("Not able to create {} property", propName);
2059 } catch (Exception e) {
2060 log.debug("createProperty caught exception {}", e.getMessage());
2067 public String getNodeDescription(Node node) {
2068 // Check first if user configured a name
2069 SwitchConfig config = getSwitchConfig(node.toString());
2070 if (config != null) {
2071 String configuredDesc = config.getNodeDescription();
2072 if (configuredDesc != null && !configuredDesc.isEmpty()) {
2073 return configuredDesc;
2077 // No name configured by user, get the node advertised name
2078 Description desc = (Description) getNodeProp(node,
2079 Description.propertyName);
2080 return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? ""