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.BatchedModifications;
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.ReadData;
23 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
24 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransaction;
25 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
26 import org.opendaylight.controller.cluster.datastore.messages.SerializableMessage;
27 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
28 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
29 import org.opendaylight.controller.cluster.datastore.modification.Modification;
30 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
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.yang.data.api.YangInstanceIdentifier;
34 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
35 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import scala.concurrent.Future;
40 public class TransactionContextImpl extends AbstractTransactionContext {
41 private static final Logger LOG = LoggerFactory.getLogger(TransactionContextImpl.class);
43 private final ActorContext actorContext;
44 private final String transactionPath;
45 private final ActorSelection actor;
46 private final boolean isTxActorLocal;
47 private final short remoteTransactionVersion;
49 private final OperationCompleter operationCompleter;
50 private BatchedModifications batchedModifications;
52 protected 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.getClientDispatcher());
66 return operationFuture;
70 private ActorSelection getActor() {
74 protected short getRemoteTransactionVersion() {
75 return remoteTransactionVersion;
78 protected Future<Object> executeOperationAsync(SerializableMessage msg) {
79 return completeOperation(actorContext.executeOperationAsync(getActor(), isTxActorLocal ? msg : msg.toSerializable()));
83 public void closeTransaction() {
84 LOG.debug("Tx {} closeTransaction called", identifier);
86 actorContext.sendOperationAsync(getActor(), CloseTransaction.INSTANCE.toSerializable());
90 public Future<ActorSelection> readyTransaction() {
91 LOG.debug("Tx {} readyTransaction called with {} previous recorded operations pending",
92 identifier, recordedOperationFutures.size());
94 // Send the remaining batched modifications if any.
96 sendBatchedModifications();
98 // Send the ReadyTransaction message to the Tx actor.
100 final Future<Object> replyFuture = executeOperationAsync(ReadyTransaction.INSTANCE);
102 // Combine all the previously recorded put/merge/delete operation reply Futures and the
103 // ReadyTransactionReply Future into one Future. If any one fails then the combined
104 // Future will fail. We need all prior operations and the ready operation to succeed
105 // in order to attempt commit.
107 List<Future<Object>> futureList =
108 Lists.newArrayListWithCapacity(recordedOperationFutures.size() + 1);
109 futureList.addAll(recordedOperationFutures);
110 futureList.add(replyFuture);
112 Future<Iterable<Object>> combinedFutures = akka.dispatch.Futures.sequence(futureList,
113 actorContext.getClientDispatcher());
115 // Transform the combined Future into a Future that returns the cohort actor path from
116 // the ReadyTransactionReply. That's the end result of the ready operation.
118 return combinedFutures.transform(new Mapper<Iterable<Object>, ActorSelection>() {
120 public ActorSelection checkedApply(Iterable<Object> notUsed) {
121 LOG.debug("Tx {} readyTransaction: pending recorded operations succeeded",
124 // At this point all the Futures succeeded and we need to extract the cohort
125 // actor path from the ReadyTransactionReply. For the recorded operations, they
126 // don't return any data so we're only interested that they completed
127 // successfully. We could be paranoid and verify the correct reply types but
128 // that really should never happen so it's not worth the overhead of
129 // de-serializing each reply.
131 // Note the Future get call here won't block as it's complete.
132 Object serializedReadyReply = replyFuture.value().get().get();
133 if (serializedReadyReply instanceof ReadyTransactionReply) {
134 return actorContext.actorSelection(((ReadyTransactionReply)serializedReadyReply).getCohortPath());
136 } else if(serializedReadyReply.getClass().equals(ReadyTransactionReply.SERIALIZABLE_CLASS)) {
137 ReadyTransactionReply reply = ReadyTransactionReply.fromSerializable(serializedReadyReply);
138 String cohortPath = reply.getCohortPath();
140 // In Helium we used to return the local path of the actor which represented
141 // a remote ThreePhaseCommitCohort. The local path would then be converted to
142 // a remote path using this resolvePath method. To maintain compatibility with
143 // a Helium node we need to continue to do this conversion.
144 // At some point in the future when upgrades from Helium are not supported
145 // we could remove this code to resolvePath and just use the cohortPath as the
146 // resolved cohortPath
147 if(TransactionContextImpl.this.remoteTransactionVersion <
148 DataStoreVersions.HELIUM_1_VERSION) {
149 cohortPath = actorContext.resolvePath(transactionPath, cohortPath);
152 return actorContext.actorSelection(cohortPath);
155 // Throwing an exception here will fail the Future.
156 throw new IllegalArgumentException(String.format("%s: Invalid reply type %s",
157 identifier, serializedReadyReply.getClass()));
160 }, TransactionProxy.SAME_FAILURE_TRANSFORMER, actorContext.getClientDispatcher());
163 private void batchModification(Modification modification) {
164 if(batchedModifications == null) {
165 batchedModifications = new BatchedModifications(remoteTransactionVersion);
168 batchedModifications.addModification(modification);
170 if(batchedModifications.getModifications().size() >=
171 actorContext.getDatastoreContext().getShardBatchedModificationCount()) {
172 sendBatchedModifications();
176 private void sendBatchedModifications() {
177 if(batchedModifications != null) {
178 LOG.debug("Tx {} sending {} batched modifications", identifier,
179 batchedModifications.getModifications().size());
181 recordedOperationFutures.add(executeOperationAsync(batchedModifications));
182 batchedModifications = null;
187 public void deleteData(YangInstanceIdentifier path) {
188 LOG.debug("Tx {} deleteData called path = {}", identifier, path);
190 batchModification(new DeleteModification(path));
194 public void mergeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
195 LOG.debug("Tx {} mergeData called path = {}", identifier, path);
197 batchModification(new MergeModification(path, data));
201 public void writeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
202 LOG.debug("Tx {} writeData called path = {}", identifier, path);
204 batchModification(new WriteModification(path, data));
208 public void readData(
209 final YangInstanceIdentifier path,final SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture ) {
211 LOG.debug("Tx {} readData called path = {}", identifier, path);
213 // Send the remaining batched modifications if any.
215 sendBatchedModifications();
217 // If there were any previous recorded put/merge/delete operation reply Futures then we
218 // must wait for them to successfully complete. This is necessary to honor the read
219 // uncommitted semantics of the public API contract. If any one fails then fail the read.
221 if(recordedOperationFutures.isEmpty()) {
222 finishReadData(path, returnFuture);
224 LOG.debug("Tx {} readData: verifying {} previous recorded operations",
225 identifier, recordedOperationFutures.size());
227 // Note: we make a copy of recordedOperationFutures to be on the safe side in case
228 // Futures#sequence accesses the passed List on a different thread, as
229 // recordedOperationFutures is not synchronized.
231 Future<Iterable<Object>> combinedFutures = akka.dispatch.Futures.sequence(
232 Lists.newArrayList(recordedOperationFutures),
233 actorContext.getClientDispatcher());
235 OnComplete<Iterable<Object>> onComplete = new OnComplete<Iterable<Object>>() {
237 public void onComplete(Throwable failure, Iterable<Object> notUsed)
239 if(failure != null) {
240 LOG.debug("Tx {} readData: a recorded operation failed: {}",
241 identifier, failure);
242 returnFuture.setException(new ReadFailedException(
243 "The read could not be performed because a previous put, merge,"
244 + "or delete operation failed", failure));
246 finishReadData(path, returnFuture);
251 combinedFutures.onComplete(onComplete, actorContext.getClientDispatcher());
256 private void finishReadData(final YangInstanceIdentifier path,
257 final SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture) {
259 LOG.debug("Tx {} finishReadData called path = {}", identifier, path);
261 OnComplete<Object> onComplete = new OnComplete<Object>() {
263 public void onComplete(Throwable failure, Object readResponse) throws Throwable {
264 if(failure != null) {
265 LOG.debug("Tx {} read operation failed: {}", identifier, failure);
266 returnFuture.setException(new ReadFailedException(
267 "Error reading data for path " + path, failure));
270 LOG.debug("Tx {} read operation succeeded", identifier, failure);
272 if (readResponse instanceof ReadDataReply) {
273 ReadDataReply reply = (ReadDataReply) readResponse;
274 returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
276 } else if (ReadDataReply.isSerializedType(readResponse)) {
277 ReadDataReply reply = ReadDataReply.fromSerializable(readResponse);
278 returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
281 returnFuture.setException(new ReadFailedException(
282 "Invalid response reading data for path " + path));
288 Future<Object> readFuture = executeOperationAsync(new ReadData(path));
290 readFuture.onComplete(onComplete, actorContext.getClientDispatcher());
294 public void dataExists(final YangInstanceIdentifier path, final SettableFuture<Boolean> returnFuture) {
296 LOG.debug("Tx {} dataExists called path = {}", identifier, path);
298 // Send the remaining batched modifications if any.
300 sendBatchedModifications();
302 // If there were any previous recorded put/merge/delete operation reply Futures then we
303 // must wait for them to successfully complete. This is necessary to honor the read
304 // uncommitted semantics of the public API contract. If any one fails then fail this
307 if(recordedOperationFutures.isEmpty()) {
308 finishDataExists(path, returnFuture);
310 LOG.debug("Tx {} dataExists: verifying {} previous recorded operations",
311 identifier, recordedOperationFutures.size());
313 // Note: we make a copy of recordedOperationFutures to be on the safe side in case
314 // Futures#sequence accesses the passed List on a different thread, as
315 // recordedOperationFutures is not synchronized.
317 Future<Iterable<Object>> combinedFutures = akka.dispatch.Futures.sequence(
318 Lists.newArrayList(recordedOperationFutures),
319 actorContext.getClientDispatcher());
320 OnComplete<Iterable<Object>> onComplete = new OnComplete<Iterable<Object>>() {
322 public void onComplete(Throwable failure, Iterable<Object> notUsed)
324 if(failure != null) {
325 LOG.debug("Tx {} dataExists: a recorded operation failed: {}",
326 identifier, failure);
327 returnFuture.setException(new ReadFailedException(
328 "The data exists could not be performed because a previous "
329 + "put, merge, or delete operation failed", failure));
331 finishDataExists(path, returnFuture);
336 combinedFutures.onComplete(onComplete, actorContext.getClientDispatcher());
340 private void finishDataExists(final YangInstanceIdentifier path,
341 final SettableFuture<Boolean> returnFuture) {
343 LOG.debug("Tx {} finishDataExists called path = {}", identifier, path);
345 OnComplete<Object> onComplete = new OnComplete<Object>() {
347 public void onComplete(Throwable failure, Object response) throws Throwable {
348 if(failure != null) {
349 LOG.debug("Tx {} dataExists operation failed: {}", identifier, failure);
350 returnFuture.setException(new ReadFailedException(
351 "Error checking data exists for path " + path, failure));
353 LOG.debug("Tx {} dataExists operation succeeded", identifier, failure);
355 if (response instanceof DataExistsReply) {
356 returnFuture.set(Boolean.valueOf(((DataExistsReply) response).exists()));
358 } else if (response.getClass().equals(DataExistsReply.SERIALIZABLE_CLASS)) {
359 returnFuture.set(Boolean.valueOf(DataExistsReply.fromSerializable(response).exists()));
362 returnFuture.setException(new ReadFailedException(
363 "Invalid response checking exists for path " + path));
369 Future<Object> future = executeOperationAsync(new DataExists(path));
371 future.onComplete(onComplete, actorContext.getClientDispatcher());