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.WriteData;
46 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
47 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
48 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
49 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
50 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
51 import org.opendaylight.yangtools.util.concurrent.MappingCheckedFuture;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
53 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
54 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57 import scala.concurrent.Future;
58 import scala.concurrent.Promise;
59 import scala.concurrent.duration.FiniteDuration;
62 * TransactionProxy acts as a proxy for one or more transactions that were created on a remote shard
64 * Creating a transaction on the consumer side will create one instance of a transaction proxy. If during
65 * the transaction reads and writes are done on data that belongs to different shards then a separate transaction will
66 * be created on each of those shards by the TransactionProxy
69 * The TransactionProxy does not make any guarantees about atomicity or order in which the transactions on the various
70 * shards will be executed.
73 public class TransactionProxy implements DOMStoreReadWriteTransaction {
75 public static enum TransactionType {
81 static final Mapper<Throwable, Throwable> SAME_FAILURE_TRANSFORMER =
82 new Mapper<Throwable, Throwable>() {
84 public Throwable apply(Throwable failure) {
89 private static final AtomicLong counter = new AtomicLong();
91 private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
94 * Time interval in between transaction create retries.
96 private static final FiniteDuration CREATE_TX_TRY_INTERVAL =
97 FiniteDuration.create(1, TimeUnit.SECONDS);
100 * Used to enqueue the PhantomReferences for read-only TransactionProxy instances. The
101 * FinalizableReferenceQueue is safe to use statically in an OSGi environment as it uses some
102 * trickery to clean up its internal thread when the bundle is unloaded.
104 private static final FinalizableReferenceQueue phantomReferenceQueue =
105 new FinalizableReferenceQueue();
108 * This stores the TransactionProxyCleanupPhantomReference instances statically, This is
109 * necessary because PhantomReferences need a hard reference so they're not garbage collected.
110 * Once finalized, the TransactionProxyCleanupPhantomReference removes itself from this map
111 * and thus becomes eligible for garbage collection.
113 private static final Map<TransactionProxyCleanupPhantomReference,
114 TransactionProxyCleanupPhantomReference> phantomReferenceCache =
115 new ConcurrentHashMap<>();
118 * A PhantomReference that closes remote transactions for a TransactionProxy when it's
119 * garbage collected. This is used for read-only transactions as they're not explicitly closed
120 * by clients. So the only way to detect that a transaction is no longer in use and it's safe
121 * to clean up is when it's garbage collected. It's inexact as to when an instance will be GC'ed
122 * but TransactionProxy instances should generally be short-lived enough to avoid being moved
123 * to the old generation space and thus should be cleaned up in a timely manner as the GC
124 * runs on the young generation (eden, swap1...) space much more frequently.
126 private static class TransactionProxyCleanupPhantomReference
127 extends FinalizablePhantomReference<TransactionProxy> {
129 private final List<ActorSelection> remoteTransactionActors;
130 private final AtomicBoolean remoteTransactionActorsMB;
131 private final ActorContext actorContext;
132 private final TransactionIdentifier identifier;
134 protected TransactionProxyCleanupPhantomReference(TransactionProxy referent) {
135 super(referent, phantomReferenceQueue);
137 // Note we need to cache the relevant fields from the TransactionProxy as we can't
138 // have a hard reference to the TransactionProxy instance itself.
140 remoteTransactionActors = referent.remoteTransactionActors;
141 remoteTransactionActorsMB = referent.remoteTransactionActorsMB;
142 actorContext = referent.actorContext;
143 identifier = referent.identifier;
147 public void finalizeReferent() {
148 LOG.trace("Cleaning up {} Tx actors for TransactionProxy {}",
149 remoteTransactionActors.size(), identifier);
151 phantomReferenceCache.remove(this);
153 // Access the memory barrier volatile to ensure all previous updates to the
154 // remoteTransactionActors list are visible to this thread.
156 if(remoteTransactionActorsMB.get()) {
157 for(ActorSelection actor : remoteTransactionActors) {
158 LOG.trace("Sending CloseTransaction to {}", actor);
159 actorContext.sendOperationAsync(actor,
160 new CloseTransaction().toSerializable());
167 * Stores the remote Tx actors for each requested data store path to be used by the
168 * PhantomReference to close the remote Tx's. This is only used for read-only Tx's. The
169 * remoteTransactionActorsMB volatile serves as a memory barrier to publish updates to the
170 * remoteTransactionActors list so they will be visible to the thread accessing the
173 private List<ActorSelection> remoteTransactionActors;
174 private AtomicBoolean remoteTransactionActorsMB;
177 * Stores the create transaction results per shard.
179 private final Map<String, TransactionFutureCallback> txFutureCallbackMap = new HashMap<>();
181 private final TransactionType transactionType;
182 private final ActorContext actorContext;
183 private final TransactionIdentifier identifier;
184 private final String transactionChainId;
185 private final SchemaContext schemaContext;
186 private boolean inReadyState;
188 public TransactionProxy(ActorContext actorContext, TransactionType transactionType) {
189 this(actorContext, transactionType, "");
192 public TransactionProxy(ActorContext actorContext, TransactionType transactionType,
193 String transactionChainId) {
194 this.actorContext = Preconditions.checkNotNull(actorContext,
195 "actorContext should not be null");
196 this.transactionType = Preconditions.checkNotNull(transactionType,
197 "transactionType should not be null");
198 this.schemaContext = Preconditions.checkNotNull(actorContext.getSchemaContext(),
199 "schemaContext should not be null");
200 this.transactionChainId = transactionChainId;
202 String memberName = actorContext.getCurrentMemberName();
203 if(memberName == null){
204 memberName = "UNKNOWN-MEMBER";
207 this.identifier = TransactionIdentifier.builder().memberName(memberName).counter(
208 counter.getAndIncrement()).build();
210 if(transactionType == TransactionType.READ_ONLY) {
211 // Read-only Tx's aren't explicitly closed by the client so we create a PhantomReference
212 // to close the remote Tx's when this instance is no longer in use and is garbage
215 remoteTransactionActors = Lists.newArrayList();
216 remoteTransactionActorsMB = new AtomicBoolean();
218 TransactionProxyCleanupPhantomReference cleanup =
219 new TransactionProxyCleanupPhantomReference(this);
220 phantomReferenceCache.put(cleanup, cleanup);
223 LOG.debug("Created txn {} of type {}", identifier, transactionType);
227 List<Future<Object>> getRecordedOperationFutures() {
228 List<Future<Object>> recordedOperationFutures = Lists.newArrayList();
229 for(TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) {
230 TransactionContext transactionContext = txFutureCallback.getTransactionContext();
231 if(transactionContext != null) {
232 recordedOperationFutures.addAll(transactionContext.getRecordedOperationFutures());
236 return recordedOperationFutures;
240 boolean hasTransactionContext() {
241 for(TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) {
242 TransactionContext transactionContext = txFutureCallback.getTransactionContext();
243 if(transactionContext != null) {
252 public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(
253 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 TransactionContext transactionContext = txFutureCallback.getTransactionContext();
263 CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> future;
264 if(transactionContext != null) {
265 future = transactionContext.readData(path);
267 // The shard Tx hasn't been created yet so add the Tx operation to the Tx Future
268 // callback to be executed after the Tx is created.
269 final SettableFuture<Optional<NormalizedNode<?, ?>>> proxyFuture = SettableFuture.create();
270 txFutureCallback.addTxOperationOnComplete(new TransactionOperation() {
272 public void invoke(TransactionContext transactionContext) {
273 Futures.addCallback(transactionContext.readData(path),
274 new FutureCallback<Optional<NormalizedNode<?, ?>>>() {
276 public void onSuccess(Optional<NormalizedNode<?, ?>> data) {
277 proxyFuture.set(data);
281 public void onFailure(Throwable t) {
282 proxyFuture.setException(t);
288 future = MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
295 public CheckedFuture<Boolean, ReadFailedException> exists(final YangInstanceIdentifier path) {
297 Preconditions.checkState(transactionType != TransactionType.WRITE_ONLY,
298 "Exists operation on write-only transaction is not allowed");
300 LOG.debug("Tx {} exists {}", identifier, path);
302 TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
303 TransactionContext transactionContext = txFutureCallback.getTransactionContext();
305 CheckedFuture<Boolean, ReadFailedException> future;
306 if(transactionContext != null) {
307 future = transactionContext.dataExists(path);
309 // The shard Tx hasn't been created yet so add the Tx operation to the Tx Future
310 // callback to be executed after the Tx is created.
311 final SettableFuture<Boolean> proxyFuture = SettableFuture.create();
312 txFutureCallback.addTxOperationOnComplete(new TransactionOperation() {
314 public void invoke(TransactionContext transactionContext) {
315 Futures.addCallback(transactionContext.dataExists(path),
316 new FutureCallback<Boolean>() {
318 public void onSuccess(Boolean exists) {
319 proxyFuture.set(exists);
323 public void onFailure(Throwable t) {
324 proxyFuture.setException(t);
330 future = MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
336 private void checkModificationState() {
337 Preconditions.checkState(transactionType != TransactionType.READ_ONLY,
338 "Modification operation on read-only transaction is not allowed");
339 Preconditions.checkState(!inReadyState,
340 "Transaction is sealed - further modifications are not allowed");
344 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
346 checkModificationState();
348 LOG.debug("Tx {} write {}", identifier, path);
350 TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
351 TransactionContext transactionContext = txFutureCallback.getTransactionContext();
352 if(transactionContext != null) {
353 transactionContext.writeData(path, data);
355 // The shard Tx hasn't been created yet so add the Tx operation to the Tx Future
356 // callback to be executed after the Tx is created.
357 txFutureCallback.addTxOperationOnComplete(new TransactionOperation() {
359 public void invoke(TransactionContext transactionContext) {
360 transactionContext.writeData(path, data);
367 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
369 checkModificationState();
371 LOG.debug("Tx {} merge {}", identifier, path);
373 TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
374 TransactionContext transactionContext = txFutureCallback.getTransactionContext();
375 if(transactionContext != null) {
376 transactionContext.mergeData(path, data);
378 // The shard Tx hasn't been created yet so add the Tx operation to the Tx Future
379 // callback to be executed after the Tx is created.
380 txFutureCallback.addTxOperationOnComplete(new TransactionOperation() {
382 public void invoke(TransactionContext transactionContext) {
383 transactionContext.mergeData(path, data);
390 public void delete(final YangInstanceIdentifier path) {
392 checkModificationState();
394 LOG.debug("Tx {} delete {}", identifier, path);
396 TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
397 TransactionContext transactionContext = txFutureCallback.getTransactionContext();
398 if(transactionContext != null) {
399 transactionContext.deleteData(path);
401 // The shard Tx hasn't been created yet so add the Tx operation to the Tx Future
402 // callback to be executed after the Tx is created.
403 txFutureCallback.addTxOperationOnComplete(new TransactionOperation() {
405 public void invoke(TransactionContext transactionContext) {
406 transactionContext.deleteData(path);
413 public DOMStoreThreePhaseCommitCohort ready() {
415 checkModificationState();
419 LOG.debug("Tx {} Readying {} transactions for commit", identifier,
420 txFutureCallbackMap.size());
422 List<Future<ActorSelection>> cohortFutures = Lists.newArrayList();
424 for(TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) {
426 LOG.debug("Tx {} Readying transaction for shard {}", identifier,
427 txFutureCallback.getShardName());
429 TransactionContext transactionContext = txFutureCallback.getTransactionContext();
430 if(transactionContext != null) {
431 cohortFutures.add(transactionContext.readyTransaction());
433 // The shard Tx hasn't been created yet so create a promise to ready the Tx later
434 // after it's created.
435 final Promise<ActorSelection> cohortPromise = akka.dispatch.Futures.promise();
436 txFutureCallback.addTxOperationOnComplete(new TransactionOperation() {
438 public void invoke(TransactionContext transactionContext) {
439 cohortPromise.completeWith(transactionContext.readyTransaction());
443 cohortFutures.add(cohortPromise.future());
447 onTransactionReady(cohortFutures);
449 return new ThreePhaseCommitCohortProxy(actorContext, cohortFutures,
450 identifier.toString());
454 * Method for derived classes to be notified when the transaction has been readied.
456 * @param cohortFutures the cohort Futures for each shard transaction.
458 protected void onTransactionReady(List<Future<ActorSelection>> cohortFutures) {
462 * Method called to send a CreateTransaction message to a shard.
464 * @param shard the shard actor to send to
465 * @param serializedCreateMessage the serialized message to send
466 * @return the response Future
468 protected Future<Object> sendCreateTransaction(ActorSelection shard,
469 Object serializedCreateMessage) {
470 return actorContext.executeOperationAsync(shard, serializedCreateMessage);
474 public Object getIdentifier() {
475 return this.identifier;
479 public void close() {
480 for(TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) {
481 TransactionContext transactionContext = txFutureCallback.getTransactionContext();
482 if(transactionContext != null) {
483 transactionContext.closeTransaction();
485 txFutureCallback.addTxOperationOnComplete(new TransactionOperation() {
487 public void invoke(TransactionContext transactionContext) {
488 transactionContext.closeTransaction();
494 txFutureCallbackMap.clear();
496 if(transactionType == TransactionType.READ_ONLY) {
497 remoteTransactionActors.clear();
498 remoteTransactionActorsMB.set(true);
502 private String shardNameFromIdentifier(YangInstanceIdentifier path){
503 return ShardStrategyFactory.getStrategy(path).findShard(path);
506 private TransactionFutureCallback getOrCreateTxFutureCallback(YangInstanceIdentifier path) {
507 String shardName = shardNameFromIdentifier(path);
508 TransactionFutureCallback txFutureCallback = txFutureCallbackMap.get(shardName);
509 if(txFutureCallback == null) {
510 Future<ActorSelection> findPrimaryFuture = actorContext.findPrimaryShardAsync(shardName);
512 final TransactionFutureCallback newTxFutureCallback =
513 new TransactionFutureCallback(shardName);
515 txFutureCallback = newTxFutureCallback;
516 txFutureCallbackMap.put(shardName, txFutureCallback);
518 findPrimaryFuture.onComplete(new OnComplete<ActorSelection>() {
520 public void onComplete(Throwable failure, ActorSelection primaryShard) {
521 if(failure != null) {
522 newTxFutureCallback.onComplete(failure, null);
524 newTxFutureCallback.setPrimaryShard(primaryShard);
527 }, actorContext.getActorSystem().dispatcher());
530 return txFutureCallback;
533 public String getTransactionChainId() {
534 return transactionChainId;
538 * Interface for a transaction operation to be invoked later.
540 private static interface TransactionOperation {
541 void invoke(TransactionContext transactionContext);
545 * Implements a Future OnComplete callback for a CreateTransaction message. This class handles
546 * retries, up to a limit, if the shard doesn't have a leader yet. This is done by scheduling a
547 * retry task after a short delay.
549 * The end result from a completed CreateTransaction message is a TransactionContext that is
550 * used to perform transaction operations. Transaction operations that occur before the
551 * CreateTransaction completes are cache and executed once the CreateTransaction completes,
552 * successfully or not.
554 private class TransactionFutureCallback extends OnComplete<Object> {
557 * The list of transaction operations to execute once the CreateTransaction completes.
559 @GuardedBy("txOperationsOnComplete")
560 private final List<TransactionOperation> txOperationsOnComplete = Lists.newArrayList();
563 * The TransactionContext resulting from the CreateTransaction reply.
565 private volatile TransactionContext transactionContext;
568 * The target primary shard.
570 private volatile ActorSelection primaryShard;
572 private volatile int createTxTries = (int) (actorContext.getDatastoreContext().
573 getShardLeaderElectionTimeout().duration().toMillis() /
574 CREATE_TX_TRY_INTERVAL.toMillis());
576 private final String shardName;
578 TransactionFutureCallback(String shardName) {
579 this.shardName = shardName;
582 String getShardName() {
586 TransactionContext getTransactionContext() {
587 return transactionContext;
592 * Sets the target primary shard and initiates a CreateTransaction try.
594 void setPrimaryShard(ActorSelection primaryShard) {
595 LOG.debug("Tx {} Primary shard found - trying create transaction", identifier);
597 this.primaryShard = primaryShard;
598 tryCreateTransaction();
602 * Adds a TransactionOperation to be executed after the CreateTransaction completes.
604 void addTxOperationOnComplete(TransactionOperation operation) {
605 synchronized(txOperationsOnComplete) {
606 if(transactionContext == null) {
607 LOG.debug("Tx {} Adding operation on complete {}", identifier);
609 txOperationsOnComplete.add(operation);
611 operation.invoke(transactionContext);
617 * Performs a CreateTransaction try async.
619 private void tryCreateTransaction() {
620 Future<Object> createTxFuture = sendCreateTransaction(primaryShard,
621 new CreateTransaction(identifier.toString(),
622 TransactionProxy.this.transactionType.ordinal(),
623 getTransactionChainId()).toSerializable());
625 createTxFuture.onComplete(this, actorContext.getActorSystem().dispatcher());
629 public void onComplete(Throwable failure, Object response) {
630 if(failure instanceof NoShardLeaderException) {
631 // There's no leader for the shard yet - schedule and try again, unless we're out
632 // of retries. Note: createTxTries is volatile as it may be written by different
633 // threads however not concurrently, therefore decrementing it non-atomically here
635 if(--createTxTries > 0) {
636 LOG.debug("Tx {} Shard {} has no leader yet - scheduling create Tx retry",
637 identifier, shardName);
639 actorContext.getActorSystem().scheduler().scheduleOnce(CREATE_TX_TRY_INTERVAL,
643 tryCreateTransaction();
645 }, actorContext.getActorSystem().dispatcher());
650 // Create the TransactionContext from the response or failure and execute delayed
651 // TransactionOperations. This entire section is done atomically (ie synchronized) with
652 // respect to #addTxOperationOnComplete to handle timing issues and ensure no
653 // TransactionOperation is missed and that they are processed in the order they occurred.
654 synchronized(txOperationsOnComplete) {
655 // Store the new TransactionContext locally until we've completed invoking the
656 // TransactionOperations. This avoids thread timing issues which could cause
657 // out-of-order TransactionOperations. Eg, on a modification operation, if the
658 // TransactionContext is non-null, then we directly call the TransactionContext.
659 // However, at the same time, the code may be executing the cached
660 // TransactionOperations. So to avoid thus timing, we don't publish the
661 // TransactionContext until after we've executed all cached TransactionOperations.
662 TransactionContext localTransactionContext;
663 if(failure != null) {
664 LOG.debug("Tx {} Creating NoOpTransaction because of error: {}", identifier,
665 failure.getMessage());
667 localTransactionContext = new NoOpTransactionContext(failure, identifier);
668 } else if (response.getClass().equals(CreateTransactionReply.SERIALIZABLE_CLASS)) {
669 localTransactionContext = createValidTransactionContext(
670 CreateTransactionReply.fromSerializable(response));
672 IllegalArgumentException exception = new IllegalArgumentException(String.format(
673 "Invalid reply type %s for CreateTransaction", response.getClass()));
675 localTransactionContext = new NoOpTransactionContext(exception, identifier);
678 for(TransactionOperation oper: txOperationsOnComplete) {
679 oper.invoke(localTransactionContext);
682 txOperationsOnComplete.clear();
684 // We're done invoking the TransactionOperations so we can now publish the
685 // TransactionContext.
686 transactionContext = localTransactionContext;
690 private TransactionContext createValidTransactionContext(CreateTransactionReply reply) {
691 String transactionPath = reply.getTransactionPath();
693 LOG.debug("Tx {} Received transaction actor path {}", identifier, transactionPath);
695 ActorSelection transactionActor = actorContext.actorSelection(transactionPath);
697 if (transactionType == TransactionType.READ_ONLY) {
698 // Add the actor to the remoteTransactionActors list for access by the
699 // cleanup PhantonReference.
700 remoteTransactionActors.add(transactionActor);
702 // Write to the memory barrier volatile to publish the above update to the
703 // remoteTransactionActors list for thread visibility.
704 remoteTransactionActorsMB.set(true);
707 // TxActor is always created where the leader of the shard is.
708 // Check if TxActor is created in the same node
709 boolean isTxActorLocal = actorContext.isLocalPath(transactionPath);
711 return new TransactionContextImpl(transactionPath, transactionActor, identifier,
712 actorContext, schemaContext, isTxActorLocal, reply.getVersion());
716 private interface TransactionContext {
717 void closeTransaction();
719 Future<ActorSelection> readyTransaction();
721 void writeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data);
723 void deleteData(YangInstanceIdentifier path);
725 void mergeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data);
727 CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readData(
728 final YangInstanceIdentifier path);
730 CheckedFuture<Boolean, ReadFailedException> dataExists(YangInstanceIdentifier path);
732 List<Future<Object>> getRecordedOperationFutures();
735 private static abstract class AbstractTransactionContext implements TransactionContext {
737 protected final TransactionIdentifier identifier;
738 protected final List<Future<Object>> recordedOperationFutures = Lists.newArrayList();
740 AbstractTransactionContext(TransactionIdentifier identifier) {
741 this.identifier = identifier;
745 public List<Future<Object>> getRecordedOperationFutures() {
746 return recordedOperationFutures;
750 private static class TransactionContextImpl extends AbstractTransactionContext {
751 private final Logger LOG = LoggerFactory.getLogger(TransactionContextImpl.class);
753 private final ActorContext actorContext;
754 private final SchemaContext schemaContext;
755 private final String transactionPath;
756 private final ActorSelection actor;
757 private final boolean isTxActorLocal;
758 private final int remoteTransactionVersion;
760 private TransactionContextImpl(String transactionPath, ActorSelection actor, TransactionIdentifier identifier,
761 ActorContext actorContext, SchemaContext schemaContext,
762 boolean isTxActorLocal, int remoteTransactionVersion) {
764 this.transactionPath = transactionPath;
766 this.actorContext = actorContext;
767 this.schemaContext = schemaContext;
768 this.isTxActorLocal = isTxActorLocal;
769 this.remoteTransactionVersion = remoteTransactionVersion;
772 private ActorSelection getActor() {
777 public void closeTransaction() {
778 LOG.debug("Tx {} closeTransaction called", identifier);
780 actorContext.sendOperationAsync(getActor(), new CloseTransaction().toSerializable());
784 public Future<ActorSelection> readyTransaction() {
785 LOG.debug("Tx {} readyTransaction called with {} previous recorded operations pending",
786 identifier, recordedOperationFutures.size());
788 // Send the ReadyTransaction message to the Tx actor.
790 ReadyTransaction readyTransaction = new ReadyTransaction();
791 final Future<Object> replyFuture = actorContext.executeOperationAsync(getActor(),
792 isTxActorLocal ? readyTransaction : readyTransaction.toSerializable());
794 // Combine all the previously recorded put/merge/delete operation reply Futures and the
795 // ReadyTransactionReply Future into one Future. If any one fails then the combined
796 // Future will fail. We need all prior operations and the ready operation to succeed
797 // in order to attempt commit.
799 List<Future<Object>> futureList =
800 Lists.newArrayListWithCapacity(recordedOperationFutures.size() + 1);
801 futureList.addAll(recordedOperationFutures);
802 futureList.add(replyFuture);
804 Future<Iterable<Object>> combinedFutures = akka.dispatch.Futures.sequence(futureList,
805 actorContext.getActorSystem().dispatcher());
807 // Transform the combined Future into a Future that returns the cohort actor path from
808 // the ReadyTransactionReply. That's the end result of the ready operation.
810 return combinedFutures.transform(new Mapper<Iterable<Object>, ActorSelection>() {
812 public ActorSelection checkedApply(Iterable<Object> notUsed) {
813 LOG.debug("Tx {} readyTransaction: pending recorded operations succeeded",
816 // At this point all the Futures succeeded and we need to extract the cohort
817 // actor path from the ReadyTransactionReply. For the recorded operations, they
818 // don't return any data so we're only interested that they completed
819 // successfully. We could be paranoid and verify the correct reply types but
820 // that really should never happen so it's not worth the overhead of
821 // de-serializing each reply.
823 // Note the Future get call here won't block as it's complete.
824 Object serializedReadyReply = replyFuture.value().get().get();
825 if (serializedReadyReply instanceof ReadyTransactionReply) {
826 return actorContext.actorSelection(((ReadyTransactionReply)serializedReadyReply).getCohortPath());
828 } else if(serializedReadyReply.getClass().equals(ReadyTransactionReply.SERIALIZABLE_CLASS)) {
829 ReadyTransactionReply reply = ReadyTransactionReply.fromSerializable(serializedReadyReply);
830 String cohortPath = reply.getCohortPath();
832 // In Helium we used to return the local path of the actor which represented
833 // a remote ThreePhaseCommitCohort. The local path would then be converted to
834 // a remote path using this resolvePath method. To maintain compatibility with
835 // a Helium node we need to continue to do this conversion.
836 // At some point in the future when upgrades from Helium are not supported
837 // we could remove this code to resolvePath and just use the cohortPath as the
838 // resolved cohortPath
839 if(TransactionContextImpl.this.remoteTransactionVersion < CreateTransaction.HELIUM_1_VERSION) {
840 cohortPath = actorContext.resolvePath(transactionPath, cohortPath);
843 return actorContext.actorSelection(cohortPath);
846 // Throwing an exception here will fail the Future.
847 throw new IllegalArgumentException(String.format("Invalid reply type {}",
848 serializedReadyReply.getClass()));
851 }, SAME_FAILURE_TRANSFORMER, actorContext.getActorSystem().dispatcher());
855 public void deleteData(YangInstanceIdentifier path) {
856 LOG.debug("Tx {} deleteData called path = {}", identifier, path);
858 DeleteData deleteData = new DeleteData(path);
859 recordedOperationFutures.add(actorContext.executeOperationAsync(getActor(),
860 isTxActorLocal ? deleteData : deleteData.toSerializable()));
864 public void mergeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
865 LOG.debug("Tx {} mergeData called path = {}", identifier, path);
867 MergeData mergeData = new MergeData(path, data, schemaContext);
868 recordedOperationFutures.add(actorContext.executeOperationAsync(getActor(),
869 isTxActorLocal ? mergeData : mergeData.toSerializable()));
873 public void writeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
874 LOG.debug("Tx {} writeData called path = {}", identifier, path);
876 WriteData writeData = new WriteData(path, data, schemaContext);
877 recordedOperationFutures.add(actorContext.executeOperationAsync(getActor(),
878 isTxActorLocal ? writeData : writeData.toSerializable()));
882 public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readData(
883 final YangInstanceIdentifier path) {
885 LOG.debug("Tx {} readData called path = {}", identifier, path);
887 final SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture = SettableFuture.create();
889 // If there were any previous recorded put/merge/delete operation reply Futures then we
890 // must wait for them to successfully complete. This is necessary to honor the read
891 // uncommitted semantics of the public API contract. If any one fails then fail the read.
893 if(recordedOperationFutures.isEmpty()) {
894 finishReadData(path, returnFuture);
896 LOG.debug("Tx {} readData: verifying {} previous recorded operations",
897 identifier, recordedOperationFutures.size());
899 // Note: we make a copy of recordedOperationFutures to be on the safe side in case
900 // Futures#sequence accesses the passed List on a different thread, as
901 // recordedOperationFutures is not synchronized.
903 Future<Iterable<Object>> combinedFutures = akka.dispatch.Futures.sequence(
904 Lists.newArrayList(recordedOperationFutures),
905 actorContext.getActorSystem().dispatcher());
907 OnComplete<Iterable<Object>> onComplete = new OnComplete<Iterable<Object>>() {
909 public void onComplete(Throwable failure, Iterable<Object> notUsed)
911 if(failure != null) {
912 LOG.debug("Tx {} readData: a recorded operation failed: {}",
913 identifier, failure);
914 returnFuture.setException(new ReadFailedException(
915 "The read could not be performed because a previous put, merge,"
916 + "or delete operation failed", failure));
918 finishReadData(path, returnFuture);
923 combinedFutures.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
926 return MappingCheckedFuture.create(returnFuture, ReadFailedException.MAPPER);
929 private void finishReadData(final YangInstanceIdentifier path,
930 final SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture) {
932 LOG.debug("Tx {} finishReadData called path = {}", identifier, path);
934 OnComplete<Object> onComplete = new OnComplete<Object>() {
936 public void onComplete(Throwable failure, Object readResponse) throws Throwable {
937 if(failure != null) {
938 LOG.debug("Tx {} read operation failed: {}", identifier, failure);
939 returnFuture.setException(new ReadFailedException(
940 "Error reading data for path " + path, failure));
943 LOG.debug("Tx {} read operation succeeded", identifier, failure);
945 if (readResponse instanceof ReadDataReply) {
946 ReadDataReply reply = (ReadDataReply) readResponse;
947 returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
949 } else if (readResponse.getClass().equals(ReadDataReply.SERIALIZABLE_CLASS)) {
950 ReadDataReply reply = ReadDataReply.fromSerializable(schemaContext, path, readResponse);
951 returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
954 returnFuture.setException(new ReadFailedException(
955 "Invalid response reading data for path " + path));
961 ReadData readData = new ReadData(path);
962 Future<Object> readFuture = actorContext.executeOperationAsync(getActor(),
963 isTxActorLocal ? readData : readData.toSerializable());
965 readFuture.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
969 public CheckedFuture<Boolean, ReadFailedException> dataExists(
970 final YangInstanceIdentifier path) {
972 LOG.debug("Tx {} dataExists called path = {}", identifier, path);
974 final SettableFuture<Boolean> returnFuture = SettableFuture.create();
976 // If there were any previous recorded put/merge/delete operation reply Futures then we
977 // must wait for them to successfully complete. This is necessary to honor the read
978 // uncommitted semantics of the public API contract. If any one fails then fail this
981 if(recordedOperationFutures.isEmpty()) {
982 finishDataExists(path, returnFuture);
984 LOG.debug("Tx {} dataExists: verifying {} previous recorded operations",
985 identifier, recordedOperationFutures.size());
987 // Note: we make a copy of recordedOperationFutures to be on the safe side in case
988 // Futures#sequence accesses the passed List on a different thread, as
989 // recordedOperationFutures is not synchronized.
991 Future<Iterable<Object>> combinedFutures = akka.dispatch.Futures.sequence(
992 Lists.newArrayList(recordedOperationFutures),
993 actorContext.getActorSystem().dispatcher());
994 OnComplete<Iterable<Object>> onComplete = new OnComplete<Iterable<Object>>() {
996 public void onComplete(Throwable failure, Iterable<Object> notUsed)
998 if(failure != null) {
999 LOG.debug("Tx {} dataExists: a recorded operation failed: {}",
1000 identifier, failure);
1001 returnFuture.setException(new ReadFailedException(
1002 "The data exists could not be performed because a previous "
1003 + "put, merge, or delete operation failed", failure));
1005 finishDataExists(path, returnFuture);
1010 combinedFutures.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
1013 return MappingCheckedFuture.create(returnFuture, ReadFailedException.MAPPER);
1016 private void finishDataExists(final YangInstanceIdentifier path,
1017 final SettableFuture<Boolean> returnFuture) {
1019 LOG.debug("Tx {} finishDataExists called path = {}", identifier, path);
1021 OnComplete<Object> onComplete = new OnComplete<Object>() {
1023 public void onComplete(Throwable failure, Object response) throws Throwable {
1024 if(failure != null) {
1025 LOG.debug("Tx {} dataExists operation failed: {}", identifier, failure);
1026 returnFuture.setException(new ReadFailedException(
1027 "Error checking data exists for path " + path, failure));
1029 LOG.debug("Tx {} dataExists operation succeeded", identifier, failure);
1031 if (response instanceof DataExistsReply) {
1032 returnFuture.set(Boolean.valueOf(((DataExistsReply) response).exists()));
1034 } else if (response.getClass().equals(DataExistsReply.SERIALIZABLE_CLASS)) {
1035 returnFuture.set(Boolean.valueOf(DataExistsReply.fromSerializable(response).exists()));
1038 returnFuture.setException(new ReadFailedException(
1039 "Invalid response checking exists for path " + path));
1045 DataExists dataExists = new DataExists(path);
1046 Future<Object> future = actorContext.executeOperationAsync(getActor(),
1047 isTxActorLocal ? dataExists : dataExists.toSerializable());
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));