07ff936b2f8e87f331e53fb71212a57040b3f9e8
[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.japi.Function;
17 import akka.pattern.Patterns;
18 import akka.util.Timeout;
19 import com.google.common.base.Preconditions;
20 import com.google.common.base.Throwables;
21 import com.google.common.collect.Iterables;
22 import java.util.Collection;
23 import java.util.Iterator;
24 import java.util.concurrent.ExecutionException;
25 import java.util.concurrent.TimeoutException;
26 import org.opendaylight.controller.cluster.datastore.DataTreeCohortActor.CanCommit;
27 import org.opendaylight.controller.cluster.datastore.DataTreeCohortActor.Success;
28 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
29 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
30 import scala.concurrent.Await;
31 import scala.concurrent.Future;
32
33 /**
34  *
35  * Composite cohort, which coordinates multiple user-provided cohorts as if it was only one cohort.
36  *
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          */
76         FAILED,
77         /**
78          *
79          * Abort message was send to all cohorts which responded with success previously.
80          *
81          */
82         ABORTED
83     }
84
85     protected static final Recover<Object> EXCEPTION_TO_MESSAGE = new Recover<Object>() {
86         @Override
87         public Failure recover(Throwable error) throws Throwable {
88             return new Failure(error);
89         }
90     };
91
92
93     private final DataTreeCohortActorRegistry registry;
94     private final String txId;
95     private final SchemaContext schema;
96     private final Timeout timeout;
97     private Iterable<Success> successfulFromPrevious;
98     private State state = State.IDLE;
99
100     CompositeDataTreeCohort(DataTreeCohortActorRegistry registry, String txId, SchemaContext schema, Timeout timeout) {
101         this.registry = Preconditions.checkNotNull(registry);
102         this.txId = Preconditions.checkNotNull(txId);
103         this.schema = Preconditions.checkNotNull(schema);
104         this.timeout = Preconditions.checkNotNull(timeout);
105     }
106
107     void canCommit(DataTreeCandidateTip tip) throws ExecutionException, TimeoutException {
108         Collection<CanCommit> messages = registry.createCanCommitMessages(txId, tip, schema);
109         // FIXME: Optimize empty collection list with pre-created futures, containing success.
110         Future<Iterable<Object>> canCommitsFuture =
111                 Futures.traverse(messages, new Function<CanCommit, Future<Object>>() {
112                     @Override
113                     public Future<Object> apply(CanCommit input) {
114                         return Patterns.ask(input.getCohort(), input, timeout).recover(EXCEPTION_TO_MESSAGE,
115                                 ExecutionContexts.global());
116                     }
117                 }, ExecutionContexts.global());
118         changeStateFrom(State.IDLE, State.CAN_COMMIT_SENT);
119         processResponses(canCommitsFuture, State.CAN_COMMIT_SENT, State.CAN_COMMIT_SUCCESSFUL);
120     }
121
122     void preCommit() throws ExecutionException, TimeoutException {
123         Preconditions.checkState(successfulFromPrevious != null);
124         Future<Iterable<Object>> preCommitFutures = sendMesageToSuccessful(new DataTreeCohortActor.PreCommit(txId));
125         changeStateFrom(State.CAN_COMMIT_SUCCESSFUL, State.PRE_COMMIT_SENT);
126         processResponses(preCommitFutures, State.PRE_COMMIT_SENT, State.PRE_COMMIT_SUCCESSFUL);
127     }
128
129     void commit() throws ExecutionException, TimeoutException {
130         Preconditions.checkState(successfulFromPrevious != null);
131         Future<Iterable<Object>> commitsFuture = sendMesageToSuccessful(new DataTreeCohortActor.Commit(txId));
132         changeStateFrom(State.PRE_COMMIT_SUCCESSFUL, State.COMMIT_SENT);
133         processResponses(commitsFuture, State.COMMIT_SENT, State.COMMITED);
134     }
135
136     void abort() throws TimeoutException {
137         if (successfulFromPrevious != null) {
138             sendMesageToSuccessful(new DataTreeCohortActor.Abort(txId));
139         }
140     }
141
142     private Future<Iterable<Object>> sendMesageToSuccessful(final Object message) {
143         return Futures.traverse(successfulFromPrevious, new Function<DataTreeCohortActor.Success, Future<Object>>() {
144
145             @Override
146             public Future<Object> apply(DataTreeCohortActor.Success cohortResponse) throws Exception {
147                 return Patterns.ask(cohortResponse.getCohort(), message, timeout);
148             }
149
150         }, ExecutionContexts.global());
151     }
152
153     private void processResponses(Future<Iterable<Object>> resultsFuture, State currentState, State afterState)
154             throws TimeoutException, ExecutionException {
155         final Iterable<Object> results;
156         try {
157             results = Await.result(resultsFuture, timeout.duration());
158         } catch (Exception e) {
159             successfulFromPrevious = null;
160             Throwables.propagateIfInstanceOf(e, TimeoutException.class);
161             throw Throwables.propagate(e);
162         }
163         Iterable<Failure> failed = Iterables.filter(results, Status.Failure.class);
164         Iterable<Success> successful = Iterables.filter(results, DataTreeCohortActor.Success.class);
165         successfulFromPrevious = successful;
166         if (!Iterables.isEmpty(failed)) {
167             changeStateFrom(currentState, State.FAILED);
168             Iterator<Failure> it = failed.iterator();
169             Throwable firstEx = it.next().cause();
170             while (it.hasNext()) {
171                 firstEx.addSuppressed(it.next().cause());
172             }
173             Throwables.propagateIfPossible(firstEx, ExecutionException.class);
174             Throwables.propagateIfPossible(firstEx, TimeoutException.class);
175             throw Throwables.propagate(firstEx);
176         }
177         changeStateFrom(currentState, afterState);
178     }
179
180     void changeStateFrom(State expected, State followup) {
181         Preconditions.checkState(state == expected);
182         state = followup;
183     }
184 }