4a6ea67ebdfa531b48363a6934b39ed3dfb568b3
[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.base.Verify;
13 import com.google.common.util.concurrent.CheckedFuture;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import com.google.common.util.concurrent.MoreExecutors;
18 import java.util.AbstractMap.SimpleImmutableEntry;
19 import java.util.Map.Entry;
20 import java.util.concurrent.CancellationException;
21 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
22 import javax.annotation.Nonnull;
23 import javax.annotation.concurrent.GuardedBy;
24 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
25 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
26 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
27 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
28 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
29 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
30 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
31 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
32 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
33 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
34 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
35 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
36 import org.opendaylight.controller.md.sal.dom.spi.ForwardingDOMDataReadWriteTransaction;
37 import org.opendaylight.yangtools.yang.common.RpcResult;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
39 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * An implementation of {@link DOMTransactionChain}, which has a very specific
45  * behavior, which some users may find surprising. If keeps the general
46  * intent of the contract, but it makes sure there are never more than two
47  * transactions allocated at any given time: one of them is being committed,
48  * and while that is happening, the other one acts as the scratch pad. Once
49  * the committing transaction completes successfully, the scratch transaction
50  * is enqueued as soon as it is ready.
51  *
52  * <p>
53  * This mode of operation means that there is no inherent isolation between
54  * the front-end transactions and transactions cannot be reasonably cancelled.
55  *
56  * <p>
57  * It furthermore means that the transactions returned by {@link #newReadOnlyTransaction()}
58  * counts as an outstanding transaction and the user may not allocate multiple
59  * read-only transactions at the same time.
60  */
61 public final class PingPongTransactionChain implements DOMTransactionChain {
62     private static final Logger LOG = LoggerFactory.getLogger(PingPongTransactionChain.class);
63     private final TransactionChainListener listener;
64     private final DOMTransactionChain delegate;
65
66     @GuardedBy("this")
67     private boolean failed;
68     @GuardedBy("this")
69     private PingPongTransaction shutdownTx;
70     @GuardedBy("this")
71     private Entry<PingPongTransaction, Throwable> deadTx;
72
73     /**
74      * This updater is used to manipulate the "ready" transaction. We perform only atomic
75      * get-and-set on it.
76      */
77     private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> READY_UPDATER
78             = AtomicReferenceFieldUpdater
79             .newUpdater(PingPongTransactionChain.class, PingPongTransaction.class, "readyTx");
80     private volatile PingPongTransaction readyTx;
81
82     /**
83      * This updater is used to manipulate the "locked" transaction. A locked transaction
84      * means we know that the user still holds a transaction and should at some point call
85      * us. We perform on compare-and-swap to ensure we properly detect when a user is
86      * attempting to allocated multiple transactions concurrently.
87      */
88     private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> LOCKED_UPDATER
89             = AtomicReferenceFieldUpdater
90             .newUpdater(PingPongTransactionChain.class, PingPongTransaction.class, "lockedTx");
91     private volatile PingPongTransaction lockedTx;
92
93     /**
94      * This updater is used to manipulate the "inflight" transaction. There can be at most
95      * one of these at any given time. We perform only compare-and-swap on these.
96      */
97     private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> INFLIGHT_UPDATER
98             = AtomicReferenceFieldUpdater
99             .newUpdater(PingPongTransactionChain.class, PingPongTransaction.class, "inflightTx");
100     private volatile PingPongTransaction inflightTx;
101
102     PingPongTransactionChain(final DOMDataBroker broker, final TransactionChainListener listener) {
103         this.listener = Preconditions.checkNotNull(listener);
104         this.delegate = broker.createTransactionChain(new TransactionChainListener() {
105             @Override
106             public void onTransactionChainFailed(final TransactionChain<?, ?> chain,
107                                                  final AsyncTransaction<?, ?> transaction, final Throwable cause) {
108                 LOG.debug("Transaction chain {} reported failure in {}", chain, transaction, cause);
109                 delegateFailed(chain, cause);
110             }
111
112             @Override
113             public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
114                 delegateSuccessful(chain);
115             }
116         });
117     }
118
119     void delegateSuccessful(final TransactionChain<?, ?> chain) {
120         final Entry<PingPongTransaction, Throwable> canceled;
121         synchronized (this) {
122             // This looks weird, but we need not hold the lock while invoking callbacks
123             canceled = deadTx;
124         }
125
126         if (canceled == null) {
127             listener.onTransactionChainSuccessful(this);
128             return;
129         }
130
131         // Backend shutdown successful, but we have a batch of transactions we have to report as dead due to the
132         // user calling cancel().
133         final PingPongTransaction tx = canceled.getKey();
134         final Throwable cause = canceled.getValue();
135         LOG.debug("Transaction chain {} successful, failing cancelled transaction {}", chain, tx, cause);
136
137         listener.onTransactionChainFailed(this, tx.getFrontendTransaction(), cause);
138         tx.onFailure(cause);
139     }
140
141     void delegateFailed(final TransactionChain<?, ?> chain, final Throwable cause) {
142
143         final DOMDataReadWriteTransaction frontend;
144         final PingPongTransaction tx = inflightTx;
145         if (tx == null) {
146             LOG.warn("Transaction chain {} failed with no pending transactions", chain);
147             frontend = null;
148         } else {
149             frontend = tx.getFrontendTransaction();
150         }
151
152         listener.onTransactionChainFailed(this, frontend, cause);
153
154         synchronized (this) {
155             failed = true;
156
157             /*
158              * If we do not have a locked transaction, we need to ensure that
159              * the backend transaction is cancelled. Otherwise we can defer
160              * until the user calls us.
161              */
162             if (lockedTx == null) {
163                 processIfReady();
164             }
165         }
166     }
167
168     private synchronized PingPongTransaction slowAllocateTransaction() {
169         Preconditions.checkState(shutdownTx == null, "Transaction chain %s has been shut down", this);
170
171         if (deadTx != null) {
172             throw new IllegalStateException(
173                     String.format("Transaction chain %s has failed due to transaction %s being canceled", this,
174                                   deadTx.getKey()), deadTx.getValue());
175         }
176
177         final DOMDataReadWriteTransaction delegateTx = delegate.newReadWriteTransaction();
178         final PingPongTransaction newTx = new PingPongTransaction(delegateTx);
179
180         if (!LOCKED_UPDATER.compareAndSet(this, null, newTx)) {
181             delegateTx.cancel();
182             throw new IllegalStateException(
183                     String.format("New transaction %s raced with transaction %s", newTx, lockedTx));
184         }
185
186         return newTx;
187     }
188
189     private PingPongTransaction allocateTransaction() {
190         // Step 1: acquire current state
191         final PingPongTransaction oldTx = READY_UPDATER.getAndSet(this, null);
192
193         // Slow path: allocate a delegate transaction
194         if (oldTx == null) {
195             return slowAllocateTransaction();
196         }
197
198         // Fast path: reuse current transaction. We will check failures and similar on submit().
199         if (!LOCKED_UPDATER.compareAndSet(this, null, oldTx)) {
200             // Ouch. Delegate chain has not detected a duplicate transaction allocation. This is the best we can do.
201             oldTx.getTransaction().cancel();
202             throw new IllegalStateException(
203                     String.format("Reusable transaction %s raced with transaction %s", oldTx, lockedTx));
204         }
205
206         return oldTx;
207     }
208
209     /*
210      * This forces allocateTransaction() on a slow path, which has to happen after
211      * this method has completed executing. Also inflightTx may be updated outside
212      * the lock, hence we need to re-check.
213      */
214     @GuardedBy("this")
215     private void processIfReady() {
216         if (inflightTx == null) {
217             final PingPongTransaction tx = READY_UPDATER.getAndSet(this, null);
218             if (tx != null) {
219                 processTransaction(tx);
220             }
221         }
222     }
223
224     /**
225      * Process a ready transaction. The caller needs to ensure that
226      * each transaction is seen only once by this method.
227      *
228      * @param tx Transaction which needs processing.
229      */
230     @GuardedBy("this")
231     private void processTransaction(@Nonnull final PingPongTransaction tx) {
232         if (failed) {
233             LOG.debug("Cancelling transaction {}", tx);
234             tx.getTransaction().cancel();
235             return;
236         }
237
238         LOG.debug("Submitting transaction {}", tx);
239         if (!INFLIGHT_UPDATER.compareAndSet(this, null, tx)) {
240             LOG.warn("Submitting transaction {} while {} is still running", tx, inflightTx);
241         }
242
243         Futures.addCallback(tx.getTransaction().submit(), new FutureCallback<Void>() {
244             @Override
245             public void onSuccess(final Void result) {
246                 transactionSuccessful(tx, result);
247             }
248
249             @Override
250             public void onFailure(final Throwable throwable) {
251                 transactionFailed(tx, throwable);
252             }
253         }, MoreExecutors.directExecutor());
254     }
255
256     /*
257      * We got invoked from the data store thread. We need to do two things:
258      * 1) release the in-flight transaction
259      * 2) process the potential next transaction
260      *
261      * We have to perform 2) under lock. We could perform 1) without locking, but that means the CAS result may
262      * not be accurate, as a user thread may submit the ready transaction before we acquire the lock -- and checking
263      * for next transaction is not enough, as that may have also be allocated (as a result of a quick
264      * submit/allocate/submit between 1) and 2)). Hence we'd end up doing the following:
265      * 1) CAS of inflightTx
266      * 2) take lock
267      * 3) volatile read of inflightTx
268      *
269      * Rather than doing that, we keep this method synchronized, hence performing only:
270      * 1) take lock
271      * 2) CAS of inflightTx
272      *
273      * Since the user thread is barred from submitting the transaction (in processIfReady), we can then proceed with
274      * the knowledge that inflightTx is null -- processTransaction() will still do a CAS, but that is only for
275      * correctness.
276      */
277     private synchronized void processNextTransaction(final PingPongTransaction tx) {
278         final boolean success = INFLIGHT_UPDATER.compareAndSet(this, tx, null);
279         Preconditions.checkState(success, "Completed transaction %s while %s was submitted", tx, inflightTx);
280
281         final PingPongTransaction nextTx = READY_UPDATER.getAndSet(this, null);
282         if (nextTx != null) {
283             processTransaction(nextTx);
284         } else if (shutdownTx != null) {
285             processTransaction(shutdownTx);
286             delegate.close();
287             shutdownTx = null;
288         }
289     }
290
291     void transactionSuccessful(final PingPongTransaction tx, final Void result) {
292         LOG.debug("Transaction {} completed successfully", tx);
293
294         tx.onSuccess(result);
295         processNextTransaction(tx);
296     }
297
298     void transactionFailed(final PingPongTransaction tx, final Throwable throwable) {
299         LOG.debug("Transaction {} failed", tx, throwable);
300
301         tx.onFailure(throwable);
302         processNextTransaction(tx);
303     }
304
305     void readyTransaction(@Nonnull final PingPongTransaction tx) {
306         // First mark the transaction as not locked.
307         final boolean lockedMatch = LOCKED_UPDATER.compareAndSet(this, tx, null);
308         Preconditions.checkState(lockedMatch, "Attempted to submit transaction %s while we have %s", tx, lockedTx);
309         LOG.debug("Transaction {} unlocked", tx);
310
311         /*
312          * The transaction is ready. It will then be picked up by either next allocation,
313          * or a background transaction completion callback.
314          */
315         final boolean success = READY_UPDATER.compareAndSet(this, null, tx);
316         Preconditions.checkState(success, "Transaction %s collided on ready state", tx, readyTx);
317         LOG.debug("Transaction {} readied", tx);
318
319         /*
320          * We do not see a transaction being in-flight, so we need to take care of dispatching
321          * the transaction to the backend. We are in the ready case, we cannot short-cut
322          * the checking of readyTx, as an in-flight transaction may have completed between us
323          * setting the field above and us checking.
324          */
325         if (inflightTx == null) {
326             synchronized (this) {
327                 processIfReady();
328             }
329         }
330     }
331
332     /**
333      * Transaction cancellation is a heavyweight operation. We only support cancelation of a locked transaction
334      * and return false for everything else. Cancelling such a transaction will result in all transactions in the
335      * batch to be cancelled.
336      *
337      * @param tx         Backend shared transaction
338      * @param frontendTx transaction
339      * @param isOpen     indicator whether the transaction was already closed
340      */
341     synchronized void cancelTransaction(final PingPongTransaction tx, final DOMDataReadWriteTransaction frontendTx) {
342         // Attempt to unlock the operation.
343         final boolean lockedMatch = LOCKED_UPDATER.compareAndSet(this, tx, null);
344         Verify.verify(lockedMatch, "Cancelling transaction %s collided with locked transaction %s", tx, lockedTx);
345
346         // Cancel the backend transaction, so we do not end up leaking it.
347         final boolean backendCancelled = tx.getTransaction().cancel();
348
349         if (failed) {
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,
352             return;
353         } else if (!backendCancelled) {
354             LOG.warn("Backend transaction cannot be cancelled during cancellation of {}, attempting to continue", tx);
355         }
356
357         // We have dealt with canceling the backend transaction and have unlocked the transaction. Since we are still
358         // inside the synchronized block, any allocations are blocking on the slow path. Now we have to decide the fate
359         // of this transaction chain.
360         //
361         // If there are no other frontend transactions in this batch we are aligned with backend state and we can
362         // continue processing.
363         if (frontendTx.equals(tx.getFrontendTransaction())) {
364             LOG.debug("Cancelled transaction {} was head of the batch, resuming processing", tx);
365             return;
366         }
367
368         // There are multiple frontend transactions in this batch. We have to report them as failed, which dooms this
369         // transaction chain, too. Since we just came off of a locked transaction, we do not have a ready transaction
370         // at the moment, but there may be some transaction in-flight. So we proceed to shutdown the backend chain
371         // and mark the fact that we should be turning its completion into a failure.
372         deadTx = new SimpleImmutableEntry<>(tx, new CancellationException("Transaction " + frontendTx + " canceled")
373                 .fillInStackTrace());
374         delegate.close();
375     }
376
377     @Override
378     public synchronized void close() {
379         final PingPongTransaction notLocked = lockedTx;
380         Preconditions
381                 .checkState(notLocked == null, "Attempted to close chain with outstanding transaction %s", notLocked);
382
383         // This is not reliable, but if we observe it to be null and the process has already completed,
384         // the backend transaction chain will throw the appropriate error.
385         Preconditions.checkState(shutdownTx == null, "Attempted to close an already-closed chain");
386
387         // This may be a reaction to our failure callback, in that case the backend is already shutdown
388         if (deadTx != null) {
389             LOG.debug("Delegate {} is already closed due to failure {}", delegate, deadTx);
390             return;
391         }
392
393         // Force allocations on slow path, picking up a potentially-outstanding transaction
394         final PingPongTransaction tx = READY_UPDATER.getAndSet(this, null);
395
396         if (tx != null) {
397             // We have one more transaction, which needs to be processed somewhere. If we do not
398             // a transaction in-flight, we need to push it down ourselves.
399             // If there is an in-flight transaction we will schedule this last one into a dedicated
400             // slot. Allocation slow path will check its presence and fail, the in-flight path will
401             // pick it up, submit and immediately close the chain.
402             if (inflightTx == null) {
403                 processTransaction(tx);
404                 delegate.close();
405             } else {
406                 shutdownTx = tx;
407             }
408         } else {
409             // Nothing outstanding, we can safely shutdown
410             delegate.close();
411         }
412     }
413
414     @Override
415     public DOMDataReadOnlyTransaction newReadOnlyTransaction() {
416         final PingPongTransaction tx = allocateTransaction();
417
418         return new DOMDataReadOnlyTransaction() {
419             @Override
420             public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(
421                     final LogicalDatastoreType store, final YangInstanceIdentifier path) {
422                 return tx.getTransaction().read(store, path);
423             }
424
425             @Override
426             public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
427                                                                       final YangInstanceIdentifier path) {
428                 return tx.getTransaction().exists(store, path);
429             }
430
431             @Override
432             public Object getIdentifier() {
433                 return tx.getTransaction().getIdentifier();
434             }
435
436             @Override
437             public void close() {
438                 readyTransaction(tx);
439             }
440         };
441     }
442
443     @Override
444     public DOMDataReadWriteTransaction newReadWriteTransaction() {
445         final PingPongTransaction tx = allocateTransaction();
446         final DOMDataReadWriteTransaction ret = new ForwardingDOMDataReadWriteTransaction() {
447             private boolean isOpen = true;
448
449             @Override
450             protected DOMDataReadWriteTransaction delegate() {
451                 return tx.getTransaction();
452             }
453
454             @Override
455             public CheckedFuture<Void, TransactionCommitFailedException> submit() {
456                 readyTransaction(tx);
457                 isOpen = false;
458                 return tx.getSubmitFuture();
459             }
460
461             @Deprecated
462             @Override
463             public ListenableFuture<RpcResult<TransactionStatus>> commit() {
464                 readyTransaction(tx);
465                 isOpen = false;
466                 return tx.getCommitFuture();
467             }
468
469             @Override
470             public boolean cancel() {
471                 if (isOpen) {
472                     cancelTransaction(tx, this);
473                     isOpen = false;
474                     return true;
475                 } else {
476                     return false;
477                 }
478             }
479         };
480
481         tx.recordFrontendTransaction(ret);
482         return ret;
483     }
484
485     @Override
486     public DOMDataWriteTransaction newWriteOnlyTransaction() {
487         return newReadWriteTransaction();
488     }
489 }