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.md.sal.dom.broker.impl;
10 import java.util.List;
11 import java.util.concurrent.Executor;
12 import java.util.concurrent.ExecutorService;
13 import java.util.concurrent.TimeUnit;
14 import java.util.concurrent.atomic.AtomicInteger;
15 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
16 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
17 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
18 import org.opendaylight.yangtools.util.DurationStatisticsTracker;
19 import org.opendaylight.yangtools.util.concurrent.MappingCheckedFuture;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22 import com.google.common.base.Preconditions;
23 import com.google.common.collect.Iterables;
24 import com.google.common.util.concurrent.AbstractFuture;
25 import com.google.common.util.concurrent.AbstractListeningExecutorService;
26 import com.google.common.util.concurrent.CheckedFuture;
27 import com.google.common.util.concurrent.FutureCallback;
28 import com.google.common.util.concurrent.Futures;
29 import com.google.common.util.concurrent.ListenableFuture;
32 * Implementation of DOMDataCommitExecutor that coordinates transaction commits concurrently. The 3
33 * commit phases (canCommit, preCommit, and commit) are performed serially and non-blocking
34 * (ie async) per transaction but multiple transaction commits can run concurrent.
36 * @author Thomas Pantelis
38 public class DOMConcurrentDataCommitCoordinator implements DOMDataCommitExecutor {
40 private static final String CAN_COMMIT = "CAN_COMMIT";
41 private static final String PRE_COMMIT = "PRE_COMMIT";
42 private static final String COMMIT = "COMMIT";
44 private static final Logger LOG = LoggerFactory.getLogger(DOMConcurrentDataCommitCoordinator.class);
46 private final DurationStatisticsTracker commitStatsTracker = DurationStatisticsTracker.createConcurrent();
49 * This executor is used to execute Future listener callback Runnables async.
51 private final ExecutorService clientFutureCallbackExecutor;
54 * This executor is re-used internally in calls to Futures#addCallback to avoid the overhead
55 * of Futures#addCallback creating a MoreExecutors#sameThreadExecutor for each call.
57 private final ExecutorService internalFutureCallbackExecutor = new SimpleSameThreadExecutor();
59 public DOMConcurrentDataCommitCoordinator(ExecutorService listenableFutureExecutor) {
60 this.clientFutureCallbackExecutor = Preconditions.checkNotNull(listenableFutureExecutor);
63 public DurationStatisticsTracker getCommitStatsTracker() {
64 return commitStatsTracker;
68 public CheckedFuture<Void, TransactionCommitFailedException> submit(DOMDataWriteTransaction transaction,
69 Iterable<DOMStoreThreePhaseCommitCohort> cohorts) {
71 Preconditions.checkArgument(transaction != null, "Transaction must not be null.");
72 Preconditions.checkArgument(cohorts != null, "Cohorts must not be null.");
73 LOG.debug("Tx: {} is submitted for execution.", transaction.getIdentifier());
75 final int cohortSize = Iterables.size(cohorts);
76 final AsyncNotifyingSettableFuture clientSubmitFuture =
77 new AsyncNotifyingSettableFuture(clientFutureCallbackExecutor);
79 doCanCommit(clientSubmitFuture, transaction, cohorts, cohortSize);
81 return MappingCheckedFuture.create(clientSubmitFuture,
82 TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER);
85 private void doCanCommit(final AsyncNotifyingSettableFuture clientSubmitFuture,
86 final DOMDataWriteTransaction transaction,
87 final Iterable<DOMStoreThreePhaseCommitCohort> cohorts, final int cohortSize) {
89 final long startTime = System.nanoTime();
91 // Not using Futures.allAsList here to avoid its internal overhead.
92 final AtomicInteger remaining = new AtomicInteger(cohortSize);
93 FutureCallback<Boolean> futureCallback = new FutureCallback<Boolean>() {
95 public void onSuccess(Boolean result) {
96 if (result == null || !result) {
97 handleException(clientSubmitFuture, transaction, cohorts, cohortSize,
98 CAN_COMMIT, new TransactionCommitFailedException(
99 "Can Commit failed, no detailed cause available."));
101 if(remaining.decrementAndGet() == 0) {
102 // All cohorts completed successfully - we can move on to the preCommit phase
103 doPreCommit(startTime, clientSubmitFuture, transaction, cohorts, cohortSize);
109 public void onFailure(Throwable t) {
110 handleException(clientSubmitFuture, transaction, cohorts, cohortSize, CAN_COMMIT, t);
114 for(DOMStoreThreePhaseCommitCohort cohort: cohorts) {
115 ListenableFuture<Boolean> canCommitFuture = cohort.canCommit();
116 Futures.addCallback(canCommitFuture, futureCallback, internalFutureCallbackExecutor);
120 private void doPreCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
121 final DOMDataWriteTransaction transaction,
122 final Iterable<DOMStoreThreePhaseCommitCohort> cohorts, final int cohortSize) {
124 // Not using Futures.allAsList here to avoid its internal overhead.
125 final AtomicInteger remaining = new AtomicInteger(cohortSize);
126 FutureCallback<Void> futureCallback = new FutureCallback<Void>() {
128 public void onSuccess(Void notUsed) {
129 if(remaining.decrementAndGet() == 0) {
130 // All cohorts completed successfully - we can move on to the commit phase
131 doCommit(startTime, clientSubmitFuture, transaction, cohorts, cohortSize);
136 public void onFailure(Throwable t) {
137 handleException(clientSubmitFuture, transaction, cohorts, cohortSize, CAN_COMMIT, t);
141 for(DOMStoreThreePhaseCommitCohort cohort: cohorts) {
142 ListenableFuture<Void> preCommitFuture = cohort.preCommit();
143 Futures.addCallback(preCommitFuture, futureCallback, internalFutureCallbackExecutor);
147 private void doCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
148 final DOMDataWriteTransaction transaction,
149 final Iterable<DOMStoreThreePhaseCommitCohort> cohorts, final int cohortSize) {
151 // Not using Futures.allAsList here to avoid its internal overhead.
152 final AtomicInteger remaining = new AtomicInteger(cohortSize);
153 FutureCallback<Void> futureCallback = new FutureCallback<Void>() {
155 public void onSuccess(Void notUsed) {
156 if(remaining.decrementAndGet() == 0) {
157 // All cohorts completed successfully - we're done.
158 commitStatsTracker.addDuration(System.nanoTime() - startTime);
160 clientSubmitFuture.set();
165 public void onFailure(Throwable t) {
166 handleException(clientSubmitFuture, transaction, cohorts, cohortSize, CAN_COMMIT, t);
170 for(DOMStoreThreePhaseCommitCohort cohort: cohorts) {
171 ListenableFuture<Void> commitFuture = cohort.commit();
172 Futures.addCallback(commitFuture, futureCallback, internalFutureCallbackExecutor);
176 private void handleException(final AsyncNotifyingSettableFuture clientSubmitFuture,
177 final DOMDataWriteTransaction transaction,
178 final Iterable<DOMStoreThreePhaseCommitCohort> cohorts, int cohortSize,
179 final String phase, final Throwable t) {
181 if(clientSubmitFuture.isDone()) {
182 // We must have had failures from multiple cohorts.
186 LOG.warn("Tx: {} Error during phase {}, starting Abort", transaction.getIdentifier(), phase, t);
188 if(t instanceof Exception) {
191 e = new RuntimeException("Unexpected error occurred", t);
194 final TransactionCommitFailedException clientException =
195 TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER.apply(e);
197 // Transaction failed - tell all cohorts to abort.
199 @SuppressWarnings("unchecked")
200 ListenableFuture<Void>[] canCommitFutures = new ListenableFuture[cohortSize];
202 for(DOMStoreThreePhaseCommitCohort cohort: cohorts) {
203 canCommitFutures[i++] = cohort.abort();
206 ListenableFuture<List<Void>> combinedFuture = Futures.allAsList(canCommitFutures);
207 Futures.addCallback(combinedFuture, new FutureCallback<List<Void>>() {
209 public void onSuccess(List<Void> notUsed) {
210 // Propagate the original exception to the client.
211 clientSubmitFuture.setException(clientException);
215 public void onFailure(Throwable t) {
216 LOG.error("Tx: {} Error during Abort.", transaction.getIdentifier(), t);
218 // Propagate the original exception as that is what caused the Tx to fail and is
219 // what's interesting to the client.
220 clientSubmitFuture.setException(clientException);
222 }, internalFutureCallbackExecutor);
226 * A settable future that uses an {@link Executor} to execute listener callback Runnables,
227 * registered via {@link #addListener}, asynchronously when this future completes. This is
228 * done to guarantee listener executions are off-loaded onto another thread to avoid blocking
229 * the thread that completed this future, as a common use case is to pass an executor that runs
230 * tasks in the same thread as the caller (ie MoreExecutors#sameThreadExecutor)
231 * to {@link #addListener}.
233 * FIXME: This class should probably be moved to yangtools common utils for re-usability and
234 * unified with AsyncNotifyingListenableFutureTask.
236 private static class AsyncNotifyingSettableFuture extends AbstractFuture<Void> {
239 * ThreadLocal used to detect if the task completion thread is running the future listener Runnables.
241 private static final ThreadLocal<Boolean> ON_TASK_COMPLETION_THREAD_TL = new ThreadLocal<Boolean>();
243 private final ExecutorService listenerExecutor;
245 AsyncNotifyingSettableFuture(ExecutorService listenerExecutor) {
246 this.listenerExecutor = listenerExecutor;
250 public void addListener(final Runnable listener, final Executor executor) {
251 // Wrap the listener Runnable in a DelegatingRunnable. If the specified executor is one
252 // that runs tasks in the same thread as the caller submitting the task
253 // (e.g. {@link com.google.common.util.concurrent.MoreExecutors#sameThreadExecutor}) and
254 // the listener is executed from the #set methods, then the DelegatingRunnable will detect
255 // this via the ThreadLocal and submit the listener Runnable to the listenerExecutor.
257 // On the other hand, if this task is already complete, the call to ExecutionList#add in
258 // superclass will execute the listener Runnable immediately and, since the ThreadLocal
259 // won't be set, the DelegatingRunnable will run the listener Runnable inline.
260 super.addListener(new DelegatingRunnable(listener, listenerExecutor), executor);
264 ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
266 return super.set(null);
268 ON_TASK_COMPLETION_THREAD_TL.set(null);
273 protected boolean setException(Throwable throwable) {
274 ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
276 return super.setException(throwable);
278 ON_TASK_COMPLETION_THREAD_TL.set(null);
282 private static final class DelegatingRunnable implements Runnable {
283 private final Runnable delegate;
284 private final Executor executor;
286 DelegatingRunnable(final Runnable delegate, final Executor executor) {
287 this.delegate = Preconditions.checkNotNull(delegate);
288 this.executor = Preconditions.checkNotNull(executor);
293 if (ON_TASK_COMPLETION_THREAD_TL.get() != null) {
294 // We're running on the task completion thread so off-load to the executor.
295 LOG.trace("Submitting ListenenableFuture Runnable from thread {} to executor {}",
296 Thread.currentThread().getName(), executor);
297 executor.execute(delegate);
299 // We're not running on the task completion thread so run the delegate inline.
300 LOG.trace("Executing ListenenableFuture Runnable on this thread: {}",
301 Thread.currentThread().getName());
309 * A simple same-thread executor without the internal locking overhead that
310 * MoreExecutors#sameThreadExecutor has. The #execute method is the only one of concern - we
311 * don't shutdown the executor so the other methods irrelevant.
313 private static class SimpleSameThreadExecutor extends AbstractListeningExecutorService {
316 public void execute(Runnable command) {
321 public boolean awaitTermination(long arg0, TimeUnit arg1) throws InterruptedException {
326 public boolean isShutdown() {
331 public boolean isTerminated() {
336 public void shutdown() {
340 public List<Runnable> shutdownNow() {