Deprecate all MD-SAL APIs
[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 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.base.Optional;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import com.google.common.util.concurrent.FluentFuture;
17 import com.google.common.util.concurrent.FutureCallback;
18 import com.google.common.util.concurrent.MoreExecutors;
19 import java.util.AbstractMap.SimpleImmutableEntry;
20 import java.util.Map.Entry;
21 import java.util.concurrent.CancellationException;
22 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
23 import org.checkerframework.checker.lock.qual.GuardedBy;
24 import org.checkerframework.checker.lock.qual.Holding;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
27 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
28 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
29 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
30 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
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.mdsal.common.api.CommitInfo;
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 @Deprecated
62 public final class PingPongTransactionChain implements DOMTransactionChain {
63     private static final Logger LOG = LoggerFactory.getLogger(PingPongTransactionChain.class);
64     private final TransactionChainListener listener;
65     private final DOMTransactionChain delegate;
66
67     @GuardedBy("this")
68     private boolean failed;
69     @GuardedBy("this")
70     private PingPongTransaction shutdownTx;
71     @GuardedBy("this")
72     private Entry<PingPongTransaction, Throwable> deadTx;
73
74     /**
75      * This updater is used to manipulate the "ready" transaction. We perform only atomic
76      * get-and-set on it.
77      */
78     private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> READY_UPDATER
79             = AtomicReferenceFieldUpdater
80             .newUpdater(PingPongTransactionChain.class, PingPongTransaction.class, "readyTx");
81     private volatile PingPongTransaction readyTx;
82
83     /**
84      * This updater is used to manipulate the "locked" transaction. A locked transaction
85      * means we know that the user still holds a transaction and should at some point call
86      * us. We perform on compare-and-swap to ensure we properly detect when a user is
87      * attempting to allocated multiple transactions concurrently.
88      */
89     private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> LOCKED_UPDATER
90             = AtomicReferenceFieldUpdater
91             .newUpdater(PingPongTransactionChain.class, PingPongTransaction.class, "lockedTx");
92     private volatile PingPongTransaction lockedTx;
93
94     /**
95      * This updater is used to manipulate the "inflight" transaction. There can be at most
96      * one of these at any given time. We perform only compare-and-swap on these.
97      */
98     private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> INFLIGHT_UPDATER
99             = AtomicReferenceFieldUpdater
100             .newUpdater(PingPongTransactionChain.class, PingPongTransaction.class, "inflightTx");
101     private volatile PingPongTransaction inflightTx;
102
103     PingPongTransactionChain(final DOMDataBroker broker, final TransactionChainListener listener) {
104         this.listener = requireNonNull(listener);
105         this.delegate = broker.createTransactionChain(new TransactionChainListener() {
106             @Override
107             public void onTransactionChainFailed(final TransactionChain<?, ?> chain,
108                                                  final AsyncTransaction<?, ?> transaction, final Throwable cause) {
109                 LOG.debug("Transaction chain {} reported failure in {}", chain, transaction, cause);
110                 delegateFailed(chain, cause);
111             }
112
113             @Override
114             public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
115                 delegateSuccessful(chain);
116             }
117         });
118     }
119
120     void delegateSuccessful(final TransactionChain<?, ?> chain) {
121         final Entry<PingPongTransaction, Throwable> canceled;
122         synchronized (this) {
123             // This looks weird, but we need not hold the lock while invoking callbacks
124             canceled = deadTx;
125         }
126
127         if (canceled == null) {
128             listener.onTransactionChainSuccessful(this);
129             return;
130         }
131
132         // Backend shutdown successful, but we have a batch of transactions we have to report as dead due to the
133         // user calling cancel().
134         final PingPongTransaction tx = canceled.getKey();
135         final Throwable cause = canceled.getValue();
136         LOG.debug("Transaction chain {} successful, failing cancelled transaction {}", chain, tx, cause);
137
138         listener.onTransactionChainFailed(this, tx.getFrontendTransaction(), cause);
139         tx.onFailure(cause);
140     }
141
142     void delegateFailed(final TransactionChain<?, ?> chain, final Throwable cause) {
143
144         final DOMDataReadWriteTransaction frontend;
145         final PingPongTransaction tx = inflightTx;
146         if (tx == null) {
147             LOG.warn("Transaction chain {} failed with no pending transactions", chain);
148             frontend = null;
149         } else {
150             frontend = tx.getFrontendTransaction();
151         }
152
153         listener.onTransactionChainFailed(this, frontend, cause);
154
155         synchronized (this) {
156             failed = true;
157
158             /*
159              * If we do not have a locked transaction, we need to ensure that
160              * the backend transaction is cancelled. Otherwise we can defer
161              * until the user calls us.
162              */
163             if (lockedTx == null) {
164                 processIfReady();
165             }
166         }
167     }
168
169     private synchronized PingPongTransaction slowAllocateTransaction() {
170         checkState(shutdownTx == null, "Transaction chain %s has been shut down", this);
171
172         if (deadTx != null) {
173             throw new IllegalStateException(
174                     String.format("Transaction chain %s has failed due to transaction %s being canceled", this,
175                                   deadTx.getKey()), deadTx.getValue());
176         }
177
178         final DOMDataReadWriteTransaction delegateTx = delegate.newReadWriteTransaction();
179         final PingPongTransaction newTx = new PingPongTransaction(delegateTx);
180
181         if (!LOCKED_UPDATER.compareAndSet(this, null, newTx)) {
182             delegateTx.cancel();
183             throw new IllegalStateException(
184                     String.format("New transaction %s raced with transaction %s", newTx, lockedTx));
185         }
186
187         return newTx;
188     }
189
190     private PingPongTransaction allocateTransaction() {
191         // Step 1: acquire current state
192         final PingPongTransaction oldTx = READY_UPDATER.getAndSet(this, null);
193
194         // Slow path: allocate a delegate transaction
195         if (oldTx == null) {
196             return slowAllocateTransaction();
197         }
198
199         // Fast path: reuse current transaction. We will check failures and similar on commit().
200         if (!LOCKED_UPDATER.compareAndSet(this, null, oldTx)) {
201             // Ouch. Delegate chain has not detected a duplicate transaction allocation. This is the best we can do.
202             oldTx.getTransaction().cancel();
203             throw new IllegalStateException(
204                     String.format("Reusable transaction %s raced with transaction %s", oldTx, lockedTx));
205         }
206
207         return oldTx;
208     }
209
210     /*
211      * This forces allocateTransaction() on a slow path, which has to happen after
212      * this method has completed executing. Also inflightTx may be updated outside
213      * the lock, hence we need to re-check.
214      */
215     @Holding("this")
216     private void processIfReady() {
217         if (inflightTx == null) {
218             final PingPongTransaction tx = READY_UPDATER.getAndSet(this, null);
219             if (tx != null) {
220                 processTransaction(tx);
221             }
222         }
223     }
224
225     /**
226      * Process a ready transaction. The caller needs to ensure that
227      * each transaction is seen only once by this method.
228      *
229      * @param tx Transaction which needs processing.
230      */
231     @Holding("this")
232     private void processTransaction(final @NonNull PingPongTransaction tx) {
233         if (failed) {
234             LOG.debug("Cancelling transaction {}", tx);
235             tx.getTransaction().cancel();
236             return;
237         }
238
239         LOG.debug("Submitting transaction {}", tx);
240         if (!INFLIGHT_UPDATER.compareAndSet(this, null, tx)) {
241             LOG.warn("Submitting transaction {} while {} is still running", tx, inflightTx);
242         }
243
244         tx.getTransaction().commit().addCallback(new FutureCallback<CommitInfo>() {
245             @Override
246             public void onSuccess(final CommitInfo result) {
247                 transactionSuccessful(tx, result);
248             }
249
250             @Override
251             public void onFailure(final Throwable throwable) {
252                 transactionFailed(tx, throwable);
253             }
254         }, MoreExecutors.directExecutor());
255     }
256
257     /*
258      * We got invoked from the data store thread. We need to do two things:
259      * 1) release the in-flight transaction
260      * 2) process the potential next transaction
261      *
262      * We have to perform 2) under lock. We could perform 1) without locking, but that means the CAS result may
263      * not be accurate, as a user thread may submit the ready transaction before we acquire the lock -- and checking
264      * for next transaction is not enough, as that may have also be allocated (as a result of a quick
265      * submit/allocate/submit between 1) and 2)). Hence we'd end up doing the following:
266      * 1) CAS of inflightTx
267      * 2) take lock
268      * 3) volatile read of inflightTx
269      *
270      * Rather than doing that, we keep this method synchronized, hence performing only:
271      * 1) take lock
272      * 2) CAS of inflightTx
273      *
274      * Since the user thread is barred from submitting the transaction (in processIfReady), we can then proceed with
275      * the knowledge that inflightTx is null -- processTransaction() will still do a CAS, but that is only for
276      * correctness.
277      */
278     private synchronized void processNextTransaction(final PingPongTransaction tx) {
279         final boolean success = INFLIGHT_UPDATER.compareAndSet(this, tx, null);
280         checkState(success, "Completed transaction %s while %s was submitted", tx, inflightTx);
281
282         final PingPongTransaction nextTx = READY_UPDATER.getAndSet(this, null);
283         if (nextTx != null) {
284             processTransaction(nextTx);
285         } else if (shutdownTx != null) {
286             processTransaction(shutdownTx);
287             delegate.close();
288             shutdownTx = null;
289         }
290     }
291
292     void transactionSuccessful(final PingPongTransaction tx, final CommitInfo result) {
293         LOG.debug("Transaction {} completed successfully", tx);
294
295         tx.onSuccess(result);
296         processNextTransaction(tx);
297     }
298
299     void transactionFailed(final PingPongTransaction tx, final Throwable throwable) {
300         LOG.debug("Transaction {} failed", tx, throwable);
301
302         tx.onFailure(throwable);
303         processNextTransaction(tx);
304     }
305
306     void readyTransaction(final @NonNull PingPongTransaction tx) {
307         // First mark the transaction as not locked.
308         final boolean lockedMatch = LOCKED_UPDATER.compareAndSet(this, tx, null);
309         checkState(lockedMatch, "Attempted to submit transaction %s while we have %s", tx, lockedTx);
310         LOG.debug("Transaction {} unlocked", tx);
311
312         /*
313          * The transaction is ready. It will then be picked up by either next allocation,
314          * or a background transaction completion callback.
315          */
316         final boolean success = READY_UPDATER.compareAndSet(this, null, tx);
317         checkState(success, "Transaction %s collided on ready state", tx, readyTx);
318         LOG.debug("Transaction {} readied", tx);
319
320         /*
321          * We do not see a transaction being in-flight, so we need to take care of dispatching
322          * the transaction to the backend. We are in the ready case, we cannot short-cut
323          * the checking of readyTx, as an in-flight transaction may have completed between us
324          * setting the field above and us checking.
325          */
326         if (inflightTx == null) {
327             synchronized (this) {
328                 processIfReady();
329             }
330         }
331     }
332
333     /**
334      * Transaction cancellation is a heavyweight operation. We only support cancelation of a locked transaction
335      * and return false for everything else. Cancelling such a transaction will result in all transactions in the
336      * batch to be cancelled.
337      *
338      * @param tx         Backend shared transaction
339      * @param frontendTx transaction
340      * @param isOpen     indicator whether the transaction was already closed
341      */
342     synchronized void cancelTransaction(final PingPongTransaction tx, final DOMDataReadWriteTransaction frontendTx) {
343         // Attempt to unlock the operation.
344         final boolean lockedMatch = LOCKED_UPDATER.compareAndSet(this, tx, null);
345         verify(lockedMatch, "Cancelling transaction %s collided with locked transaction %s", tx, lockedTx);
346
347         // Cancel the backend transaction, so we do not end up leaking it.
348         final boolean backendCancelled = tx.getTransaction().cancel();
349
350         if (failed) {
351             // The transaction has failed, this is probably the user just clearing up the transaction they had. We have
352             // already cancelled the transaction anyway,
353             return;
354         } else if (!backendCancelled) {
355             LOG.warn("Backend transaction cannot be cancelled during cancellation of {}, attempting to continue", tx);
356         }
357
358         // We have dealt with canceling the backend transaction and have unlocked the transaction. Since we are still
359         // inside the synchronized block, any allocations are blocking on the slow path. Now we have to decide the fate
360         // of this transaction chain.
361         //
362         // If there are no other frontend transactions in this batch we are aligned with backend state and we can
363         // continue processing.
364         if (frontendTx.equals(tx.getFrontendTransaction())) {
365             LOG.debug("Cancelled transaction {} was head of the batch, resuming processing", tx);
366             return;
367         }
368
369         // There are multiple frontend transactions in this batch. We have to report them as failed, which dooms this
370         // transaction chain, too. Since we just came off of a locked transaction, we do not have a ready transaction
371         // at the moment, but there may be some transaction in-flight. So we proceed to shutdown the backend chain
372         // and mark the fact that we should be turning its completion into a failure.
373         deadTx = new SimpleImmutableEntry<>(tx, new CancellationException("Transaction " + frontendTx + " canceled")
374                 .fillInStackTrace());
375         delegate.close();
376     }
377
378     @Override
379     public synchronized void close() {
380         final PingPongTransaction notLocked = lockedTx;
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         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 FluentFuture<? extends CommitInfo> commit() {
456                 readyTransaction(tx);
457                 isOpen = false;
458                 return FluentFuture.from(tx.getCommitFuture()).transformAsync(
459                     ignored -> CommitInfo.emptyFluentFuture(), MoreExecutors.directExecutor());
460             }
461
462             @Override
463             public boolean cancel() {
464                 if (isOpen) {
465                     cancelTransaction(tx, this);
466                     isOpen = false;
467                     return true;
468                 } else {
469                     return false;
470                 }
471             }
472         };
473
474         tx.recordFrontendTransaction(ret);
475         return ret;
476     }
477
478     @Override
479     public DOMDataWriteTransaction newWriteOnlyTransaction() {
480         return newReadWriteTransaction();
481     }
482 }