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.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35 import org.eclipse.osgi.framework.console.CommandInterpreter;
36 import org.eclipse.osgi.framework.console.CommandProvider;
37 import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
38 import org.opendaylight.controller.clustering.services.IClusterGlobalServices;
39 import org.opendaylight.controller.clustering.services.ICoordinatorChangeAware;
40 import org.opendaylight.controller.connectionmanager.ConnectionMgmtScheme;
41 import org.opendaylight.controller.connectionmanager.IConnectionManager;
42 import org.opendaylight.controller.connectionmanager.scheme.AbstractScheme;
43 import org.opendaylight.controller.connectionmanager.scheme.SchemeFactory;
44 import org.opendaylight.controller.sal.connection.ConnectionConstants;
45 import org.opendaylight.controller.sal.connection.IConnectionListener;
46 import org.opendaylight.controller.sal.connection.IConnectionService;
47 import org.opendaylight.controller.sal.core.Node;
48 import org.opendaylight.controller.sal.core.NodeConnector;
49 import org.opendaylight.controller.sal.core.Property;
50 import org.opendaylight.controller.sal.core.UpdateType;
51 import org.opendaylight.controller.sal.inventory.IInventoryService;
52 import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates;
53 import org.opendaylight.controller.sal.utils.Status;
54 import org.opendaylight.controller.sal.utils.StatusCode;
55 import org.osgi.framework.BundleContext;
56 import org.osgi.framework.FrameworkUtil;
58 public class ConnectionManager implements IConnectionManager, IConnectionListener,
59 ICoordinatorChangeAware, IListenInventoryUpdates,
60 ICacheUpdateAware<Node, Set<InetAddress>>,
62 private static final Logger logger = LoggerFactory.getLogger(ConnectionManager.class);
63 private ConnectionMgmtScheme activeScheme = ConnectionMgmtScheme.ANY_CONTROLLER_ONE_MASTER;
64 private IClusterGlobalServices clusterServices;
65 private ConcurrentMap<ConnectionMgmtScheme, AbstractScheme> schemes;
66 private IConnectionService connectionService;
67 private Thread connectionEventThread;
68 private BlockingQueue<ConnectionMgmtEvent> connectionEvents;
69 private IInventoryService inventoryService;
71 public void setClusterServices(IClusterGlobalServices i) {
72 this.clusterServices = i;
75 public void unsetClusterServices(IClusterGlobalServices i) {
76 if (this.clusterServices == i) {
77 this.clusterServices = null;
81 public void setConnectionService(IConnectionService i) {
82 this.connectionService = i;
85 public void unsetConnectionService(IConnectionService i) {
86 if (this.connectionService == i) {
87 this.connectionService = null;
91 public void setInventoryService(IInventoryService service) {
92 logger.trace("Got inventory service set request {}", service);
93 this.inventoryService = service;
96 public void unsetInventoryService(IInventoryService service) {
97 logger.trace("Got a service UNset request");
98 this.inventoryService = null;
101 private void getInventories() {
102 Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps();
103 for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) {
104 Node node = entry.getKey();
105 logger.debug("getInventories for node:{}", new Object[] { node });
106 Map<String, Property> propMap = entry.getValue();
107 Set<Property> props = new HashSet<Property>();
108 for (Property property : propMap.values()) {
111 updateNode(node, UpdateType.ADDED, props);
114 Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps();
115 for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) {
116 Map<String, Property> propMap = entry.getValue();
117 Set<Property> props = new HashSet<Property>();
118 for (Property property : propMap.values()) {
121 updateNodeConnector(entry.getKey(), UpdateType.ADDED, props);
125 public void started() {
126 connectionEventThread = new Thread(new EventHandler(), "ConnectionEvent Thread");
127 connectionEventThread.start();
129 registerWithOSGIConsole();
130 notifyClusterViewChanged();
131 // Should pull the Inventory updates in case we missed it
136 this.connectionEvents = new LinkedBlockingQueue<ConnectionMgmtEvent>();
137 schemes = new ConcurrentHashMap<ConnectionMgmtScheme, AbstractScheme>();
138 for (ConnectionMgmtScheme scheme : ConnectionMgmtScheme.values()) {
139 AbstractScheme schemeImpl = SchemeFactory.getScheme(scheme, clusterServices);
140 if (schemeImpl != null) schemes.put(scheme, schemeImpl);
145 connectionEventThread.interrupt();
146 Set<Node> localNodes = getLocalNodes();
147 if (localNodes != null) {
148 AbstractScheme scheme = schemes.get(activeScheme);
149 for (Node localNode : localNodes) {
150 connectionService.disconnect(localNode);
151 if (scheme != null) scheme.removeNode(localNode);
157 public ConnectionMgmtScheme getActiveScheme() {
162 public Set<Node> getNodes(InetAddress controller) {
163 AbstractScheme scheme = schemes.get(activeScheme);
164 if (scheme == null) return null;
165 return scheme.getNodes(controller);
169 public Set<Node> getLocalNodes() {
170 AbstractScheme scheme = schemes.get(activeScheme);
171 if (scheme == null) return null;
172 return scheme.getNodes();
176 public boolean isLocal(Node node) {
177 AbstractScheme scheme = schemes.get(activeScheme);
178 if (scheme == null) return false;
179 return scheme.isLocal(node);
183 public void updateNode(Node node, UpdateType type, Set<Property> props) {
184 logger.debug("updateNode: {} type {} props {}", node, type, props);
185 AbstractScheme scheme = schemes.get(activeScheme);
186 if (scheme == null) return;
189 scheme.addNode(node);
192 scheme.removeNode(node);
200 public void updateNodeConnector(NodeConnector nodeConnector,
201 UpdateType type, Set<Property> props) {
202 logger.debug("updateNodeConnector: {} type {} props {}", nodeConnector, type, props);
203 AbstractScheme scheme = schemes.get(activeScheme);
204 if (scheme == null) return;
207 scheme.addNode(nodeConnector.getNode());
215 public void coordinatorChanged() {
216 notifyClusterViewChanged();
220 public Node connect(String connectionIdentifier, Map<ConnectionConstants, String> params) {
221 if (connectionService == null) return null;
222 return connectionService.connect(connectionIdentifier, params);
226 public Node connect(String type, String connectionIdentifier, Map<ConnectionConstants, String> params) {
227 if (connectionService == null) return null;
228 return connectionService.connect(type, connectionIdentifier, params);
232 public Status disconnect (Node node) {
233 if (connectionService == null) return new Status(StatusCode.NOSERVICE);
234 return connectionService.disconnect(node);
238 public void entryCreated(Node key, String cacheName, boolean originLocal) {
239 if (originLocal) return;
243 * Clustering Services' doesnt provide the existing states in the cache update callbacks.
244 * Hence, using a scratch local cache to maintain the existing state.
247 private ConcurrentMap<Node, Set<InetAddress>> existingConnections = new ConcurrentHashMap<Node, Set<InetAddress>>();
250 public void entryUpdated(Node node, Set<InetAddress> newControllers, String cacheName, boolean originLocal) {
251 if (originLocal) return;
252 Set<InetAddress> existingControllers = existingConnections.get(node);
253 if (existingControllers != null) {
254 logger.debug("Processing Update for : {} NewControllers : {} existingControllers : {}", node,
255 newControllers.toString(), existingControllers.toString());
256 if (newControllers.size() < existingControllers.size()) {
257 Set<InetAddress> removed = new HashSet<InetAddress>(existingControllers);
258 if (removed.removeAll(newControllers)) {
259 logger.debug("notifyNodeDisconnectFromMaster({})", node);
260 notifyNodeDisconnectedEvent(node);
264 logger.debug("Ignoring the Update for : {} NewControllers : {}", node, newControllers.toString());
266 existingConnections.put(node, newControllers);
270 public void entryDeleted(Node key, String cacheName, boolean originLocal) {
271 if (originLocal) return;
272 logger.debug("Deleted : {} cache : {}", key, cacheName);
273 notifyNodeDisconnectedEvent(key);
276 private void enqueueConnectionEvent(ConnectionMgmtEvent event) {
278 if (!connectionEvents.contains(event)) {
279 this.connectionEvents.put(event);
281 } catch (InterruptedException e) {
282 logger.debug("enqueueConnectionEvent caught Interrupt Exception for event {}", event);
286 private void notifyClusterViewChanged() {
287 ConnectionMgmtEvent event = new ConnectionMgmtEvent(ConnectionMgmtEventType.CLUSTER_VIEW_CHANGED, null);
288 enqueueConnectionEvent(event);
291 private void notifyNodeDisconnectedEvent(Node node) {
292 ConnectionMgmtEvent event = new ConnectionMgmtEvent(ConnectionMgmtEventType.NODE_DISCONNECTED_FROM_MASTER, node);
293 enqueueConnectionEvent(event);
297 * this thread monitors the connectionEvent queue for new incoming events from
299 private class EventHandler implements Runnable {
305 ConnectionMgmtEvent ev = connectionEvents.take();
306 ConnectionMgmtEventType eType = ev.getEvent();
308 case NODE_DISCONNECTED_FROM_MASTER:
309 Node node = (Node)ev.getData();
310 connectionService.notifyNodeDisconnectFromMaster(node);
312 case CLUSTER_VIEW_CHANGED:
313 AbstractScheme scheme = schemes.get(activeScheme);
314 if (scheme == null) return;
315 scheme.handleClusterViewChanged();
316 connectionService.notifyClusterViewChanged();
319 logger.error("Unknown Connection event {}", eType.ordinal());
321 } catch (InterruptedException e) {
322 connectionEvents.clear();
329 private void registerWithOSGIConsole() {
330 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
332 bundleContext.registerService(CommandProvider.class.getName(), this,
336 public void _scheme (CommandInterpreter ci) {
337 String schemeStr = ci.nextArgument();
338 if (schemeStr == null) {
339 ci.println("Please enter valid Scheme name");
340 ci.println("Current Scheme : " + activeScheme.name());
343 ConnectionMgmtScheme scheme = ConnectionMgmtScheme.valueOf(schemeStr);
344 if (scheme == null) {
345 ci.println("Please enter a valid Scheme name");
348 activeScheme = scheme;
351 public void _printNodes (CommandInterpreter ci) {
352 String controller = ci.nextArgument();
353 if (controller == null) {
354 ci.println("Nodes connected to this controller : ");
355 if (this.getLocalNodes() == null) ci.println("None");
356 else ci.println(this.getLocalNodes().toString());
360 InetAddress address = InetAddress.getByName(controller);
361 ci.println("Nodes connected to controller "+controller);
362 if (this.getNodes(address) == null) ci.println("None");
363 else ci.println(this.getNodes(address).toString());
365 } catch (UnknownHostException e) {
366 logger.error("An error occured",e);
371 public String getHelp() {
372 StringBuffer help = new StringBuffer();
373 help.append("---Connection Manager---\n");
374 help.append("\t scheme [<name>] - Print / Set scheme\n");
375 help.append("\t printNodes [<controller>] - Print connected nodes\n");
376 return help.toString();