Optimize inflight transitions
[controller.git] / opendaylight / md-sal / sal-dom-broker / src / main / java / org / opendaylight / controller / md / sal / dom / broker / impl / PingPongTransactionChain.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.md.sal.dom.broker.impl;
9
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;
37
38 /**
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.
46  *
47  * This mode of operation means that there is no inherent isolation between
48  * the front-end transactions and transactions cannot be reasonably cancelled.
49  *
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.
53  */
54 public final class PingPongTransactionChain implements DOMTransactionChain {
55     private static final Logger LOG = LoggerFactory.getLogger(PingPongTransactionChain.class);
56     private final DOMTransactionChain delegate;
57
58     @GuardedBy("this")
59     private boolean failed;
60
61     /**
62      * This updater is used to manipulate the "ready" transaction. We perform only atomic
63      * get-and-set on it.
64      */
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;
69
70     /**
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.
75      */
76     private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> LOCKED_UPDATER =
77             AtomicReferenceFieldUpdater.newUpdater(PingPongTransactionChain.class, PingPongTransaction.class, "lockedTx");
78     private volatile PingPongTransaction lockedTx;
79
80     /**
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.
83      */
84     private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> INFLIGHT_UPDATER =
85             AtomicReferenceFieldUpdater.newUpdater(PingPongTransactionChain.class, PingPongTransaction.class, "inflightTx");
86     private volatile PingPongTransaction inflightTx;
87
88     PingPongTransactionChain(final DOMDataBroker broker, final TransactionChainListener listener) {
89         this.delegate = broker.createTransactionChain(new TransactionChainListener() {
90             @Override
91             public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
92                 LOG.debug("Delegate chain {} reported failure in {}", chain, transaction, cause);
93
94                 final DOMDataReadWriteTransaction frontend;
95                 final PingPongTransaction tx = inflightTx;
96                 if (tx == null) {
97                     LOG.warn("Transaction chain {} failed with no pending transactions", chain);
98                     frontend = null;
99                 } else {
100                     frontend = tx.getFrontendTransaction();
101                 }
102
103                 listener.onTransactionChainFailed(PingPongTransactionChain.this, frontend, cause);
104                 delegateFailed();
105             }
106
107             @Override
108             public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
109                 listener.onTransactionChainSuccessful(PingPongTransactionChain.this);
110             }
111         });
112     }
113
114     private synchronized void delegateFailed() {
115         failed = true;
116
117         /*
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.
121          */
122         if (lockedTx == null) {
123             processIfReady();
124         }
125     }
126
127     private synchronized PingPongTransaction slowAllocateTransaction() {
128         final DOMDataReadWriteTransaction delegateTx = delegate.newReadWriteTransaction();
129         final PingPongTransaction newTx = new PingPongTransaction(delegateTx);
130
131         if (!LOCKED_UPDATER.compareAndSet(this, null, newTx)) {
132             delegateTx.cancel();
133             throw new IllegalStateException(String.format("New transaction %s raced with transacion %s", newTx, lockedTx));
134         }
135
136         return newTx;
137     }
138
139     private PingPongTransaction allocateTransaction() {
140         // Step 1: acquire current state
141         final PingPongTransaction oldTx = READY_UPDATER.getAndSet(this, null);
142
143         // Slow path: allocate a delegate transaction
144         if (oldTx == null) {
145             return slowAllocateTransaction();
146         }
147
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));
155         }
156
157         return oldTx;
158     }
159
160     // This forces allocateTransaction() on a slow path
161     @GuardedBy("this")
162     private void processIfReady() {
163         final PingPongTransaction tx = READY_UPDATER.getAndSet(this, null);
164         if (tx != null) {
165             processTransaction(tx);
166         }
167     }
168
169     /**
170      * Process a ready transaction. The caller needs to ensure that
171      * each transaction is seen only once by this method.
172      *
173      * @param tx Transaction which needs processing.
174      */
175     @GuardedBy("this")
176     private void processTransaction(final @Nonnull PingPongTransaction tx) {
177         if (failed) {
178             LOG.debug("Cancelling transaction {}", tx);
179             tx.getTransaction().cancel();
180             return;
181         }
182
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);
186         }
187
188         Futures.addCallback(tx.getTransaction().submit(), new FutureCallback<Void>() {
189             @Override
190             public void onSuccess(final Void result) {
191                 transactionSuccessful(tx, result);
192             }
193
194             @Override
195             public void onFailure(final Throwable t) {
196                 transactionFailed(tx, t);
197             }
198         });
199     }
200
201     private void transactionSuccessful(final PingPongTransaction tx, final Void result) {
202         LOG.debug("Transaction {} completed successfully", tx);
203
204         final boolean success = INFLIGHT_UPDATER.compareAndSet(this, tx, null);
205         Preconditions.checkState(success, "Successful transaction %s while %s was submitted", tx, inflightTx);
206
207         synchronized (this) {
208             processIfReady();
209         }
210
211         // Can run unsynchronized
212         tx.onSuccess(result);
213     }
214
215     private void transactionFailed(final PingPongTransaction tx, final Throwable t) {
216         LOG.debug("Transaction {} failed", tx, t);
217
218         final boolean success = INFLIGHT_UPDATER.compareAndSet(this, tx, null);
219         Preconditions.checkState(success, "Failed transaction %s while %s was submitted", tx, inflightTx);
220
221         tx.onFailure(t);
222     }
223
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);
227
228         LOG.debug("Transaction {} unlocked", tx);
229
230         if (inflightTx == null) {
231             synchronized (this) {
232                 processTransaction(tx);
233             }
234         }
235     }
236
237     @Override
238     public void close() {
239         final PingPongTransaction notLocked = lockedTx;
240         Preconditions.checkState(notLocked == null, "Attempted to close chain with outstanding transaction %s", notLocked);
241
242         synchronized (this) {
243             processIfReady();
244             delegate.close();
245         }
246     }
247
248     @Override
249     public DOMDataReadOnlyTransaction newReadOnlyTransaction() {
250         final PingPongTransaction tx = allocateTransaction();
251
252         return new DOMDataReadOnlyTransaction() {
253             @Override
254             public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
255                     final YangInstanceIdentifier path) {
256                 return tx.getTransaction().read(store, path);
257             }
258
259             @Override
260             public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
261                     final YangInstanceIdentifier path) {
262                 return tx.getTransaction().exists(store, path);
263             }
264
265             @Override
266             public Object getIdentifier() {
267                 return tx.getTransaction().getIdentifier();
268             }
269
270             @Override
271             public void close() {
272                 readyTransaction(tx);
273             }
274         };
275     }
276
277     @Override
278     public DOMDataReadWriteTransaction newReadWriteTransaction() {
279         final PingPongTransaction tx = allocateTransaction();
280         final DOMDataReadWriteTransaction ret = new ForwardingDOMDataReadWriteTransaction() {
281             @Override
282             protected DOMDataReadWriteTransaction delegate() {
283                 return tx.getTransaction();
284             }
285
286             @Override
287             public CheckedFuture<Void, TransactionCommitFailedException> submit() {
288                 readyTransaction(tx);
289                 return tx.getSubmitFuture();
290             }
291
292             @Override
293             public ListenableFuture<RpcResult<TransactionStatus>> commit() {
294                 readyTransaction(tx);
295                 return tx.getCommitFuture();
296             }
297
298             @Override
299             public boolean cancel() {
300                 throw new UnsupportedOperationException("Transaction cancellation is not supported");
301             }
302         };
303
304         tx.recordFrontendTransaction(ret);
305         return ret;
306     }
307
308     @Override
309     public DOMDataWriteTransaction newWriteOnlyTransaction() {
310         return newReadWriteTransaction();
311     }
312 }