Make AbstractPingPongTransactionChain.close() idempotent
[mdsal.git] / dom / mdsal-dom-spi / src / main / java / org / opendaylight / mdsal / dom / spi / AbstractPingPongTransactionChain.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.spi;
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 import static org.opendaylight.mdsal.dom.spi.PingPongTransactionChain.LOG;
14
15 import com.google.common.util.concurrent.FluentFuture;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.MoreExecutors;
18 import java.lang.invoke.MethodHandles;
19 import java.lang.invoke.VarHandle;
20 import java.util.Map;
21 import java.util.Map.Entry;
22 import java.util.Optional;
23 import java.util.concurrent.CancellationException;
24 import java.util.function.Function;
25 import org.checkerframework.checker.lock.qual.GuardedBy;
26 import org.checkerframework.checker.lock.qual.Holding;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.opendaylight.mdsal.common.api.CommitInfo;
30 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
31 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
32 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
33 import org.opendaylight.mdsal.dom.api.DOMDataTreeTransaction;
34 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
35 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
36 import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39
40 /**
41  * The actual implementation of {@link PingPongTransactionChain}. Split out to allow deeper testing while keeping the
42  * externally-visible implementation final.
43  */
44 abstract class AbstractPingPongTransactionChain implements DOMTransactionChain {
45     private final DOMTransactionChainListener listener;
46     private final DOMTransactionChain delegate;
47
48     @GuardedBy("this")
49     private boolean closed;
50     @GuardedBy("this")
51     private boolean failed;
52     @GuardedBy("this")
53     private PingPongTransaction shutdownTx;
54     @GuardedBy("this")
55     private Entry<PingPongTransaction, Throwable> deadTx;
56
57     //  This VarHandle is used to manipulate the "ready" transaction. We perform only atomic get-and-set on it.
58     private static final VarHandle READY_TX;
59     @SuppressWarnings("unused")
60     private volatile PingPongTransaction readyTx;
61
62     /*
63      * This VarHandle is used to manipulate the "locked" transaction. A locked transaction means we know that the user
64      * still holds a transaction and should at some point call us. We perform on compare-and-swap to ensure we properly
65      * detect when a user is attempting to allocated multiple transactions concurrently.
66      */
67     private static final VarHandle LOCKED_TX;
68     private volatile PingPongTransaction lockedTx;
69
70     /*
71      * This updater is used to manipulate the "inflight" transaction. There can be at most one of these at any given
72      * time. We perform only compare-and-swap on these.
73      */
74     private static final VarHandle INFLIGHT_TX;
75     private volatile PingPongTransaction inflightTx;
76
77     static {
78         final var lookup = MethodHandles.lookup();
79         try {
80             INFLIGHT_TX = lookup.findVarHandle(AbstractPingPongTransactionChain.class, "inflightTx",
81                 PingPongTransaction.class);
82             LOCKED_TX = lookup.findVarHandle(AbstractPingPongTransactionChain.class, "lockedTx",
83                 PingPongTransaction.class);
84             READY_TX = lookup.findVarHandle(AbstractPingPongTransactionChain.class, "readyTx",
85                 PingPongTransaction.class);
86         } catch (NoSuchFieldException | IllegalAccessException e) {
87             throw new ExceptionInInitializerError(e);
88         }
89     }
90
91     AbstractPingPongTransactionChain(final Function<DOMTransactionChainListener, DOMTransactionChain> delegateFactory,
92             final DOMTransactionChainListener listener) {
93         this.listener = requireNonNull(listener);
94         delegate = delegateFactory.apply(new DOMTransactionChainListener() {
95             @Override
96             public void onTransactionChainFailed(final DOMTransactionChain chain,
97                     final DOMDataTreeTransaction transaction, final Throwable cause) {
98                 LOG.debug("Transaction chain {} reported failure in {}", chain, transaction, cause);
99                 delegateFailed(chain, cause);
100             }
101
102             @Override
103             public void onTransactionChainSuccessful(final DOMTransactionChain chain) {
104                 delegateSuccessful(chain);
105             }
106         });
107     }
108
109     private void delegateSuccessful(final DOMTransactionChain chain) {
110         final Entry<PingPongTransaction, Throwable> canceled;
111         synchronized (this) {
112             // This looks weird, but we need not hold the lock while invoking callbacks
113             canceled = deadTx;
114         }
115
116         if (canceled == null) {
117             listener.onTransactionChainSuccessful(this);
118             return;
119         }
120
121         // Backend shutdown successful, but we have a batch of transactions we have to report as dead due to the
122         // user calling cancel().
123         final PingPongTransaction tx = canceled.getKey();
124         final Throwable cause = canceled.getValue();
125         LOG.debug("Transaction chain {} successful, failing cancelled transaction {}", chain, tx, cause);
126
127         listener.onTransactionChainFailed(this, tx.getFrontendTransaction(), cause);
128         tx.onFailure(cause);
129     }
130
131     private void delegateFailed(final DOMTransactionChain chain, final Throwable cause) {
132         final DOMDataTreeReadWriteTransaction frontend;
133         final PingPongTransaction tx = inflightTx;
134         if (tx == null) {
135             LOG.warn("Transaction chain {} failed with no pending transactions", chain);
136             frontend = null;
137         } else {
138             frontend = tx.getFrontendTransaction();
139         }
140
141         listener.onTransactionChainFailed(this, frontend, cause);
142
143         synchronized (this) {
144             failed = true;
145
146             /*
147              * If we do not have a locked transaction, we need to ensure that the backend transaction is cancelled.
148              * Otherwise we can defer until the user calls us.
149              */
150             if (lockedTx == null) {
151                 processIfReady();
152             }
153         }
154     }
155
156     private synchronized @NonNull PingPongTransaction slowAllocateTransaction() {
157         checkState(shutdownTx == null, "Transaction chain %s has been shut down", this);
158
159         if (deadTx != null) {
160             throw new IllegalStateException(String.format(
161                 "Transaction chain %s has failed due to transaction %s being canceled", this, deadTx.getKey()),
162                 deadTx.getValue());
163         }
164
165         final DOMDataTreeReadWriteTransaction delegateTx = delegate.newReadWriteTransaction();
166         final PingPongTransaction newTx = new PingPongTransaction(delegateTx);
167
168         final Object witness = LOCKED_TX.compareAndExchange(this, null, newTx);
169         if (witness != null) {
170             delegateTx.cancel();
171             throw new IllegalStateException(
172                     String.format("New transaction %s raced with transaction %s", newTx, witness));
173         }
174
175         return newTx;
176     }
177
178     private @Nullable PingPongTransaction acquireReadyTx() {
179         return (PingPongTransaction) READY_TX.getAndSet(this, null);
180     }
181
182     private @NonNull PingPongTransaction allocateTransaction() {
183         // Step 1: acquire current state
184         final PingPongTransaction oldTx = acquireReadyTx();
185
186         // Slow path: allocate a delegate transaction
187         if (oldTx == null) {
188             return slowAllocateTransaction();
189         }
190
191         // Fast path: reuse current transaction. We will check failures and similar on commit().
192         final Object witness = LOCKED_TX.compareAndExchange(this, null, oldTx);
193         if (witness != null) {
194             // Ouch. Delegate chain has not detected a duplicate transaction allocation. This is the best we can do.
195             oldTx.getTransaction().cancel();
196             throw new IllegalStateException(String.format("Reusable transaction %s raced with transaction %s", oldTx,
197                 witness));
198         }
199
200         return oldTx;
201     }
202
203     /**
204      * This forces allocateTransaction() on a slow path, which has to happen after this method has completed executing.
205      * Also inflightTx may be updated outside the lock, hence we need to re-check.
206      */
207     @Holding("this")
208     private void processIfReady() {
209         if (inflightTx == null) {
210             final PingPongTransaction tx = acquireReadyTx();
211             if (tx != null) {
212                 processTransaction(tx);
213             }
214         }
215     }
216
217     /**
218      * Process a ready transaction. The caller needs to ensure that each transaction is seen only once by this method.
219      *
220      * @param tx Transaction which needs processing.
221      */
222     @Holding("this")
223     private void processTransaction(final @NonNull PingPongTransaction tx) {
224         if (failed) {
225             LOG.debug("Cancelling transaction {}", tx);
226             tx.getTransaction().cancel();
227             return;
228         }
229
230         LOG.debug("Submitting transaction {}", tx);
231         final Object witness = INFLIGHT_TX.compareAndExchange(this, null, tx);
232         if (witness != null) {
233             LOG.warn("Submitting transaction {} while {} is still running", tx, witness);
234         }
235
236         tx.getTransaction().commit().addCallback(new FutureCallback<CommitInfo>() {
237             @Override
238             public void onSuccess(final CommitInfo result) {
239                 transactionSuccessful(tx, result);
240             }
241
242             @Override
243             public void onFailure(final Throwable throwable) {
244                 transactionFailed(tx, throwable);
245             }
246         }, MoreExecutors.directExecutor());
247     }
248
249     /*
250      * We got invoked from the data store thread. We need to do two things:
251      * 1) release the in-flight transaction
252      * 2) process the potential next transaction
253      *
254      * We have to perform 2) under lock. We could perform 1) without locking, but that means the CAS result may
255      * not be accurate, as a user thread may submit the ready transaction before we acquire the lock -- and checking
256      * for next transaction is not enough, as that may have also be allocated (as a result of a quick
257      * submit/allocate/submit between 1) and 2)). Hence we'd end up doing the following:
258      * 1) CAS of inflightTx
259      * 2) take lock
260      * 3) volatile read of inflightTx
261      *
262      * Rather than doing that, we keep this method synchronized, hence performing only:
263      * 1) take lock
264      * 2) CAS of inflightTx
265      *
266      * Since the user thread is barred from submitting the transaction (in processIfReady), we can then proceed with
267      * the knowledge that inflightTx is null -- processTransaction() will still do a CAS, but that is only for
268      * correctness.
269      */
270     private synchronized void processNextTransaction(final PingPongTransaction tx) {
271         final Object witness = INFLIGHT_TX.compareAndExchange(this, tx, null);
272         checkState(witness == tx, "Completed transaction %s while %s was submitted", tx, witness);
273
274         final PingPongTransaction nextTx = acquireReadyTx();
275         if (nextTx == null) {
276             final PingPongTransaction local = shutdownTx;
277             if (local != null) {
278                 processTransaction(local);
279                 delegate.close();
280                 shutdownTx = null;
281             }
282         } else {
283             processTransaction(nextTx);
284         }
285     }
286
287     private 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     private 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     private void readyTransaction(final @NonNull PingPongTransaction tx) {
302         // First mark the transaction as not locked.
303         final Object lockedWitness = LOCKED_TX.compareAndExchange(this, tx, null);
304         checkState(lockedWitness == tx, "Attempted to submit transaction %s while we have %s", tx, lockedWitness);
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 Object readyWitness = READY_TX.compareAndExchange(this, null, tx);
312         checkState(readyWitness == null, "Transaction %s collided on ready state with %s", tx, readyWitness);
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      * @return {@code true} if the transaction was cancelled successfully
336      */
337     private synchronized boolean cancelTransaction(final PingPongTransaction tx,
338             final DOMDataTreeReadWriteTransaction frontendTx) {
339         // Attempt to unlock the operation.
340         final Object witness = LOCKED_TX.compareAndExchange(this, tx, null);
341         verify(witness == tx, "Cancelling transaction %s collided with locked transaction %s", tx, witness);
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 true;
350         }
351
352         // We have dealt with cancelling the backend transaction and have unlocked the transaction. Since we are still
353         // inside the synchronized block, any allocations are blocking on the slow path. Now we have to decide the fate
354         // of this transaction chain.
355         //
356         // If there are no other frontend transactions in this batch we are aligned with backend state and we can
357         // continue processing.
358         if (frontendTx.equals(tx.getFrontendTransaction())) {
359             if (backendCancelled) {
360                 LOG.debug("Cancelled transaction {} was head of the batch, resuming processing", tx);
361                 return true;
362             }
363
364             // Backend refused to cancel the transaction. Reinstate it to locked state.
365             final Object reinstateWitness = LOCKED_TX.compareAndExchange(this, null, tx);
366             verify(reinstateWitness == null, "Reinstating transaction %s collided with locked transaction %s", tx,
367                 reinstateWitness);
368             return false;
369         }
370
371         if (!backendCancelled) {
372             LOG.warn("Backend transaction cannot be cancelled during cancellation of {}, attempting to continue", tx);
373         }
374
375         // There are multiple frontend transactions in this batch. We have to report them as failed, which dooms this
376         // transaction chain, too. Since we just came off of a locked transaction, we do not have a ready transaction
377         // at the moment, but there may be some transaction in-flight. So we proceed to shutdown the backend chain
378         // and mark the fact that we should be turning its completion into a failure.
379         deadTx = Map.entry(tx, new CancellationException("Transaction " + frontendTx + " canceled").fillInStackTrace());
380         delegate.close();
381         return true;
382     }
383
384     @Override
385     public final synchronized void close() {
386         if (closed) {
387             LOG.debug("Attempted to close an already-closed chain");
388             return;
389         }
390
391         // Note: we do not derive from AbstractRegistration due to ordering of this check
392         final var notLocked = lockedTx;
393         if (notLocked != null) {
394             throw new IllegalStateException("Attempted to close chain with outstanding transaction " + notLocked);
395         }
396         closed = true;
397
398         // This may be a reaction to our failure callback, in that case the backend is already shutdown
399         if (deadTx != null) {
400             LOG.debug("Delegate {} is already closed due to failure {}", delegate, deadTx);
401             return;
402         }
403
404         // Force allocations on slow path, picking up a potentially-outstanding transaction
405         final var tx = acquireReadyTx();
406         if (tx != null) {
407             // We have one more transaction, which needs to be processed somewhere. If we do not
408             // a transaction in-flight, we need to push it down ourselves.
409             // If there is an in-flight transaction we will schedule this last one into a dedicated
410             // slot. Allocation slow path will check its presence and fail, the in-flight path will
411             // pick it up, submit and immediately close the chain.
412             if (inflightTx == null) {
413                 processTransaction(tx);
414                 delegate.close();
415             } else {
416                 shutdownTx = tx;
417             }
418         } else {
419             // Nothing outstanding, we can safely shutdown
420             delegate.close();
421         }
422     }
423
424     @Override
425     public final DOMDataTreeReadTransaction newReadOnlyTransaction() {
426         return new PingPongReadTransaction(allocateTransaction());
427     }
428
429     @Override
430     public final DOMDataTreeReadWriteTransaction newReadWriteTransaction() {
431         final PingPongTransaction tx = allocateTransaction();
432         final DOMDataTreeReadWriteTransaction ret = new PingPongReadWriteTransaction(tx);
433         tx.recordFrontendTransaction(ret);
434         return ret;
435     }
436
437     @Override
438     public final DOMDataTreeWriteTransaction newWriteOnlyTransaction() {
439         return newReadWriteTransaction();
440     }
441
442     private final class PingPongReadTransaction implements DOMDataTreeReadTransaction {
443         private final @NonNull PingPongTransaction tx;
444
445         PingPongReadTransaction(final PingPongTransaction tx) {
446             this.tx = requireNonNull(tx);
447         }
448
449         @Override
450         public FluentFuture<Optional<NormalizedNode>> read(final LogicalDatastoreType store,
451                 final YangInstanceIdentifier path) {
452             return tx.getTransaction().read(store, path);
453         }
454
455         @Override
456         public FluentFuture<Boolean> exists(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
457             return tx.getTransaction().exists(store, path);
458         }
459
460         @Override
461         public Object getIdentifier() {
462             return tx.getTransaction().getIdentifier();
463         }
464
465         @Override
466         public void close() {
467             readyTransaction(tx);
468         }
469     }
470
471     private final class PingPongReadWriteTransaction extends ForwardingDOMDataReadWriteTransaction {
472         private final @NonNull PingPongTransaction tx;
473
474         private boolean isOpen = true;
475
476         PingPongReadWriteTransaction(final PingPongTransaction tx) {
477             this.tx = requireNonNull(tx);
478         }
479
480         @Override
481         public FluentFuture<? extends CommitInfo> commit() {
482             readyTransaction(tx);
483             isOpen = false;
484             return tx.getCommitFuture().transform(ignored -> CommitInfo.empty(), MoreExecutors.directExecutor());
485         }
486
487         @Override
488         public boolean cancel() {
489             if (isOpen && cancelTransaction(tx, this)) {
490                 isOpen = false;
491                 return true;
492             }
493             return false;
494         }
495
496         @Override
497         protected DOMDataTreeReadWriteTransaction delegate() {
498             return tx.getTransaction();
499         }
500     }
501 }