Fix Connection manager to retrieve inventory when is up
[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.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;
57
58 public class ConnectionManager implements IConnectionManager, IConnectionListener,
59                                           ICoordinatorChangeAware, IListenInventoryUpdates,
60                                           ICacheUpdateAware<Node, Set<InetAddress>>,
61                                           CommandProvider {
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;
70
71     public void setClusterServices(IClusterGlobalServices i) {
72         this.clusterServices = i;
73     }
74
75     public void unsetClusterServices(IClusterGlobalServices i) {
76         if (this.clusterServices == i) {
77             this.clusterServices = null;
78         }
79     }
80
81     public void setConnectionService(IConnectionService i) {
82         this.connectionService = i;
83     }
84
85     public void unsetConnectionService(IConnectionService i) {
86         if (this.connectionService == i) {
87             this.connectionService = null;
88         }
89     }
90
91     public void setInventoryService(IInventoryService service) {
92         logger.trace("Got inventory service set request {}", service);
93         this.inventoryService = service;
94     }
95
96     public void unsetInventoryService(IInventoryService service) {
97         logger.trace("Got a service UNset request");
98         this.inventoryService = null;
99     }
100
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()) {
109                 props.add(property);
110             }
111             updateNode(node, UpdateType.ADDED, props);
112         }
113
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()) {
119                 props.add(property);
120             }
121             updateNodeConnector(entry.getKey(), UpdateType.ADDED, props);
122         }
123     }
124
125     public void started() {
126         connectionEventThread = new Thread(new EventHandler(), "ConnectionEvent Thread");
127         connectionEventThread.start();
128
129         registerWithOSGIConsole();
130         notifyClusterViewChanged();
131         // Should pull the Inventory updates in case we missed it
132         getInventories();
133     }
134
135     public void init() {
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);
141         }
142     }
143
144     public void stop() {
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);
152             }
153         }
154     }
155
156     @Override
157     public ConnectionMgmtScheme getActiveScheme() {
158         return activeScheme;
159     }
160
161     @Override
162     public Set<Node> getNodes(InetAddress controller) {
163         AbstractScheme scheme = schemes.get(activeScheme);
164         if (scheme == null) return null;
165         return scheme.getNodes(controller);
166     }
167
168     @Override
169     public Set<Node> getLocalNodes() {
170         AbstractScheme scheme = schemes.get(activeScheme);
171         if (scheme == null) return null;
172         return scheme.getNodes();
173     }
174
175     @Override
176     public boolean isLocal(Node node) {
177         AbstractScheme scheme = schemes.get(activeScheme);
178         if (scheme == null) return false;
179         return scheme.isLocal(node);
180     }
181
182     @Override
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;
187         switch (type) {
188         case ADDED:
189             scheme.addNode(node);
190             break;
191         case REMOVED:
192             scheme.removeNode(node);
193             break;
194         default:
195                 break;
196         }
197     }
198
199     @Override
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;
205         switch (type) {
206         case ADDED:
207             scheme.addNode(nodeConnector.getNode());
208             break;
209         default:
210                 break;
211         }
212     }
213
214     @Override
215     public void coordinatorChanged() {
216         notifyClusterViewChanged();
217     }
218
219     @Override
220     public Node connect(String connectionIdentifier, Map<ConnectionConstants, String> params) {
221         if (connectionService == null) return null;
222         return connectionService.connect(connectionIdentifier, params);
223     }
224
225     @Override
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);
229     }
230
231     @Override
232     public Status disconnect (Node node) {
233         if (connectionService == null) return new Status(StatusCode.NOSERVICE);
234         return connectionService.disconnect(node);
235     }
236
237     @Override
238     public void entryCreated(Node key, String cacheName, boolean originLocal) {
239         if (originLocal) return;
240     }
241
242     /*
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.
245      *
246      */
247     private ConcurrentMap<Node, Set<InetAddress>> existingConnections = new ConcurrentHashMap<Node, Set<InetAddress>>();
248
249     @Override
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);
261                 }
262             }
263         } else {
264             logger.debug("Ignoring the Update for : {} NewControllers : {}", node, newControllers.toString());
265         }
266         existingConnections.put(node, newControllers);
267     }
268
269     @Override
270     public void entryDeleted(Node key, String cacheName, boolean originLocal) {
271         if (originLocal) return;
272         logger.debug("Deleted : {} cache : {}", key, cacheName);
273         notifyNodeDisconnectedEvent(key);
274     }
275
276     private void enqueueConnectionEvent(ConnectionMgmtEvent event) {
277         try {
278             if (!connectionEvents.contains(event)) {
279                 this.connectionEvents.put(event);
280             }
281         } catch (InterruptedException e) {
282             logger.debug("enqueueConnectionEvent caught Interrupt Exception for event {}", event);
283         }
284     }
285
286     private void notifyClusterViewChanged() {
287         ConnectionMgmtEvent event = new ConnectionMgmtEvent(ConnectionMgmtEventType.CLUSTER_VIEW_CHANGED, null);
288         enqueueConnectionEvent(event);
289     }
290
291     private void notifyNodeDisconnectedEvent(Node node) {
292         ConnectionMgmtEvent event = new ConnectionMgmtEvent(ConnectionMgmtEventType.NODE_DISCONNECTED_FROM_MASTER, node);
293         enqueueConnectionEvent(event);
294     }
295
296     /*
297      * this thread monitors the connectionEvent queue for new incoming events from
298      */
299     private class EventHandler implements Runnable {
300         @Override
301         public void run() {
302
303             while (true) {
304                 try {
305                     ConnectionMgmtEvent ev = connectionEvents.take();
306                     ConnectionMgmtEventType eType = ev.getEvent();
307                     switch (eType) {
308                     case NODE_DISCONNECTED_FROM_MASTER:
309                         Node node = (Node)ev.getData();
310                         connectionService.notifyNodeDisconnectFromMaster(node);
311                         break;
312                     case CLUSTER_VIEW_CHANGED:
313                         AbstractScheme scheme = schemes.get(activeScheme);
314                         if (scheme == null) return;
315                         scheme.handleClusterViewChanged();
316                         connectionService.notifyClusterViewChanged();
317                         break;
318                     default:
319                         logger.error("Unknown Connection event {}", eType.ordinal());
320                     }
321                 } catch (InterruptedException e) {
322                     connectionEvents.clear();
323                     return;
324                 }
325             }
326         }
327     }
328
329     private void registerWithOSGIConsole() {
330         BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
331                 .getBundleContext();
332         bundleContext.registerService(CommandProvider.class.getName(), this,
333                 null);
334     }
335
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());
341             return;
342         }
343         ConnectionMgmtScheme scheme = ConnectionMgmtScheme.valueOf(schemeStr);
344         if (scheme == null) {
345             ci.println("Please enter a valid Scheme name");
346             return;
347         }
348         activeScheme = scheme;
349     }
350
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());
357             return;
358         }
359         try {
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());
364             return;
365         } catch (UnknownHostException e) {
366             e.printStackTrace();
367         }
368     }
369
370     @Override
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();
377     }
378 }