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