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.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;
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;
73 public class OvsdbConnectionInstance {
74 private static final Logger LOG = LoggerFactory.getLogger(OvsdbConnectionInstance.class);
76 private static final ImmutableSet<String> SKIP_OVSDB_TABLE = ImmutableSet.of(
82 "Flow_Sample_Collector_Set");
84 private final OvsdbClient client;
85 private ConnectionInfo connectionInfo;
86 private final TransactionInvoker txInvoker;
87 private Map<TypedDatabaseSchema, TransactInvoker> transactInvokers;
88 private MonitorCallBack callback;
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<>();
97 OvsdbConnectionInstance(final ConnectionInfo key, final OvsdbClient client, final TransactionInvoker txInvoker,
98 final InstanceIdentifier<Node> iid) {
100 this.client = client;
101 this.txInvoker = txInvoker;
103 instanceIdentifier = iid;
106 public void updatePort(final UUID uuid, final InstanceIdentifier<Node> iid) {
107 ports.put(uuid, iid);
110 public void removePort(final UUID uuid) {
114 public InstanceIdentifier<Node> getPort(final UUID uuid) {
115 return ports.get(uuid);
118 public void updatePortInterface(final String name, final InstanceIdentifier<Node> iid) {
119 portInterfaces.put(name, iid);
122 public void removePortInterface(final String name) {
123 portInterfaces.remove(name);
126 public InstanceIdentifier<Node> getPortInterface(final String name) {
127 return portInterfaces.get(name);
131 * Apply the given command to the given events, based on the given bridge state.
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.
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);
146 * Apply the given command to the given modifications, based on the given bridge state.
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.
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);
161 public ListenableFuture<List<OperationResult>> transact(
162 final DatabaseSchema dbSchema, final List<Operation> operations) {
163 return client.transact(dbSchema, operations);
166 public void registerCallbacks(final InstanceIdentifierCodec instanceIdentifierCodec) {
167 if (callback == null) {
168 if (initialCreateData != null) {
169 this.updateConnectionAttributes(instanceIdentifierCodec);
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);
180 LOG.info("No database {} found on {}", database, connectionInfo);
182 } catch (InterruptedException | ExecutionException e) {
183 LOG.warn("Exception attempting to registerCallbacks {}: ", connectionInfo, e);
188 public void createTransactInvokers() {
189 if (transactInvokers == null) {
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));
196 } catch (InterruptedException | ExecutionException e) {
197 LOG.warn("Exception attempting to createTransactionInvokers {}", connectionInfo, e);
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);
218 monitorRequests.add(new MonitorRequestBuilder<>(tableSchema)
220 .with(new MonitorSelect(true, true, true, true)).build());
223 callback.update(monitor(dbSchema, monitorRequests, callback), dbSchema);
225 LOG.warn("No tables for schema {} for database {} for key {}",dbSchema,database,connectionInfo);
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()) {
235 TransactionBuilder transaction = new TransactionBuilder(client, entry.getKey());
238 OpenVSwitch ovs = transaction.getTypedRowWrapper(OpenVSwitch.class);
240 Map<OpenvswitchExternalIdsKey, OpenvswitchExternalIds> externalIds =
241 initialCreateData.getOpenvswitchExternalIds();
243 stampInstanceIdentifier(transaction, instanceIdentifier.firstIdentifierOf(Node.class),
244 instanceIdentifierCodec);
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);
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()));
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);
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) {
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);
285 LOG.trace("invoke exit tb: {}", txBuilder);
289 public ListenableFuture<List<String>> getDatabases() {
290 return client.getDatabases();
293 public ListenableFuture<TypedDatabaseSchema> getSchema(final String database) {
294 return client.getSchema(database);
297 public TransactionBuilder transactBuilder(final DatabaseSchema dbSchema) {
298 return client.transactBuilder(dbSchema);
301 public <E extends TableSchema<E>> TableUpdates monitor(
302 final DatabaseSchema schema, final List<MonitorRequest> monitorRequests,
303 final MonitorHandle monitorHandle, final MonitorCallBack callbackArgument) {
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);
313 public void cancelMonitor(final MonitorHandle handler) {
314 client.cancelMonitor(handler);
317 public void lock(final String lockId, final LockAquisitionCallback lockedCallBack,
318 final LockStolenCallback stolenCallback) {
319 client.lock(lockId, lockedCallBack, stolenCallback);
322 public ListenableFuture<Boolean> steal(final String lockId) {
323 return client.steal(lockId);
326 public ListenableFuture<Boolean> unLock(final String lockId) {
327 return client.unLock(lockId);
330 public boolean isActive() {
331 return client.isActive();
334 public void disconnect() {
338 public DatabaseSchema getDatabaseSchema(final String dbName) {
339 return client.getDatabaseSchema(dbName);
342 public <T extends TypedBaseTable<?>> T createTypedRowWrapper(final Class<T> klazz) {
343 return client.createTypedRowWrapper(klazz);
346 public <T extends TypedBaseTable<?>> T createTypedRowWrapper(
347 final DatabaseSchema dbSchema, final Class<T> klazz) {
348 return client.createTypedRowWrapper(dbSchema, klazz);
351 public <T extends TypedBaseTable<?>> T getTypedRowWrapper(final Class<T> klazz,
352 final Row<GenericTableSchema> row) {
353 return client.getTypedRowWrapper(klazz, row);
356 public OvsdbConnectionInfo getConnectionInfo() {
357 return client.getConnectionInfo();
360 public ConnectionInfo getMDConnectionInfo() {
361 return connectionInfo;
364 public void setMDConnectionInfo(final ConnectionInfo key) {
365 connectionInfo = key;
368 public InstanceIdentifier<Node> getInstanceIdentifier() {
369 return instanceIdentifier;
372 public NodeKey getNodeKey() {
373 return getInstanceIdentifier().firstKeyOf(Node.class);
376 public NodeId getNodeId() {
377 return getNodeKey().getNodeId();
380 public void setInstanceIdentifier(final InstanceIdentifier<Node> iid) {
381 instanceIdentifier = iid;
384 public Entity getConnectedEntity() {
385 return connectedEntity;
388 public void setConnectedEntity(final Entity entity) {
389 connectedEntity = entity;
392 public Boolean hasOvsdbClient(final OvsdbClient otherClient) {
393 return client.equals(otherClient);
396 public Boolean getHasDeviceOwnership() {
397 return hasDeviceOwnership;
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;
408 public void setDeviceOwnershipCandidateRegistration(
409 @NonNull final EntityOwnershipCandidateRegistration registration) {
410 deviceOwnershipCandidateRegistration = registration;
413 public void closeDeviceOwnershipCandidateRegistration() {
414 if (deviceOwnershipCandidateRegistration != null) {
415 deviceOwnershipCandidateRegistration.close();
416 setHasDeviceOwnership(Boolean.FALSE);
420 public OvsdbNodeAugmentation getOvsdbNodeAugmentation() {
421 return initialCreateData;
424 public void setOvsdbNodeAugmentation(final OvsdbNodeAugmentation ovsdbNodeCreateData) {
425 initialCreateData = ovsdbNodeCreateData;
428 public OvsdbClient getOvsdbClient() {