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