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.Iterator;
19 import java.util.List;
21 import java.util.concurrent.Executor;
22 import java.util.concurrent.ExecutorService;
23 import java.util.concurrent.TimeUnit;
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 final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();
96 // Not using Futures.allAsList here to avoid its internal overhead.
97 FutureCallback<Boolean> futureCallback = new FutureCallback<Boolean>() {
99 public void onSuccess(Boolean result) {
100 if (result == null || !result) {
101 handleException(clientSubmitFuture, transaction, cohorts,
102 CAN_COMMIT, TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER,
103 new TransactionCommitFailedException(
104 "Can Commit failed, no detailed cause available."));
106 if(!cohortIterator.hasNext()) {
107 // All cohorts completed successfully - we can move on to the preCommit phase
108 doPreCommit(startTime, clientSubmitFuture, transaction, cohorts);
110 ListenableFuture<Boolean> canCommitFuture = cohortIterator.next().canCommit();
111 Futures.addCallback(canCommitFuture, this, internalFutureCallbackExecutor);
117 public void onFailure(Throwable t) {
118 handleException(clientSubmitFuture, transaction, cohorts, CAN_COMMIT,
119 TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER, t);
123 ListenableFuture<Boolean> canCommitFuture = cohortIterator.next().canCommit();
124 Futures.addCallback(canCommitFuture, futureCallback, internalFutureCallbackExecutor);
127 private void doPreCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
128 final DOMDataWriteTransaction transaction,
129 final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
131 final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();
133 // Not using Futures.allAsList here to avoid its internal overhead.
134 FutureCallback<Void> futureCallback = new FutureCallback<Void>() {
136 public void onSuccess(Void notUsed) {
137 if(!cohortIterator.hasNext()) {
138 // All cohorts completed successfully - we can move on to the commit phase
139 doCommit(startTime, clientSubmitFuture, transaction, cohorts);
141 ListenableFuture<Void> preCommitFuture = cohortIterator.next().preCommit();
142 Futures.addCallback(preCommitFuture, this, internalFutureCallbackExecutor);
147 public void onFailure(Throwable t) {
148 handleException(clientSubmitFuture, transaction, cohorts, PRE_COMMIT,
149 TransactionCommitFailedExceptionMapper.PRE_COMMIT_MAPPER, t);
153 ListenableFuture<Void> preCommitFuture = cohortIterator.next().preCommit();
154 Futures.addCallback(preCommitFuture, futureCallback, internalFutureCallbackExecutor);
157 private void doCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
158 final DOMDataWriteTransaction transaction,
159 final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
161 final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();
163 // Not using Futures.allAsList here to avoid its internal overhead.
164 FutureCallback<Void> futureCallback = new FutureCallback<Void>() {
166 public void onSuccess(Void notUsed) {
167 if(!cohortIterator.hasNext()) {
168 // All cohorts completed successfully - we're done.
169 commitStatsTracker.addDuration(System.nanoTime() - startTime);
171 clientSubmitFuture.set();
173 ListenableFuture<Void> commitFuture = cohortIterator.next().commit();
174 Futures.addCallback(commitFuture, this, internalFutureCallbackExecutor);
179 public void onFailure(Throwable t) {
180 handleException(clientSubmitFuture, transaction, cohorts, COMMIT,
181 TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER, t);
185 ListenableFuture<Void> commitFuture = cohortIterator.next().commit();
186 Futures.addCallback(commitFuture, futureCallback, internalFutureCallbackExecutor);
189 private void handleException(final AsyncNotifyingSettableFuture clientSubmitFuture,
190 final DOMDataWriteTransaction transaction,
191 final Collection<DOMStoreThreePhaseCommitCohort> cohorts,
192 final String phase, final TransactionCommitFailedExceptionMapper exMapper,
195 if(clientSubmitFuture.isDone()) {
196 // We must have had failures from multiple cohorts.
200 LOG.warn("Tx: {} Error during phase {}, starting Abort", transaction.getIdentifier(), phase, t);
202 if(t instanceof Exception) {
205 e = new RuntimeException("Unexpected error occurred", t);
208 final TransactionCommitFailedException clientException = exMapper.apply(e);
210 // Transaction failed - tell all cohorts to abort.
212 @SuppressWarnings("unchecked")
213 ListenableFuture<Void>[] canCommitFutures = new ListenableFuture[cohorts.size()];
215 for(DOMStoreThreePhaseCommitCohort cohort: cohorts) {
216 canCommitFutures[i++] = cohort.abort();
219 ListenableFuture<List<Void>> combinedFuture = Futures.allAsList(canCommitFutures);
220 Futures.addCallback(combinedFuture, new FutureCallback<List<Void>>() {
222 public void onSuccess(List<Void> notUsed) {
223 // Propagate the original exception to the client.
224 clientSubmitFuture.setException(clientException);
228 public void onFailure(Throwable t) {
229 LOG.error("Tx: {} Error during Abort.", transaction.getIdentifier(), t);
231 // Propagate the original exception as that is what caused the Tx to fail and is
232 // what's interesting to the client.
233 clientSubmitFuture.setException(clientException);
235 }, internalFutureCallbackExecutor);
239 * A settable future that uses an {@link Executor} to execute listener callback Runnables,
240 * registered via {@link #addListener}, asynchronously when this future completes. This is
241 * done to guarantee listener executions are off-loaded onto another thread to avoid blocking
242 * the thread that completed this future, as a common use case is to pass an executor that runs
243 * tasks in the same thread as the caller (ie MoreExecutors#sameThreadExecutor)
244 * to {@link #addListener}.
246 * FIXME: This class should probably be moved to yangtools common utils for re-usability and
247 * unified with AsyncNotifyingListenableFutureTask.
249 private static class AsyncNotifyingSettableFuture extends AbstractFuture<Void> {
252 * ThreadLocal used to detect if the task completion thread is running the future listener Runnables.
254 private static final ThreadLocal<Boolean> ON_TASK_COMPLETION_THREAD_TL = new ThreadLocal<Boolean>();
256 private final ExecutorService listenerExecutor;
258 AsyncNotifyingSettableFuture(ExecutorService listenerExecutor) {
259 this.listenerExecutor = listenerExecutor;
263 public void addListener(final Runnable listener, final Executor executor) {
264 // Wrap the listener Runnable in a DelegatingRunnable. If the specified executor is one
265 // that runs tasks in the same thread as the caller submitting the task
266 // (e.g. {@link com.google.common.util.concurrent.MoreExecutors#sameThreadExecutor}) and
267 // the listener is executed from the #set methods, then the DelegatingRunnable will detect
268 // this via the ThreadLocal and submit the listener Runnable to the listenerExecutor.
270 // On the other hand, if this task is already complete, the call to ExecutionList#add in
271 // superclass will execute the listener Runnable immediately and, since the ThreadLocal
272 // won't be set, the DelegatingRunnable will run the listener Runnable inline.
273 super.addListener(new DelegatingRunnable(listener, listenerExecutor), executor);
277 ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
279 return super.set(null);
281 ON_TASK_COMPLETION_THREAD_TL.set(null);
286 protected boolean setException(Throwable throwable) {
287 ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
289 return super.setException(throwable);
291 ON_TASK_COMPLETION_THREAD_TL.set(null);
295 private static final class DelegatingRunnable implements Runnable {
296 private final Runnable delegate;
297 private final Executor executor;
299 DelegatingRunnable(final Runnable delegate, final Executor executor) {
300 this.delegate = Preconditions.checkNotNull(delegate);
301 this.executor = Preconditions.checkNotNull(executor);
306 if (ON_TASK_COMPLETION_THREAD_TL.get() != null) {
307 // We're running on the task completion thread so off-load to the executor.
308 LOG.trace("Submitting ListenenableFuture Runnable from thread {} to executor {}",
309 Thread.currentThread().getName(), executor);
310 executor.execute(delegate);
312 // We're not running on the task completion thread so run the delegate inline.
313 LOG.trace("Executing ListenenableFuture Runnable on this thread: {}",
314 Thread.currentThread().getName());
322 * A simple same-thread executor without the internal locking overhead that
323 * MoreExecutors#sameThreadExecutor has. The #execute method is the only one of concern - we
324 * don't shutdown the executor so the other methods irrelevant.
326 private static class SimpleSameThreadExecutor extends AbstractListeningExecutorService {
329 public void execute(Runnable command) {
334 public boolean awaitTermination(long arg0, TimeUnit arg1) throws InterruptedException {
339 public boolean isShutdown() {
344 public boolean isTerminated() {
349 public void shutdown() {
353 public List<Runnable> shutdownNow() {