fdf6d2a1dd67bd1af166b7ac8623e98f3797673b
[ovsdb.git] / southbound / southbound-impl / src / main / java / org / opendaylight / ovsdb / southbound / OvsdbConnectionInstance.java
1 /*
2  * Copyright (c) 2015, 2016 Cisco Systems, Inc. and others.  All rights reserved.
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 package org.opendaylight.ovsdb.southbound;
9
10 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
11
12 import com.google.common.collect.Lists;
13 import com.google.common.util.concurrent.ListenableFuture;
14
15 import java.util.Collection;
16 import java.util.Collections;
17 import java.util.HashMap;
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.ExecutionException;
23
24 import javax.annotation.Nonnull;
25
26 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
27 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
28 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
29 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
30 import org.opendaylight.ovsdb.lib.LockAquisitionCallback;
31 import org.opendaylight.ovsdb.lib.LockStolenCallback;
32 import org.opendaylight.ovsdb.lib.MonitorCallBack;
33 import org.opendaylight.ovsdb.lib.MonitorHandle;
34 import org.opendaylight.ovsdb.lib.OvsdbClient;
35 import org.opendaylight.ovsdb.lib.OvsdbConnectionInfo;
36 import org.opendaylight.ovsdb.lib.message.MonitorRequest;
37 import org.opendaylight.ovsdb.lib.message.MonitorRequestBuilder;
38 import org.opendaylight.ovsdb.lib.message.MonitorSelect;
39 import org.opendaylight.ovsdb.lib.message.TableUpdates;
40 import org.opendaylight.ovsdb.lib.notation.Mutator;
41 import org.opendaylight.ovsdb.lib.notation.Row;
42 import org.opendaylight.ovsdb.lib.operations.Mutate;
43 import org.opendaylight.ovsdb.lib.operations.Operation;
44 import org.opendaylight.ovsdb.lib.operations.OperationResult;
45 import org.opendaylight.ovsdb.lib.operations.TransactionBuilder;
46 import org.opendaylight.ovsdb.lib.schema.DatabaseSchema;
47 import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
48 import org.opendaylight.ovsdb.lib.schema.TableSchema;
49 import org.opendaylight.ovsdb.lib.schema.typed.TypedBaseTable;
50 import org.opendaylight.ovsdb.lib.schema.typed.TyperUtils;
51 import org.opendaylight.ovsdb.schema.openvswitch.OpenVSwitch;
52 import org.opendaylight.ovsdb.southbound.ovsdb.transact.BridgeOperationalState;
53 import org.opendaylight.ovsdb.southbound.ovsdb.transact.TransactCommand;
54 import org.opendaylight.ovsdb.southbound.ovsdb.transact.TransactInvoker;
55 import org.opendaylight.ovsdb.southbound.ovsdb.transact.TransactInvokerImpl;
56 import org.opendaylight.ovsdb.southbound.ovsdb.transact.TransactUtils;
57 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvoker;
58 import org.opendaylight.ovsdb.utils.yang.YangUtils;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfo;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.OpenvswitchExternalIds;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.OpenvswitchOtherConfigs;
63 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
64 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
65 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
66 import org.opendaylight.yangtools.yang.binding.DataObject;
67 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70
71 public class OvsdbConnectionInstance {
72     private static final Logger LOG = LoggerFactory.getLogger(OvsdbConnectionInstance.class);
73     private OvsdbClient client;
74     private ConnectionInfo connectionInfo;
75     private TransactionInvoker txInvoker;
76     private Map<DatabaseSchema,TransactInvoker> transactInvokers;
77     private MonitorCallBack callback;
78     private InstanceIdentifier<Node> instanceIdentifier;
79     private volatile boolean hasDeviceOwnership = false;
80     private Entity connectedEntity;
81     private EntityOwnershipCandidateRegistration deviceOwnershipCandidateRegistration;
82     private OvsdbNodeAugmentation initialCreateData = null;
83
84     OvsdbConnectionInstance(ConnectionInfo key, OvsdbClient client, TransactionInvoker txInvoker,
85                             InstanceIdentifier<Node> iid) {
86         this.connectionInfo = key;
87         this.client = client;
88         this.txInvoker = txInvoker;
89         // this.key = key;
90         this.instanceIdentifier = iid;
91     }
92
93     /**
94      * Apply the given command to the given events, based on the given bridge state.
95      *
96      * @param command The command to run.
97      * @param state The current bridge state.
98      * @param events The events to process.
99      * @param instanceIdentifierCodec The instance identifier codec to use.
100      */
101     public void transact(TransactCommand command, BridgeOperationalState state,
102             AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> events,
103             InstanceIdentifierCodec instanceIdentifierCodec) {
104         for (TransactInvoker transactInvoker : transactInvokers.values()) {
105             transactInvoker.invoke(command, state, events, instanceIdentifierCodec);
106         }
107     }
108
109     /**
110      * Apply the given command to the given modifications, based on the given bridge state.
111      *
112      * @param command The command to run.
113      * @param state The current bridge state.
114      * @param modifications The modifications to process.
115      * @param instanceIdentifierCodec The instance identifier codec to use.
116      */
117     public void transact(TransactCommand command, BridgeOperationalState state,
118             Collection<DataTreeModification<Node>> modifications, InstanceIdentifierCodec instanceIdentifierCodec) {
119         for (TransactInvoker transactInvoker : transactInvokers.values()) {
120             transactInvoker.invoke(command, state, modifications, instanceIdentifierCodec);
121         }
122     }
123
124     public ListenableFuture<List<OperationResult>> transact(
125             DatabaseSchema dbSchema, List<Operation> operations) {
126         return client.transact(dbSchema, operations);
127     }
128
129     public void registerCallbacks(InstanceIdentifierCodec instanceIdentifierCodec) {
130         if (this.callback == null) {
131             if (this.initialCreateData != null ) {
132                 this.updateConnectionAttributes(instanceIdentifierCodec);
133             }
134
135             try {
136                 String database = SouthboundConstants.OPEN_V_SWITCH;
137                 DatabaseSchema dbSchema = getSchema(database).get();
138                 if (dbSchema != null) {
139                     LOG.info("Monitoring database: {}", database);
140                     callback = new OvsdbMonitorCallback(instanceIdentifierCodec, this, txInvoker);
141                     monitorTables(database, dbSchema);
142                 } else {
143                     LOG.info("No database {} found on {}", database, connectionInfo);
144                 }
145             } catch (InterruptedException | ExecutionException e) {
146                 LOG.warn("Exception attempting to registerCallbacks {}: ", connectionInfo, e);
147             }
148         }
149     }
150
151     public void createTransactInvokers() {
152         if (transactInvokers == null) {
153             try {
154                 transactInvokers = new HashMap<>();
155                 DatabaseSchema dbSchema = getSchema(SouthboundConstants.OPEN_V_SWITCH).get();
156                 if (dbSchema != null) {
157                     transactInvokers.put(dbSchema, new TransactInvokerImpl(this,dbSchema));
158                 }
159             } catch (InterruptedException | ExecutionException e) {
160                 LOG.warn("Exception attempting to createTransactionInvokers {}", connectionInfo, e);
161             }
162         }
163     }
164
165     private void monitorTables(String database, DatabaseSchema dbSchema) {
166         Set<String> tables = dbSchema.getTables();
167         if (tables != null) {
168             List<MonitorRequest> monitorRequests = Lists.newArrayList();
169             for (String tableName : tables) {
170                 if (!SouthboundConstants.SKIP_OVSDB_TABLE.contains(tableName)) {
171                     LOG.info("Southbound monitoring OVSDB schema table {}", tableName);
172                     GenericTableSchema tableSchema = dbSchema.table(tableName, GenericTableSchema.class);
173                     // We copy the columns so we can clean the set up later
174                     Set<String> columns = new HashSet<>(tableSchema.getColumns());
175                     List<String> skipColumns = SouthboundConstants.SKIP_COLUMN_FROM_TABLE.get(tableName);
176                     if (skipColumns != null) {
177                         LOG.info("Southbound NOT monitoring columns {} in table {}", skipColumns, tableName);
178                         columns.removeAll(skipColumns);
179                     }
180                     monitorRequests.add(new MonitorRequestBuilder<>(tableSchema)
181                             .addColumns(columns)
182                             .with(new MonitorSelect(true, true, true, true)).build());
183                 }
184             }
185             this.callback.update(monitor(dbSchema, monitorRequests, callback), dbSchema);
186         } else {
187             LOG.warn("No tables for schema {} for database {} for key {}",dbSchema,database,connectionInfo);
188         }
189     }
190
191     private void updateConnectionAttributes(InstanceIdentifierCodec instanceIdentifierCodec) {
192         LOG.debug("Update attributes of ovsdb node ip: {} port: {}",
193                     this.initialCreateData.getConnectionInfo().getRemoteIp(),
194                     this.initialCreateData.getConnectionInfo().getRemotePort());
195         for ( Map.Entry<DatabaseSchema,TransactInvoker> entry: transactInvokers.entrySet()) {
196
197             TransactionBuilder transaction = new TransactionBuilder(this.client, entry.getKey());
198
199             // OpenVSwitchPart
200             OpenVSwitch ovs = TyperUtils.getTypedRowWrapper(transaction.getDatabaseSchema(), OpenVSwitch.class);
201
202             List<OpenvswitchExternalIds> externalIds = this.initialCreateData.getOpenvswitchExternalIds();
203
204             stampInstanceIdentifier(transaction, this.instanceIdentifier.firstIdentifierOf(Node.class),
205                     instanceIdentifierCodec);
206
207             try {
208                 ovs.setExternalIds(
209                         YangUtils.convertYangKeyValueListToMap(externalIds, OpenvswitchExternalIds::getExternalIdKey,
210                                 OpenvswitchExternalIds::getExternalIdValue));
211                 Mutate<GenericTableSchema> mutate = op.mutate(ovs)
212                             .addMutation(ovs.getExternalIdsColumn().getSchema(),
213                                 Mutator.INSERT,
214                                 ovs.getExternalIdsColumn().getData());
215                 transaction.add(mutate);
216             } catch (NullPointerException e) {
217                 LOG.warn("Incomplete OVSDB Node external IDs", e);
218             }
219
220
221
222             List<OpenvswitchOtherConfigs> otherConfigs = this.initialCreateData.getOpenvswitchOtherConfigs();
223             if (otherConfigs != null) {
224                 try {
225                     ovs.setOtherConfig(YangUtils.convertYangKeyValueListToMap(otherConfigs,
226                             OpenvswitchOtherConfigs::getOtherConfigKey,
227                             OpenvswitchOtherConfigs::getOtherConfigValue));
228                     transaction.add(op.mutate(ovs).addMutation(ovs.getOtherConfigColumn().getSchema(),
229                         Mutator.INSERT,
230                         ovs.getOtherConfigColumn().getData()));
231                 } catch (NullPointerException e) {
232                     LOG.warn("Incomplete OVSDB Node other_config", e);
233                 }
234             }
235
236             invoke(transaction);
237         }
238     }
239
240     private void stampInstanceIdentifier(TransactionBuilder transaction,InstanceIdentifier<Node> iid,
241             InstanceIdentifierCodec instanceIdentifierCodec) {
242         OpenVSwitch ovs = TyperUtils.getTypedRowWrapper(transaction.getDatabaseSchema(), OpenVSwitch.class);
243         ovs.setExternalIds(Collections.<String,String>emptyMap());
244         TransactUtils.stampInstanceIdentifier(transaction, iid, ovs.getSchema(), ovs.getExternalIdsColumn().getSchema(),
245                 instanceIdentifierCodec);
246     }
247
248     private void invoke(TransactionBuilder txBuilder) {
249         ListenableFuture<List<OperationResult>> result = txBuilder.execute();
250         LOG.debug("invoke: tb: {}", txBuilder);
251         if (txBuilder.getOperations().size() > 0) {
252             try {
253                 List<OperationResult> got = result.get();
254                 LOG.debug("OVSDB transaction result: {}", got);
255             } catch (InterruptedException | ExecutionException e) {
256                 LOG.warn("Transact execution exception: ", e);
257             }
258             LOG.trace("invoke exit tb: {}", txBuilder);
259         }
260     }
261
262
263     public ListenableFuture<List<String>> getDatabases() {
264         return client.getDatabases();
265     }
266
267     public ListenableFuture<DatabaseSchema> getSchema(String database) {
268         return client.getSchema(database);
269     }
270
271     public TransactionBuilder transactBuilder(DatabaseSchema dbSchema) {
272         return client.transactBuilder(dbSchema);
273     }
274
275     public <E extends TableSchema<E>> TableUpdates monitor(
276             DatabaseSchema schema, List<MonitorRequest> monitorRequests,
277             MonitorHandle monitorHandle, MonitorCallBack callbackArgument) {
278         return null;
279     }
280
281     public <E extends TableSchema<E>> TableUpdates monitor(
282             DatabaseSchema schema, List<MonitorRequest> monitorRequests,
283             MonitorCallBack callbackArgument) {
284         return client.monitor(schema, monitorRequests, callbackArgument);
285     }
286
287     public void cancelMonitor(MonitorHandle handler) {
288         client.cancelMonitor(handler);
289     }
290
291     public void lock(String lockId, LockAquisitionCallback lockedCallBack,
292             LockStolenCallback stolenCallback) {
293         client.lock(lockId, lockedCallBack, stolenCallback);
294     }
295
296     public ListenableFuture<Boolean> steal(String lockId) {
297         return client.steal(lockId);
298     }
299
300     public ListenableFuture<Boolean> unLock(String lockId) {
301         return client.unLock(lockId);
302     }
303
304     public boolean isActive() {
305         return client.isActive();
306     }
307
308     public void disconnect() {
309         client.disconnect();
310     }
311
312     public DatabaseSchema getDatabaseSchema(String dbName) {
313         return client.getDatabaseSchema(dbName);
314     }
315
316     public <T extends TypedBaseTable<?>> T createTypedRowWrapper(Class<T> klazz) {
317         return client.createTypedRowWrapper(klazz);
318     }
319
320     public <T extends TypedBaseTable<?>> T createTypedRowWrapper(
321             DatabaseSchema dbSchema, Class<T> klazz) {
322         return client.createTypedRowWrapper(dbSchema, klazz);
323     }
324
325     public <T extends TypedBaseTable<?>> T getTypedRowWrapper(Class<T> klazz,
326             Row<GenericTableSchema> row) {
327         return client.getTypedRowWrapper(klazz, row);
328     }
329
330     public OvsdbConnectionInfo getConnectionInfo() {
331         return client.getConnectionInfo();
332     }
333
334     public ConnectionInfo getMDConnectionInfo() {
335         return connectionInfo;
336     }
337
338     public void setMDConnectionInfo(ConnectionInfo key) {
339         this.connectionInfo = key;
340     }
341
342     public InstanceIdentifier<Node> getInstanceIdentifier() {
343         return instanceIdentifier;
344     }
345
346     public NodeKey getNodeKey() {
347         return getInstanceIdentifier().firstKeyOf(Node.class);
348     }
349
350     public NodeId getNodeId() {
351         return getNodeKey().getNodeId();
352     }
353
354     public void setInstanceIdentifier(InstanceIdentifier<Node> iid) {
355         this.instanceIdentifier = iid;
356     }
357
358     public Entity getConnectedEntity() {
359         return this.connectedEntity;
360     }
361
362     public void setConnectedEntity(Entity entity ) {
363         this.connectedEntity = entity;
364     }
365
366     public Boolean hasOvsdbClient(OvsdbClient otherClient) {
367         return client.equals(otherClient);
368     }
369
370     public Boolean getHasDeviceOwnership() {
371         return hasDeviceOwnership;
372     }
373
374     public void setHasDeviceOwnership(Boolean hasDeviceOwnership) {
375         if (hasDeviceOwnership != null) {
376             this.hasDeviceOwnership = hasDeviceOwnership;
377         }
378     }
379
380     public void setDeviceOwnershipCandidateRegistration(@Nonnull EntityOwnershipCandidateRegistration registration) {
381         this.deviceOwnershipCandidateRegistration = registration;
382     }
383
384     public void closeDeviceOwnershipCandidateRegistration() {
385         if (deviceOwnershipCandidateRegistration != null) {
386             this.deviceOwnershipCandidateRegistration.close();
387             setHasDeviceOwnership(Boolean.FALSE);
388         }
389     }
390
391     public OvsdbNodeAugmentation getOvsdbNodeAugmentation() {
392         return this.initialCreateData;
393     }
394
395     public void setOvsdbNodeAugmentation(OvsdbNodeAugmentation ovsdbNodeCreateData) {
396         this.initialCreateData = ovsdbNodeCreateData;
397     }
398
399     public OvsdbClient getOvsdbClient() {
400         return client;
401     }
402 }