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.OpenvswitchExternalIdsKey;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.OpenvswitchOtherConfigs;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.OpenvswitchOtherConfigsKey;
65 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
66 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
67 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
68 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
72 public class OvsdbConnectionInstance {
73 private static final Logger LOG = LoggerFactory.getLogger(OvsdbConnectionInstance.class);
74 private final OvsdbClient client;
75 private ConnectionInfo connectionInfo;
76 private final TransactionInvoker txInvoker;
77 private Map<TypedDatabaseSchema, TransactInvoker> transactInvokers;
78 private MonitorCallBack callback;
79 private InstanceIdentifier<Node> instanceIdentifier;
80 private volatile boolean hasDeviceOwnership = false;
81 private Entity connectedEntity;
82 private EntityOwnershipCandidateRegistration deviceOwnershipCandidateRegistration;
83 private OvsdbNodeAugmentation initialCreateData = null;
84 private final Map<UUID, InstanceIdentifier<Node>> ports = new ConcurrentHashMap<>();
85 private final Map<String, InstanceIdentifier<Node>> portInterfaces = new ConcurrentHashMap<>();
87 OvsdbConnectionInstance(final ConnectionInfo key, final OvsdbClient client, final TransactionInvoker txInvoker,
88 final InstanceIdentifier<Node> iid) {
89 this.connectionInfo = key;
91 this.txInvoker = txInvoker;
93 this.instanceIdentifier = iid;
96 public void updatePort(UUID uuid, InstanceIdentifier<Node> iid) {
100 public void removePort(UUID uuid) {
104 public InstanceIdentifier<Node> getPort(UUID uuid) {
105 return ports.get(uuid);
108 public void updatePortInterface(String name, InstanceIdentifier<Node> iid) {
109 portInterfaces.put(name, iid);
112 public void removePortInterface(String name) {
113 portInterfaces.remove(name);
116 public InstanceIdentifier<Node> getPortInterface(String name) {
117 return portInterfaces.get(name);
121 * Apply the given command to the given events, based on the given bridge state.
123 * @param command The command to run.
124 * @param state The current bridge state.
125 * @param events The events to process.
126 * @param instanceIdentifierCodec The instance identifier codec to use.
128 public void transact(final TransactCommand command, final BridgeOperationalState state,
129 final DataChangeEvent events, final InstanceIdentifierCodec instanceIdentifierCodec) {
130 for (TransactInvoker transactInvoker : transactInvokers.values()) {
131 transactInvoker.invoke(command, state, events, instanceIdentifierCodec);
136 * Apply the given command to the given modifications, based on the given bridge state.
138 * @param command The command to run.
139 * @param state The current bridge state.
140 * @param modifications The modifications to process.
141 * @param instanceIdentifierCodec The instance identifier codec to use.
143 public void transact(final TransactCommand command, final BridgeOperationalState state,
144 final Collection<DataTreeModification<Node>> modifications,
145 final InstanceIdentifierCodec instanceIdentifierCodec) {
146 for (TransactInvoker transactInvoker : transactInvokers.values()) {
147 transactInvoker.invoke(command, state, modifications, instanceIdentifierCodec);
151 public ListenableFuture<List<OperationResult>> transact(
152 final DatabaseSchema dbSchema, final List<Operation> operations) {
153 return client.transact(dbSchema, operations);
156 public void registerCallbacks(final InstanceIdentifierCodec instanceIdentifierCodec) {
157 if (this.callback == null) {
158 if (this.initialCreateData != null) {
159 this.updateConnectionAttributes(instanceIdentifierCodec);
163 String database = SouthboundConstants.OPEN_V_SWITCH;
164 DatabaseSchema dbSchema = getSchema(database).get();
165 if (dbSchema != null) {
166 LOG.info("Monitoring database: {}", database);
167 callback = new OvsdbMonitorCallback(instanceIdentifierCodec, this, txInvoker);
168 monitorTables(database, dbSchema);
170 LOG.info("No database {} found on {}", database, connectionInfo);
172 } catch (InterruptedException | ExecutionException e) {
173 LOG.warn("Exception attempting to registerCallbacks {}: ", connectionInfo, e);
178 public void createTransactInvokers() {
179 if (transactInvokers == null) {
181 transactInvokers = new HashMap<>();
182 TypedDatabaseSchema dbSchema = getSchema(SouthboundConstants.OPEN_V_SWITCH).get();
183 if (dbSchema != null) {
184 transactInvokers.put(dbSchema, new TransactInvokerImpl(this,dbSchema));
186 } catch (InterruptedException | ExecutionException e) {
187 LOG.warn("Exception attempting to createTransactionInvokers {}", connectionInfo, e);
193 void monitorTables(final String database, final DatabaseSchema dbSchema) {
194 Set<String> tables = dbSchema.getTables();
195 if (tables != null) {
196 List<MonitorRequest> monitorRequests = new ArrayList<>();
197 for (String tableName : tables) {
198 if (!SouthboundConstants.SKIP_OVSDB_TABLE.contains(tableName)) {
199 LOG.info("Southbound monitoring OVSDB schema table {}", tableName);
200 GenericTableSchema tableSchema = dbSchema.table(tableName, GenericTableSchema.class);
201 // We copy the columns so we can clean the set up later
202 Set<String> columns = new HashSet<>(tableSchema.getColumns());
203 List<String> skipColumns = SouthboundConstants.SKIP_COLUMN_FROM_TABLE.get(tableName);
204 if (skipColumns != null) {
205 LOG.info("Southbound NOT monitoring columns {} in table {}", skipColumns, tableName);
206 columns.removeAll(skipColumns);
208 monitorRequests.add(new MonitorRequestBuilder<>(tableSchema)
210 .with(new MonitorSelect(true, true, true, true)).build());
213 this.callback.update(monitor(dbSchema, monitorRequests, callback), dbSchema);
215 LOG.warn("No tables for schema {} for database {} for key {}",dbSchema,database,connectionInfo);
219 private void updateConnectionAttributes(final InstanceIdentifierCodec instanceIdentifierCodec) {
220 LOG.debug("Update attributes of ovsdb node ip: {} port: {}",
221 this.initialCreateData.getConnectionInfo().getRemoteIp(),
222 this.initialCreateData.getConnectionInfo().getRemotePort());
223 for (Map.Entry<TypedDatabaseSchema, TransactInvoker> entry: transactInvokers.entrySet()) {
225 TransactionBuilder transaction = new TransactionBuilder(this.client, entry.getKey());
228 OpenVSwitch ovs = transaction.getTypedRowWrapper(OpenVSwitch.class);
230 Map<OpenvswitchExternalIdsKey, OpenvswitchExternalIds> externalIds =
231 this.initialCreateData.getOpenvswitchExternalIds();
233 stampInstanceIdentifier(transaction, this.instanceIdentifier.firstIdentifierOf(Node.class),
234 instanceIdentifierCodec);
238 YangUtils.convertYangKeyValueListToMap(externalIds, OpenvswitchExternalIds::getExternalIdKey,
239 OpenvswitchExternalIds::getExternalIdValue));
240 Mutate<GenericTableSchema> mutate = op.mutate(ovs)
241 .addMutation(ovs.getExternalIdsColumn().getSchema(),
243 ovs.getExternalIdsColumn().getData());
244 transaction.add(mutate);
245 } catch (NullPointerException e) {
246 LOG.warn("Incomplete OVSDB Node external IDs", e);
251 Map<OpenvswitchOtherConfigsKey, OpenvswitchOtherConfigs> otherConfigs =
252 this.initialCreateData.getOpenvswitchOtherConfigs();
253 if (otherConfigs != null) {
255 ovs.setOtherConfig(YangUtils.convertYangKeyValueListToMap(otherConfigs,
256 OpenvswitchOtherConfigs::getOtherConfigKey,
257 OpenvswitchOtherConfigs::getOtherConfigValue));
258 transaction.add(op.mutate(ovs).addMutation(ovs.getOtherConfigColumn().getSchema(),
260 ovs.getOtherConfigColumn().getData()));
261 } catch (NullPointerException e) {
262 LOG.warn("Incomplete OVSDB Node other_config", e);
270 private static void stampInstanceIdentifier(final TransactionBuilder transaction,final InstanceIdentifier<Node> iid,
271 final InstanceIdentifierCodec instanceIdentifierCodec) {
272 OpenVSwitch ovs = transaction.getTypedRowWrapper(OpenVSwitch.class);
273 ovs.setExternalIds(Collections.emptyMap());
274 TransactUtils.stampInstanceIdentifier(transaction, iid, ovs.getSchema(), ovs.getExternalIdsColumn().getSchema(),
275 instanceIdentifierCodec);
278 private static void invoke(final TransactionBuilder txBuilder) {
279 ListenableFuture<List<OperationResult>> result = txBuilder.execute();
280 LOG.debug("invoke: tb: {}", txBuilder);
281 if (txBuilder.getOperations().size() > 0) {
283 List<OperationResult> got = result.get();
284 LOG.debug("OVSDB transaction result: {}", got);
285 } catch (InterruptedException | ExecutionException e) {
286 LOG.warn("Transact execution exception: ", e);
288 LOG.trace("invoke exit tb: {}", txBuilder);
292 public ListenableFuture<List<String>> getDatabases() {
293 return client.getDatabases();
296 public ListenableFuture<TypedDatabaseSchema> getSchema(final String database) {
297 return client.getSchema(database);
300 public TransactionBuilder transactBuilder(final DatabaseSchema dbSchema) {
301 return client.transactBuilder(dbSchema);
304 public <E extends TableSchema<E>> TableUpdates monitor(
305 final DatabaseSchema schema, final List<MonitorRequest> monitorRequests,
306 final MonitorHandle monitorHandle, final MonitorCallBack callbackArgument) {
310 public <E extends TableSchema<E>> TableUpdates monitor(
311 final DatabaseSchema schema, final List<MonitorRequest> monitorRequests,
312 final MonitorCallBack callbackArgument) {
313 return client.monitor(schema, monitorRequests, callbackArgument);
316 public void cancelMonitor(final MonitorHandle handler) {
317 client.cancelMonitor(handler);
320 public void lock(final String lockId, final LockAquisitionCallback lockedCallBack,
321 final LockStolenCallback stolenCallback) {
322 client.lock(lockId, lockedCallBack, stolenCallback);
325 public ListenableFuture<Boolean> steal(final String lockId) {
326 return client.steal(lockId);
329 public ListenableFuture<Boolean> unLock(final String lockId) {
330 return client.unLock(lockId);
333 public boolean isActive() {
334 return client.isActive();
337 public void disconnect() {
341 public DatabaseSchema getDatabaseSchema(final String dbName) {
342 return client.getDatabaseSchema(dbName);
345 public <T extends TypedBaseTable<?>> T createTypedRowWrapper(final Class<T> klazz) {
346 return client.createTypedRowWrapper(klazz);
349 public <T extends TypedBaseTable<?>> T createTypedRowWrapper(
350 final DatabaseSchema dbSchema, final Class<T> klazz) {
351 return client.createTypedRowWrapper(dbSchema, klazz);
354 public <T extends TypedBaseTable<?>> T getTypedRowWrapper(final Class<T> klazz,
355 final Row<GenericTableSchema> row) {
356 return client.getTypedRowWrapper(klazz, row);
359 public OvsdbConnectionInfo getConnectionInfo() {
360 return client.getConnectionInfo();
363 public ConnectionInfo getMDConnectionInfo() {
364 return connectionInfo;
367 public void setMDConnectionInfo(final ConnectionInfo key) {
368 this.connectionInfo = key;
371 public InstanceIdentifier<Node> getInstanceIdentifier() {
372 return instanceIdentifier;
375 public NodeKey getNodeKey() {
376 return getInstanceIdentifier().firstKeyOf(Node.class);
379 public NodeId getNodeId() {
380 return getNodeKey().getNodeId();
383 public void setInstanceIdentifier(final InstanceIdentifier<Node> iid) {
384 this.instanceIdentifier = iid;
387 public Entity getConnectedEntity() {
388 return this.connectedEntity;
391 public void setConnectedEntity(final Entity entity) {
392 this.connectedEntity = entity;
395 public Boolean hasOvsdbClient(final OvsdbClient otherClient) {
396 return client.equals(otherClient);
399 public Boolean getHasDeviceOwnership() {
400 return hasDeviceOwnership;
403 public void setHasDeviceOwnership(final Boolean hasDeviceOwnership) {
404 if (hasDeviceOwnership != null) {
405 LOG.debug("Ownership status for {} old {} new {}",
406 instanceIdentifier, this.hasDeviceOwnership, hasDeviceOwnership);
407 this.hasDeviceOwnership = hasDeviceOwnership;
411 public void setDeviceOwnershipCandidateRegistration(
412 @NonNull final EntityOwnershipCandidateRegistration registration) {
413 this.deviceOwnershipCandidateRegistration = registration;
416 public void closeDeviceOwnershipCandidateRegistration() {
417 if (deviceOwnershipCandidateRegistration != null) {
418 this.deviceOwnershipCandidateRegistration.close();
419 setHasDeviceOwnership(Boolean.FALSE);
423 public OvsdbNodeAugmentation getOvsdbNodeAugmentation() {
424 return this.initialCreateData;
427 public void setOvsdbNodeAugmentation(final OvsdbNodeAugmentation ovsdbNodeCreateData) {
428 this.initialCreateData = ovsdbNodeCreateData;
431 public OvsdbClient getOvsdbClient() {