bdaa6db6c1a1f1d3fc08b10c25f8f83ee27b5a60
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / databroker / ConcurrentDOMDataBroker.java
1 /*
2  * Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.cluster.databroker;
9
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;
21 import java.util.Map;
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;
40
41 /**
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.
45  *
46  * @author Thomas Pantelis
47  */
48 @Beta
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";
54
55     private final DurationStatisticsTracker commitStatsTracker;
56
57     /**
58      * This executor is used to execute Future listener callback Runnables async.
59      */
60     private final Executor clientFutureCallbackExecutor;
61
62     public ConcurrentDOMDataBroker(final Map<LogicalDatastoreType, DOMStore> datastores, Executor listenableFutureExecutor) {
63         this(datastores, listenableFutureExecutor, DurationStatisticsTracker.createConcurrent());
64     }
65
66     public ConcurrentDOMDataBroker(final Map<LogicalDatastoreType, DOMStore> datastores, Executor listenableFutureExecutor,
67             DurationStatisticsTracker commitStatsTracker) {
68         super(datastores);
69         this.clientFutureCallbackExecutor = Preconditions.checkNotNull(listenableFutureExecutor);
70         this.commitStatsTracker = Preconditions.checkNotNull(commitStatsTracker);
71     }
72
73     public DurationStatisticsTracker getCommitStatsTracker() {
74         return commitStatsTracker;
75     }
76
77     @Override
78     protected CheckedFuture<Void, TransactionCommitFailedException> submit(DOMDataWriteTransaction transaction,
79             Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
80
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());
84
85         if(cohorts.isEmpty()){
86             return Futures.immediateCheckedFuture(null);
87         }
88
89         final AsyncNotifyingSettableFuture clientSubmitFuture =
90                 new AsyncNotifyingSettableFuture(clientFutureCallbackExecutor);
91
92         doCanCommit(clientSubmitFuture, transaction, cohorts);
93
94         return MappingCheckedFuture.create(clientSubmitFuture,
95                 TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER);
96     }
97
98     private void doCanCommit(final AsyncNotifyingSettableFuture clientSubmitFuture,
99             final DOMDataWriteTransaction transaction,
100             final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
101
102         final long startTime = System.nanoTime();
103
104         final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();
105
106         // Not using Futures.allAsList here to avoid its internal overhead.
107         FutureCallback<Boolean> futureCallback = new FutureCallback<Boolean>() {
108             @Override
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."));
115                 } else {
116                     if(!cohortIterator.hasNext()) {
117                         // All cohorts completed successfully - we can move on to the preCommit phase
118                         doPreCommit(startTime, clientSubmitFuture, transaction, cohorts);
119                     } else {
120                         ListenableFuture<Boolean> canCommitFuture = cohortIterator.next().canCommit();
121                         Futures.addCallback(canCommitFuture, this, MoreExecutors.directExecutor());
122                     }
123                 }
124             }
125
126             @Override
127             public void onFailure(Throwable t) {
128                 handleException(clientSubmitFuture, transaction, cohorts, CAN_COMMIT,
129                         TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER, t);
130             }
131         };
132
133         ListenableFuture<Boolean> canCommitFuture = cohortIterator.next().canCommit();
134         Futures.addCallback(canCommitFuture, futureCallback, MoreExecutors.directExecutor());
135     }
136
137     private void doPreCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
138             final DOMDataWriteTransaction transaction,
139             final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
140
141         final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();
142
143         // Not using Futures.allAsList here to avoid its internal overhead.
144         FutureCallback<Void> futureCallback = new FutureCallback<Void>() {
145             @Override
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);
150                 } else {
151                     ListenableFuture<Void> preCommitFuture = cohortIterator.next().preCommit();
152                     Futures.addCallback(preCommitFuture, this, MoreExecutors.directExecutor());
153                 }
154             }
155
156             @Override
157             public void onFailure(Throwable t) {
158                 handleException(clientSubmitFuture, transaction, cohorts, PRE_COMMIT,
159                         TransactionCommitFailedExceptionMapper.PRE_COMMIT_MAPPER, t);
160             }
161         };
162
163         ListenableFuture<Void> preCommitFuture = cohortIterator.next().preCommit();
164         Futures.addCallback(preCommitFuture, futureCallback, MoreExecutors.directExecutor());
165     }
166
167     private void doCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
168             final DOMDataWriteTransaction transaction,
169             final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
170
171         final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();
172
173         // Not using Futures.allAsList here to avoid its internal overhead.
174         FutureCallback<Void> futureCallback = new FutureCallback<Void>() {
175             @Override
176             public void onSuccess(Void notUsed) {
177                 if(!cohortIterator.hasNext()) {
178                     // All cohorts completed successfully - we're done.
179                     commitStatsTracker.addDuration(System.nanoTime() - startTime);
180
181                     clientSubmitFuture.set();
182                 } else {
183                     ListenableFuture<Void> commitFuture = cohortIterator.next().commit();
184                     Futures.addCallback(commitFuture, this, MoreExecutors.directExecutor());
185                 }
186             }
187
188             @Override
189             public void onFailure(Throwable t) {
190                 handleException(clientSubmitFuture, transaction, cohorts, COMMIT,
191                         TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER, t);
192             }
193         };
194
195         ListenableFuture<Void> commitFuture = cohortIterator.next().commit();
196         Futures.addCallback(commitFuture, futureCallback, MoreExecutors.directExecutor());
197     }
198
199     private static void handleException(final AsyncNotifyingSettableFuture clientSubmitFuture,
200             final DOMDataWriteTransaction transaction,
201             final Collection<DOMStoreThreePhaseCommitCohort> cohorts,
202             final String phase, final TransactionCommitFailedExceptionMapper exMapper,
203             final Throwable t) {
204
205         if (clientSubmitFuture.isDone()) {
206             // We must have had failures from multiple cohorts.
207             return;
208         }
209
210         LOG.warn("Tx: {} Error during phase {}, starting Abort", transaction.getIdentifier(), phase, t);
211         final Exception e;
212         if(t instanceof NoShardLeaderException || t instanceof ShardLeaderNotRespondingException) {
213             e = new DataStoreUnavailableException(t.getMessage(), t);
214         } else if (t instanceof Exception) {
215             e = (Exception)t;
216         } else {
217             e = new RuntimeException("Unexpected error occurred", t);
218         }
219
220         final TransactionCommitFailedException clientException = exMapper.apply(e);
221
222         // Transaction failed - tell all cohorts to abort.
223
224         @SuppressWarnings("unchecked")
225         ListenableFuture<Void>[] canCommitFutures = new ListenableFuture[cohorts.size()];
226         int i = 0;
227         for (DOMStoreThreePhaseCommitCohort cohort : cohorts) {
228             canCommitFutures[i++] = cohort.abort();
229         }
230
231         ListenableFuture<List<Void>> combinedFuture = Futures.allAsList(canCommitFutures);
232         Futures.addCallback(combinedFuture, new FutureCallback<List<Void>>() {
233             @Override
234             public void onSuccess(List<Void> notUsed) {
235                 // Propagate the original exception to the client.
236                 clientSubmitFuture.setException(clientException);
237             }
238
239             @Override
240             public void onFailure(Throwable t) {
241                 LOG.error("Tx: {} Error during Abort.", transaction.getIdentifier(), t);
242
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);
246             }
247         }, MoreExecutors.directExecutor());
248     }
249
250     /**
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}.
257      *
258      * FIXME: This class should probably be moved to yangtools common utils for re-usability and
259      * unified with AsyncNotifyingListenableFutureTask.
260      */
261     private static class AsyncNotifyingSettableFuture extends AbstractFuture<Void> {
262
263         /**
264          * ThreadLocal used to detect if the task completion thread is running the future listener Runnables.
265          */
266         private static final ThreadLocal<Boolean> ON_TASK_COMPLETION_THREAD_TL = new ThreadLocal<>();
267
268         private final Executor listenerExecutor;
269
270         AsyncNotifyingSettableFuture(Executor listenerExecutor) {
271             this.listenerExecutor = Preconditions.checkNotNull(listenerExecutor);
272         }
273
274         @Override
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.
281             //
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);
286         }
287
288         boolean set() {
289             ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
290             try {
291                 return super.set(null);
292             } finally {
293                 ON_TASK_COMPLETION_THREAD_TL.set(null);
294             }
295         }
296
297         @Override
298         protected boolean setException(Throwable throwable) {
299             ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
300             try {
301                 return super.setException(throwable);
302             } finally {
303                 ON_TASK_COMPLETION_THREAD_TL.set(null);
304             }
305         }
306
307         private static final class DelegatingRunnable implements Runnable {
308             private final Runnable delegate;
309             private final Executor executor;
310
311             DelegatingRunnable(final Runnable delegate, final Executor executor) {
312                 this.delegate = Preconditions.checkNotNull(delegate);
313                 this.executor = Preconditions.checkNotNull(executor);
314             }
315
316             @Override
317             public void run() {
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);
323                 } else {
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());
327                     delegate.run();
328                 }
329             }
330         }
331     }
332
333     @Override
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);
339         }
340         throw new UnsupportedOperationException("Commit cohort is not supported for " + path);
341     }
342
343     private static LogicalDatastoreType toLegacy(org.opendaylight.mdsal.common.api.LogicalDatastoreType datastoreType) {
344         switch (datastoreType) {
345             case CONFIGURATION:
346                 return LogicalDatastoreType.CONFIGURATION;
347             case OPERATIONAL:
348                 return LogicalDatastoreType.OPERATIONAL;
349             default:
350                 throw new IllegalArgumentException("Unsupported data store type: " + datastoreType);
351         }
352     }
353
354     @Override
355     public String toString() {
356         return "Clustered ConcurrentDOMDataBroker";
357     }
358 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.