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.broker.pingpong;
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.util.AbstractMap.SimpleImmutableEntry;
18 import java.util.Map.Entry;
19 import java.util.Optional;
20 import java.util.concurrent.CancellationException;
21 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
22 import javax.annotation.concurrent.GuardedBy;
23 import org.eclipse.jdt.annotation.NonNull;
24 import org.opendaylight.mdsal.common.api.CommitInfo;
25 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
26 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
27 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
28 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
29 import org.opendaylight.mdsal.dom.api.DOMDataTreeTransaction;
30 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
31 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
32 import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
33 import org.opendaylight.mdsal.dom.spi.ForwardingDOMDataReadWriteTransaction;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
40 * An implementation of {@link DOMTransactionChain}, which has a very specific
41 * behavior, which some users may find surprising. If keeps the general
42 * intent of the contract, but it makes sure there are never more than two
43 * transactions allocated at any given time: one of them is being committed,
44 * and while that is happening, the other one acts as the scratch pad. Once
45 * the committing transaction completes successfully, the scratch transaction
46 * is enqueued as soon as it is ready.
49 * This mode of operation means that there is no inherent isolation between
50 * the front-end transactions and transactions cannot be reasonably cancelled.
53 * It furthermore means that the transactions returned by {@link #newReadOnlyTransaction()}
54 * counts as an outstanding transaction and the user may not allocate multiple
55 * read-only transactions at the same time.
57 public final class PingPongTransactionChain implements DOMTransactionChain {
58 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;
70 * This updater is used to manipulate the "ready" transaction. We perform only atomic
73 private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> READY_UPDATER =
74 AtomicReferenceFieldUpdater.newUpdater(PingPongTransactionChain.class, PingPongTransaction.class,
76 private volatile PingPongTransaction readyTx;
79 * This updater is used to manipulate the "locked" transaction. A locked transaction
80 * means we know that the user still holds a transaction and should at some point call
81 * us. We perform on compare-and-swap to ensure we properly detect when a user is
82 * attempting to allocated multiple transactions concurrently.
84 private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> LOCKED_UPDATER
85 = AtomicReferenceFieldUpdater
86 .newUpdater(PingPongTransactionChain.class, PingPongTransaction.class, "lockedTx");
87 private volatile PingPongTransaction lockedTx;
90 * This updater is used to manipulate the "inflight" transaction. There can be at most
91 * one of these at any given time. We perform only compare-and-swap on these.
93 private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> INFLIGHT_UPDATER
94 = AtomicReferenceFieldUpdater
95 .newUpdater(PingPongTransactionChain.class, PingPongTransaction.class, "inflightTx");
96 private volatile PingPongTransaction inflightTx;
98 PingPongTransactionChain(final DOMDataBroker broker, final DOMTransactionChainListener listener) {
99 this.listener = requireNonNull(listener);
100 this.delegate = broker.createTransactionChain(new DOMTransactionChainListener() {
102 public void onTransactionChainFailed(final DOMTransactionChain chain,
103 final DOMDataTreeTransaction transaction, final Throwable cause) {
104 LOG.debug("Transaction chain {} reported failure in {}", chain, transaction, cause);
105 delegateFailed(chain, cause);
109 public void onTransactionChainSuccessful(final DOMTransactionChain chain) {
110 delegateSuccessful(chain);
115 void delegateSuccessful(final DOMTransactionChain chain) {
116 final Entry<PingPongTransaction, Throwable> canceled;
117 synchronized (this) {
118 // This looks weird, but we need not hold the lock while invoking callbacks
122 if (canceled == null) {
123 listener.onTransactionChainSuccessful(this);
127 // Backend shutdown successful, but we have a batch of transactions we have to report as dead due to the
128 // user calling cancel().
129 final PingPongTransaction tx = canceled.getKey();
130 final Throwable cause = canceled.getValue();
131 LOG.debug("Transaction chain {} successful, failing cancelled transaction {}", chain, tx, cause);
133 listener.onTransactionChainFailed(this, tx.getFrontendTransaction(), cause);
137 void delegateFailed(final DOMTransactionChain chain, final Throwable cause) {
139 final DOMDataTreeReadWriteTransaction frontend;
140 final PingPongTransaction tx = inflightTx;
142 LOG.warn("Transaction chain {} failed with no pending transactions", chain);
145 frontend = tx.getFrontendTransaction();
148 listener.onTransactionChainFailed(this, frontend, cause);
150 synchronized (this) {
154 * If we do not have a locked transaction, we need to ensure that
155 * the backend transaction is cancelled. Otherwise we can defer
156 * until the user calls us.
158 if (lockedTx == null) {
164 private synchronized @NonNull PingPongTransaction slowAllocateTransaction() {
165 checkState(shutdownTx == null, "Transaction chain %s has been shut down", this);
167 if (deadTx != null) {
168 throw new IllegalStateException(
169 String.format("Transaction chain %s has failed due to transaction %s being canceled", this,
170 deadTx.getKey()), deadTx.getValue());
173 final DOMDataTreeReadWriteTransaction delegateTx = delegate.newReadWriteTransaction();
174 final PingPongTransaction newTx = new PingPongTransaction(delegateTx);
176 if (!LOCKED_UPDATER.compareAndSet(this, null, newTx)) {
178 throw new IllegalStateException(
179 String.format("New transaction %s raced with transaction %s", newTx, lockedTx));
185 private @NonNull PingPongTransaction allocateTransaction() {
186 // Step 1: acquire current state
187 final PingPongTransaction oldTx = READY_UPDATER.getAndSet(this, null);
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 if (!LOCKED_UPDATER.compareAndSet(this, null, oldTx)) {
196 // Ouch. Delegate chain has not detected a duplicate transaction allocation. This is the best we can do.
197 oldTx.getTransaction().cancel();
198 throw new IllegalStateException(
199 String.format("Reusable transaction %s raced with transaction %s", oldTx, lockedTx));
206 * This forces allocateTransaction() on a slow path, which has to happen after
207 * this method has completed executing. Also inflightTx may be updated outside
208 * the lock, hence we need to re-check.
211 private void processIfReady() {
212 if (inflightTx == null) {
213 final PingPongTransaction tx = READY_UPDATER.getAndSet(this, null);
215 processTransaction(tx);
221 * Process a ready transaction. The caller needs to ensure that
222 * each transaction is seen only once by this method.
224 * @param tx Transaction which needs processing.
227 private void processTransaction(final @NonNull PingPongTransaction tx) {
229 LOG.debug("Cancelling transaction {}", tx);
230 tx.getTransaction().cancel();
234 LOG.debug("Submitting transaction {}", tx);
235 if (!INFLIGHT_UPDATER.compareAndSet(this, null, tx)) {
236 LOG.warn("Submitting transaction {} while {} is still running", tx, inflightTx);
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 boolean success = INFLIGHT_UPDATER.compareAndSet(this, tx, null);
275 checkState(success, "Completed transaction %s while %s was submitted", tx, inflightTx);
277 final PingPongTransaction nextTx = READY_UPDATER.getAndSet(this, null);
278 if (nextTx != null) {
279 processTransaction(nextTx);
280 } else if (shutdownTx != null) {
281 processTransaction(shutdownTx);
287 void transactionSuccessful(final PingPongTransaction tx, final CommitInfo result) {
288 LOG.debug("Transaction {} completed successfully", tx);
290 tx.onSuccess(result);
291 processNextTransaction(tx);
294 void transactionFailed(final PingPongTransaction tx, final Throwable throwable) {
295 LOG.debug("Transaction {} failed", tx, throwable);
297 tx.onFailure(throwable);
298 processNextTransaction(tx);
301 void readyTransaction(final @NonNull PingPongTransaction tx) {
302 // First mark the transaction as not locked.
303 final boolean lockedMatch = LOCKED_UPDATER.compareAndSet(this, tx, null);
304 checkState(lockedMatch, "Attempted to submit transaction %s while we have %s", tx, lockedTx);
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 boolean success = READY_UPDATER.compareAndSet(this, null, tx);
312 checkState(success, "Transaction %s collided on ready state", tx, readyTx);
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 * @param isOpen indicator whether the transaction was already closed
337 synchronized void cancelTransaction(final PingPongTransaction tx,
338 final DOMDataTreeReadWriteTransaction frontendTx) {
339 // Attempt to unlock the operation.
340 final boolean lockedMatch = LOCKED_UPDATER.compareAndSet(this, tx, null);
341 verify(lockedMatch, "Cancelling transaction %s collided with locked transaction %s", tx, lockedTx);
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,
350 } else if (!backendCancelled) {
351 LOG.warn("Backend transaction cannot be cancelled during cancellation of {}, attempting to continue", tx);
354 // We have dealt with canceling the backend transaction and have unlocked the transaction. Since we are still
355 // inside the synchronized block, any allocations are blocking on the slow path. Now we have to decide the fate
356 // of this transaction chain.
358 // If there are no other frontend transactions in this batch we are aligned with backend state and we can
359 // continue processing.
360 if (frontendTx.equals(tx.getFrontendTransaction())) {
361 LOG.debug("Cancelled transaction {} was head of the batch, resuming processing", tx);
365 // There are multiple frontend transactions in this batch. We have to report them as failed, which dooms this
366 // transaction chain, too. Since we just came off of a locked transaction, we do not have a ready transaction
367 // at the moment, but there may be some transaction in-flight. So we proceed to shutdown the backend chain
368 // and mark the fact that we should be turning its completion into a failure.
369 deadTx = new SimpleImmutableEntry<>(tx, new CancellationException("Transaction " + frontendTx + " canceled")
370 .fillInStackTrace());
375 public synchronized void close() {
376 final PingPongTransaction notLocked = lockedTx;
377 checkState(notLocked == null, "Attempted to close chain with outstanding transaction %s", notLocked);
379 // This is not reliable, but if we observe it to be null and the process has already completed,
380 // the backend transaction chain will throw the appropriate error.
381 checkState(shutdownTx == null, "Attempted to close an already-closed chain");
383 // This may be a reaction to our failure callback, in that case the backend is already shutdown
384 if (deadTx != null) {
385 LOG.debug("Delegate {} is already closed due to failure {}", delegate, deadTx);
389 // Force allocations on slow path, picking up a potentially-outstanding transaction
390 final PingPongTransaction tx = READY_UPDATER.getAndSet(this, null);
393 // We have one more transaction, which needs to be processed somewhere. If we do not
394 // a transaction in-flight, we need to push it down ourselves.
395 // If there is an in-flight transaction we will schedule this last one into a dedicated
396 // slot. Allocation slow path will check its presence and fail, the in-flight path will
397 // pick it up, submit and immediately close the chain.
398 if (inflightTx == null) {
399 processTransaction(tx);
405 // Nothing outstanding, we can safely shutdown
411 public DOMDataTreeReadTransaction newReadOnlyTransaction() {
412 final PingPongTransaction tx = allocateTransaction();
414 return new DOMDataTreeReadTransaction() {
416 public FluentFuture<Optional<NormalizedNode<?, ?>>> read(
417 final LogicalDatastoreType store, final YangInstanceIdentifier path) {
418 return tx.getTransaction().read(store, path);
422 public FluentFuture<Boolean> exists(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
423 return tx.getTransaction().exists(store, path);
427 public Object getIdentifier() {
428 return tx.getTransaction().getIdentifier();
432 public void close() {
433 readyTransaction(tx);
439 public DOMDataTreeReadWriteTransaction newReadWriteTransaction() {
440 final PingPongTransaction tx = allocateTransaction();
441 final DOMDataTreeReadWriteTransaction ret = new ForwardingDOMDataReadWriteTransaction() {
442 private boolean isOpen = true;
445 protected DOMDataTreeReadWriteTransaction delegate() {
446 return tx.getTransaction();
450 public FluentFuture<? extends CommitInfo> commit() {
451 readyTransaction(tx);
453 return tx.getCommitFuture().transform(ignored -> CommitInfo.empty(), MoreExecutors.directExecutor());
457 public boolean cancel() {
459 cancelTransaction(tx, this);
468 public void close() {
469 // TODO Auto-generated method stub
474 tx.recordFrontendTransaction(ret);
479 public DOMDataTreeWriteTransaction newWriteOnlyTransaction() {
480 return newReadWriteTransaction();