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.lib.schema.typed.TyperUtils;
49 import org.opendaylight.ovsdb.schema.openvswitch.OpenVSwitch;
50 import org.opendaylight.ovsdb.southbound.ovsdb.transact.BridgeOperationalState;
51 import org.opendaylight.ovsdb.southbound.ovsdb.transact.DataChangeEvent;
52 import org.opendaylight.ovsdb.southbound.ovsdb.transact.TransactCommand;
53 import org.opendaylight.ovsdb.southbound.ovsdb.transact.TransactInvoker;
54 import org.opendaylight.ovsdb.southbound.ovsdb.transact.TransactInvokerImpl;
55 import org.opendaylight.ovsdb.southbound.ovsdb.transact.TransactUtils;
56 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvoker;
57 import org.opendaylight.ovsdb.utils.yang.YangUtils;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfo;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.OpenvswitchExternalIds;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.OpenvswitchOtherConfigs;
62 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
63 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
64 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
65 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
69 public class OvsdbConnectionInstance {
70 private static final Logger LOG = LoggerFactory.getLogger(OvsdbConnectionInstance.class);
71 private final OvsdbClient client;
72 private ConnectionInfo connectionInfo;
73 private final TransactionInvoker txInvoker;
74 private Map<TypedDatabaseSchema, TransactInvoker> transactInvokers;
75 private MonitorCallBack callback;
76 private InstanceIdentifier<Node> instanceIdentifier;
77 private volatile boolean hasDeviceOwnership = false;
78 private Entity connectedEntity;
79 private EntityOwnershipCandidateRegistration deviceOwnershipCandidateRegistration;
80 private OvsdbNodeAugmentation initialCreateData = null;
82 OvsdbConnectionInstance(final ConnectionInfo key, final OvsdbClient client, final TransactionInvoker txInvoker,
83 final InstanceIdentifier<Node> iid) {
84 this.connectionInfo = key;
86 this.txInvoker = txInvoker;
88 this.instanceIdentifier = iid;
92 * Apply the given command to the given events, based on the given bridge state.
94 * @param command The command to run.
95 * @param state The current bridge state.
96 * @param events The events to process.
97 * @param instanceIdentifierCodec The instance identifier codec to use.
99 public void transact(final TransactCommand command, final BridgeOperationalState state,
100 final DataChangeEvent events, final InstanceIdentifierCodec instanceIdentifierCodec) {
101 for (TransactInvoker transactInvoker : transactInvokers.values()) {
102 transactInvoker.invoke(command, state, events, instanceIdentifierCodec);
107 * Apply the given command to the given modifications, based on the given bridge state.
109 * @param command The command to run.
110 * @param state The current bridge state.
111 * @param modifications The modifications to process.
112 * @param instanceIdentifierCodec The instance identifier codec to use.
114 public void transact(final TransactCommand command, final BridgeOperationalState state,
115 final Collection<DataTreeModification<Node>> modifications,
116 final InstanceIdentifierCodec instanceIdentifierCodec) {
117 for (TransactInvoker transactInvoker : transactInvokers.values()) {
118 transactInvoker.invoke(command, state, modifications, instanceIdentifierCodec);
122 public ListenableFuture<List<OperationResult>> transact(
123 final DatabaseSchema dbSchema, final List<Operation> operations) {
124 return client.transact(dbSchema, operations);
127 public void registerCallbacks(final InstanceIdentifierCodec instanceIdentifierCodec) {
128 if (this.callback == null) {
129 if (this.initialCreateData != null) {
130 this.updateConnectionAttributes(instanceIdentifierCodec);
134 String database = SouthboundConstants.OPEN_V_SWITCH;
135 DatabaseSchema dbSchema = getSchema(database).get();
136 if (dbSchema != null) {
137 LOG.info("Monitoring database: {}", database);
138 callback = new OvsdbMonitorCallback(instanceIdentifierCodec, this, txInvoker);
139 monitorTables(database, dbSchema);
141 LOG.info("No database {} found on {}", database, connectionInfo);
143 } catch (InterruptedException | ExecutionException e) {
144 LOG.warn("Exception attempting to registerCallbacks {}: ", connectionInfo, e);
149 public void createTransactInvokers() {
150 if (transactInvokers == null) {
152 transactInvokers = new HashMap<>();
153 TypedDatabaseSchema dbSchema = getSchema(SouthboundConstants.OPEN_V_SWITCH).get();
154 if (dbSchema != null) {
155 transactInvokers.put(dbSchema, new TransactInvokerImpl(this,dbSchema));
157 } catch (InterruptedException | ExecutionException e) {
158 LOG.warn("Exception attempting to createTransactionInvokers {}", connectionInfo, e);
164 void monitorTables(final String database, final DatabaseSchema dbSchema) {
165 Set<String> tables = dbSchema.getTables();
166 if (tables != null) {
167 List<MonitorRequest> monitorRequests = new ArrayList<>();
168 for (String tableName : tables) {
169 if (!SouthboundConstants.SKIP_OVSDB_TABLE.contains(tableName)) {
170 LOG.info("Southbound monitoring OVSDB schema table {}", tableName);
171 GenericTableSchema tableSchema = dbSchema.table(tableName, GenericTableSchema.class);
172 // We copy the columns so we can clean the set up later
173 Set<String> columns = new HashSet<>(tableSchema.getColumns());
174 List<String> skipColumns = SouthboundConstants.SKIP_COLUMN_FROM_TABLE.get(tableName);
175 if (skipColumns != null) {
176 LOG.info("Southbound NOT monitoring columns {} in table {}", skipColumns, tableName);
177 columns.removeAll(skipColumns);
179 monitorRequests.add(new MonitorRequestBuilder<>(tableSchema)
181 .with(new MonitorSelect(true, true, true, true)).build());
184 this.callback.update(monitor(dbSchema, monitorRequests, callback), dbSchema);
186 LOG.warn("No tables for schema {} for database {} for key {}",dbSchema,database,connectionInfo);
190 private void updateConnectionAttributes(final InstanceIdentifierCodec instanceIdentifierCodec) {
191 LOG.debug("Update attributes of ovsdb node ip: {} port: {}",
192 this.initialCreateData.getConnectionInfo().getRemoteIp(),
193 this.initialCreateData.getConnectionInfo().getRemotePort());
194 for (Map.Entry<TypedDatabaseSchema, TransactInvoker> entry: transactInvokers.entrySet()) {
196 TransactionBuilder transaction = new TransactionBuilder(this.client, entry.getKey());
199 OpenVSwitch ovs = TyperUtils.getTypedRowWrapper(transaction.getDatabaseSchema(), OpenVSwitch.class);
201 List<OpenvswitchExternalIds> externalIds = this.initialCreateData.getOpenvswitchExternalIds();
203 stampInstanceIdentifier(transaction, this.instanceIdentifier.firstIdentifierOf(Node.class),
204 instanceIdentifierCodec);
208 YangUtils.convertYangKeyValueListToMap(externalIds, OpenvswitchExternalIds::getExternalIdKey,
209 OpenvswitchExternalIds::getExternalIdValue));
210 Mutate<GenericTableSchema> mutate = op.mutate(ovs)
211 .addMutation(ovs.getExternalIdsColumn().getSchema(),
213 ovs.getExternalIdsColumn().getData());
214 transaction.add(mutate);
215 } catch (NullPointerException e) {
216 LOG.warn("Incomplete OVSDB Node external IDs", e);
221 List<OpenvswitchOtherConfigs> otherConfigs = this.initialCreateData.getOpenvswitchOtherConfigs();
222 if (otherConfigs != null) {
224 ovs.setOtherConfig(YangUtils.convertYangKeyValueListToMap(otherConfigs,
225 OpenvswitchOtherConfigs::getOtherConfigKey,
226 OpenvswitchOtherConfigs::getOtherConfigValue));
227 transaction.add(op.mutate(ovs).addMutation(ovs.getOtherConfigColumn().getSchema(),
229 ovs.getOtherConfigColumn().getData()));
230 } catch (NullPointerException e) {
231 LOG.warn("Incomplete OVSDB Node other_config", e);
239 private static void stampInstanceIdentifier(final TransactionBuilder transaction,final InstanceIdentifier<Node> iid,
240 final InstanceIdentifierCodec instanceIdentifierCodec) {
241 OpenVSwitch ovs = TyperUtils.getTypedRowWrapper(transaction.getDatabaseSchema(), OpenVSwitch.class);
242 ovs.setExternalIds(Collections.emptyMap());
243 TransactUtils.stampInstanceIdentifier(transaction, iid, ovs.getSchema(), ovs.getExternalIdsColumn().getSchema(),
244 instanceIdentifierCodec);
247 private static void invoke(final TransactionBuilder txBuilder) {
248 ListenableFuture<List<OperationResult>> result = txBuilder.execute();
249 LOG.debug("invoke: tb: {}", txBuilder);
250 if (txBuilder.getOperations().size() > 0) {
252 List<OperationResult> got = result.get();
253 LOG.debug("OVSDB transaction result: {}", got);
254 } catch (InterruptedException | ExecutionException e) {
255 LOG.warn("Transact execution exception: ", e);
257 LOG.trace("invoke exit tb: {}", txBuilder);
261 public ListenableFuture<List<String>> getDatabases() {
262 return client.getDatabases();
265 public ListenableFuture<TypedDatabaseSchema> getSchema(final String database) {
266 return client.getSchema(database);
269 public TransactionBuilder transactBuilder(final DatabaseSchema dbSchema) {
270 return client.transactBuilder(dbSchema);
273 public <E extends TableSchema<E>> TableUpdates monitor(
274 final DatabaseSchema schema, final List<MonitorRequest> monitorRequests,
275 final MonitorHandle monitorHandle, final MonitorCallBack callbackArgument) {
279 public <E extends TableSchema<E>> TableUpdates monitor(
280 final DatabaseSchema schema, final List<MonitorRequest> monitorRequests,
281 final MonitorCallBack callbackArgument) {
282 return client.monitor(schema, monitorRequests, callbackArgument);
285 public void cancelMonitor(final MonitorHandle handler) {
286 client.cancelMonitor(handler);
289 public void lock(final String lockId, final LockAquisitionCallback lockedCallBack,
290 final LockStolenCallback stolenCallback) {
291 client.lock(lockId, lockedCallBack, stolenCallback);
294 public ListenableFuture<Boolean> steal(final String lockId) {
295 return client.steal(lockId);
298 public ListenableFuture<Boolean> unLock(final String lockId) {
299 return client.unLock(lockId);
302 public boolean isActive() {
303 return client.isActive();
306 public void disconnect() {
310 public DatabaseSchema getDatabaseSchema(final String dbName) {
311 return client.getDatabaseSchema(dbName);
314 public <T extends TypedBaseTable<?>> T createTypedRowWrapper(final Class<T> klazz) {
315 return client.createTypedRowWrapper(klazz);
318 public <T extends TypedBaseTable<?>> T createTypedRowWrapper(
319 final DatabaseSchema dbSchema, final Class<T> klazz) {
320 return client.createTypedRowWrapper(dbSchema, klazz);
323 public <T extends TypedBaseTable<?>> T getTypedRowWrapper(final Class<T> klazz,
324 final Row<GenericTableSchema> row) {
325 return client.getTypedRowWrapper(klazz, row);
328 public OvsdbConnectionInfo getConnectionInfo() {
329 return client.getConnectionInfo();
332 public ConnectionInfo getMDConnectionInfo() {
333 return connectionInfo;
336 public void setMDConnectionInfo(final ConnectionInfo key) {
337 this.connectionInfo = key;
340 public InstanceIdentifier<Node> getInstanceIdentifier() {
341 return instanceIdentifier;
344 public NodeKey getNodeKey() {
345 return getInstanceIdentifier().firstKeyOf(Node.class);
348 public NodeId getNodeId() {
349 return getNodeKey().getNodeId();
352 public void setInstanceIdentifier(final InstanceIdentifier<Node> iid) {
353 this.instanceIdentifier = iid;
356 public Entity getConnectedEntity() {
357 return this.connectedEntity;
360 public void setConnectedEntity(final Entity entity) {
361 this.connectedEntity = entity;
364 public Boolean hasOvsdbClient(final OvsdbClient otherClient) {
365 return client.equals(otherClient);
368 public Boolean getHasDeviceOwnership() {
369 return hasDeviceOwnership;
372 public void setHasDeviceOwnership(final Boolean hasDeviceOwnership) {
373 if (hasDeviceOwnership != null) {
374 LOG.debug("Ownership status for {} old {} new {}",
375 instanceIdentifier, this.hasDeviceOwnership, hasDeviceOwnership);
376 this.hasDeviceOwnership = hasDeviceOwnership;
380 public void setDeviceOwnershipCandidateRegistration(
381 @NonNull final EntityOwnershipCandidateRegistration registration) {
382 this.deviceOwnershipCandidateRegistration = registration;
385 public void closeDeviceOwnershipCandidateRegistration() {
386 if (deviceOwnershipCandidateRegistration != null) {
387 this.deviceOwnershipCandidateRegistration.close();
388 setHasDeviceOwnership(Boolean.FALSE);
392 public OvsdbNodeAugmentation getOvsdbNodeAugmentation() {
393 return this.initialCreateData;
396 public void setOvsdbNodeAugmentation(final OvsdbNodeAugmentation ovsdbNodeCreateData) {
397 this.initialCreateData = ovsdbNodeCreateData;
400 public OvsdbClient getOvsdbClient() {