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