6c159b1f5e1ce65c211b4a0ea2442ec964c319b3
[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         dataTree.startCanCommit(this);
112     }
113
114     @Override
115     public void preCommit(final FutureCallback<DataTreeCandidate> newCallback) {
116         checkState(State.CAN_COMMIT_COMPLETE);
117         this.callback = Preconditions.checkNotNull(newCallback);
118         state = State.PRE_COMMIT_PENDING;
119
120         if (nextFailure == null) {
121             dataTree.startPreCommit(this);
122         } else {
123             failedPreCommit(nextFailure);
124         }
125     }
126
127     @Override
128     public void abort(final FutureCallback<Void> abortCallback) {
129         if (!dataTree.startAbort(this)) {
130             abortCallback.onSuccess(null);
131             return;
132         }
133
134         candidate = null;
135         state = State.ABORTED;
136
137         final Optional<List<Future<Object>>> maybeAborts = userCohorts.abort();
138         if (!maybeAborts.isPresent()) {
139             abortCallback.onSuccess(null);
140             return;
141         }
142
143         final Future<Iterable<Object>> aborts = Futures.sequence(maybeAborts.get(), ExecutionContexts.global());
144         if (aborts.isCompleted()) {
145             abortCallback.onSuccess(null);
146             return;
147         }
148
149         aborts.onComplete(new OnComplete<Iterable<Object>>() {
150             @Override
151             public void onComplete(final Throwable failure, final Iterable<Object> objs) {
152                 if (failure != null) {
153                     abortCallback.onFailure(failure);
154                 } else {
155                     abortCallback.onSuccess(null);
156                 }
157             }
158         }, ExecutionContexts.global());
159     }
160
161     @Override
162     public void commit(final FutureCallback<UnsignedLong> newCallback) {
163         checkState(State.PRE_COMMIT_COMPLETE);
164         this.callback = Preconditions.checkNotNull(newCallback);
165         state = State.COMMIT_PENDING;
166
167         if (nextFailure == null) {
168             dataTree.startCommit(this, candidate);
169         } else {
170             failedCommit(nextFailure);
171         }
172     }
173
174     private <T> FutureCallback<T> switchState(final State newState) {
175         @SuppressWarnings("unchecked")
176         final FutureCallback<T> ret = (FutureCallback<T>) this.callback;
177         this.callback = null;
178         LOG.debug("Transaction {} changing state from {} to {}", transactionId, state, newState);
179         this.state = newState;
180         return ret;
181     }
182
183     void setNewCandidate(final DataTreeCandidateTip dataTreeCandidate) {
184         checkState(State.PRE_COMMIT_COMPLETE);
185         this.candidate = Verify.verifyNotNull(dataTreeCandidate);
186     }
187
188     void successfulCanCommit() {
189         switchState(State.CAN_COMMIT_COMPLETE).onSuccess(null);
190     }
191
192     void failedCanCommit(final Exception cause) {
193         switchState(State.FAILED).onFailure(cause);
194     }
195
196     /**
197      * Run user-defined canCommit and preCommit hooks. We want to run these before we initiate persistence so that
198      * any failure to validate is propagated before we record the transaction.
199      *
200      * @param dataTreeCandidate {@link DataTreeCandidate} under consideration
201      * @throws ExecutionException if the operation fails
202      * @throws TimeoutException if the operation times out
203      */
204     // FIXME: this should be asynchronous
205     void userPreCommit(final DataTreeCandidate dataTreeCandidate) throws ExecutionException, TimeoutException {
206         userCohorts.reset();
207         userCohorts.canCommit(dataTreeCandidate);
208         userCohorts.preCommit();
209     }
210
211     void successfulPreCommit(final DataTreeCandidateTip dataTreeCandidate) {
212         LOG.trace("Transaction {} prepared candidate {}", transaction, dataTreeCandidate);
213         this.candidate = Verify.verifyNotNull(dataTreeCandidate);
214         switchState(State.PRE_COMMIT_COMPLETE).onSuccess(dataTreeCandidate);
215     }
216
217     void failedPreCommit(final Exception cause) {
218         if (LOG.isTraceEnabled()) {
219             LOG.trace("Transaction {} failed to prepare", transaction, cause);
220         } else {
221             LOG.error("Transaction {} failed to prepare", transactionId, cause);
222         }
223
224         userCohorts.abort();
225         switchState(State.FAILED).onFailure(cause);
226     }
227
228     void successfulCommit(final UnsignedLong journalIndex) {
229         try {
230             userCohorts.commit();
231         } catch (TimeoutException | ExecutionException e) {
232             // We are probably dead, depending on what the cohorts end up doing
233             LOG.error("User cohorts failed to commit", e);
234         }
235
236         switchState(State.COMMITTED).onSuccess(journalIndex);
237     }
238
239     void failedCommit(final Exception cause) {
240         if (LOG.isTraceEnabled()) {
241             LOG.trace("Transaction {} failed to commit", transaction, cause);
242         } else {
243             LOG.error("Transaction failed to commit", cause);
244         }
245
246         userCohorts.abort();
247         switchState(State.FAILED).onFailure(cause);
248     }
249
250     @Override
251     public State getState() {
252         return state;
253     }
254
255     void reportFailure(final Exception cause) {
256         this.nextFailure = Preconditions.checkNotNull(cause);
257     }
258
259     /**
260      * If there is an initial failure, throw it so the caller can process it.
261      *
262      * @throws Exception reported failure.
263      */
264     abstract void throwCanCommitFailure() throws Exception;
265
266     @Override
267     public boolean isFailed() {
268         return state == State.FAILED || nextFailure != null;
269     }
270
271     @Override
272     ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
273         return super.addToStringAttributes(toStringHelper).add("nextFailure", nextFailure);
274     }
275 }

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