d208fcd5ea39c2b4d551b91ae3cfaf248d59b2ce
[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.spi.TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER;
13 import static org.opendaylight.mdsal.dom.spi.TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER;
14 import static org.opendaylight.mdsal.dom.spi.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.MoreExecutors;
22 import java.util.Map;
23 import java.util.concurrent.Executor;
24 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
25 import org.opendaylight.controller.cluster.datastore.exceptions.ShardLeaderNotRespondingException;
26 import org.opendaylight.mdsal.common.api.CommitInfo;
27 import org.opendaylight.mdsal.common.api.DataStoreUnavailableException;
28 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
29 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
30 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
31 import org.opendaylight.mdsal.dom.spi.AbstractDOMDataBroker;
32 import org.opendaylight.mdsal.dom.spi.TransactionCommitFailedExceptionMapper;
33 import org.opendaylight.mdsal.dom.spi.store.DOMStore;
34 import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
35 import org.opendaylight.yangtools.util.DurationStatisticsTracker;
36 import org.opendaylight.yangtools.yang.common.Empty;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 /**
41  * ConcurrentDOMDataBroker commits transactions concurrently. The 3
42  * commit phases (canCommit, preCommit, and commit) are performed serially and non-blocking
43  * (ie async) per transaction but multiple transaction commits can run concurrent.
44  *
45  * @author Thomas Pantelis
46  */
47 @Beta
48 public class ConcurrentDOMDataBroker extends AbstractDOMDataBroker {
49     private static final Logger LOG = LoggerFactory.getLogger(ConcurrentDOMDataBroker.class);
50     private static final String CAN_COMMIT = "CAN_COMMIT";
51     private static final String PRE_COMMIT = "PRE_COMMIT";
52     private static final String COMMIT = "COMMIT";
53
54     private final DurationStatisticsTracker commitStatsTracker;
55
56     /**
57      * This executor is used to execute Future listener callback Runnables async.
58      */
59     private final Executor clientFutureCallbackExecutor;
60
61     public ConcurrentDOMDataBroker(final Map<LogicalDatastoreType, DOMStore> datastores,
62             final Executor listenableFutureExecutor) {
63         this(datastores, listenableFutureExecutor, DurationStatisticsTracker.createConcurrent());
64     }
65
66     public ConcurrentDOMDataBroker(final Map<LogicalDatastoreType, DOMStore> datastores,
67             final Executor listenableFutureExecutor, final DurationStatisticsTracker commitStatsTracker) {
68         super(datastores);
69         clientFutureCallbackExecutor = requireNonNull(listenableFutureExecutor);
70         this.commitStatsTracker = requireNonNull(commitStatsTracker);
71     }
72
73     public DurationStatisticsTracker getCommitStatsTracker() {
74         return commitStatsTracker;
75     }
76
77     @Override
78     protected FluentFuture<? extends CommitInfo> commit(final DOMDataTreeWriteTransaction transaction,
79             final DOMStoreThreePhaseCommitCohort cohort) {
80
81         checkArgument(transaction != null, "Transaction must not be null.");
82         checkArgument(cohort != null, "Cohorts must not be null.");
83         LOG.debug("Tx: {} is submitted for execution.", transaction.getIdentifier());
84
85         final AsyncNotifyingSettableFuture clientSubmitFuture =
86                 new AsyncNotifyingSettableFuture(clientFutureCallbackExecutor);
87
88         doCanCommit(clientSubmitFuture, transaction, cohort);
89         return FluentFuture.from(clientSubmitFuture);
90     }
91
92     private void doCanCommit(final AsyncNotifyingSettableFuture clientSubmitFuture,
93             final DOMDataTreeWriteTransaction transaction,
94             final DOMStoreThreePhaseCommitCohort cohort) {
95         final long startTime = System.nanoTime();
96
97         Futures.addCallback(cohort.canCommit(), new FutureCallback<>() {
98             @Override
99             public void onSuccess(final Boolean result) {
100                 if (result == null || !result) {
101                     onFailure(new TransactionCommitFailedException("Can Commit failed, no detailed cause available."));
102                 } else {
103                     doPreCommit(startTime, clientSubmitFuture, transaction, cohort);
104                 }
105             }
106
107             @Override
108             public void onFailure(final Throwable failure) {
109                 handleException(clientSubmitFuture, transaction, cohort, CAN_COMMIT, CAN_COMMIT_ERROR_MAPPER, failure);
110             }
111         }, MoreExecutors.directExecutor());
112     }
113
114     private void doPreCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
115             final DOMDataTreeWriteTransaction transaction, final DOMStoreThreePhaseCommitCohort cohort) {
116         Futures.addCallback(cohort.preCommit(), new FutureCallback<>() {
117             @Override
118             public void onSuccess(final Empty result) {
119                 doCommit(startTime, clientSubmitFuture, transaction, cohort);
120             }
121
122             @Override
123             public void onFailure(final Throwable failure) {
124                 handleException(clientSubmitFuture, transaction, cohort, PRE_COMMIT, PRE_COMMIT_MAPPER, failure);
125             }
126         }, MoreExecutors.directExecutor());
127     }
128
129     private void doCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
130             final DOMDataTreeWriteTransaction transaction, final DOMStoreThreePhaseCommitCohort cohort) {
131         Futures.addCallback(cohort.commit(), new FutureCallback<CommitInfo>() {
132             @Override
133             public void onSuccess(final CommitInfo result) {
134                 commitStatsTracker.addDuration(System.nanoTime() - startTime);
135                 clientSubmitFuture.set();
136             }
137
138             @Override
139             public void onFailure(final Throwable throwable) {
140                 handleException(clientSubmitFuture, transaction, cohort, COMMIT, COMMIT_ERROR_MAPPER, throwable);
141             }
142         }, MoreExecutors.directExecutor());
143     }
144
145     private static void handleException(final AsyncNotifyingSettableFuture clientSubmitFuture,
146             final DOMDataTreeWriteTransaction transaction, final DOMStoreThreePhaseCommitCohort cohort,
147             final String phase, final TransactionCommitFailedExceptionMapper exMapper, final Throwable throwable) {
148         if (clientSubmitFuture.isDone()) {
149             // We must have had failures from multiple cohorts.
150             return;
151         }
152
153         // Use debug instead of warn level here because this exception gets propagate back to the caller via the Future
154         LOG.debug("Tx: {} Error during phase {}, starting Abort", transaction.getIdentifier(), phase, throwable);
155
156         // Propagate the original exception
157         final Exception e;
158         if (throwable instanceof NoShardLeaderException || throwable instanceof ShardLeaderNotRespondingException) {
159             e = new DataStoreUnavailableException(throwable.getMessage(), throwable);
160         } else if (throwable instanceof Exception) {
161             e = (Exception) throwable;
162         } else {
163             e = new RuntimeException("Unexpected error occurred", throwable);
164         }
165         clientSubmitFuture.setException(exMapper.apply(e));
166
167         // abort
168         Futures.addCallback(cohort.abort(), new FutureCallback<Empty>() {
169             @Override
170             public void onSuccess(final Empty result) {
171                 // Propagate the original exception to the client.
172                 LOG.debug("Tx: {} aborted successfully", transaction.getIdentifier());
173             }
174
175             @Override
176             public void onFailure(final Throwable failure) {
177                 LOG.error("Tx: {} Error during Abort.", transaction.getIdentifier(), failure);
178             }
179         }, MoreExecutors.directExecutor());
180     }
181
182     /**
183      * A settable future that uses an {@link Executor} to execute listener callback Runnables,
184      * registered via {@link #addListener}, asynchronously when this future completes. This is
185      * done to guarantee listener executions are off-loaded onto another thread to avoid blocking
186      * the thread that completed this future, as a common use case is to pass an executor that runs
187      * tasks in the same thread as the caller (ie MoreExecutors#sameThreadExecutor)
188      * to {@link #addListener}.
189      * FIXME: This class should probably be moved to yangtools common utils for re-usability and
190      * unified with AsyncNotifyingListenableFutureTask.
191      */
192     private static class AsyncNotifyingSettableFuture extends AbstractFuture<CommitInfo> {
193         /**
194          * ThreadLocal used to detect if the task completion thread is running the future listener Runnables.
195          */
196         private static final ThreadLocal<Boolean> ON_TASK_COMPLETION_THREAD_TL = new ThreadLocal<>();
197
198         private final Executor listenerExecutor;
199
200         AsyncNotifyingSettableFuture(final Executor listenerExecutor) {
201             this.listenerExecutor = requireNonNull(listenerExecutor);
202         }
203
204         @Override
205         public void addListener(final Runnable listener, final Executor executor) {
206             // Wrap the listener Runnable in a DelegatingRunnable. If the specified executor is one
207             // that runs tasks in the same thread as the caller submitting the task
208             // (e.g. {@link com.google.common.util.concurrent.MoreExecutors#sameThreadExecutor}) and
209             // the listener is executed from the #set methods, then the DelegatingRunnable will detect
210             // this via the ThreadLocal and submit the listener Runnable to the listenerExecutor.
211             //
212             // On the other hand, if this task is already complete, the call to ExecutionList#add in
213             // superclass will execute the listener Runnable immediately and, since the ThreadLocal
214             // won't be set, the DelegatingRunnable will run the listener Runnable inline.
215             super.addListener(new DelegatingRunnable(listener, listenerExecutor), executor);
216         }
217
218         boolean set() {
219             ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
220             try {
221                 return super.set(CommitInfo.empty());
222             } finally {
223                 ON_TASK_COMPLETION_THREAD_TL.set(null);
224             }
225         }
226
227         @Override
228         protected boolean setException(final Throwable throwable) {
229             ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
230             try {
231                 return super.setException(throwable);
232             } finally {
233                 ON_TASK_COMPLETION_THREAD_TL.set(null);
234             }
235         }
236
237         private static final class DelegatingRunnable implements Runnable {
238             private final Runnable delegate;
239             private final Executor executor;
240
241             DelegatingRunnable(final Runnable delegate, final Executor executor) {
242                 this.delegate = requireNonNull(delegate);
243                 this.executor = requireNonNull(executor);
244             }
245
246             @Override
247             public void run() {
248                 if (ON_TASK_COMPLETION_THREAD_TL.get() != null) {
249                     // We're running on the task completion thread so off-load to the executor.
250                     LOG.trace("Submitting ListenenableFuture Runnable from thread {} to executor {}",
251                             Thread.currentThread().getName(), executor);
252                     executor.execute(delegate);
253                 } else {
254                     // We're not running on the task completion thread so run the delegate inline.
255                     LOG.trace("Executing ListenenableFuture Runnable on this thread: {}",
256                             Thread.currentThread().getName());
257                     delegate.run();
258                 }
259             }
260         }
261     }
262
263     @Override
264     public String toString() {
265         return "Clustered ConcurrentDOMDataBroker";
266     }
267 }