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;
13 import static org.opendaylight.mdsal.dom.spi.PingPongTransactionChain.LOG;
15 import com.google.common.util.concurrent.FluentFuture;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.MoreExecutors;
18 import java.lang.invoke.MethodHandles;
19 import java.lang.invoke.VarHandle;
21 import java.util.Map.Entry;
22 import java.util.Optional;
23 import java.util.concurrent.CancellationException;
24 import java.util.function.Function;
25 import org.checkerframework.checker.lock.qual.GuardedBy;
26 import org.checkerframework.checker.lock.qual.Holding;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.opendaylight.mdsal.common.api.CommitInfo;
30 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
31 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
32 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
33 import org.opendaylight.mdsal.dom.api.DOMDataTreeTransaction;
34 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
35 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
36 import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
41 * The actual implementation of {@link PingPongTransactionChain}. Split out to allow deeper testing while keeping the
42 * externally-visible implementation final.
44 abstract class AbstractPingPongTransactionChain implements DOMTransactionChain {
45 private final DOMTransactionChainListener listener;
46 private final DOMTransactionChain delegate;
49 private boolean closed;
51 private boolean failed;
53 private PingPongTransaction shutdownTx;
55 private Entry<PingPongTransaction, Throwable> deadTx;
57 // This VarHandle is used to manipulate the "ready" transaction. We perform only atomic get-and-set on it.
58 private static final VarHandle READY_TX;
59 @SuppressWarnings("unused")
60 private volatile PingPongTransaction readyTx;
63 * This VarHandle is used to manipulate the "locked" transaction. A locked transaction means we know that the user
64 * still holds a transaction and should at some point call us. We perform on compare-and-swap to ensure we properly
65 * detect when a user is attempting to allocated multiple transactions concurrently.
67 private static final VarHandle LOCKED_TX;
68 private volatile PingPongTransaction lockedTx;
71 * This updater is used to manipulate the "inflight" transaction. There can be at most one of these at any given
72 * time. We perform only compare-and-swap on these.
74 private static final VarHandle INFLIGHT_TX;
75 private volatile PingPongTransaction inflightTx;
78 final var lookup = MethodHandles.lookup();
80 INFLIGHT_TX = lookup.findVarHandle(AbstractPingPongTransactionChain.class, "inflightTx",
81 PingPongTransaction.class);
82 LOCKED_TX = lookup.findVarHandle(AbstractPingPongTransactionChain.class, "lockedTx",
83 PingPongTransaction.class);
84 READY_TX = lookup.findVarHandle(AbstractPingPongTransactionChain.class, "readyTx",
85 PingPongTransaction.class);
86 } catch (NoSuchFieldException | IllegalAccessException e) {
87 throw new ExceptionInInitializerError(e);
91 AbstractPingPongTransactionChain(final Function<DOMTransactionChainListener, DOMTransactionChain> delegateFactory,
92 final DOMTransactionChainListener listener) {
93 this.listener = requireNonNull(listener);
94 delegate = delegateFactory.apply(new DOMTransactionChainListener() {
96 public void onTransactionChainFailed(final DOMTransactionChain chain,
97 final DOMDataTreeTransaction transaction, final Throwable cause) {
98 LOG.debug("Transaction chain {} reported failure in {}", chain, transaction, cause);
99 delegateFailed(chain, cause);
103 public void onTransactionChainSuccessful(final DOMTransactionChain chain) {
104 delegateSuccessful(chain);
109 private void delegateSuccessful(final DOMTransactionChain chain) {
110 final Entry<PingPongTransaction, Throwable> canceled;
111 synchronized (this) {
112 // This looks weird, but we need not hold the lock while invoking callbacks
116 if (canceled == null) {
117 listener.onTransactionChainSuccessful(this);
121 // Backend shutdown successful, but we have a batch of transactions we have to report as dead due to the
122 // user calling cancel().
123 final PingPongTransaction tx = canceled.getKey();
124 final Throwable cause = canceled.getValue();
125 LOG.debug("Transaction chain {} successful, failing cancelled transaction {}", chain, tx, cause);
127 listener.onTransactionChainFailed(this, tx.getFrontendTransaction(), cause);
131 private void delegateFailed(final DOMTransactionChain chain, final Throwable cause) {
132 final DOMDataTreeReadWriteTransaction frontend;
133 final PingPongTransaction tx = inflightTx;
135 LOG.warn("Transaction chain {} failed with no pending transactions", chain);
138 frontend = tx.getFrontendTransaction();
141 listener.onTransactionChainFailed(this, frontend, cause);
143 synchronized (this) {
147 * If we do not have a locked transaction, we need to ensure that the backend transaction is cancelled.
148 * Otherwise we can defer until the user calls us.
150 if (lockedTx == null) {
156 private synchronized @NonNull PingPongTransaction slowAllocateTransaction() {
157 checkState(shutdownTx == null, "Transaction chain %s has been shut down", this);
159 if (deadTx != null) {
160 throw new IllegalStateException(String.format(
161 "Transaction chain %s has failed due to transaction %s being canceled", this, deadTx.getKey()),
165 final DOMDataTreeReadWriteTransaction delegateTx = delegate.newReadWriteTransaction();
166 final PingPongTransaction newTx = new PingPongTransaction(delegateTx);
168 final Object witness = LOCKED_TX.compareAndExchange(this, null, newTx);
169 if (witness != null) {
171 throw new IllegalStateException(
172 String.format("New transaction %s raced with transaction %s", newTx, witness));
178 private @Nullable PingPongTransaction acquireReadyTx() {
179 return (PingPongTransaction) READY_TX.getAndSet(this, null);
182 private @NonNull PingPongTransaction allocateTransaction() {
183 // Step 1: acquire current state
184 final PingPongTransaction oldTx = acquireReadyTx();
186 // Slow path: allocate a delegate transaction
188 return slowAllocateTransaction();
191 // Fast path: reuse current transaction. We will check failures and similar on commit().
192 final Object witness = LOCKED_TX.compareAndExchange(this, null, oldTx);
193 if (witness != null) {
194 // Ouch. Delegate chain has not detected a duplicate transaction allocation. This is the best we can do.
195 oldTx.getTransaction().cancel();
196 throw new IllegalStateException(String.format("Reusable transaction %s raced with transaction %s", oldTx,
204 * This forces allocateTransaction() on a slow path, which has to happen after this method has completed executing.
205 * Also inflightTx may be updated outside the lock, hence we need to re-check.
208 private void processIfReady() {
209 if (inflightTx == null) {
210 final PingPongTransaction tx = acquireReadyTx();
212 processTransaction(tx);
218 * Process a ready transaction. The caller needs to ensure that each transaction is seen only once by this method.
220 * @param tx Transaction which needs processing.
223 private void processTransaction(final @NonNull PingPongTransaction tx) {
225 LOG.debug("Cancelling transaction {}", tx);
226 tx.getTransaction().cancel();
230 LOG.debug("Submitting transaction {}", tx);
231 final Object witness = INFLIGHT_TX.compareAndExchange(this, null, tx);
232 if (witness != null) {
233 LOG.warn("Submitting transaction {} while {} is still running", tx, witness);
236 tx.getTransaction().commit().addCallback(new FutureCallback<CommitInfo>() {
238 public void onSuccess(final CommitInfo result) {
239 transactionSuccessful(tx, result);
243 public void onFailure(final Throwable throwable) {
244 transactionFailed(tx, throwable);
246 }, MoreExecutors.directExecutor());
250 * We got invoked from the data store thread. We need to do two things:
251 * 1) release the in-flight transaction
252 * 2) process the potential next transaction
254 * We have to perform 2) under lock. We could perform 1) without locking, but that means the CAS result may
255 * not be accurate, as a user thread may submit the ready transaction before we acquire the lock -- and checking
256 * for next transaction is not enough, as that may have also be allocated (as a result of a quick
257 * submit/allocate/submit between 1) and 2)). Hence we'd end up doing the following:
258 * 1) CAS of inflightTx
260 * 3) volatile read of inflightTx
262 * Rather than doing that, we keep this method synchronized, hence performing only:
264 * 2) CAS of inflightTx
266 * Since the user thread is barred from submitting the transaction (in processIfReady), we can then proceed with
267 * the knowledge that inflightTx is null -- processTransaction() will still do a CAS, but that is only for
270 private synchronized void processNextTransaction(final PingPongTransaction tx) {
271 final Object witness = INFLIGHT_TX.compareAndExchange(this, tx, null);
272 checkState(witness == tx, "Completed transaction %s while %s was submitted", tx, witness);
274 final PingPongTransaction nextTx = acquireReadyTx();
275 if (nextTx == null) {
276 final PingPongTransaction local = shutdownTx;
278 processTransaction(local);
283 processTransaction(nextTx);
287 private void transactionSuccessful(final PingPongTransaction tx, final CommitInfo result) {
288 LOG.debug("Transaction {} completed successfully", tx);
290 tx.onSuccess(result);
291 processNextTransaction(tx);
294 private void transactionFailed(final PingPongTransaction tx, final Throwable throwable) {
295 LOG.debug("Transaction {} failed", tx, throwable);
297 tx.onFailure(throwable);
298 processNextTransaction(tx);
301 private void readyTransaction(final @NonNull PingPongTransaction tx) {
302 // First mark the transaction as not locked.
303 final Object lockedWitness = LOCKED_TX.compareAndExchange(this, tx, null);
304 checkState(lockedWitness == tx, "Attempted to submit transaction %s while we have %s", tx, lockedWitness);
305 LOG.debug("Transaction {} unlocked", tx);
308 * The transaction is ready. It will then be picked up by either next allocation,
309 * or a background transaction completion callback.
311 final Object readyWitness = READY_TX.compareAndExchange(this, null, tx);
312 checkState(readyWitness == null, "Transaction %s collided on ready state with %s", tx, readyWitness);
313 LOG.debug("Transaction {} readied", tx);
316 * We do not see a transaction being in-flight, so we need to take care of dispatching
317 * the transaction to the backend. We are in the ready case, we cannot short-cut
318 * the checking of readyTx, as an in-flight transaction may have completed between us
319 * setting the field above and us checking.
321 if (inflightTx == null) {
322 synchronized (this) {
329 * Transaction cancellation is a heavyweight operation. We only support cancelation of a locked transaction
330 * and return false for everything else. Cancelling such a transaction will result in all transactions in the
331 * batch to be cancelled.
333 * @param tx Backend shared transaction
334 * @param frontendTx transaction
335 * @return {@code true} if the transaction was cancelled successfully
337 private synchronized boolean cancelTransaction(final PingPongTransaction tx,
338 final DOMDataTreeReadWriteTransaction frontendTx) {
339 // Attempt to unlock the operation.
340 final Object witness = LOCKED_TX.compareAndExchange(this, tx, null);
341 verify(witness == tx, "Cancelling transaction %s collided with locked transaction %s", tx, witness);
343 // Cancel the backend transaction, so we do not end up leaking it.
344 final boolean backendCancelled = tx.getTransaction().cancel();
347 // The transaction has failed, this is probably the user just clearing up the transaction they had. We have
348 // already cancelled the transaction anyway,
352 // We have dealt with cancelling the backend transaction and have unlocked the transaction. Since we are still
353 // inside the synchronized block, any allocations are blocking on the slow path. Now we have to decide the fate
354 // of this transaction chain.
356 // If there are no other frontend transactions in this batch we are aligned with backend state and we can
357 // continue processing.
358 if (frontendTx.equals(tx.getFrontendTransaction())) {
359 if (backendCancelled) {
360 LOG.debug("Cancelled transaction {} was head of the batch, resuming processing", tx);
364 // Backend refused to cancel the transaction. Reinstate it to locked state.
365 final Object reinstateWitness = LOCKED_TX.compareAndExchange(this, null, tx);
366 verify(reinstateWitness == null, "Reinstating transaction %s collided with locked transaction %s", tx,
371 if (!backendCancelled) {
372 LOG.warn("Backend transaction cannot be cancelled during cancellation of {}, attempting to continue", tx);
375 // There are multiple frontend transactions in this batch. We have to report them as failed, which dooms this
376 // transaction chain, too. Since we just came off of a locked transaction, we do not have a ready transaction
377 // at the moment, but there may be some transaction in-flight. So we proceed to shutdown the backend chain
378 // and mark the fact that we should be turning its completion into a failure.
379 deadTx = Map.entry(tx, new CancellationException("Transaction " + frontendTx + " canceled").fillInStackTrace());
385 public final synchronized void close() {
387 LOG.debug("Attempted to close an already-closed chain");
391 // Note: we do not derive from AbstractRegistration due to ordering of this check
392 final var notLocked = lockedTx;
393 if (notLocked != null) {
394 throw new IllegalStateException("Attempted to close chain with outstanding transaction " + notLocked);
398 // This may be a reaction to our failure callback, in that case the backend is already shutdown
399 if (deadTx != null) {
400 LOG.debug("Delegate {} is already closed due to failure {}", delegate, deadTx);
404 // Force allocations on slow path, picking up a potentially-outstanding transaction
405 final var tx = acquireReadyTx();
407 // We have one more transaction, which needs to be processed somewhere. If we do not
408 // a transaction in-flight, we need to push it down ourselves.
409 // If there is an in-flight transaction we will schedule this last one into a dedicated
410 // slot. Allocation slow path will check its presence and fail, the in-flight path will
411 // pick it up, submit and immediately close the chain.
412 if (inflightTx == null) {
413 processTransaction(tx);
419 // Nothing outstanding, we can safely shutdown
425 public final DOMDataTreeReadTransaction newReadOnlyTransaction() {
426 return new PingPongReadTransaction(allocateTransaction());
430 public final DOMDataTreeReadWriteTransaction newReadWriteTransaction() {
431 final PingPongTransaction tx = allocateTransaction();
432 final DOMDataTreeReadWriteTransaction ret = new PingPongReadWriteTransaction(tx);
433 tx.recordFrontendTransaction(ret);
438 public final DOMDataTreeWriteTransaction newWriteOnlyTransaction() {
439 return newReadWriteTransaction();
442 private final class PingPongReadTransaction implements DOMDataTreeReadTransaction {
443 private final @NonNull PingPongTransaction tx;
445 PingPongReadTransaction(final PingPongTransaction tx) {
446 this.tx = requireNonNull(tx);
450 public FluentFuture<Optional<NormalizedNode>> read(final LogicalDatastoreType store,
451 final YangInstanceIdentifier path) {
452 return tx.getTransaction().read(store, path);
456 public FluentFuture<Boolean> exists(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
457 return tx.getTransaction().exists(store, path);
461 public Object getIdentifier() {
462 return tx.getTransaction().getIdentifier();
466 public void close() {
467 readyTransaction(tx);
471 private final class PingPongReadWriteTransaction extends ForwardingDOMDataReadWriteTransaction {
472 private final @NonNull PingPongTransaction tx;
474 private boolean isOpen = true;
476 PingPongReadWriteTransaction(final PingPongTransaction tx) {
477 this.tx = requireNonNull(tx);
481 public FluentFuture<? extends CommitInfo> commit() {
482 readyTransaction(tx);
484 return tx.getCommitFuture().transform(ignored -> CommitInfo.empty(), MoreExecutors.directExecutor());
488 public boolean cancel() {
489 if (isOpen && cancelTransaction(tx, this)) {
497 protected DOMDataTreeReadWriteTransaction delegate() {
498 return tx.getTransaction();