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