4ee0c7a9863fc700463d86ef68236f85b280d28c
[mdsal.git] / dom / mdsal-dom-broker / src / main / java / org / opendaylight / mdsal / dom / broker / pingpong / 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.mdsal.dom.broker.pingpong;
9
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;
13
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;
38
39 /**
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.
47  *
48  * <p>
49  * This mode of operation means that there is no inherent isolation between
50  * the front-end transactions and transactions cannot be reasonably cancelled.
51  *
52  * <p>
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.
56  */
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;
61
62     @GuardedBy("this")
63     private boolean failed;
64     @GuardedBy("this")
65     private PingPongTransaction shutdownTx;
66     @GuardedBy("this")
67     private Entry<PingPongTransaction, Throwable> deadTx;
68
69     /**
70      * This updater is used to manipulate the "ready" transaction. We perform only atomic
71      * get-and-set on it.
72      */
73     private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> READY_UPDATER =
74             AtomicReferenceFieldUpdater.newUpdater(PingPongTransactionChain.class, PingPongTransaction.class,
75                 "readyTx");
76     private volatile PingPongTransaction readyTx;
77
78     /**
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.
83      */
84     private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> LOCKED_UPDATER
85             = AtomicReferenceFieldUpdater
86             .newUpdater(PingPongTransactionChain.class, PingPongTransaction.class, "lockedTx");
87     private volatile PingPongTransaction lockedTx;
88
89     /**
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.
92      */
93     private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> INFLIGHT_UPDATER
94             = AtomicReferenceFieldUpdater
95             .newUpdater(PingPongTransactionChain.class, PingPongTransaction.class, "inflightTx");
96     private volatile PingPongTransaction inflightTx;
97
98     PingPongTransactionChain(final DOMDataBroker broker, final DOMTransactionChainListener listener) {
99         this.listener = requireNonNull(listener);
100         this.delegate = broker.createTransactionChain(new DOMTransactionChainListener() {
101             @Override
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);
106             }
107
108             @Override
109             public void onTransactionChainSuccessful(final DOMTransactionChain chain) {
110                 delegateSuccessful(chain);
111             }
112         });
113     }
114
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
119             canceled = deadTx;
120         }
121
122         if (canceled == null) {
123             listener.onTransactionChainSuccessful(this);
124             return;
125         }
126
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);
132
133         listener.onTransactionChainFailed(this, tx.getFrontendTransaction(), cause);
134         tx.onFailure(cause);
135     }
136
137     void delegateFailed(final DOMTransactionChain chain, final Throwable cause) {
138
139         final DOMDataTreeReadWriteTransaction frontend;
140         final PingPongTransaction tx = inflightTx;
141         if (tx == null) {
142             LOG.warn("Transaction chain {} failed with no pending transactions", chain);
143             frontend = null;
144         } else {
145             frontend = tx.getFrontendTransaction();
146         }
147
148         listener.onTransactionChainFailed(this, frontend, cause);
149
150         synchronized (this) {
151             failed = true;
152
153             /*
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.
157              */
158             if (lockedTx == null) {
159                 processIfReady();
160             }
161         }
162     }
163
164     private synchronized @NonNull PingPongTransaction slowAllocateTransaction() {
165         checkState(shutdownTx == null, "Transaction chain %s has been shut down", this);
166
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());
171         }
172
173         final DOMDataTreeReadWriteTransaction delegateTx = delegate.newReadWriteTransaction();
174         final PingPongTransaction newTx = new PingPongTransaction(delegateTx);
175
176         if (!LOCKED_UPDATER.compareAndSet(this, null, newTx)) {
177             delegateTx.cancel();
178             throw new IllegalStateException(
179                     String.format("New transaction %s raced with transaction %s", newTx, lockedTx));
180         }
181
182         return newTx;
183     }
184
185     private @NonNull PingPongTransaction allocateTransaction() {
186         // Step 1: acquire current state
187         final PingPongTransaction oldTx = READY_UPDATER.getAndSet(this, null);
188
189         // Slow path: allocate a delegate transaction
190         if (oldTx == null) {
191             return slowAllocateTransaction();
192         }
193
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));
200         }
201
202         return oldTx;
203     }
204
205     /*
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.
209      */
210     @GuardedBy("this")
211     private void processIfReady() {
212         if (inflightTx == null) {
213             final PingPongTransaction tx = READY_UPDATER.getAndSet(this, null);
214             if (tx != null) {
215                 processTransaction(tx);
216             }
217         }
218     }
219
220     /**
221      * Process a ready transaction. The caller needs to ensure that
222      * each transaction is seen only once by this method.
223      *
224      * @param tx Transaction which needs processing.
225      */
226     @GuardedBy("this")
227     private void processTransaction(final @NonNull PingPongTransaction tx) {
228         if (failed) {
229             LOG.debug("Cancelling transaction {}", tx);
230             tx.getTransaction().cancel();
231             return;
232         }
233
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);
237         }
238
239         tx.getTransaction().commit().addCallback(new FutureCallback<CommitInfo>() {
240             @Override
241             public void onSuccess(final CommitInfo result) {
242                 transactionSuccessful(tx, result);
243             }
244
245             @Override
246             public void onFailure(final Throwable throwable) {
247                 transactionFailed(tx, throwable);
248             }
249         }, MoreExecutors.directExecutor());
250     }
251
252     /*
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
256      *
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
262      * 2) take lock
263      * 3) volatile read of inflightTx
264      *
265      * Rather than doing that, we keep this method synchronized, hence performing only:
266      * 1) take lock
267      * 2) CAS of inflightTx
268      *
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
271      * correctness.
272      */
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);
276
277         final PingPongTransaction nextTx = READY_UPDATER.getAndSet(this, null);
278         if (nextTx != null) {
279             processTransaction(nextTx);
280         } else if (shutdownTx != null) {
281             processTransaction(shutdownTx);
282             delegate.close();
283             shutdownTx = null;
284         }
285     }
286
287     void transactionSuccessful(final PingPongTransaction tx, final CommitInfo result) {
288         LOG.debug("Transaction {} completed successfully", tx);
289
290         tx.onSuccess(result);
291         processNextTransaction(tx);
292     }
293
294     void transactionFailed(final PingPongTransaction tx, final Throwable throwable) {
295         LOG.debug("Transaction {} failed", tx, throwable);
296
297         tx.onFailure(throwable);
298         processNextTransaction(tx);
299     }
300
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);
306
307         /*
308          * The transaction is ready. It will then be picked up by either next allocation,
309          * or a background transaction completion callback.
310          */
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);
314
315         /*
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.
320          */
321         if (inflightTx == null) {
322             synchronized (this) {
323                 processIfReady();
324             }
325         }
326     }
327
328     /**
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.
332      *
333      * @param tx         Backend shared transaction
334      * @param frontendTx transaction
335      * @param isOpen     indicator whether the transaction was already closed
336      */
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);
342
343         // Cancel the backend transaction, so we do not end up leaking it.
344         final boolean backendCancelled = tx.getTransaction().cancel();
345
346         if (failed) {
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,
349             return;
350         } else if (!backendCancelled) {
351             LOG.warn("Backend transaction cannot be cancelled during cancellation of {}, attempting to continue", tx);
352         }
353
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.
357         //
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);
362             return;
363         }
364
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());
371         delegate.close();
372     }
373
374     @Override
375     public synchronized void close() {
376         final PingPongTransaction notLocked = lockedTx;
377         checkState(notLocked == null, "Attempted to close chain with outstanding transaction %s", notLocked);
378
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");
382
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);
386             return;
387         }
388
389         // Force allocations on slow path, picking up a potentially-outstanding transaction
390         final PingPongTransaction tx = READY_UPDATER.getAndSet(this, null);
391
392         if (tx != 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);
400                 delegate.close();
401             } else {
402                 shutdownTx = tx;
403             }
404         } else {
405             // Nothing outstanding, we can safely shutdown
406             delegate.close();
407         }
408     }
409
410     @Override
411     public DOMDataTreeReadTransaction newReadOnlyTransaction() {
412         final PingPongTransaction tx = allocateTransaction();
413
414         return new DOMDataTreeReadTransaction() {
415             @Override
416             public FluentFuture<Optional<NormalizedNode<?, ?>>> read(
417                     final LogicalDatastoreType store, final YangInstanceIdentifier path) {
418                 return tx.getTransaction().read(store, path);
419             }
420
421             @Override
422             public FluentFuture<Boolean> exists(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
423                 return tx.getTransaction().exists(store, path);
424             }
425
426             @Override
427             public Object getIdentifier() {
428                 return tx.getTransaction().getIdentifier();
429             }
430
431             @Override
432             public void close() {
433                 readyTransaction(tx);
434             }
435         };
436     }
437
438     @Override
439     public DOMDataTreeReadWriteTransaction newReadWriteTransaction() {
440         final PingPongTransaction tx = allocateTransaction();
441         final DOMDataTreeReadWriteTransaction ret = new ForwardingDOMDataReadWriteTransaction() {
442             private boolean isOpen = true;
443
444             @Override
445             protected DOMDataTreeReadWriteTransaction delegate() {
446                 return tx.getTransaction();
447             }
448
449             @Override
450             public FluentFuture<? extends CommitInfo> commit() {
451                 readyTransaction(tx);
452                 isOpen = false;
453                 return tx.getCommitFuture().transform(ignored -> CommitInfo.empty(), MoreExecutors.directExecutor());
454             }
455
456             @Override
457             public boolean cancel() {
458                 if (isOpen) {
459                     cancelTransaction(tx, this);
460                     isOpen = false;
461                     return true;
462                 }
463
464                 return false;
465             }
466
467             @Override
468             public void close() {
469                 // TODO Auto-generated method stub
470
471             }
472         };
473
474         tx.recordFrontendTransaction(ret);
475         return ret;
476     }
477
478     @Override
479     public DOMDataTreeWriteTransaction newWriteOnlyTransaction() {
480         return newReadWriteTransaction();
481     }
482 }