2 * Copyright (c) 2014 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
9 package org.opendaylight.controller.cluster.datastore;
11 import akka.actor.ActorSelection;
12 import akka.dispatch.Mapper;
13 import akka.dispatch.OnComplete;
14 import com.google.common.annotations.VisibleForTesting;
15 import com.google.common.base.FinalizablePhantomReference;
16 import com.google.common.base.FinalizableReferenceQueue;
17 import com.google.common.base.Optional;
18 import com.google.common.base.Preconditions;
19 import com.google.common.collect.Lists;
20 import com.google.common.util.concurrent.CheckedFuture;
21 import com.google.common.util.concurrent.FutureCallback;
22 import com.google.common.util.concurrent.Futures;
23 import com.google.common.util.concurrent.SettableFuture;
24 import java.util.HashMap;
25 import java.util.List;
27 import java.util.concurrent.ConcurrentHashMap;
28 import java.util.concurrent.TimeUnit;
29 import java.util.concurrent.atomic.AtomicBoolean;
30 import java.util.concurrent.atomic.AtomicLong;
31 import javax.annotation.concurrent.GuardedBy;
32 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
33 import org.opendaylight.controller.cluster.datastore.identifiers.TransactionIdentifier;
34 import org.opendaylight.controller.cluster.datastore.messages.CloseTransaction;
35 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
36 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
37 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
38 import org.opendaylight.controller.cluster.datastore.messages.DataExistsReply;
39 import org.opendaylight.controller.cluster.datastore.messages.DeleteData;
40 import org.opendaylight.controller.cluster.datastore.messages.MergeData;
41 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
42 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
43 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransaction;
44 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
45 import org.opendaylight.controller.cluster.datastore.messages.SerializableMessage;
46 import org.opendaylight.controller.cluster.datastore.messages.WriteData;
47 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
48 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
49 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
50 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
51 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
52 import org.opendaylight.yangtools.util.concurrent.MappingCheckedFuture;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
54 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
55 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58 import scala.concurrent.Future;
59 import scala.concurrent.Promise;
60 import scala.concurrent.duration.FiniteDuration;
63 * TransactionProxy acts as a proxy for one or more transactions that were created on a remote shard
65 * Creating a transaction on the consumer side will create one instance of a transaction proxy. If during
66 * the transaction reads and writes are done on data that belongs to different shards then a separate transaction will
67 * be created on each of those shards by the TransactionProxy
70 * The TransactionProxy does not make any guarantees about atomicity or order in which the transactions on the various
71 * shards will be executed.
74 public class TransactionProxy implements DOMStoreReadWriteTransaction {
76 public static enum TransactionType {
82 static final Mapper<Throwable, Throwable> SAME_FAILURE_TRANSFORMER =
83 new Mapper<Throwable, Throwable>() {
85 public Throwable apply(Throwable failure) {
90 private static final AtomicLong counter = new AtomicLong();
92 private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
95 * Time interval in between transaction create retries.
97 private static final FiniteDuration CREATE_TX_TRY_INTERVAL =
98 FiniteDuration.create(1, TimeUnit.SECONDS);
101 * Used to enqueue the PhantomReferences for read-only TransactionProxy instances. The
102 * FinalizableReferenceQueue is safe to use statically in an OSGi environment as it uses some
103 * trickery to clean up its internal thread when the bundle is unloaded.
105 private static final FinalizableReferenceQueue phantomReferenceQueue =
106 new FinalizableReferenceQueue();
109 * This stores the TransactionProxyCleanupPhantomReference instances statically, This is
110 * necessary because PhantomReferences need a hard reference so they're not garbage collected.
111 * Once finalized, the TransactionProxyCleanupPhantomReference removes itself from this map
112 * and thus becomes eligible for garbage collection.
114 private static final Map<TransactionProxyCleanupPhantomReference,
115 TransactionProxyCleanupPhantomReference> phantomReferenceCache =
116 new ConcurrentHashMap<>();
119 * A PhantomReference that closes remote transactions for a TransactionProxy when it's
120 * garbage collected. This is used for read-only transactions as they're not explicitly closed
121 * by clients. So the only way to detect that a transaction is no longer in use and it's safe
122 * to clean up is when it's garbage collected. It's inexact as to when an instance will be GC'ed
123 * but TransactionProxy instances should generally be short-lived enough to avoid being moved
124 * to the old generation space and thus should be cleaned up in a timely manner as the GC
125 * runs on the young generation (eden, swap1...) space much more frequently.
127 private static class TransactionProxyCleanupPhantomReference
128 extends FinalizablePhantomReference<TransactionProxy> {
130 private final List<ActorSelection> remoteTransactionActors;
131 private final AtomicBoolean remoteTransactionActorsMB;
132 private final ActorContext actorContext;
133 private final TransactionIdentifier identifier;
135 protected TransactionProxyCleanupPhantomReference(TransactionProxy referent) {
136 super(referent, phantomReferenceQueue);
138 // Note we need to cache the relevant fields from the TransactionProxy as we can't
139 // have a hard reference to the TransactionProxy instance itself.
141 remoteTransactionActors = referent.remoteTransactionActors;
142 remoteTransactionActorsMB = referent.remoteTransactionActorsMB;
143 actorContext = referent.actorContext;
144 identifier = referent.identifier;
148 public void finalizeReferent() {
149 LOG.trace("Cleaning up {} Tx actors for TransactionProxy {}",
150 remoteTransactionActors.size(), identifier);
152 phantomReferenceCache.remove(this);
154 // Access the memory barrier volatile to ensure all previous updates to the
155 // remoteTransactionActors list are visible to this thread.
157 if(remoteTransactionActorsMB.get()) {
158 for(ActorSelection actor : remoteTransactionActors) {
159 LOG.trace("Sending CloseTransaction to {}", actor);
160 actorContext.sendOperationAsync(actor,
161 new CloseTransaction().toSerializable());
168 * Stores the remote Tx actors for each requested data store path to be used by the
169 * PhantomReference to close the remote Tx's. This is only used for read-only Tx's. The
170 * remoteTransactionActorsMB volatile serves as a memory barrier to publish updates to the
171 * remoteTransactionActors list so they will be visible to the thread accessing the
174 private List<ActorSelection> remoteTransactionActors;
175 private AtomicBoolean remoteTransactionActorsMB;
178 * Stores the create transaction results per shard.
180 private final Map<String, TransactionFutureCallback> txFutureCallbackMap = new HashMap<>();
182 private final TransactionType transactionType;
183 private final ActorContext actorContext;
184 private final TransactionIdentifier identifier;
185 private final String transactionChainId;
186 private final SchemaContext schemaContext;
187 private boolean inReadyState;
189 public TransactionProxy(ActorContext actorContext, TransactionType transactionType) {
190 this(actorContext, transactionType, "");
193 public TransactionProxy(ActorContext actorContext, TransactionType transactionType,
194 String transactionChainId) {
195 this.actorContext = Preconditions.checkNotNull(actorContext,
196 "actorContext should not be null");
197 this.transactionType = Preconditions.checkNotNull(transactionType,
198 "transactionType should not be null");
199 this.schemaContext = Preconditions.checkNotNull(actorContext.getSchemaContext(),
200 "schemaContext should not be null");
201 this.transactionChainId = transactionChainId;
203 String memberName = actorContext.getCurrentMemberName();
204 if(memberName == null){
205 memberName = "UNKNOWN-MEMBER";
208 this.identifier = TransactionIdentifier.builder().memberName(memberName).counter(
209 counter.getAndIncrement()).build();
211 if(transactionType == TransactionType.READ_ONLY) {
212 // Read-only Tx's aren't explicitly closed by the client so we create a PhantomReference
213 // to close the remote Tx's when this instance is no longer in use and is garbage
216 remoteTransactionActors = Lists.newArrayList();
217 remoteTransactionActorsMB = new AtomicBoolean();
219 TransactionProxyCleanupPhantomReference cleanup =
220 new TransactionProxyCleanupPhantomReference(this);
221 phantomReferenceCache.put(cleanup, cleanup);
224 LOG.debug("Created txn {} of type {} on chain {}", identifier, transactionType, transactionChainId);
228 List<Future<Object>> getRecordedOperationFutures() {
229 List<Future<Object>> recordedOperationFutures = Lists.newArrayList();
230 for(TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) {
231 TransactionContext transactionContext = txFutureCallback.getTransactionContext();
232 if(transactionContext != null) {
233 recordedOperationFutures.addAll(transactionContext.getRecordedOperationFutures());
237 return recordedOperationFutures;
241 boolean hasTransactionContext() {
242 for(TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) {
243 TransactionContext transactionContext = txFutureCallback.getTransactionContext();
244 if(transactionContext != null) {
253 public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final YangInstanceIdentifier path) {
255 Preconditions.checkState(transactionType != TransactionType.WRITE_ONLY,
256 "Read operation on write-only transaction is not allowed");
258 LOG.debug("Tx {} read {}", identifier, path);
260 TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
261 return txFutureCallback.enqueueReadOperation(new ReadOperation<Optional<NormalizedNode<?, ?>>>() {
263 public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> invoke(
264 TransactionContext transactionContext) {
265 return transactionContext.readData(path);
271 public CheckedFuture<Boolean, ReadFailedException> exists(final YangInstanceIdentifier path) {
273 Preconditions.checkState(transactionType != TransactionType.WRITE_ONLY,
274 "Exists operation on write-only transaction is not allowed");
276 LOG.debug("Tx {} exists {}", identifier, path);
278 TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
279 return txFutureCallback.enqueueReadOperation(new ReadOperation<Boolean>() {
281 public CheckedFuture<Boolean, ReadFailedException> invoke(TransactionContext transactionContext) {
282 return transactionContext.dataExists(path);
288 private void checkModificationState() {
289 Preconditions.checkState(transactionType != TransactionType.READ_ONLY,
290 "Modification operation on read-only transaction is not allowed");
291 Preconditions.checkState(!inReadyState,
292 "Transaction is sealed - further modifications are not allowed");
296 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
298 checkModificationState();
300 LOG.debug("Tx {} write {}", identifier, path);
302 TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
303 txFutureCallback.enqueueModifyOperation(new TransactionOperation() {
305 public void invoke(TransactionContext transactionContext) {
306 transactionContext.writeData(path, data);
312 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
314 checkModificationState();
316 LOG.debug("Tx {} merge {}", identifier, path);
318 TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
319 txFutureCallback.enqueueModifyOperation(new TransactionOperation() {
321 public void invoke(TransactionContext transactionContext) {
322 transactionContext.mergeData(path, data);
328 public void delete(final YangInstanceIdentifier path) {
330 checkModificationState();
332 LOG.debug("Tx {} delete {}", identifier, path);
334 TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
335 txFutureCallback.enqueueModifyOperation(new TransactionOperation() {
337 public void invoke(TransactionContext transactionContext) {
338 transactionContext.deleteData(path);
344 public DOMStoreThreePhaseCommitCohort ready() {
346 checkModificationState();
350 LOG.debug("Tx {} Readying {} transactions for commit", identifier,
351 txFutureCallbackMap.size());
353 List<Future<ActorSelection>> cohortFutures = Lists.newArrayList();
355 for(TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) {
357 LOG.debug("Tx {} Readying transaction for shard {} chain {}", identifier,
358 txFutureCallback.getShardName(), transactionChainId);
360 Future<ActorSelection> future = txFutureCallback.enqueueFutureOperation(new FutureOperation<ActorSelection>() {
362 public Future<ActorSelection> invoke(TransactionContext transactionContext) {
363 return transactionContext.readyTransaction();
367 cohortFutures.add(future);
370 onTransactionReady(cohortFutures);
372 return new ThreePhaseCommitCohortProxy(actorContext, cohortFutures,
373 identifier.toString());
377 * Method for derived classes to be notified when the transaction has been readied.
379 * @param cohortFutures the cohort Futures for each shard transaction.
381 protected void onTransactionReady(List<Future<ActorSelection>> cohortFutures) {
385 * Method called to send a CreateTransaction message to a shard.
387 * @param shard the shard actor to send to
388 * @param serializedCreateMessage the serialized message to send
389 * @return the response Future
391 protected Future<Object> sendCreateTransaction(ActorSelection shard,
392 Object serializedCreateMessage) {
393 return actorContext.executeOperationAsync(shard, serializedCreateMessage);
397 public Object getIdentifier() {
398 return this.identifier;
402 public void close() {
403 for (TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) {
404 txFutureCallback.enqueueModifyOperation(new TransactionOperation() {
406 public void invoke(TransactionContext transactionContext) {
407 transactionContext.closeTransaction();
412 txFutureCallbackMap.clear();
414 if(transactionType == TransactionType.READ_ONLY) {
415 remoteTransactionActors.clear();
416 remoteTransactionActorsMB.set(true);
420 private String shardNameFromIdentifier(YangInstanceIdentifier path){
421 return ShardStrategyFactory.getStrategy(path).findShard(path);
424 private TransactionFutureCallback getOrCreateTxFutureCallback(YangInstanceIdentifier path) {
425 String shardName = shardNameFromIdentifier(path);
426 TransactionFutureCallback txFutureCallback = txFutureCallbackMap.get(shardName);
427 if(txFutureCallback == null) {
428 Future<ActorSelection> findPrimaryFuture = actorContext.findPrimaryShardAsync(shardName);
430 final TransactionFutureCallback newTxFutureCallback =
431 new TransactionFutureCallback(shardName);
433 txFutureCallback = newTxFutureCallback;
434 txFutureCallbackMap.put(shardName, txFutureCallback);
436 findPrimaryFuture.onComplete(new OnComplete<ActorSelection>() {
438 public void onComplete(Throwable failure, ActorSelection primaryShard) {
439 if(failure != null) {
440 newTxFutureCallback.onComplete(failure, null);
442 newTxFutureCallback.setPrimaryShard(primaryShard);
445 }, actorContext.getActorSystem().dispatcher());
448 return txFutureCallback;
451 public String getTransactionChainId() {
452 return transactionChainId;
455 protected ActorContext getActorContext() {
460 * Interfaces for transaction operations to be invoked later.
462 private static interface TransactionOperation {
463 void invoke(TransactionContext transactionContext);
467 * This interface returns a Guava Future
469 private static interface ReadOperation<T> {
470 CheckedFuture<T, ReadFailedException> invoke(TransactionContext transactionContext);
474 * This interface returns a Scala Future
476 private static interface FutureOperation<T> {
477 Future<T> invoke(TransactionContext transactionContext);
481 * Implements a Future OnComplete callback for a CreateTransaction message. This class handles
482 * retries, up to a limit, if the shard doesn't have a leader yet. This is done by scheduling a
483 * retry task after a short delay.
485 * The end result from a completed CreateTransaction message is a TransactionContext that is
486 * used to perform transaction operations. Transaction operations that occur before the
487 * CreateTransaction completes are cache and executed once the CreateTransaction completes,
488 * successfully or not.
490 private class TransactionFutureCallback extends OnComplete<Object> {
493 * The list of transaction operations to execute once the CreateTransaction completes.
495 @GuardedBy("txOperationsOnComplete")
496 private final List<TransactionOperation> txOperationsOnComplete = Lists.newArrayList();
499 * The TransactionContext resulting from the CreateTransaction reply.
501 private volatile TransactionContext transactionContext;
504 * The target primary shard.
506 private volatile ActorSelection primaryShard;
508 private volatile int createTxTries = (int) (actorContext.getDatastoreContext().
509 getShardLeaderElectionTimeout().duration().toMillis() /
510 CREATE_TX_TRY_INTERVAL.toMillis());
512 private final String shardName;
514 TransactionFutureCallback(String shardName) {
515 this.shardName = shardName;
518 String getShardName() {
522 TransactionContext getTransactionContext() {
523 return transactionContext;
528 * Sets the target primary shard and initiates a CreateTransaction try.
530 void setPrimaryShard(ActorSelection primaryShard) {
531 LOG.debug("Tx {} Primary shard found - trying create transaction", identifier);
533 this.primaryShard = primaryShard;
534 tryCreateTransaction();
538 * Adds a TransactionOperation to be executed after the CreateTransaction completes.
540 void addTxOperationOnComplete(TransactionOperation operation) {
541 synchronized(txOperationsOnComplete) {
542 if(transactionContext == null) {
543 LOG.debug("Tx {} Adding operation on complete {}", identifier);
545 txOperationsOnComplete.add(operation);
547 operation.invoke(transactionContext);
553 <T> Future<T> enqueueFutureOperation(final FutureOperation<T> op) {
557 if (transactionContext != null) {
558 future = op.invoke(transactionContext);
560 // The shard Tx hasn't been created yet so add the Tx operation to the Tx Future
561 // callback to be executed after the Tx is created.
562 final Promise<T> promise = akka.dispatch.Futures.promise();
563 addTxOperationOnComplete(new TransactionOperation() {
565 public void invoke(TransactionContext transactionContext) {
566 promise.completeWith(op.invoke(transactionContext));
570 future = promise.future();
576 <T> CheckedFuture<T, ReadFailedException> enqueueReadOperation(final ReadOperation<T> op) {
578 CheckedFuture<T, ReadFailedException> future;
580 if (transactionContext != null) {
581 future = op.invoke(transactionContext);
583 // The shard Tx hasn't been created yet so add the Tx operation to the Tx Future
584 // callback to be executed after the Tx is created.
585 final SettableFuture<T> proxyFuture = SettableFuture.create();
586 addTxOperationOnComplete(new TransactionOperation() {
588 public void invoke(TransactionContext transactionContext) {
589 Futures.addCallback(op.invoke(transactionContext), new FutureCallback<T>() {
591 public void onSuccess(T data) {
592 proxyFuture.set(data);
596 public void onFailure(Throwable t) {
597 proxyFuture.setException(t);
603 future = MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
609 void enqueueModifyOperation(final TransactionOperation op) {
611 if (transactionContext != null) {
612 op.invoke(transactionContext);
614 // The shard Tx hasn't been created yet so add the Tx operation to the Tx Future
615 // callback to be executed after the Tx is created.
616 addTxOperationOnComplete(op);
625 * Performs a CreateTransaction try async.
627 private void tryCreateTransaction() {
628 Future<Object> createTxFuture = sendCreateTransaction(primaryShard,
629 new CreateTransaction(identifier.toString(),
630 TransactionProxy.this.transactionType.ordinal(),
631 getTransactionChainId()).toSerializable());
633 createTxFuture.onComplete(this, actorContext.getActorSystem().dispatcher());
637 public void onComplete(Throwable failure, Object response) {
638 if(failure instanceof NoShardLeaderException) {
639 // There's no leader for the shard yet - schedule and try again, unless we're out
640 // of retries. Note: createTxTries is volatile as it may be written by different
641 // threads however not concurrently, therefore decrementing it non-atomically here
643 if(--createTxTries > 0) {
644 LOG.debug("Tx {} Shard {} has no leader yet - scheduling create Tx retry",
645 identifier, shardName);
647 actorContext.getActorSystem().scheduler().scheduleOnce(CREATE_TX_TRY_INTERVAL,
651 tryCreateTransaction();
653 }, actorContext.getActorSystem().dispatcher());
658 // Create the TransactionContext from the response or failure and execute delayed
659 // TransactionOperations. This entire section is done atomically (ie synchronized) with
660 // respect to #addTxOperationOnComplete to handle timing issues and ensure no
661 // TransactionOperation is missed and that they are processed in the order they occurred.
662 synchronized(txOperationsOnComplete) {
663 // Store the new TransactionContext locally until we've completed invoking the
664 // TransactionOperations. This avoids thread timing issues which could cause
665 // out-of-order TransactionOperations. Eg, on a modification operation, if the
666 // TransactionContext is non-null, then we directly call the TransactionContext.
667 // However, at the same time, the code may be executing the cached
668 // TransactionOperations. So to avoid thus timing, we don't publish the
669 // TransactionContext until after we've executed all cached TransactionOperations.
670 TransactionContext localTransactionContext;
671 if(failure != null) {
672 LOG.debug("Tx {} Creating NoOpTransaction because of error: {}", identifier,
673 failure.getMessage());
675 localTransactionContext = new NoOpTransactionContext(failure, identifier);
676 } else if (response.getClass().equals(CreateTransactionReply.SERIALIZABLE_CLASS)) {
677 localTransactionContext = createValidTransactionContext(
678 CreateTransactionReply.fromSerializable(response));
680 IllegalArgumentException exception = new IllegalArgumentException(String.format(
681 "Invalid reply type %s for CreateTransaction", response.getClass()));
683 localTransactionContext = new NoOpTransactionContext(exception, identifier);
686 for(TransactionOperation oper: txOperationsOnComplete) {
687 oper.invoke(localTransactionContext);
690 txOperationsOnComplete.clear();
692 // We're done invoking the TransactionOperations so we can now publish the
693 // TransactionContext.
694 transactionContext = localTransactionContext;
698 private TransactionContext createValidTransactionContext(CreateTransactionReply reply) {
699 String transactionPath = reply.getTransactionPath();
701 LOG.debug("Tx {} Received transaction actor path {}", identifier, transactionPath);
703 ActorSelection transactionActor = actorContext.actorSelection(transactionPath);
705 if (transactionType == TransactionType.READ_ONLY) {
706 // Add the actor to the remoteTransactionActors list for access by the
707 // cleanup PhantonReference.
708 remoteTransactionActors.add(transactionActor);
710 // Write to the memory barrier volatile to publish the above update to the
711 // remoteTransactionActors list for thread visibility.
712 remoteTransactionActorsMB.set(true);
715 // TxActor is always created where the leader of the shard is.
716 // Check if TxActor is created in the same node
717 boolean isTxActorLocal = actorContext.isPathLocal(transactionPath);
719 return new TransactionContextImpl(transactionPath, transactionActor, identifier,
720 actorContext, schemaContext, isTxActorLocal, reply.getVersion());
724 private interface TransactionContext {
725 void closeTransaction();
727 Future<ActorSelection> readyTransaction();
729 void writeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data);
731 void deleteData(YangInstanceIdentifier path);
733 void mergeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data);
735 CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readData(
736 final YangInstanceIdentifier path);
738 CheckedFuture<Boolean, ReadFailedException> dataExists(YangInstanceIdentifier path);
740 List<Future<Object>> getRecordedOperationFutures();
743 private static abstract class AbstractTransactionContext implements TransactionContext {
745 protected final TransactionIdentifier identifier;
746 protected final List<Future<Object>> recordedOperationFutures = Lists.newArrayList();
748 AbstractTransactionContext(TransactionIdentifier identifier) {
749 this.identifier = identifier;
753 public List<Future<Object>> getRecordedOperationFutures() {
754 return recordedOperationFutures;
758 private static class TransactionContextImpl extends AbstractTransactionContext {
759 private final Logger LOG = LoggerFactory.getLogger(TransactionContextImpl.class);
761 private final ActorContext actorContext;
762 private final SchemaContext schemaContext;
763 private final String transactionPath;
764 private final ActorSelection actor;
765 private final boolean isTxActorLocal;
766 private final int remoteTransactionVersion;
768 private TransactionContextImpl(String transactionPath, ActorSelection actor, TransactionIdentifier identifier,
769 ActorContext actorContext, SchemaContext schemaContext,
770 boolean isTxActorLocal, int remoteTransactionVersion) {
772 this.transactionPath = transactionPath;
774 this.actorContext = actorContext;
775 this.schemaContext = schemaContext;
776 this.isTxActorLocal = isTxActorLocal;
777 this.remoteTransactionVersion = remoteTransactionVersion;
780 private ActorSelection getActor() {
784 private Future<Object> executeOperationAsync(SerializableMessage msg) {
785 return actorContext.executeOperationAsync(getActor(), isTxActorLocal ? msg : msg.toSerializable());
789 public void closeTransaction() {
790 LOG.debug("Tx {} closeTransaction called", identifier);
792 actorContext.sendOperationAsync(getActor(), new CloseTransaction().toSerializable());
796 public Future<ActorSelection> readyTransaction() {
797 LOG.debug("Tx {} readyTransaction called with {} previous recorded operations pending",
798 identifier, recordedOperationFutures.size());
800 // Send the ReadyTransaction message to the Tx actor.
802 final Future<Object> replyFuture = executeOperationAsync(new ReadyTransaction());
804 // Combine all the previously recorded put/merge/delete operation reply Futures and the
805 // ReadyTransactionReply Future into one Future. If any one fails then the combined
806 // Future will fail. We need all prior operations and the ready operation to succeed
807 // in order to attempt commit.
809 List<Future<Object>> futureList =
810 Lists.newArrayListWithCapacity(recordedOperationFutures.size() + 1);
811 futureList.addAll(recordedOperationFutures);
812 futureList.add(replyFuture);
814 Future<Iterable<Object>> combinedFutures = akka.dispatch.Futures.sequence(futureList,
815 actorContext.getActorSystem().dispatcher());
817 // Transform the combined Future into a Future that returns the cohort actor path from
818 // the ReadyTransactionReply. That's the end result of the ready operation.
820 return combinedFutures.transform(new Mapper<Iterable<Object>, ActorSelection>() {
822 public ActorSelection checkedApply(Iterable<Object> notUsed) {
823 LOG.debug("Tx {} readyTransaction: pending recorded operations succeeded",
826 // At this point all the Futures succeeded and we need to extract the cohort
827 // actor path from the ReadyTransactionReply. For the recorded operations, they
828 // don't return any data so we're only interested that they completed
829 // successfully. We could be paranoid and verify the correct reply types but
830 // that really should never happen so it's not worth the overhead of
831 // de-serializing each reply.
833 // Note the Future get call here won't block as it's complete.
834 Object serializedReadyReply = replyFuture.value().get().get();
835 if (serializedReadyReply instanceof ReadyTransactionReply) {
836 return actorContext.actorSelection(((ReadyTransactionReply)serializedReadyReply).getCohortPath());
838 } else if(serializedReadyReply.getClass().equals(ReadyTransactionReply.SERIALIZABLE_CLASS)) {
839 ReadyTransactionReply reply = ReadyTransactionReply.fromSerializable(serializedReadyReply);
840 String cohortPath = reply.getCohortPath();
842 // In Helium we used to return the local path of the actor which represented
843 // a remote ThreePhaseCommitCohort. The local path would then be converted to
844 // a remote path using this resolvePath method. To maintain compatibility with
845 // a Helium node we need to continue to do this conversion.
846 // At some point in the future when upgrades from Helium are not supported
847 // we could remove this code to resolvePath and just use the cohortPath as the
848 // resolved cohortPath
849 if(TransactionContextImpl.this.remoteTransactionVersion < CreateTransaction.HELIUM_1_VERSION) {
850 cohortPath = actorContext.resolvePath(transactionPath, cohortPath);
853 return actorContext.actorSelection(cohortPath);
856 // Throwing an exception here will fail the Future.
857 throw new IllegalArgumentException(String.format("Invalid reply type {}",
858 serializedReadyReply.getClass()));
861 }, SAME_FAILURE_TRANSFORMER, actorContext.getActorSystem().dispatcher());
865 public void deleteData(YangInstanceIdentifier path) {
866 LOG.debug("Tx {} deleteData called path = {}", identifier, path);
868 recordedOperationFutures.add(executeOperationAsync(new DeleteData(path)));
872 public void mergeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
873 LOG.debug("Tx {} mergeData called path = {}", identifier, path);
875 recordedOperationFutures.add(executeOperationAsync(new MergeData(path, data, schemaContext)));
879 public void writeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
880 LOG.debug("Tx {} writeData called path = {}", identifier, path);
882 recordedOperationFutures.add(executeOperationAsync(new WriteData(path, data, schemaContext)));
886 public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readData(
887 final YangInstanceIdentifier path) {
889 LOG.debug("Tx {} readData called path = {}", identifier, path);
891 final SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture = SettableFuture.create();
893 // If there were any previous recorded put/merge/delete operation reply Futures then we
894 // must wait for them to successfully complete. This is necessary to honor the read
895 // uncommitted semantics of the public API contract. If any one fails then fail the read.
897 if(recordedOperationFutures.isEmpty()) {
898 finishReadData(path, returnFuture);
900 LOG.debug("Tx {} readData: verifying {} previous recorded operations",
901 identifier, recordedOperationFutures.size());
903 // Note: we make a copy of recordedOperationFutures to be on the safe side in case
904 // Futures#sequence accesses the passed List on a different thread, as
905 // recordedOperationFutures is not synchronized.
907 Future<Iterable<Object>> combinedFutures = akka.dispatch.Futures.sequence(
908 Lists.newArrayList(recordedOperationFutures),
909 actorContext.getActorSystem().dispatcher());
911 OnComplete<Iterable<Object>> onComplete = new OnComplete<Iterable<Object>>() {
913 public void onComplete(Throwable failure, Iterable<Object> notUsed)
915 if(failure != null) {
916 LOG.debug("Tx {} readData: a recorded operation failed: {}",
917 identifier, failure);
918 returnFuture.setException(new ReadFailedException(
919 "The read could not be performed because a previous put, merge,"
920 + "or delete operation failed", failure));
922 finishReadData(path, returnFuture);
927 combinedFutures.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
930 return MappingCheckedFuture.create(returnFuture, ReadFailedException.MAPPER);
933 private void finishReadData(final YangInstanceIdentifier path,
934 final SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture) {
936 LOG.debug("Tx {} finishReadData called path = {}", identifier, path);
938 OnComplete<Object> onComplete = new OnComplete<Object>() {
940 public void onComplete(Throwable failure, Object readResponse) throws Throwable {
941 if(failure != null) {
942 LOG.debug("Tx {} read operation failed: {}", identifier, failure);
943 returnFuture.setException(new ReadFailedException(
944 "Error reading data for path " + path, failure));
947 LOG.debug("Tx {} read operation succeeded", identifier, failure);
949 if (readResponse instanceof ReadDataReply) {
950 ReadDataReply reply = (ReadDataReply) readResponse;
951 returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
953 } else if (readResponse.getClass().equals(ReadDataReply.SERIALIZABLE_CLASS)) {
954 ReadDataReply reply = ReadDataReply.fromSerializable(schemaContext, path, readResponse);
955 returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
958 returnFuture.setException(new ReadFailedException(
959 "Invalid response reading data for path " + path));
965 Future<Object> readFuture = executeOperationAsync(new ReadData(path));
967 readFuture.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
971 public CheckedFuture<Boolean, ReadFailedException> dataExists(
972 final YangInstanceIdentifier path) {
974 LOG.debug("Tx {} dataExists called path = {}", identifier, path);
976 final SettableFuture<Boolean> returnFuture = SettableFuture.create();
978 // If there were any previous recorded put/merge/delete operation reply Futures then we
979 // must wait for them to successfully complete. This is necessary to honor the read
980 // uncommitted semantics of the public API contract. If any one fails then fail this
983 if(recordedOperationFutures.isEmpty()) {
984 finishDataExists(path, returnFuture);
986 LOG.debug("Tx {} dataExists: verifying {} previous recorded operations",
987 identifier, recordedOperationFutures.size());
989 // Note: we make a copy of recordedOperationFutures to be on the safe side in case
990 // Futures#sequence accesses the passed List on a different thread, as
991 // recordedOperationFutures is not synchronized.
993 Future<Iterable<Object>> combinedFutures = akka.dispatch.Futures.sequence(
994 Lists.newArrayList(recordedOperationFutures),
995 actorContext.getActorSystem().dispatcher());
996 OnComplete<Iterable<Object>> onComplete = new OnComplete<Iterable<Object>>() {
998 public void onComplete(Throwable failure, Iterable<Object> notUsed)
1000 if(failure != null) {
1001 LOG.debug("Tx {} dataExists: a recorded operation failed: {}",
1002 identifier, failure);
1003 returnFuture.setException(new ReadFailedException(
1004 "The data exists could not be performed because a previous "
1005 + "put, merge, or delete operation failed", failure));
1007 finishDataExists(path, returnFuture);
1012 combinedFutures.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
1015 return MappingCheckedFuture.create(returnFuture, ReadFailedException.MAPPER);
1018 private void finishDataExists(final YangInstanceIdentifier path,
1019 final SettableFuture<Boolean> returnFuture) {
1021 LOG.debug("Tx {} finishDataExists called path = {}", identifier, path);
1023 OnComplete<Object> onComplete = new OnComplete<Object>() {
1025 public void onComplete(Throwable failure, Object response) throws Throwable {
1026 if(failure != null) {
1027 LOG.debug("Tx {} dataExists operation failed: {}", identifier, failure);
1028 returnFuture.setException(new ReadFailedException(
1029 "Error checking data exists for path " + path, failure));
1031 LOG.debug("Tx {} dataExists operation succeeded", identifier, failure);
1033 if (response instanceof DataExistsReply) {
1034 returnFuture.set(Boolean.valueOf(((DataExistsReply) response).exists()));
1036 } else if (response.getClass().equals(DataExistsReply.SERIALIZABLE_CLASS)) {
1037 returnFuture.set(Boolean.valueOf(DataExistsReply.fromSerializable(response).exists()));
1040 returnFuture.setException(new ReadFailedException(
1041 "Invalid response checking exists for path " + path));
1047 Future<Object> future = executeOperationAsync(new DataExists(path));
1049 future.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
1053 private static class NoOpTransactionContext extends AbstractTransactionContext {
1055 private final Logger LOG = LoggerFactory.getLogger(NoOpTransactionContext.class);
1057 private final Throwable failure;
1059 public NoOpTransactionContext(Throwable failure, TransactionIdentifier identifier){
1061 this.failure = failure;
1065 public void closeTransaction() {
1066 LOG.debug("NoOpTransactionContext {} closeTransaction called", identifier);
1070 public Future<ActorSelection> readyTransaction() {
1071 LOG.debug("Tx {} readyTransaction called", identifier);
1072 return akka.dispatch.Futures.failed(failure);
1076 public void deleteData(YangInstanceIdentifier path) {
1077 LOG.debug("Tx {} deleteData called path = {}", identifier, path);
1081 public void mergeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
1082 LOG.debug("Tx {} mergeData called path = {}", identifier, path);
1086 public void writeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
1087 LOG.debug("Tx {} writeData called path = {}", identifier, path);
1091 public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readData(
1092 YangInstanceIdentifier path) {
1093 LOG.debug("Tx {} readData called path = {}", identifier, path);
1094 return Futures.immediateFailedCheckedFuture(new ReadFailedException(
1095 "Error reading data for path " + path, failure));
1099 public CheckedFuture<Boolean, ReadFailedException> dataExists(
1100 YangInstanceIdentifier path) {
1101 LOG.debug("Tx {} dataExists called path = {}", identifier, path);
1102 return Futures.immediateFailedCheckedFuture(new ReadFailedException(
1103 "Error checking exists for path " + path, failure));