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