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.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;
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.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;
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.
44 * @author Thomas Pantelis
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";
53 private final DurationStatisticsTracker commitStatsTracker;
56 * This executor is used to execute Future listener callback Runnables async.
58 private final Executor clientFutureCallbackExecutor;
60 public ConcurrentDOMDataBroker(final Map<LogicalDatastoreType, DOMStore> datastores,
61 final Executor listenableFutureExecutor) {
62 this(datastores, listenableFutureExecutor, DurationStatisticsTracker.createConcurrent());
65 public ConcurrentDOMDataBroker(final Map<LogicalDatastoreType, DOMStore> datastores,
66 final Executor listenableFutureExecutor, final DurationStatisticsTracker commitStatsTracker) {
68 clientFutureCallbackExecutor = requireNonNull(listenableFutureExecutor);
69 this.commitStatsTracker = requireNonNull(commitStatsTracker);
72 public DurationStatisticsTracker getCommitStatsTracker() {
73 return commitStatsTracker;
77 protected FluentFuture<? extends CommitInfo> commit(final DOMDataTreeWriteTransaction transaction,
78 final DOMStoreThreePhaseCommitCohort cohort) {
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());
84 final AsyncNotifyingSettableFuture clientSubmitFuture =
85 new AsyncNotifyingSettableFuture(clientFutureCallbackExecutor);
87 doCanCommit(clientSubmitFuture, transaction, cohort);
88 return FluentFuture.from(clientSubmitFuture);
91 private void doCanCommit(final AsyncNotifyingSettableFuture clientSubmitFuture,
92 final DOMDataTreeWriteTransaction transaction,
93 final DOMStoreThreePhaseCommitCohort cohort) {
94 final long startTime = System.nanoTime();
96 Futures.addCallback(cohort.canCommit(), new FutureCallback<>() {
98 public void onSuccess(final Boolean result) {
99 if (result == null || !result) {
100 onFailure(new TransactionCommitFailedException("Can Commit failed, no detailed cause available."));
102 doPreCommit(startTime, clientSubmitFuture, transaction, cohort);
107 public void onFailure(final Throwable failure) {
108 handleException(clientSubmitFuture, transaction, cohort, CAN_COMMIT, CAN_COMMIT_ERROR_MAPPER, failure);
110 }, MoreExecutors.directExecutor());
113 private void doPreCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
114 final DOMDataTreeWriteTransaction transaction, final DOMStoreThreePhaseCommitCohort cohort) {
115 Futures.addCallback(cohort.preCommit(), new FutureCallback<>() {
117 public void onSuccess(final Empty result) {
118 doCommit(startTime, clientSubmitFuture, transaction, cohort);
122 public void onFailure(final Throwable failure) {
123 handleException(clientSubmitFuture, transaction, cohort, PRE_COMMIT, PRE_COMMIT_MAPPER, failure);
125 }, MoreExecutors.directExecutor());
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>() {
132 public void onSuccess(final CommitInfo result) {
133 commitStatsTracker.addDuration(System.nanoTime() - startTime);
134 clientSubmitFuture.set();
138 public void onFailure(final Throwable throwable) {
139 handleException(clientSubmitFuture, transaction, cohort, COMMIT, COMMIT_ERROR_MAPPER, throwable);
141 }, MoreExecutors.directExecutor());
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.
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);
155 // Propagate the original exception
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;
162 e = new RuntimeException("Unexpected error occurred", throwable);
164 clientSubmitFuture.setException(exMapper.apply(e));
167 Futures.addCallback(cohort.abort(), new FutureCallback<Empty>() {
169 public void onSuccess(final Empty result) {
170 // Propagate the original exception to the client.
171 LOG.debug("Tx: {} aborted successfully", transaction.getIdentifier());
175 public void onFailure(final Throwable failure) {
176 LOG.error("Tx: {} Error during Abort.", transaction.getIdentifier(), failure);
178 }, MoreExecutors.directExecutor());
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.
191 private static class AsyncNotifyingSettableFuture extends AbstractFuture<CommitInfo> {
193 * ThreadLocal used to detect if the task completion thread is running the future listener Runnables.
195 private static final ThreadLocal<Boolean> ON_TASK_COMPLETION_THREAD_TL = new ThreadLocal<>();
197 private final Executor listenerExecutor;
199 AsyncNotifyingSettableFuture(final Executor listenerExecutor) {
200 this.listenerExecutor = requireNonNull(listenerExecutor);
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.
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);
218 ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
220 return super.set(CommitInfo.empty());
222 ON_TASK_COMPLETION_THREAD_TL.set(null);
227 protected boolean setException(final Throwable throwable) {
228 ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
230 return super.setException(throwable);
232 ON_TASK_COMPLETION_THREAD_TL.set(null);
236 private static final class DelegatingRunnable implements Runnable {
237 private final Runnable delegate;
238 private final Executor executor;
240 DelegatingRunnable(final Runnable delegate, final Executor executor) {
241 this.delegate = requireNonNull(delegate);
242 this.executor = requireNonNull(executor);
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);
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());
263 public String toString() {
264 return "Clustered ConcurrentDOMDataBroker";