Add AsyncWriteTransaction.commit()
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / databroker / ConcurrentDOMDataBroker.java
1 /*
2  * Copyright (c) 2014 Brocade Communications 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.cluster.databroker;
9
10 import static org.opendaylight.mdsal.dom.broker.TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER;
11 import static org.opendaylight.mdsal.dom.broker.TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER;
12 import static org.opendaylight.mdsal.dom.broker.TransactionCommitFailedExceptionMapper.PRE_COMMIT_MAPPER;
13
14 import com.google.common.annotations.Beta;
15 import com.google.common.base.Preconditions;
16 import com.google.common.util.concurrent.AbstractFuture;
17 import com.google.common.util.concurrent.FluentFuture;
18 import com.google.common.util.concurrent.FutureCallback;
19 import com.google.common.util.concurrent.Futures;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.MoreExecutors;
22 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
23 import java.util.Collection;
24 import java.util.Iterator;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.concurrent.Executor;
28 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
29 import org.opendaylight.controller.cluster.datastore.exceptions.ShardLeaderNotRespondingException;
30 import org.opendaylight.mdsal.common.api.CommitInfo;
31 import org.opendaylight.mdsal.common.api.DataStoreUnavailableException;
32 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
33 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
34 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
35 import org.opendaylight.mdsal.dom.broker.TransactionCommitFailedExceptionMapper;
36 import org.opendaylight.mdsal.dom.spi.store.DOMStore;
37 import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
38 import org.opendaylight.yangtools.util.DurationStatisticsTracker;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * ConcurrentDOMDataBroker commits transactions concurrently. The 3
44  * commit phases (canCommit, preCommit, and commit) are performed serially and non-blocking
45  * (ie async) per transaction but multiple transaction commits can run concurrent.
46  *
47  * @author Thomas Pantelis
48  */
49 @Beta
50 public class ConcurrentDOMDataBroker extends AbstractDOMBroker {
51     private static final Logger LOG = LoggerFactory.getLogger(ConcurrentDOMDataBroker.class);
52     private static final String CAN_COMMIT = "CAN_COMMIT";
53     private static final String PRE_COMMIT = "PRE_COMMIT";
54     private static final String COMMIT = "COMMIT";
55
56     private final DurationStatisticsTracker commitStatsTracker;
57
58     /**
59      * This executor is used to execute Future listener callback Runnables async.
60      */
61     private final Executor clientFutureCallbackExecutor;
62
63     public ConcurrentDOMDataBroker(final Map<LogicalDatastoreType, DOMStore> datastores,
64             final Executor listenableFutureExecutor) {
65         this(datastores, listenableFutureExecutor, DurationStatisticsTracker.createConcurrent());
66     }
67
68     public ConcurrentDOMDataBroker(final Map<LogicalDatastoreType, DOMStore> datastores,
69             final Executor listenableFutureExecutor, final DurationStatisticsTracker commitStatsTracker) {
70         super(datastores);
71         this.clientFutureCallbackExecutor = Preconditions.checkNotNull(listenableFutureExecutor);
72         this.commitStatsTracker = Preconditions.checkNotNull(commitStatsTracker);
73     }
74
75     public DurationStatisticsTracker getCommitStatsTracker() {
76         return commitStatsTracker;
77     }
78
79     @Override
80     protected FluentFuture<? extends CommitInfo> commit(
81             final DOMDataTreeWriteTransaction transaction, final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
82
83         Preconditions.checkArgument(transaction != null, "Transaction must not be null.");
84         Preconditions.checkArgument(cohorts != null, "Cohorts must not be null.");
85         LOG.debug("Tx: {} is submitted for execution.", transaction.getIdentifier());
86
87         if (cohorts.isEmpty()) {
88             return CommitInfo.emptyFluentFuture();
89         }
90
91         final AsyncNotifyingSettableFuture clientSubmitFuture =
92                 new AsyncNotifyingSettableFuture(clientFutureCallbackExecutor);
93
94         doCanCommit(clientSubmitFuture, transaction, cohorts);
95
96         return FluentFuture.from(clientSubmitFuture).transform(ignored -> CommitInfo.empty(),
97                 MoreExecutors.directExecutor());
98     }
99
100     private void doCanCommit(final AsyncNotifyingSettableFuture clientSubmitFuture,
101             final DOMDataTreeWriteTransaction transaction,
102             final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
103
104         final long startTime = System.nanoTime();
105
106         final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();
107
108         // Not using Futures.allAsList here to avoid its internal overhead.
109         FutureCallback<Boolean> futureCallback = new FutureCallback<Boolean>() {
110             @Override
111             public void onSuccess(final Boolean result) {
112                 if (result == null || !result) {
113                     handleException(clientSubmitFuture, transaction, cohorts, CAN_COMMIT, CAN_COMMIT_ERROR_MAPPER,
114                             new TransactionCommitFailedException("Can Commit failed, no detailed cause available."));
115                 } else if (!cohortIterator.hasNext()) {
116                     // All cohorts completed successfully - we can move on to the preCommit phase
117                     doPreCommit(startTime, clientSubmitFuture, transaction, cohorts);
118                 } else {
119                     Futures.addCallback(cohortIterator.next().canCommit(), this, MoreExecutors.directExecutor());
120                 }
121             }
122
123             @Override
124             public void onFailure(final Throwable failure) {
125                 handleException(clientSubmitFuture, transaction, cohorts, CAN_COMMIT, CAN_COMMIT_ERROR_MAPPER, failure);
126             }
127         };
128
129         ListenableFuture<Boolean> canCommitFuture = cohortIterator.next().canCommit();
130         Futures.addCallback(canCommitFuture, futureCallback, MoreExecutors.directExecutor());
131     }
132
133     private void doPreCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
134             final DOMDataTreeWriteTransaction transaction,
135             final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
136
137         final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();
138
139         // Not using Futures.allAsList here to avoid its internal overhead.
140         FutureCallback<Void> futureCallback = new FutureCallback<Void>() {
141             @Override
142             public void onSuccess(final Void notUsed) {
143                 if (!cohortIterator.hasNext()) {
144                     // All cohorts completed successfully - we can move on to the commit phase
145                     doCommit(startTime, clientSubmitFuture, transaction, cohorts);
146                 } else {
147                     ListenableFuture<Void> preCommitFuture = cohortIterator.next().preCommit();
148                     Futures.addCallback(preCommitFuture, this, MoreExecutors.directExecutor());
149                 }
150             }
151
152             @Override
153             public void onFailure(final Throwable failure) {
154                 handleException(clientSubmitFuture, transaction, cohorts, PRE_COMMIT, PRE_COMMIT_MAPPER, failure);
155             }
156         };
157
158         ListenableFuture<Void> preCommitFuture = cohortIterator.next().preCommit();
159         Futures.addCallback(preCommitFuture, futureCallback, MoreExecutors.directExecutor());
160     }
161
162     private void doCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
163             final DOMDataTreeWriteTransaction transaction,
164             final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
165
166         final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();
167
168         // Not using Futures.allAsList here to avoid its internal overhead.
169         FutureCallback<Void> futureCallback = new FutureCallback<Void>() {
170             @Override
171             public void onSuccess(final Void notUsed) {
172                 if (!cohortIterator.hasNext()) {
173                     // All cohorts completed successfully - we're done.
174                     commitStatsTracker.addDuration(System.nanoTime() - startTime);
175
176                     clientSubmitFuture.set();
177                 } else {
178                     ListenableFuture<Void> commitFuture = cohortIterator.next().commit();
179                     Futures.addCallback(commitFuture, this, MoreExecutors.directExecutor());
180                 }
181             }
182
183             @Override
184             public void onFailure(final Throwable throwable) {
185                 handleException(clientSubmitFuture, transaction, cohorts, COMMIT, COMMIT_ERROR_MAPPER, throwable);
186             }
187         };
188
189         ListenableFuture<Void> commitFuture = cohortIterator.next().commit();
190         Futures.addCallback(commitFuture, futureCallback, MoreExecutors.directExecutor());
191     }
192
193     @SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST_OF_RETURN_VALUE",
194             justification = "Pertains to the assignment of the 'clientException' var. FindBugs flags this as an "
195                 + "uncomfirmed cast but the generic type in TransactionCommitFailedExceptionMapper is "
196                 + "TransactionCommitFailedException and thus should be deemed as confirmed.")
197     private static void handleException(final AsyncNotifyingSettableFuture clientSubmitFuture,
198             final DOMDataTreeWriteTransaction transaction,
199             final Collection<DOMStoreThreePhaseCommitCohort> cohorts,
200             final String phase, final TransactionCommitFailedExceptionMapper exMapper,
201             final Throwable throwable) {
202
203         if (clientSubmitFuture.isDone()) {
204             // We must have had failures from multiple cohorts.
205             return;
206         }
207
208         // Use debug instead of warn level here because this exception gets propagate back to the caller via the Future
209         LOG.debug("Tx: {} Error during phase {}, starting Abort", transaction.getIdentifier(), phase, throwable);
210
211         // Transaction failed - tell all cohorts to abort.
212         @SuppressWarnings("unchecked")
213         ListenableFuture<Void>[] canCommitFutures = new ListenableFuture[cohorts.size()];
214         int index = 0;
215         for (DOMStoreThreePhaseCommitCohort cohort : cohorts) {
216             canCommitFutures[index++] = cohort.abort();
217         }
218
219         // Propagate the original exception
220         final Exception e;
221         if (throwable instanceof NoShardLeaderException || throwable instanceof ShardLeaderNotRespondingException) {
222             e = new DataStoreUnavailableException(throwable.getMessage(), throwable);
223         } else if (throwable instanceof Exception) {
224             e = (Exception)throwable;
225         } else {
226             e = new RuntimeException("Unexpected error occurred", throwable);
227         }
228         clientSubmitFuture.setException(exMapper.apply(e));
229
230         ListenableFuture<List<Void>> combinedFuture = Futures.allAsList(canCommitFutures);
231         Futures.addCallback(combinedFuture, new FutureCallback<List<Void>>() {
232             @Override
233             public void onSuccess(final List<Void> notUsed) {
234                 // Propagate the original exception to the client.
235                 LOG.debug("Tx: {} aborted successfully", transaction.getIdentifier());
236             }
237
238             @Override
239             public void onFailure(final Throwable failure) {
240                 LOG.error("Tx: {} Error during Abort.", transaction.getIdentifier(), failure);
241             }
242         }, MoreExecutors.directExecutor());
243     }
244
245     /**
246      * A settable future that uses an {@link Executor} to execute listener callback Runnables,
247      * registered via {@link #addListener}, asynchronously when this future completes. This is
248      * done to guarantee listener executions are off-loaded onto another thread to avoid blocking
249      * the thread that completed this future, as a common use case is to pass an executor that runs
250      * tasks in the same thread as the caller (ie MoreExecutors#sameThreadExecutor)
251      * to {@link #addListener}.
252      * FIXME: This class should probably be moved to yangtools common utils for re-usability and
253      * unified with AsyncNotifyingListenableFutureTask.
254      */
255     private static class AsyncNotifyingSettableFuture extends AbstractFuture<Void> {
256
257         /**
258          * ThreadLocal used to detect if the task completion thread is running the future listener Runnables.
259          */
260         private static final ThreadLocal<Boolean> ON_TASK_COMPLETION_THREAD_TL = new ThreadLocal<>();
261
262         private final Executor listenerExecutor;
263
264         AsyncNotifyingSettableFuture(final Executor listenerExecutor) {
265             this.listenerExecutor = Preconditions.checkNotNull(listenerExecutor);
266         }
267
268         @Override
269         public void addListener(final Runnable listener, final Executor executor) {
270             // Wrap the listener Runnable in a DelegatingRunnable. If the specified executor is one
271             // that runs tasks in the same thread as the caller submitting the task
272             // (e.g. {@link com.google.common.util.concurrent.MoreExecutors#sameThreadExecutor}) and
273             // the listener is executed from the #set methods, then the DelegatingRunnable will detect
274             // this via the ThreadLocal and submit the listener Runnable to the listenerExecutor.
275             //
276             // On the other hand, if this task is already complete, the call to ExecutionList#add in
277             // superclass will execute the listener Runnable immediately and, since the ThreadLocal
278             // won't be set, the DelegatingRunnable will run the listener Runnable inline.
279             super.addListener(new DelegatingRunnable(listener, listenerExecutor), executor);
280         }
281
282         boolean set() {
283             ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
284             try {
285                 return super.set(null);
286             } finally {
287                 ON_TASK_COMPLETION_THREAD_TL.set(null);
288             }
289         }
290
291         @Override
292         protected boolean setException(final Throwable throwable) {
293             ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
294             try {
295                 return super.setException(throwable);
296             } finally {
297                 ON_TASK_COMPLETION_THREAD_TL.set(null);
298             }
299         }
300
301         private static final class DelegatingRunnable implements Runnable {
302             private final Runnable delegate;
303             private final Executor executor;
304
305             DelegatingRunnable(final Runnable delegate, final Executor executor) {
306                 this.delegate = Preconditions.checkNotNull(delegate);
307                 this.executor = Preconditions.checkNotNull(executor);
308             }
309
310             @Override
311             public void run() {
312                 if (ON_TASK_COMPLETION_THREAD_TL.get() != null) {
313                     // We're running on the task completion thread so off-load to the executor.
314                     LOG.trace("Submitting ListenenableFuture Runnable from thread {} to executor {}",
315                             Thread.currentThread().getName(), executor);
316                     executor.execute(delegate);
317                 } else {
318                     // We're not running on the task completion thread so run the delegate inline.
319                     LOG.trace("Executing ListenenableFuture Runnable on this thread: {}",
320                             Thread.currentThread().getName());
321                     delegate.run();
322                 }
323             }
324         }
325     }
326
327     @Override
328     public String toString() {
329         return "Clustered ConcurrentDOMDataBroker";
330     }
331 }