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 com.google.common.base.Preconditions;
11 import com.google.common.collect.Iterables;
12 import com.google.common.util.concurrent.AbstractFuture;
13 import com.google.common.util.concurrent.AbstractListeningExecutorService;
14 import com.google.common.util.concurrent.CheckedFuture;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.Futures;
17 import com.google.common.util.concurrent.ListenableFuture;
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.sal.core.spi.data.DOMStore;
28 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
29 import org.opendaylight.yangtools.util.DurationStatisticsTracker;
30 import org.opendaylight.yangtools.util.concurrent.MappingCheckedFuture;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
35 * Implementation of DOMDataCommitExecutor that coordinates transaction commits concurrently. The 3
36 * commit phases (canCommit, preCommit, and commit) are performed serially and non-blocking
37 * (ie async) per transaction but multiple transaction commits can run concurrent.
39 * @author Thomas Pantelis
41 public class ConcurrentDOMDataBroker extends AbstractDOMDataBroker {
42 private static final Logger LOG = LoggerFactory.getLogger(ConcurrentDOMDataBroker.class);
43 private static final String CAN_COMMIT = "CAN_COMMIT";
44 private static final String PRE_COMMIT = "PRE_COMMIT";
45 private static final String COMMIT = "COMMIT";
47 private final DurationStatisticsTracker commitStatsTracker = DurationStatisticsTracker.createConcurrent();
50 * This executor is used to execute Future listener callback Runnables async.
52 private final ExecutorService clientFutureCallbackExecutor;
55 * This executor is re-used internally in calls to Futures#addCallback to avoid the overhead
56 * of Futures#addCallback creating a MoreExecutors#sameThreadExecutor for each call.
58 private final ExecutorService internalFutureCallbackExecutor = new SimpleSameThreadExecutor();
60 public ConcurrentDOMDataBroker(final Map<LogicalDatastoreType, DOMStore> datastores, ExecutorService listenableFutureExecutor) {
62 this.clientFutureCallbackExecutor = Preconditions.checkNotNull(listenableFutureExecutor);
65 public DurationStatisticsTracker getCommitStatsTracker() {
66 return commitStatsTracker;
70 public CheckedFuture<Void, TransactionCommitFailedException> submit(DOMDataWriteTransaction transaction,
71 Iterable<DOMStoreThreePhaseCommitCohort> cohorts) {
73 Preconditions.checkArgument(transaction != null, "Transaction must not be null.");
74 Preconditions.checkArgument(cohorts != null, "Cohorts must not be null.");
75 LOG.debug("Tx: {} is submitted for execution.", transaction.getIdentifier());
77 final int cohortSize = Iterables.size(cohorts);
78 final AsyncNotifyingSettableFuture clientSubmitFuture =
79 new AsyncNotifyingSettableFuture(clientFutureCallbackExecutor);
81 doCanCommit(clientSubmitFuture, transaction, cohorts, cohortSize);
83 return MappingCheckedFuture.create(clientSubmitFuture,
84 TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER);
87 private void doCanCommit(final AsyncNotifyingSettableFuture clientSubmitFuture,
88 final DOMDataWriteTransaction transaction,
89 final Iterable<DOMStoreThreePhaseCommitCohort> cohorts, final int cohortSize) {
91 final long startTime = System.nanoTime();
93 // Not using Futures.allAsList here to avoid its internal overhead.
94 final AtomicInteger remaining = new AtomicInteger(cohortSize);
95 FutureCallback<Boolean> futureCallback = new FutureCallback<Boolean>() {
97 public void onSuccess(Boolean result) {
98 if (result == null || !result) {
99 handleException(clientSubmitFuture, transaction, cohorts, cohortSize,
100 CAN_COMMIT, TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER,
101 new TransactionCommitFailedException(
102 "Can Commit failed, no detailed cause available."));
104 if(remaining.decrementAndGet() == 0) {
105 // All cohorts completed successfully - we can move on to the preCommit phase
106 doPreCommit(startTime, clientSubmitFuture, transaction, cohorts, cohortSize);
112 public void onFailure(Throwable t) {
113 handleException(clientSubmitFuture, transaction, cohorts, cohortSize, CAN_COMMIT,
114 TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER, t);
118 for(DOMStoreThreePhaseCommitCohort cohort: cohorts) {
119 ListenableFuture<Boolean> canCommitFuture = cohort.canCommit();
120 Futures.addCallback(canCommitFuture, futureCallback, internalFutureCallbackExecutor);
124 private void doPreCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
125 final DOMDataWriteTransaction transaction,
126 final Iterable<DOMStoreThreePhaseCommitCohort> cohorts, final int cohortSize) {
128 // Not using Futures.allAsList here to avoid its internal overhead.
129 final AtomicInteger remaining = new AtomicInteger(cohortSize);
130 FutureCallback<Void> futureCallback = new FutureCallback<Void>() {
132 public void onSuccess(Void notUsed) {
133 if(remaining.decrementAndGet() == 0) {
134 // All cohorts completed successfully - we can move on to the commit phase
135 doCommit(startTime, clientSubmitFuture, transaction, cohorts, cohortSize);
140 public void onFailure(Throwable t) {
141 handleException(clientSubmitFuture, transaction, cohorts, cohortSize, PRE_COMMIT,
142 TransactionCommitFailedExceptionMapper.PRE_COMMIT_MAPPER, t);
146 for(DOMStoreThreePhaseCommitCohort cohort: cohorts) {
147 ListenableFuture<Void> preCommitFuture = cohort.preCommit();
148 Futures.addCallback(preCommitFuture, futureCallback, internalFutureCallbackExecutor);
152 private void doCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
153 final DOMDataWriteTransaction transaction,
154 final Iterable<DOMStoreThreePhaseCommitCohort> cohorts, final int cohortSize) {
156 // Not using Futures.allAsList here to avoid its internal overhead.
157 final AtomicInteger remaining = new AtomicInteger(cohortSize);
158 FutureCallback<Void> futureCallback = new FutureCallback<Void>() {
160 public void onSuccess(Void notUsed) {
161 if(remaining.decrementAndGet() == 0) {
162 // All cohorts completed successfully - we're done.
163 commitStatsTracker.addDuration(System.nanoTime() - startTime);
165 clientSubmitFuture.set();
170 public void onFailure(Throwable t) {
171 handleException(clientSubmitFuture, transaction, cohorts, cohortSize, COMMIT,
172 TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER, t);
176 for(DOMStoreThreePhaseCommitCohort cohort: cohorts) {
177 ListenableFuture<Void> commitFuture = cohort.commit();
178 Futures.addCallback(commitFuture, futureCallback, internalFutureCallbackExecutor);
182 private void handleException(final AsyncNotifyingSettableFuture clientSubmitFuture,
183 final DOMDataWriteTransaction transaction,
184 final Iterable<DOMStoreThreePhaseCommitCohort> cohorts, int cohortSize,
185 final String phase, final TransactionCommitFailedExceptionMapper exMapper,
188 if(clientSubmitFuture.isDone()) {
189 // We must have had failures from multiple cohorts.
193 LOG.warn("Tx: {} Error during phase {}, starting Abort", transaction.getIdentifier(), phase, t);
195 if(t instanceof Exception) {
198 e = new RuntimeException("Unexpected error occurred", t);
201 final TransactionCommitFailedException clientException = exMapper.apply(e);
203 // Transaction failed - tell all cohorts to abort.
205 @SuppressWarnings("unchecked")
206 ListenableFuture<Void>[] canCommitFutures = new ListenableFuture[cohortSize];
208 for(DOMStoreThreePhaseCommitCohort cohort: cohorts) {
209 canCommitFutures[i++] = cohort.abort();
212 ListenableFuture<List<Void>> combinedFuture = Futures.allAsList(canCommitFutures);
213 Futures.addCallback(combinedFuture, new FutureCallback<List<Void>>() {
215 public void onSuccess(List<Void> notUsed) {
216 // Propagate the original exception to the client.
217 clientSubmitFuture.setException(clientException);
221 public void onFailure(Throwable t) {
222 LOG.error("Tx: {} Error during Abort.", transaction.getIdentifier(), t);
224 // Propagate the original exception as that is what caused the Tx to fail and is
225 // what's interesting to the client.
226 clientSubmitFuture.setException(clientException);
228 }, internalFutureCallbackExecutor);
232 * A settable future that uses an {@link Executor} to execute listener callback Runnables,
233 * registered via {@link #addListener}, asynchronously when this future completes. This is
234 * done to guarantee listener executions are off-loaded onto another thread to avoid blocking
235 * the thread that completed this future, as a common use case is to pass an executor that runs
236 * tasks in the same thread as the caller (ie MoreExecutors#sameThreadExecutor)
237 * to {@link #addListener}.
239 * FIXME: This class should probably be moved to yangtools common utils for re-usability and
240 * unified with AsyncNotifyingListenableFutureTask.
242 private static class AsyncNotifyingSettableFuture extends AbstractFuture<Void> {
245 * ThreadLocal used to detect if the task completion thread is running the future listener Runnables.
247 private static final ThreadLocal<Boolean> ON_TASK_COMPLETION_THREAD_TL = new ThreadLocal<Boolean>();
249 private final ExecutorService listenerExecutor;
251 AsyncNotifyingSettableFuture(ExecutorService listenerExecutor) {
252 this.listenerExecutor = listenerExecutor;
256 public void addListener(final Runnable listener, final Executor executor) {
257 // Wrap the listener Runnable in a DelegatingRunnable. If the specified executor is one
258 // that runs tasks in the same thread as the caller submitting the task
259 // (e.g. {@link com.google.common.util.concurrent.MoreExecutors#sameThreadExecutor}) and
260 // the listener is executed from the #set methods, then the DelegatingRunnable will detect
261 // this via the ThreadLocal and submit the listener Runnable to the listenerExecutor.
263 // On the other hand, if this task is already complete, the call to ExecutionList#add in
264 // superclass will execute the listener Runnable immediately and, since the ThreadLocal
265 // won't be set, the DelegatingRunnable will run the listener Runnable inline.
266 super.addListener(new DelegatingRunnable(listener, listenerExecutor), executor);
270 ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
272 return super.set(null);
274 ON_TASK_COMPLETION_THREAD_TL.set(null);
279 protected boolean setException(Throwable throwable) {
280 ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
282 return super.setException(throwable);
284 ON_TASK_COMPLETION_THREAD_TL.set(null);
288 private static final class DelegatingRunnable implements Runnable {
289 private final Runnable delegate;
290 private final Executor executor;
292 DelegatingRunnable(final Runnable delegate, final Executor executor) {
293 this.delegate = Preconditions.checkNotNull(delegate);
294 this.executor = Preconditions.checkNotNull(executor);
299 if (ON_TASK_COMPLETION_THREAD_TL.get() != null) {
300 // We're running on the task completion thread so off-load to the executor.
301 LOG.trace("Submitting ListenenableFuture Runnable from thread {} to executor {}",
302 Thread.currentThread().getName(), executor);
303 executor.execute(delegate);
305 // We're not running on the task completion thread so run the delegate inline.
306 LOG.trace("Executing ListenenableFuture Runnable on this thread: {}",
307 Thread.currentThread().getName());
315 * A simple same-thread executor without the internal locking overhead that
316 * MoreExecutors#sameThreadExecutor has. The #execute method is the only one of concern - we
317 * don't shutdown the executor so the other methods irrelevant.
319 private static class SimpleSameThreadExecutor extends AbstractListeningExecutorService {
322 public void execute(Runnable command) {
327 public boolean awaitTermination(long arg0, TimeUnit arg1) throws InterruptedException {
332 public boolean isShutdown() {
337 public boolean isTerminated() {
342 public void shutdown() {
346 public List<Runnable> shutdownNow() {