2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.cluster.datastore;
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;
41 final class TransactionContextImpl extends AbstractTransactionContext {
42 private static final Logger LOG = LoggerFactory.getLogger(TransactionContextImpl.class);
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;
52 TransactionContextImpl(String transactionPath, ActorSelection actor, TransactionIdentifier identifier,
53 ActorContext actorContext, SchemaContext schemaContext,
54 boolean isTxActorLocal, short remoteTransactionVersion, OperationCompleter operationCompleter) {
56 this.transactionPath = transactionPath;
58 this.actorContext = actorContext;
59 this.isTxActorLocal = isTxActorLocal;
60 this.remoteTransactionVersion = remoteTransactionVersion;
61 this.operationCompleter = operationCompleter;
64 private Future<Object> completeOperation(Future<Object> operationFuture){
65 operationFuture.onComplete(this.operationCompleter, actorContext.getActorSystem().dispatcher());
66 return operationFuture;
70 private ActorSelection getActor() {
74 private Future<Object> executeOperationAsync(SerializableMessage msg) {
75 return completeOperation(actorContext.executeOperationAsync(getActor(), isTxActorLocal ? msg : msg.toSerializable()));
78 private Future<Object> executeOperationAsync(VersionedSerializableMessage msg) {
79 return completeOperation(actorContext.executeOperationAsync(getActor(), isTxActorLocal ? msg :
80 msg.toSerializable(remoteTransactionVersion)));
84 public void closeTransaction() {
85 LOG.debug("Tx {} closeTransaction called", identifier);
87 actorContext.sendOperationAsync(getActor(), CloseTransaction.INSTANCE.toSerializable());
91 public Future<ActorSelection> readyTransaction() {
92 LOG.debug("Tx {} readyTransaction called with {} previous recorded operations pending",
93 identifier, recordedOperationFutures.size());
95 // Send the ReadyTransaction message to the Tx actor.
97 final Future<Object> replyFuture = executeOperationAsync(ReadyTransaction.INSTANCE);
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.
104 List<Future<Object>> futureList =
105 Lists.newArrayListWithCapacity(recordedOperationFutures.size() + 1);
106 futureList.addAll(recordedOperationFutures);
107 futureList.add(replyFuture);
109 Future<Iterable<Object>> combinedFutures = akka.dispatch.Futures.sequence(futureList,
110 actorContext.getActorSystem().dispatcher());
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.
115 return combinedFutures.transform(new Mapper<Iterable<Object>, ActorSelection>() {
117 public ActorSelection checkedApply(Iterable<Object> notUsed) {
118 LOG.debug("Tx {} readyTransaction: pending recorded operations succeeded",
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.
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());
133 } else if(serializedReadyReply.getClass().equals(ReadyTransactionReply.SERIALIZABLE_CLASS)) {
134 ReadyTransactionReply reply = ReadyTransactionReply.fromSerializable(serializedReadyReply);
135 String cohortPath = reply.getCohortPath();
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);
149 return actorContext.actorSelection(cohortPath);
152 // Throwing an exception here will fail the Future.
153 throw new IllegalArgumentException(String.format("Invalid reply type %s",
154 serializedReadyReply.getClass()));
157 }, TransactionProxy.SAME_FAILURE_TRANSFORMER, actorContext.getActorSystem().dispatcher());
161 public void deleteData(YangInstanceIdentifier path) {
162 LOG.debug("Tx {} deleteData called path = {}", identifier, path);
164 recordedOperationFutures.add(executeOperationAsync(new DeleteData(path)));
168 public void mergeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
169 LOG.debug("Tx {} mergeData called path = {}", identifier, path);
171 recordedOperationFutures.add(executeOperationAsync(new MergeData(path, data)));
175 public void writeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
176 LOG.debug("Tx {} writeData called path = {}", identifier, path);
178 recordedOperationFutures.add(executeOperationAsync(new WriteData(path, data)));
182 public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readData(
183 final YangInstanceIdentifier path) {
185 LOG.debug("Tx {} readData called path = {}", identifier, path);
187 final SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture = SettableFuture.create();
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.
193 if(recordedOperationFutures.isEmpty()) {
194 finishReadData(path, returnFuture);
196 LOG.debug("Tx {} readData: verifying {} previous recorded operations",
197 identifier, recordedOperationFutures.size());
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.
203 Future<Iterable<Object>> combinedFutures = akka.dispatch.Futures.sequence(
204 Lists.newArrayList(recordedOperationFutures),
205 actorContext.getActorSystem().dispatcher());
207 OnComplete<Iterable<Object>> onComplete = new OnComplete<Iterable<Object>>() {
209 public void onComplete(Throwable failure, Iterable<Object> notUsed)
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));
218 finishReadData(path, returnFuture);
223 combinedFutures.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
226 return MappingCheckedFuture.create(returnFuture, ReadFailedException.MAPPER);
229 private void finishReadData(final YangInstanceIdentifier path,
230 final SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture) {
232 LOG.debug("Tx {} finishReadData called path = {}", identifier, path);
234 OnComplete<Object> onComplete = new OnComplete<Object>() {
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));
243 LOG.debug("Tx {} read operation succeeded", identifier, failure);
245 if (readResponse instanceof ReadDataReply) {
246 ReadDataReply reply = (ReadDataReply) readResponse;
247 returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
249 } else if (ReadDataReply.isSerializedType(readResponse)) {
250 ReadDataReply reply = ReadDataReply.fromSerializable(readResponse);
251 returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
254 returnFuture.setException(new ReadFailedException(
255 "Invalid response reading data for path " + path));
261 Future<Object> readFuture = executeOperationAsync(new ReadData(path));
263 readFuture.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
267 public CheckedFuture<Boolean, ReadFailedException> dataExists(
268 final YangInstanceIdentifier path) {
270 LOG.debug("Tx {} dataExists called path = {}", identifier, path);
272 final SettableFuture<Boolean> returnFuture = SettableFuture.create();
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
279 if(recordedOperationFutures.isEmpty()) {
280 finishDataExists(path, returnFuture);
282 LOG.debug("Tx {} dataExists: verifying {} previous recorded operations",
283 identifier, recordedOperationFutures.size());
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.
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>>() {
294 public void onComplete(Throwable failure, Iterable<Object> notUsed)
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));
303 finishDataExists(path, returnFuture);
308 combinedFutures.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
311 return MappingCheckedFuture.create(returnFuture, ReadFailedException.MAPPER);
314 private void finishDataExists(final YangInstanceIdentifier path,
315 final SettableFuture<Boolean> returnFuture) {
317 LOG.debug("Tx {} finishDataExists called path = {}", identifier, path);
319 OnComplete<Object> onComplete = new OnComplete<Object>() {
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));
327 LOG.debug("Tx {} dataExists operation succeeded", identifier, failure);
329 if (response instanceof DataExistsReply) {
330 returnFuture.set(Boolean.valueOf(((DataExistsReply) response).exists()));
332 } else if (response.getClass().equals(DataExistsReply.SERIALIZABLE_CLASS)) {
333 returnFuture.set(Boolean.valueOf(DataExistsReply.fromSerializable(response).exists()));
336 returnFuture.setException(new ReadFailedException(
337 "Invalid response checking exists for path " + path));
343 Future<Object> future = executeOperationAsync(new DataExists(path));
345 future.onComplete(onComplete, actorContext.getActorSystem().dispatcher());