2 * Copyright (c) 2014 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.controller.cluster.datastore;
10 import akka.actor.ActorSelection;
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.Function;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Supplier;
16 import com.google.common.collect.Iterables;
17 import com.google.common.util.concurrent.CheckedFuture;
18 import com.google.common.util.concurrent.Futures;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import com.google.common.util.concurrent.MoreExecutors;
21 import com.google.common.util.concurrent.SettableFuture;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.List;
26 import java.util.Map.Entry;
28 import java.util.TreeMap;
29 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
30 import org.opendaylight.controller.cluster.datastore.messages.AbstractRead;
31 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
32 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
33 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
34 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
35 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
36 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
37 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
38 import org.opendaylight.controller.cluster.datastore.utils.NormalizedNodeAggregator;
39 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
40 import org.opendaylight.controller.sal.core.spi.data.AbstractDOMStoreTransaction;
41 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
42 import org.opendaylight.mdsal.common.api.MappingCheckedFuture;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import scala.concurrent.Future;
49 import scala.concurrent.Promise;
52 * A transaction potentially spanning multiple backend shards.
54 public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIdentifier>
55 implements DOMStoreReadWriteTransaction {
56 private enum TransactionState {
62 private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
64 // Global lock used for transactions spanning multiple shards - synchronizes sending of the ready messages
65 // for atomicity to avoid potential deadlock with concurrent transactions spanning the same shards as outlined
66 // in the following scenario:
68 // - Tx1 sends ready message to shard A
69 // - Tx2 sends ready message to shard A
70 // - Tx2 sends ready message to shard B
71 // - Tx1 sends ready message to shard B
73 // This scenario results in deadlock: after Tx1 canCommits to shard A, it can't proceed with shard B until Tx2
74 // completes as Tx2 was readied first on shard B. However Tx2 cannot make progress because it's waiting to canCommit
75 // on shard A which is blocked by Tx1.
77 // The global lock avoids this as it forces the ready messages to be sent in a predictable order:
79 // - Tx1 sends ready message to shard A
80 // - Tx1 sends ready message to shard B
81 // - Tx2 sends ready message to shard A
82 // - Tx2 sends ready message to shard B
84 private static final Object GLOBAL_TX_READY_LOCK = new Object();
86 private final Map<String, TransactionContextWrapper> txContextWrappers = new TreeMap<>();
87 private final AbstractTransactionContextFactory<?> txContextFactory;
88 private final TransactionType type;
89 private TransactionState state = TransactionState.OPEN;
92 public TransactionProxy(final AbstractTransactionContextFactory<?> txContextFactory, final TransactionType type) {
93 super(txContextFactory.nextIdentifier(), txContextFactory.getActorContext().getDatastoreContext()
94 .isTransactionDebugContextEnabled());
95 this.txContextFactory = txContextFactory;
96 this.type = Preconditions.checkNotNull(type);
98 LOG.debug("New {} Tx - {}", type, getIdentifier());
102 public CheckedFuture<Boolean, ReadFailedException> exists(final YangInstanceIdentifier path) {
103 return executeRead(shardNameFromIdentifier(path), new DataExists(path, DataStoreVersions.CURRENT_VERSION));
106 private <T> CheckedFuture<T, ReadFailedException> executeRead(final String shardName,
107 final AbstractRead<T> readCmd) {
108 Preconditions.checkState(type != TransactionType.WRITE_ONLY,
109 "Reads from write-only transactions are not allowed");
111 LOG.trace("Tx {} {} {}", getIdentifier(), readCmd.getClass().getSimpleName(), readCmd.getPath());
113 final SettableFuture<T> proxyFuture = SettableFuture.create();
114 TransactionContextWrapper contextWrapper = getContextWrapper(shardName);
115 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
117 public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
118 transactionContext.executeRead(readCmd, proxyFuture, havePermit);
122 return MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
126 public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final YangInstanceIdentifier path) {
127 Preconditions.checkState(type != TransactionType.WRITE_ONLY,
128 "Reads from write-only transactions are not allowed");
130 LOG.trace("Tx {} read {}", getIdentifier(), path);
132 if (YangInstanceIdentifier.EMPTY.equals(path)) {
133 return readAllData();
135 return singleShardRead(shardNameFromIdentifier(path), path);
139 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> singleShardRead(
140 final String shardName, final YangInstanceIdentifier path) {
141 return executeRead(shardName, new ReadData(path, DataStoreVersions.CURRENT_VERSION));
144 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readAllData() {
145 final Set<String> allShardNames = txContextFactory.getActorContext().getConfiguration().getAllShardNames();
146 final Collection<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>> futures =
147 new ArrayList<>(allShardNames.size());
149 for (String shardName : allShardNames) {
150 futures.add(singleShardRead(shardName, YangInstanceIdentifier.EMPTY));
153 final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
154 final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;
156 aggregateFuture = Futures.transform(listFuture,
157 (Function<List<Optional<NormalizedNode<?, ?>>>, Optional<NormalizedNode<?, ?>>>) input -> {
159 return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input,
160 txContextFactory.getActorContext().getSchemaContext(),
161 txContextFactory.getActorContext().getDatastoreContext().getLogicalStoreType());
162 } catch (DataValidationFailedException e) {
163 throw new IllegalArgumentException("Failed to aggregate", e);
165 }, MoreExecutors.directExecutor());
167 return MappingCheckedFuture.create(aggregateFuture, ReadFailedException.MAPPER);
171 public void delete(final YangInstanceIdentifier path) {
172 executeModification(new DeleteModification(path));
176 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
177 executeModification(new MergeModification(path, data));
181 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
182 executeModification(new WriteModification(path, data));
185 private void executeModification(final AbstractModification modification) {
186 checkModificationState();
188 LOG.trace("Tx {} executeModification {} {}", getIdentifier(), modification.getClass().getSimpleName(),
189 modification.getPath());
191 TransactionContextWrapper contextWrapper = getContextWrapper(modification.getPath());
192 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
194 protected void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
195 transactionContext.executeModification(modification, havePermit);
200 private void checkModificationState() {
201 Preconditions.checkState(type != TransactionType.READ_ONLY,
202 "Modification operation on read-only transaction is not allowed");
203 Preconditions.checkState(state == TransactionState.OPEN,
204 "Transaction is sealed - further modifications are not allowed");
207 private boolean seal(final TransactionState newState) {
208 if (state == TransactionState.OPEN) {
217 public final void close() {
218 if (!seal(TransactionState.CLOSED)) {
219 Preconditions.checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
221 // Idempotent no-op as per AutoCloseable recommendation
225 for (TransactionContextWrapper contextWrapper : txContextWrappers.values()) {
226 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
228 public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
229 transactionContext.closeTransaction();
235 txContextWrappers.clear();
239 public final AbstractThreePhaseCommitCohort<?> ready() {
240 Preconditions.checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
242 final boolean success = seal(TransactionState.READY);
243 Preconditions.checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
245 LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextWrappers.size());
247 final AbstractThreePhaseCommitCohort<?> ret;
248 switch (txContextWrappers.size()) {
250 ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
253 final Entry<String, TransactionContextWrapper> e = Iterables.getOnlyElement(
254 txContextWrappers.entrySet());
255 ret = createSingleCommitCohort(e.getKey(), e.getValue());
258 ret = createMultiCommitCohort(txContextWrappers.entrySet());
261 txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
263 final Throwable debugContext = getDebugContext();
264 return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
267 @SuppressWarnings({ "rawtypes", "unchecked" })
268 private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
269 final TransactionContextWrapper contextWrapper) {
271 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
273 final OperationCallback.Reference operationCallbackRef =
274 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
276 final TransactionContext transactionContext = contextWrapper.getTransactionContext();
278 if (transactionContext == null) {
279 final Promise promise = akka.dispatch.Futures.promise();
280 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
282 public void invoke(final TransactionContext newTransactionContext, final Boolean havePermit) {
283 promise.completeWith(getDirectCommitFuture(newTransactionContext, operationCallbackRef,
287 future = promise.future();
289 // avoid the creation of a promise and a TransactionOperation
290 future = getDirectCommitFuture(transactionContext, operationCallbackRef, null);
293 return new SingleCommitCohortProxy(txContextFactory.getActorContext(), future, getIdentifier(),
294 operationCallbackRef);
297 private Future<?> getDirectCommitFuture(final TransactionContext transactionContext,
298 final OperationCallback.Reference operationCallbackRef, final Boolean havePermit) {
299 TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
300 txContextFactory.getActorContext());
301 operationCallbackRef.set(rateLimitingCallback);
302 rateLimitingCallback.run();
303 return transactionContext.directCommit(havePermit);
306 private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort(
307 final Set<Entry<String, TransactionContextWrapper>> txContextWrapperEntries) {
309 final List<ThreePhaseCommitCohortProxy.CohortInfo> cohorts = new ArrayList<>(txContextWrapperEntries.size());
311 synchronized (GLOBAL_TX_READY_LOCK) {
312 for (Entry<String, TransactionContextWrapper> e : txContextWrapperEntries) {
313 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
315 final TransactionContextWrapper wrapper = e.getValue();
317 // The remote tx version is obtained the via TransactionContext which may not be available yet so
318 // we pass a Supplier to dynamically obtain it. Once the ready Future is resolved the
319 // TransactionContext is available.
320 Supplier<Short> txVersionSupplier = () -> wrapper.getTransactionContext().getTransactionVersion();
322 cohorts.add(new ThreePhaseCommitCohortProxy.CohortInfo(wrapper.readyTransaction(), txVersionSupplier));
326 return new ThreePhaseCommitCohortProxy(txContextFactory.getActorContext(), cohorts, getIdentifier());
329 private String shardNameFromIdentifier(final YangInstanceIdentifier path) {
330 return txContextFactory.getActorContext().getShardStrategyFactory().getStrategy(path).findShard(path);
333 private TransactionContextWrapper getContextWrapper(final YangInstanceIdentifier path) {
334 return getContextWrapper(shardNameFromIdentifier(path));
337 private TransactionContextWrapper getContextWrapper(final String shardName) {
338 final TransactionContextWrapper existing = txContextWrappers.get(shardName);
339 if (existing != null) {
343 final TransactionContextWrapper fresh = txContextFactory.newTransactionContextWrapper(this, shardName);
344 txContextWrappers.put(shardName, fresh);
348 TransactionType getType() {
353 return state != TransactionState.OPEN;
356 ActorContext getActorContext() {
357 return txContextFactory.getActorContext();