530a36cff657304005ebd4b43a5bb1e46449951b
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / TransactionContextImpl.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.actor.ActorSelection;
11 import akka.dispatch.Mapper;
12 import akka.dispatch.OnComplete;
13 import com.google.common.base.Optional;
14 import com.google.common.collect.Lists;
15 import com.google.common.util.concurrent.SettableFuture;
16 import java.util.List;
17 import org.opendaylight.controller.cluster.datastore.identifiers.TransactionIdentifier;
18 import org.opendaylight.controller.cluster.datastore.messages.CloseTransaction;
19 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
20 import org.opendaylight.controller.cluster.datastore.messages.DataExistsReply;
21 import org.opendaylight.controller.cluster.datastore.messages.DeleteData;
22 import org.opendaylight.controller.cluster.datastore.messages.MergeData;
23 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
24 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
25 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransaction;
26 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
27 import org.opendaylight.controller.cluster.datastore.messages.SerializableMessage;
28 import org.opendaylight.controller.cluster.datastore.messages.VersionedSerializableMessage;
29 import org.opendaylight.controller.cluster.datastore.messages.WriteData;
30 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
31 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
34 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import scala.concurrent.Future;
38
39 final class TransactionContextImpl extends AbstractTransactionContext {
40     private static final Logger LOG = LoggerFactory.getLogger(TransactionContextImpl.class);
41
42     private final ActorContext actorContext;
43     private final String transactionPath;
44     private final ActorSelection actor;
45     private final boolean isTxActorLocal;
46     private final short remoteTransactionVersion;
47     private final OperationCompleter operationCompleter;
48
49
50     TransactionContextImpl(String transactionPath, ActorSelection actor, TransactionIdentifier identifier,
51             ActorContext actorContext, SchemaContext schemaContext,
52             boolean isTxActorLocal, short remoteTransactionVersion, OperationCompleter operationCompleter) {
53         super(identifier);
54         this.transactionPath = transactionPath;
55         this.actor = actor;
56         this.actorContext = actorContext;
57         this.isTxActorLocal = isTxActorLocal;
58         this.remoteTransactionVersion = remoteTransactionVersion;
59         this.operationCompleter = operationCompleter;
60     }
61
62     private Future<Object> completeOperation(Future<Object> operationFuture){
63         operationFuture.onComplete(this.operationCompleter, actorContext.getActorSystem().dispatcher());
64         return operationFuture;
65     }
66
67
68     private ActorSelection getActor() {
69         return actor;
70     }
71
72     private Future<Object> executeOperationAsync(SerializableMessage msg) {
73         return completeOperation(actorContext.executeOperationAsync(getActor(), isTxActorLocal ? msg : msg.toSerializable()));
74     }
75
76     private Future<Object> executeOperationAsync(VersionedSerializableMessage msg) {
77         return completeOperation(actorContext.executeOperationAsync(getActor(), isTxActorLocal ? msg :
78                 msg.toSerializable(remoteTransactionVersion)));
79     }
80
81     @Override
82     public void closeTransaction() {
83         LOG.debug("Tx {} closeTransaction called", identifier);
84
85         actorContext.sendOperationAsync(getActor(), CloseTransaction.INSTANCE.toSerializable());
86     }
87
88     @Override
89     public Future<ActorSelection> readyTransaction() {
90         LOG.debug("Tx {} readyTransaction called with {} previous recorded operations pending",
91                 identifier, recordedOperationFutures.size());
92
93         // Send the ReadyTransaction message to the Tx actor.
94
95         final Future<Object> replyFuture = executeOperationAsync(ReadyTransaction.INSTANCE);
96
97         // Combine all the previously recorded put/merge/delete operation reply Futures and the
98         // ReadyTransactionReply Future into one Future. If any one fails then the combined
99         // Future will fail. We need all prior operations and the ready operation to succeed
100         // in order to attempt commit.
101
102         List<Future<Object>> futureList =
103                 Lists.newArrayListWithCapacity(recordedOperationFutures.size() + 1);
104         futureList.addAll(recordedOperationFutures);
105         futureList.add(replyFuture);
106
107         Future<Iterable<Object>> combinedFutures = akka.dispatch.Futures.sequence(futureList,
108                 actorContext.getActorSystem().dispatcher());
109
110         // Transform the combined Future into a Future that returns the cohort actor path from
111         // the ReadyTransactionReply. That's the end result of the ready operation.
112
113         return combinedFutures.transform(new Mapper<Iterable<Object>, ActorSelection>() {
114             @Override
115             public ActorSelection checkedApply(Iterable<Object> notUsed) {
116                 LOG.debug("Tx {} readyTransaction: pending recorded operations succeeded",
117                         identifier);
118
119                 // At this point all the Futures succeeded and we need to extract the cohort
120                 // actor path from the ReadyTransactionReply. For the recorded operations, they
121                 // don't return any data so we're only interested that they completed
122                 // successfully. We could be paranoid and verify the correct reply types but
123                 // that really should never happen so it's not worth the overhead of
124                 // de-serializing each reply.
125
126                 // Note the Future get call here won't block as it's complete.
127                 Object serializedReadyReply = replyFuture.value().get().get();
128                 if (serializedReadyReply instanceof ReadyTransactionReply) {
129                     return actorContext.actorSelection(((ReadyTransactionReply)serializedReadyReply).getCohortPath());
130
131                 } else if(serializedReadyReply.getClass().equals(ReadyTransactionReply.SERIALIZABLE_CLASS)) {
132                     ReadyTransactionReply reply = ReadyTransactionReply.fromSerializable(serializedReadyReply);
133                     String cohortPath = reply.getCohortPath();
134
135                     // In Helium we used to return the local path of the actor which represented
136                     // a remote ThreePhaseCommitCohort. The local path would then be converted to
137                     // a remote path using this resolvePath method. To maintain compatibility with
138                     // a Helium node we need to continue to do this conversion.
139                     // At some point in the future when upgrades from Helium are not supported
140                     // we could remove this code to resolvePath and just use the cohortPath as the
141                     // resolved cohortPath
142                     if(TransactionContextImpl.this.remoteTransactionVersion <
143                             DataStoreVersions.HELIUM_1_VERSION) {
144                         cohortPath = actorContext.resolvePath(transactionPath, cohortPath);
145                     }
146
147                     return actorContext.actorSelection(cohortPath);
148
149                 } else {
150                     // Throwing an exception here will fail the Future.
151                     throw new IllegalArgumentException(String.format("Invalid reply type %s",
152                             serializedReadyReply.getClass()));
153                 }
154             }
155         }, TransactionProxy.SAME_FAILURE_TRANSFORMER, actorContext.getActorSystem().dispatcher());
156     }
157
158     @Override
159     public void deleteData(YangInstanceIdentifier path) {
160         LOG.debug("Tx {} deleteData called path = {}", identifier, path);
161
162         recordedOperationFutures.add(executeOperationAsync(new DeleteData(path)));
163     }
164
165     @Override
166     public void mergeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
167         LOG.debug("Tx {} mergeData called path = {}", identifier, path);
168
169         recordedOperationFutures.add(executeOperationAsync(new MergeData(path, data)));
170     }
171
172     @Override
173     public void writeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
174         LOG.debug("Tx {} writeData called path = {}", identifier, path);
175
176         recordedOperationFutures.add(executeOperationAsync(new WriteData(path, data)));
177     }
178
179     @Override
180     public void readData(
181             final YangInstanceIdentifier path,final SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture ) {
182
183         LOG.debug("Tx {} readData called path = {}", identifier, path);
184
185         // If there were any previous recorded put/merge/delete operation reply Futures then we
186         // must wait for them to successfully complete. This is necessary to honor the read
187         // uncommitted semantics of the public API contract. If any one fails then fail the read.
188
189         if(recordedOperationFutures.isEmpty()) {
190             finishReadData(path, returnFuture);
191         } else {
192             LOG.debug("Tx {} readData: verifying {} previous recorded operations",
193                     identifier, recordedOperationFutures.size());
194
195             // Note: we make a copy of recordedOperationFutures to be on the safe side in case
196             // Futures#sequence accesses the passed List on a different thread, as
197             // recordedOperationFutures is not synchronized.
198
199             Future<Iterable<Object>> combinedFutures = akka.dispatch.Futures.sequence(
200                     Lists.newArrayList(recordedOperationFutures),
201                     actorContext.getActorSystem().dispatcher());
202
203             OnComplete<Iterable<Object>> onComplete = new OnComplete<Iterable<Object>>() {
204                 @Override
205                 public void onComplete(Throwable failure, Iterable<Object> notUsed)
206                         throws Throwable {
207                     if(failure != null) {
208                         LOG.debug("Tx {} readData: a recorded operation failed: {}",
209                                 identifier, failure);
210                         returnFuture.setException(new ReadFailedException(
211                                 "The read could not be performed because a previous put, merge,"
212                                 + "or delete operation failed", failure));
213                     } else {
214                         finishReadData(path, returnFuture);
215                     }
216                 }
217             };
218
219             combinedFutures.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
220         }
221
222     }
223
224     private void finishReadData(final YangInstanceIdentifier path,
225             final SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture) {
226
227         LOG.debug("Tx {} finishReadData called path = {}", identifier, path);
228
229         OnComplete<Object> onComplete = new OnComplete<Object>() {
230             @Override
231             public void onComplete(Throwable failure, Object readResponse) throws Throwable {
232                 if(failure != null) {
233                     LOG.debug("Tx {} read operation failed: {}", identifier, failure);
234                     returnFuture.setException(new ReadFailedException(
235                             "Error reading data for path " + path, failure));
236
237                 } else {
238                     LOG.debug("Tx {} read operation succeeded", identifier, failure);
239
240                     if (readResponse instanceof ReadDataReply) {
241                         ReadDataReply reply = (ReadDataReply) readResponse;
242                         returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
243
244                     } else if (ReadDataReply.isSerializedType(readResponse)) {
245                         ReadDataReply reply = ReadDataReply.fromSerializable(readResponse);
246                         returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
247
248                     } else {
249                         returnFuture.setException(new ReadFailedException(
250                             "Invalid response reading data for path " + path));
251                     }
252                 }
253             }
254         };
255
256         Future<Object> readFuture = executeOperationAsync(new ReadData(path));
257
258         readFuture.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
259     }
260
261     @Override
262     public void dataExists(final YangInstanceIdentifier path, final SettableFuture<Boolean> returnFuture) {
263
264         LOG.debug("Tx {} dataExists called path = {}", identifier, path);
265
266         // If there were any previous recorded put/merge/delete operation reply Futures then we
267         // must wait for them to successfully complete. This is necessary to honor the read
268         // uncommitted semantics of the public API contract. If any one fails then fail this
269         // request.
270
271         if(recordedOperationFutures.isEmpty()) {
272             finishDataExists(path, returnFuture);
273         } else {
274             LOG.debug("Tx {} dataExists: verifying {} previous recorded operations",
275                     identifier, recordedOperationFutures.size());
276
277             // Note: we make a copy of recordedOperationFutures to be on the safe side in case
278             // Futures#sequence accesses the passed List on a different thread, as
279             // recordedOperationFutures is not synchronized.
280
281             Future<Iterable<Object>> combinedFutures = akka.dispatch.Futures.sequence(
282                     Lists.newArrayList(recordedOperationFutures),
283                     actorContext.getActorSystem().dispatcher());
284             OnComplete<Iterable<Object>> onComplete = new OnComplete<Iterable<Object>>() {
285                 @Override
286                 public void onComplete(Throwable failure, Iterable<Object> notUsed)
287                         throws Throwable {
288                     if(failure != null) {
289                         LOG.debug("Tx {} dataExists: a recorded operation failed: {}",
290                                 identifier, failure);
291                         returnFuture.setException(new ReadFailedException(
292                                 "The data exists could not be performed because a previous "
293                                 + "put, merge, or delete operation failed", failure));
294                     } else {
295                         finishDataExists(path, returnFuture);
296                     }
297                 }
298             };
299
300             combinedFutures.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
301         }
302     }
303
304     private void finishDataExists(final YangInstanceIdentifier path,
305             final SettableFuture<Boolean> returnFuture) {
306
307         LOG.debug("Tx {} finishDataExists called path = {}", identifier, path);
308
309         OnComplete<Object> onComplete = new OnComplete<Object>() {
310             @Override
311             public void onComplete(Throwable failure, Object response) throws Throwable {
312                 if(failure != null) {
313                     LOG.debug("Tx {} dataExists operation failed: {}", identifier, failure);
314                     returnFuture.setException(new ReadFailedException(
315                             "Error checking data exists for path " + path, failure));
316                 } else {
317                     LOG.debug("Tx {} dataExists operation succeeded", identifier, failure);
318
319                     if (response instanceof DataExistsReply) {
320                         returnFuture.set(Boolean.valueOf(((DataExistsReply) response).exists()));
321
322                     } else if (response.getClass().equals(DataExistsReply.SERIALIZABLE_CLASS)) {
323                         returnFuture.set(Boolean.valueOf(DataExistsReply.fromSerializable(response).exists()));
324
325                     } else {
326                         returnFuture.setException(new ReadFailedException(
327                                 "Invalid response checking exists for path " + path));
328                     }
329                 }
330             }
331         };
332
333         Future<Object> future = executeOperationAsync(new DataExists(path));
334
335         future.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
336     }
337 }