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.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;
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<>();
85 OvsdbConnectionInstance(final ConnectionInfo key, final OvsdbClient client, final TransactionInvoker txInvoker,
86 final InstanceIdentifier<Node> iid) {
87 this.connectionInfo = key;
89 this.txInvoker = txInvoker;
91 this.instanceIdentifier = iid;
94 public void updatePort(UUID uuid, InstanceIdentifier<Node> iid) {
98 public void removePort(UUID uuid) {
102 public InstanceIdentifier<Node> getPort(UUID uuid) {
103 return ports.get(uuid);
106 public void updatePortInterface(String name, InstanceIdentifier<Node> iid) {
107 portInterfaces.put(name, iid);
110 public void removePortInterface(String name) {
111 portInterfaces.remove(name);
114 public InstanceIdentifier<Node> getPortInterface(String name) {
115 return portInterfaces.get(name);
119 * Apply the given command to the given events, based on the given bridge state.
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.
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);
134 * Apply the given command to the given modifications, based on the given bridge state.
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.
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);
149 public ListenableFuture<List<OperationResult>> transact(
150 final DatabaseSchema dbSchema, final List<Operation> operations) {
151 return client.transact(dbSchema, operations);
154 public void registerCallbacks(final InstanceIdentifierCodec instanceIdentifierCodec) {
155 if (this.callback == null) {
156 if (this.initialCreateData != null) {
157 this.updateConnectionAttributes(instanceIdentifierCodec);
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);
168 LOG.info("No database {} found on {}", database, connectionInfo);
170 } catch (InterruptedException | ExecutionException e) {
171 LOG.warn("Exception attempting to registerCallbacks {}: ", connectionInfo, e);
176 public void createTransactInvokers() {
177 if (transactInvokers == null) {
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));
184 } catch (InterruptedException | ExecutionException e) {
185 LOG.warn("Exception attempting to createTransactionInvokers {}", connectionInfo, e);
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);
206 monitorRequests.add(new MonitorRequestBuilder<>(tableSchema)
208 .with(new MonitorSelect(true, true, true, true)).build());
211 this.callback.update(monitor(dbSchema, monitorRequests, callback), dbSchema);
213 LOG.warn("No tables for schema {} for database {} for key {}",dbSchema,database,connectionInfo);
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()) {
223 TransactionBuilder transaction = new TransactionBuilder(this.client, entry.getKey());
226 OpenVSwitch ovs = transaction.getTypedRowWrapper(OpenVSwitch.class);
228 List<OpenvswitchExternalIds> externalIds = this.initialCreateData.getOpenvswitchExternalIds();
230 stampInstanceIdentifier(transaction, this.instanceIdentifier.firstIdentifierOf(Node.class),
231 instanceIdentifierCodec);
235 YangUtils.convertYangKeyValueListToMap(externalIds, OpenvswitchExternalIds::getExternalIdKey,
236 OpenvswitchExternalIds::getExternalIdValue));
237 Mutate<GenericTableSchema> mutate = op.mutate(ovs)
238 .addMutation(ovs.getExternalIdsColumn().getSchema(),
240 ovs.getExternalIdsColumn().getData());
241 transaction.add(mutate);
242 } catch (NullPointerException e) {
243 LOG.warn("Incomplete OVSDB Node external IDs", e);
248 List<OpenvswitchOtherConfigs> otherConfigs = this.initialCreateData.getOpenvswitchOtherConfigs();
249 if (otherConfigs != null) {
251 ovs.setOtherConfig(YangUtils.convertYangKeyValueListToMap(otherConfigs,
252 OpenvswitchOtherConfigs::getOtherConfigKey,
253 OpenvswitchOtherConfigs::getOtherConfigValue));
254 transaction.add(op.mutate(ovs).addMutation(ovs.getOtherConfigColumn().getSchema(),
256 ovs.getOtherConfigColumn().getData()));
257 } catch (NullPointerException e) {
258 LOG.warn("Incomplete OVSDB Node other_config", e);
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);
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) {
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);
284 LOG.trace("invoke exit tb: {}", txBuilder);
288 public ListenableFuture<List<String>> getDatabases() {
289 return client.getDatabases();
292 public ListenableFuture<TypedDatabaseSchema> getSchema(final String database) {
293 return client.getSchema(database);
296 public TransactionBuilder transactBuilder(final DatabaseSchema dbSchema) {
297 return client.transactBuilder(dbSchema);
300 public <E extends TableSchema<E>> TableUpdates monitor(
301 final DatabaseSchema schema, final List<MonitorRequest> monitorRequests,
302 final MonitorHandle monitorHandle, final MonitorCallBack callbackArgument) {
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);
312 public void cancelMonitor(final MonitorHandle handler) {
313 client.cancelMonitor(handler);
316 public void lock(final String lockId, final LockAquisitionCallback lockedCallBack,
317 final LockStolenCallback stolenCallback) {
318 client.lock(lockId, lockedCallBack, stolenCallback);
321 public ListenableFuture<Boolean> steal(final String lockId) {
322 return client.steal(lockId);
325 public ListenableFuture<Boolean> unLock(final String lockId) {
326 return client.unLock(lockId);
329 public boolean isActive() {
330 return client.isActive();
333 public void disconnect() {
337 public DatabaseSchema getDatabaseSchema(final String dbName) {
338 return client.getDatabaseSchema(dbName);
341 public <T extends TypedBaseTable<?>> T createTypedRowWrapper(final Class<T> klazz) {
342 return client.createTypedRowWrapper(klazz);
345 public <T extends TypedBaseTable<?>> T createTypedRowWrapper(
346 final DatabaseSchema dbSchema, final Class<T> klazz) {
347 return client.createTypedRowWrapper(dbSchema, klazz);
350 public <T extends TypedBaseTable<?>> T getTypedRowWrapper(final Class<T> klazz,
351 final Row<GenericTableSchema> row) {
352 return client.getTypedRowWrapper(klazz, row);
355 public OvsdbConnectionInfo getConnectionInfo() {
356 return client.getConnectionInfo();
359 public ConnectionInfo getMDConnectionInfo() {
360 return connectionInfo;
363 public void setMDConnectionInfo(final ConnectionInfo key) {
364 this.connectionInfo = key;
367 public InstanceIdentifier<Node> getInstanceIdentifier() {
368 return instanceIdentifier;
371 public NodeKey getNodeKey() {
372 return getInstanceIdentifier().firstKeyOf(Node.class);
375 public NodeId getNodeId() {
376 return getNodeKey().getNodeId();
379 public void setInstanceIdentifier(final InstanceIdentifier<Node> iid) {
380 this.instanceIdentifier = iid;
383 public Entity getConnectedEntity() {
384 return this.connectedEntity;
387 public void setConnectedEntity(final Entity entity) {
388 this.connectedEntity = entity;
391 public Boolean hasOvsdbClient(final OvsdbClient otherClient) {
392 return client.equals(otherClient);
395 public Boolean getHasDeviceOwnership() {
396 return hasDeviceOwnership;
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;
407 public void setDeviceOwnershipCandidateRegistration(
408 @NonNull final EntityOwnershipCandidateRegistration registration) {
409 this.deviceOwnershipCandidateRegistration = registration;
412 public void closeDeviceOwnershipCandidateRegistration() {
413 if (deviceOwnershipCandidateRegistration != null) {
414 this.deviceOwnershipCandidateRegistration.close();
415 setHasDeviceOwnership(Boolean.FALSE);
419 public OvsdbNodeAugmentation getOvsdbNodeAugmentation() {
420 return this.initialCreateData;
423 public void setOvsdbNodeAugmentation(final OvsdbNodeAugmentation ovsdbNodeCreateData) {
424 this.initialCreateData = ovsdbNodeCreateData;
427 public OvsdbClient getOvsdbClient() {