Merge "BUG 3045 : Use non-strict parsing in hello message."
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / 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.datastore;
9
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;
20 import java.util.Map;
21 import java.util.concurrent.Executor;
22 import java.util.concurrent.ExecutorService;
23 import java.util.concurrent.TimeUnit;
24 import org.opendaylight.controller.cluster.databroker.AbstractDOMBroker;
25 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
26 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
27 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
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;
35
36 /**
37  * ConcurrentDOMDataBroker commits transactions 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.
40  *
41  * @author Thomas Pantelis
42  */
43 public class ConcurrentDOMDataBroker extends AbstractDOMBroker {
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";
48
49     private final DurationStatisticsTracker commitStatsTracker = DurationStatisticsTracker.createConcurrent();
50
51     /**
52      * This executor is used to execute Future listener callback Runnables async.
53      */
54     private final ExecutorService clientFutureCallbackExecutor;
55
56     /**
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.
59      */
60     private final ExecutorService internalFutureCallbackExecutor = new SimpleSameThreadExecutor();
61
62     public ConcurrentDOMDataBroker(final Map<LogicalDatastoreType, DOMStore> datastores, ExecutorService listenableFutureExecutor) {
63         super(datastores);
64         this.clientFutureCallbackExecutor = Preconditions.checkNotNull(listenableFutureExecutor);
65     }
66
67     public DurationStatisticsTracker getCommitStatsTracker() {
68         return commitStatsTracker;
69     }
70
71     @Override
72     public CheckedFuture<Void, TransactionCommitFailedException> submit(DOMDataWriteTransaction transaction,
73             Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
74
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());
78
79         final AsyncNotifyingSettableFuture clientSubmitFuture =
80                 new AsyncNotifyingSettableFuture(clientFutureCallbackExecutor);
81
82         doCanCommit(clientSubmitFuture, transaction, cohorts);
83
84         return MappingCheckedFuture.create(clientSubmitFuture,
85                 TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER);
86     }
87
88     private void doCanCommit(final AsyncNotifyingSettableFuture clientSubmitFuture,
89             final DOMDataWriteTransaction transaction,
90             final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
91
92         final long startTime = System.nanoTime();
93
94         final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();
95
96         // Not using Futures.allAsList here to avoid its internal overhead.
97         FutureCallback<Boolean> futureCallback = new FutureCallback<Boolean>() {
98             @Override
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."));
105                 } else {
106                     if(!cohortIterator.hasNext()) {
107                         // All cohorts completed successfully - we can move on to the preCommit phase
108                         doPreCommit(startTime, clientSubmitFuture, transaction, cohorts);
109                     } else {
110                         ListenableFuture<Boolean> canCommitFuture = cohortIterator.next().canCommit();
111                         Futures.addCallback(canCommitFuture, this, internalFutureCallbackExecutor);
112                     }
113                 }
114             }
115
116             @Override
117             public void onFailure(Throwable t) {
118                 handleException(clientSubmitFuture, transaction, cohorts, CAN_COMMIT,
119                         TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER, t);
120             }
121         };
122
123         ListenableFuture<Boolean> canCommitFuture = cohortIterator.next().canCommit();
124         Futures.addCallback(canCommitFuture, futureCallback, internalFutureCallbackExecutor);
125     }
126
127     private void doPreCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
128             final DOMDataWriteTransaction transaction,
129             final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
130
131         final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();
132
133         // Not using Futures.allAsList here to avoid its internal overhead.
134         FutureCallback<Void> futureCallback = new FutureCallback<Void>() {
135             @Override
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);
140                 } else {
141                     ListenableFuture<Void> preCommitFuture = cohortIterator.next().preCommit();
142                     Futures.addCallback(preCommitFuture, this, internalFutureCallbackExecutor);
143                 }
144             }
145
146             @Override
147             public void onFailure(Throwable t) {
148                 handleException(clientSubmitFuture, transaction, cohorts, PRE_COMMIT,
149                         TransactionCommitFailedExceptionMapper.PRE_COMMIT_MAPPER, t);
150             }
151         };
152
153         ListenableFuture<Void> preCommitFuture = cohortIterator.next().preCommit();
154         Futures.addCallback(preCommitFuture, futureCallback, internalFutureCallbackExecutor);
155     }
156
157     private void doCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
158             final DOMDataWriteTransaction transaction,
159             final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
160
161         final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();
162
163         // Not using Futures.allAsList here to avoid its internal overhead.
164         FutureCallback<Void> futureCallback = new FutureCallback<Void>() {
165             @Override
166             public void onSuccess(Void notUsed) {
167                 if(!cohortIterator.hasNext()) {
168                     // All cohorts completed successfully - we're done.
169                     commitStatsTracker.addDuration(System.nanoTime() - startTime);
170
171                     clientSubmitFuture.set();
172                 } else {
173                     ListenableFuture<Void> commitFuture = cohortIterator.next().commit();
174                     Futures.addCallback(commitFuture, this, internalFutureCallbackExecutor);
175                 }
176             }
177
178             @Override
179             public void onFailure(Throwable t) {
180                 handleException(clientSubmitFuture, transaction, cohorts, COMMIT,
181                         TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER, t);
182             }
183         };
184
185         ListenableFuture<Void> commitFuture = cohortIterator.next().commit();
186         Futures.addCallback(commitFuture, futureCallback, internalFutureCallbackExecutor);
187     }
188
189     private void handleException(final AsyncNotifyingSettableFuture clientSubmitFuture,
190             final DOMDataWriteTransaction transaction,
191             final Collection<DOMStoreThreePhaseCommitCohort> cohorts,
192             final String phase, final TransactionCommitFailedExceptionMapper exMapper,
193             final Throwable t) {
194
195         if(clientSubmitFuture.isDone()) {
196             // We must have had failures from multiple cohorts.
197             return;
198         }
199
200         LOG.warn("Tx: {} Error during phase {}, starting Abort", transaction.getIdentifier(), phase, t);
201         Exception e;
202         if(t instanceof Exception) {
203             e = (Exception)t;
204         } else {
205             e = new RuntimeException("Unexpected error occurred", t);
206         }
207
208         final TransactionCommitFailedException clientException = exMapper.apply(e);
209
210         // Transaction failed - tell all cohorts to abort.
211
212         @SuppressWarnings("unchecked")
213         ListenableFuture<Void>[] canCommitFutures = new ListenableFuture[cohorts.size()];
214         int i = 0;
215         for(DOMStoreThreePhaseCommitCohort cohort: cohorts) {
216             canCommitFutures[i++] = cohort.abort();
217         }
218
219         ListenableFuture<List<Void>> combinedFuture = Futures.allAsList(canCommitFutures);
220         Futures.addCallback(combinedFuture, new FutureCallback<List<Void>>() {
221             @Override
222             public void onSuccess(List<Void> notUsed) {
223                 // Propagate the original exception to the client.
224                 clientSubmitFuture.setException(clientException);
225             }
226
227             @Override
228             public void onFailure(Throwable t) {
229                 LOG.error("Tx: {} Error during Abort.", transaction.getIdentifier(), t);
230
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);
234             }
235         }, internalFutureCallbackExecutor);
236     }
237
238     /**
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}.
245      *
246      * FIXME: This class should probably be moved to yangtools common utils for re-usability and
247      * unified with AsyncNotifyingListenableFutureTask.
248      */
249     private static class AsyncNotifyingSettableFuture extends AbstractFuture<Void> {
250
251         /**
252          * ThreadLocal used to detect if the task completion thread is running the future listener Runnables.
253          */
254         private static final ThreadLocal<Boolean> ON_TASK_COMPLETION_THREAD_TL = new ThreadLocal<Boolean>();
255
256         private final ExecutorService listenerExecutor;
257
258         AsyncNotifyingSettableFuture(ExecutorService listenerExecutor) {
259             this.listenerExecutor = listenerExecutor;
260         }
261
262         @Override
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.
269             //
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);
274         }
275
276         boolean set() {
277             ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
278             try {
279                 return super.set(null);
280             } finally {
281                 ON_TASK_COMPLETION_THREAD_TL.set(null);
282             }
283         }
284
285         @Override
286         protected boolean setException(Throwable throwable) {
287             ON_TASK_COMPLETION_THREAD_TL.set(Boolean.TRUE);
288             try {
289                 return super.setException(throwable);
290             } finally {
291                 ON_TASK_COMPLETION_THREAD_TL.set(null);
292             }
293         }
294
295         private static final class DelegatingRunnable implements Runnable {
296             private final Runnable delegate;
297             private final Executor executor;
298
299             DelegatingRunnable(final Runnable delegate, final Executor executor) {
300                 this.delegate = Preconditions.checkNotNull(delegate);
301                 this.executor = Preconditions.checkNotNull(executor);
302             }
303
304             @Override
305             public void run() {
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);
311                 } else {
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());
315                     delegate.run();
316                 }
317             }
318         }
319     }
320
321     /**
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.
325      */
326     private static class SimpleSameThreadExecutor extends AbstractListeningExecutorService {
327
328         @Override
329         public void execute(Runnable command) {
330             command.run();
331         }
332
333         @Override
334         public boolean awaitTermination(long arg0, TimeUnit arg1) throws InterruptedException {
335             return true;
336         }
337
338         @Override
339         public boolean isShutdown() {
340             return false;
341         }
342
343         @Override
344         public boolean isTerminated() {
345             return false;
346         }
347
348         @Override
349         public void shutdown() {
350         }
351
352         @Override
353         public List<Runnable> shutdownNow() {
354             return null;
355         }
356     }
357 }