Refactor TransactionProxy
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / TransactionProxy.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.cluster.datastore;
10
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;
26 import java.util.Map;
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;
61
62 /**
63  * TransactionProxy acts as a proxy for one or more transactions that were created on a remote shard
64  * <p>
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
68  *</p>
69  * <p>
70  * The TransactionProxy does not make any guarantees about atomicity or order in which the transactions on the various
71  * shards will be executed.
72  * </p>
73  */
74 public class TransactionProxy implements DOMStoreReadWriteTransaction {
75
76     public static enum TransactionType {
77         READ_ONLY,
78         WRITE_ONLY,
79         READ_WRITE
80     }
81
82     static final Mapper<Throwable, Throwable> SAME_FAILURE_TRANSFORMER =
83                                                               new Mapper<Throwable, Throwable>() {
84         @Override
85         public Throwable apply(Throwable failure) {
86             return failure;
87         }
88     };
89
90     private static final AtomicLong counter = new AtomicLong();
91
92     private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
93
94     /**
95      * Time interval in between transaction create retries.
96      */
97     private static final FiniteDuration CREATE_TX_TRY_INTERVAL =
98             FiniteDuration.create(1, TimeUnit.SECONDS);
99
100     /**
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.
104      */
105     private static final FinalizableReferenceQueue phantomReferenceQueue =
106                                                                   new FinalizableReferenceQueue();
107
108     /**
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.
113      */
114     private static final Map<TransactionProxyCleanupPhantomReference,
115                              TransactionProxyCleanupPhantomReference> phantomReferenceCache =
116                                                                         new ConcurrentHashMap<>();
117
118     /**
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.
126      */
127     private static class TransactionProxyCleanupPhantomReference
128                                            extends FinalizablePhantomReference<TransactionProxy> {
129
130         private final List<ActorSelection> remoteTransactionActors;
131         private final AtomicBoolean remoteTransactionActorsMB;
132         private final ActorContext actorContext;
133         private final TransactionIdentifier identifier;
134
135         protected TransactionProxyCleanupPhantomReference(TransactionProxy referent) {
136             super(referent, phantomReferenceQueue);
137
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.
140
141             remoteTransactionActors = referent.remoteTransactionActors;
142             remoteTransactionActorsMB = referent.remoteTransactionActorsMB;
143             actorContext = referent.actorContext;
144             identifier = referent.identifier;
145         }
146
147         @Override
148         public void finalizeReferent() {
149             LOG.trace("Cleaning up {} Tx actors for TransactionProxy {}",
150                     remoteTransactionActors.size(), identifier);
151
152             phantomReferenceCache.remove(this);
153
154             // Access the memory barrier volatile to ensure all previous updates to the
155             // remoteTransactionActors list are visible to this thread.
156
157             if(remoteTransactionActorsMB.get()) {
158                 for(ActorSelection actor : remoteTransactionActors) {
159                     LOG.trace("Sending CloseTransaction to {}", actor);
160                     actorContext.sendOperationAsync(actor,
161                             new CloseTransaction().toSerializable());
162                 }
163             }
164         }
165     }
166
167     /**
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
172      * PhantomReference.
173      */
174     private List<ActorSelection> remoteTransactionActors;
175     private AtomicBoolean remoteTransactionActorsMB;
176
177     /**
178      * Stores the create transaction results per shard.
179      */
180     private final Map<String, TransactionFutureCallback> txFutureCallbackMap = new HashMap<>();
181
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;
188
189     public TransactionProxy(ActorContext actorContext, TransactionType transactionType) {
190         this(actorContext, transactionType, "");
191     }
192
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;
202
203         String memberName = actorContext.getCurrentMemberName();
204         if(memberName == null){
205             memberName = "UNKNOWN-MEMBER";
206         }
207
208         this.identifier = TransactionIdentifier.builder().memberName(memberName).counter(
209             counter.getAndIncrement()).build();
210
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
214             // collected.
215
216             remoteTransactionActors = Lists.newArrayList();
217             remoteTransactionActorsMB = new AtomicBoolean();
218
219             TransactionProxyCleanupPhantomReference cleanup =
220                 new TransactionProxyCleanupPhantomReference(this);
221             phantomReferenceCache.put(cleanup, cleanup);
222         }
223
224         LOG.debug("Created txn {} of type {} on chain {}", identifier, transactionType, transactionChainId);
225     }
226
227     @VisibleForTesting
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());
234             }
235         }
236
237         return recordedOperationFutures;
238     }
239
240     @VisibleForTesting
241     boolean hasTransactionContext() {
242         for(TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) {
243             TransactionContext transactionContext = txFutureCallback.getTransactionContext();
244             if(transactionContext != null) {
245                 return true;
246             }
247         }
248
249         return false;
250     }
251
252     @Override
253     public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final YangInstanceIdentifier path) {
254
255         Preconditions.checkState(transactionType != TransactionType.WRITE_ONLY,
256                 "Read operation on write-only transaction is not allowed");
257
258         LOG.debug("Tx {} read {}", identifier, path);
259
260         TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
261         return txFutureCallback.enqueueReadOperation(new ReadOperation<Optional<NormalizedNode<?, ?>>>() {
262             @Override
263             public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> invoke(
264                     TransactionContext transactionContext) {
265                 return transactionContext.readData(path);
266             }
267         });
268     }
269
270     @Override
271     public CheckedFuture<Boolean, ReadFailedException> exists(final YangInstanceIdentifier path) {
272
273         Preconditions.checkState(transactionType != TransactionType.WRITE_ONLY,
274                 "Exists operation on write-only transaction is not allowed");
275
276         LOG.debug("Tx {} exists {}", identifier, path);
277
278         TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
279         return txFutureCallback.enqueueReadOperation(new ReadOperation<Boolean>() {
280             @Override
281             public CheckedFuture<Boolean, ReadFailedException> invoke(TransactionContext transactionContext) {
282                 return transactionContext.dataExists(path);
283             }
284         });
285     }
286
287
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");
293     }
294
295     @Override
296     public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
297
298         checkModificationState();
299
300         LOG.debug("Tx {} write {}", identifier, path);
301
302         TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
303         txFutureCallback.enqueueModifyOperation(new TransactionOperation() {
304             @Override
305             public void invoke(TransactionContext transactionContext) {
306                 transactionContext.writeData(path, data);
307             }
308         });
309     }
310
311     @Override
312     public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
313
314         checkModificationState();
315
316         LOG.debug("Tx {} merge {}", identifier, path);
317
318         TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
319         txFutureCallback.enqueueModifyOperation(new TransactionOperation() {
320             @Override
321             public void invoke(TransactionContext transactionContext) {
322                 transactionContext.mergeData(path, data);
323             }
324         });
325     }
326
327     @Override
328     public void delete(final YangInstanceIdentifier path) {
329
330         checkModificationState();
331
332         LOG.debug("Tx {} delete {}", identifier, path);
333
334         TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
335         txFutureCallback.enqueueModifyOperation(new TransactionOperation() {
336             @Override
337             public void invoke(TransactionContext transactionContext) {
338                 transactionContext.deleteData(path);
339             }
340         });
341     }
342
343     @Override
344     public DOMStoreThreePhaseCommitCohort ready() {
345
346         checkModificationState();
347
348         inReadyState = true;
349
350         LOG.debug("Tx {} Readying {} transactions for commit", identifier,
351                     txFutureCallbackMap.size());
352
353         List<Future<ActorSelection>> cohortFutures = Lists.newArrayList();
354
355         for(TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) {
356
357             LOG.debug("Tx {} Readying transaction for shard {} chain {}", identifier,
358                         txFutureCallback.getShardName(), transactionChainId);
359
360             Future<ActorSelection> future = txFutureCallback.enqueueFutureOperation(new FutureOperation<ActorSelection>() {
361                 @Override
362                 public Future<ActorSelection> invoke(TransactionContext transactionContext) {
363                     return transactionContext.readyTransaction();
364                 }
365             });
366
367             cohortFutures.add(future);
368         }
369
370         onTransactionReady(cohortFutures);
371
372         return new ThreePhaseCommitCohortProxy(actorContext, cohortFutures,
373                 identifier.toString());
374     }
375
376     /**
377      * Method for derived classes to be notified when the transaction has been readied.
378      *
379      * @param cohortFutures the cohort Futures for each shard transaction.
380      */
381     protected void onTransactionReady(List<Future<ActorSelection>> cohortFutures) {
382     }
383
384     /**
385      * Method called to send a CreateTransaction message to a shard.
386      *
387      * @param shard the shard actor to send to
388      * @param serializedCreateMessage the serialized message to send
389      * @return the response Future
390      */
391     protected Future<Object> sendCreateTransaction(ActorSelection shard,
392             Object serializedCreateMessage) {
393         return actorContext.executeOperationAsync(shard, serializedCreateMessage);
394     }
395
396     @Override
397     public Object getIdentifier() {
398         return this.identifier;
399     }
400
401     @Override
402     public void close() {
403         for (TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) {
404             txFutureCallback.enqueueModifyOperation(new TransactionOperation() {
405                 @Override
406                 public void invoke(TransactionContext transactionContext) {
407                     transactionContext.closeTransaction();
408                 }
409             });
410         }
411
412         txFutureCallbackMap.clear();
413
414         if(transactionType == TransactionType.READ_ONLY) {
415             remoteTransactionActors.clear();
416             remoteTransactionActorsMB.set(true);
417         }
418     }
419
420     private String shardNameFromIdentifier(YangInstanceIdentifier path){
421         return ShardStrategyFactory.getStrategy(path).findShard(path);
422     }
423
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);
429
430             final TransactionFutureCallback newTxFutureCallback =
431                     new TransactionFutureCallback(shardName);
432
433             txFutureCallback = newTxFutureCallback;
434             txFutureCallbackMap.put(shardName, txFutureCallback);
435
436             findPrimaryFuture.onComplete(new OnComplete<ActorSelection>() {
437                 @Override
438                 public void onComplete(Throwable failure, ActorSelection primaryShard) {
439                     if(failure != null) {
440                         newTxFutureCallback.onComplete(failure, null);
441                     } else {
442                         newTxFutureCallback.setPrimaryShard(primaryShard);
443                     }
444                 }
445             }, actorContext.getActorSystem().dispatcher());
446         }
447
448         return txFutureCallback;
449     }
450
451     public String getTransactionChainId() {
452         return transactionChainId;
453     }
454
455     protected ActorContext getActorContext() {
456         return actorContext;
457     }
458
459     /**
460      * Interfaces for transaction operations to be invoked later.
461      */
462     private static interface TransactionOperation {
463         void invoke(TransactionContext transactionContext);
464     }
465
466     /**
467      * This interface returns a Guava Future
468      */
469     private static interface ReadOperation<T> {
470         CheckedFuture<T, ReadFailedException> invoke(TransactionContext transactionContext);
471     }
472
473     /**
474      * This interface returns a Scala Future
475      */
476     private static interface FutureOperation<T> {
477         Future<T> invoke(TransactionContext transactionContext);
478     }
479
480     /**
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.
484      * <p>
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.
489      */
490     private class TransactionFutureCallback extends OnComplete<Object> {
491
492         /**
493          * The list of transaction operations to execute once the CreateTransaction completes.
494          */
495         @GuardedBy("txOperationsOnComplete")
496         private final List<TransactionOperation> txOperationsOnComplete = Lists.newArrayList();
497
498         /**
499          * The TransactionContext resulting from the CreateTransaction reply.
500          */
501         private volatile TransactionContext transactionContext;
502
503         /**
504          * The target primary shard.
505          */
506         private volatile ActorSelection primaryShard;
507
508         private volatile int createTxTries = (int) (actorContext.getDatastoreContext().
509                 getShardLeaderElectionTimeout().duration().toMillis() /
510                 CREATE_TX_TRY_INTERVAL.toMillis());
511
512         private final String shardName;
513
514         TransactionFutureCallback(String shardName) {
515             this.shardName = shardName;
516         }
517
518         String getShardName() {
519             return shardName;
520         }
521
522         TransactionContext getTransactionContext() {
523             return transactionContext;
524         }
525
526
527         /**
528          * Sets the target primary shard and initiates a CreateTransaction try.
529          */
530         void setPrimaryShard(ActorSelection primaryShard) {
531             LOG.debug("Tx {} Primary shard found - trying create transaction", identifier);
532
533             this.primaryShard = primaryShard;
534             tryCreateTransaction();
535         }
536
537         /**
538          * Adds a TransactionOperation to be executed after the CreateTransaction completes.
539          */
540         void addTxOperationOnComplete(TransactionOperation operation) {
541             synchronized(txOperationsOnComplete) {
542                 if(transactionContext == null) {
543                     LOG.debug("Tx {} Adding operation on complete {}", identifier);
544
545                     txOperationsOnComplete.add(operation);
546                 } else {
547                     operation.invoke(transactionContext);
548                 }
549             }
550         }
551
552
553         <T> Future<T> enqueueFutureOperation(final FutureOperation<T> op) {
554
555             Future<T> future;
556
557             if (transactionContext != null) {
558                 future = op.invoke(transactionContext);
559             } else {
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() {
564                     @Override
565                     public void invoke(TransactionContext transactionContext) {
566                         promise.completeWith(op.invoke(transactionContext));
567                     }
568                 });
569
570                 future = promise.future();
571             }
572
573             return future;
574         }
575
576         <T> CheckedFuture<T, ReadFailedException> enqueueReadOperation(final ReadOperation<T> op) {
577
578             CheckedFuture<T, ReadFailedException> future;
579
580             if (transactionContext != null) {
581                 future = op.invoke(transactionContext);
582             } else {
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() {
587                     @Override
588                     public void invoke(TransactionContext transactionContext) {
589                         Futures.addCallback(op.invoke(transactionContext), new FutureCallback<T>() {
590                             @Override
591                             public void onSuccess(T data) {
592                                 proxyFuture.set(data);
593                             }
594
595                             @Override
596                             public void onFailure(Throwable t) {
597                                 proxyFuture.setException(t);
598                             }
599                         });
600                     }
601                 });
602
603                 future = MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
604             }
605
606             return future;
607         }
608
609         void enqueueModifyOperation(final TransactionOperation op) {
610
611             if (transactionContext != null) {
612                 op.invoke(transactionContext);
613             } else {
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);
617             }
618         }
619
620
621
622
623
624         /**
625          * Performs a CreateTransaction try async.
626          */
627         private void tryCreateTransaction() {
628             Future<Object> createTxFuture = sendCreateTransaction(primaryShard,
629                     new CreateTransaction(identifier.toString(),
630                             TransactionProxy.this.transactionType.ordinal(),
631                             getTransactionChainId()).toSerializable());
632
633             createTxFuture.onComplete(this, actorContext.getActorSystem().dispatcher());
634         }
635
636         @Override
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
642                 // is ok.
643                 if(--createTxTries > 0) {
644                     LOG.debug("Tx {} Shard {} has no leader yet - scheduling create Tx retry",
645                             identifier, shardName);
646
647                     actorContext.getActorSystem().scheduler().scheduleOnce(CREATE_TX_TRY_INTERVAL,
648                             new Runnable() {
649                                 @Override
650                                 public void run() {
651                                     tryCreateTransaction();
652                                 }
653                             }, actorContext.getActorSystem().dispatcher());
654                     return;
655                 }
656             }
657
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());
674
675                     localTransactionContext = new NoOpTransactionContext(failure, identifier);
676                 } else if (response.getClass().equals(CreateTransactionReply.SERIALIZABLE_CLASS)) {
677                     localTransactionContext = createValidTransactionContext(
678                             CreateTransactionReply.fromSerializable(response));
679                 } else {
680                     IllegalArgumentException exception = new IllegalArgumentException(String.format(
681                         "Invalid reply type %s for CreateTransaction", response.getClass()));
682
683                     localTransactionContext = new NoOpTransactionContext(exception, identifier);
684                 }
685
686                 for(TransactionOperation oper: txOperationsOnComplete) {
687                     oper.invoke(localTransactionContext);
688                 }
689
690                 txOperationsOnComplete.clear();
691
692                 // We're done invoking the TransactionOperations so we can now publish the
693                 // TransactionContext.
694                 transactionContext = localTransactionContext;
695             }
696         }
697
698         private TransactionContext createValidTransactionContext(CreateTransactionReply reply) {
699             String transactionPath = reply.getTransactionPath();
700
701             LOG.debug("Tx {} Received transaction actor path {}", identifier, transactionPath);
702
703             ActorSelection transactionActor = actorContext.actorSelection(transactionPath);
704
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);
709
710                 // Write to the memory barrier volatile to publish the above update to the
711                 // remoteTransactionActors list for thread visibility.
712                 remoteTransactionActorsMB.set(true);
713             }
714
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);
718
719             return new TransactionContextImpl(transactionPath, transactionActor, identifier,
720                 actorContext, schemaContext, isTxActorLocal, reply.getVersion());
721         }
722     }
723
724     private interface TransactionContext {
725         void closeTransaction();
726
727         Future<ActorSelection> readyTransaction();
728
729         void writeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data);
730
731         void deleteData(YangInstanceIdentifier path);
732
733         void mergeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data);
734
735         CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readData(
736                 final YangInstanceIdentifier path);
737
738         CheckedFuture<Boolean, ReadFailedException> dataExists(YangInstanceIdentifier path);
739
740         List<Future<Object>> getRecordedOperationFutures();
741     }
742
743     private static abstract class AbstractTransactionContext implements TransactionContext {
744
745         protected final TransactionIdentifier identifier;
746         protected final List<Future<Object>> recordedOperationFutures = Lists.newArrayList();
747
748         AbstractTransactionContext(TransactionIdentifier identifier) {
749             this.identifier = identifier;
750         }
751
752         @Override
753         public List<Future<Object>> getRecordedOperationFutures() {
754             return recordedOperationFutures;
755         }
756     }
757
758     private static class TransactionContextImpl extends AbstractTransactionContext {
759         private final Logger LOG = LoggerFactory.getLogger(TransactionContextImpl.class);
760
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;
767
768         private TransactionContextImpl(String transactionPath, ActorSelection actor, TransactionIdentifier identifier,
769                 ActorContext actorContext, SchemaContext schemaContext,
770                 boolean isTxActorLocal, int remoteTransactionVersion) {
771             super(identifier);
772             this.transactionPath = transactionPath;
773             this.actor = actor;
774             this.actorContext = actorContext;
775             this.schemaContext = schemaContext;
776             this.isTxActorLocal = isTxActorLocal;
777             this.remoteTransactionVersion = remoteTransactionVersion;
778         }
779
780         private ActorSelection getActor() {
781             return actor;
782         }
783
784         private Future<Object> executeOperationAsync(SerializableMessage msg) {
785             return actorContext.executeOperationAsync(getActor(), isTxActorLocal ? msg : msg.toSerializable());
786         }
787
788         @Override
789         public void closeTransaction() {
790             LOG.debug("Tx {} closeTransaction called", identifier);
791
792             actorContext.sendOperationAsync(getActor(), new CloseTransaction().toSerializable());
793         }
794
795         @Override
796         public Future<ActorSelection> readyTransaction() {
797             LOG.debug("Tx {} readyTransaction called with {} previous recorded operations pending",
798                     identifier, recordedOperationFutures.size());
799
800             // Send the ReadyTransaction message to the Tx actor.
801
802             final Future<Object> replyFuture = executeOperationAsync(new ReadyTransaction());
803
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.
808
809             List<Future<Object>> futureList =
810                     Lists.newArrayListWithCapacity(recordedOperationFutures.size() + 1);
811             futureList.addAll(recordedOperationFutures);
812             futureList.add(replyFuture);
813
814             Future<Iterable<Object>> combinedFutures = akka.dispatch.Futures.sequence(futureList,
815                     actorContext.getActorSystem().dispatcher());
816
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.
819
820             return combinedFutures.transform(new Mapper<Iterable<Object>, ActorSelection>() {
821                 @Override
822                 public ActorSelection checkedApply(Iterable<Object> notUsed) {
823                     LOG.debug("Tx {} readyTransaction: pending recorded operations succeeded",
824                             identifier);
825
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.
832
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());
837
838                     } else if(serializedReadyReply.getClass().equals(ReadyTransactionReply.SERIALIZABLE_CLASS)) {
839                         ReadyTransactionReply reply = ReadyTransactionReply.fromSerializable(serializedReadyReply);
840                         String cohortPath = reply.getCohortPath();
841
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);
851                         }
852
853                         return actorContext.actorSelection(cohortPath);
854
855                     } else {
856                         // Throwing an exception here will fail the Future.
857                         throw new IllegalArgumentException(String.format("Invalid reply type {}",
858                                 serializedReadyReply.getClass()));
859                     }
860                 }
861             }, SAME_FAILURE_TRANSFORMER, actorContext.getActorSystem().dispatcher());
862         }
863
864         @Override
865         public void deleteData(YangInstanceIdentifier path) {
866             LOG.debug("Tx {} deleteData called path = {}", identifier, path);
867
868             recordedOperationFutures.add(executeOperationAsync(new DeleteData(path)));
869         }
870
871         @Override
872         public void mergeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
873             LOG.debug("Tx {} mergeData called path = {}", identifier, path);
874
875             recordedOperationFutures.add(executeOperationAsync(new MergeData(path, data, schemaContext)));
876         }
877
878         @Override
879         public void writeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
880             LOG.debug("Tx {} writeData called path = {}", identifier, path);
881
882             recordedOperationFutures.add(executeOperationAsync(new WriteData(path, data, schemaContext)));
883         }
884
885         @Override
886         public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readData(
887                 final YangInstanceIdentifier path) {
888
889             LOG.debug("Tx {} readData called path = {}", identifier, path);
890
891             final SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture = SettableFuture.create();
892
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.
896
897             if(recordedOperationFutures.isEmpty()) {
898                 finishReadData(path, returnFuture);
899             } else {
900                 LOG.debug("Tx {} readData: verifying {} previous recorded operations",
901                         identifier, recordedOperationFutures.size());
902
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.
906
907                 Future<Iterable<Object>> combinedFutures = akka.dispatch.Futures.sequence(
908                         Lists.newArrayList(recordedOperationFutures),
909                         actorContext.getActorSystem().dispatcher());
910
911                 OnComplete<Iterable<Object>> onComplete = new OnComplete<Iterable<Object>>() {
912                     @Override
913                     public void onComplete(Throwable failure, Iterable<Object> notUsed)
914                             throws Throwable {
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));
921                         } else {
922                             finishReadData(path, returnFuture);
923                         }
924                     }
925                 };
926
927                 combinedFutures.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
928             }
929
930             return MappingCheckedFuture.create(returnFuture, ReadFailedException.MAPPER);
931         }
932
933         private void finishReadData(final YangInstanceIdentifier path,
934                 final SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture) {
935
936             LOG.debug("Tx {} finishReadData called path = {}", identifier, path);
937
938             OnComplete<Object> onComplete = new OnComplete<Object>() {
939                 @Override
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));
945
946                     } else {
947                         LOG.debug("Tx {} read operation succeeded", identifier, failure);
948
949                         if (readResponse instanceof ReadDataReply) {
950                             ReadDataReply reply = (ReadDataReply) readResponse;
951                             returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
952
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()));
956
957                         } else {
958                             returnFuture.setException(new ReadFailedException(
959                                 "Invalid response reading data for path " + path));
960                         }
961                     }
962                 }
963             };
964
965             Future<Object> readFuture = executeOperationAsync(new ReadData(path));
966
967             readFuture.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
968         }
969
970         @Override
971         public CheckedFuture<Boolean, ReadFailedException> dataExists(
972                 final YangInstanceIdentifier path) {
973
974             LOG.debug("Tx {} dataExists called path = {}", identifier, path);
975
976             final SettableFuture<Boolean> returnFuture = SettableFuture.create();
977
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
981             // request.
982
983             if(recordedOperationFutures.isEmpty()) {
984                 finishDataExists(path, returnFuture);
985             } else {
986                 LOG.debug("Tx {} dataExists: verifying {} previous recorded operations",
987                         identifier, recordedOperationFutures.size());
988
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.
992
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>>() {
997                     @Override
998                     public void onComplete(Throwable failure, Iterable<Object> notUsed)
999                             throws Throwable {
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));
1006                         } else {
1007                             finishDataExists(path, returnFuture);
1008                         }
1009                     }
1010                 };
1011
1012                 combinedFutures.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
1013             }
1014
1015             return MappingCheckedFuture.create(returnFuture, ReadFailedException.MAPPER);
1016         }
1017
1018         private void finishDataExists(final YangInstanceIdentifier path,
1019                 final SettableFuture<Boolean> returnFuture) {
1020
1021             LOG.debug("Tx {} finishDataExists called path = {}", identifier, path);
1022
1023             OnComplete<Object> onComplete = new OnComplete<Object>() {
1024                 @Override
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));
1030                     } else {
1031                         LOG.debug("Tx {} dataExists operation succeeded", identifier, failure);
1032
1033                         if (response instanceof DataExistsReply) {
1034                             returnFuture.set(Boolean.valueOf(((DataExistsReply) response).exists()));
1035
1036                         } else if (response.getClass().equals(DataExistsReply.SERIALIZABLE_CLASS)) {
1037                             returnFuture.set(Boolean.valueOf(DataExistsReply.fromSerializable(response).exists()));
1038
1039                         } else {
1040                             returnFuture.setException(new ReadFailedException(
1041                                     "Invalid response checking exists for path " + path));
1042                         }
1043                     }
1044                 }
1045             };
1046
1047             Future<Object> future = executeOperationAsync(new DataExists(path));
1048
1049             future.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
1050         }
1051     }
1052
1053     private static class NoOpTransactionContext extends AbstractTransactionContext {
1054
1055         private final Logger LOG = LoggerFactory.getLogger(NoOpTransactionContext.class);
1056
1057         private final Throwable failure;
1058
1059         public NoOpTransactionContext(Throwable failure, TransactionIdentifier identifier){
1060             super(identifier);
1061             this.failure = failure;
1062         }
1063
1064         @Override
1065         public void closeTransaction() {
1066             LOG.debug("NoOpTransactionContext {} closeTransaction called", identifier);
1067         }
1068
1069         @Override
1070         public Future<ActorSelection> readyTransaction() {
1071             LOG.debug("Tx {} readyTransaction called", identifier);
1072             return akka.dispatch.Futures.failed(failure);
1073         }
1074
1075         @Override
1076         public void deleteData(YangInstanceIdentifier path) {
1077             LOG.debug("Tx {} deleteData called path = {}", identifier, path);
1078         }
1079
1080         @Override
1081         public void mergeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
1082             LOG.debug("Tx {} mergeData called path = {}", identifier, path);
1083         }
1084
1085         @Override
1086         public void writeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
1087             LOG.debug("Tx {} writeData called path = {}", identifier, path);
1088         }
1089
1090         @Override
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));
1096         }
1097
1098         @Override
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));
1104         }
1105     }
1106 }