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.md.sal.dom.broker.impl;
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.util.concurrent.CheckedFuture;
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
17 import javax.annotation.Nonnull;
18 import javax.annotation.concurrent.GuardedBy;
19 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
20 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
21 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
22 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
23 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
24 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
25 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
26 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
27 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
28 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
29 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
30 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
31 import org.opendaylight.controller.md.sal.dom.spi.ForwardingDOMDataReadWriteTransaction;
32 import org.opendaylight.yangtools.yang.common.RpcResult;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
34 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
39 * An implementation of {@link DOMTransactionChain}, which has a very specific
40 * behavior, which some users may find surprising. If keeps the general
41 * intent of the contract, but it makes sure there are never more than two
42 * transactions allocated at any given time: one of them is being committed,
43 * and while that is happening, the other one acts as the scratch pad. Once
44 * the committing transaction completes successfully, the scratch transaction
45 * is enqueued as soon as it is ready.
47 * This mode of operation means that there is no inherent isolation between
48 * the front-end transactions and transactions cannot be reasonably cancelled.
50 * It furthermore means that the transactions returned by {@link #newReadOnlyTransaction()}
51 * counts as an outstanding transaction and the user may not allocate multiple
52 * read-only transactions at the same time.
54 public final class PingPongTransactionChain implements DOMTransactionChain {
55 private static final Logger LOG = LoggerFactory.getLogger(PingPongTransactionChain.class);
56 private final DOMTransactionChain delegate;
59 private boolean failed;
62 * This updater is used to manipulate the "ready" transaction. We perform only atomic
65 private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> READY_UPDATER =
66 AtomicReferenceFieldUpdater.newUpdater(PingPongTransactionChain.class, PingPongTransaction.class, "readyTx");
67 @SuppressWarnings("unused") // Accessed via READY_UPDATER
68 private volatile PingPongTransaction readyTx;
71 * This updater is used to manipulate the "locked" transaction. A locked transaction
72 * means we know that the user still holds a transaction and should at some point call
73 * us. We perform on compare-and-swap to ensure we properly detect when a user is
74 * attempting to allocated multiple transactions concurrently.
76 private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> LOCKED_UPDATER =
77 AtomicReferenceFieldUpdater.newUpdater(PingPongTransactionChain.class, PingPongTransaction.class, "lockedTx");
78 private volatile PingPongTransaction lockedTx;
81 * This updater is used to manipulate the "inflight" transaction. There can be at most
82 * one of these at any given time. We perform only compare-and-swap on these.
84 private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> INFLIGHT_UPDATER =
85 AtomicReferenceFieldUpdater.newUpdater(PingPongTransactionChain.class, PingPongTransaction.class, "inflightTx");
86 private volatile PingPongTransaction inflightTx;
88 PingPongTransactionChain(final DOMDataBroker broker, final TransactionChainListener listener) {
89 this.delegate = broker.createTransactionChain(new TransactionChainListener() {
91 public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
92 LOG.debug("Delegate chain {} reported failure in {}", chain, transaction, cause);
94 final DOMDataReadWriteTransaction frontend;
95 final PingPongTransaction tx = inflightTx;
97 LOG.warn("Transaction chain {} failed with no pending transactions", chain);
100 frontend = tx.getFrontendTransaction();
103 listener.onTransactionChainFailed(PingPongTransactionChain.this, frontend, cause);
108 public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
109 listener.onTransactionChainSuccessful(PingPongTransactionChain.this);
114 private synchronized void delegateFailed() {
118 * If we do not have a locked transaction, we need to ensure that
119 * the backend transaction is cancelled. Otherwise we can defer
120 * until the user calls us.
122 if (lockedTx == null) {
127 private synchronized PingPongTransaction slowAllocateTransaction() {
128 final DOMDataReadWriteTransaction delegateTx = delegate.newReadWriteTransaction();
129 final PingPongTransaction newTx = new PingPongTransaction(delegateTx);
131 if (!LOCKED_UPDATER.compareAndSet(this, null, newTx)) {
133 throw new IllegalStateException(String.format("New transaction %s raced with transacion %s", newTx, lockedTx));
139 private PingPongTransaction allocateTransaction() {
140 // Step 1: acquire current state
141 final PingPongTransaction oldTx = READY_UPDATER.getAndSet(this, null);
143 // Slow path: allocate a delegate transaction
145 return slowAllocateTransaction();
148 // Fast path: reuse current transaction. We will check
149 // failures and similar on submit().
150 if (!LOCKED_UPDATER.compareAndSet(this, null, oldTx)) {
151 // Ouch. Delegate chain has not detected a duplicate
152 // transaction allocation. This is the best we can do.
153 oldTx.getTransaction().cancel();
154 throw new IllegalStateException(String.format("Reusable transaction %s raced with transaction %s", oldTx, lockedTx));
160 // This forces allocateTransaction() on a slow path
162 private void processIfReady() {
163 final PingPongTransaction tx = READY_UPDATER.getAndSet(this, null);
165 processTransaction(tx);
170 * Process a ready transaction. The caller needs to ensure that
171 * each transaction is seen only once by this method.
173 * @param tx Transaction which needs processing.
176 private void processTransaction(final @Nonnull PingPongTransaction tx) {
178 LOG.debug("Cancelling transaction {}", tx);
179 tx.getTransaction().cancel();
183 LOG.debug("Submitting transaction {}", tx);
184 if (!INFLIGHT_UPDATER.compareAndSet(this, null, tx)) {
185 LOG.warn("Submitting transaction {} while {} is still running", tx, inflightTx);
188 Futures.addCallback(tx.getTransaction().submit(), new FutureCallback<Void>() {
190 public void onSuccess(final Void result) {
191 transactionSuccessful(tx, result);
195 public void onFailure(final Throwable t) {
196 transactionFailed(tx, t);
201 private void transactionSuccessful(final PingPongTransaction tx, final Void result) {
202 LOG.debug("Transaction {} completed successfully", tx);
204 final boolean success = INFLIGHT_UPDATER.compareAndSet(this, tx, null);
205 Preconditions.checkState(success, "Successful transaction %s while %s was submitted", tx, inflightTx);
207 synchronized (this) {
211 // Can run unsynchronized
212 tx.onSuccess(result);
215 private void transactionFailed(final PingPongTransaction tx, final Throwable t) {
216 LOG.debug("Transaction {} failed", tx, t);
218 final boolean success = INFLIGHT_UPDATER.compareAndSet(this, tx, null);
219 Preconditions.checkState(success, "Failed transaction %s while %s was submitted", tx, inflightTx);
224 private void readyTransaction(final @Nonnull PingPongTransaction tx) {
225 final boolean lockedMatch = LOCKED_UPDATER.compareAndSet(this, tx, null);
226 Preconditions.checkState(lockedMatch, "Attempted to submit transaction %s while we have %s", tx, lockedTx);
228 LOG.debug("Transaction {} unlocked", tx);
230 if (inflightTx == null) {
231 synchronized (this) {
232 processTransaction(tx);
238 public void close() {
239 final PingPongTransaction notLocked = lockedTx;
240 Preconditions.checkState(notLocked == null, "Attempted to close chain with outstanding transaction %s", notLocked);
242 synchronized (this) {
249 public DOMDataReadOnlyTransaction newReadOnlyTransaction() {
250 final PingPongTransaction tx = allocateTransaction();
252 return new DOMDataReadOnlyTransaction() {
254 public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
255 final YangInstanceIdentifier path) {
256 return tx.getTransaction().read(store, path);
260 public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
261 final YangInstanceIdentifier path) {
262 return tx.getTransaction().exists(store, path);
266 public Object getIdentifier() {
267 return tx.getTransaction().getIdentifier();
271 public void close() {
272 readyTransaction(tx);
278 public DOMDataReadWriteTransaction newReadWriteTransaction() {
279 final PingPongTransaction tx = allocateTransaction();
280 final DOMDataReadWriteTransaction ret = new ForwardingDOMDataReadWriteTransaction() {
282 protected DOMDataReadWriteTransaction delegate() {
283 return tx.getTransaction();
287 public CheckedFuture<Void, TransactionCommitFailedException> submit() {
288 readyTransaction(tx);
289 return tx.getSubmitFuture();
293 public ListenableFuture<RpcResult<TransactionStatus>> commit() {
294 readyTransaction(tx);
295 return tx.getCommitFuture();
299 public boolean cancel() {
300 throw new UnsupportedOperationException("Transaction cancellation is not supported");
304 tx.recordFrontendTransaction(ret);
309 public DOMDataWriteTransaction newWriteOnlyTransaction() {
310 return newReadWriteTransaction();