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, Executor listenableFutureExecutor) {
63 this(datastores, listenableFutureExecutor, DurationStatisticsTracker.createConcurrent());
66 public ConcurrentDOMDataBroker(final Map<LogicalDatastoreType, DOMStore> datastores, Executor listenableFutureExecutor,
67 DurationStatisticsTracker commitStatsTracker) {
69 this.clientFutureCallbackExecutor = Preconditions.checkNotNull(listenableFutureExecutor);
70 this.commitStatsTracker = Preconditions.checkNotNull(commitStatsTracker);
73 public DurationStatisticsTracker getCommitStatsTracker() {
74 return commitStatsTracker;
78 protected CheckedFuture<Void, TransactionCommitFailedException> submit(DOMDataWriteTransaction transaction,
79 Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
81 Preconditions.checkArgument(transaction != null, "Transaction must not be null.");
82 Preconditions.checkArgument(cohorts != null, "Cohorts must not be null.");
83 LOG.debug("Tx: {} is submitted for execution.", transaction.getIdentifier());
85 if(cohorts.isEmpty()){
86 return Futures.immediateCheckedFuture(null);
89 final AsyncNotifyingSettableFuture clientSubmitFuture =
90 new AsyncNotifyingSettableFuture(clientFutureCallbackExecutor);
92 doCanCommit(clientSubmitFuture, transaction, cohorts);
94 return MappingCheckedFuture.create(clientSubmitFuture,
95 TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER);
98 private void doCanCommit(final AsyncNotifyingSettableFuture clientSubmitFuture,
99 final DOMDataWriteTransaction transaction,
100 final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
102 final long startTime = System.nanoTime();
104 final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();
106 // Not using Futures.allAsList here to avoid its internal overhead.
107 FutureCallback<Boolean> futureCallback = new FutureCallback<Boolean>() {
109 public void onSuccess(Boolean result) {
110 if (result == null || !result) {
111 handleException(clientSubmitFuture, transaction, cohorts,
112 CAN_COMMIT, TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER,
113 new TransactionCommitFailedException(
114 "Can Commit failed, no detailed cause available."));
116 if(!cohortIterator.hasNext()) {
117 // All cohorts completed successfully - we can move on to the preCommit phase
118 doPreCommit(startTime, clientSubmitFuture, transaction, cohorts);
120 ListenableFuture<Boolean> canCommitFuture = cohortIterator.next().canCommit();
121 Futures.addCallback(canCommitFuture, this, MoreExecutors.directExecutor());
127 public void onFailure(Throwable t) {
128 handleException(clientSubmitFuture, transaction, cohorts, CAN_COMMIT,
129 TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER, t);
133 ListenableFuture<Boolean> canCommitFuture = cohortIterator.next().canCommit();
134 Futures.addCallback(canCommitFuture, futureCallback, MoreExecutors.directExecutor());
137 private void doPreCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
138 final DOMDataWriteTransaction transaction,
139 final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
141 final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();
143 // Not using Futures.allAsList here to avoid its internal overhead.
144 FutureCallback<Void> futureCallback = new FutureCallback<Void>() {
146 public void onSuccess(Void notUsed) {
147 if(!cohortIterator.hasNext()) {
148 // All cohorts completed successfully - we can move on to the commit phase
149 doCommit(startTime, clientSubmitFuture, transaction, cohorts);
151 ListenableFuture<Void> preCommitFuture = cohortIterator.next().preCommit();
152 Futures.addCallback(preCommitFuture, this, MoreExecutors.directExecutor());
157 public void onFailure(Throwable t) {
158 handleException(clientSubmitFuture, transaction, cohorts, PRE_COMMIT,
159 TransactionCommitFailedExceptionMapper.PRE_COMMIT_MAPPER, t);
163 ListenableFuture<Void> preCommitFuture = cohortIterator.next().preCommit();
164 Futures.addCallback(preCommitFuture, futureCallback, MoreExecutors.directExecutor());
167 private void doCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
168 final DOMDataWriteTransaction transaction,
169 final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
171 final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();
173 // Not using Futures.allAsList here to avoid its internal overhead.
174 FutureCallback<Void> futureCallback = new FutureCallback<Void>() {
176 public void onSuccess(Void notUsed) {
177 if(!cohortIterator.hasNext()) {
178 // All cohorts completed successfully - we're done.
179 commitStatsTracker.addDuration(System.nanoTime() - startTime);
181 clientSubmitFuture.set();
183 ListenableFuture<Void> commitFuture = cohortIterator.next().commit();
184 Futures.addCallback(commitFuture, this, MoreExecutors.directExecutor());
189 public void onFailure(Throwable t) {
190 handleException(clientSubmitFuture, transaction, cohorts, COMMIT,
191 TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER, t);
195 ListenableFuture<Void> commitFuture = cohortIterator.next().commit();
196 Futures.addCallback(commitFuture, futureCallback, MoreExecutors.directExecutor());
199 private static void handleException(final AsyncNotifyingSettableFuture clientSubmitFuture,
200 final DOMDataWriteTransaction transaction,
201 final Collection<DOMStoreThreePhaseCommitCohort> cohorts,
202 final String phase, final TransactionCommitFailedExceptionMapper exMapper,
205 if (clientSubmitFuture.isDone()) {
206 // We must have had failures from multiple cohorts.
210 LOG.warn("Tx: {} Error during phase {}, starting Abort", transaction.getIdentifier(), phase, t);
212 if(t instanceof NoShardLeaderException || t instanceof ShardLeaderNotRespondingException) {
213 e = new DataStoreUnavailableException(t.getMessage(), t);
214 } else if (t instanceof Exception) {
217 e = new RuntimeException("Unexpected error occurred", t);
220 final TransactionCommitFailedException clientException = exMapper.apply(e);
222 // Transaction failed - tell all cohorts to abort.
224 @SuppressWarnings("unchecked")
225 ListenableFuture<Void>[] canCommitFutures = new ListenableFuture[cohorts.size()];
227 for (DOMStoreThreePhaseCommitCohort cohort : cohorts) {
228 canCommitFutures[i++] = cohort.abort();
231 ListenableFuture<List<Void>> combinedFuture = Futures.allAsList(canCommitFutures);
232 Futures.addCallback(combinedFuture, new FutureCallback<List<Void>>() {
234 public void onSuccess(List<Void> notUsed) {
235 // Propagate the original exception to the client.
236 clientSubmitFuture.setException(clientException);
240 public void onFailure(Throwable t) {
241 LOG.error("Tx: {} Error during Abort.", transaction.getIdentifier(), t);
243 // Propagate the original exception as that is what caused the Tx to fail and is
244 // what's interesting to the client.
245 clientSubmitFuture.setException(clientException);
247 }, MoreExecutors.directExecutor());
251 * A settable future that uses an {@link Executor} to execute listener callback Runnables,
252 * registered via {@link #addListener}, asynchronously when this future completes. This is
253 * done to guarantee listener executions are off-loaded onto another thread to avoid blocking
254 * the thread that completed this future, as a common use case is to pass an executor that runs
255 * tasks in the same thread as the caller (ie MoreExecutors#sameThreadExecutor)
256 * 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<Boolean>();
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);