2 * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.cluster.databroker;
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;
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;
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;
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.
45 * @author Thomas Pantelis
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";
54 private final DurationStatisticsTracker commitStatsTracker;
57 * This executor is used to execute Future listener callback Runnables async.
59 private final Executor clientFutureCallbackExecutor;
61 public ConcurrentDOMDataBroker(final Map<LogicalDatastoreType, DOMStore> datastores,
62 final Executor listenableFutureExecutor) {
63 this(datastores, listenableFutureExecutor, DurationStatisticsTracker.createConcurrent());
66 public ConcurrentDOMDataBroker(final Map<LogicalDatastoreType, DOMStore> datastores,
67 final Executor listenableFutureExecutor, final DurationStatisticsTracker commitStatsTracker) {
69 clientFutureCallbackExecutor = requireNonNull(listenableFutureExecutor);
70 this.commitStatsTracker = requireNonNull(commitStatsTracker);
73 public DurationStatisticsTracker getCommitStatsTracker() {
74 return commitStatsTracker;
78 protected FluentFuture<? extends CommitInfo> commit(final DOMDataTreeWriteTransaction transaction,
79 final DOMStoreThreePhaseCommitCohort cohort) {
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());
85 final AsyncNotifyingSettableFuture clientSubmitFuture =
86 new AsyncNotifyingSettableFuture(clientFutureCallbackExecutor);
88 doCanCommit(clientSubmitFuture, transaction, cohort);
89 return FluentFuture.from(clientSubmitFuture);
92 private void doCanCommit(final AsyncNotifyingSettableFuture clientSubmitFuture,
93 final DOMDataTreeWriteTransaction transaction,
94 final DOMStoreThreePhaseCommitCohort cohort) {
95 final long startTime = System.nanoTime();
97 Futures.addCallback(cohort.canCommit(), new FutureCallback<>() {
99 public void onSuccess(final Boolean result) {
100 if (result == null || !result) {
101 onFailure(new TransactionCommitFailedException("Can Commit failed, no detailed cause available."));
103 doPreCommit(startTime, clientSubmitFuture, transaction, cohort);
108 public void onFailure(final Throwable failure) {
109 handleException(clientSubmitFuture, transaction, cohort, CAN_COMMIT, CAN_COMMIT_ERROR_MAPPER, failure);
111 }, MoreExecutors.directExecutor());
114 private void doPreCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
115 final DOMDataTreeWriteTransaction transaction, final DOMStoreThreePhaseCommitCohort cohort) {
116 Futures.addCallback(cohort.preCommit(), new FutureCallback<>() {
118 public void onSuccess(final Empty result) {
119 doCommit(startTime, clientSubmitFuture, transaction, cohort);
123 public void onFailure(final Throwable failure) {
124 handleException(clientSubmitFuture, transaction, cohort, PRE_COMMIT, PRE_COMMIT_MAPPER, failure);
126 }, MoreExecutors.directExecutor());
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>() {
133 public void onSuccess(final CommitInfo result) {
134 commitStatsTracker.addDuration(System.nanoTime() - startTime);
135 clientSubmitFuture.set();
139 public void onFailure(final Throwable throwable) {
140 handleException(clientSubmitFuture, transaction, cohort, COMMIT, COMMIT_ERROR_MAPPER, throwable);
142 }, MoreExecutors.directExecutor());
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.
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);
156 // Propagate the original exception
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;
163 e = new RuntimeException("Unexpected error occurred", throwable);
165 clientSubmitFuture.setException(exMapper.apply(e));
168 Futures.addCallback(cohort.abort(), new FutureCallback<Empty>() {
170 public void onSuccess(final Empty result) {
171 // Propagate the original exception to the client.
172 LOG.debug("Tx: {} aborted successfully", transaction.getIdentifier());
176 public void onFailure(final Throwable failure) {
177 LOG.error("Tx: {} Error during Abort.", transaction.getIdentifier(), failure);
179 }, MoreExecutors.directExecutor());
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.
192 private static class AsyncNotifyingSettableFuture extends AbstractFuture<CommitInfo> {
194 * ThreadLocal used to detect if the task completion thread is running the future listener Runnables.
196 private static final ThreadLocal<Boolean> ON_TASK_COMPLETION_THREAD_TL = new ThreadLocal<>();
198 private final Executor listenerExecutor;
200 AsyncNotifyingSettableFuture(final Executor listenerExecutor) {
201 this.listenerExecutor = requireNonNull(listenerExecutor);
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.
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);
219 ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
221 return super.set(CommitInfo.empty());
223 ON_TASK_COMPLETION_THREAD_TL.set(null);
228 protected boolean setException(final Throwable throwable) {
229 ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
231 return super.setException(throwable);
233 ON_TASK_COMPLETION_THREAD_TL.set(null);
237 private static final class DelegatingRunnable implements Runnable {
238 private final Runnable delegate;
239 private final Executor executor;
241 DelegatingRunnable(final Runnable delegate, final Executor executor) {
242 this.delegate = requireNonNull(delegate);
243 this.executor = requireNonNull(executor);
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);
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());
264 public String toString() {
265 return "Clustered ConcurrentDOMDataBroker";