3 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
5 * This program and the accompanying materials are made available under the
6 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7 * and is available at http://www.eclipse.org/legal/epl-v10.html
11 * Connection Manager provides south-bound connectivity services.
12 * The APIs are currently focused towards Active-Active Clustering support
13 * wherein the node can connect to any of the Active Controller in the Cluster.
14 * This component can also host the necessary logic for south-bound connectivity
15 * when partial cluster is identified during Partition scenarios.
17 * But this (and its corresponding implementation) component can also be used for
18 * basic connectivity mechansims for various south-bound plugins.
21 package org.opendaylight.controller.connectionmanager.internal;
23 import java.net.InetAddress;
24 import java.net.UnknownHostException;
25 import java.util.HashSet;
28 import java.util.concurrent.BlockingQueue;
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.ConcurrentMap;
31 import java.util.concurrent.LinkedBlockingQueue;
33 import org.eclipse.osgi.framework.console.CommandInterpreter;
34 import org.eclipse.osgi.framework.console.CommandProvider;
35 import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
36 import org.opendaylight.controller.clustering.services.IClusterGlobalServices;
37 import org.opendaylight.controller.clustering.services.ICoordinatorChangeAware;
38 import org.opendaylight.controller.connectionmanager.ConnectionMgmtScheme;
39 import org.opendaylight.controller.connectionmanager.IConnectionManager;
40 import org.opendaylight.controller.connectionmanager.scheme.AbstractScheme;
41 import org.opendaylight.controller.connectionmanager.scheme.SchemeFactory;
42 import org.opendaylight.controller.sal.connection.ConnectionConstants;
43 import org.opendaylight.controller.sal.connection.ConnectionLocality;
44 import org.opendaylight.controller.sal.connection.IConnectionListener;
45 import org.opendaylight.controller.sal.connection.IConnectionService;
46 import org.opendaylight.controller.sal.core.Node;
47 import org.opendaylight.controller.sal.core.NodeConnector;
48 import org.opendaylight.controller.sal.core.Property;
49 import org.opendaylight.controller.sal.core.UpdateType;
50 import org.opendaylight.controller.sal.inventory.IInventoryService;
51 import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates;
52 import org.opendaylight.controller.sal.utils.Status;
53 import org.opendaylight.controller.sal.utils.StatusCode;
54 import org.osgi.framework.BundleContext;
55 import org.osgi.framework.FrameworkUtil;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
59 public class ConnectionManager implements IConnectionManager, IConnectionListener,
60 ICoordinatorChangeAware, IListenInventoryUpdates,
61 ICacheUpdateAware<Node, Set<InetAddress>>,
63 private static final Logger logger = LoggerFactory.getLogger(ConnectionManager.class);
64 private ConnectionMgmtScheme activeScheme = ConnectionMgmtScheme.ANY_CONTROLLER_ONE_MASTER;
65 private IClusterGlobalServices clusterServices;
66 private ConcurrentMap<ConnectionMgmtScheme, AbstractScheme> schemes;
67 private IConnectionService connectionService;
68 private Thread connectionEventThread;
69 private BlockingQueue<ConnectionMgmtEvent> connectionEvents;
70 private IInventoryService inventoryService;
72 public void setClusterServices(IClusterGlobalServices i) {
73 this.clusterServices = i;
76 public void unsetClusterServices(IClusterGlobalServices i) {
77 if (this.clusterServices == i) {
78 this.clusterServices = null;
82 public void setConnectionService(IConnectionService i) {
83 this.connectionService = i;
86 public void unsetConnectionService(IConnectionService i) {
87 if (this.connectionService == i) {
88 this.connectionService = null;
92 public void setInventoryService(IInventoryService service) {
93 logger.trace("Got inventory service set request {}", service);
94 this.inventoryService = service;
97 public void unsetInventoryService(IInventoryService service) {
98 logger.trace("Got a service UNset request");
99 this.inventoryService = null;
102 private void getInventories() {
103 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
104 for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) {
105 Node node = entry.getKey();
106 logger.debug("getInventories for node:{}", new Object[] { node });
107 Map<String, Property> propMap = entry.getValue();
108 Set<Property> props = new HashSet<Property>();
109 for (Property property : propMap.values()) {
112 updateNode(node, UpdateType.ADDED, props);
115 Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps();
116 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) {
117 Map<String, Property> propMap = entry.getValue();
118 Set<Property> props = new HashSet<Property>();
119 for (Property property : propMap.values()) {
122 updateNodeConnector(entry.getKey(), UpdateType.ADDED, props);
127 public void started() {
128 String schemeStr = System.getProperty("connection.scheme");
129 for (ConnectionMgmtScheme scheme : ConnectionMgmtScheme.values()) {
130 AbstractScheme schemeImpl = SchemeFactory.getScheme(scheme, clusterServices);
131 if (schemeImpl != null) {
132 schemes.put(scheme, schemeImpl);
133 if (scheme.name().equalsIgnoreCase(schemeStr)) {
134 activeScheme = scheme;
139 connectionEventThread.start();
141 registerWithOSGIConsole();
142 notifyClusterViewChanged();
143 // Should pull the Inventory updates in case we missed it
148 connectionEventThread = new Thread(new EventHandler(), "ConnectionEvent Thread");
149 this.connectionEvents = new LinkedBlockingQueue<ConnectionMgmtEvent>();
150 schemes = new ConcurrentHashMap<ConnectionMgmtScheme, AbstractScheme>();
153 public void stopping() {
154 connectionEventThread.interrupt();
155 Set<Node> localNodes = getLocalNodes();
156 if (localNodes != null) {
157 AbstractScheme scheme = schemes.get(activeScheme);
158 for (Node localNode : localNodes) {
159 connectionService.disconnect(localNode);
160 if (scheme != null) scheme.removeNode(localNode);
166 public ConnectionMgmtScheme getActiveScheme() {
171 public Set<Node> getNodes(InetAddress controller) {
172 AbstractScheme scheme = schemes.get(activeScheme);
173 if (scheme == null) return null;
174 return scheme.getNodes(controller);
178 public Set<Node> getLocalNodes() {
179 AbstractScheme scheme = schemes.get(activeScheme);
180 if (scheme == null) return null;
181 return scheme.getNodes();
185 public boolean isLocal(Node node) {
186 AbstractScheme scheme = schemes.get(activeScheme);
187 if (scheme == null) return false;
188 return scheme.isLocal(node);
192 public ConnectionLocality getLocalityStatus(Node node) {
193 AbstractScheme scheme = schemes.get(activeScheme);
194 if (scheme == null) return ConnectionLocality.NOT_CONNECTED;
195 return scheme.getLocalityStatus(node);
199 public void updateNode(Node node, UpdateType type, Set<Property> props) {
200 logger.debug("updateNode: {} type {} props {}", node, type, props);
201 AbstractScheme scheme = schemes.get(activeScheme);
202 if (scheme == null) return;
205 scheme.addNode(node);
208 scheme.removeNode(node);
216 public void updateNodeConnector(NodeConnector nodeConnector,
217 UpdateType type, Set<Property> props) {
218 logger.debug("updateNodeConnector: {} type {} props {}", nodeConnector, type, props);
219 AbstractScheme scheme = schemes.get(activeScheme);
220 if (scheme == null) return;
223 scheme.addNode(nodeConnector.getNode());
231 public void coordinatorChanged() {
232 notifyClusterViewChanged();
236 public Node connect(String connectionIdentifier, Map<ConnectionConstants, String> params) {
237 if (connectionService == null) return null;
238 Node node = connectionService.connect(connectionIdentifier, params);
239 AbstractScheme scheme = schemes.get(activeScheme);
240 if (scheme != null && node != null) scheme.addNode(node);
245 public Node connect(String type, String connectionIdentifier, Map<ConnectionConstants, String> params) {
246 if (connectionService == null) return null;
247 Node node = connectionService.connect(connectionIdentifier, params);
248 AbstractScheme scheme = schemes.get(activeScheme);
249 if (scheme != null && node != null) scheme.addNode(node);
254 public Status disconnect (Node node) {
255 if (node == null) return new Status(StatusCode.BADREQUEST);
256 if (connectionService == null) return new Status(StatusCode.NOSERVICE);
257 Status status = connectionService.disconnect(node);
258 if (status.isSuccess()) {
259 AbstractScheme scheme = schemes.get(activeScheme);
260 if (scheme != null) scheme.removeNode(node);
266 public void entryCreated(Node key, String cacheName, boolean originLocal) {
267 if (originLocal) return;
271 * Clustering Services' doesnt provide the existing states in the cache update callbacks.
272 * Hence, using a scratch local cache to maintain the existing state.
275 private ConcurrentMap<Node, Set<InetAddress>> existingConnections = new ConcurrentHashMap<Node, Set<InetAddress>>();
278 public void entryUpdated(Node node, Set<InetAddress> newControllers, String cacheName, boolean originLocal) {
279 if (originLocal) return;
280 Set<InetAddress> existingControllers = existingConnections.get(node);
281 if (existingControllers != null) {
282 logger.debug("Processing Update for : {} NewControllers : {} existingControllers : {}", node,
283 newControllers.toString(), existingControllers.toString());
284 if (newControllers.size() < existingControllers.size()) {
285 Set<InetAddress> removed = new HashSet<InetAddress>(existingControllers);
286 if (removed.removeAll(newControllers)) {
287 logger.debug("notifyNodeDisconnectFromMaster({})", node);
288 notifyNodeDisconnectedEvent(node);
292 logger.debug("Ignoring the Update for : {} NewControllers : {}", node, newControllers.toString());
294 existingConnections.put(node, newControllers);
298 public void entryDeleted(Node key, String cacheName, boolean originLocal) {
299 if (originLocal) return;
300 logger.debug("Deleted : {} cache : {}", key, cacheName);
301 notifyNodeDisconnectedEvent(key);
304 private void enqueueConnectionEvent(ConnectionMgmtEvent event) {
306 if (!connectionEvents.contains(event)) {
307 this.connectionEvents.put(event);
309 } catch (InterruptedException e) {
310 logger.debug("enqueueConnectionEvent caught Interrupt Exception for event {}", event);
314 private void notifyClusterViewChanged() {
315 ConnectionMgmtEvent event = new ConnectionMgmtEvent(ConnectionMgmtEventType.CLUSTER_VIEW_CHANGED, null);
316 enqueueConnectionEvent(event);
319 private void notifyNodeDisconnectedEvent(Node node) {
320 ConnectionMgmtEvent event = new ConnectionMgmtEvent(ConnectionMgmtEventType.NODE_DISCONNECTED_FROM_MASTER, node);
321 enqueueConnectionEvent(event);
325 * this thread monitors the connectionEvent queue for new incoming events from
327 private class EventHandler implements Runnable {
333 ConnectionMgmtEvent ev = connectionEvents.take();
334 ConnectionMgmtEventType eType = ev.getEvent();
336 case NODE_DISCONNECTED_FROM_MASTER:
337 Node node = (Node)ev.getData();
338 connectionService.notifyNodeDisconnectFromMaster(node);
340 case CLUSTER_VIEW_CHANGED:
341 AbstractScheme scheme = schemes.get(activeScheme);
342 if (scheme == null) return;
343 scheme.handleClusterViewChanged();
344 connectionService.notifyClusterViewChanged();
347 logger.error("Unknown Connection event {}", eType.ordinal());
349 } catch (InterruptedException e) {
350 connectionEvents.clear();
357 private void registerWithOSGIConsole() {
358 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
360 bundleContext.registerService(CommandProvider.class.getName(), this,
364 public void _scheme (CommandInterpreter ci) {
365 String schemeStr = ci.nextArgument();
366 if (schemeStr == null) {
367 ci.println("Please enter valid Scheme name");
368 ci.println("Current Scheme : " + activeScheme.name());
371 ConnectionMgmtScheme scheme = ConnectionMgmtScheme.valueOf(schemeStr);
372 if (scheme == null) {
373 ci.println("Please enter a valid Scheme name");
376 activeScheme = scheme;
379 public void _printNodes (CommandInterpreter ci) {
380 String controller = ci.nextArgument();
381 if (controller == null) {
382 ci.println("Nodes connected to this controller : ");
383 if (this.getLocalNodes() == null) {
386 ci.println(this.getLocalNodes().toString());
391 InetAddress address = InetAddress.getByName(controller);
392 ci.println("Nodes connected to controller "+controller);
393 if (this.getNodes(address) == null) {
396 ci.println(this.getNodes(address).toString());
398 } catch (UnknownHostException e) {
399 logger.error("An error occured",e);
404 public String getHelp() {
405 StringBuffer help = new StringBuffer();
406 help.append("---Connection Manager---\n");
407 help.append("\t scheme [<name>] - Print / Set scheme\n");
408 help.append("\t printNodes [<controller>] - Print connected nodes\n");
409 return help.toString();