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