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 * The actual implementation of {@link PingPongTransactionChain}. Split out to allow deeper testing while keeping the
43 * externally-visible implementation final.
45 abstract class AbstractPingPongTransactionChain implements DOMTransactionChain {
46 private static final Logger LOG = LoggerFactory.getLogger(AbstractPingPongTransactionChain.class);
48 private final DOMTransactionChainListener listener;
49 private final DOMTransactionChain delegate;
52 private boolean closed;
54 private boolean failed;
56 private PingPongTransaction shutdownTx;
58 private Entry<PingPongTransaction, Throwable> deadTx;
60 // This VarHandle is used to manipulate the "ready" transaction. We perform only atomic get-and-set on it.
61 private static final VarHandle READY_TX;
62 @SuppressWarnings("unused")
63 private volatile PingPongTransaction readyTx;
66 * This VarHandle is used to manipulate the "locked" transaction. A locked transaction means we know that the user
67 * still holds a transaction and should at some point call us. We perform on compare-and-swap to ensure we properly
68 * detect when a user is attempting to allocated multiple transactions concurrently.
70 private static final VarHandle LOCKED_TX;
71 private volatile PingPongTransaction lockedTx;
74 * This updater is used to manipulate the "inflight" transaction. There can be at most one of these at any given
75 * time. We perform only compare-and-swap on these.
77 private static final VarHandle INFLIGHT_TX;
78 private volatile PingPongTransaction inflightTx;
81 final var lookup = MethodHandles.lookup();
83 INFLIGHT_TX = lookup.findVarHandle(AbstractPingPongTransactionChain.class, "inflightTx",
84 PingPongTransaction.class);
85 LOCKED_TX = lookup.findVarHandle(AbstractPingPongTransactionChain.class, "lockedTx",
86 PingPongTransaction.class);
87 READY_TX = lookup.findVarHandle(AbstractPingPongTransactionChain.class, "readyTx",
88 PingPongTransaction.class);
89 } catch (NoSuchFieldException | IllegalAccessException e) {
90 throw new ExceptionInInitializerError(e);
94 AbstractPingPongTransactionChain(final Function<DOMTransactionChainListener, DOMTransactionChain> delegateFactory,
95 final DOMTransactionChainListener listener) {
96 this.listener = requireNonNull(listener);
97 delegate = delegateFactory.apply(new DOMTransactionChainListener() {
99 public void onTransactionChainFailed(final DOMTransactionChain chain,
100 final DOMDataTreeTransaction transaction, final Throwable cause) {
101 LOG.debug("Transaction chain {} reported failure in {}", chain, transaction, cause);
102 delegateFailed(chain, cause);
106 public void onTransactionChainSuccessful(final DOMTransactionChain chain) {
107 delegateSuccessful(chain);
112 private void delegateSuccessful(final DOMTransactionChain chain) {
113 final Entry<PingPongTransaction, Throwable> canceled;
114 synchronized (this) {
115 // This looks weird, but we need not hold the lock while invoking callbacks
119 if (canceled == null) {
120 listener.onTransactionChainSuccessful(this);
124 // Backend shutdown successful, but we have a batch of transactions we have to report as dead due to the
125 // user calling cancel().
126 final PingPongTransaction tx = canceled.getKey();
127 final Throwable cause = canceled.getValue();
128 LOG.debug("Transaction chain {} successful, failing cancelled transaction {}", chain, tx, cause);
130 listener.onTransactionChainFailed(this, tx.getFrontendTransaction(), cause);
134 private void delegateFailed(final DOMTransactionChain chain, final Throwable cause) {
135 final DOMDataTreeReadWriteTransaction frontend;
136 final PingPongTransaction tx = inflightTx;
138 LOG.warn("Transaction chain {} failed with no pending transactions", chain);
141 frontend = tx.getFrontendTransaction();
144 listener.onTransactionChainFailed(this, frontend, cause);
146 synchronized (this) {
150 * If we do not have a locked transaction, we need to ensure that the backend transaction is cancelled.
151 * Otherwise we can defer until the user calls us.
153 if (lockedTx == null) {
159 private synchronized @NonNull PingPongTransaction slowAllocateTransaction() {
160 checkState(shutdownTx == null, "Transaction chain %s has been shut down", this);
162 if (deadTx != null) {
163 throw new IllegalStateException(String.format(
164 "Transaction chain %s has failed due to transaction %s being canceled", this, deadTx.getKey()),
168 final DOMDataTreeReadWriteTransaction delegateTx = delegate.newReadWriteTransaction();
169 final PingPongTransaction newTx = new PingPongTransaction(delegateTx);
171 final Object witness = LOCKED_TX.compareAndExchange(this, null, newTx);
172 if (witness != null) {
174 throw new IllegalStateException(
175 String.format("New transaction %s raced with transaction %s", newTx, witness));
181 private @Nullable PingPongTransaction acquireReadyTx() {
182 return (PingPongTransaction) READY_TX.getAndSet(this, null);
185 private @NonNull PingPongTransaction allocateTransaction() {
186 // Step 1: acquire current state
187 final PingPongTransaction oldTx = acquireReadyTx();
189 // Slow path: allocate a delegate transaction
191 return slowAllocateTransaction();
194 // Fast path: reuse current transaction. We will check failures and similar on commit().
195 final Object witness = LOCKED_TX.compareAndExchange(this, null, oldTx);
196 if (witness != null) {
197 // Ouch. Delegate chain has not detected a duplicate transaction allocation. This is the best we can do.
198 oldTx.getTransaction().cancel();
199 throw new IllegalStateException(String.format("Reusable transaction %s raced with transaction %s", oldTx,
207 * This forces allocateTransaction() on a slow path, which has to happen after this method has completed executing.
208 * Also inflightTx may be updated outside the lock, hence we need to re-check.
211 private void processIfReady() {
212 if (inflightTx == null) {
213 final PingPongTransaction tx = acquireReadyTx();
215 processTransaction(tx);
221 * Process a ready transaction. The caller needs to ensure that each transaction is seen only once by this method.
223 * @param tx Transaction which needs processing.
226 private void processTransaction(final @NonNull PingPongTransaction tx) {
228 LOG.debug("Cancelling transaction {}", tx);
229 tx.getTransaction().cancel();
233 LOG.debug("Submitting transaction {}", tx);
234 final Object witness = INFLIGHT_TX.compareAndExchange(this, null, tx);
235 if (witness != null) {
236 LOG.warn("Submitting transaction {} while {} is still running", tx, witness);
239 tx.getTransaction().commit().addCallback(new FutureCallback<CommitInfo>() {
241 public void onSuccess(final CommitInfo result) {
242 transactionSuccessful(tx, result);
246 public void onFailure(final Throwable throwable) {
247 transactionFailed(tx, throwable);
249 }, MoreExecutors.directExecutor());
253 * We got invoked from the data store thread. We need to do two things:
254 * 1) release the in-flight transaction
255 * 2) process the potential next transaction
257 * We have to perform 2) under lock. We could perform 1) without locking, but that means the CAS result may
258 * not be accurate, as a user thread may submit the ready transaction before we acquire the lock -- and checking
259 * for next transaction is not enough, as that may have also be allocated (as a result of a quick
260 * submit/allocate/submit between 1) and 2)). Hence we'd end up doing the following:
261 * 1) CAS of inflightTx
263 * 3) volatile read of inflightTx
265 * Rather than doing that, we keep this method synchronized, hence performing only:
267 * 2) CAS of inflightTx
269 * Since the user thread is barred from submitting the transaction (in processIfReady), we can then proceed with
270 * the knowledge that inflightTx is null -- processTransaction() will still do a CAS, but that is only for
273 private synchronized void processNextTransaction(final PingPongTransaction tx) {
274 final Object witness = INFLIGHT_TX.compareAndExchange(this, tx, null);
275 checkState(witness == tx, "Completed transaction %s while %s was submitted", tx, witness);
277 final PingPongTransaction nextTx = acquireReadyTx();
278 if (nextTx == null) {
279 final PingPongTransaction local = shutdownTx;
281 processTransaction(local);
286 processTransaction(nextTx);
290 private void transactionSuccessful(final PingPongTransaction tx, final CommitInfo result) {
291 LOG.debug("Transaction {} completed successfully", tx);
293 tx.onSuccess(result);
294 processNextTransaction(tx);
297 private void transactionFailed(final PingPongTransaction tx, final Throwable throwable) {
298 LOG.debug("Transaction {} failed", tx, throwable);
300 tx.onFailure(throwable);
301 processNextTransaction(tx);
304 private void readyTransaction(final @NonNull PingPongTransaction tx) {
305 // First mark the transaction as not locked.
306 final Object lockedWitness = LOCKED_TX.compareAndExchange(this, tx, null);
307 checkState(lockedWitness == tx, "Attempted to submit transaction %s while we have %s", tx, lockedWitness);
308 LOG.debug("Transaction {} unlocked", tx);
311 * The transaction is ready. It will then be picked up by either next allocation,
312 * or a background transaction completion callback.
314 final Object readyWitness = READY_TX.compareAndExchange(this, null, tx);
315 checkState(readyWitness == null, "Transaction %s collided on ready state with %s", tx, readyWitness);
316 LOG.debug("Transaction {} readied", tx);
319 * We do not see a transaction being in-flight, so we need to take care of dispatching
320 * the transaction to the backend. We are in the ready case, we cannot short-cut
321 * the checking of readyTx, as an in-flight transaction may have completed between us
322 * setting the field above and us checking.
324 if (inflightTx == null) {
325 synchronized (this) {
332 * Transaction cancellation is a heavyweight operation. We only support cancelation of a locked transaction
333 * and return false for everything else. Cancelling such a transaction will result in all transactions in the
334 * batch to be cancelled.
336 * @param tx Backend shared transaction
337 * @param frontendTx transaction
338 * @return {@code true} if the transaction was cancelled successfully
340 private synchronized boolean cancelTransaction(final PingPongTransaction tx,
341 final DOMDataTreeReadWriteTransaction frontendTx) {
342 // Attempt to unlock the operation.
343 final Object witness = LOCKED_TX.compareAndExchange(this, tx, null);
344 verify(witness == tx, "Cancelling transaction %s collided with locked transaction %s", tx, witness);
346 // Cancel the backend transaction, so we do not end up leaking it.
347 final boolean backendCancelled = tx.getTransaction().cancel();
350 // The transaction has failed, this is probably the user just clearing up the transaction they had. We have
351 // already cancelled the transaction anyway,
355 // We have dealt with cancelling the backend transaction and have unlocked the transaction. Since we are still
356 // inside the synchronized block, any allocations are blocking on the slow path. Now we have to decide the fate
357 // of this transaction chain.
359 // If there are no other frontend transactions in this batch we are aligned with backend state and we can
360 // continue processing.
361 if (frontendTx.equals(tx.getFrontendTransaction())) {
362 if (backendCancelled) {
363 LOG.debug("Cancelled transaction {} was head of the batch, resuming processing", tx);
367 // Backend refused to cancel the transaction. Reinstate it to locked state.
368 final Object reinstateWitness = LOCKED_TX.compareAndExchange(this, null, tx);
369 verify(reinstateWitness == null, "Reinstating transaction %s collided with locked transaction %s", tx,
374 if (!backendCancelled) {
375 LOG.warn("Backend transaction cannot be cancelled during cancellation of {}, attempting to continue", tx);
378 // There are multiple frontend transactions in this batch. We have to report them as failed, which dooms this
379 // transaction chain, too. Since we just came off of a locked transaction, we do not have a ready transaction
380 // at the moment, but there may be some transaction in-flight. So we proceed to shutdown the backend chain
381 // and mark the fact that we should be turning its completion into a failure.
382 deadTx = Map.entry(tx, new CancellationException("Transaction " + frontendTx + " canceled").fillInStackTrace());
388 public final synchronized void close() {
390 LOG.debug("Attempted to close an already-closed chain");
394 // Note: we do not derive from AbstractRegistration due to ordering of this check
395 final var notLocked = lockedTx;
396 if (notLocked != null) {
397 throw new IllegalStateException("Attempted to close chain with outstanding transaction " + notLocked);
401 // This may be a reaction to our failure callback, in that case the backend is already shutdown
402 if (deadTx != null) {
403 LOG.debug("Delegate {} is already closed due to failure {}", delegate, deadTx);
407 // Force allocations on slow path, picking up a potentially-outstanding transaction
408 final var tx = acquireReadyTx();
410 // We have one more transaction, which needs to be processed somewhere. If we do not
411 // a transaction in-flight, we need to push it down ourselves.
412 // If there is an in-flight transaction we will schedule this last one into a dedicated
413 // slot. Allocation slow path will check its presence and fail, the in-flight path will
414 // pick it up, submit and immediately close the chain.
415 if (inflightTx == null) {
416 processTransaction(tx);
422 // Nothing outstanding, we can safely shutdown
428 public final DOMDataTreeReadTransaction newReadOnlyTransaction() {
429 return new PingPongReadTransaction(allocateTransaction());
433 public final DOMDataTreeReadWriteTransaction newReadWriteTransaction() {
434 final PingPongTransaction tx = allocateTransaction();
435 final DOMDataTreeReadWriteTransaction ret = new PingPongReadWriteTransaction(tx);
436 tx.recordFrontendTransaction(ret);
441 public final DOMDataTreeWriteTransaction newWriteOnlyTransaction() {
442 return newReadWriteTransaction();
445 private final class PingPongReadTransaction implements DOMDataTreeReadTransaction {
446 private final @NonNull PingPongTransaction tx;
448 PingPongReadTransaction(final PingPongTransaction tx) {
449 this.tx = requireNonNull(tx);
453 public FluentFuture<Optional<NormalizedNode>> read(final LogicalDatastoreType store,
454 final YangInstanceIdentifier path) {
455 return tx.getTransaction().read(store, path);
459 public FluentFuture<Boolean> exists(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
460 return tx.getTransaction().exists(store, path);
464 public Object getIdentifier() {
465 return tx.getTransaction().getIdentifier();
469 public void close() {
470 readyTransaction(tx);
474 private final class PingPongReadWriteTransaction extends ForwardingDOMDataReadWriteTransaction {
475 private final @NonNull PingPongTransaction tx;
477 private boolean isOpen = true;
479 PingPongReadWriteTransaction(final PingPongTransaction tx) {
480 this.tx = requireNonNull(tx);
484 public FluentFuture<? extends CommitInfo> commit() {
485 readyTransaction(tx);
487 return tx.getCommitFuture().transform(ignored -> CommitInfo.empty(), MoreExecutors.directExecutor());
491 public boolean cancel() {
492 if (isOpen && cancelTransaction(tx, this)) {
500 protected DOMDataTreeReadWriteTransaction delegate() {
501 return tx.getTransaction();