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