2 * Copyright © 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.ovsdb.southbound;
10 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
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;
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;
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;
81 OvsdbConnectionInstance(final ConnectionInfo key, final OvsdbClient client, final TransactionInvoker txInvoker,
82 final InstanceIdentifier<Node> iid) {
83 this.connectionInfo = key;
85 this.txInvoker = txInvoker;
87 this.instanceIdentifier = iid;
91 * Apply the given command to the given events, based on the given bridge state.
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.
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);
106 * Apply the given command to the given modifications, based on the given bridge state.
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.
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);
121 public ListenableFuture<List<OperationResult>> transact(
122 final DatabaseSchema dbSchema, final List<Operation> operations) {
123 return client.transact(dbSchema, operations);
126 public void registerCallbacks(final InstanceIdentifierCodec instanceIdentifierCodec) {
127 if (this.callback == null) {
128 if (this.initialCreateData != null) {
129 this.updateConnectionAttributes(instanceIdentifierCodec);
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);
140 LOG.info("No database {} found on {}", database, connectionInfo);
142 } catch (InterruptedException | ExecutionException e) {
143 LOG.warn("Exception attempting to registerCallbacks {}: ", connectionInfo, e);
148 public void createTransactInvokers() {
149 if (transactInvokers == null) {
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));
156 } catch (InterruptedException | ExecutionException e) {
157 LOG.warn("Exception attempting to createTransactionInvokers {}", connectionInfo, e);
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);
178 monitorRequests.add(new MonitorRequestBuilder<>(tableSchema)
180 .with(new MonitorSelect(true, true, true, true)).build());
183 this.callback.update(monitor(dbSchema, monitorRequests, callback), dbSchema);
185 LOG.warn("No tables for schema {} for database {} for key {}",dbSchema,database,connectionInfo);
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()) {
195 TransactionBuilder transaction = new TransactionBuilder(this.client, entry.getKey());
198 OpenVSwitch ovs = transaction.getTypedRowWrapper(OpenVSwitch.class);
200 List<OpenvswitchExternalIds> externalIds = this.initialCreateData.getOpenvswitchExternalIds();
202 stampInstanceIdentifier(transaction, this.instanceIdentifier.firstIdentifierOf(Node.class),
203 instanceIdentifierCodec);
207 YangUtils.convertYangKeyValueListToMap(externalIds, OpenvswitchExternalIds::getExternalIdKey,
208 OpenvswitchExternalIds::getExternalIdValue));
209 Mutate<GenericTableSchema> mutate = op.mutate(ovs)
210 .addMutation(ovs.getExternalIdsColumn().getSchema(),
212 ovs.getExternalIdsColumn().getData());
213 transaction.add(mutate);
214 } catch (NullPointerException e) {
215 LOG.warn("Incomplete OVSDB Node external IDs", e);
220 List<OpenvswitchOtherConfigs> otherConfigs = this.initialCreateData.getOpenvswitchOtherConfigs();
221 if (otherConfigs != null) {
223 ovs.setOtherConfig(YangUtils.convertYangKeyValueListToMap(otherConfigs,
224 OpenvswitchOtherConfigs::getOtherConfigKey,
225 OpenvswitchOtherConfigs::getOtherConfigValue));
226 transaction.add(op.mutate(ovs).addMutation(ovs.getOtherConfigColumn().getSchema(),
228 ovs.getOtherConfigColumn().getData()));
229 } catch (NullPointerException e) {
230 LOG.warn("Incomplete OVSDB Node other_config", e);
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);
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) {
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);
256 LOG.trace("invoke exit tb: {}", txBuilder);
260 public ListenableFuture<List<String>> getDatabases() {
261 return client.getDatabases();
264 public ListenableFuture<TypedDatabaseSchema> getSchema(final String database) {
265 return client.getSchema(database);
268 public TransactionBuilder transactBuilder(final DatabaseSchema dbSchema) {
269 return client.transactBuilder(dbSchema);
272 public <E extends TableSchema<E>> TableUpdates monitor(
273 final DatabaseSchema schema, final List<MonitorRequest> monitorRequests,
274 final MonitorHandle monitorHandle, final MonitorCallBack callbackArgument) {
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);
284 public void cancelMonitor(final MonitorHandle handler) {
285 client.cancelMonitor(handler);
288 public void lock(final String lockId, final LockAquisitionCallback lockedCallBack,
289 final LockStolenCallback stolenCallback) {
290 client.lock(lockId, lockedCallBack, stolenCallback);
293 public ListenableFuture<Boolean> steal(final String lockId) {
294 return client.steal(lockId);
297 public ListenableFuture<Boolean> unLock(final String lockId) {
298 return client.unLock(lockId);
301 public boolean isActive() {
302 return client.isActive();
305 public void disconnect() {
309 public DatabaseSchema getDatabaseSchema(final String dbName) {
310 return client.getDatabaseSchema(dbName);
313 public <T extends TypedBaseTable<?>> T createTypedRowWrapper(final Class<T> klazz) {
314 return client.createTypedRowWrapper(klazz);
317 public <T extends TypedBaseTable<?>> T createTypedRowWrapper(
318 final DatabaseSchema dbSchema, final Class<T> klazz) {
319 return client.createTypedRowWrapper(dbSchema, klazz);
322 public <T extends TypedBaseTable<?>> T getTypedRowWrapper(final Class<T> klazz,
323 final Row<GenericTableSchema> row) {
324 return client.getTypedRowWrapper(klazz, row);
327 public OvsdbConnectionInfo getConnectionInfo() {
328 return client.getConnectionInfo();
331 public ConnectionInfo getMDConnectionInfo() {
332 return connectionInfo;
335 public void setMDConnectionInfo(final ConnectionInfo key) {
336 this.connectionInfo = key;
339 public InstanceIdentifier<Node> getInstanceIdentifier() {
340 return instanceIdentifier;
343 public NodeKey getNodeKey() {
344 return getInstanceIdentifier().firstKeyOf(Node.class);
347 public NodeId getNodeId() {
348 return getNodeKey().getNodeId();
351 public void setInstanceIdentifier(final InstanceIdentifier<Node> iid) {
352 this.instanceIdentifier = iid;
355 public Entity getConnectedEntity() {
356 return this.connectedEntity;
359 public void setConnectedEntity(final Entity entity) {
360 this.connectedEntity = entity;
363 public Boolean hasOvsdbClient(final OvsdbClient otherClient) {
364 return client.equals(otherClient);
367 public Boolean getHasDeviceOwnership() {
368 return hasDeviceOwnership;
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;
379 public void setDeviceOwnershipCandidateRegistration(
380 @NonNull final EntityOwnershipCandidateRegistration registration) {
381 this.deviceOwnershipCandidateRegistration = registration;
384 public void closeDeviceOwnershipCandidateRegistration() {
385 if (deviceOwnershipCandidateRegistration != null) {
386 this.deviceOwnershipCandidateRegistration.close();
387 setHasDeviceOwnership(Boolean.FALSE);
391 public OvsdbNodeAugmentation getOvsdbNodeAugmentation() {
392 return this.initialCreateData;
395 public void setOvsdbNodeAugmentation(final OvsdbNodeAugmentation ovsdbNodeCreateData) {
396 this.initialCreateData = ovsdbNodeCreateData;
399 public OvsdbClient getOvsdbClient() {