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.databroker;
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Preconditions;
12 import com.google.common.util.concurrent.AbstractFuture;
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 com.google.common.util.concurrent.MoreExecutors;
18 import java.util.Collection;
19 import java.util.Iterator;
20 import java.util.List;
22 import java.util.concurrent.Executor;
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.mdsal.dom.api.DOMDataTreeCommitCohort;
33 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
34 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistry;
35 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
36 import org.opendaylight.yangtools.util.DurationStatisticsTracker;
37 import org.opendaylight.yangtools.util.concurrent.MappingCheckedFuture;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
42 * ConcurrentDOMDataBroker commits transactions concurrently. The 3
43 * commit phases (canCommit, preCommit, and commit) are performed serially and non-blocking
44 * (ie async) per transaction but multiple transaction commits can run concurrent.
46 * @author Thomas Pantelis
49 public class ConcurrentDOMDataBroker extends AbstractDOMBroker implements DOMDataTreeCommitCohortRegistry {
50 private static final Logger LOG = LoggerFactory.getLogger(ConcurrentDOMDataBroker.class);
51 private static final String CAN_COMMIT = "CAN_COMMIT";
52 private static final String PRE_COMMIT = "PRE_COMMIT";
53 private static final String COMMIT = "COMMIT";
55 private final DurationStatisticsTracker commitStatsTracker;
58 * This executor is used to execute Future listener callback Runnables async.
60 private final Executor clientFutureCallbackExecutor;
62 public ConcurrentDOMDataBroker(final Map<LogicalDatastoreType, DOMStore> datastores,
63 Executor listenableFutureExecutor) {
64 this(datastores, listenableFutureExecutor, DurationStatisticsTracker.createConcurrent());
67 public ConcurrentDOMDataBroker(final Map<LogicalDatastoreType, DOMStore> datastores,
68 Executor listenableFutureExecutor, DurationStatisticsTracker commitStatsTracker) {
70 this.clientFutureCallbackExecutor = Preconditions.checkNotNull(listenableFutureExecutor);
71 this.commitStatsTracker = Preconditions.checkNotNull(commitStatsTracker);
74 public DurationStatisticsTracker getCommitStatsTracker() {
75 return commitStatsTracker;
79 protected CheckedFuture<Void, TransactionCommitFailedException> submit(DOMDataWriteTransaction transaction,
80 Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
82 Preconditions.checkArgument(transaction != null, "Transaction must not be null.");
83 Preconditions.checkArgument(cohorts != null, "Cohorts must not be null.");
84 LOG.debug("Tx: {} is submitted for execution.", transaction.getIdentifier());
86 if (cohorts.isEmpty()) {
87 return Futures.immediateCheckedFuture(null);
90 final AsyncNotifyingSettableFuture clientSubmitFuture =
91 new AsyncNotifyingSettableFuture(clientFutureCallbackExecutor);
93 doCanCommit(clientSubmitFuture, transaction, cohorts);
95 return MappingCheckedFuture.create(clientSubmitFuture,
96 TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER);
99 private void doCanCommit(final AsyncNotifyingSettableFuture clientSubmitFuture,
100 final DOMDataWriteTransaction transaction,
101 final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
103 final long startTime = System.nanoTime();
105 final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();
107 // Not using Futures.allAsList here to avoid its internal overhead.
108 FutureCallback<Boolean> futureCallback = new FutureCallback<Boolean>() {
110 public void onSuccess(Boolean result) {
111 if (result == null || !result) {
112 handleException(clientSubmitFuture, transaction, cohorts,
113 CAN_COMMIT, TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER,
114 new TransactionCommitFailedException(
115 "Can Commit failed, no detailed cause available."));
117 if (!cohortIterator.hasNext()) {
118 // All cohorts completed successfully - we can move on to the preCommit phase
119 doPreCommit(startTime, clientSubmitFuture, transaction, cohorts);
121 ListenableFuture<Boolean> canCommitFuture = cohortIterator.next().canCommit();
122 Futures.addCallback(canCommitFuture, this, MoreExecutors.directExecutor());
128 public void onFailure(Throwable failure) {
129 handleException(clientSubmitFuture, transaction, cohorts, CAN_COMMIT,
130 TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER, failure);
134 ListenableFuture<Boolean> canCommitFuture = cohortIterator.next().canCommit();
135 Futures.addCallback(canCommitFuture, futureCallback, MoreExecutors.directExecutor());
138 private void doPreCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
139 final DOMDataWriteTransaction transaction,
140 final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
142 final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();
144 // Not using Futures.allAsList here to avoid its internal overhead.
145 FutureCallback<Void> futureCallback = new FutureCallback<Void>() {
147 public void onSuccess(Void notUsed) {
148 if (!cohortIterator.hasNext()) {
149 // All cohorts completed successfully - we can move on to the commit phase
150 doCommit(startTime, clientSubmitFuture, transaction, cohorts);
152 ListenableFuture<Void> preCommitFuture = cohortIterator.next().preCommit();
153 Futures.addCallback(preCommitFuture, this, MoreExecutors.directExecutor());
158 public void onFailure(Throwable failure) {
159 handleException(clientSubmitFuture, transaction, cohorts, PRE_COMMIT,
160 TransactionCommitFailedExceptionMapper.PRE_COMMIT_MAPPER, failure);
164 ListenableFuture<Void> preCommitFuture = cohortIterator.next().preCommit();
165 Futures.addCallback(preCommitFuture, futureCallback, MoreExecutors.directExecutor());
168 private void doCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
169 final DOMDataWriteTransaction transaction,
170 final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
172 final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();
174 // Not using Futures.allAsList here to avoid its internal overhead.
175 FutureCallback<Void> futureCallback = new FutureCallback<Void>() {
177 public void onSuccess(Void notUsed) {
178 if (!cohortIterator.hasNext()) {
179 // All cohorts completed successfully - we're done.
180 commitStatsTracker.addDuration(System.nanoTime() - startTime);
182 clientSubmitFuture.set();
184 ListenableFuture<Void> commitFuture = cohortIterator.next().commit();
185 Futures.addCallback(commitFuture, this, MoreExecutors.directExecutor());
190 public void onFailure(Throwable throwable) {
191 handleException(clientSubmitFuture, transaction, cohorts, COMMIT,
192 TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER, throwable);
196 ListenableFuture<Void> commitFuture = cohortIterator.next().commit();
197 Futures.addCallback(commitFuture, futureCallback, MoreExecutors.directExecutor());
200 private static void handleException(final AsyncNotifyingSettableFuture clientSubmitFuture,
201 final DOMDataWriteTransaction transaction,
202 final Collection<DOMStoreThreePhaseCommitCohort> cohorts,
203 final String phase, final TransactionCommitFailedExceptionMapper exMapper,
204 final Throwable throwable) {
206 if (clientSubmitFuture.isDone()) {
207 // We must have had failures from multiple cohorts.
211 LOG.warn("Tx: {} Error during phase {}, starting Abort", transaction.getIdentifier(), phase, throwable);
213 if (throwable instanceof NoShardLeaderException || throwable instanceof ShardLeaderNotRespondingException) {
214 e = new DataStoreUnavailableException(throwable.getMessage(), throwable);
215 } else if (throwable instanceof Exception) {
216 e = (Exception)throwable;
218 e = new RuntimeException("Unexpected error occurred", throwable);
221 final TransactionCommitFailedException clientException = exMapper.apply(e);
223 // Transaction failed - tell all cohorts to abort.
225 @SuppressWarnings("unchecked")
226 ListenableFuture<Void>[] canCommitFutures = new ListenableFuture[cohorts.size()];
228 for (DOMStoreThreePhaseCommitCohort cohort : cohorts) {
229 canCommitFutures[index++] = cohort.abort();
232 ListenableFuture<List<Void>> combinedFuture = Futures.allAsList(canCommitFutures);
233 Futures.addCallback(combinedFuture, new FutureCallback<List<Void>>() {
235 public void onSuccess(List<Void> notUsed) {
236 // Propagate the original exception to the client.
237 clientSubmitFuture.setException(clientException);
241 public void onFailure(Throwable failure) {
242 LOG.error("Tx: {} Error during Abort.", transaction.getIdentifier(), failure);
244 // Propagate the original exception as that is what caused the Tx to fail and is
245 // what's interesting to the client.
246 clientSubmitFuture.setException(clientException);
248 }, MoreExecutors.directExecutor());
252 * A settable future that uses an {@link Executor} to execute listener callback Runnables,
253 * registered via {@link #addListener}, asynchronously when this future completes. This is
254 * done to guarantee listener executions are off-loaded onto another thread to avoid blocking
255 * the thread that completed this future, as a common use case is to pass an executor that runs
256 * tasks in the same thread as the caller (ie MoreExecutors#sameThreadExecutor)
257 * to {@link #addListener}.
258 * FIXME: This class should probably be moved to yangtools common utils for re-usability and
259 * unified with AsyncNotifyingListenableFutureTask.
261 private static class AsyncNotifyingSettableFuture extends AbstractFuture<Void> {
264 * ThreadLocal used to detect if the task completion thread is running the future listener Runnables.
266 private static final ThreadLocal<Boolean> ON_TASK_COMPLETION_THREAD_TL = new ThreadLocal<>();
268 private final Executor listenerExecutor;
270 AsyncNotifyingSettableFuture(Executor listenerExecutor) {
271 this.listenerExecutor = Preconditions.checkNotNull(listenerExecutor);
275 public void addListener(final Runnable listener, final Executor executor) {
276 // Wrap the listener Runnable in a DelegatingRunnable. If the specified executor is one
277 // that runs tasks in the same thread as the caller submitting the task
278 // (e.g. {@link com.google.common.util.concurrent.MoreExecutors#sameThreadExecutor}) and
279 // the listener is executed from the #set methods, then the DelegatingRunnable will detect
280 // this via the ThreadLocal and submit the listener Runnable to the listenerExecutor.
282 // On the other hand, if this task is already complete, the call to ExecutionList#add in
283 // superclass will execute the listener Runnable immediately and, since the ThreadLocal
284 // won't be set, the DelegatingRunnable will run the listener Runnable inline.
285 super.addListener(new DelegatingRunnable(listener, listenerExecutor), executor);
289 ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
291 return super.set(null);
293 ON_TASK_COMPLETION_THREAD_TL.set(null);
298 protected boolean setException(Throwable throwable) {
299 ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
301 return super.setException(throwable);
303 ON_TASK_COMPLETION_THREAD_TL.set(null);
307 private static final class DelegatingRunnable implements Runnable {
308 private final Runnable delegate;
309 private final Executor executor;
311 DelegatingRunnable(final Runnable delegate, final Executor executor) {
312 this.delegate = Preconditions.checkNotNull(delegate);
313 this.executor = Preconditions.checkNotNull(executor);
318 if (ON_TASK_COMPLETION_THREAD_TL.get() != null) {
319 // We're running on the task completion thread so off-load to the executor.
320 LOG.trace("Submitting ListenenableFuture Runnable from thread {} to executor {}",
321 Thread.currentThread().getName(), executor);
322 executor.execute(delegate);
324 // We're not running on the task completion thread so run the delegate inline.
325 LOG.trace("Executing ListenenableFuture Runnable on this thread: {}",
326 Thread.currentThread().getName());
334 public <T extends DOMDataTreeCommitCohort> DOMDataTreeCommitCohortRegistration<T> registerCommitCohort(
335 DOMDataTreeIdentifier path, T cohort) {
336 DOMStore store = getTxFactories().get(toLegacy(path.getDatastoreType()));
337 if (store instanceof DOMDataTreeCommitCohortRegistry) {
338 return ((DOMDataTreeCommitCohortRegistry) store).registerCommitCohort(path, cohort);
340 throw new UnsupportedOperationException("Commit cohort is not supported for " + path);
343 private static LogicalDatastoreType toLegacy(org.opendaylight.mdsal.common.api.LogicalDatastoreType datastoreType) {
344 switch (datastoreType) {
346 return LogicalDatastoreType.CONFIGURATION;
348 return LogicalDatastoreType.OPERATIONAL;
350 throw new IllegalArgumentException("Unsupported data store type: " + datastoreType);
355 public String toString() {
356 return "Clustered ConcurrentDOMDataBroker";