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