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.datastore;
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;
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;
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.
42 * @author Thomas Pantelis
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";
50 private final DurationStatisticsTracker commitStatsTracker = DurationStatisticsTracker.createConcurrent();
53 * This executor is used to execute Future listener callback Runnables async.
55 private final Executor clientFutureCallbackExecutor;
57 public ConcurrentDOMDataBroker(final Map<LogicalDatastoreType, DOMStore> datastores, Executor listenableFutureExecutor) {
59 this.clientFutureCallbackExecutor = Preconditions.checkNotNull(listenableFutureExecutor);
62 public DurationStatisticsTracker getCommitStatsTracker() {
63 return commitStatsTracker;
67 protected CheckedFuture<Void, TransactionCommitFailedException> submit(DOMDataWriteTransaction transaction,
68 Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
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());
74 if(cohorts.isEmpty()){
75 return Futures.immediateCheckedFuture(null);
78 final AsyncNotifyingSettableFuture clientSubmitFuture =
79 new AsyncNotifyingSettableFuture(clientFutureCallbackExecutor);
81 doCanCommit(clientSubmitFuture, transaction, cohorts);
83 return MappingCheckedFuture.create(clientSubmitFuture,
84 TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER);
87 private void doCanCommit(final AsyncNotifyingSettableFuture clientSubmitFuture,
88 final DOMDataWriteTransaction transaction,
89 final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
91 final long startTime = System.nanoTime();
93 final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();
95 // Not using Futures.allAsList here to avoid its internal overhead.
96 FutureCallback<Boolean> futureCallback = new FutureCallback<Boolean>() {
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."));
105 if(!cohortIterator.hasNext()) {
106 // All cohorts completed successfully - we can move on to the preCommit phase
107 doPreCommit(startTime, clientSubmitFuture, transaction, cohorts);
109 ListenableFuture<Boolean> canCommitFuture = cohortIterator.next().canCommit();
110 Futures.addCallback(canCommitFuture, this, MoreExecutors.directExecutor());
116 public void onFailure(Throwable t) {
117 handleException(clientSubmitFuture, transaction, cohorts, CAN_COMMIT,
118 TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER, t);
122 ListenableFuture<Boolean> canCommitFuture = cohortIterator.next().canCommit();
123 Futures.addCallback(canCommitFuture, futureCallback, MoreExecutors.directExecutor());
126 private void doPreCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
127 final DOMDataWriteTransaction transaction,
128 final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
130 final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();
132 // Not using Futures.allAsList here to avoid its internal overhead.
133 FutureCallback<Void> futureCallback = new FutureCallback<Void>() {
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);
140 ListenableFuture<Void> preCommitFuture = cohortIterator.next().preCommit();
141 Futures.addCallback(preCommitFuture, this, MoreExecutors.directExecutor());
146 public void onFailure(Throwable t) {
147 handleException(clientSubmitFuture, transaction, cohorts, PRE_COMMIT,
148 TransactionCommitFailedExceptionMapper.PRE_COMMIT_MAPPER, t);
152 ListenableFuture<Void> preCommitFuture = cohortIterator.next().preCommit();
153 Futures.addCallback(preCommitFuture, futureCallback, MoreExecutors.directExecutor());
156 private void doCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
157 final DOMDataWriteTransaction transaction,
158 final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
160 final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();
162 // Not using Futures.allAsList here to avoid its internal overhead.
163 FutureCallback<Void> futureCallback = new FutureCallback<Void>() {
165 public void onSuccess(Void notUsed) {
166 if(!cohortIterator.hasNext()) {
167 // All cohorts completed successfully - we're done.
168 commitStatsTracker.addDuration(System.nanoTime() - startTime);
170 clientSubmitFuture.set();
172 ListenableFuture<Void> commitFuture = cohortIterator.next().commit();
173 Futures.addCallback(commitFuture, this, MoreExecutors.directExecutor());
178 public void onFailure(Throwable t) {
179 handleException(clientSubmitFuture, transaction, cohorts, COMMIT,
180 TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER, t);
184 ListenableFuture<Void> commitFuture = cohortIterator.next().commit();
185 Futures.addCallback(commitFuture, futureCallback, MoreExecutors.directExecutor());
188 private static void handleException(final AsyncNotifyingSettableFuture clientSubmitFuture,
189 final DOMDataWriteTransaction transaction,
190 final Collection<DOMStoreThreePhaseCommitCohort> cohorts,
191 final String phase, final TransactionCommitFailedExceptionMapper exMapper,
194 if (clientSubmitFuture.isDone()) {
195 // We must have had failures from multiple cohorts.
199 LOG.warn("Tx: {} Error during phase {}, starting Abort", transaction.getIdentifier(), phase, t);
201 if(t instanceof NoShardLeaderException || t instanceof ShardLeaderNotRespondingException) {
202 e = new DataStoreUnavailableException(t.getMessage(), t);
203 } else if (t instanceof Exception) {
206 e = new RuntimeException("Unexpected error occurred", t);
209 final TransactionCommitFailedException clientException = exMapper.apply(e);
211 // Transaction failed - tell all cohorts to abort.
213 @SuppressWarnings("unchecked")
214 ListenableFuture<Void>[] canCommitFutures = new ListenableFuture[cohorts.size()];
216 for (DOMStoreThreePhaseCommitCohort cohort : cohorts) {
217 canCommitFutures[i++] = cohort.abort();
220 ListenableFuture<List<Void>> combinedFuture = Futures.allAsList(canCommitFutures);
221 Futures.addCallback(combinedFuture, new FutureCallback<List<Void>>() {
223 public void onSuccess(List<Void> notUsed) {
224 // Propagate the original exception to the client.
225 clientSubmitFuture.setException(clientException);
229 public void onFailure(Throwable t) {
230 LOG.error("Tx: {} Error during Abort.", transaction.getIdentifier(), t);
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);
236 }, MoreExecutors.directExecutor());
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}.
247 * FIXME: This class should probably be moved to yangtools common utils for re-usability and
248 * unified with AsyncNotifyingListenableFutureTask.
250 private static class AsyncNotifyingSettableFuture extends AbstractFuture<Void> {
253 * ThreadLocal used to detect if the task completion thread is running the future listener Runnables.
255 private static final ThreadLocal<Boolean> ON_TASK_COMPLETION_THREAD_TL = new ThreadLocal<Boolean>();
257 private final Executor listenerExecutor;
259 AsyncNotifyingSettableFuture(Executor listenerExecutor) {
260 this.listenerExecutor = Preconditions.checkNotNull(listenerExecutor);
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.
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);
278 ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
280 return super.set(null);
282 ON_TASK_COMPLETION_THREAD_TL.set(null);
287 protected boolean setException(Throwable throwable) {
288 ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
290 return super.setException(throwable);
292 ON_TASK_COMPLETION_THREAD_TL.set(null);
296 private static final class DelegatingRunnable implements Runnable {
297 private final Runnable delegate;
298 private final Executor executor;
300 DelegatingRunnable(final Runnable delegate, final Executor executor) {
301 this.delegate = Preconditions.checkNotNull(delegate);
302 this.executor = Preconditions.checkNotNull(executor);
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);
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());