+ void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
+ final CommitEntry entry = pendingTransactions.peek();
+ Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
+
+ final SimpleShardDataTreeCohort current = entry.cohort;
+ Verify.verify(cohort.equals(current), "Attempted to commit %s while %s is pending", cohort, current);
+
+ if (shard.canSkipPayload() || candidate.getRootNode().getModificationType() == ModificationType.UNMODIFIED) {
+ LOG.debug("{}: No replication required, proceeding to finish commit", logContext);
+ finishCommit(cohort);
+ return;
+ }
+
+ final TransactionIdentifier txId = cohort.getIdentifier();
+ final Payload payload;
+ try {
+ payload = CommitTransactionPayload.create(txId, candidate);
+ } catch (IOException e) {
+ LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
+ pendingTransactions.poll().cohort.failedCommit(e);
+ return;
+ }
+
+ // Once completed, we will continue via payloadReplicationComplete
+ entry.lastAccess = shard.ticker().read();
+ shard.persistPayload(txId, payload);
+ LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
+ }
+
+ void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
+ cohortRegistry.process(sender, message);
+ }
+
+ @Override
+ ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId,
+ final DataTreeModification modification) {
+ SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, modification, txId,
+ cohortRegistry.createCohort(schemaContext, txId, COMMIT_STEP_TIMEOUT));
+ pendingTransactions.add(new CommitEntry(cohort, shard.ticker().read()));
+ return cohort;
+ }
+
+ @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
+ void checkForExpiredTransactions(final long transactionCommitTimeoutMillis) {
+ final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
+ final long now = shard.ticker().read();
+ final CommitEntry currentTx = pendingTransactions.peek();
+ if (currentTx != null && currentTx.lastAccess + timeout < now) {
+ LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
+ currentTx.cohort.getIdentifier(), transactionCommitTimeoutMillis, currentTx.cohort.getState());
+ boolean processNext = true;
+ switch (currentTx.cohort.getState()) {
+ case CAN_COMMIT_PENDING:
+ pendingTransactions.remove().cohort.failedCanCommit(new TimeoutException());
+ break;
+ case CAN_COMMIT_COMPLETE:
+ // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
+ // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
+ // in PRE_COMMIT_COMPLETE is changed.
+ pendingTransactions.remove().cohort.reportFailure(new TimeoutException());
+ break;
+ case PRE_COMMIT_PENDING:
+ pendingTransactions.remove().cohort.failedPreCommit(new TimeoutException());
+ break;
+ case PRE_COMMIT_COMPLETE:
+ // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
+ // are ready we should commit the transaction, not abort it. Our current software stack does
+ // not allow us to do that consistently, because we persist at the time of commit, hence
+ // we can end up in a state where we have pre-committed a transaction, then a leader failover
+ // occurred ... the new leader does not see the pre-committed transaction and does not have
+ // a running timer. To fix this we really need two persistence events.
+ //
+ // The first one, done at pre-commit time will hold the transaction payload. When consensus
+ // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
+ // apply the state in this event.
+ //
+ // The second one, done at commit (or abort) time holds only the transaction identifier and
+ // signals to followers that the state should (or should not) be applied.
+ //
+ // In order to make the pre-commit timer working across failovers, though, we need
+ // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
+ // restart the timer.
+ pendingTransactions.remove().cohort.reportFailure(new TimeoutException());
+ break;
+ case COMMIT_PENDING:
+ LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
+ currentTx.cohort.getIdentifier());
+ currentTx.lastAccess = now;
+ processNext = false;
+ return;
+ case ABORTED:
+ case COMMITTED:
+ case FAILED:
+ case READY:
+ default:
+ pendingTransactions.remove();
+ }
+
+ if (processNext) {
+ processNextTransaction();
+ }
+ }
+ }
+
+ boolean startAbort(final SimpleShardDataTreeCohort cohort) {
+ final Iterator<CommitEntry> it = pendingTransactions.iterator();
+ if (!it.hasNext()) {
+ LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
+ return true;
+ }
+
+ // First entry is special, as it may already be committing
+ final CommitEntry first = it.next();
+ if (cohort.equals(first.cohort)) {
+ if (cohort.getState() != State.COMMIT_PENDING) {
+ LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
+ cohort.getIdentifier());
+
+ it.remove();
+ rebasePreCommittedTransactions(it, dataTree);
+ processNextTransaction();
+ return true;
+ }
+
+ LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
+ return false;
+ }
+
+ TipProducingDataTreeTip newTip = dataTree;
+ while (it.hasNext()) {
+ final CommitEntry e = it.next();
+ if (cohort.equals(e.cohort)) {
+ LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
+ it.remove();
+ rebasePreCommittedTransactions(it, newTip);
+ return true;
+ } else {
+ newTip = cohort.getCandidate();
+ }
+ }
+
+ LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
+ return true;
+ }
+
+ @SuppressWarnings("checkstyle:IllegalCatch")
+ private void rebasePreCommittedTransactions(Iterator<CommitEntry> iter, TipProducingDataTreeTip newTip) {
+ tip = newTip;
+ while (iter.hasNext()) {
+ final SimpleShardDataTreeCohort cohort = iter.next().cohort;
+ if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
+ LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
+
+ try {
+ tip.validate(cohort.getDataTreeModification());
+ } catch (DataValidationFailedException | RuntimeException e) {
+ LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
+ cohort.reportFailure(e);
+ }
+ } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
+ LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
+
+ try {
+ tip.validate(cohort.getDataTreeModification());
+ DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
+ cohort.userPreCommit(candidate);
+
+ cohort.setNewCandidate(candidate);
+ tip = candidate;
+ } catch (ExecutionException | TimeoutException | RuntimeException | DataValidationFailedException e) {
+ LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
+ cohort.reportFailure(e);
+ }
+ }
+ }
+ }
+
+ void setRunOnPendingTransactionsComplete(final Runnable operation) {
+ runOnPendingTransactionsComplete = operation;
+ maybeRunOperationOnPendingTransactionsComplete();
+ }
+
+ private void maybeRunOperationOnPendingTransactionsComplete() {
+ if (runOnPendingTransactionsComplete != null && pendingTransactions.isEmpty()) {
+ LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
+ runOnPendingTransactionsComplete);
+
+ runOnPendingTransactionsComplete.run();
+ runOnPendingTransactionsComplete = null;
+ }
+ }