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