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.mdsal.dom.spi;
10 import static com.google.common.base.Preconditions.checkState;
11 import static com.google.common.base.Verify.verify;
12 import static java.util.Objects.requireNonNull;
14 import com.google.common.util.concurrent.FluentFuture;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.MoreExecutors;
17 import java.lang.invoke.MethodHandles;
18 import java.lang.invoke.VarHandle;
20 import java.util.Map.Entry;
21 import java.util.Optional;
22 import java.util.concurrent.CancellationException;
23 import java.util.function.Function;
24 import org.checkerframework.checker.lock.qual.GuardedBy;
25 import org.checkerframework.checker.lock.qual.Holding;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.opendaylight.mdsal.common.api.CommitInfo;
29 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
30 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
31 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
32 import org.opendaylight.mdsal.dom.api.DOMDataTreeTransaction;
33 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
34 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
35 import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
42 * An implementation of {@link DOMTransactionChain}, which has a very specific behavior, which some users may find
43 * surprising. If keeps the general intent of the contract, but it makes sure there are never more than two transactions
44 * allocated at any given time: one of them is being committed, and while that is happening, the other one acts as
45 * a scratch pad. Once the committing transaction completes successfully, the scratch transaction is enqueued as soon as
49 * This mode of operation means that there is no inherent isolation between the front-end transactions and transactions
50 * cannot be reasonably cancelled.
53 * It furthermore means that the transactions returned by {@link #newReadOnlyTransaction()} counts as an outstanding
54 * transaction and the user may not allocate multiple read-only transactions at the same time.
56 public final class PingPongTransactionChain implements DOMTransactionChain {
57 private static final Logger LOG = LoggerFactory.getLogger(PingPongTransactionChain.class);
59 private final DOMTransactionChainListener listener;
60 private final DOMTransactionChain delegate;
63 private boolean failed;
65 private PingPongTransaction shutdownTx;
67 private Entry<PingPongTransaction, Throwable> deadTx;
69 // This VarHandle is used to manipulate the "ready" transaction. We perform only atomic get-and-set on it.
70 private static final VarHandle READY_TX;
71 @SuppressWarnings("unused")
72 private volatile PingPongTransaction readyTx;
75 * This VarHandle is used to manipulate the "locked" transaction. A locked transaction means we know that the user
76 * still holds a transaction and should at some point call us. We perform on compare-and-swap to ensure we properly
77 * detect when a user is attempting to allocated multiple transactions concurrently.
79 private static final VarHandle LOCKED_TX;
80 private volatile PingPongTransaction lockedTx;
83 * This updater is used to manipulate the "inflight" transaction. There can be at most one of these at any given
84 * time. We perform only compare-and-swap on these.
86 private static final VarHandle INFLIGHT_TX;
87 private volatile PingPongTransaction inflightTx;
90 final var lookup = MethodHandles.lookup();
92 INFLIGHT_TX = lookup.findVarHandle(PingPongTransactionChain.class, "inflightTx", PingPongTransaction.class);
93 LOCKED_TX = lookup.findVarHandle(PingPongTransactionChain.class, "lockedTx", PingPongTransaction.class);
94 READY_TX = lookup.findVarHandle(PingPongTransactionChain.class, "readyTx", PingPongTransaction.class);
95 } catch (NoSuchFieldException | IllegalAccessException e) {
96 throw new ExceptionInInitializerError(e);
100 public PingPongTransactionChain(final Function<DOMTransactionChainListener, DOMTransactionChain> delegateFactory,
101 final DOMTransactionChainListener listener) {
102 this.listener = requireNonNull(listener);
103 delegate = delegateFactory.apply(new DOMTransactionChainListener() {
105 public void onTransactionChainFailed(final DOMTransactionChain chain,
106 final DOMDataTreeTransaction transaction, final Throwable cause) {
107 LOG.debug("Transaction chain {} reported failure in {}", chain, transaction, cause);
108 delegateFailed(chain, cause);
112 public void onTransactionChainSuccessful(final DOMTransactionChain chain) {
113 delegateSuccessful(chain);
118 void delegateSuccessful(final DOMTransactionChain chain) {
119 final Entry<PingPongTransaction, Throwable> canceled;
120 synchronized (this) {
121 // This looks weird, but we need not hold the lock while invoking callbacks
125 if (canceled == null) {
126 listener.onTransactionChainSuccessful(this);
130 // Backend shutdown successful, but we have a batch of transactions we have to report as dead due to the
131 // user calling cancel().
132 final PingPongTransaction tx = canceled.getKey();
133 final Throwable cause = canceled.getValue();
134 LOG.debug("Transaction chain {} successful, failing cancelled transaction {}", chain, tx, cause);
136 listener.onTransactionChainFailed(this, tx.getFrontendTransaction(), cause);
140 void delegateFailed(final DOMTransactionChain chain, final Throwable cause) {
142 final DOMDataTreeReadWriteTransaction frontend;
143 final PingPongTransaction tx = inflightTx;
145 LOG.warn("Transaction chain {} failed with no pending transactions", chain);
148 frontend = tx.getFrontendTransaction();
151 listener.onTransactionChainFailed(this, frontend, cause);
153 synchronized (this) {
157 * If we do not have a locked transaction, we need to ensure that the backend transaction is cancelled.
158 * Otherwise we can defer until the user calls us.
160 if (lockedTx == null) {
166 private synchronized @NonNull PingPongTransaction slowAllocateTransaction() {
167 checkState(shutdownTx == null, "Transaction chain %s has been shut down", this);
169 if (deadTx != null) {
170 throw new IllegalStateException(String.format(
171 "Transaction chain %s has failed due to transaction %s being canceled", this, deadTx.getKey()),
175 final DOMDataTreeReadWriteTransaction delegateTx = delegate.newReadWriteTransaction();
176 final PingPongTransaction newTx = new PingPongTransaction(delegateTx);
178 final Object witness = LOCKED_TX.compareAndExchange(this, null, newTx);
179 if (witness != null) {
181 throw new IllegalStateException(
182 String.format("New transaction %s raced with transaction %s", newTx, witness));
188 private @Nullable PingPongTransaction acquireReadyTx() {
189 return (PingPongTransaction) READY_TX.getAndSet(this, null);
192 private @NonNull PingPongTransaction allocateTransaction() {
193 // Step 1: acquire current state
194 final PingPongTransaction oldTx = acquireReadyTx();
196 // Slow path: allocate a delegate transaction
198 return slowAllocateTransaction();
201 // Fast path: reuse current transaction. We will check failures and similar on commit().
202 final Object witness = LOCKED_TX.compareAndExchange(this, null, oldTx);
203 if (witness != null) {
204 // Ouch. Delegate chain has not detected a duplicate transaction allocation. This is the best we can do.
205 oldTx.getTransaction().cancel();
206 throw new IllegalStateException(String.format("Reusable transaction %s raced with transaction %s", oldTx,
214 * This forces allocateTransaction() on a slow path, which has to happen after this method has completed executing.
215 * Also inflightTx may be updated outside the lock, hence we need to re-check.
218 private void processIfReady() {
219 if (inflightTx == null) {
220 final PingPongTransaction tx = acquireReadyTx();
222 processTransaction(tx);
228 * Process a ready transaction. The caller needs to ensure that each transaction is seen only once by this method.
230 * @param tx Transaction which needs processing.
233 private void processTransaction(final @NonNull PingPongTransaction tx) {
235 LOG.debug("Cancelling transaction {}", tx);
236 tx.getTransaction().cancel();
240 LOG.debug("Submitting transaction {}", tx);
241 final Object witness = INFLIGHT_TX.compareAndExchange(this, null, tx);
242 if (witness != null) {
243 LOG.warn("Submitting transaction {} while {} is still running", tx, witness);
246 tx.getTransaction().commit().addCallback(new FutureCallback<CommitInfo>() {
248 public void onSuccess(final CommitInfo result) {
249 transactionSuccessful(tx, result);
253 public void onFailure(final Throwable throwable) {
254 transactionFailed(tx, throwable);
256 }, MoreExecutors.directExecutor());
260 * We got invoked from the data store thread. We need to do two things:
261 * 1) release the in-flight transaction
262 * 2) process the potential next transaction
264 * We have to perform 2) under lock. We could perform 1) without locking, but that means the CAS result may
265 * not be accurate, as a user thread may submit the ready transaction before we acquire the lock -- and checking
266 * for next transaction is not enough, as that may have also be allocated (as a result of a quick
267 * submit/allocate/submit between 1) and 2)). Hence we'd end up doing the following:
268 * 1) CAS of inflightTx
270 * 3) volatile read of inflightTx
272 * Rather than doing that, we keep this method synchronized, hence performing only:
274 * 2) CAS of inflightTx
276 * Since the user thread is barred from submitting the transaction (in processIfReady), we can then proceed with
277 * the knowledge that inflightTx is null -- processTransaction() will still do a CAS, but that is only for
280 private synchronized void processNextTransaction(final PingPongTransaction tx) {
281 final Object witness = INFLIGHT_TX.compareAndExchange(this, tx, null);
282 checkState(witness == tx, "Completed transaction %s while %s was submitted", tx, witness);
284 final PingPongTransaction nextTx = acquireReadyTx();
285 if (nextTx == null) {
286 final PingPongTransaction local = shutdownTx;
288 processTransaction(local);
293 processTransaction(nextTx);
297 void transactionSuccessful(final PingPongTransaction tx, final CommitInfo result) {
298 LOG.debug("Transaction {} completed successfully", tx);
300 tx.onSuccess(result);
301 processNextTransaction(tx);
304 void transactionFailed(final PingPongTransaction tx, final Throwable throwable) {
305 LOG.debug("Transaction {} failed", tx, throwable);
307 tx.onFailure(throwable);
308 processNextTransaction(tx);
311 void readyTransaction(final @NonNull PingPongTransaction tx) {
312 // First mark the transaction as not locked.
313 final Object lockedWitness = LOCKED_TX.compareAndExchange(this, tx, null);
314 checkState(lockedWitness == tx, "Attempted to submit transaction %s while we have %s", tx, lockedWitness);
315 LOG.debug("Transaction {} unlocked", tx);
318 * The transaction is ready. It will then be picked up by either next allocation,
319 * or a background transaction completion callback.
321 final Object readyWitness = READY_TX.compareAndExchange(this, null, tx);
322 checkState(readyWitness == null, "Transaction %s collided on ready state with %s", tx, readyWitness);
323 LOG.debug("Transaction {} readied", tx);
326 * We do not see a transaction being in-flight, so we need to take care of dispatching
327 * the transaction to the backend. We are in the ready case, we cannot short-cut
328 * the checking of readyTx, as an in-flight transaction may have completed between us
329 * setting the field above and us checking.
331 if (inflightTx == null) {
332 synchronized (this) {
339 * Transaction cancellation is a heavyweight operation. We only support cancelation of a locked transaction
340 * and return false for everything else. Cancelling such a transaction will result in all transactions in the
341 * batch to be cancelled.
343 * @param tx Backend shared transaction
344 * @param frontendTx transaction
345 * @return {@code true} if the transaction was cancelled successfully
347 synchronized boolean cancelTransaction(final PingPongTransaction tx,
348 final DOMDataTreeReadWriteTransaction frontendTx) {
349 // Attempt to unlock the operation.
350 final Object witness = LOCKED_TX.compareAndExchange(this, tx, null);
351 verify(witness == tx, "Cancelling transaction %s collided with locked transaction %s", tx, witness);
353 // Cancel the backend transaction, so we do not end up leaking it.
354 final boolean backendCancelled = tx.getTransaction().cancel();
357 // The transaction has failed, this is probably the user just clearing up the transaction they had. We have
358 // already cancelled the transaction anyway,
362 // We have dealt with cancelling the backend transaction and have unlocked the transaction. Since we are still
363 // inside the synchronized block, any allocations are blocking on the slow path. Now we have to decide the fate
364 // of this transaction chain.
366 // If there are no other frontend transactions in this batch we are aligned with backend state and we can
367 // continue processing.
368 if (frontendTx.equals(tx.getFrontendTransaction())) {
369 if (backendCancelled) {
370 LOG.debug("Cancelled transaction {} was head of the batch, resuming processing", tx);
374 // Backend refused to cancel the transaction. Reinstate it to locked state.
375 final Object reinstateWitness = LOCKED_TX.compareAndExchange(this, null, tx);
376 verify(reinstateWitness == null, "Reinstating transaction %s collided with locked transaction %s", tx,
381 if (!backendCancelled) {
382 LOG.warn("Backend transaction cannot be cancelled during cancellation of {}, attempting to continue", tx);
385 // There are multiple frontend transactions in this batch. We have to report them as failed, which dooms this
386 // transaction chain, too. Since we just came off of a locked transaction, we do not have a ready transaction
387 // at the moment, but there may be some transaction in-flight. So we proceed to shutdown the backend chain
388 // and mark the fact that we should be turning its completion into a failure.
389 deadTx = Map.entry(tx, new CancellationException("Transaction " + frontendTx + " canceled").fillInStackTrace());
395 public synchronized void close() {
396 final PingPongTransaction notLocked = lockedTx;
397 checkState(notLocked == null, "Attempted to close chain with outstanding transaction %s", notLocked);
399 // This is not reliable, but if we observe it to be null and the process has already completed,
400 // the backend transaction chain will throw the appropriate error.
401 checkState(shutdownTx == null, "Attempted to close an already-closed chain");
403 // This may be a reaction to our failure callback, in that case the backend is already shutdown
404 if (deadTx != null) {
405 LOG.debug("Delegate {} is already closed due to failure {}", delegate, deadTx);
409 // Force allocations on slow path, picking up a potentially-outstanding transaction
410 final PingPongTransaction tx = acquireReadyTx();
413 // We have one more transaction, which needs to be processed somewhere. If we do not
414 // a transaction in-flight, we need to push it down ourselves.
415 // If there is an in-flight transaction we will schedule this last one into a dedicated
416 // slot. Allocation slow path will check its presence and fail, the in-flight path will
417 // pick it up, submit and immediately close the chain.
418 if (inflightTx == null) {
419 processTransaction(tx);
425 // Nothing outstanding, we can safely shutdown
431 public DOMDataTreeReadTransaction newReadOnlyTransaction() {
432 return new PingPongReadTransaction(allocateTransaction());
436 public DOMDataTreeReadWriteTransaction newReadWriteTransaction() {
437 final PingPongTransaction tx = allocateTransaction();
438 final DOMDataTreeReadWriteTransaction ret = new PingPongReadWriteTransaction(tx);
439 tx.recordFrontendTransaction(ret);
444 public DOMDataTreeWriteTransaction newWriteOnlyTransaction() {
445 return newReadWriteTransaction();
448 private final class PingPongReadTransaction implements DOMDataTreeReadTransaction {
449 private final @NonNull PingPongTransaction tx;
451 PingPongReadTransaction(final PingPongTransaction tx) {
452 this.tx = requireNonNull(tx);
456 public FluentFuture<Optional<NormalizedNode>> read(final LogicalDatastoreType store,
457 final YangInstanceIdentifier path) {
458 return tx.getTransaction().read(store, path);
462 public FluentFuture<Boolean> exists(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
463 return tx.getTransaction().exists(store, path);
467 public Object getIdentifier() {
468 return tx.getTransaction().getIdentifier();
472 public void close() {
473 readyTransaction(tx);
477 private final class PingPongReadWriteTransaction extends ForwardingDOMDataReadWriteTransaction {
478 private final @NonNull PingPongTransaction tx;
480 private boolean isOpen = true;
482 PingPongReadWriteTransaction(final PingPongTransaction tx) {
483 this.tx = requireNonNull(tx);
487 public FluentFuture<? extends CommitInfo> commit() {
488 readyTransaction(tx);
490 return tx.getCommitFuture().transform(ignored -> CommitInfo.empty(), MoreExecutors.directExecutor());
494 public boolean cancel() {
495 if (isOpen && cancelTransaction(tx, this)) {
503 protected DOMDataTreeReadWriteTransaction delegate() {
504 return tx.getTransaction();