Sonar clean-up: braces for control statements
[netvirt.git] / plugin / src / main / java / org / opendaylight / ovsdb / plugin / impl / ConnectionServiceImpl.java
1 /*
2  * Copyright (C) 2013 Red Hat, Inc.
3  *
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
7  *
8  * Authors : Madhu Venugopal, Brent Salisbury, Evan Zeller
9  */
10 package org.opendaylight.ovsdb.plugin.impl;
11
12 import io.netty.channel.ChannelHandler;
13
14 import java.io.IOException;
15 import java.net.InetAddress;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Set;
21 import java.util.concurrent.ConcurrentHashMap;
22 import java.util.concurrent.ConcurrentMap;
23 import java.util.concurrent.ExecutionException;
24
25 import org.opendaylight.ovsdb.lib.MonitorCallBack;
26 import org.opendaylight.ovsdb.lib.OvsdbClient;
27 import org.opendaylight.ovsdb.lib.OvsdbConnection;
28 import org.opendaylight.ovsdb.lib.OvsdbConnectionInfo;
29 import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
30 import org.opendaylight.ovsdb.lib.message.MonitorRequest;
31 import org.opendaylight.ovsdb.lib.message.MonitorRequestBuilder;
32 import org.opendaylight.ovsdb.lib.message.MonitorSelect;
33 import org.opendaylight.ovsdb.lib.message.TableUpdates;
34 import org.opendaylight.ovsdb.lib.schema.DatabaseSchema;
35 import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
36 import org.opendaylight.ovsdb.lib.schema.TableSchema;
37 import org.opendaylight.ovsdb.plugin.api.Connection;
38 import org.opendaylight.ovsdb.plugin.api.ConnectionConstants;
39 import org.opendaylight.ovsdb.plugin.api.Status;
40 import org.opendaylight.ovsdb.plugin.api.StatusCode;
41 import org.opendaylight.ovsdb.plugin.api.OvsdbConnectionService;
42 import org.opendaylight.ovsdb.plugin.api.OvsdbInventoryService;
43 import org.opendaylight.ovsdb.utils.config.ConfigProperties;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 import com.google.common.collect.Lists;
49
50
51 /**
52  * Represents the openflow plugin component in charge of programming the flows
53  * the flow programming and relay them to functional modules above SAL.
54  */
55 public class ConnectionServiceImpl implements OvsdbConnectionService,
56                                               OvsdbConnectionListener {
57     protected static final Logger logger = LoggerFactory.getLogger(ConnectionServiceImpl.class);
58
59     // Properties that can be set in config.ini
60     private static final Integer DEFAULT_OVSDB_PORT = 6640;
61     private static final String OVSDB_LISTENPORT = "ovsdb.listenPort";
62
63
64     public void putOvsdbConnection (String identifier, Connection connection) {
65         ovsdbConnections.put(identifier, connection);
66     }
67
68     private ConcurrentMap<String, Connection> ovsdbConnections = new ConcurrentHashMap<String, Connection>();
69     private List<ChannelHandler> handlers = null;
70
71     private volatile OvsdbInventoryService ovsdbInventoryService;
72     private volatile OvsdbConnection connectionLib;
73
74     public void setOvsdbInventoryService(OvsdbInventoryService inventoryService) {
75         this.ovsdbInventoryService = inventoryService;
76     }
77
78     public void setOvsdbConnection(OvsdbConnection ovsdbConnection) {
79         this.connectionLib = ovsdbConnection;
80     }
81
82     public void init() {
83     }
84
85     /**
86      * Function called by the dependency manager when at least one dependency
87      * become unsatisfied or when the component is shutting down because for
88      * example bundle is being stopped.
89      */
90     void destroy() {
91     }
92
93     /**
94      * Function called by dependency manager after "init ()" is called and after
95      * the services provided by the class are registered in the service registry
96      */
97     void start() {
98         /* Start ovsdb server before getting connection clients */
99         String portString = ConfigProperties.getProperty(OvsdbConnectionService.class, OVSDB_LISTENPORT);
100         int ovsdbListenPort = DEFAULT_OVSDB_PORT;
101         if (portString != null) {
102             ovsdbListenPort = Integer.decode(portString).intValue();
103         }
104
105         if (!connectionLib.startOvsdbManager(ovsdbListenPort)) {
106             logger.warn("Start OVSDB manager call from ConnectionService was not necessary");
107         }
108
109         /* Then get connection clients */
110         Collection<OvsdbClient> connections = connectionLib.getConnections();
111         for (OvsdbClient client : connections) {
112             logger.info("CONNECT start connected clients client = {}", client);
113             this.connected(client);
114         }
115     }
116
117     /**
118      * Function called by the dependency manager before the services exported by
119      * the component are unregistered, this will be followed by a "destroy ()"
120      * calls
121      */
122     void stopping() {
123         for (Connection connection : ovsdbConnections.values()) {
124             connection.disconnect();
125         }
126     }
127
128     public Status disconnect(Node node) {
129         Connection connection = getConnection(node);
130         if (connection != null) {
131             ovsdbConnections.remove(normalizeId(node.getId().getValue()));
132             connection.disconnect();
133             ovsdbInventoryService.removeNode(node);
134             return new Status(StatusCode.SUCCESS);
135         } else {
136             return new Status(StatusCode.NOTFOUND);
137         }
138     }
139
140     public Node connect(String identifier, Map<ConnectionConstants, String> params) {
141         InetAddress address;
142         Integer port;
143
144         try {
145             address = InetAddress.getByName(params.get(ConnectionConstants.ADDRESS));
146         } catch (Exception e) {
147             logger.error("Unable to resolve " + params.get(ConnectionConstants.ADDRESS), e);
148             return null;
149         }
150
151         try {
152             port = Integer.parseInt(params.get(ConnectionConstants.PORT));
153             if (port == 0) {
154                 port = DEFAULT_OVSDB_PORT;
155             }
156         } catch (Exception e) {
157             port = DEFAULT_OVSDB_PORT;
158         }
159
160         try {
161             OvsdbClient client = connectionLib.connect(address, port);
162             return handleNewConnection(identifier, client);
163         } catch (InterruptedException e) {
164             logger.error("Thread was interrupted during connect", e);
165         } catch (ExecutionException e) {
166             logger.error("ExecutionException in handleNewConnection for identifier " + identifier, e);
167         }
168         return null;
169     }
170
171     public List<ChannelHandler> getHandlers() {
172         return handlers;
173     }
174
175     public void setHandlers(List<ChannelHandler> handlers) {
176         this.handlers = handlers;
177     }
178
179     private String normalizeId (String identifier) {
180         String id = identifier;
181
182         String[] pair = identifier.split("\\|");
183         if (pair[0].equals("OVS")) {
184             id = pair[1];
185         }
186
187         return id;
188     }
189
190     @Override
191     public Connection getConnection(Node node) {
192         return ovsdbConnections.get(normalizeId(node.getId().getValue()));
193     }
194
195     @Override
196     public Node getNode (String identifier) {
197         Connection connection = ovsdbConnections.get(normalizeId(identifier));
198         if (connection != null) {
199             return connection.getNode();
200         } else {
201             return null;
202         }
203     }
204
205     @Override
206     public List<Node> getNodes() {
207         List<Node> nodes = new ArrayList<Node>();
208         for (Connection connection : ovsdbConnections.values()) {
209             nodes.add(connection.getNode());
210         }
211         return nodes;
212     }
213
214     private Node handleNewConnection(String identifier, OvsdbClient client) throws InterruptedException, ExecutionException {
215         Connection connection = new Connection(identifier, client);
216         Node node = connection.getNode();
217         ovsdbConnections.put(identifier, connection);
218         List<String> dbs = client.getDatabases().get();
219         for (String db : dbs) {
220             client.getSchema(db).get();
221         }
222         // Keeping the Initial inventory update(s) on its own thread.
223         new Thread() {
224             Connection connection;
225             String identifier;
226
227             @Override
228             public void run() {
229                 try {
230                     logger.info("Initialize inventory for {}", connection.toString());
231                     initializeInventoryForNewNode(connection);
232                 } catch (InterruptedException | ExecutionException | IOException e) {
233                     logger.error("Failed to initialize inventory for node with identifier " + identifier, e);
234                     ovsdbConnections.remove(identifier);
235                 }
236             }
237             public Thread initializeConnectionParams(String identifier, Connection connection) {
238                 this.identifier = identifier;
239                 this.connection = connection;
240                 return this;
241             }
242         }.initializeConnectionParams(identifier, connection).start();
243         return node;
244     }
245
246     public void channelClosed(Node node) throws Exception {
247         logger.info("Connection to Node : {} closed", node);
248         disconnect(node);
249         ovsdbInventoryService.removeNode(node);
250     }
251
252     private void initializeInventoryForNewNode (Connection connection) throws InterruptedException, ExecutionException, IOException {
253         OvsdbClient client = connection.getClient();
254         InetAddress address = client.getConnectionInfo().getRemoteAddress();
255         int port = client.getConnectionInfo().getRemotePort();
256
257         List<String> databases = client.getDatabases().get();
258         if (databases == null) {
259             logger.error("Unable to get Databases for the ovsdb connection : {}", client.getConnectionInfo());
260             return;
261         }
262         for (String database : databases) {
263             DatabaseSchema dbSchema = client.getSchema(database).get();
264             TableUpdates updates = this.monitorTables(connection.getNode(), dbSchema);
265             ovsdbInventoryService.processTableUpdates(connection.getNode(), dbSchema.getName(), updates);
266         }
267         logger.info("Notifying Inventory Listeners for Node Added: {}", connection.getNode().toString());
268         ovsdbInventoryService.notifyNodeAdded(connection.getNode(), address, port);
269     }
270
271     public TableUpdates monitorTables(Node node, DatabaseSchema dbSchema) throws ExecutionException, InterruptedException, IOException {
272         Connection connection = getConnection(node);
273         OvsdbClient client = connection.getClient();
274         if (dbSchema == null) {
275             logger.error("Unable to get Database Schema for the ovsdb connection : {}", client.getConnectionInfo());
276             return null;
277         }
278         Set<String> tables = dbSchema.getTables();
279         if (tables == null) {
280             logger.warn("Database {} without any tables. Strange !", dbSchema.getName());
281             return null;
282         }
283         List<MonitorRequest<GenericTableSchema>> monitorRequests = Lists.newArrayList();
284         for (String tableName : tables) {
285             GenericTableSchema tableSchema = dbSchema.table(tableName, GenericTableSchema.class);
286             monitorRequests.add(this.getAllColumnsMonitorRequest(tableSchema));
287         }
288         return client.monitor(dbSchema, monitorRequests, new UpdateMonitor(node));
289     }
290
291     /**
292      * As per RFC 7047, section 4.1.5, if a Monitor request is sent without any columns, the update response will not include
293      * the _uuid column.
294      * ----------------------------------------------------------------------------------------------------------------------------------
295      * Each &lt;monitor-request&gt; specifies one or more columns and the manner in which the columns (or the entire table) are to be monitored.
296      * The "columns" member specifies the columns whose values are monitored. It MUST NOT contain duplicates.
297      * If "columns" is omitted, all columns in the table, except for "_uuid", are monitored.
298      * ----------------------------------------------------------------------------------------------------------------------------------
299      * In order to overcome this limitation, this method
300      *
301      * @return MonitorRequest that includes all the Bridge Columns including _uuid
302      */
303     public <T extends TableSchema<T>> MonitorRequest<T> getAllColumnsMonitorRequest (T tableSchema) {
304         Set<String> columns = tableSchema.getColumns();
305         MonitorRequestBuilder<T> monitorBuilder = MonitorRequestBuilder.builder(tableSchema);
306         for (String column : columns) {
307             monitorBuilder.addColumn(column);
308         }
309         return monitorBuilder.with(new MonitorSelect(true, true, true, true)).build();
310     }
311
312     private class UpdateMonitor implements MonitorCallBack {
313         Node node = null;
314         public UpdateMonitor(Node node) {
315             this.node = node;
316         }
317
318         @Override
319         public void update(TableUpdates result, DatabaseSchema dbSchema) {
320             ovsdbInventoryService.processTableUpdates(node, dbSchema.getName(), result);
321         }
322
323         @Override
324         public void exception(Throwable t) {
325             System.out.println("Exception t = " + t);
326         }
327     }
328
329     private String getConnectionIdentifier(OvsdbClient client) {
330         OvsdbConnectionInfo info = client.getConnectionInfo();
331         return info.getRemoteAddress().getHostAddress()+":"+info.getRemotePort();
332     }
333
334
335     @Override
336     public void connected(OvsdbClient client) {
337         String identifier = getConnectionIdentifier(client);
338         try {
339             this.handleNewConnection(identifier, client);
340         } catch (InterruptedException | ExecutionException e) {
341             e.printStackTrace();
342         }
343     }
344
345     @Override
346     public void disconnected(OvsdbClient client) {
347         Connection connection = ovsdbConnections.get(this.getConnectionIdentifier(client));
348         if (connection == null) {
349             return;
350         }
351         this.disconnect(connection.getNode());
352     }
353 }