BUG-5626: split out CohortEntry
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / ShardCommitCoordinator.java
index 739321b06876ca6331bd785acb6074944ac86daf..f313329c7070a1fd582bf045888321493ee4074a 100644 (file)
@@ -12,7 +12,6 @@ import akka.actor.Status.Failure;
 import akka.serialization.Serialization;
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Preconditions;
-import com.google.common.base.Stopwatch;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
@@ -23,8 +22,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Queue;
 import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeUnit;
-import org.opendaylight.controller.cluster.datastore.ShardCommitCoordinator.CohortEntry.State;
+import org.opendaylight.controller.cluster.datastore.DataTreeCohortActorRegistry.CohortRegistryCommand;
 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
@@ -34,11 +32,9 @@ import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
-import org.opendaylight.controller.cluster.datastore.modification.Modification;
 import org.opendaylight.controller.cluster.datastore.utils.AbstractBatchedModificationsCursor;
 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.slf4j.Logger;
 
 /**
@@ -46,7 +42,7 @@ import org.slf4j.Logger;
  *
  * @author Thomas Pantelis
  */
-class ShardCommitCoordinator {
+final class ShardCommitCoordinator {
 
     // Interface hook for unit tests to replace or decorate the DOMStoreThreePhaseCommitCohorts.
     public interface CohortDecorator {
@@ -59,6 +55,8 @@ class ShardCommitCoordinator {
 
     private final ShardDataTree dataTree;
 
+    private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
+
     // We use a LinkedList here to avoid synchronization overhead with concurrent queue impls
     // since this should only be accessed on the shard's dispatcher.
     private final Queue<CohortEntry> queuedCohortEntries = new LinkedList<>();
@@ -78,8 +76,8 @@ class ShardCommitCoordinator {
 
     private Runnable runOnPendingTransactionsComplete;
 
-    ShardCommitCoordinator(ShardDataTree dataTree,
-            long cacheExpiryTimeoutInMillis, int queueCapacity, Logger log, String name) {
+    ShardCommitCoordinator(ShardDataTree dataTree, long cacheExpiryTimeoutInMillis, int queueCapacity, Logger log,
+            String name) {
 
         this.queueCapacity = queueCapacity;
         this.log = log;
@@ -119,7 +117,7 @@ class ShardCommitCoordinator {
         } else {
             cohortCache.remove(cohortEntry.getTransactionID());
 
-            RuntimeException ex = new RuntimeException(
+            final RuntimeException ex = new RuntimeException(
                     String.format("%s: Could not enqueue transaction %s - the maximum commit queue"+
                                   " capacity %d has been reached.",
                                   name, cohortEntry.getTransactionID(), queueCapacity));
@@ -136,13 +134,15 @@ class ShardCommitCoordinator {
      * @param ready the ForwardedReadyTransaction message to process
      * @param sender the sender of the message
      * @param shard the transaction's shard actor
+     * @param schema
      */
-    void handleForwardedReadyTransaction(ForwardedReadyTransaction ready, ActorRef sender, Shard shard) {
+    void handleForwardedReadyTransaction(ForwardedReadyTransaction ready, ActorRef sender, Shard shard,
+            SchemaContext schema) {
         log.debug("{}: Readying transaction {}, client version {}", name,
                 ready.getTransactionID(), ready.getTxnClientVersion());
 
-        ShardDataTreeCohort cohort = ready.getTransaction().ready();
-        CohortEntry cohortEntry = new CohortEntry(ready.getTransactionID(), cohort, ready.getTxnClientVersion());
+        final ShardDataTreeCohort cohort = ready.getTransaction().ready();
+        final CohortEntry cohortEntry = new CohortEntry(ready.getTransactionID(), cohort, cohortRegistry, schema, ready.getTxnClientVersion());
         cohortCache.put(ready.getTransactionID(), cohortEntry);
 
         if(!queueCohortEntry(cohortEntry, sender, shard)) {
@@ -171,12 +171,12 @@ class ShardCommitCoordinator {
      * @param sender the sender of the message
      * @param shard the transaction's shard actor
      */
-    void handleBatchedModifications(BatchedModifications batched, ActorRef sender, Shard shard) {
+    void handleBatchedModifications(BatchedModifications batched, ActorRef sender, Shard shard, SchemaContext schema) {
         CohortEntry cohortEntry = cohortCache.get(batched.getTransactionID());
         if(cohortEntry == null) {
             cohortEntry = new CohortEntry(batched.getTransactionID(),
-                    dataTree.newReadWriteTransaction(batched.getTransactionID(),
-                        batched.getTransactionChainID()), batched.getVersion());
+                    dataTree.newReadWriteTransaction(batched.getTransactionID(), batched.getTransactionChainID()),
+                    cohortRegistry, schema,  batched.getVersion());
             cohortCache.put(batched.getTransactionID(), cohortEntry);
         }
 
@@ -225,16 +225,18 @@ class ShardCommitCoordinator {
 
     /**
      * This method handles {@link ReadyLocalTransaction} message. All transaction modifications have
-     * been prepared beforehand by the sender and we just need to drive them through into the dataTree.
+     * been prepared beforehand by the sender and we just need to drive them through into the
+     * dataTree.
      *
      * @param message the ReadyLocalTransaction message to process
      * @param sender the sender of the message
      * @param shard the transaction's shard actor
      */
-    void handleReadyLocalTransaction(ReadyLocalTransaction message, ActorRef sender, Shard shard) {
+    void handleReadyLocalTransaction(ReadyLocalTransaction message, ActorRef sender, Shard shard,
+            SchemaContext schema) {
         final ShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(dataTree, message.getModification(),
                 message.getTransactionID());
-        final CohortEntry cohortEntry = new CohortEntry(message.getTransactionID(), cohort,
+        final CohortEntry cohortEntry = new CohortEntry(message.getTransactionID(), cohort, cohortRegistry, schema,
                 DataStoreVersions.CURRENT_VERSION);
         cohortCache.put(message.getTransactionID(), cohortEntry);
         cohortEntry.setDoImmediateCommit(message.isDoCommitOnReady());
@@ -503,6 +505,7 @@ class ShardCommitCoordinator {
 
     private List<CohortEntry> getAndClearPendingCohortEntries() {
         List<CohortEntry> cohortEntries = new ArrayList<>();
+
         if(currentCohortEntry != null) {
             cohortEntries.add(currentCohortEntry);
             cohortCache.remove(currentCohortEntry.getTransactionID());
@@ -538,7 +541,7 @@ class ShardCommitCoordinator {
                             newModifications.getLast().getModifications().size() >= maxModificationsPerBatch) {
                         newModifications.add(new BatchedModifications(cohortEntry.getTransactionID(),
                                 cohortEntry.getClientVersion(), ""));
-                    }
+        }
 
                     return newModifications.getLast();
                 }
@@ -551,12 +554,12 @@ class ShardCommitCoordinator {
                 last.setTotalMessagesSent(newModifications.size());
                 messages.addAll(newModifications);
 
-                if(!cohortEntry.isDoImmediateCommit() && cohortEntry.getState() == State.CAN_COMMITTED) {
+                if(!cohortEntry.isDoImmediateCommit() && cohortEntry.getState() == CohortEntry.State.CAN_COMMITTED) {
                     messages.add(new CanCommitTransaction(cohortEntry.getTransactionID(),
                             cohortEntry.getClientVersion()));
                 }
 
-                if(!cohortEntry.isDoImmediateCommit() && cohortEntry.getState() == State.PRE_COMMITTED) {
+                if(!cohortEntry.isDoImmediateCommit() && cohortEntry.getState() == CohortEntry.State.PRE_COMMITTED) {
                     messages.add(new CommitTransaction(cohortEntry.getTransactionID(),
                             cohortEntry.getClientVersion()));
                 }
@@ -621,9 +624,9 @@ class ShardCommitCoordinator {
     private void maybeProcessNextCohortEntry() {
         // Check if there's a next cohort entry waiting in the queue and if it is ready to commit. Also
         // clean out expired entries.
-        Iterator<CohortEntry> iter = queuedCohortEntries.iterator();
+        final Iterator<CohortEntry> iter = queuedCohortEntries.iterator();
         while(iter.hasNext()) {
-            CohortEntry next = iter.next();
+            final CohortEntry next = iter.next();
             if(next.isReadyToCommit()) {
                 if(currentCohortEntry == null) {
                     if(log.isDebugEnabled()) {
@@ -674,173 +677,7 @@ class ShardCommitCoordinator {
         this.cohortDecorator = cohortDecorator;
     }
 
-    static class CohortEntry {
-        enum State {
-            PENDING,
-            CAN_COMMITTED,
-            PRE_COMMITTED,
-            COMMITTED,
-            ABORTED
-        }
-
-        private final String transactionID;
-        private ShardDataTreeCohort cohort;
-        private final ReadWriteShardDataTreeTransaction transaction;
-        private RuntimeException lastBatchedModificationsException;
-        private ActorRef replySender;
-        private Shard shard;
-        private boolean doImmediateCommit;
-        private final Stopwatch lastAccessTimer = Stopwatch.createStarted();
-        private int totalBatchedModificationsReceived;
-        private State state = State.PENDING;
-        private final short clientVersion;
-
-        CohortEntry(String transactionID, ReadWriteShardDataTreeTransaction transaction, short clientVersion) {
-            this.transaction = Preconditions.checkNotNull(transaction);
-            this.transactionID = transactionID;
-            this.clientVersion = clientVersion;
-        }
-
-        CohortEntry(String transactionID, ShardDataTreeCohort cohort, short clientVersion) {
-            this.transactionID = transactionID;
-            this.cohort = cohort;
-            this.transaction = null;
-            this.clientVersion = clientVersion;
-        }
-
-        void updateLastAccessTime() {
-            lastAccessTimer.reset();
-            lastAccessTimer.start();
-        }
-
-        String getTransactionID() {
-            return transactionID;
-        }
-
-        short getClientVersion() {
-            return clientVersion;
-        }
-
-        State getState() {
-            return state;
-        }
-
-        DataTreeCandidate getCandidate() {
-            return cohort.getCandidate();
-        }
-
-        DataTreeModification getDataTreeModification() {
-            return cohort.getDataTreeModification();
-        }
-
-        ReadWriteShardDataTreeTransaction getTransaction() {
-            return transaction;
-        }
-
-        int getTotalBatchedModificationsReceived() {
-            return totalBatchedModificationsReceived;
-        }
-
-        RuntimeException getLastBatchedModificationsException() {
-            return lastBatchedModificationsException;
-        }
-
-        void applyModifications(Iterable<Modification> modifications) {
-            totalBatchedModificationsReceived++;
-            if(lastBatchedModificationsException == null) {
-                for (Modification modification : modifications) {
-                        try {
-                            modification.apply(transaction.getSnapshot());
-                        } catch (RuntimeException e) {
-                            lastBatchedModificationsException = e;
-                            throw e;
-                        }
-                }
-            }
-        }
-
-        boolean canCommit() throws InterruptedException, ExecutionException {
-            state = State.CAN_COMMITTED;
-
-            // We block on the future here (and also preCommit(), commit(), abort()) so we don't have to worry
-            // about possibly accessing our state on a different thread outside of our dispatcher.
-            // TODO: the ShardDataTreeCohort returns immediate Futures anyway which begs the question - why
-            // bother even returning Futures from ShardDataTreeCohort if we have to treat them synchronously
-            // anyway?. The Futures are really a remnant from when we were using the InMemoryDataBroker.
-            return cohort.canCommit().get();
-        }
-
-        void preCommit() throws InterruptedException, ExecutionException {
-            state = State.PRE_COMMITTED;
-            cohort.preCommit().get();
-        }
-
-        void commit() throws InterruptedException, ExecutionException {
-            state = State.COMMITTED;
-            cohort.commit().get();
-        }
-
-        void abort() throws InterruptedException, ExecutionException {
-            state = State.ABORTED;
-            cohort.abort().get();
-        }
-
-        void ready(CohortDecorator cohortDecorator, boolean doImmediateCommit) {
-            Preconditions.checkState(cohort == null, "cohort was already set");
-
-            setDoImmediateCommit(doImmediateCommit);
-
-            cohort = transaction.ready();
-
-            if(cohortDecorator != null) {
-                // Call the hook for unit tests.
-                cohort = cohortDecorator.decorate(transactionID, cohort);
-            }
-        }
-
-        boolean isReadyToCommit() {
-            return replySender != null;
-        }
-
-        boolean isExpired(long expireTimeInMillis) {
-            return lastAccessTimer.elapsed(TimeUnit.MILLISECONDS) >= expireTimeInMillis;
-        }
-
-        boolean isDoImmediateCommit() {
-            return doImmediateCommit;
-        }
-
-        void setDoImmediateCommit(boolean doImmediateCommit) {
-            this.doImmediateCommit = doImmediateCommit;
-        }
-
-        ActorRef getReplySender() {
-            return replySender;
-        }
-
-        void setReplySender(ActorRef replySender) {
-            this.replySender = replySender;
-        }
-
-        Shard getShard() {
-            return shard;
-        }
-
-        void setShard(Shard shard) {
-            this.shard = shard;
-        }
-
-
-        boolean isAborted() {
-            return state == State.ABORTED;
-        }
-
-        @Override
-        public String toString() {
-            StringBuilder builder = new StringBuilder();
-            builder.append("CohortEntry [transactionID=").append(transactionID).append(", doImmediateCommit=")
-                    .append(doImmediateCommit).append("]");
-            return builder.toString();
-        }
+   void processCohortRegistryCommand(ActorRef sender, CohortRegistryCommand message) {
+        cohortRegistry.process(sender, message);
     }
 }