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.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;
39 final class TransactionContextImpl extends AbstractTransactionContext {
40 private static final Logger LOG = LoggerFactory.getLogger(TransactionContextImpl.class);
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;
50 TransactionContextImpl(String transactionPath, ActorSelection actor, TransactionIdentifier identifier,
51 ActorContext actorContext, SchemaContext schemaContext,
52 boolean isTxActorLocal, short remoteTransactionVersion, OperationCompleter operationCompleter) {
54 this.transactionPath = transactionPath;
56 this.actorContext = actorContext;
57 this.isTxActorLocal = isTxActorLocal;
58 this.remoteTransactionVersion = remoteTransactionVersion;
59 this.operationCompleter = operationCompleter;
62 private Future<Object> completeOperation(Future<Object> operationFuture){
63 operationFuture.onComplete(this.operationCompleter, actorContext.getActorSystem().dispatcher());
64 return operationFuture;
68 private ActorSelection getActor() {
72 private Future<Object> executeOperationAsync(SerializableMessage msg) {
73 return completeOperation(actorContext.executeOperationAsync(getActor(), isTxActorLocal ? msg : msg.toSerializable()));
76 private Future<Object> executeOperationAsync(VersionedSerializableMessage msg) {
77 return completeOperation(actorContext.executeOperationAsync(getActor(), isTxActorLocal ? msg :
78 msg.toSerializable(remoteTransactionVersion)));
82 public void closeTransaction() {
83 LOG.debug("Tx {} closeTransaction called", identifier);
85 actorContext.sendOperationAsync(getActor(), CloseTransaction.INSTANCE.toSerializable());
89 public Future<ActorSelection> readyTransaction() {
90 LOG.debug("Tx {} readyTransaction called with {} previous recorded operations pending",
91 identifier, recordedOperationFutures.size());
93 // Send the ReadyTransaction message to the Tx actor.
95 final Future<Object> replyFuture = executeOperationAsync(ReadyTransaction.INSTANCE);
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.
102 List<Future<Object>> futureList =
103 Lists.newArrayListWithCapacity(recordedOperationFutures.size() + 1);
104 futureList.addAll(recordedOperationFutures);
105 futureList.add(replyFuture);
107 Future<Iterable<Object>> combinedFutures = akka.dispatch.Futures.sequence(futureList,
108 actorContext.getActorSystem().dispatcher());
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.
113 return combinedFutures.transform(new Mapper<Iterable<Object>, ActorSelection>() {
115 public ActorSelection checkedApply(Iterable<Object> notUsed) {
116 LOG.debug("Tx {} readyTransaction: pending recorded operations succeeded",
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.
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());
131 } else if(serializedReadyReply.getClass().equals(ReadyTransactionReply.SERIALIZABLE_CLASS)) {
132 ReadyTransactionReply reply = ReadyTransactionReply.fromSerializable(serializedReadyReply);
133 String cohortPath = reply.getCohortPath();
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);
147 return actorContext.actorSelection(cohortPath);
150 // Throwing an exception here will fail the Future.
151 throw new IllegalArgumentException(String.format("Invalid reply type %s",
152 serializedReadyReply.getClass()));
155 }, TransactionProxy.SAME_FAILURE_TRANSFORMER, actorContext.getActorSystem().dispatcher());
159 public void deleteData(YangInstanceIdentifier path) {
160 LOG.debug("Tx {} deleteData called path = {}", identifier, path);
162 recordedOperationFutures.add(executeOperationAsync(new DeleteData(path)));
166 public void mergeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
167 LOG.debug("Tx {} mergeData called path = {}", identifier, path);
169 recordedOperationFutures.add(executeOperationAsync(new MergeData(path, data)));
173 public void writeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
174 LOG.debug("Tx {} writeData called path = {}", identifier, path);
176 recordedOperationFutures.add(executeOperationAsync(new WriteData(path, data)));
180 public void readData(
181 final YangInstanceIdentifier path,final SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture ) {
183 LOG.debug("Tx {} readData called path = {}", identifier, path);
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.
189 if(recordedOperationFutures.isEmpty()) {
190 finishReadData(path, returnFuture);
192 LOG.debug("Tx {} readData: verifying {} previous recorded operations",
193 identifier, recordedOperationFutures.size());
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.
199 Future<Iterable<Object>> combinedFutures = akka.dispatch.Futures.sequence(
200 Lists.newArrayList(recordedOperationFutures),
201 actorContext.getActorSystem().dispatcher());
203 OnComplete<Iterable<Object>> onComplete = new OnComplete<Iterable<Object>>() {
205 public void onComplete(Throwable failure, Iterable<Object> notUsed)
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));
214 finishReadData(path, returnFuture);
219 combinedFutures.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
224 private void finishReadData(final YangInstanceIdentifier path,
225 final SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture) {
227 LOG.debug("Tx {} finishReadData called path = {}", identifier, path);
229 OnComplete<Object> onComplete = new OnComplete<Object>() {
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));
238 LOG.debug("Tx {} read operation succeeded", identifier, failure);
240 if (readResponse instanceof ReadDataReply) {
241 ReadDataReply reply = (ReadDataReply) readResponse;
242 returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
244 } else if (ReadDataReply.isSerializedType(readResponse)) {
245 ReadDataReply reply = ReadDataReply.fromSerializable(readResponse);
246 returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
249 returnFuture.setException(new ReadFailedException(
250 "Invalid response reading data for path " + path));
256 Future<Object> readFuture = executeOperationAsync(new ReadData(path));
258 readFuture.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
262 public void dataExists(final YangInstanceIdentifier path, final SettableFuture<Boolean> returnFuture) {
264 LOG.debug("Tx {} dataExists called path = {}", identifier, path);
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
271 if(recordedOperationFutures.isEmpty()) {
272 finishDataExists(path, returnFuture);
274 LOG.debug("Tx {} dataExists: verifying {} previous recorded operations",
275 identifier, recordedOperationFutures.size());
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.
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>>() {
286 public void onComplete(Throwable failure, Iterable<Object> notUsed)
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));
295 finishDataExists(path, returnFuture);
300 combinedFutures.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
304 private void finishDataExists(final YangInstanceIdentifier path,
305 final SettableFuture<Boolean> returnFuture) {
307 LOG.debug("Tx {} finishDataExists called path = {}", identifier, path);
309 OnComplete<Object> onComplete = new OnComplete<Object>() {
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));
317 LOG.debug("Tx {} dataExists operation succeeded", identifier, failure);
319 if (response instanceof DataExistsReply) {
320 returnFuture.set(Boolean.valueOf(((DataExistsReply) response).exists()));
322 } else if (response.getClass().equals(DataExistsReply.SERIALIZABLE_CLASS)) {
323 returnFuture.set(Boolean.valueOf(DataExistsReply.fromSerializable(response).exists()));
326 returnFuture.setException(new ReadFailedException(
327 "Invalid response checking exists for path " + path));
333 Future<Object> future = executeOperationAsync(new DataExists(path));
335 future.onComplete(onComplete, actorContext.getActorSystem().dispatcher());