BUG-8618: turn timeouts in READY state into canCommit failures
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / SimpleShardDataTreeCohort.java
1 /*
2  * Copyright (c) 2015 Cisco 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 akka.dispatch.ExecutionContexts;
11 import akka.dispatch.Futures;
12 import akka.dispatch.OnComplete;
13 import com.google.common.base.MoreObjects.ToStringHelper;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Verify;
16 import com.google.common.primitives.UnsignedLong;
17 import com.google.common.util.concurrent.FutureCallback;
18 import java.util.List;
19 import java.util.Optional;
20 import java.util.concurrent.ExecutionException;
21 import java.util.concurrent.TimeoutException;
22 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28 import scala.concurrent.Future;
29
30 abstract class SimpleShardDataTreeCohort extends ShardDataTreeCohort {
31     static final class DeadOnArrival extends SimpleShardDataTreeCohort {
32         private final Exception failure;
33
34         DeadOnArrival(final ShardDataTree dataTree, final DataTreeModification transaction,
35             final TransactionIdentifier transactionId, final Exception failure) {
36             super(dataTree, transaction, transactionId, null);
37             this.failure = Preconditions.checkNotNull(failure);
38         }
39
40         @Override
41         void throwCanCommitFailure() throws Exception {
42             throw failure;
43         }
44
45         @Override
46         ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
47             return super.addToStringAttributes(toStringHelper).add("failure", failure);
48         }
49     }
50
51     static final class Normal extends SimpleShardDataTreeCohort {
52         Normal(final ShardDataTree dataTree, final DataTreeModification transaction,
53             final TransactionIdentifier transactionId, final CompositeDataTreeCohort userCohorts) {
54             super(dataTree, transaction, transactionId, Preconditions.checkNotNull(userCohorts));
55         }
56
57         @Override
58         void throwCanCommitFailure() {
59             // No-op
60         }
61     }
62
63     private static final Logger LOG = LoggerFactory.getLogger(SimpleShardDataTreeCohort.class);
64
65     private final DataTreeModification transaction;
66     private final ShardDataTree dataTree;
67     private final TransactionIdentifier transactionId;
68     private final CompositeDataTreeCohort userCohorts;
69
70     private State state = State.READY;
71     private DataTreeCandidateTip candidate;
72     private FutureCallback<?> callback;
73     private Exception nextFailure;
74
75     SimpleShardDataTreeCohort(final ShardDataTree dataTree, final DataTreeModification transaction,
76             final TransactionIdentifier transactionId, final CompositeDataTreeCohort userCohorts) {
77         this.dataTree = Preconditions.checkNotNull(dataTree);
78         this.transaction = Preconditions.checkNotNull(transaction);
79         this.transactionId = Preconditions.checkNotNull(transactionId);
80         this.userCohorts = userCohorts;
81     }
82
83     @Override
84     public TransactionIdentifier getIdentifier() {
85         return transactionId;
86     }
87
88     @Override
89     DataTreeCandidateTip getCandidate() {
90         return candidate;
91     }
92
93     @Override
94     DataTreeModification getDataTreeModification() {
95         return transaction;
96     }
97
98     private void checkState(final State expected) {
99         Preconditions.checkState(state == expected, "State %s does not match expected state %s", state, expected);
100     }
101
102     @Override
103     public void canCommit(final FutureCallback<Void> newCallback) {
104         if (state == State.CAN_COMMIT_PENDING) {
105             return;
106         }
107
108         checkState(State.READY);
109         this.callback = Preconditions.checkNotNull(newCallback);
110         state = State.CAN_COMMIT_PENDING;
111
112         if (nextFailure == null) {
113             dataTree.startCanCommit(this);
114         } else {
115             failedCanCommit(nextFailure);
116         }
117     }
118
119     @Override
120     public void preCommit(final FutureCallback<DataTreeCandidate> newCallback) {
121         checkState(State.CAN_COMMIT_COMPLETE);
122         this.callback = Preconditions.checkNotNull(newCallback);
123         state = State.PRE_COMMIT_PENDING;
124
125         if (nextFailure == null) {
126             dataTree.startPreCommit(this);
127         } else {
128             failedPreCommit(nextFailure);
129         }
130     }
131
132     @Override
133     public void abort(final FutureCallback<Void> abortCallback) {
134         if (!dataTree.startAbort(this)) {
135             abortCallback.onSuccess(null);
136             return;
137         }
138
139         candidate = null;
140         state = State.ABORTED;
141
142         final Optional<List<Future<Object>>> maybeAborts = userCohorts.abort();
143         if (!maybeAborts.isPresent()) {
144             abortCallback.onSuccess(null);
145             return;
146         }
147
148         final Future<Iterable<Object>> aborts = Futures.sequence(maybeAborts.get(), ExecutionContexts.global());
149         if (aborts.isCompleted()) {
150             abortCallback.onSuccess(null);
151             return;
152         }
153
154         aborts.onComplete(new OnComplete<Iterable<Object>>() {
155             @Override
156             public void onComplete(final Throwable failure, final Iterable<Object> objs) {
157                 if (failure != null) {
158                     abortCallback.onFailure(failure);
159                 } else {
160                     abortCallback.onSuccess(null);
161                 }
162             }
163         }, ExecutionContexts.global());
164     }
165
166     @Override
167     public void commit(final FutureCallback<UnsignedLong> newCallback) {
168         checkState(State.PRE_COMMIT_COMPLETE);
169         this.callback = Preconditions.checkNotNull(newCallback);
170         state = State.COMMIT_PENDING;
171
172         if (nextFailure == null) {
173             dataTree.startCommit(this, candidate);
174         } else {
175             failedCommit(nextFailure);
176         }
177     }
178
179     private <T> FutureCallback<T> switchState(final State newState) {
180         @SuppressWarnings("unchecked")
181         final FutureCallback<T> ret = (FutureCallback<T>) this.callback;
182         this.callback = null;
183         LOG.debug("Transaction {} changing state from {} to {}", transactionId, state, newState);
184         this.state = newState;
185         return ret;
186     }
187
188     void setNewCandidate(final DataTreeCandidateTip dataTreeCandidate) {
189         checkState(State.PRE_COMMIT_COMPLETE);
190         this.candidate = Verify.verifyNotNull(dataTreeCandidate);
191     }
192
193     void successfulCanCommit() {
194         switchState(State.CAN_COMMIT_COMPLETE).onSuccess(null);
195     }
196
197     void failedCanCommit(final Exception cause) {
198         switchState(State.FAILED).onFailure(cause);
199     }
200
201     /**
202      * Run user-defined canCommit and preCommit hooks. We want to run these before we initiate persistence so that
203      * any failure to validate is propagated before we record the transaction.
204      *
205      * @param dataTreeCandidate {@link DataTreeCandidate} under consideration
206      * @throws ExecutionException if the operation fails
207      * @throws TimeoutException if the operation times out
208      */
209     // FIXME: this should be asynchronous
210     void userPreCommit(final DataTreeCandidate dataTreeCandidate) throws ExecutionException, TimeoutException {
211         userCohorts.reset();
212         userCohorts.canCommit(dataTreeCandidate);
213         userCohorts.preCommit();
214     }
215
216     void successfulPreCommit(final DataTreeCandidateTip dataTreeCandidate) {
217         LOG.trace("Transaction {} prepared candidate {}", transaction, dataTreeCandidate);
218         this.candidate = Verify.verifyNotNull(dataTreeCandidate);
219         switchState(State.PRE_COMMIT_COMPLETE).onSuccess(dataTreeCandidate);
220     }
221
222     void failedPreCommit(final Exception cause) {
223         if (LOG.isTraceEnabled()) {
224             LOG.trace("Transaction {} failed to prepare", transaction, cause);
225         } else {
226             LOG.error("Transaction {} failed to prepare", transactionId, cause);
227         }
228
229         userCohorts.abort();
230         switchState(State.FAILED).onFailure(cause);
231     }
232
233     void successfulCommit(final UnsignedLong journalIndex) {
234         try {
235             userCohorts.commit();
236         } catch (TimeoutException | ExecutionException e) {
237             // We are probably dead, depending on what the cohorts end up doing
238             LOG.error("User cohorts failed to commit", e);
239         }
240
241         switchState(State.COMMITTED).onSuccess(journalIndex);
242     }
243
244     void failedCommit(final Exception cause) {
245         if (LOG.isTraceEnabled()) {
246             LOG.trace("Transaction {} failed to commit", transaction, cause);
247         } else {
248             LOG.error("Transaction failed to commit", cause);
249         }
250
251         userCohorts.abort();
252         switchState(State.FAILED).onFailure(cause);
253     }
254
255     @Override
256     public State getState() {
257         return state;
258     }
259
260     void reportFailure(final Exception cause) {
261         this.nextFailure = Preconditions.checkNotNull(cause);
262     }
263
264     /**
265      * If there is an initial failure, throw it so the caller can process it.
266      *
267      * @throws Exception reported failure.
268      */
269     abstract void throwCanCommitFailure() throws Exception;
270
271     @Override
272     public boolean isFailed() {
273         return state == State.FAILED || nextFailure != null;
274     }
275
276     @Override
277     ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
278         return super.addToStringAttributes(toStringHelper).add("nextFailure", nextFailure);
279     }
280 }

©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.