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.AbstractListeningExecutorService;
13 import com.google.common.util.concurrent.CheckedFuture;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import java.util.Collection;
18 import java.util.List;
20 import java.util.concurrent.Executor;
21 import java.util.concurrent.ExecutorService;
22 import java.util.concurrent.TimeUnit;
23 import java.util.concurrent.atomic.AtomicInteger;
24 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
25 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
26 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
27 import org.opendaylight.controller.md.sal.dom.broker.impl.AbstractDOMDataBroker;
28 import org.opendaylight.controller.md.sal.dom.broker.impl.TransactionCommitFailedExceptionMapper;
29 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
30 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
31 import org.opendaylight.yangtools.util.DurationStatisticsTracker;
32 import org.opendaylight.yangtools.util.concurrent.MappingCheckedFuture;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
37 * Implementation of DOMDataCommitExecutor that coordinates transaction commits concurrently. The 3
38 * commit phases (canCommit, preCommit, and commit) are performed serially and non-blocking
39 * (ie async) per transaction but multiple transaction commits can run concurrent.
41 * @author Thomas Pantelis
43 public class ConcurrentDOMDataBroker extends AbstractDOMDataBroker {
44 private static final Logger LOG = LoggerFactory.getLogger(ConcurrentDOMDataBroker.class);
45 private static final String CAN_COMMIT = "CAN_COMMIT";
46 private static final String PRE_COMMIT = "PRE_COMMIT";
47 private static final String COMMIT = "COMMIT";
49 private final DurationStatisticsTracker commitStatsTracker = DurationStatisticsTracker.createConcurrent();
52 * This executor is used to execute Future listener callback Runnables async.
54 private final ExecutorService clientFutureCallbackExecutor;
57 * This executor is re-used internally in calls to Futures#addCallback to avoid the overhead
58 * of Futures#addCallback creating a MoreExecutors#sameThreadExecutor for each call.
60 private final ExecutorService internalFutureCallbackExecutor = new SimpleSameThreadExecutor();
62 public ConcurrentDOMDataBroker(final Map<LogicalDatastoreType, DOMStore> datastores, ExecutorService listenableFutureExecutor) {
64 this.clientFutureCallbackExecutor = Preconditions.checkNotNull(listenableFutureExecutor);
67 public DurationStatisticsTracker getCommitStatsTracker() {
68 return commitStatsTracker;
72 public CheckedFuture<Void, TransactionCommitFailedException> submit(DOMDataWriteTransaction transaction,
73 Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
75 Preconditions.checkArgument(transaction != null, "Transaction must not be null.");
76 Preconditions.checkArgument(cohorts != null, "Cohorts must not be null.");
77 LOG.debug("Tx: {} is submitted for execution.", transaction.getIdentifier());
79 final AsyncNotifyingSettableFuture clientSubmitFuture =
80 new AsyncNotifyingSettableFuture(clientFutureCallbackExecutor);
82 doCanCommit(clientSubmitFuture, transaction, cohorts);
84 return MappingCheckedFuture.create(clientSubmitFuture,
85 TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER);
88 private void doCanCommit(final AsyncNotifyingSettableFuture clientSubmitFuture,
89 final DOMDataWriteTransaction transaction,
90 final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
92 final long startTime = System.nanoTime();
94 // Not using Futures.allAsList here to avoid its internal overhead.
95 final AtomicInteger remaining = new AtomicInteger(cohorts.size());
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(remaining.decrementAndGet() == 0) {
106 // All cohorts completed successfully - we can move on to the preCommit phase
107 doPreCommit(startTime, clientSubmitFuture, transaction, cohorts);
113 public void onFailure(Throwable t) {
114 handleException(clientSubmitFuture, transaction, cohorts, CAN_COMMIT,
115 TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER, t);
119 for(DOMStoreThreePhaseCommitCohort cohort: cohorts) {
120 ListenableFuture<Boolean> canCommitFuture = cohort.canCommit();
121 Futures.addCallback(canCommitFuture, futureCallback, internalFutureCallbackExecutor);
125 private void doPreCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
126 final DOMDataWriteTransaction transaction,
127 final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
129 // Not using Futures.allAsList here to avoid its internal overhead.
130 final AtomicInteger remaining = new AtomicInteger(cohorts.size());
131 FutureCallback<Void> futureCallback = new FutureCallback<Void>() {
133 public void onSuccess(Void notUsed) {
134 if(remaining.decrementAndGet() == 0) {
135 // All cohorts completed successfully - we can move on to the commit phase
136 doCommit(startTime, clientSubmitFuture, transaction, cohorts);
141 public void onFailure(Throwable t) {
142 handleException(clientSubmitFuture, transaction, cohorts, PRE_COMMIT,
143 TransactionCommitFailedExceptionMapper.PRE_COMMIT_MAPPER, t);
147 for(DOMStoreThreePhaseCommitCohort cohort: cohorts) {
148 ListenableFuture<Void> preCommitFuture = cohort.preCommit();
149 Futures.addCallback(preCommitFuture, futureCallback, internalFutureCallbackExecutor);
153 private void doCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
154 final DOMDataWriteTransaction transaction,
155 final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
157 // Not using Futures.allAsList here to avoid its internal overhead.
158 final AtomicInteger remaining = new AtomicInteger(cohorts.size());
159 FutureCallback<Void> futureCallback = new FutureCallback<Void>() {
161 public void onSuccess(Void notUsed) {
162 if(remaining.decrementAndGet() == 0) {
163 // All cohorts completed successfully - we're done.
164 commitStatsTracker.addDuration(System.nanoTime() - startTime);
166 clientSubmitFuture.set();
171 public void onFailure(Throwable t) {
172 handleException(clientSubmitFuture, transaction, cohorts, COMMIT,
173 TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER, t);
177 for(DOMStoreThreePhaseCommitCohort cohort: cohorts) {
178 ListenableFuture<Void> commitFuture = cohort.commit();
179 Futures.addCallback(commitFuture, futureCallback, internalFutureCallbackExecutor);
183 private void handleException(final AsyncNotifyingSettableFuture clientSubmitFuture,
184 final DOMDataWriteTransaction transaction,
185 final Collection<DOMStoreThreePhaseCommitCohort> cohorts,
186 final String phase, final TransactionCommitFailedExceptionMapper exMapper,
189 if(clientSubmitFuture.isDone()) {
190 // We must have had failures from multiple cohorts.
194 LOG.warn("Tx: {} Error during phase {}, starting Abort", transaction.getIdentifier(), phase, t);
196 if(t instanceof Exception) {
199 e = new RuntimeException("Unexpected error occurred", t);
202 final TransactionCommitFailedException clientException = exMapper.apply(e);
204 // Transaction failed - tell all cohorts to abort.
206 @SuppressWarnings("unchecked")
207 ListenableFuture<Void>[] canCommitFutures = new ListenableFuture[cohorts.size()];
209 for(DOMStoreThreePhaseCommitCohort cohort: cohorts) {
210 canCommitFutures[i++] = cohort.abort();
213 ListenableFuture<List<Void>> combinedFuture = Futures.allAsList(canCommitFutures);
214 Futures.addCallback(combinedFuture, new FutureCallback<List<Void>>() {
216 public void onSuccess(List<Void> notUsed) {
217 // Propagate the original exception to the client.
218 clientSubmitFuture.setException(clientException);
222 public void onFailure(Throwable t) {
223 LOG.error("Tx: {} Error during Abort.", transaction.getIdentifier(), t);
225 // Propagate the original exception as that is what caused the Tx to fail and is
226 // what's interesting to the client.
227 clientSubmitFuture.setException(clientException);
229 }, internalFutureCallbackExecutor);
233 * A settable future that uses an {@link Executor} to execute listener callback Runnables,
234 * registered via {@link #addListener}, asynchronously when this future completes. This is
235 * done to guarantee listener executions are off-loaded onto another thread to avoid blocking
236 * the thread that completed this future, as a common use case is to pass an executor that runs
237 * tasks in the same thread as the caller (ie MoreExecutors#sameThreadExecutor)
238 * to {@link #addListener}.
240 * FIXME: This class should probably be moved to yangtools common utils for re-usability and
241 * unified with AsyncNotifyingListenableFutureTask.
243 private static class AsyncNotifyingSettableFuture extends AbstractFuture<Void> {
246 * ThreadLocal used to detect if the task completion thread is running the future listener Runnables.
248 private static final ThreadLocal<Boolean> ON_TASK_COMPLETION_THREAD_TL = new ThreadLocal<Boolean>();
250 private final ExecutorService listenerExecutor;
252 AsyncNotifyingSettableFuture(ExecutorService listenerExecutor) {
253 this.listenerExecutor = listenerExecutor;
257 public void addListener(final Runnable listener, final Executor executor) {
258 // Wrap the listener Runnable in a DelegatingRunnable. If the specified executor is one
259 // that runs tasks in the same thread as the caller submitting the task
260 // (e.g. {@link com.google.common.util.concurrent.MoreExecutors#sameThreadExecutor}) and
261 // the listener is executed from the #set methods, then the DelegatingRunnable will detect
262 // this via the ThreadLocal and submit the listener Runnable to the listenerExecutor.
264 // On the other hand, if this task is already complete, the call to ExecutionList#add in
265 // superclass will execute the listener Runnable immediately and, since the ThreadLocal
266 // won't be set, the DelegatingRunnable will run the listener Runnable inline.
267 super.addListener(new DelegatingRunnable(listener, listenerExecutor), executor);
271 ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
273 return super.set(null);
275 ON_TASK_COMPLETION_THREAD_TL.set(null);
280 protected boolean setException(Throwable throwable) {
281 ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
283 return super.setException(throwable);
285 ON_TASK_COMPLETION_THREAD_TL.set(null);
289 private static final class DelegatingRunnable implements Runnable {
290 private final Runnable delegate;
291 private final Executor executor;
293 DelegatingRunnable(final Runnable delegate, final Executor executor) {
294 this.delegate = Preconditions.checkNotNull(delegate);
295 this.executor = Preconditions.checkNotNull(executor);
300 if (ON_TASK_COMPLETION_THREAD_TL.get() != null) {
301 // We're running on the task completion thread so off-load to the executor.
302 LOG.trace("Submitting ListenenableFuture Runnable from thread {} to executor {}",
303 Thread.currentThread().getName(), executor);
304 executor.execute(delegate);
306 // We're not running on the task completion thread so run the delegate inline.
307 LOG.trace("Executing ListenenableFuture Runnable on this thread: {}",
308 Thread.currentThread().getName());
316 * A simple same-thread executor without the internal locking overhead that
317 * MoreExecutors#sameThreadExecutor has. The #execute method is the only one of concern - we
318 * don't shutdown the executor so the other methods irrelevant.
320 private static class SimpleSameThreadExecutor extends AbstractListeningExecutorService {
323 public void execute(Runnable command) {
328 public boolean awaitTermination(long arg0, TimeUnit arg1) throws InterruptedException {
333 public boolean isShutdown() {
338 public boolean isTerminated() {
343 public void shutdown() {
347 public List<Runnable> shutdownNow() {