Merge "Fix warnings in config-manager"
[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.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;
60
61 /**
62  * TransactionProxy acts as a proxy for one or more transactions that were created on a remote shard
63  * <p>
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
67  *</p>
68  * <p>
69  * The TransactionProxy does not make any guarantees about atomicity or order in which the transactions on the various
70  * shards will be executed.
71  * </p>
72  */
73 public class TransactionProxy implements DOMStoreReadWriteTransaction {
74
75     public static enum TransactionType {
76         READ_ONLY,
77         WRITE_ONLY,
78         READ_WRITE
79     }
80
81     static final Mapper<Throwable, Throwable> SAME_FAILURE_TRANSFORMER =
82                                                               new Mapper<Throwable, Throwable>() {
83         @Override
84         public Throwable apply(Throwable failure) {
85             return failure;
86         }
87     };
88
89     private static final AtomicLong counter = new AtomicLong();
90
91     private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
92
93     /**
94      * Time interval in between transaction create retries.
95      */
96     private static final FiniteDuration CREATE_TX_TRY_INTERVAL =
97             FiniteDuration.create(1, TimeUnit.SECONDS);
98
99     /**
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.
103      */
104     private static final FinalizableReferenceQueue phantomReferenceQueue =
105                                                                   new FinalizableReferenceQueue();
106
107     /**
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.
112      */
113     private static final Map<TransactionProxyCleanupPhantomReference,
114                              TransactionProxyCleanupPhantomReference> phantomReferenceCache =
115                                                                         new ConcurrentHashMap<>();
116
117     /**
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.
125      */
126     private static class TransactionProxyCleanupPhantomReference
127                                            extends FinalizablePhantomReference<TransactionProxy> {
128
129         private final List<ActorSelection> remoteTransactionActors;
130         private final AtomicBoolean remoteTransactionActorsMB;
131         private final ActorContext actorContext;
132         private final TransactionIdentifier identifier;
133
134         protected TransactionProxyCleanupPhantomReference(TransactionProxy referent) {
135             super(referent, phantomReferenceQueue);
136
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.
139
140             remoteTransactionActors = referent.remoteTransactionActors;
141             remoteTransactionActorsMB = referent.remoteTransactionActorsMB;
142             actorContext = referent.actorContext;
143             identifier = referent.identifier;
144         }
145
146         @Override
147         public void finalizeReferent() {
148             LOG.trace("Cleaning up {} Tx actors for TransactionProxy {}",
149                     remoteTransactionActors.size(), identifier);
150
151             phantomReferenceCache.remove(this);
152
153             // Access the memory barrier volatile to ensure all previous updates to the
154             // remoteTransactionActors list are visible to this thread.
155
156             if(remoteTransactionActorsMB.get()) {
157                 for(ActorSelection actor : remoteTransactionActors) {
158                     LOG.trace("Sending CloseTransaction to {}", actor);
159                     actorContext.sendOperationAsync(actor,
160                             new CloseTransaction().toSerializable());
161                 }
162             }
163         }
164     }
165
166     /**
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
171      * PhantomReference.
172      */
173     private List<ActorSelection> remoteTransactionActors;
174     private AtomicBoolean remoteTransactionActorsMB;
175
176     /**
177      * Stores the create transaction results per shard.
178      */
179     private final Map<String, TransactionFutureCallback> txFutureCallbackMap = new HashMap<>();
180
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;
187
188     public TransactionProxy(ActorContext actorContext, TransactionType transactionType) {
189         this(actorContext, transactionType, "");
190     }
191
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;
201
202         String memberName = actorContext.getCurrentMemberName();
203         if(memberName == null){
204             memberName = "UNKNOWN-MEMBER";
205         }
206
207         this.identifier = TransactionIdentifier.builder().memberName(memberName).counter(
208             counter.getAndIncrement()).build();
209
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
213             // collected.
214
215             remoteTransactionActors = Lists.newArrayList();
216             remoteTransactionActorsMB = new AtomicBoolean();
217
218             TransactionProxyCleanupPhantomReference cleanup =
219                 new TransactionProxyCleanupPhantomReference(this);
220             phantomReferenceCache.put(cleanup, cleanup);
221         }
222
223         LOG.debug("Created txn {} of type {}", identifier, transactionType);
224     }
225
226     @VisibleForTesting
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());
233             }
234         }
235
236         return recordedOperationFutures;
237     }
238
239     @VisibleForTesting
240     boolean hasTransactionContext() {
241         for(TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) {
242             TransactionContext transactionContext = txFutureCallback.getTransactionContext();
243             if(transactionContext != null) {
244                 return true;
245             }
246         }
247
248         return false;
249     }
250
251     @Override
252     public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(
253             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         TransactionContext transactionContext = txFutureCallback.getTransactionContext();
262
263         CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> future;
264         if(transactionContext != null) {
265             future = transactionContext.readData(path);
266         } else {
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() {
271                 @Override
272                 public void invoke(TransactionContext transactionContext) {
273                     Futures.addCallback(transactionContext.readData(path),
274                         new FutureCallback<Optional<NormalizedNode<?, ?>>>() {
275                             @Override
276                             public void onSuccess(Optional<NormalizedNode<?, ?>> data) {
277                                 proxyFuture.set(data);
278                             }
279
280                             @Override
281                             public void onFailure(Throwable t) {
282                                 proxyFuture.setException(t);
283                             }
284                         });
285                 }
286             });
287
288             future = MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
289         }
290
291         return future;
292     }
293
294     @Override
295     public CheckedFuture<Boolean, ReadFailedException> exists(final YangInstanceIdentifier path) {
296
297         Preconditions.checkState(transactionType != TransactionType.WRITE_ONLY,
298                 "Exists operation on write-only transaction is not allowed");
299
300         LOG.debug("Tx {} exists {}", identifier, path);
301
302         TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
303         TransactionContext transactionContext = txFutureCallback.getTransactionContext();
304
305         CheckedFuture<Boolean, ReadFailedException> future;
306         if(transactionContext != null) {
307             future = transactionContext.dataExists(path);
308         } else {
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() {
313                 @Override
314                 public void invoke(TransactionContext transactionContext) {
315                     Futures.addCallback(transactionContext.dataExists(path),
316                         new FutureCallback<Boolean>() {
317                             @Override
318                             public void onSuccess(Boolean exists) {
319                                 proxyFuture.set(exists);
320                             }
321
322                             @Override
323                             public void onFailure(Throwable t) {
324                                 proxyFuture.setException(t);
325                             }
326                         });
327                 }
328             });
329
330             future = MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
331         }
332
333         return future;
334     }
335
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");
341     }
342
343     @Override
344     public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
345
346         checkModificationState();
347
348         LOG.debug("Tx {} write {}", identifier, path);
349
350         TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
351         TransactionContext transactionContext = txFutureCallback.getTransactionContext();
352         if(transactionContext != null) {
353             transactionContext.writeData(path, data);
354         } else {
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() {
358                 @Override
359                 public void invoke(TransactionContext transactionContext) {
360                     transactionContext.writeData(path, data);
361                 }
362             });
363         }
364     }
365
366     @Override
367     public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
368
369         checkModificationState();
370
371         LOG.debug("Tx {} merge {}", identifier, path);
372
373         TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
374         TransactionContext transactionContext = txFutureCallback.getTransactionContext();
375         if(transactionContext != null) {
376             transactionContext.mergeData(path, data);
377         } else {
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() {
381                 @Override
382                 public void invoke(TransactionContext transactionContext) {
383                     transactionContext.mergeData(path, data);
384                 }
385             });
386         }
387     }
388
389     @Override
390     public void delete(final YangInstanceIdentifier path) {
391
392         checkModificationState();
393
394         LOG.debug("Tx {} delete {}", identifier, path);
395
396         TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path);
397         TransactionContext transactionContext = txFutureCallback.getTransactionContext();
398         if(transactionContext != null) {
399             transactionContext.deleteData(path);
400         } else {
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() {
404                 @Override
405                 public void invoke(TransactionContext transactionContext) {
406                     transactionContext.deleteData(path);
407                 }
408             });
409         }
410     }
411
412     @Override
413     public DOMStoreThreePhaseCommitCohort ready() {
414
415         checkModificationState();
416
417         inReadyState = true;
418
419         LOG.debug("Tx {} Readying {} transactions for commit", identifier,
420                     txFutureCallbackMap.size());
421
422         List<Future<ActorSelection>> cohortFutures = Lists.newArrayList();
423
424         for(TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) {
425
426             LOG.debug("Tx {} Readying transaction for shard {}", identifier,
427                         txFutureCallback.getShardName());
428
429             TransactionContext transactionContext = txFutureCallback.getTransactionContext();
430             if(transactionContext != null) {
431                 cohortFutures.add(transactionContext.readyTransaction());
432             } else {
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() {
437                     @Override
438                     public void invoke(TransactionContext transactionContext) {
439                         cohortPromise.completeWith(transactionContext.readyTransaction());
440                     }
441                 });
442
443                 cohortFutures.add(cohortPromise.future());
444             }
445         }
446
447         onTransactionReady(cohortFutures);
448
449         return new ThreePhaseCommitCohortProxy(actorContext, cohortFutures,
450                 identifier.toString());
451     }
452
453     /**
454      * Method for derived classes to be notified when the transaction has been readied.
455      *
456      * @param cohortFutures the cohort Futures for each shard transaction.
457      */
458     protected void onTransactionReady(List<Future<ActorSelection>> cohortFutures) {
459     }
460
461     /**
462      * Method called to send a CreateTransaction message to a shard.
463      *
464      * @param shard the shard actor to send to
465      * @param serializedCreateMessage the serialized message to send
466      * @return the response Future
467      */
468     protected Future<Object> sendCreateTransaction(ActorSelection shard,
469             Object serializedCreateMessage) {
470         return actorContext.executeOperationAsync(shard, serializedCreateMessage);
471     }
472
473     @Override
474     public Object getIdentifier() {
475         return this.identifier;
476     }
477
478     @Override
479     public void close() {
480         for(TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) {
481             TransactionContext transactionContext = txFutureCallback.getTransactionContext();
482             if(transactionContext != null) {
483                 transactionContext.closeTransaction();
484             } else {
485                 txFutureCallback.addTxOperationOnComplete(new TransactionOperation() {
486                     @Override
487                     public void invoke(TransactionContext transactionContext) {
488                         transactionContext.closeTransaction();
489                     }
490                 });
491             }
492         }
493
494         txFutureCallbackMap.clear();
495
496         if(transactionType == TransactionType.READ_ONLY) {
497             remoteTransactionActors.clear();
498             remoteTransactionActorsMB.set(true);
499         }
500     }
501
502     private String shardNameFromIdentifier(YangInstanceIdentifier path){
503         return ShardStrategyFactory.getStrategy(path).findShard(path);
504     }
505
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);
511
512             final TransactionFutureCallback newTxFutureCallback =
513                     new TransactionFutureCallback(shardName);
514
515             txFutureCallback = newTxFutureCallback;
516             txFutureCallbackMap.put(shardName, txFutureCallback);
517
518             findPrimaryFuture.onComplete(new OnComplete<ActorSelection>() {
519                 @Override
520                 public void onComplete(Throwable failure, ActorSelection primaryShard) {
521                     if(failure != null) {
522                         newTxFutureCallback.onComplete(failure, null);
523                     } else {
524                         newTxFutureCallback.setPrimaryShard(primaryShard);
525                     }
526                 }
527             }, actorContext.getActorSystem().dispatcher());
528         }
529
530         return txFutureCallback;
531     }
532
533     public String getTransactionChainId() {
534         return transactionChainId;
535     }
536
537     /**
538      * Interface for a transaction operation to be invoked later.
539      */
540     private static interface TransactionOperation {
541         void invoke(TransactionContext transactionContext);
542     }
543
544     /**
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.
548      * <p>
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.
553      */
554     private class TransactionFutureCallback extends OnComplete<Object> {
555
556         /**
557          * The list of transaction operations to execute once the CreateTransaction completes.
558          */
559         @GuardedBy("txOperationsOnComplete")
560         private final List<TransactionOperation> txOperationsOnComplete = Lists.newArrayList();
561
562         /**
563          * The TransactionContext resulting from the CreateTransaction reply.
564          */
565         private volatile TransactionContext transactionContext;
566
567         /**
568          * The target primary shard.
569          */
570         private volatile ActorSelection primaryShard;
571
572         private volatile int createTxTries = (int) (actorContext.getDatastoreContext().
573                 getShardLeaderElectionTimeout().duration().toMillis() /
574                 CREATE_TX_TRY_INTERVAL.toMillis());
575
576         private final String shardName;
577
578         TransactionFutureCallback(String shardName) {
579             this.shardName = shardName;
580         }
581
582         String getShardName() {
583             return shardName;
584         }
585
586         TransactionContext getTransactionContext() {
587             return transactionContext;
588         }
589
590
591         /**
592          * Sets the target primary shard and initiates a CreateTransaction try.
593          */
594         void setPrimaryShard(ActorSelection primaryShard) {
595             LOG.debug("Tx {} Primary shard found - trying create transaction", identifier);
596
597             this.primaryShard = primaryShard;
598             tryCreateTransaction();
599         }
600
601         /**
602          * Adds a TransactionOperation to be executed after the CreateTransaction completes.
603          */
604         void addTxOperationOnComplete(TransactionOperation operation) {
605             synchronized(txOperationsOnComplete) {
606                 if(transactionContext == null) {
607                     LOG.debug("Tx {} Adding operation on complete {}", identifier);
608
609                     txOperationsOnComplete.add(operation);
610                 } else {
611                     operation.invoke(transactionContext);
612                 }
613             }
614         }
615
616         /**
617          * Performs a CreateTransaction try async.
618          */
619         private void tryCreateTransaction() {
620             Future<Object> createTxFuture = sendCreateTransaction(primaryShard,
621                     new CreateTransaction(identifier.toString(),
622                             TransactionProxy.this.transactionType.ordinal(),
623                             getTransactionChainId()).toSerializable());
624
625             createTxFuture.onComplete(this, actorContext.getActorSystem().dispatcher());
626         }
627
628         @Override
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
634                 // is ok.
635                 if(--createTxTries > 0) {
636                     LOG.debug("Tx {} Shard {} has no leader yet - scheduling create Tx retry",
637                             identifier, shardName);
638
639                     actorContext.getActorSystem().scheduler().scheduleOnce(CREATE_TX_TRY_INTERVAL,
640                             new Runnable() {
641                                 @Override
642                                 public void run() {
643                                     tryCreateTransaction();
644                                 }
645                             }, actorContext.getActorSystem().dispatcher());
646                     return;
647                 }
648             }
649
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());
666
667                     localTransactionContext = new NoOpTransactionContext(failure, identifier);
668                 } else if (response.getClass().equals(CreateTransactionReply.SERIALIZABLE_CLASS)) {
669                     localTransactionContext = createValidTransactionContext(
670                             CreateTransactionReply.fromSerializable(response));
671                 } else {
672                     IllegalArgumentException exception = new IllegalArgumentException(String.format(
673                         "Invalid reply type %s for CreateTransaction", response.getClass()));
674
675                     localTransactionContext = new NoOpTransactionContext(exception, identifier);
676                 }
677
678                 for(TransactionOperation oper: txOperationsOnComplete) {
679                     oper.invoke(localTransactionContext);
680                 }
681
682                 txOperationsOnComplete.clear();
683
684                 // We're done invoking the TransactionOperations so we can now publish the
685                 // TransactionContext.
686                 transactionContext = localTransactionContext;
687             }
688         }
689
690         private TransactionContext createValidTransactionContext(CreateTransactionReply reply) {
691             String transactionPath = reply.getTransactionPath();
692
693             LOG.debug("Tx {} Received transaction actor path {}", identifier, transactionPath);
694
695             ActorSelection transactionActor = actorContext.actorSelection(transactionPath);
696
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);
701
702                 // Write to the memory barrier volatile to publish the above update to the
703                 // remoteTransactionActors list for thread visibility.
704                 remoteTransactionActorsMB.set(true);
705             }
706
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);
710
711             return new TransactionContextImpl(transactionPath, transactionActor, identifier,
712                 actorContext, schemaContext, isTxActorLocal, reply.getVersion());
713         }
714     }
715
716     private interface TransactionContext {
717         void closeTransaction();
718
719         Future<ActorSelection> readyTransaction();
720
721         void writeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data);
722
723         void deleteData(YangInstanceIdentifier path);
724
725         void mergeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data);
726
727         CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readData(
728                 final YangInstanceIdentifier path);
729
730         CheckedFuture<Boolean, ReadFailedException> dataExists(YangInstanceIdentifier path);
731
732         List<Future<Object>> getRecordedOperationFutures();
733     }
734
735     private static abstract class AbstractTransactionContext implements TransactionContext {
736
737         protected final TransactionIdentifier identifier;
738         protected final List<Future<Object>> recordedOperationFutures = Lists.newArrayList();
739
740         AbstractTransactionContext(TransactionIdentifier identifier) {
741             this.identifier = identifier;
742         }
743
744         @Override
745         public List<Future<Object>> getRecordedOperationFutures() {
746             return recordedOperationFutures;
747         }
748     }
749
750     private static class TransactionContextImpl extends AbstractTransactionContext {
751         private final Logger LOG = LoggerFactory.getLogger(TransactionContextImpl.class);
752
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;
759
760         private TransactionContextImpl(String transactionPath, ActorSelection actor, TransactionIdentifier identifier,
761                 ActorContext actorContext, SchemaContext schemaContext,
762                 boolean isTxActorLocal, int remoteTransactionVersion) {
763             super(identifier);
764             this.transactionPath = transactionPath;
765             this.actor = actor;
766             this.actorContext = actorContext;
767             this.schemaContext = schemaContext;
768             this.isTxActorLocal = isTxActorLocal;
769             this.remoteTransactionVersion = remoteTransactionVersion;
770         }
771
772         private ActorSelection getActor() {
773             return actor;
774         }
775
776         @Override
777         public void closeTransaction() {
778             LOG.debug("Tx {} closeTransaction called", identifier);
779
780             actorContext.sendOperationAsync(getActor(), new CloseTransaction().toSerializable());
781         }
782
783         @Override
784         public Future<ActorSelection> readyTransaction() {
785             LOG.debug("Tx {} readyTransaction called with {} previous recorded operations pending",
786                     identifier, recordedOperationFutures.size());
787
788             // Send the ReadyTransaction message to the Tx actor.
789
790             ReadyTransaction readyTransaction = new ReadyTransaction();
791             final Future<Object> replyFuture = actorContext.executeOperationAsync(getActor(),
792                 isTxActorLocal ? readyTransaction : readyTransaction.toSerializable());
793
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.
798
799             List<Future<Object>> futureList =
800                     Lists.newArrayListWithCapacity(recordedOperationFutures.size() + 1);
801             futureList.addAll(recordedOperationFutures);
802             futureList.add(replyFuture);
803
804             Future<Iterable<Object>> combinedFutures = akka.dispatch.Futures.sequence(futureList,
805                     actorContext.getActorSystem().dispatcher());
806
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.
809
810             return combinedFutures.transform(new Mapper<Iterable<Object>, ActorSelection>() {
811                 @Override
812                 public ActorSelection checkedApply(Iterable<Object> notUsed) {
813                     LOG.debug("Tx {} readyTransaction: pending recorded operations succeeded",
814                             identifier);
815
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.
822
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());
827
828                     } else if(serializedReadyReply.getClass().equals(ReadyTransactionReply.SERIALIZABLE_CLASS)) {
829                         ReadyTransactionReply reply = ReadyTransactionReply.fromSerializable(serializedReadyReply);
830                         String cohortPath = reply.getCohortPath();
831
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);
841                         }
842
843                         return actorContext.actorSelection(cohortPath);
844
845                     } else {
846                         // Throwing an exception here will fail the Future.
847                         throw new IllegalArgumentException(String.format("Invalid reply type {}",
848                                 serializedReadyReply.getClass()));
849                     }
850                 }
851             }, SAME_FAILURE_TRANSFORMER, actorContext.getActorSystem().dispatcher());
852         }
853
854         @Override
855         public void deleteData(YangInstanceIdentifier path) {
856             LOG.debug("Tx {} deleteData called path = {}", identifier, path);
857
858             DeleteData deleteData = new DeleteData(path);
859             recordedOperationFutures.add(actorContext.executeOperationAsync(getActor(),
860                 isTxActorLocal ? deleteData : deleteData.toSerializable()));
861         }
862
863         @Override
864         public void mergeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
865             LOG.debug("Tx {} mergeData called path = {}", identifier, path);
866
867             MergeData mergeData = new MergeData(path, data, schemaContext);
868             recordedOperationFutures.add(actorContext.executeOperationAsync(getActor(),
869                 isTxActorLocal ? mergeData : mergeData.toSerializable()));
870         }
871
872         @Override
873         public void writeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
874             LOG.debug("Tx {} writeData called path = {}", identifier, path);
875
876             WriteData writeData = new WriteData(path, data, schemaContext);
877             recordedOperationFutures.add(actorContext.executeOperationAsync(getActor(),
878                 isTxActorLocal ? writeData : writeData.toSerializable()));
879         }
880
881         @Override
882         public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readData(
883                 final YangInstanceIdentifier path) {
884
885             LOG.debug("Tx {} readData called path = {}", identifier, path);
886
887             final SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture = SettableFuture.create();
888
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.
892
893             if(recordedOperationFutures.isEmpty()) {
894                 finishReadData(path, returnFuture);
895             } else {
896                 LOG.debug("Tx {} readData: verifying {} previous recorded operations",
897                         identifier, recordedOperationFutures.size());
898
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.
902
903                 Future<Iterable<Object>> combinedFutures = akka.dispatch.Futures.sequence(
904                         Lists.newArrayList(recordedOperationFutures),
905                         actorContext.getActorSystem().dispatcher());
906
907                 OnComplete<Iterable<Object>> onComplete = new OnComplete<Iterable<Object>>() {
908                     @Override
909                     public void onComplete(Throwable failure, Iterable<Object> notUsed)
910                             throws Throwable {
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));
917                         } else {
918                             finishReadData(path, returnFuture);
919                         }
920                     }
921                 };
922
923                 combinedFutures.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
924             }
925
926             return MappingCheckedFuture.create(returnFuture, ReadFailedException.MAPPER);
927         }
928
929         private void finishReadData(final YangInstanceIdentifier path,
930                 final SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture) {
931
932             LOG.debug("Tx {} finishReadData called path = {}", identifier, path);
933
934             OnComplete<Object> onComplete = new OnComplete<Object>() {
935                 @Override
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));
941
942                     } else {
943                         LOG.debug("Tx {} read operation succeeded", identifier, failure);
944
945                         if (readResponse instanceof ReadDataReply) {
946                             ReadDataReply reply = (ReadDataReply) readResponse;
947                             returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
948
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()));
952
953                         } else {
954                             returnFuture.setException(new ReadFailedException(
955                                 "Invalid response reading data for path " + path));
956                         }
957                     }
958                 }
959             };
960
961             ReadData readData = new ReadData(path);
962             Future<Object> readFuture = actorContext.executeOperationAsync(getActor(),
963                 isTxActorLocal ? readData : readData.toSerializable());
964
965             readFuture.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
966         }
967
968         @Override
969         public CheckedFuture<Boolean, ReadFailedException> dataExists(
970                 final YangInstanceIdentifier path) {
971
972             LOG.debug("Tx {} dataExists called path = {}", identifier, path);
973
974             final SettableFuture<Boolean> returnFuture = SettableFuture.create();
975
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
979             // request.
980
981             if(recordedOperationFutures.isEmpty()) {
982                 finishDataExists(path, returnFuture);
983             } else {
984                 LOG.debug("Tx {} dataExists: verifying {} previous recorded operations",
985                         identifier, recordedOperationFutures.size());
986
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.
990
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>>() {
995                     @Override
996                     public void onComplete(Throwable failure, Iterable<Object> notUsed)
997                             throws Throwable {
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));
1004                         } else {
1005                             finishDataExists(path, returnFuture);
1006                         }
1007                     }
1008                 };
1009
1010                 combinedFutures.onComplete(onComplete, actorContext.getActorSystem().dispatcher());
1011             }
1012
1013             return MappingCheckedFuture.create(returnFuture, ReadFailedException.MAPPER);
1014         }
1015
1016         private void finishDataExists(final YangInstanceIdentifier path,
1017                 final SettableFuture<Boolean> returnFuture) {
1018
1019             LOG.debug("Tx {} finishDataExists called path = {}", identifier, path);
1020
1021             OnComplete<Object> onComplete = new OnComplete<Object>() {
1022                 @Override
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));
1028                     } else {
1029                         LOG.debug("Tx {} dataExists operation succeeded", identifier, failure);
1030
1031                         if (response instanceof DataExistsReply) {
1032                             returnFuture.set(Boolean.valueOf(((DataExistsReply) response).exists()));
1033
1034                         } else if (response.getClass().equals(DataExistsReply.SERIALIZABLE_CLASS)) {
1035                             returnFuture.set(Boolean.valueOf(DataExistsReply.fromSerializable(response).exists()));
1036
1037                         } else {
1038                             returnFuture.setException(new ReadFailedException(
1039                                     "Invalid response checking exists for path " + path));
1040                         }
1041                     }
1042                 }
1043             };
1044
1045             DataExists dataExists = new DataExists(path);
1046             Future<Object> future = actorContext.executeOperationAsync(getActor(),
1047                 isTxActorLocal ? dataExists : dataExists.toSerializable());
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 }