2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.switchmanager.internal;
11 import java.io.FileNotFoundException;
12 import java.io.IOException;
13 import java.io.ObjectInputStream;
14 import java.net.InetAddress;
15 import java.net.NetworkInterface;
16 import java.net.SocketException;
17 import java.util.ArrayList;
18 import java.util.Collections;
19 import java.util.Dictionary;
20 import java.util.EnumSet;
21 import java.util.Enumeration;
22 import java.util.HashMap;
23 import java.util.HashSet;
24 import java.util.List;
27 import java.util.concurrent.ConcurrentHashMap;
28 import java.util.concurrent.ConcurrentMap;
29 import java.util.concurrent.CopyOnWriteArrayList;
31 import org.apache.felix.dm.Component;
32 import org.eclipse.osgi.framework.console.CommandInterpreter;
33 import org.eclipse.osgi.framework.console.CommandProvider;
34 import org.opendaylight.controller.clustering.services.CacheConfigException;
35 import org.opendaylight.controller.clustering.services.CacheExistException;
36 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
37 import org.opendaylight.controller.clustering.services.IClusterServices;
38 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
39 import org.opendaylight.controller.sal.core.Bandwidth;
40 import org.opendaylight.controller.sal.core.Config;
41 import org.opendaylight.controller.sal.core.ConstructionException;
42 import org.opendaylight.controller.sal.core.Description;
43 import org.opendaylight.controller.sal.core.ForwardingMode;
44 import org.opendaylight.controller.sal.core.MacAddress;
45 import org.opendaylight.controller.sal.core.Name;
46 import org.opendaylight.controller.sal.core.Node;
47 import org.opendaylight.controller.sal.core.NodeConnector;
48 import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType;
49 import org.opendaylight.controller.sal.core.Property;
50 import org.opendaylight.controller.sal.core.State;
51 import org.opendaylight.controller.sal.core.Tier;
52 import org.opendaylight.controller.sal.core.UpdateType;
53 import org.opendaylight.controller.sal.inventory.IInventoryService;
54 import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates;
55 import org.opendaylight.controller.sal.reader.NodeDescription;
56 import org.opendaylight.controller.sal.utils.GlobalConstants;
57 import org.opendaylight.controller.sal.utils.HexEncode;
58 import org.opendaylight.controller.sal.utils.IObjectReader;
59 import org.opendaylight.controller.sal.utils.ObjectReader;
60 import org.opendaylight.controller.sal.utils.ObjectWriter;
61 import org.opendaylight.controller.sal.utils.Status;
62 import org.opendaylight.controller.sal.utils.StatusCode;
63 import org.opendaylight.controller.statisticsmanager.IStatisticsManager;
64 import org.opendaylight.controller.switchmanager.IInventoryListener;
65 import org.opendaylight.controller.switchmanager.ISpanAware;
66 import org.opendaylight.controller.switchmanager.ISwitchManager;
67 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
68 import org.opendaylight.controller.switchmanager.SpanConfig;
69 import org.opendaylight.controller.switchmanager.Subnet;
70 import org.opendaylight.controller.switchmanager.SubnetConfig;
71 import org.opendaylight.controller.switchmanager.Switch;
72 import org.opendaylight.controller.switchmanager.SwitchConfig;
73 import org.osgi.framework.BundleContext;
74 import org.osgi.framework.FrameworkUtil;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
79 * The class describes SwitchManager which is the central repository of all the
80 * inventory data including nodes, node connectors, properties attached, Layer3
81 * configurations, Span configurations, node configurations, network device
82 * representations viewed by Controller Web applications. One SwitchManager
83 * instance per container of the network. All the node/nodeConnector properties
84 * are maintained in the default container only.
86 public class SwitchManager implements ISwitchManager, IConfigurationContainerAware,
87 IObjectReader, IListenInventoryUpdates, CommandProvider {
88 private static Logger log = LoggerFactory.getLogger(SwitchManager.class);
89 private static String ROOT = GlobalConstants.STARTUPHOME.toString();
90 private String subnetFileName, spanFileName, switchConfigFileName;
91 private final List<NodeConnector> spanNodeConnectors = new CopyOnWriteArrayList<NodeConnector>();
92 // Collection of Subnets keyed by the InetAddress
93 private ConcurrentMap<InetAddress, Subnet> subnets;
94 private ConcurrentMap<String, SubnetConfig> subnetsConfigList;
95 private ConcurrentMap<SpanConfig, SpanConfig> spanConfigList;
96 // manually configured parameters for the node such as name, tier, mode
97 private ConcurrentMap<String, SwitchConfig> nodeConfigList;
98 private ConcurrentMap<Node, Map<String, Property>> nodeProps;
99 private ConcurrentMap<NodeConnector, Map<String, Property>> nodeConnectorProps;
100 private ConcurrentMap<Node, Map<String, NodeConnector>> nodeConnectorNames;
101 private ConcurrentMap<String, Property> controllerProps;
102 private IInventoryService inventoryService;
103 private IStatisticsManager statisticsManager;
104 private final Set<ISwitchManagerAware> switchManagerAware = Collections
105 .synchronizedSet(new HashSet<ISwitchManagerAware>());
106 private final Set<IInventoryListener> inventoryListeners = Collections
107 .synchronizedSet(new HashSet<IInventoryListener>());
108 private final Set<ISpanAware> spanAware = Collections.synchronizedSet(new HashSet<ISpanAware>());
109 private IClusterContainerServices clusterContainerService = null;
110 private String containerName = null;
111 private boolean isDefaultContainer = true;
112 private static final int REPLACE_RETRY = 1;
114 /* Information about the default subnet. If there have been no configured subnets, i.e.,
115 * subnets.size() == 0 or subnetsConfigList.size() == 0, then this subnet will be the
116 * only subnet returned. As soon as a user-configured subnet is created this one will
119 protected static SubnetConfig DEFAULT_SUBNETCONFIG;
120 protected static Subnet DEFAULT_SUBNET;
121 protected static String DEFAULT_SUBNET_NAME = "default (cannot be modifed)";
123 DEFAULT_SUBNETCONFIG = new SubnetConfig(DEFAULT_SUBNET_NAME, "0.0.0.0/0", new ArrayList<String>());
124 DEFAULT_SUBNET = new Subnet(DEFAULT_SUBNETCONFIG);
127 public void notifySubnetChange(Subnet sub, boolean add) {
128 synchronized (switchManagerAware) {
129 for (Object subAware : switchManagerAware) {
131 ((ISwitchManagerAware) subAware).subnetNotify(sub, add);
132 } catch (Exception e) {
133 log.error("Failed to notify Subnet change {}",
140 public void notifySpanPortChange(Node node, List<NodeConnector> ports, boolean add) {
141 synchronized (spanAware) {
142 for (Object sa : spanAware) {
144 ((ISpanAware) sa).spanUpdate(node, ports, add);
145 } catch (Exception e) {
146 log.error("Failed to notify Span Interface change {}",
153 private void notifyModeChange(Node node, boolean proactive) {
154 synchronized (switchManagerAware) {
155 for (ISwitchManagerAware service : switchManagerAware) {
157 service.modeChangeNotify(node, proactive);
158 } catch (Exception e) {
159 log.error("Failed to notify Subnet change {}",
166 public void startUp() {
167 String container = this.getContainerName();
168 // Initialize configuration file names
169 subnetFileName = ROOT + "subnets_" + container + ".conf";
170 spanFileName = ROOT + "spanPorts_" + container + ".conf";
171 switchConfigFileName = ROOT + "switchConfig_" + container + ".conf";
173 // Instantiate cluster synced variables
178 * Read startup and build database if we have not already gotten the
179 * configurations synced from another node
181 if (subnetsConfigList.isEmpty()) {
182 loadSubnetConfiguration();
184 if (spanConfigList.isEmpty()) {
185 loadSpanConfiguration();
187 if (nodeConfigList.isEmpty()) {
188 loadSwitchConfiguration();
191 // Add controller MAC, if first node in the cluster
192 if (!controllerProps.containsKey(MacAddress.name)) {
193 byte controllerMac[] = getHardwareMAC();
194 if (controllerMac != null) {
195 Property existing = controllerProps.putIfAbsent(MacAddress.name, new MacAddress(controllerMac));
196 if (existing == null && log.isTraceEnabled()) {
197 log.trace("Container {}: Setting controller MAC address in the cluster: {}", container,
198 HexEncode.bytesToHexStringFormat(controllerMac));
204 public void shutDown() {
207 private void allocateCaches() {
208 if (this.clusterContainerService == null) {
209 this.nonClusterObjectCreate();
210 log.warn("un-initialized clusterContainerService, can't create cache");
215 clusterContainerService.createCache(
216 "switchmanager.subnetsConfigList",
217 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
218 clusterContainerService.createCache("switchmanager.spanConfigList",
219 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
220 clusterContainerService.createCache("switchmanager.nodeConfigList",
221 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
222 clusterContainerService.createCache("switchmanager.subnets",
223 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
224 clusterContainerService.createCache("switchmanager.nodeProps",
225 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
226 clusterContainerService.createCache(
227 "switchmanager.nodeConnectorProps",
228 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
229 clusterContainerService.createCache(
230 "switchmanager.nodeConnectorNames",
231 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
232 clusterContainerService.createCache(
233 "switchmanager.controllerProps",
234 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
235 } catch (CacheConfigException cce) {
236 log.error("\nCache configuration invalid - check cache mode");
237 } catch (CacheExistException ce) {
238 log.error("\nCache already exits - destroy and recreate if needed");
242 @SuppressWarnings({ "unchecked" })
243 private void retrieveCaches() {
244 if (this.clusterContainerService == null) {
245 log.info("un-initialized clusterContainerService, can't create cache");
249 subnetsConfigList = (ConcurrentMap<String, SubnetConfig>) clusterContainerService
250 .getCache("switchmanager.subnetsConfigList");
251 if (subnetsConfigList == null) {
252 log.error("\nFailed to get cache for subnetsConfigList");
255 spanConfigList = (ConcurrentMap<SpanConfig, SpanConfig>) clusterContainerService
256 .getCache("switchmanager.spanConfigList");
257 if (spanConfigList == null) {
258 log.error("\nFailed to get cache for spanConfigList");
261 nodeConfigList = (ConcurrentMap<String, SwitchConfig>) clusterContainerService
262 .getCache("switchmanager.nodeConfigList");
263 if (nodeConfigList == null) {
264 log.error("\nFailed to get cache for nodeConfigList");
267 subnets = (ConcurrentMap<InetAddress, Subnet>) clusterContainerService
268 .getCache("switchmanager.subnets");
269 if (subnets == null) {
270 log.error("\nFailed to get cache for subnets");
273 nodeProps = (ConcurrentMap<Node, Map<String, Property>>) clusterContainerService
274 .getCache("switchmanager.nodeProps");
275 if (nodeProps == null) {
276 log.error("\nFailed to get cache for nodeProps");
279 nodeConnectorProps = (ConcurrentMap<NodeConnector, Map<String, Property>>) clusterContainerService
280 .getCache("switchmanager.nodeConnectorProps");
281 if (nodeConnectorProps == null) {
282 log.error("\nFailed to get cache for nodeConnectorProps");
285 nodeConnectorNames = (ConcurrentMap<Node, Map<String, NodeConnector>>) clusterContainerService
286 .getCache("switchmanager.nodeConnectorNames");
287 if (nodeConnectorNames == null) {
288 log.error("\nFailed to get cache for nodeConnectorNames");
291 controllerProps = (ConcurrentMap<String, Property>) clusterContainerService
292 .getCache("switchmanager.controllerProps");
293 if (controllerProps == null) {
294 log.error("\nFailed to get cache for controllerProps");
298 private void nonClusterObjectCreate() {
299 subnetsConfigList = new ConcurrentHashMap<String, SubnetConfig>();
300 spanConfigList = new ConcurrentHashMap<SpanConfig, SpanConfig>();
301 nodeConfigList = new ConcurrentHashMap<String, SwitchConfig>();
302 subnets = new ConcurrentHashMap<InetAddress, Subnet>();
303 nodeProps = new ConcurrentHashMap<Node, Map<String, Property>>();
304 nodeConnectorProps = new ConcurrentHashMap<NodeConnector, Map<String, Property>>();
305 nodeConnectorNames = new ConcurrentHashMap<Node, Map<String, NodeConnector>>();
306 controllerProps = new ConcurrentHashMap<String, Property>();
310 public List<SubnetConfig> getSubnetsConfigList() {
311 // if there are no subnets, return the default subnet
312 if(subnetsConfigList.size() == 0){
313 return Collections.singletonList(DEFAULT_SUBNETCONFIG);
315 return new ArrayList<SubnetConfig>(subnetsConfigList.values());
320 public SubnetConfig getSubnetConfig(String subnet) {
321 // if there are no subnets, return the default subnet
322 if(subnetsConfigList.size() == 0 && subnet == DEFAULT_SUBNET_NAME){
323 return DEFAULT_SUBNETCONFIG;
325 return subnetsConfigList.get(subnet);
329 private List<SpanConfig> getSpanConfigList(Node node) {
330 List<SpanConfig> confList = new ArrayList<SpanConfig>();
331 String nodeId = node.toString();
332 for (SpanConfig conf : spanConfigList.values()) {
333 if (conf.matchNode(nodeId)) {
340 public List<SwitchConfig> getNodeConfigList() {
341 return new ArrayList<SwitchConfig>(nodeConfigList.values());
345 public SwitchConfig getSwitchConfig(String switchId) {
346 return nodeConfigList.get(switchId);
349 public Switch getSwitchByNode(Node node) {
350 Switch sw = new Switch(node);
352 MacAddress mac = (MacAddress) this.getNodeProp(node,
355 sw.setDataLayerAddress(mac.getMacAddress());
357 Set<NodeConnector> ncSet = getPhysicalNodeConnectors(node);
358 sw.setNodeConnectors(ncSet);
360 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
361 for (NodeConnector nodeConnector : ncSet) {
362 if (spanNodeConnectors.contains(nodeConnector)) {
363 ncList.add(nodeConnector);
366 sw.addSpanPorts(ncList);
372 public List<Switch> getNetworkDevices() {
373 Set<Node> nodeSet = getNodes();
374 List<Switch> swList = new ArrayList<Switch>();
375 if (nodeSet != null) {
376 for (Node node : nodeSet) {
377 swList.add(getSwitchByNode(node));
384 private Status updateConfig(SubnetConfig conf, boolean add) {
386 if(subnetsConfigList.putIfAbsent(conf.getName(), conf) != null) {
387 String msg = "Cluster conflict: Subnet with name " + conf.getName() + "already exists.";
388 return new Status(StatusCode.CONFLICT, msg);
391 subnetsConfigList.remove(conf.getName());
393 return new Status(StatusCode.SUCCESS);
396 private Status updateDatabase(SubnetConfig conf, boolean add) {
398 Subnet subnetCurr = subnets.get(conf.getIPAddress());
400 if (subnetCurr == null) {
401 subnet = new Subnet(conf);
403 subnet = subnetCurr.clone();
405 // In case of API3 call we may receive the ports along with the
407 if (!conf.isGlobal()) {
408 subnet.addNodeConnectors(conf.getNodeConnectors());
410 boolean putNewSubnet = false;
411 if(subnetCurr == null) {
412 if(subnets.putIfAbsent(conf.getIPAddress(), subnet) == null) {
416 putNewSubnet = subnets.replace(conf.getIPAddress(), subnetCurr, subnet);
419 String msg = "Cluster conflict: Conflict while adding the subnet " + conf.getIPAddress();
420 return new Status(StatusCode.CONFLICT, msg);
423 // Subnet removal case
425 subnets.remove(conf.getIPAddress());
427 return new Status(StatusCode.SUCCESS);
430 private Status semanticCheck(SubnetConfig conf) {
431 Subnet newSubnet = new Subnet(conf);
432 Set<InetAddress> IPs = subnets.keySet();
434 return new Status(StatusCode.SUCCESS);
436 for (InetAddress i : IPs) {
437 Subnet existingSubnet = subnets.get(i);
438 if ((existingSubnet != null) && !existingSubnet.isMutualExclusive(newSubnet)) {
439 return new Status(StatusCode.CONFLICT, "This subnet conflicts with an existing one.");
442 return new Status(StatusCode.SUCCESS);
445 private Status addRemoveSubnet(SubnetConfig conf, boolean isAdding) {
446 // Valid configuration check
447 Status status = conf.validate();
448 if (!status.isSuccess()) {
449 log.warn(status.getDescription());
455 if (subnetsConfigList.containsKey(conf.getName())) {
456 return new Status(StatusCode.CONFLICT,
457 "Subnet with the specified name already exists.");
460 status = semanticCheck(conf);
461 if (!status.isSuccess()) {
465 if (conf.getName().equals(DEFAULT_SUBNET_NAME)) {
466 return new Status(StatusCode.NOTALLOWED, "The specified subnet gateway cannot be removed");
471 status = updateDatabase(conf, isAdding);
473 if (status.isSuccess()) {
474 // Update Configuration
475 status = updateConfig(conf, isAdding);
476 if(!status.isSuccess()) {
477 updateDatabase(conf, (!isAdding));
485 * Adds Subnet configured in GUI or API3
488 public Status addSubnet(SubnetConfig conf) {
489 return this.addRemoveSubnet(conf, true);
493 public Status removeSubnet(SubnetConfig conf) {
494 return this.addRemoveSubnet(conf, false);
498 public Status removeSubnet(String name) {
499 if (name.equals(DEFAULT_SUBNET_NAME)) {
500 return new Status(StatusCode.NOTALLOWED, "The specified subnet gateway cannot be removed");
502 SubnetConfig conf = subnetsConfigList.get(name);
504 return new Status(StatusCode.SUCCESS, "Subnet not present");
506 return this.addRemoveSubnet(conf, false);
510 public Status modifySubnet(SubnetConfig conf) {
513 return new Status(StatusCode.BADREQUEST, "Invalid Subnet configuration: null");
516 // Valid configuration check
517 Status status = conf.validate();
518 if (!status.isSuccess()) {
519 log.warn(status.getDescription());
523 // If a subnet configuration with this name does not exist, consider this is a creation
524 SubnetConfig target = subnetsConfigList.get(conf.getName());
525 if (target == null) {
526 return this.addSubnet(conf);
530 if (target.equals(conf)) {
531 return new Status(StatusCode.SUCCESS);
534 // Check not allowed modifications
535 if (!target.getSubnet().equals(conf.getSubnet())) {
536 return new Status(StatusCode.BADREQUEST, "IP address change is not allowed");
539 // Derive the set of node connectors that are being removed
540 Set<NodeConnector> toRemove = target.getNodeConnectors();
541 toRemove.removeAll(conf.getNodeConnectors());
542 List<String> nodeConnectorStrings = null;
543 if (!toRemove.isEmpty()) {
544 nodeConnectorStrings = new ArrayList<String>();
545 for (NodeConnector nc : toRemove) {
546 nodeConnectorStrings.add(nc.toString());
548 status = this.removePortsFromSubnet(conf.getName(), nodeConnectorStrings);
549 if (!status.isSuccess()) {
554 // Derive the set of node connectors that are being added
555 Set<NodeConnector> toAdd = conf.getNodeConnectors();
556 toAdd.removeAll(target.getNodeConnectors());
557 if (!toAdd.isEmpty()) {
558 List<String> nodeConnectorStringRemoved = nodeConnectorStrings;
559 nodeConnectorStrings = new ArrayList<String>();
560 for (NodeConnector nc : toAdd) {
561 nodeConnectorStrings.add(nc.toString());
563 status = this.addPortsToSubnet(conf.getName(), nodeConnectorStrings);
564 if (!status.isSuccess()) {
565 // If any port was removed, add it back as a best recovery effort
566 if (!toRemove.isEmpty()) {
567 this.addPortsToSubnet(conf.getName(), nodeConnectorStringRemoved);
573 // Update Configuration
574 subnetsConfigList.put(conf.getName(), conf);
576 return new Status(StatusCode.SUCCESS);
580 public Status addPortsToSubnet(String name, List<String> switchPorts) {
582 return new Status(StatusCode.BADREQUEST, "Null subnet name");
584 SubnetConfig confCurr = subnetsConfigList.get(name);
585 if (confCurr == null) {
586 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
589 if (switchPorts == null || switchPorts.isEmpty()) {
590 return new Status(StatusCode.BADREQUEST, "Null or empty port set");
593 Subnet subCurr = subnets.get(confCurr.getIPAddress());
594 if (subCurr == null) {
595 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress());
596 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
600 Subnet sub = subCurr.clone();
601 Set<NodeConnector> sp = NodeConnector.fromString(switchPorts);
602 sub.addNodeConnectors(sp);
603 boolean subnetsReplaced = subnets.replace(confCurr.getIPAddress(), subCurr, sub);
604 if (!subnetsReplaced) {
605 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
606 return new Status(StatusCode.CONFLICT, msg);
609 // Update Configuration
610 SubnetConfig conf = confCurr.clone();
611 conf.addNodeConnectors(switchPorts);
612 boolean configReplaced = subnetsConfigList.replace(name, confCurr, conf);
613 if (!configReplaced) {
614 // TODO: recovery using Transactionality
615 String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name;
616 return new Status(StatusCode.CONFLICT, msg);
619 return new Status(StatusCode.SUCCESS);
623 public Status removePortsFromSubnet(String name, List<String> switchPorts) {
625 return new Status(StatusCode.BADREQUEST, "Null subnet name");
627 SubnetConfig confCurr = subnetsConfigList.get(name);
628 if (confCurr == null) {
629 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
632 if (switchPorts == null || switchPorts.isEmpty()) {
633 return new Status(StatusCode.BADREQUEST, "Null or empty port set");
636 Subnet subCurr = subnets.get(confCurr.getIPAddress());
637 if (subCurr == null) {
638 log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress());
639 return new Status(StatusCode.NOTFOUND, "Subnet does not exist");
643 Status status = SubnetConfig.validatePorts(switchPorts);
644 if (!status.isSuccess()) {
648 Subnet sub = subCurr.clone();
649 Set<NodeConnector> sp = NodeConnector.fromString(switchPorts);
650 sub.deleteNodeConnectors(sp);
651 boolean subnetsReplace = subnets.replace(confCurr.getIPAddress(), subCurr, sub);
652 if (!subnetsReplace) {
653 String msg = "Cluster conflict: Conflict while removing ports from the subnet " + name;
654 return new Status(StatusCode.CONFLICT, msg);
657 // Update Configuration
658 SubnetConfig conf = confCurr.clone();
659 conf.removeNodeConnectors(switchPorts);
660 boolean result = subnetsConfigList.replace(name, confCurr, conf);
662 // TODO: recovery using Transactionality
663 String msg = "Cluster conflict: Conflict while removing ports from " + conf;
664 return new Status(StatusCode.CONFLICT, msg);
667 return new Status(StatusCode.SUCCESS);
670 public String getContainerName() {
671 if (containerName == null) {
672 return GlobalConstants.DEFAULT.toString();
674 return containerName;
678 public Subnet getSubnetByNetworkAddress(InetAddress networkAddress) {
679 // if there are no subnets, return the default subnet
680 if (subnets.size() == 0) {
681 return DEFAULT_SUBNET;
685 Set<InetAddress> indices = subnets.keySet();
686 for (InetAddress i : indices) {
687 sub = subnets.get(i);
688 if (sub.isSubnetOf(networkAddress)) {
696 public Object readObject(ObjectInputStream ois)
697 throws FileNotFoundException, IOException, ClassNotFoundException {
698 // Perform the class deserialization locally, from inside the package
699 // where the class is defined
700 return ois.readObject();
703 @SuppressWarnings("unchecked")
704 private void loadSubnetConfiguration() {
705 ObjectReader objReader = new ObjectReader();
706 ConcurrentMap<String, SubnetConfig> confList = (ConcurrentMap<String, SubnetConfig>) objReader
707 .read(this, subnetFileName);
709 if (confList == null) {
713 for (SubnetConfig conf : confList.values()) {
718 @SuppressWarnings("unchecked")
719 private void loadSpanConfiguration() {
720 ObjectReader objReader = new ObjectReader();
721 ConcurrentMap<Integer, SpanConfig> confList = (ConcurrentMap<Integer, SpanConfig>) objReader
722 .read(this, spanFileName);
724 if (confList == null) {
728 for (SpanConfig conf : confList.values()) {
733 @SuppressWarnings("unchecked")
734 private void loadSwitchConfiguration() {
735 ObjectReader objReader = new ObjectReader();
736 ConcurrentMap<String, SwitchConfig> confList = (ConcurrentMap<String, SwitchConfig>) objReader
737 .read(this, switchConfigFileName);
739 if (confList == null) {
743 for (SwitchConfig conf : confList.values()) {
744 updateNodeConfig(conf);
748 @SuppressWarnings("deprecation")
750 public void updateSwitchConfig(SwitchConfig cfgObject) {
751 // update default container only
752 if (!isDefaultContainer) {
756 SwitchConfig sc = nodeConfigList.get(cfgObject.getNodeId());
758 if (nodeConfigList.putIfAbsent(cfgObject.getNodeId(), cfgObject) != null) {
762 if (!nodeConfigList.replace(cfgObject.getNodeId(), sc, cfgObject)) {
767 boolean modeChange = false;
769 if ((sc == null) || !cfgObject.getMode().equals(sc.getMode())) {
773 String nodeId = cfgObject.getNodeId();
774 Node node = Node.fromString(nodeId);
775 Map<String, Property> propMapCurr = nodeProps.get(node);
776 if (propMapCurr == null) {
779 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
780 Property desc = new Description(cfgObject.getNodeDescription());
781 propMap.put(desc.getName(), desc);
782 Property tier = new Tier(Integer.parseInt(cfgObject.getTier()));
783 propMap.put(tier.getName(), tier);
785 if (!nodeProps.replace(node, propMapCurr, propMap)) {
786 // TODO rollback using Transactionality
790 log.info("Set Node {}'s Mode to {}", nodeId, cfgObject.getMode());
793 notifyModeChange(node, cfgObject.isProactive());
798 public Status updateNodeConfig(SwitchConfig switchConfig) {
799 Status status = switchConfig.validate();
800 if (!status.isSuccess()) {
804 Map<String, Property> updateProperties = switchConfig.getNodeProperties();
805 ForwardingMode mode = (ForwardingMode) updateProperties.get(ForwardingMode.name);
807 if (isDefaultContainer) {
808 if (!mode.isValid()) {
809 return new Status(StatusCode.BADREQUEST, "Invalid Forwarding Mode Value");
812 return new Status(StatusCode.NOTACCEPTABLE,
813 "Forwarding Mode modification is allowed only in default container");
817 Description description = (Description) switchConfig.getProperty(Description.propertyName);
818 String nodeId = switchConfig.getNodeId();
819 Node node = Node.fromString(nodeId);
820 NodeDescription nodeDesc = (this.statisticsManager == null) ? null : this.statisticsManager
821 .getNodeDescription(node);
822 String advertisedDesc = (nodeDesc == null) ? "" : nodeDesc.getDescription();
823 if (description != null && description.getValue() != null) {
824 if (description.getValue().isEmpty() || description.getValue().equals(advertisedDesc)) {
825 updateProperties.remove(Description.propertyName);
826 switchConfig = new SwitchConfig(nodeId, updateProperties);
828 // check if description is configured or was published by any other node
829 for (Map.Entry<Node, Map<String, Property>> entry : nodeProps.entrySet()) {
830 Node n = entry.getKey();
831 Description desc = (Description) getNodeProp(n, Description.propertyName);
832 NodeDescription nDesc = (this.statisticsManager == null) ? null : this.statisticsManager
833 .getNodeDescription(n);
834 String advDesc = (nDesc == null) ? "" : nDesc.getDescription();
835 if ((description.equals(desc) || description.getValue().equals(advDesc)) && !node.equals(n)) {
836 return new Status(StatusCode.CONFLICT, "Node name already in use");
842 boolean modeChange = false;
843 SwitchConfig sc = nodeConfigList.get(nodeId);
844 Map<String, Property> prevNodeProperties = new HashMap<String, Property>();
846 if ((mode != null) && mode.isProactive()) {
849 if (!updateProperties.isEmpty()) {
850 if (nodeConfigList.putIfAbsent(nodeId, switchConfig) != null) {
851 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
855 prevNodeProperties = new HashMap<String, Property>(sc.getNodeProperties());
856 ForwardingMode prevMode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
858 if ((prevMode != null) && (prevMode.isProactive())) {
862 if (((prevMode != null) && (prevMode.getValue() != mode.getValue()))
863 || (prevMode == null && mode.isProactive())) {
867 if (updateProperties.isEmpty()) {
868 nodeConfigList.remove(nodeId);
870 if (!nodeConfigList.replace(nodeId, sc, switchConfig)) {
871 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
875 Map<String, Property> propMapCurr = nodeProps.get(node);
876 if (propMapCurr == null) {
877 return new Status(StatusCode.SUCCESS);
879 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
880 for (Map.Entry<String, Property> entry : prevNodeProperties.entrySet()) {
881 String prop = entry.getKey();
882 if (!updateProperties.containsKey(prop)) {
883 if (prop.equals(Description.propertyName)) {
884 if (!advertisedDesc.isEmpty()) {
885 Property desc = new Description(advertisedDesc);
886 propMap.put(Description.propertyName, desc);
889 } else if (prop.equals(ForwardingMode.name)) {
890 Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING);
891 propMap.put(ForwardingMode.name, defaultMode);
894 propMap.remove(prop);
897 propMap.putAll(updateProperties);
898 if (!nodeProps.replace(node, propMapCurr, propMap)) {
899 // TODO rollback using Transactionality
900 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration");
903 notifyModeChange(node, (mode == null) ? false : mode.isProactive());
905 return new Status(StatusCode.SUCCESS);
909 public Status removeNodeConfig(String nodeId) {
910 if ((nodeId == null) || (nodeId.isEmpty())) {
911 return new Status(StatusCode.BADREQUEST, "nodeId cannot be empty.");
913 Map<String, Property> nodeProperties = getSwitchConfig(nodeId).getNodeProperties();
914 Node node = Node.fromString(nodeId);
915 Map<String, Property> propMapCurr = nodeProps.get(node);
916 if ((propMapCurr != null) && (nodeProperties != null) && (!nodeProperties.isEmpty())) {
917 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
918 for (Map.Entry<String, Property> entry : nodeProperties.entrySet()) {
919 String prop = entry.getKey();
920 if (prop.equals(Description.propertyName)) {
921 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
922 if (nodeProp.get(node) != null) {
923 propMap.put(Description.propertyName, nodeProp.get(node).get(Description.propertyName));
927 propMap.remove(prop);
929 if (!nodeProps.replace(node, propMapCurr, propMap)) {
930 return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration.");
933 if (nodeConfigList != null) {
934 nodeConfigList.remove(nodeId);
936 return new Status(StatusCode.SUCCESS);
940 public Status saveSwitchConfig() {
941 return saveSwitchConfigInternal();
944 public Status saveSwitchConfigInternal() {
945 Status retS = null, retP = null;
946 ObjectWriter objWriter = new ObjectWriter();
948 retS = objWriter.write(new ConcurrentHashMap<String, SubnetConfig>(
949 subnetsConfigList), subnetFileName);
950 retP = objWriter.write(new ConcurrentHashMap<SpanConfig, SpanConfig>(
951 spanConfigList), spanFileName);
952 retS = objWriter.write(new ConcurrentHashMap<String, SwitchConfig>(
953 nodeConfigList), switchConfigFileName);
954 if (retS.equals(retP)) {
955 if (retS.isSuccess()) {
958 return new Status(StatusCode.INTERNALERROR, "Save failed");
961 return new Status(StatusCode.INTERNALERROR, "Partial save failure");
966 public List<SpanConfig> getSpanConfigList() {
967 return new ArrayList<SpanConfig>(spanConfigList.values());
971 public Status addSpanConfig(SpanConfig conf) {
972 // Valid config check
973 if (!conf.isValidConfig()) {
974 String msg = "Invalid Span configuration";
976 return new Status(StatusCode.BADREQUEST, msg);
980 if (spanConfigList.containsKey(conf)) {
981 return new Status(StatusCode.CONFLICT, "Same span config exists");
984 // Update configuration
985 if (spanConfigList.putIfAbsent(conf, conf) == null) {
986 // Update database and notify clients
987 addSpanPorts(conf.getNode(), conf.getPortArrayList());
990 return new Status(StatusCode.SUCCESS);
994 public Status removeSpanConfig(SpanConfig conf) {
995 removeSpanPorts(conf.getNode(), conf.getPortArrayList());
997 // Update configuration
998 spanConfigList.remove(conf);
1000 return new Status(StatusCode.SUCCESS);
1004 public List<NodeConnector> getSpanPorts(Node node) {
1005 List<NodeConnector> ncList = new ArrayList<NodeConnector>();
1007 for (NodeConnector nodeConnector : spanNodeConnectors) {
1008 if (nodeConnector.getNode().equals(node)) {
1009 ncList.add(nodeConnector);
1015 private void addNode(Node node, Set<Property> props) {
1016 log.trace("{} added, props: {}", node, props);
1017 if (nodeProps == null) {
1021 Map<String, Property> propMapCurr = nodeProps.get(node);
1022 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1023 : new HashMap<String, Property>(propMapCurr);
1025 // copy node properties from plugin
1026 if (props != null) {
1027 for (Property prop : props) {
1028 propMap.put(prop.getName(), prop);
1032 boolean proactiveForwarding = false;
1033 // copy node properties from config
1034 if (nodeConfigList != null) {
1035 String nodeId = node.toString();
1036 SwitchConfig conf = nodeConfigList.get(nodeId);
1037 if (conf != null && (conf.getNodeProperties() != null)) {
1038 Map<String, Property> nodeProperties = conf.getNodeProperties();
1039 propMap.putAll(nodeProperties);
1040 if (nodeProperties.get(ForwardingMode.name) != null) {
1041 ForwardingMode mode = (ForwardingMode) nodeProperties.get(ForwardingMode.name);
1042 proactiveForwarding = mode.isProactive();
1047 if (!propMap.containsKey(ForwardingMode.name)) {
1048 Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING);
1049 propMap.put(ForwardingMode.name, defaultMode);
1051 boolean result = false;
1052 if (propMapCurr == null) {
1053 if (nodeProps.putIfAbsent(node, propMap) == null) {
1057 result = nodeProps.replace(node, propMapCurr, propMap);
1060 log.debug("Cluster conflict: Conflict while adding the node properties. Node: {} Properties: {}",
1061 node.getID(), props);
1062 addNodeProps(node, propMap);
1065 // check if span ports are configed
1068 // notify node listeners
1069 notifyNode(node, UpdateType.ADDED, propMap);
1071 // notify proactive mode forwarding
1072 if (proactiveForwarding) {
1073 notifyModeChange(node, true);
1077 private void removeNode(Node node) {
1078 log.trace("{} removed", node);
1079 if (nodeProps == null) {
1082 nodeProps.remove(node);
1083 nodeConnectorNames.remove(node);
1084 Set<NodeConnector> removeNodeConnectorSet = new HashSet<NodeConnector>();
1085 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1086 NodeConnector nodeConnector = entry.getKey();
1087 if (nodeConnector.getNode().equals(node)) {
1088 removeNodeConnectorSet.add(nodeConnector);
1091 for (NodeConnector nc : removeNodeConnectorSet) {
1092 nodeConnectorProps.remove(nc);
1095 // check if span ports need to be cleaned up
1096 removeSpanPorts(node);
1098 /* notify node listeners */
1099 notifyNode(node, UpdateType.REMOVED, null);
1102 private void updateNode(Node node, Set<Property> props) {
1103 log.trace("{} updated, props: {}", node, props);
1104 if (nodeProps == null || !nodeProps.containsKey(node) ||
1105 props == null || props.isEmpty()) {
1109 Map<String, Property> propMapCurr = nodeProps.get(node);
1110 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1111 : new HashMap<String, Property>(propMapCurr);
1113 // copy node properties from plugin
1114 String nodeId = node.toString();
1115 for (Property prop : props) {
1116 if (nodeConfigList != null) {
1117 SwitchConfig conf = nodeConfigList.get(nodeId);
1118 if (conf != null && (conf.getNodeProperties() != null)
1119 && conf.getNodeProperties().containsKey(prop.getName())) {
1123 propMap.put(prop.getName(), prop);
1126 if (propMapCurr == null) {
1127 if (nodeProps.putIfAbsent(node, propMap) != null) {
1128 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1129 node.getID(), props);
1130 addNodeProps(node, propMap);
1133 if (!nodeProps.replace(node, propMapCurr, propMap)) {
1134 log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}",
1135 node.getID(), props);
1136 addNodeProps(node, propMap);
1140 /* notify node listeners */
1141 notifyNode(node, UpdateType.CHANGED, propMap);
1145 public void updateNode(Node node, UpdateType type, Set<Property> props) {
1146 log.debug("updateNode: {} type {} props {} for container {}",
1147 new Object[] { node, type, props, containerName });
1150 addNode(node, props);
1153 updateNode(node, props);
1164 public void updateNodeConnector(NodeConnector nodeConnector,
1165 UpdateType type, Set<Property> props) {
1166 Map<String, Property> propMap = new HashMap<String, Property>();
1167 boolean update = true;
1169 log.debug("updateNodeConnector: {} type {} props {} for container {}",
1170 new Object[] { nodeConnector, type, props, containerName });
1172 if (nodeConnectorProps == null) {
1178 if (props != null) {
1179 for (Property prop : props) {
1180 addNodeConnectorProp(nodeConnector, prop);
1181 propMap.put(prop.getName(), prop);
1184 addNodeConnectorProp(nodeConnector, null);
1187 addSpanPort(nodeConnector);
1190 if (!nodeConnectorProps.containsKey(nodeConnector) || (props == null)) {
1193 for (Property prop : props) {
1194 addNodeConnectorProp(nodeConnector, prop);
1195 propMap.put(prop.getName(), prop);
1200 if (!nodeConnectorProps.containsKey(nodeConnector)) {
1203 removeNodeConnectorAllProps(nodeConnector);
1205 // clean up span config
1206 removeSpanPort(nodeConnector);
1214 notifyNodeConnector(nodeConnector, type, propMap);
1219 public Set<Node> getNodes() {
1220 return (nodeProps != null) ? new HashSet<Node>(nodeProps.keySet()) : new HashSet<Node>();
1224 public Map<String, Property> getControllerProperties() {
1225 return new HashMap<String, Property>(this.controllerProps);
1229 public Property getControllerProperty(String propertyName) {
1230 if (propertyName != null) {
1231 HashMap<String, Property> propertyMap = new HashMap<String, Property>(this.controllerProps);
1232 return propertyMap.get(propertyName);
1238 public Status setControllerProperty(Property property) {
1239 if (property != null) {
1240 this.controllerProps.put(property.getName(), property);
1241 return new Status(StatusCode.SUCCESS);
1243 return new Status(StatusCode.BADREQUEST, "Invalid property provided when setting property");
1247 public Status removeControllerProperty(String propertyName) {
1248 if (propertyName != null) {
1249 if (this.controllerProps.containsKey(propertyName)) {
1250 this.controllerProps.remove(propertyName);
1251 if (!this.controllerProps.containsKey(propertyName)) {
1252 return new Status(StatusCode.SUCCESS);
1255 String msg = "Unable to remove property " + propertyName + " from Controller";
1256 return new Status(StatusCode.BADREQUEST, msg);
1258 String msg = "Invalid property provided when removing property from Controller";
1259 return new Status(StatusCode.BADREQUEST, msg);
1263 * Returns a copy of a list of properties for a given node
1268 * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps
1269 * (org.opendaylight.controller.sal.core.Node)
1272 public Map<String, Property> getNodeProps(Node node) {
1273 Map<String, Property> rv = new HashMap<String, Property>();
1274 if (this.nodeProps != null) {
1275 rv = this.nodeProps.get(node);
1277 /* make a copy of it */
1278 rv = new HashMap<String, Property>(rv);
1285 public Property getNodeProp(Node node, String propName) {
1286 Map<String, Property> propMap = getNodeProps(node);
1287 return (propMap != null) ? propMap.get(propName) : null;
1291 public void setNodeProp(Node node, Property prop) {
1293 for (int i = 0; i <= REPLACE_RETRY; i++) {
1294 /* Get a copy of the property map */
1295 Map<String, Property> propMapCurr = getNodeProps(node);
1296 if (propMapCurr == null) {
1300 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1301 propMap.put(prop.getName(), prop);
1303 if (nodeProps.replace(node, propMapCurr, propMap)) {
1306 if (!propMapCurr.get(prop.getName()).equals(nodeProps.get(node).get(prop.getName()))) {
1307 log.debug("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1311 log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID());
1315 public Status removeNodeProp(Node node, String propName) {
1316 for (int i = 0; i <= REPLACE_RETRY; i++) {
1317 Map<String, Property> propMapCurr = getNodeProps(node);
1318 if (propMapCurr != null) {
1319 if (!propMapCurr.containsKey(propName)) {
1320 return new Status(StatusCode.SUCCESS);
1322 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1323 propMap.remove(propName);
1324 if (nodeProps.replace(node, propMapCurr, propMap)) {
1325 return new Status(StatusCode.SUCCESS);
1327 if (!propMapCurr.get(propName).equals(nodeProps.get(node).get(propName))) {
1328 String msg = "Cluster conflict: Unable to remove property " + propName + " for node "
1330 return new Status(StatusCode.CONFLICT, msg);
1334 return new Status(StatusCode.SUCCESS);
1337 String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID();
1338 return new Status(StatusCode.CONFLICT, msg);
1342 public Status removeNodeAllProps(Node node) {
1343 this.nodeProps.remove(node);
1344 return new Status(StatusCode.SUCCESS);
1348 public Set<NodeConnector> getUpNodeConnectors(Node node) {
1349 if (nodeConnectorProps == null) {
1353 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1354 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1355 NodeConnector nodeConnector = entry.getKey();
1356 if (!nodeConnector.getNode().equals(node)) {
1359 if (isNodeConnectorEnabled(nodeConnector)) {
1360 nodeConnectorSet.add(nodeConnector);
1364 return nodeConnectorSet;
1368 public Set<NodeConnector> getNodeConnectors(Node node) {
1369 if (nodeConnectorProps == null) {
1373 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1374 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1375 NodeConnector nodeConnector = entry.getKey();
1376 if (!nodeConnector.getNode().equals(node)) {
1379 nodeConnectorSet.add(nodeConnector);
1382 return nodeConnectorSet;
1386 public Set<NodeConnector> getPhysicalNodeConnectors(Node node) {
1387 if (nodeConnectorProps == null) {
1391 Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>();
1392 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1393 NodeConnector nodeConnector = entry.getKey();
1394 if (!nodeConnector.getNode().equals(node)
1395 || isSpecial(nodeConnector)) {
1398 nodeConnectorSet.add(nodeConnector);
1401 return nodeConnectorSet;
1405 public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) {
1406 Map<String, Property> rv = new HashMap<String, Property>();
1407 if (this.nodeConnectorProps != null) {
1408 rv = this.nodeConnectorProps.get(nodeConnector);
1410 rv = new HashMap<String, Property>(rv);
1417 public Property getNodeConnectorProp(NodeConnector nodeConnector,
1419 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1420 return (propMap != null) ? propMap.get(propName) : null;
1423 private byte[] getHardwareMAC() {
1424 Enumeration<NetworkInterface> nis;
1425 byte[] macAddress = null;
1428 nis = NetworkInterface.getNetworkInterfaces();
1429 } catch (SocketException e) {
1430 log.error("Failed to acquire controller MAC: ", e);
1434 while (nis.hasMoreElements()) {
1435 NetworkInterface ni = nis.nextElement();
1437 macAddress = ni.getHardwareAddress();
1438 } catch (SocketException e) {
1439 log.error("Failed to acquire controller MAC: ", e);
1441 if (macAddress != null) {
1445 if (macAddress == null) {
1446 log.warn("Failed to acquire controller MAC: No physical interface found");
1447 // This happens when running controller on windows VM, for example
1448 // Try parsing the OS command output
1454 public byte[] getControllerMAC() {
1455 MacAddress macProperty = (MacAddress)controllerProps.get(MacAddress.name);
1456 return (macProperty == null) ? null : macProperty.getMacAddress();
1460 public NodeConnector getNodeConnector(Node node, String nodeConnectorName) {
1461 if (nodeConnectorNames == null) {
1465 Map<String, NodeConnector> map = nodeConnectorNames.get(node);
1470 return map.get(nodeConnectorName);
1474 * Adds a node connector and its property if any
1476 * @param nodeConnector
1477 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1479 * name of {@link org.opendaylight.controller.sal.core.Property}
1480 * @return success or failed reason
1483 public Status addNodeConnectorProp(NodeConnector nodeConnector,
1485 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1486 Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>()
1487 : new HashMap<String, Property>(propMapCurr);
1489 String msg = "Cluster conflict: Unable to add NodeConnector Property.";
1490 // Just add the nodeConnector if prop is not available (in a non-default
1493 if (propMapCurr == null) {
1494 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1495 return new Status(StatusCode.CONFLICT, msg);
1498 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1499 return new Status(StatusCode.CONFLICT, msg);
1502 return new Status(StatusCode.SUCCESS);
1505 propMap.put(prop.getName(), prop);
1506 if (propMapCurr == null) {
1507 if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) {
1508 return new Status(StatusCode.CONFLICT, msg);
1511 if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) {
1512 return new Status(StatusCode.CONFLICT, msg);
1516 if (prop.getName().equals(Name.NamePropName)) {
1517 if (nodeConnectorNames != null) {
1518 Node node = nodeConnector.getNode();
1519 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1520 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1521 if (mapCurr != null) {
1522 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1523 String s = entry.getKey();
1525 map.put(s, new NodeConnector(entry.getValue()));
1526 } catch (ConstructionException e) {
1527 log.error("An error occured",e);
1532 map.put(((Name) prop).getValue(), nodeConnector);
1533 if (mapCurr == null) {
1534 if (nodeConnectorNames.putIfAbsent(node, map) != null) {
1535 // TODO: recovery using Transactionality
1536 return new Status(StatusCode.CONFLICT, msg);
1539 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1540 // TODO: recovery using Transactionality
1541 return new Status(StatusCode.CONFLICT, msg);
1547 return new Status(StatusCode.SUCCESS);
1551 * Removes one property of a node connector
1553 * @param nodeConnector
1554 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1556 * name of {@link org.opendaylight.controller.sal.core.Property}
1557 * @return success or failed reason
1560 public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) {
1561 Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector);
1563 if (propMapCurr == null) {
1564 /* Nothing to remove */
1565 return new Status(StatusCode.SUCCESS);
1568 Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr);
1569 propMap.remove(propName);
1570 boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap);
1571 String msg = "Cluster conflict: Unable to remove NodeConnector property.";
1573 return new Status(StatusCode.CONFLICT, msg);
1576 if (propName.equals(Name.NamePropName)) {
1577 if (nodeConnectorNames != null) {
1578 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1580 Node node = nodeConnector.getNode();
1581 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1582 if (mapCurr != null) {
1583 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1584 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1585 String s = entry.getKey();
1587 map.put(s, new NodeConnector(entry.getValue()));
1588 } catch (ConstructionException e) {
1589 log.error("An error occured",e);
1592 map.remove(name.getValue());
1593 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1594 // TODO: recovery using Transactionality
1595 return new Status(StatusCode.CONFLICT, msg);
1602 return new Status(StatusCode.SUCCESS);
1606 * Removes all the properties of a node connector
1608 * @param nodeConnector
1609 * {@link org.opendaylight.controller.sal.core.NodeConnector}
1610 * @return success or failed reason
1613 public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) {
1614 if (nodeConnectorNames != null) {
1615 Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName));
1617 Node node = nodeConnector.getNode();
1618 Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node);
1619 if (mapCurr != null) {
1620 Map<String, NodeConnector> map = new HashMap<String, NodeConnector>();
1621 for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) {
1622 String s = entry.getKey();
1624 map.put(s, new NodeConnector(entry.getValue()));
1625 } catch (ConstructionException e) {
1626 log.error("An error occured",e);
1629 map.remove(name.getValue());
1630 if (map.isEmpty()) {
1631 nodeConnectorNames.remove(node);
1633 if (!nodeConnectorNames.replace(node, mapCurr, map)) {
1634 log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.",
1635 nodeConnector.getID());
1642 nodeConnectorProps.remove(nodeConnector);
1644 return new Status(StatusCode.SUCCESS);
1648 * Function called by the dependency manager when all the required
1649 * dependencies are satisfied
1652 void init(Component c) {
1653 Dictionary<?, ?> props = c.getServiceProperties();
1654 if (props != null) {
1655 this.containerName = (String) props.get("containerName");
1656 log.trace("Running containerName: {}", this.containerName);
1658 // In the Global instance case the containerName is empty
1659 this.containerName = "";
1661 isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT
1668 * Function called by the dependency manager when at least one dependency
1669 * become unsatisfied or when the component is shutting down because for
1670 * example bundle is being stopped.
1678 * Function called by dependency manager after "init ()" is called and after
1679 * the services provided by the class are registered in the service registry
1684 registerWithOSGIConsole();
1688 * Function called after registered the service in OSGi service registry.
1691 // solicit for existing inventories
1696 * Function called by the dependency manager before the services exported by
1697 * the component are unregistered, this will be followed by a "destroy ()"
1704 public void setInventoryService(IInventoryService service) {
1705 log.trace("Got inventory service set request {}", service);
1706 this.inventoryService = service;
1708 // solicit for existing inventories
1712 public void unsetInventoryService(IInventoryService service) {
1713 log.trace("Got a service UNset request");
1714 this.inventoryService = null;
1716 // clear existing inventories
1720 public void setStatisticsManager(IStatisticsManager statisticsManager) {
1721 log.trace("Got statistics manager set request {}", statisticsManager);
1722 this.statisticsManager = statisticsManager;
1725 public void unsetStatisticsManager(IStatisticsManager statisticsManager) {
1726 log.trace("Got statistics manager UNset request");
1727 this.statisticsManager = null;
1730 public void setSwitchManagerAware(ISwitchManagerAware service) {
1731 log.trace("Got inventory service set request {}", service);
1732 if (this.switchManagerAware != null) {
1733 this.switchManagerAware.add(service);
1736 // bulk update for newly joined
1737 switchManagerAwareNotify(service);
1740 public void unsetSwitchManagerAware(ISwitchManagerAware service) {
1741 log.trace("Got a service UNset request");
1742 if (this.switchManagerAware != null) {
1743 this.switchManagerAware.remove(service);
1747 public void setInventoryListener(IInventoryListener service) {
1748 log.trace("Got inventory listener set request {}", service);
1749 if (this.inventoryListeners != null) {
1750 this.inventoryListeners.add(service);
1753 // bulk update for newly joined
1754 bulkUpdateService(service);
1757 public void unsetInventoryListener(IInventoryListener service) {
1758 log.trace("Got a service UNset request");
1759 if (this.inventoryListeners != null) {
1760 this.inventoryListeners.remove(service);
1764 public void setSpanAware(ISpanAware service) {
1765 log.trace("Got SpanAware set request {}", service);
1766 if (this.spanAware != null) {
1767 this.spanAware.add(service);
1770 // bulk update for newly joined
1771 spanAwareNotify(service);
1774 public void unsetSpanAware(ISpanAware service) {
1775 log.trace("Got a service UNset request");
1776 if (this.spanAware != null) {
1777 this.spanAware.remove(service);
1781 void setClusterContainerService(IClusterContainerServices s) {
1782 log.trace("Cluster Service set");
1783 this.clusterContainerService = s;
1786 void unsetClusterContainerService(IClusterContainerServices s) {
1787 if (this.clusterContainerService == s) {
1788 log.trace("Cluster Service removed!");
1789 this.clusterContainerService = null;
1793 private void getInventories() {
1794 if (inventoryService == null) {
1795 log.trace("inventory service not avaiable");
1799 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
1800 for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) {
1801 Node node = entry.getKey();
1802 log.debug("getInventories: {} added for container {}", new Object[] { node, containerName });
1803 Map<String, Property> propMap = entry.getValue();
1804 Set<Property> props = new HashSet<Property>();
1805 for (Property property : propMap.values()) {
1806 props.add(property);
1808 addNode(node, props);
1811 Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps();
1812 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) {
1813 Map<String, Property> propMap = entry.getValue();
1814 for (Property property : propMap.values()) {
1815 addNodeConnectorProp(entry.getKey(), property);
1820 private void clearInventories() {
1822 nodeConnectorProps.clear();
1823 nodeConnectorNames.clear();
1824 spanNodeConnectors.clear();
1827 private void notifyNode(Node node, UpdateType type,
1828 Map<String, Property> propMap) {
1829 synchronized (inventoryListeners) {
1830 for (IInventoryListener service : inventoryListeners) {
1831 service.notifyNode(node, type, propMap);
1836 private void notifyNodeConnector(NodeConnector nodeConnector,
1837 UpdateType type, Map<String, Property> propMap) {
1838 synchronized (inventoryListeners) {
1839 for (IInventoryListener service : inventoryListeners) {
1840 service.notifyNodeConnector(nodeConnector, type, propMap);
1846 * For those joined late, bring them up-to-date.
1848 private void switchManagerAwareNotify(ISwitchManagerAware service) {
1849 for (Subnet sub : subnets.values()) {
1850 service.subnetNotify(sub, true);
1853 for (Node node : getNodes()) {
1854 SwitchConfig sc = getSwitchConfig(node.toString());
1855 if ((sc != null) && isDefaultContainer) {
1856 ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name);
1857 service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive());
1862 private void bulkUpdateService(IInventoryListener service) {
1863 Map<String, Property> propMap;
1864 UpdateType type = UpdateType.ADDED;
1866 for (Node node : getNodes()) {
1867 propMap = nodeProps.get(node);
1868 service.notifyNode(node, type, propMap);
1871 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) {
1872 NodeConnector nodeConnector = entry.getKey();
1873 propMap = nodeConnectorProps.get(nodeConnector);
1874 service.notifyNodeConnector(nodeConnector, type, propMap);
1878 private void spanAwareNotify(ISpanAware service) {
1879 for (Node node : getNodes()) {
1880 for (SpanConfig conf : getSpanConfigList(node)) {
1881 service.spanUpdate(node, conf.getPortArrayList(), true);
1886 private void registerWithOSGIConsole() {
1887 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
1888 .getBundleContext();
1889 bundleContext.registerService(CommandProvider.class.getName(), this,
1894 public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) {
1895 if (nodeConnector == null) {
1899 Config config = (Config) getNodeConnectorProp(nodeConnector,
1900 Config.ConfigPropName);
1901 State state = (State) getNodeConnectorProp(nodeConnector,
1902 State.StatePropName);
1903 return ((config != null) && (config.getValue() == Config.ADMIN_UP)
1904 && (state != null) && (state.getValue() == State.EDGE_UP));
1908 public boolean doesNodeConnectorExist(NodeConnector nc) {
1909 return (nc != null && nodeConnectorProps != null
1910 && nodeConnectorProps.containsKey(nc));
1914 public String getHelp() {
1915 StringBuffer help = new StringBuffer();
1916 help.append("---Switch Manager---\n");
1917 help.append("\t pencs <node id> - Print enabled node connectors for a given node\n");
1918 help.append("\t pdm <node id> - Print switch ports in device map\n");
1919 return help.toString();
1922 public void _pencs(CommandInterpreter ci) {
1923 String st = ci.nextArgument();
1925 ci.println("Please enter node id");
1929 Node node = Node.fromString(st);
1931 ci.println("Please enter node id");
1935 Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node);
1936 if (nodeConnectorSet == null) {
1939 for (NodeConnector nodeConnector : nodeConnectorSet) {
1940 if (nodeConnector == null) {
1943 ci.println(nodeConnector);
1945 ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size());
1948 public void _pdm(CommandInterpreter ci) {
1949 String st = ci.nextArgument();
1951 ci.println("Please enter node id");
1955 Node node = Node.fromString(st);
1957 ci.println("Please enter node id");
1961 Switch sw = getSwitchByNode(node);
1963 ci.println(" NodeConnector Name");
1965 Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors();
1966 String nodeConnectorName;
1967 if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
1968 for (NodeConnector nodeConnector : nodeConnectorSet) {
1969 Map<String, Property> propMap = getNodeConnectorProps(nodeConnector);
1970 nodeConnectorName = (propMap == null) ? null : ((Name) propMap
1971 .get(Name.NamePropName)).getValue();
1972 if (nodeConnectorName != null) {
1973 Node nd = nodeConnector.getNode();
1974 if (!nd.equals(node)) {
1975 log.debug("node not match {} {}", nd, node);
1977 Map<String, NodeConnector> map = nodeConnectorNames
1980 NodeConnector nc = map.get(nodeConnectorName);
1982 log.debug("no nodeConnector named {}",
1984 } else if (!nc.equals(nodeConnector)) {
1985 log.debug("nodeConnector not match {} {}", nc,
1991 ci.println(nodeConnector
1993 + ((nodeConnectorName == null) ? "" : nodeConnectorName)
1994 + "(" + nodeConnector.getID() + ")");
1996 ci.println("Total number of NodeConnectors: "
1997 + nodeConnectorSet.size());
2002 public byte[] getNodeMAC(Node node) {
2003 MacAddress mac = (MacAddress) this.getNodeProp(node,
2005 return (mac != null) ? mac.getMacAddress() : null;
2009 public boolean isSpecial(NodeConnector p) {
2010 if (p.getType().equals(NodeConnectorIDType.CONTROLLER)
2011 || p.getType().equals(NodeConnectorIDType.ALL)
2012 || p.getType().equals(NodeConnectorIDType.SWSTACK)
2013 || p.getType().equals(NodeConnectorIDType.HWPATH)) {
2020 * Add span configuration to local cache and notify clients
2022 private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2023 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2025 for (NodeConnector nodeConnector : nodeConnectors) {
2026 if (!spanNodeConnectors.contains(nodeConnector)) {
2027 ncLists.add(nodeConnector);
2031 if (ncLists.size() > 0) {
2032 spanNodeConnectors.addAll(ncLists);
2033 notifySpanPortChange(node, ncLists, true);
2037 private void addSpanPorts(Node node) {
2038 for (SpanConfig conf : getSpanConfigList(node)) {
2039 addSpanPorts(node, conf.getPortArrayList());
2043 private void addSpanPort(NodeConnector nodeConnector) {
2044 // only add if span is configured on this nodeConnector
2045 for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) {
2046 if (conf.getPortArrayList().contains(nodeConnector)) {
2047 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2048 ncLists.add(nodeConnector);
2049 addSpanPorts(nodeConnector.getNode(), ncLists);
2056 * Remove span configuration to local cache and notify clients
2058 private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) {
2059 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2061 for (NodeConnector nodeConnector : nodeConnectors) {
2062 if (spanNodeConnectors.contains(nodeConnector)) {
2063 ncLists.add(nodeConnector);
2067 if (ncLists.size() > 0) {
2068 spanNodeConnectors.removeAll(ncLists);
2069 notifySpanPortChange(node, ncLists, false);
2073 private void removeSpanPorts(Node node) {
2074 for (SpanConfig conf : getSpanConfigList(node)) {
2075 addSpanPorts(node, conf.getPortArrayList());
2079 private void removeSpanPort(NodeConnector nodeConnector) {
2080 if (spanNodeConnectors.contains(nodeConnector)) {
2081 List<NodeConnector> ncLists = new ArrayList<NodeConnector>();
2082 ncLists.add(nodeConnector);
2083 removeSpanPorts(nodeConnector.getNode(), ncLists);
2087 private void addNodeProps(Node node, Map<String, Property> propMap) {
2088 if (propMap == null) {
2089 propMap = new HashMap<String, Property>();
2091 nodeProps.put(node, propMap);
2095 public Status saveConfiguration() {
2096 return saveSwitchConfig();
2100 * Creates a Name/Tier/Bandwidth/MacAddress(controller property) Property
2101 * object based on given property name and value. Other property types are
2102 * not supported yet.
2105 * Name of the Property
2107 * Value of the Property
2108 * @return {@link org.opendaylight.controller.sal.core.Property}
2111 public Property createProperty(String propName, String propValue) {
2112 if (propName == null) {
2113 log.debug("propName is null");
2116 if (propValue == null) {
2117 log.debug("propValue is null");
2122 if (propName.equalsIgnoreCase(Description.propertyName)) {
2123 return new Description(propValue);
2124 } else if (propName.equalsIgnoreCase(Tier.TierPropName)) {
2125 int tier = Integer.parseInt(propValue);
2126 return new Tier(tier);
2127 } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) {
2128 long bw = Long.parseLong(propValue);
2129 return new Bandwidth(bw);
2130 } else if (propName.equalsIgnoreCase(ForwardingMode.name)) {
2131 int mode = Integer.parseInt(propValue);
2132 return new ForwardingMode(mode);
2133 } else if (propName.equalsIgnoreCase(MacAddress.name)){
2134 return new MacAddress(propValue);
2137 log.debug("Not able to create {} property", propName);
2139 } catch (Exception e) {
2140 log.debug("createProperty caught exception {}", e.getMessage());
2147 @SuppressWarnings("deprecation")
2149 public String getNodeDescription(Node node) {
2150 // Check first if user configured a name
2151 SwitchConfig config = getSwitchConfig(node.toString());
2152 if (config != null) {
2153 String configuredDesc = config.getNodeDescription();
2154 if (configuredDesc != null && !configuredDesc.isEmpty()) {
2155 return configuredDesc;
2159 // No name configured by user, get the node advertised name
2160 Description desc = (Description) getNodeProp(node,
2161 Description.propertyName);
2162 return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? ""
2167 public Set<Switch> getConfiguredNotConnectedSwitches() {
2168 Set<Switch> configuredNotConnectedSwitches = new HashSet<Switch>();
2169 if (this.inventoryService == null) {
2170 log.trace("inventory service not avaiable");
2171 return configuredNotConnectedSwitches;
2174 Set<Node> configuredNotConnectedNodes = this.inventoryService.getConfiguredNotConnectedNodes();
2175 if (configuredNotConnectedNodes != null) {
2176 for (Node node : configuredNotConnectedNodes) {
2177 Switch sw = getSwitchByNode(node);
2179 configuredNotConnectedSwitches.add(sw);
2183 return configuredNotConnectedSwitches;