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