2 * Copyright (c) 2015, 2016 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.collect.Lists;
13 import com.google.common.util.concurrent.ListenableFuture;
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;
24 import javax.annotation.Nonnull;
26 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
27 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
28 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
29 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
30 import org.opendaylight.ovsdb.lib.LockAquisitionCallback;
31 import org.opendaylight.ovsdb.lib.LockStolenCallback;
32 import org.opendaylight.ovsdb.lib.MonitorCallBack;
33 import org.opendaylight.ovsdb.lib.MonitorHandle;
34 import org.opendaylight.ovsdb.lib.OvsdbClient;
35 import org.opendaylight.ovsdb.lib.OvsdbConnectionInfo;
36 import org.opendaylight.ovsdb.lib.message.MonitorRequest;
37 import org.opendaylight.ovsdb.lib.message.MonitorRequestBuilder;
38 import org.opendaylight.ovsdb.lib.message.MonitorSelect;
39 import org.opendaylight.ovsdb.lib.message.TableUpdates;
40 import org.opendaylight.ovsdb.lib.notation.Mutator;
41 import org.opendaylight.ovsdb.lib.notation.Row;
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.TyperUtils;
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.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.DataObject;
67 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
71 public class OvsdbConnectionInstance {
72 private static final Logger LOG = LoggerFactory.getLogger(OvsdbConnectionInstance.class);
73 private final OvsdbClient client;
74 private ConnectionInfo connectionInfo;
75 private final TransactionInvoker txInvoker;
76 private Map<DatabaseSchema,TransactInvoker> transactInvokers;
77 private MonitorCallBack callback;
78 private InstanceIdentifier<Node> instanceIdentifier;
79 private volatile boolean hasDeviceOwnership = false;
80 private Entity connectedEntity;
81 private EntityOwnershipCandidateRegistration deviceOwnershipCandidateRegistration;
82 private OvsdbNodeAugmentation initialCreateData = null;
84 OvsdbConnectionInstance(ConnectionInfo key, OvsdbClient client, TransactionInvoker txInvoker,
85 InstanceIdentifier<Node> iid) {
86 this.connectionInfo = key;
88 this.txInvoker = txInvoker;
90 this.instanceIdentifier = iid;
94 * Apply the given command to the given events, based on the given bridge state.
96 * @param command The command to run.
97 * @param state The current bridge state.
98 * @param events The events to process.
99 * @param instanceIdentifierCodec The instance identifier codec to use.
101 public void transact(TransactCommand command, BridgeOperationalState state,
102 AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> events,
103 InstanceIdentifierCodec instanceIdentifierCodec) {
104 for (TransactInvoker transactInvoker : transactInvokers.values()) {
105 transactInvoker.invoke(command, state, events, instanceIdentifierCodec);
110 * Apply the given command to the given modifications, based on the given bridge state.
112 * @param command The command to run.
113 * @param state The current bridge state.
114 * @param modifications The modifications to process.
115 * @param instanceIdentifierCodec The instance identifier codec to use.
117 public void transact(TransactCommand command, BridgeOperationalState state,
118 Collection<DataTreeModification<Node>> modifications, InstanceIdentifierCodec instanceIdentifierCodec) {
119 for (TransactInvoker transactInvoker : transactInvokers.values()) {
120 transactInvoker.invoke(command, state, modifications, instanceIdentifierCodec);
124 public ListenableFuture<List<OperationResult>> transact(
125 DatabaseSchema dbSchema, List<Operation> operations) {
126 return client.transact(dbSchema, operations);
129 public void registerCallbacks(InstanceIdentifierCodec instanceIdentifierCodec) {
130 if (this.callback == null) {
131 if (this.initialCreateData != null ) {
132 this.updateConnectionAttributes(instanceIdentifierCodec);
136 String database = SouthboundConstants.OPEN_V_SWITCH;
137 DatabaseSchema dbSchema = getSchema(database).get();
138 if (dbSchema != null) {
139 LOG.info("Monitoring database: {}", database);
140 callback = new OvsdbMonitorCallback(instanceIdentifierCodec, this, txInvoker);
141 monitorTables(database, dbSchema);
143 LOG.info("No database {} found on {}", database, connectionInfo);
145 } catch (InterruptedException | ExecutionException e) {
146 LOG.warn("Exception attempting to registerCallbacks {}: ", connectionInfo, e);
151 public void createTransactInvokers() {
152 if (transactInvokers == null) {
154 transactInvokers = new HashMap<>();
155 DatabaseSchema dbSchema = getSchema(SouthboundConstants.OPEN_V_SWITCH).get();
156 if (dbSchema != null) {
157 transactInvokers.put(dbSchema, new TransactInvokerImpl(this,dbSchema));
159 } catch (InterruptedException | ExecutionException e) {
160 LOG.warn("Exception attempting to createTransactionInvokers {}", connectionInfo, e);
165 private void monitorTables(String database, DatabaseSchema dbSchema) {
166 Set<String> tables = dbSchema.getTables();
167 if (tables != null) {
168 List<MonitorRequest> monitorRequests = Lists.newArrayList();
169 for (String tableName : tables) {
170 if (!SouthboundConstants.SKIP_OVSDB_TABLE.contains(tableName)) {
171 LOG.info("Southbound monitoring OVSDB schema table {}", tableName);
172 GenericTableSchema tableSchema = dbSchema.table(tableName, GenericTableSchema.class);
173 // We copy the columns so we can clean the set up later
174 Set<String> columns = new HashSet<>(tableSchema.getColumns());
175 List<String> skipColumns = SouthboundConstants.SKIP_COLUMN_FROM_TABLE.get(tableName);
176 if (skipColumns != null) {
177 LOG.info("Southbound NOT monitoring columns {} in table {}", skipColumns, tableName);
178 columns.removeAll(skipColumns);
180 monitorRequests.add(new MonitorRequestBuilder<>(tableSchema)
182 .with(new MonitorSelect(true, true, true, true)).build());
185 this.callback.update(monitor(dbSchema, monitorRequests, callback), dbSchema);
187 LOG.warn("No tables for schema {} for database {} for key {}",dbSchema,database,connectionInfo);
191 private void updateConnectionAttributes(InstanceIdentifierCodec instanceIdentifierCodec) {
192 LOG.debug("Update attributes of ovsdb node ip: {} port: {}",
193 this.initialCreateData.getConnectionInfo().getRemoteIp(),
194 this.initialCreateData.getConnectionInfo().getRemotePort());
195 for ( Map.Entry<DatabaseSchema,TransactInvoker> entry: transactInvokers.entrySet()) {
197 TransactionBuilder transaction = new TransactionBuilder(this.client, entry.getKey());
200 OpenVSwitch ovs = TyperUtils.getTypedRowWrapper(transaction.getDatabaseSchema(), OpenVSwitch.class);
202 List<OpenvswitchExternalIds> externalIds = this.initialCreateData.getOpenvswitchExternalIds();
204 stampInstanceIdentifier(transaction, this.instanceIdentifier.firstIdentifierOf(Node.class),
205 instanceIdentifierCodec);
209 YangUtils.convertYangKeyValueListToMap(externalIds, OpenvswitchExternalIds::getExternalIdKey,
210 OpenvswitchExternalIds::getExternalIdValue));
211 Mutate<GenericTableSchema> mutate = op.mutate(ovs)
212 .addMutation(ovs.getExternalIdsColumn().getSchema(),
214 ovs.getExternalIdsColumn().getData());
215 transaction.add(mutate);
216 } catch (NullPointerException e) {
217 LOG.warn("Incomplete OVSDB Node external IDs", e);
222 List<OpenvswitchOtherConfigs> otherConfigs = this.initialCreateData.getOpenvswitchOtherConfigs();
223 if (otherConfigs != null) {
225 ovs.setOtherConfig(YangUtils.convertYangKeyValueListToMap(otherConfigs,
226 OpenvswitchOtherConfigs::getOtherConfigKey,
227 OpenvswitchOtherConfigs::getOtherConfigValue));
228 transaction.add(op.mutate(ovs).addMutation(ovs.getOtherConfigColumn().getSchema(),
230 ovs.getOtherConfigColumn().getData()));
231 } catch (NullPointerException e) {
232 LOG.warn("Incomplete OVSDB Node other_config", e);
240 private void stampInstanceIdentifier(TransactionBuilder transaction,InstanceIdentifier<Node> iid,
241 InstanceIdentifierCodec instanceIdentifierCodec) {
242 OpenVSwitch ovs = TyperUtils.getTypedRowWrapper(transaction.getDatabaseSchema(), OpenVSwitch.class);
243 ovs.setExternalIds(Collections.<String,String>emptyMap());
244 TransactUtils.stampInstanceIdentifier(transaction, iid, ovs.getSchema(), ovs.getExternalIdsColumn().getSchema(),
245 instanceIdentifierCodec);
248 private void invoke(TransactionBuilder txBuilder) {
249 ListenableFuture<List<OperationResult>> result = txBuilder.execute();
250 LOG.debug("invoke: tb: {}", txBuilder);
251 if (txBuilder.getOperations().size() > 0) {
253 List<OperationResult> got = result.get();
254 LOG.debug("OVSDB transaction result: {}", got);
255 } catch (InterruptedException | ExecutionException e) {
256 LOG.warn("Transact execution exception: ", e);
258 LOG.trace("invoke exit tb: {}", txBuilder);
263 public ListenableFuture<List<String>> getDatabases() {
264 return client.getDatabases();
267 public ListenableFuture<DatabaseSchema> getSchema(String database) {
268 return client.getSchema(database);
271 public TransactionBuilder transactBuilder(DatabaseSchema dbSchema) {
272 return client.transactBuilder(dbSchema);
275 public <E extends TableSchema<E>> TableUpdates monitor(
276 DatabaseSchema schema, List<MonitorRequest> monitorRequests,
277 MonitorHandle monitorHandle, MonitorCallBack callbackArgument) {
281 public <E extends TableSchema<E>> TableUpdates monitor(
282 DatabaseSchema schema, List<MonitorRequest> monitorRequests,
283 MonitorCallBack callbackArgument) {
284 return client.monitor(schema, monitorRequests, callbackArgument);
287 public void cancelMonitor(MonitorHandle handler) {
288 client.cancelMonitor(handler);
291 public void lock(String lockId, LockAquisitionCallback lockedCallBack,
292 LockStolenCallback stolenCallback) {
293 client.lock(lockId, lockedCallBack, stolenCallback);
296 public ListenableFuture<Boolean> steal(String lockId) {
297 return client.steal(lockId);
300 public ListenableFuture<Boolean> unLock(String lockId) {
301 return client.unLock(lockId);
304 public boolean isActive() {
305 return client.isActive();
308 public void disconnect() {
312 public DatabaseSchema getDatabaseSchema(String dbName) {
313 return client.getDatabaseSchema(dbName);
316 public <T extends TypedBaseTable<?>> T createTypedRowWrapper(Class<T> klazz) {
317 return client.createTypedRowWrapper(klazz);
320 public <T extends TypedBaseTable<?>> T createTypedRowWrapper(
321 DatabaseSchema dbSchema, Class<T> klazz) {
322 return client.createTypedRowWrapper(dbSchema, klazz);
325 public <T extends TypedBaseTable<?>> T getTypedRowWrapper(Class<T> klazz,
326 Row<GenericTableSchema> row) {
327 return client.getTypedRowWrapper(klazz, row);
330 public OvsdbConnectionInfo getConnectionInfo() {
331 return client.getConnectionInfo();
334 public ConnectionInfo getMDConnectionInfo() {
335 return connectionInfo;
338 public void setMDConnectionInfo(ConnectionInfo key) {
339 this.connectionInfo = key;
342 public InstanceIdentifier<Node> getInstanceIdentifier() {
343 return instanceIdentifier;
346 public NodeKey getNodeKey() {
347 return getInstanceIdentifier().firstKeyOf(Node.class);
350 public NodeId getNodeId() {
351 return getNodeKey().getNodeId();
354 public void setInstanceIdentifier(InstanceIdentifier<Node> iid) {
355 this.instanceIdentifier = iid;
358 public Entity getConnectedEntity() {
359 return this.connectedEntity;
362 public void setConnectedEntity(Entity entity ) {
363 this.connectedEntity = entity;
366 public Boolean hasOvsdbClient(OvsdbClient otherClient) {
367 return client.equals(otherClient);
370 public Boolean getHasDeviceOwnership() {
371 return hasDeviceOwnership;
374 public void setHasDeviceOwnership(Boolean hasDeviceOwnership) {
375 if (hasDeviceOwnership != null) {
376 this.hasDeviceOwnership = hasDeviceOwnership;
380 public void setDeviceOwnershipCandidateRegistration(@Nonnull 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(OvsdbNodeAugmentation ovsdbNodeCreateData) {
396 this.initialCreateData = ovsdbNodeCreateData;
399 public OvsdbClient getOvsdbClient() {