Adding Tri-states to the connection manager locality check.
[controller.git] / opendaylight / connectionmanager / implementation / src / main / java / org / opendaylight / controller / connectionmanager / internal / ConnectionManager.java
1
2 /*
3  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
4  *
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
8  */
9
10 /**
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.
16  *
17  * But this (and its corresponding implementation) component can also be used for
18  * basic connectivity mechansims for various south-bound plugins.
19  */
20
21 package org.opendaylight.controller.connectionmanager.internal;
22
23 import java.net.InetAddress;
24 import java.net.UnknownHostException;
25 import java.util.HashSet;
26 import java.util.Map;
27 import java.util.Set;
28 import java.util.concurrent.BlockingQueue;
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.ConcurrentMap;
31 import java.util.concurrent.LinkedBlockingQueue;
32
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.ConnectionLocality;
41 import org.opendaylight.controller.connectionmanager.ConnectionMgmtScheme;
42 import org.opendaylight.controller.connectionmanager.IConnectionManager;
43 import org.opendaylight.controller.connectionmanager.scheme.AbstractScheme;
44 import org.opendaylight.controller.connectionmanager.scheme.SchemeFactory;
45 import org.opendaylight.controller.sal.connection.ConnectionConstants;
46 import org.opendaylight.controller.sal.connection.IConnectionListener;
47 import org.opendaylight.controller.sal.connection.IConnectionService;
48 import org.opendaylight.controller.sal.core.Node;
49 import org.opendaylight.controller.sal.core.NodeConnector;
50 import org.opendaylight.controller.sal.core.Property;
51 import org.opendaylight.controller.sal.core.UpdateType;
52 import org.opendaylight.controller.sal.inventory.IInventoryService;
53 import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates;
54 import org.opendaylight.controller.sal.utils.Status;
55 import org.opendaylight.controller.sal.utils.StatusCode;
56 import org.osgi.framework.BundleContext;
57 import org.osgi.framework.FrameworkUtil;
58
59 public class ConnectionManager implements IConnectionManager, IConnectionListener,
60                                           ICoordinatorChangeAware, IListenInventoryUpdates,
61                                           ICacheUpdateAware<Node, Set<InetAddress>>,
62                                           CommandProvider {
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;
71
72     public void setClusterServices(IClusterGlobalServices i) {
73         this.clusterServices = i;
74     }
75
76     public void unsetClusterServices(IClusterGlobalServices i) {
77         if (this.clusterServices == i) {
78             this.clusterServices = null;
79         }
80     }
81
82     public void setConnectionService(IConnectionService i) {
83         this.connectionService = i;
84     }
85
86     public void unsetConnectionService(IConnectionService i) {
87         if (this.connectionService == i) {
88             this.connectionService = null;
89         }
90     }
91
92     public void setInventoryService(IInventoryService service) {
93         logger.trace("Got inventory service set request {}", service);
94         this.inventoryService = service;
95     }
96
97     public void unsetInventoryService(IInventoryService service) {
98         logger.trace("Got a service UNset request");
99         this.inventoryService = null;
100     }
101
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()) {
110                 props.add(property);
111             }
112             updateNode(node, UpdateType.ADDED, props);
113         }
114
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()) {
120                 props.add(property);
121             }
122             updateNodeConnector(entry.getKey(), UpdateType.ADDED, props);
123         }
124     }
125
126     public void started() {
127         connectionEventThread = new Thread(new EventHandler(), "ConnectionEvent Thread");
128         connectionEventThread.start();
129
130         registerWithOSGIConsole();
131         notifyClusterViewChanged();
132         // Should pull the Inventory updates in case we missed it
133         getInventories();
134     }
135
136     public void init() {
137         String schemeStr = System.getProperty("connection.scheme");
138         this.connectionEvents = new LinkedBlockingQueue<ConnectionMgmtEvent>();
139         schemes = new ConcurrentHashMap<ConnectionMgmtScheme, AbstractScheme>();
140         for (ConnectionMgmtScheme scheme : ConnectionMgmtScheme.values()) {
141             AbstractScheme schemeImpl = SchemeFactory.getScheme(scheme, clusterServices);
142             if (schemeImpl != null) {
143                 schemes.put(scheme, schemeImpl);
144                 if (scheme.name().equalsIgnoreCase(schemeStr)) {
145                     activeScheme = scheme;
146                 }
147             }
148         }
149     }
150
151     public void stop() {
152         connectionEventThread.interrupt();
153         Set<Node> localNodes = getLocalNodes();
154         if (localNodes != null) {
155             AbstractScheme scheme = schemes.get(activeScheme);
156             for (Node localNode : localNodes) {
157                 connectionService.disconnect(localNode);
158                 if (scheme != null) scheme.removeNode(localNode);
159             }
160         }
161     }
162
163     @Override
164     public ConnectionMgmtScheme getActiveScheme() {
165         return activeScheme;
166     }
167
168     @Override
169     public Set<Node> getNodes(InetAddress controller) {
170         AbstractScheme scheme = schemes.get(activeScheme);
171         if (scheme == null) return null;
172         return scheme.getNodes(controller);
173     }
174
175     @Override
176     public Set<Node> getLocalNodes() {
177         AbstractScheme scheme = schemes.get(activeScheme);
178         if (scheme == null) return null;
179         return scheme.getNodes();
180     }
181
182     @Override
183     public boolean isLocal(Node node) {
184         AbstractScheme scheme = schemes.get(activeScheme);
185         if (scheme == null) return false;
186         return scheme.isLocal(node);
187     }
188
189     @Override
190     public ConnectionLocality getLocalityStatus(Node node) {
191         AbstractScheme scheme = schemes.get(activeScheme);
192         if (scheme == null) return ConnectionLocality.NOT_CONNECTED;
193         return scheme.getLocalityStatus(node);
194     }
195
196     @Override
197     public void updateNode(Node node, UpdateType type, Set<Property> props) {
198         logger.debug("updateNode: {} type {} props {}", node, type, props);
199         AbstractScheme scheme = schemes.get(activeScheme);
200         if (scheme == null) return;
201         switch (type) {
202         case ADDED:
203             scheme.addNode(node);
204             break;
205         case REMOVED:
206             scheme.removeNode(node);
207             break;
208         default:
209                 break;
210         }
211     }
212
213     @Override
214     public void updateNodeConnector(NodeConnector nodeConnector,
215             UpdateType type, Set<Property> props) {
216         logger.debug("updateNodeConnector: {} type {} props {}", nodeConnector, type, props);
217         AbstractScheme scheme = schemes.get(activeScheme);
218         if (scheme == null) return;
219         switch (type) {
220         case ADDED:
221             scheme.addNode(nodeConnector.getNode());
222             break;
223         default:
224                 break;
225         }
226     }
227
228     @Override
229     public void coordinatorChanged() {
230         notifyClusterViewChanged();
231     }
232
233     @Override
234     public Node connect(String connectionIdentifier, Map<ConnectionConstants, String> params) {
235         if (connectionService == null) return null;
236         return connectionService.connect(connectionIdentifier, params);
237     }
238
239     @Override
240     public Node connect(String type, String connectionIdentifier, Map<ConnectionConstants, String> params) {
241         if (connectionService == null) return null;
242         return connectionService.connect(type, connectionIdentifier, params);
243     }
244
245     @Override
246     public Status disconnect (Node node) {
247         if (connectionService == null) return new Status(StatusCode.NOSERVICE);
248         return connectionService.disconnect(node);
249     }
250
251     @Override
252     public void entryCreated(Node key, String cacheName, boolean originLocal) {
253         if (originLocal) return;
254     }
255
256     /*
257      * Clustering Services' doesnt provide the existing states in the cache update callbacks.
258      * Hence, using a scratch local cache to maintain the existing state.
259      *
260      */
261     private ConcurrentMap<Node, Set<InetAddress>> existingConnections = new ConcurrentHashMap<Node, Set<InetAddress>>();
262
263     @Override
264     public void entryUpdated(Node node, Set<InetAddress> newControllers, String cacheName, boolean originLocal) {
265         if (originLocal) return;
266         Set<InetAddress> existingControllers = existingConnections.get(node);
267         if (existingControllers != null) {
268             logger.debug("Processing Update for : {} NewControllers : {} existingControllers : {}", node,
269                     newControllers.toString(), existingControllers.toString());
270             if (newControllers.size() < existingControllers.size()) {
271                 Set<InetAddress> removed = new HashSet<InetAddress>(existingControllers);
272                 if (removed.removeAll(newControllers)) {
273                     logger.debug("notifyNodeDisconnectFromMaster({})", node);
274                     notifyNodeDisconnectedEvent(node);
275                 }
276             }
277         } else {
278             logger.debug("Ignoring the Update for : {} NewControllers : {}", node, newControllers.toString());
279         }
280         existingConnections.put(node, newControllers);
281     }
282
283     @Override
284     public void entryDeleted(Node key, String cacheName, boolean originLocal) {
285         if (originLocal) return;
286         logger.debug("Deleted : {} cache : {}", key, cacheName);
287         notifyNodeDisconnectedEvent(key);
288     }
289
290     private void enqueueConnectionEvent(ConnectionMgmtEvent event) {
291         try {
292             if (!connectionEvents.contains(event)) {
293                 this.connectionEvents.put(event);
294             }
295         } catch (InterruptedException e) {
296             logger.debug("enqueueConnectionEvent caught Interrupt Exception for event {}", event);
297         }
298     }
299
300     private void notifyClusterViewChanged() {
301         ConnectionMgmtEvent event = new ConnectionMgmtEvent(ConnectionMgmtEventType.CLUSTER_VIEW_CHANGED, null);
302         enqueueConnectionEvent(event);
303     }
304
305     private void notifyNodeDisconnectedEvent(Node node) {
306         ConnectionMgmtEvent event = new ConnectionMgmtEvent(ConnectionMgmtEventType.NODE_DISCONNECTED_FROM_MASTER, node);
307         enqueueConnectionEvent(event);
308     }
309
310     /*
311      * this thread monitors the connectionEvent queue for new incoming events from
312      */
313     private class EventHandler implements Runnable {
314         @Override
315         public void run() {
316
317             while (true) {
318                 try {
319                     ConnectionMgmtEvent ev = connectionEvents.take();
320                     ConnectionMgmtEventType eType = ev.getEvent();
321                     switch (eType) {
322                     case NODE_DISCONNECTED_FROM_MASTER:
323                         Node node = (Node)ev.getData();
324                         connectionService.notifyNodeDisconnectFromMaster(node);
325                         break;
326                     case CLUSTER_VIEW_CHANGED:
327                         AbstractScheme scheme = schemes.get(activeScheme);
328                         if (scheme == null) return;
329                         scheme.handleClusterViewChanged();
330                         connectionService.notifyClusterViewChanged();
331                         break;
332                     default:
333                         logger.error("Unknown Connection event {}", eType.ordinal());
334                     }
335                 } catch (InterruptedException e) {
336                     connectionEvents.clear();
337                     return;
338                 }
339             }
340         }
341     }
342
343     private void registerWithOSGIConsole() {
344         BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
345                 .getBundleContext();
346         bundleContext.registerService(CommandProvider.class.getName(), this,
347                 null);
348     }
349
350     public void _scheme (CommandInterpreter ci) {
351         String schemeStr = ci.nextArgument();
352         if (schemeStr == null) {
353             ci.println("Please enter valid Scheme name");
354             ci.println("Current Scheme : " + activeScheme.name());
355             return;
356         }
357         ConnectionMgmtScheme scheme = ConnectionMgmtScheme.valueOf(schemeStr);
358         if (scheme == null) {
359             ci.println("Please enter a valid Scheme name");
360             return;
361         }
362         activeScheme = scheme;
363     }
364
365     public void _printNodes (CommandInterpreter ci) {
366         String controller = ci.nextArgument();
367         if (controller == null) {
368             ci.println("Nodes connected to this controller : ");
369             if (this.getLocalNodes() == null) {
370                 ci.println("None");
371             } else {
372                 ci.println(this.getLocalNodes().toString());
373             }
374             return;
375         }
376         try {
377             InetAddress address = InetAddress.getByName(controller);
378             ci.println("Nodes connected to controller "+controller);
379             if (this.getNodes(address) == null) {
380                 ci.println("None");
381             } else {
382                 ci.println(this.getNodes(address).toString());
383             }
384         } catch (UnknownHostException e) {
385            logger.error("An error occured",e);
386         }
387     }
388
389     @Override
390     public String getHelp() {
391         StringBuffer help = new StringBuffer();
392         help.append("---Connection Manager---\n");
393         help.append("\t scheme [<name>]                      - Print / Set scheme\n");
394         help.append("\t printNodes [<controller>]            - Print connected nodes\n");
395         return help.toString();
396     }
397 }