288bc6581804c54e7ad86ea5c0c8328cf32cc4af
[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.HashSet;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Set;
22 import java.util.concurrent.ConcurrentHashMap;
23 import java.util.concurrent.ConcurrentMap;
24 import java.util.concurrent.ExecutionException;
25
26 import org.opendaylight.controller.sal.core.Node;
27 import org.opendaylight.controller.sal.core.Property;
28 import org.opendaylight.ovsdb.lib.MonitorCallBack;
29 import org.opendaylight.ovsdb.lib.OvsdbClient;
30 import org.opendaylight.ovsdb.lib.OvsdbConnection;
31 import org.opendaylight.ovsdb.lib.OvsdbConnectionInfo;
32 import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
33 import org.opendaylight.ovsdb.lib.message.MonitorRequest;
34 import org.opendaylight.ovsdb.lib.message.MonitorRequestBuilder;
35 import org.opendaylight.ovsdb.lib.message.MonitorSelect;
36 import org.opendaylight.ovsdb.lib.message.TableUpdates;
37 import org.opendaylight.ovsdb.lib.schema.DatabaseSchema;
38 import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
39 import org.opendaylight.ovsdb.lib.schema.TableSchema;
40 import org.opendaylight.ovsdb.plugin.api.Connection;
41 import org.opendaylight.ovsdb.plugin.api.ConnectionConstants;
42 import org.opendaylight.ovsdb.plugin.api.Status;
43 import org.opendaylight.ovsdb.plugin.api.StatusCode;
44 import org.opendaylight.ovsdb.plugin.internal.IPAddressProperty;
45 import org.opendaylight.ovsdb.plugin.internal.L4PortProperty;
46 import org.opendaylight.ovsdb.plugin.api.OvsdbConnectionService;
47 import org.opendaylight.ovsdb.plugin.api.OvsdbInventoryService;
48 import org.opendaylight.ovsdb.utils.config.ConfigProperties;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 import com.google.common.collect.Lists;
53
54
55 /**
56  * Represents the openflow plugin component in charge of programming the flows
57  * the flow programming and relay them to functional modules above SAL.
58  */
59 public class ConnectionServiceImpl implements OvsdbConnectionService,
60                                               OvsdbConnectionListener {
61     protected static final Logger logger = LoggerFactory.getLogger(ConnectionServiceImpl.class);
62
63     // Properties that can be set in config.ini
64     private static final Integer DEFAULT_OVSDB_PORT = 6640;
65     private static final String OVSDB_LISTENPORT = "ovsdb.listenPort";
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         String identifier = (String) node.getID();
130         Connection connection = ovsdbConnections.get(identifier);
131         if (connection != null) {
132             ovsdbConnections.remove(identifier);
133             connection.disconnect();
134             ovsdbInventoryService.removeNode(node);
135             return new Status(StatusCode.SUCCESS);
136         } else {
137             return new Status(StatusCode.NOTFOUND);
138         }
139     }
140
141     public Node connect(String identifier, Map<ConnectionConstants, String> params) {
142         InetAddress address;
143         Integer port;
144
145         try {
146             address = InetAddress.getByName(params.get(ConnectionConstants.ADDRESS));
147         } catch (Exception e) {
148             logger.error("Unable to resolve " + params.get(ConnectionConstants.ADDRESS), e);
149             return null;
150         }
151
152         try {
153             port = Integer.parseInt(params.get(ConnectionConstants.PORT));
154             if (port == 0) port = DEFAULT_OVSDB_PORT;
155         } catch (Exception e) {
156             port = DEFAULT_OVSDB_PORT;
157         }
158
159         try {
160             OvsdbClient client = connectionLib.connect(address, port);
161             return handleNewConnection(identifier, client);
162         } catch (InterruptedException e) {
163             logger.error("Thread was interrupted during connect", e);
164         } catch (ExecutionException e) {
165             logger.error("ExecutionException in handleNewConnection for identifier " + identifier, e);
166         }
167         return null;
168     }
169
170     public List<ChannelHandler> getHandlers() {
171         return handlers;
172     }
173
174     public void setHandlers(List<ChannelHandler> handlers) {
175         this.handlers = handlers;
176     }
177
178     @Override
179     public Connection getConnection(Node node) {
180         String identifier = (String) node.getID();
181         return ovsdbConnections.get(identifier);
182     }
183
184     @Override
185     public Node getNode (String identifier) {
186         String id = identifier;
187
188         String[] pair = identifier.split("[|,:]+");
189         if (pair[0].equals("OVS")) {
190             id = pair[1];
191         }
192
193         Connection connection = ovsdbConnections.get(id);
194         if (connection != null) {
195             return connection.getNode();
196         } else {
197             return null;
198         }
199     }
200
201     @Override
202     public List<Node> getNodes() {
203         List<Node> nodes = new ArrayList<Node>();
204         for (Connection connection : ovsdbConnections.values()) {
205             nodes.add(connection.getNode());
206         }
207         return nodes;
208     }
209
210     private Node handleNewConnection(String identifier, OvsdbClient client) throws InterruptedException, ExecutionException {
211         Connection connection = new Connection(identifier, client);
212         Node node = connection.getNode();
213         ovsdbConnections.put(identifier, connection);
214         List<String> dbs = client.getDatabases().get();
215         for (String db : dbs) {
216             client.getSchema(db).get();
217         }
218         // Keeping the Initial inventory update(s) on its own thread.
219         new Thread() {
220             Connection connection;
221             String identifier;
222
223             @Override
224             public void run() {
225                 try {
226                     logger.info("Initialize inventory for {}", connection.toString());
227                     initializeInventoryForNewNode(connection);
228                 } catch (InterruptedException | ExecutionException | IOException e) {
229                     logger.error("Failed to initialize inventory for node with identifier " + identifier, e);
230                     ovsdbConnections.remove(identifier);
231                 }
232             }
233             public Thread initializeConnectionParams(String identifier, Connection connection) {
234                 this.identifier = identifier;
235                 this.connection = connection;
236                 return this;
237             }
238         }.initializeConnectionParams(identifier, connection).start();
239         return node;
240     }
241
242     public void channelClosed(Node node) throws Exception {
243         logger.info("Connection to Node : {} closed", node);
244         disconnect(node);
245         ovsdbInventoryService.removeNode(node);
246     }
247
248     private void initializeInventoryForNewNode (Connection connection) throws InterruptedException, ExecutionException, IOException {
249         OvsdbClient client = connection.getClient();
250         InetAddress address = client.getConnectionInfo().getRemoteAddress();
251         int port = client.getConnectionInfo().getRemotePort();
252         IPAddressProperty addressProp = new IPAddressProperty(address);
253         L4PortProperty l4Port = new L4PortProperty(port);
254         Set<Property> props = new HashSet<Property>();
255         props.add(addressProp);
256         props.add(l4Port);
257         logger.info("Add node to ovsdb inventory service {}", connection.getNode().toString());
258         ovsdbInventoryService.addNode(connection.getNode(), props);
259
260         List<String> databases = client.getDatabases().get();
261         if (databases == null) {
262             logger.error("Unable to get Databases for the ovsdb connection : {}", client.getConnectionInfo());
263             return;
264         }
265         for (String database : databases) {
266             DatabaseSchema dbSchema = client.getSchema(database).get();
267             TableUpdates updates = this.monitorTables(connection.getNode(), dbSchema);
268             ovsdbInventoryService.processTableUpdates(connection.getNode(), dbSchema.getName(), updates);
269         }
270         logger.info("Notifying Inventory Listeners for Node Added: {}", connection.getNode().toString());
271         ovsdbInventoryService.notifyNodeAdded(connection.getNode(), address, port);
272     }
273
274     public TableUpdates monitorTables(Node node, DatabaseSchema dbSchema) throws ExecutionException, InterruptedException, IOException {
275         String identifier = (String) node.getID();
276         Connection connection = ovsdbConnections.get(identifier);
277         OvsdbClient client = connection.getClient();
278         if (dbSchema == null) {
279             logger.error("Unable to get Database Schema for the ovsdb connection : {}", client.getConnectionInfo());
280             return null;
281         }
282         Set<String> tables = dbSchema.getTables();
283         if (tables == null) {
284             logger.warn("Database {} without any tables. Strange !", dbSchema.getName());
285             return null;
286         }
287         List<MonitorRequest<GenericTableSchema>> monitorRequests = Lists.newArrayList();
288         for (String tableName : tables) {
289             GenericTableSchema tableSchema = dbSchema.table(tableName, GenericTableSchema.class);
290             monitorRequests.add(this.getAllColumnsMonitorRequest(tableSchema));
291         }
292         return client.monitor(dbSchema, monitorRequests, new UpdateMonitor(node));
293     }
294
295     /**
296      * As per RFC 7047, section 4.1.5, if a Monitor request is sent without any columns, the update response will not include
297      * the _uuid column.
298      * ----------------------------------------------------------------------------------------------------------------------------------
299      * Each <monitor-request> specifies one or more columns and the manner in which the columns (or the entire table) are to be monitored.
300      * The "columns" member specifies the columns whose values are monitored. It MUST NOT contain duplicates.
301      * If "columns" is omitted, all columns in the table, except for "_uuid", are monitored.
302      * ----------------------------------------------------------------------------------------------------------------------------------
303      * In order to overcome this limitation, this method
304      *
305      * @return MonitorRequest that includes all the Bridge Columns including _uuid
306      */
307     public <T extends TableSchema<T>> MonitorRequest<T> getAllColumnsMonitorRequest (T tableSchema) {
308         Set<String> columns = tableSchema.getColumns();
309         MonitorRequestBuilder<T> monitorBuilder = MonitorRequestBuilder.builder(tableSchema);
310         for (String column : columns) {
311             monitorBuilder.addColumn(column);
312         }
313         return monitorBuilder.with(new MonitorSelect(true, true, true, true)).build();
314     }
315
316     private class UpdateMonitor implements MonitorCallBack {
317         Node node = null;
318         public UpdateMonitor(Node node) {
319             this.node = node;
320         }
321
322         @Override
323         public void update(TableUpdates result, DatabaseSchema dbSchema) {
324             ovsdbInventoryService.processTableUpdates(node, dbSchema.getName(), result);
325         }
326
327         @Override
328         public void exception(Throwable t) {
329             System.out.println("Exception t = " + t);
330         }
331     }
332
333     private String getConnectionIdentifier(OvsdbClient client) {
334         OvsdbConnectionInfo info = client.getConnectionInfo();
335         return info.getRemoteAddress().getHostAddress()+":"+info.getRemotePort();
336     }
337
338
339     @Override
340     public void connected(OvsdbClient client) {
341         String identifier = getConnectionIdentifier(client);
342         try {
343             this.handleNewConnection(identifier, client);
344         } catch (InterruptedException | ExecutionException e) {
345             e.printStackTrace();
346         }
347     }
348
349     @Override
350     public void disconnected(OvsdbClient client) {
351         Connection connection = ovsdbConnections.get(this.getConnectionIdentifier(client));
352         if (connection == null) return;
353         this.disconnect(connection.getNode());
354     }
355 }