Fix warnings/javadocs in sal-distributed-datastore
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / CompositeDataTreeCohort.java
1 /*
2  * Copyright (c) 2016 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
9 package org.opendaylight.controller.cluster.datastore;
10
11 import akka.actor.Status;
12 import akka.actor.Status.Failure;
13 import akka.dispatch.ExecutionContexts;
14 import akka.dispatch.Futures;
15 import akka.dispatch.Recover;
16 import akka.pattern.Patterns;
17 import akka.util.Timeout;
18 import com.google.common.base.Preconditions;
19 import com.google.common.base.Throwables;
20 import com.google.common.collect.Iterables;
21 import java.util.Collection;
22 import java.util.Iterator;
23 import java.util.Optional;
24 import java.util.concurrent.ExecutionException;
25 import java.util.concurrent.TimeoutException;
26 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
27 import org.opendaylight.controller.cluster.datastore.DataTreeCohortActor.CanCommit;
28 import org.opendaylight.controller.cluster.datastore.DataTreeCohortActor.Success;
29 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
30 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
31 import scala.concurrent.Await;
32 import scala.concurrent.Future;
33
34 /**
35  * Composite cohort, which coordinates multiple user-provided cohorts as if it was only one cohort.
36  * <p/>
37  * It tracks current operation and list of cohorts which successfuly finished previous phase in
38  * case, if abort is necessary to invoke it only on cohort steps which are still active.
39  *
40  */
41 class CompositeDataTreeCohort {
42
43     private enum State {
44         /**
45          * Cohorts are idle, no messages were sent.
46          */
47         IDLE,
48         /**
49          * CanCommit message was sent to all participating cohorts.
50          */
51         CAN_COMMIT_SENT,
52         /**
53          * Successful canCommit responses were received from every participating cohort.
54          */
55         CAN_COMMIT_SUCCESSFUL,
56         /**
57          * PreCommit message was sent to all participating cohorts.
58          */
59         PRE_COMMIT_SENT,
60         /**
61          * Successful preCommit responses were received from every participating cohort.
62          */
63         PRE_COMMIT_SUCCESSFUL,
64         /**
65          * Commit message was send to all participating cohorts.
66          */
67         COMMIT_SENT,
68         /**
69          * Successful commit responses were received from all participating cohorts.
70          */
71         COMMITED,
72         /**
73          * Some of cohorts responsed back with unsuccessful message.
74          */
75         FAILED,
76         /**
77          * Abort message was send to all cohorts which responded with success previously.
78          */
79         ABORTED
80     }
81
82     protected static final Recover<Object> EXCEPTION_TO_MESSAGE = new Recover<Object>() {
83         @Override
84         public Failure recover(final Throwable error) throws Throwable {
85             return new Failure(error);
86         }
87     };
88
89
90     private final DataTreeCohortActorRegistry registry;
91     private final TransactionIdentifier txId;
92     private final SchemaContext schema;
93     private final Timeout timeout;
94     private Iterable<Success> successfulFromPrevious;
95     private State state = State.IDLE;
96
97     CompositeDataTreeCohort(final DataTreeCohortActorRegistry registry, final TransactionIdentifier transactionID,
98         final SchemaContext schema, final Timeout timeout) {
99         this.registry = Preconditions.checkNotNull(registry);
100         this.txId = Preconditions.checkNotNull(transactionID);
101         this.schema = Preconditions.checkNotNull(schema);
102         this.timeout = Preconditions.checkNotNull(timeout);
103     }
104
105     void canCommit(final DataTreeCandidate tip) throws ExecutionException, TimeoutException {
106         Collection<CanCommit> messages = registry.createCanCommitMessages(txId, tip, schema);
107         // FIXME: Optimize empty collection list with pre-created futures, containing success.
108         Future<Iterable<Object>> canCommitsFuture = Futures.traverse(messages,
109             input -> Patterns.ask(input.getCohort(), input, timeout).recover(EXCEPTION_TO_MESSAGE,
110                     ExecutionContexts.global()), ExecutionContexts.global());
111         changeStateFrom(State.IDLE, State.CAN_COMMIT_SENT);
112         processResponses(canCommitsFuture, State.CAN_COMMIT_SENT, State.CAN_COMMIT_SUCCESSFUL);
113     }
114
115     void preCommit() throws ExecutionException, TimeoutException {
116         Preconditions.checkState(successfulFromPrevious != null);
117         Future<Iterable<Object>> preCommitFutures = sendMesageToSuccessful(new DataTreeCohortActor.PreCommit(txId));
118         changeStateFrom(State.CAN_COMMIT_SUCCESSFUL, State.PRE_COMMIT_SENT);
119         processResponses(preCommitFutures, State.PRE_COMMIT_SENT, State.PRE_COMMIT_SUCCESSFUL);
120     }
121
122     void commit() throws ExecutionException, TimeoutException {
123         Preconditions.checkState(successfulFromPrevious != null);
124         Future<Iterable<Object>> commitsFuture = sendMesageToSuccessful(new DataTreeCohortActor.Commit(txId));
125         changeStateFrom(State.PRE_COMMIT_SUCCESSFUL, State.COMMIT_SENT);
126         processResponses(commitsFuture, State.COMMIT_SENT, State.COMMITED);
127     }
128
129     Optional<Future<Iterable<Object>>> abort() {
130         if (successfulFromPrevious != null) {
131             return Optional.of(sendMesageToSuccessful(new DataTreeCohortActor.Abort(txId)));
132         }
133
134         return Optional.empty();
135     }
136
137     private Future<Iterable<Object>> sendMesageToSuccessful(final Object message) {
138         return Futures.traverse(successfulFromPrevious, cohortResponse -> Patterns.ask(
139                 cohortResponse.getCohort(), message, timeout), ExecutionContexts.global());
140     }
141
142     @SuppressWarnings("checkstyle:IllegalCatch")
143     private void processResponses(final Future<Iterable<Object>> resultsFuture, final State currentState,
144             final State afterState) throws TimeoutException, ExecutionException {
145         final Iterable<Object> results;
146         try {
147             results = Await.result(resultsFuture, timeout.duration());
148         } catch (Exception e) {
149             successfulFromPrevious = null;
150             Throwables.propagateIfInstanceOf(e, TimeoutException.class);
151             throw Throwables.propagate(e);
152         }
153         Iterable<Failure> failed = Iterables.filter(results, Status.Failure.class);
154         Iterable<Success> successful = Iterables.filter(results, DataTreeCohortActor.Success.class);
155         successfulFromPrevious = successful;
156         if (!Iterables.isEmpty(failed)) {
157             changeStateFrom(currentState, State.FAILED);
158             Iterator<Failure> it = failed.iterator();
159             Throwable firstEx = it.next().cause();
160             while (it.hasNext()) {
161                 firstEx.addSuppressed(it.next().cause());
162             }
163             Throwables.propagateIfPossible(firstEx, ExecutionException.class);
164             Throwables.propagateIfPossible(firstEx, TimeoutException.class);
165             throw Throwables.propagate(firstEx);
166         }
167         changeStateFrom(currentState, afterState);
168     }
169
170     void changeStateFrom(final State expected, final State followup) {
171         Preconditions.checkState(state == expected);
172         state = followup;
173     }
174 }

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