Refactor LegacyTransactionConntextImpl
[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.ListenableFuture;
22 import com.google.common.util.concurrent.SettableFuture;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.Semaphore;
31 import java.util.concurrent.TimeUnit;
32 import java.util.concurrent.atomic.AtomicBoolean;
33 import java.util.concurrent.atomic.AtomicLong;
34 import javax.annotation.concurrent.GuardedBy;
35 import org.opendaylight.controller.cluster.datastore.compat.PreLithiumTransactionContextImpl;
36 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
37 import org.opendaylight.controller.cluster.datastore.identifiers.TransactionIdentifier;
38 import org.opendaylight.controller.cluster.datastore.messages.CloseTransaction;
39 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
40 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
41 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
42 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
43 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
44 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
45 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
46 import org.opendaylight.yangtools.util.concurrent.MappingCheckedFuture;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
49 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import scala.concurrent.Future;
53 import scala.concurrent.Promise;
54 import scala.concurrent.duration.FiniteDuration;
55
56 /**
57  * TransactionProxy acts as a proxy for one or more transactions that were created on a remote shard
58  * <p>
59  * Creating a transaction on the consumer side will create one instance of a transaction proxy. If during
60  * the transaction reads and writes are done on data that belongs to different shards then a separate transaction will
61  * be created on each of those shards by the TransactionProxy
62  *</p>
63  * <p>
64  * The TransactionProxy does not make any guarantees about atomicity or order in which the transactions on the various
65  * shards will be executed.
66  * </p>
67  */
68 public class TransactionProxy implements DOMStoreReadWriteTransaction {
69
70     public static enum TransactionType {
71         READ_ONLY,
72         WRITE_ONLY,
73         READ_WRITE
74     }
75
76     static final Mapper<Throwable, Throwable> SAME_FAILURE_TRANSFORMER =
77                                                               new Mapper<Throwable, Throwable>() {
78         @Override
79         public Throwable apply(Throwable failure) {
80             return failure;
81         }
82     };
83
84     private static final AtomicLong counter = new AtomicLong();
85
86     private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
87
88     /**
89      * Time interval in between transaction create retries.
90      */
91     private static final FiniteDuration CREATE_TX_TRY_INTERVAL =
92             FiniteDuration.create(1, TimeUnit.SECONDS);
93
94     /**
95      * Used to enqueue the PhantomReferences for read-only TransactionProxy instances. The
96      * FinalizableReferenceQueue is safe to use statically in an OSGi environment as it uses some
97      * trickery to clean up its internal thread when the bundle is unloaded.
98      */
99     private static final FinalizableReferenceQueue phantomReferenceQueue =
100                                                                   new FinalizableReferenceQueue();
101
102     /**
103      * This stores the TransactionProxyCleanupPhantomReference instances statically, This is
104      * necessary because PhantomReferences need a hard reference so they're not garbage collected.
105      * Once finalized, the TransactionProxyCleanupPhantomReference removes itself from this map
106      * and thus becomes eligible for garbage collection.
107      */
108     private static final Map<TransactionProxyCleanupPhantomReference,
109                              TransactionProxyCleanupPhantomReference> phantomReferenceCache =
110                                                                         new ConcurrentHashMap<>();
111
112     /**
113      * A PhantomReference that closes remote transactions for a TransactionProxy when it's
114      * garbage collected. This is used for read-only transactions as they're not explicitly closed
115      * by clients. So the only way to detect that a transaction is no longer in use and it's safe
116      * to clean up is when it's garbage collected. It's inexact as to when an instance will be GC'ed
117      * but TransactionProxy instances should generally be short-lived enough to avoid being moved
118      * to the old generation space and thus should be cleaned up in a timely manner as the GC
119      * runs on the young generation (eden, swap1...) space much more frequently.
120      */
121     private static class TransactionProxyCleanupPhantomReference
122                                            extends FinalizablePhantomReference<TransactionProxy> {
123
124         private final List<ActorSelection> remoteTransactionActors;
125         private final AtomicBoolean remoteTransactionActorsMB;
126         private final ActorContext actorContext;
127         private final TransactionIdentifier identifier;
128
129         protected TransactionProxyCleanupPhantomReference(TransactionProxy referent) {
130             super(referent, phantomReferenceQueue);
131
132             // Note we need to cache the relevant fields from the TransactionProxy as we can't
133             // have a hard reference to the TransactionProxy instance itself.
134
135             remoteTransactionActors = referent.remoteTransactionActors;
136             remoteTransactionActorsMB = referent.remoteTransactionActorsMB;
137             actorContext = referent.actorContext;
138             identifier = referent.identifier;
139         }
140
141         @Override
142         public void finalizeReferent() {
143             LOG.trace("Cleaning up {} Tx actors for TransactionProxy {}",
144                     remoteTransactionActors.size(), identifier);
145
146             phantomReferenceCache.remove(this);
147
148             // Access the memory barrier volatile to ensure all previous updates to the
149             // remoteTransactionActors list are visible to this thread.
150
151             if(remoteTransactionActorsMB.get()) {
152                 for(ActorSelection actor : remoteTransactionActors) {
153                     LOG.trace("Sending CloseTransaction to {}", actor);
154                     actorContext.sendOperationAsync(actor, CloseTransaction.INSTANCE.toSerializable());
155                 }
156             }
157         }
158     }
159
160     /**
161      * Stores the remote Tx actors for each requested data store path to be used by the
162      * PhantomReference to close the remote Tx's. This is only used for read-only Tx's. The
163      * remoteTransactionActorsMB volatile serves as a memory barrier to publish updates to the
164      * remoteTransactionActors list so they will be visible to the thread accessing the
165      * PhantomReference.
166      */
167     private List<ActorSelection> remoteTransactionActors;
168     private volatile AtomicBoolean remoteTransactionActorsMB;
169
170     /**
171      * Stores the create transaction results per shard.
172      */
173     private final Map<String, TransactionFutureCallback> txFutureCallbackMap = new HashMap<>();
174
175     private final TransactionType transactionType;
176     private final ActorContext actorContext;
177     private final TransactionIdentifier identifier;
178     private final String transactionChainId;
179     private final SchemaContext schemaContext;
180     private boolean inReadyState;
181
182     private volatile boolean initialized;
183     private Semaphore operationLimiter;
184     private OperationCompleter operationCompleter;
185
186     public TransactionProxy(ActorContext actorContext, TransactionType transactionType) {
187         this(actorContext, transactionType, "");
188     }
189
190     public TransactionProxy(ActorContext actorContext, TransactionType transactionType,
191             String transactionChainId) {
192         this.actorContext = Preconditions.checkNotNull(actorContext,
193             "actorContext should not be null");
194         this.transactionType = Preconditions.checkNotNull(transactionType,
195             "transactionType should not be null");
196         this.schemaContext = Preconditions.checkNotNull(actorContext.getSchemaContext(),
197             "schemaContext should not be null");
198         this.transactionChainId = transactionChainId;
199
200         String memberName = actorContext.getCurrentMemberName();
201         if(memberName == null){
202             memberName = "UNKNOWN-MEMBER";
203         }
204
205         this.identifier = new TransactionIdentifier(memberName, counter.getAndIncrement());
206
207         LOG.debug("Created txn {} of type {} on chain {}", identifier, transactionType, transactionChainId);
208     }
209
210     @VisibleForTesting
211     List<Future<Object>> getRecordedOperationFutures() {
212         List<Future<Object>> recordedOperationFutures = Lists.newArrayList();
213         for(TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) {
214             TransactionContext transactionContext = txFutureCallback.getTransactionContext();
215             if(transactionContext != null) {
216                 recordedOperationFutures.addAll(transactionContext.getRecordedOperationFutures());
217             }
218         }
219
220         return recordedOperationFutures;
221     }
222
223     @VisibleForTesting
224     boolean hasTransactionContext() {
225         for(TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) {
226             TransactionContext transactionContext = txFutureCallback.getTransactionContext();
227             if(transactionContext != null) {
228                 return true;
229             }
230         }
231
232         return false;
233     }
234
235     @Override
236     public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final YangInstanceIdentifier path) {
237
238         Preconditions.checkState(transactionType != TransactionType.WRITE_ONLY,
239                 "Read operation on write-only transaction is not allowed");
240
241         LOG.debug("Tx {} read {}", identifier, path);
242
243         throttleOperation();
244
245         final SettableFuture<Optional<NormalizedNode<?, ?>>> proxyFuture = SettableFuture.create();
246
247         TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
248         txFutureCallback.enqueueTransactionOperation(new TransactionOperation() {
249             @Override
250             public void invoke(TransactionContext transactionContext) {
251                 transactionContext.readData(path, proxyFuture);
252             }
253         });
254
255         return MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
256     }
257
258     @Override
259     public CheckedFuture<Boolean, ReadFailedException> exists(final YangInstanceIdentifier path) {
260
261         Preconditions.checkState(transactionType != TransactionType.WRITE_ONLY,
262                 "Exists operation on write-only transaction is not allowed");
263
264         LOG.debug("Tx {} exists {}", identifier, path);
265
266         throttleOperation();
267
268         final SettableFuture<Boolean> proxyFuture = SettableFuture.create();
269
270         TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
271         txFutureCallback.enqueueTransactionOperation(new TransactionOperation() {
272             @Override
273             public void invoke(TransactionContext transactionContext) {
274                 transactionContext.dataExists(path, proxyFuture);
275             }
276         });
277
278         return MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
279     }
280
281     private void checkModificationState() {
282         Preconditions.checkState(transactionType != TransactionType.READ_ONLY,
283                 "Modification operation on read-only transaction is not allowed");
284         Preconditions.checkState(!inReadyState,
285                 "Transaction is sealed - further modifications are not allowed");
286     }
287
288     private void throttleOperation() {
289         throttleOperation(1);
290     }
291
292     private void throttleOperation(int acquirePermits) {
293         if(!initialized) {
294             // Note : Currently mailbox-capacity comes from akka.conf and not from the config-subsystem
295             operationLimiter = new Semaphore(actorContext.getTransactionOutstandingOperationLimit());
296             operationCompleter = new OperationCompleter(operationLimiter);
297
298             // Make sure we write this last because it's volatile and will also publish the non-volatile writes
299             // above as well so they'll be visible to other threads.
300             initialized = true;
301         }
302
303         try {
304             if(!operationLimiter.tryAcquire(acquirePermits,
305                     actorContext.getDatastoreContext().getOperationTimeoutInSeconds(), TimeUnit.SECONDS)){
306                 LOG.warn("Failed to acquire operation permit for transaction {}", getIdentifier());
307             }
308         } catch (InterruptedException e) {
309             if(LOG.isDebugEnabled()) {
310                 LOG.debug("Interrupted when trying to acquire operation permit for transaction " + getIdentifier().toString(), e);
311             } else {
312                 LOG.warn("Interrupted when trying to acquire operation permit for transaction {}", getIdentifier());
313             }
314         }
315     }
316
317
318     @Override
319     public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
320
321         checkModificationState();
322
323         LOG.debug("Tx {} write {}", identifier, path);
324
325         throttleOperation();
326
327         TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
328         txFutureCallback.enqueueTransactionOperation(new TransactionOperation() {
329             @Override
330             public void invoke(TransactionContext transactionContext) {
331                 transactionContext.writeData(path, data);
332             }
333         });
334     }
335
336     @Override
337     public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
338
339         checkModificationState();
340
341         LOG.debug("Tx {} merge {}", identifier, path);
342
343         throttleOperation();
344
345         TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
346         txFutureCallback.enqueueTransactionOperation(new TransactionOperation() {
347             @Override
348             public void invoke(TransactionContext transactionContext) {
349                 transactionContext.mergeData(path, data);
350             }
351         });
352     }
353
354     @Override
355     public void delete(final YangInstanceIdentifier path) {
356
357         checkModificationState();
358
359         LOG.debug("Tx {} delete {}", identifier, path);
360
361         throttleOperation();
362
363         TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
364         txFutureCallback.enqueueTransactionOperation(new TransactionOperation() {
365             @Override
366             public void invoke(TransactionContext transactionContext) {
367                 transactionContext.deleteData(path);
368             }
369         });
370     }
371
372     @Override
373     public DOMStoreThreePhaseCommitCohort ready() {
374
375         checkModificationState();
376
377         inReadyState = true;
378
379         LOG.debug("Tx {} Readying {} transactions for commit", identifier,
380                     txFutureCallbackMap.size());
381
382         if(txFutureCallbackMap.size() == 0) {
383             onTransactionReady(Collections.<Future<ActorSelection>>emptyList());
384             return NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
385         }
386
387         throttleOperation(txFutureCallbackMap.size());
388
389         List<Future<ActorSelection>> cohortFutures = Lists.newArrayList();
390
391         for(TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) {
392
393             LOG.debug("Tx {} Readying transaction for shard {} chain {}", identifier,
394                         txFutureCallback.getShardName(), transactionChainId);
395
396             final TransactionContext transactionContext = txFutureCallback.getTransactionContext();
397             final Future<ActorSelection> future;
398             if (transactionContext != null) {
399                 // avoid the creation of a promise and a TransactionOperation
400                 future = transactionContext.readyTransaction();
401             } else {
402                 final Promise<ActorSelection> promise = akka.dispatch.Futures.promise();
403                 txFutureCallback.enqueueTransactionOperation(new TransactionOperation() {
404                     @Override
405                     public void invoke(TransactionContext transactionContext) {
406                         promise.completeWith(transactionContext.readyTransaction());
407                     }
408                 });
409                 future = promise.future();
410             }
411
412             cohortFutures.add(future);
413         }
414
415         onTransactionReady(cohortFutures);
416
417         return new ThreePhaseCommitCohortProxy(actorContext, cohortFutures,
418                 identifier.toString());
419     }
420
421     /**
422      * Method for derived classes to be notified when the transaction has been readied.
423      *
424      * @param cohortFutures the cohort Futures for each shard transaction.
425      */
426     protected void onTransactionReady(List<Future<ActorSelection>> cohortFutures) {
427     }
428
429     /**
430      * Method called to send a CreateTransaction message to a shard.
431      *
432      * @param shard the shard actor to send to
433      * @param serializedCreateMessage the serialized message to send
434      * @return the response Future
435      */
436     protected Future<Object> sendCreateTransaction(ActorSelection shard,
437             Object serializedCreateMessage) {
438         return actorContext.executeOperationAsync(shard, serializedCreateMessage);
439     }
440
441     @Override
442     public Object getIdentifier() {
443         return this.identifier;
444     }
445
446     @Override
447     public void close() {
448         for (TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) {
449             txFutureCallback.enqueueTransactionOperation(new TransactionOperation() {
450                 @Override
451                 public void invoke(TransactionContext transactionContext) {
452                     transactionContext.closeTransaction();
453                 }
454             });
455         }
456
457         txFutureCallbackMap.clear();
458
459         if(remoteTransactionActorsMB != null) {
460             remoteTransactionActors.clear();
461             remoteTransactionActorsMB.set(true);
462         }
463     }
464
465     private String shardNameFromIdentifier(YangInstanceIdentifier path){
466         return ShardStrategyFactory.getStrategy(path).findShard(path);
467     }
468
469     private TransactionFutureCallback getOrCreateTxFutureCallback(YangInstanceIdentifier path) {
470         String shardName = shardNameFromIdentifier(path);
471         TransactionFutureCallback txFutureCallback = txFutureCallbackMap.get(shardName);
472         if(txFutureCallback == null) {
473             Future<ActorSelection> findPrimaryFuture = actorContext.findPrimaryShardAsync(shardName);
474
475             final TransactionFutureCallback newTxFutureCallback =
476                     new TransactionFutureCallback(shardName);
477
478             txFutureCallback = newTxFutureCallback;
479             txFutureCallbackMap.put(shardName, txFutureCallback);
480
481             findPrimaryFuture.onComplete(new OnComplete<ActorSelection>() {
482                 @Override
483                 public void onComplete(Throwable failure, ActorSelection primaryShard) {
484                     if(failure != null) {
485                         newTxFutureCallback.onComplete(failure, null);
486                     } else {
487                         newTxFutureCallback.setPrimaryShard(primaryShard);
488                     }
489                 }
490             }, actorContext.getClientDispatcher());
491         }
492
493         return txFutureCallback;
494     }
495
496     public String getTransactionChainId() {
497         return transactionChainId;
498     }
499
500     protected ActorContext getActorContext() {
501         return actorContext;
502     }
503
504     /**
505      * Interfaces for transaction operations to be invoked later.
506      */
507     private static interface TransactionOperation {
508         void invoke(TransactionContext transactionContext);
509     }
510
511     /**
512      * Implements a Future OnComplete callback for a CreateTransaction message. This class handles
513      * retries, up to a limit, if the shard doesn't have a leader yet. This is done by scheduling a
514      * retry task after a short delay.
515      * <p>
516      * The end result from a completed CreateTransaction message is a TransactionContext that is
517      * used to perform transaction operations. Transaction operations that occur before the
518      * CreateTransaction completes are cache and executed once the CreateTransaction completes,
519      * successfully or not.
520      */
521     private class TransactionFutureCallback extends OnComplete<Object> {
522
523         /**
524          * The list of transaction operations to execute once the CreateTransaction completes.
525          */
526         @GuardedBy("txOperationsOnComplete")
527         private final List<TransactionOperation> txOperationsOnComplete = Lists.newArrayList();
528
529         /**
530          * The TransactionContext resulting from the CreateTransaction reply.
531          */
532         private volatile TransactionContext transactionContext;
533
534         /**
535          * The target primary shard.
536          */
537         private volatile ActorSelection primaryShard;
538
539         private volatile int createTxTries = (int) (actorContext.getDatastoreContext().
540                 getShardLeaderElectionTimeout().duration().toMillis() /
541                 CREATE_TX_TRY_INTERVAL.toMillis());
542
543         private final String shardName;
544
545         TransactionFutureCallback(String shardName) {
546             this.shardName = shardName;
547         }
548
549         String getShardName() {
550             return shardName;
551         }
552
553         TransactionContext getTransactionContext() {
554             return transactionContext;
555         }
556
557
558         /**
559          * Sets the target primary shard and initiates a CreateTransaction try.
560          */
561         void setPrimaryShard(ActorSelection primaryShard) {
562             LOG.debug("Tx {} Primary shard found - trying create transaction", identifier);
563
564             this.primaryShard = primaryShard;
565             tryCreateTransaction();
566         }
567
568         /**
569          * Adds a TransactionOperation to be executed after the CreateTransaction completes.
570          */
571         void addTxOperationOnComplete(TransactionOperation operation) {
572             boolean invokeOperation = true;
573             synchronized(txOperationsOnComplete) {
574                 if(transactionContext == null) {
575                     LOG.debug("Tx {} Adding operation on complete {}", identifier);
576
577                     invokeOperation = false;
578                     txOperationsOnComplete.add(operation);
579                 }
580             }
581
582             if(invokeOperation) {
583                 operation.invoke(transactionContext);
584             }
585         }
586
587         void enqueueTransactionOperation(final TransactionOperation op) {
588
589             if (transactionContext != null) {
590                 op.invoke(transactionContext);
591             } else {
592                 // The shard Tx hasn't been created yet so add the Tx operation to the Tx Future
593                 // callback to be executed after the Tx is created.
594                 addTxOperationOnComplete(op);
595             }
596         }
597
598         /**
599          * Performs a CreateTransaction try async.
600          */
601         private void tryCreateTransaction() {
602             Future<Object> createTxFuture = sendCreateTransaction(primaryShard,
603                     new CreateTransaction(identifier.toString(),
604                             TransactionProxy.this.transactionType.ordinal(),
605                             getTransactionChainId()).toSerializable());
606
607             createTxFuture.onComplete(this, actorContext.getClientDispatcher());
608         }
609
610         @Override
611         public void onComplete(Throwable failure, Object response) {
612             if(failure instanceof NoShardLeaderException) {
613                 // There's no leader for the shard yet - schedule and try again, unless we're out
614                 // of retries. Note: createTxTries is volatile as it may be written by different
615                 // threads however not concurrently, therefore decrementing it non-atomically here
616                 // is ok.
617                 if(--createTxTries > 0) {
618                     LOG.debug("Tx {} Shard {} has no leader yet - scheduling create Tx retry",
619                             identifier, shardName);
620
621                     actorContext.getActorSystem().scheduler().scheduleOnce(CREATE_TX_TRY_INTERVAL,
622                             new Runnable() {
623                                 @Override
624                                 public void run() {
625                                     tryCreateTransaction();
626                                 }
627                             }, actorContext.getClientDispatcher());
628                     return;
629                 }
630             }
631
632             // Mainly checking for state violation here to perform a volatile read of "initialized" to
633             // ensure updates to operationLimter et al are visible to this thread (ie we're doing
634             // "piggy-back" synchronization here).
635             Preconditions.checkState(initialized, "Tx was not propertly initialized.");
636
637             // Create the TransactionContext from the response or failure. Store the new
638             // TransactionContext locally until we've completed invoking the
639             // TransactionOperations. This avoids thread timing issues which could cause
640             // out-of-order TransactionOperations. Eg, on a modification operation, if the
641             // TransactionContext is non-null, then we directly call the TransactionContext.
642             // However, at the same time, the code may be executing the cached
643             // TransactionOperations. So to avoid thus timing, we don't publish the
644             // TransactionContext until after we've executed all cached TransactionOperations.
645             TransactionContext localTransactionContext;
646             if(failure != null) {
647                 LOG.debug("Tx {} Creating NoOpTransaction because of error: {}", identifier,
648                         failure.getMessage());
649
650                 localTransactionContext = new NoOpTransactionContext(failure, identifier, operationLimiter);
651             } else if (response.getClass().equals(CreateTransactionReply.SERIALIZABLE_CLASS)) {
652                 localTransactionContext = createValidTransactionContext(
653                         CreateTransactionReply.fromSerializable(response));
654             } else {
655                 IllegalArgumentException exception = new IllegalArgumentException(String.format(
656                         "Invalid reply type %s for CreateTransaction", response.getClass()));
657
658                 localTransactionContext = new NoOpTransactionContext(exception, identifier, operationLimiter);
659             }
660
661             executeTxOperatonsOnComplete(localTransactionContext);
662         }
663
664         private void executeTxOperatonsOnComplete(TransactionContext localTransactionContext) {
665             while(true) {
666                 // Access to txOperationsOnComplete and transactionContext must be protected and atomic
667                 // (ie synchronized) with respect to #addTxOperationOnComplete to handle timing
668                 // issues and ensure no TransactionOperation is missed and that they are processed
669                 // in the order they occurred.
670
671                 // We'll make a local copy of the txOperationsOnComplete list to handle re-entrancy
672                 // in case a TransactionOperation results in another transaction operation being
673                 // queued (eg a put operation from a client read Future callback that is notified
674                 // synchronously).
675                 Collection<TransactionOperation> operationsBatch = null;
676                 synchronized(txOperationsOnComplete) {
677                     if(txOperationsOnComplete.isEmpty()) {
678                         // We're done invoking the TransactionOperations so we can now publish the
679                         // TransactionContext.
680                         transactionContext = localTransactionContext;
681                         break;
682                     }
683
684                     operationsBatch = new ArrayList<>(txOperationsOnComplete);
685                     txOperationsOnComplete.clear();
686                 }
687
688                 // Invoke TransactionOperations outside the sync block to avoid unnecessary blocking.
689                 // A slight down-side is that we need to re-acquire the lock below but this should
690                 // be negligible.
691                 for(TransactionOperation oper: operationsBatch) {
692                     oper.invoke(localTransactionContext);
693                 }
694             }
695         }
696
697         private TransactionContext createValidTransactionContext(CreateTransactionReply reply) {
698             String transactionPath = reply.getTransactionPath();
699
700             LOG.debug("Tx {} Received {}", identifier, reply);
701
702             ActorSelection transactionActor = actorContext.actorSelection(transactionPath);
703
704             if (transactionType == TransactionType.READ_ONLY) {
705                 // Read-only Tx's aren't explicitly closed by the client so we create a PhantomReference
706                 // to close the remote Tx's when this instance is no longer in use and is garbage
707                 // collected.
708
709                 if(remoteTransactionActorsMB == null) {
710                     remoteTransactionActors = Lists.newArrayList();
711                     remoteTransactionActorsMB = new AtomicBoolean();
712
713                     TransactionProxyCleanupPhantomReference cleanup =
714                             new TransactionProxyCleanupPhantomReference(TransactionProxy.this);
715                     phantomReferenceCache.put(cleanup, cleanup);
716                 }
717
718                 // Add the actor to the remoteTransactionActors list for access by the
719                 // cleanup PhantonReference.
720                 remoteTransactionActors.add(transactionActor);
721
722                 // Write to the memory barrier volatile to publish the above update to the
723                 // remoteTransactionActors list for thread visibility.
724                 remoteTransactionActorsMB.set(true);
725             }
726
727             // TxActor is always created where the leader of the shard is.
728             // Check if TxActor is created in the same node
729             boolean isTxActorLocal = actorContext.isPathLocal(transactionPath);
730
731             if(reply.getVersion() >= DataStoreVersions.LITHIUM_VERSION) {
732                 return new TransactionContextImpl(transactionPath, transactionActor, identifier,
733                     actorContext, schemaContext, isTxActorLocal, reply.getVersion(), operationCompleter);
734             } else {
735                 return new PreLithiumTransactionContextImpl(transactionPath, transactionActor, identifier,
736                         actorContext, schemaContext, isTxActorLocal, reply.getVersion(), operationCompleter);
737             }
738         }
739     }
740
741     private static class NoOpDOMStoreThreePhaseCommitCohort implements DOMStoreThreePhaseCommitCohort {
742         static NoOpDOMStoreThreePhaseCommitCohort INSTANCE = new NoOpDOMStoreThreePhaseCommitCohort();
743
744         private static final ListenableFuture<Void> IMMEDIATE_VOID_SUCCESS =
745                 com.google.common.util.concurrent.Futures.immediateFuture(null);
746         private static final ListenableFuture<Boolean> IMMEDIATE_BOOLEAN_SUCCESS =
747                 com.google.common.util.concurrent.Futures.immediateFuture(Boolean.TRUE);
748
749         private NoOpDOMStoreThreePhaseCommitCohort() {
750         }
751
752         @Override
753         public ListenableFuture<Boolean> canCommit() {
754             return IMMEDIATE_BOOLEAN_SUCCESS;
755         }
756
757         @Override
758         public ListenableFuture<Void> preCommit() {
759             return IMMEDIATE_VOID_SUCCESS;
760         }
761
762         @Override
763         public ListenableFuture<Void> abort() {
764             return IMMEDIATE_VOID_SUCCESS;
765         }
766
767         @Override
768         public ListenableFuture<Void> commit() {
769             return IMMEDIATE_VOID_SUCCESS;
770         }
771     }
772 }