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