Centralize DataTree operations
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / ShardDataTree.java
1 /*
2  * Copyright (c) 2015 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 package org.opendaylight.controller.cluster.datastore;
9
10 import static akka.actor.ActorRef.noSender;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verify;
13 import static com.google.common.base.Verify.verifyNotNull;
14 import static java.util.Objects.requireNonNull;
15 import static java.util.Objects.requireNonNullElse;
16
17 import akka.actor.ActorRef;
18 import akka.util.Timeout;
19 import com.google.common.annotations.VisibleForTesting;
20 import com.google.common.base.Stopwatch;
21 import com.google.common.collect.ImmutableList;
22 import com.google.common.collect.ImmutableMap;
23 import com.google.common.collect.ImmutableMap.Builder;
24 import com.google.common.collect.Iterables;
25 import com.google.common.primitives.UnsignedLong;
26 import com.google.common.util.concurrent.FutureCallback;
27 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
28 import java.io.File;
29 import java.io.IOException;
30 import java.util.ArrayDeque;
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.Collections;
34 import java.util.Deque;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.Map;
38 import java.util.Map.Entry;
39 import java.util.Optional;
40 import java.util.OptionalLong;
41 import java.util.Queue;
42 import java.util.SortedSet;
43 import java.util.concurrent.TimeUnit;
44 import java.util.concurrent.TimeoutException;
45 import java.util.function.Consumer;
46 import java.util.function.Function;
47 import java.util.function.UnaryOperator;
48 import org.eclipse.jdt.annotation.NonNull;
49 import org.eclipse.jdt.annotation.Nullable;
50 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
51 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
52 import org.opendaylight.controller.cluster.datastore.DataTreeCohortActorRegistry.CohortRegistryCommand;
53 import org.opendaylight.controller.cluster.datastore.ShardDataTreeCohort.State;
54 import org.opendaylight.controller.cluster.datastore.node.utils.transformer.ReusableNormalizedNodePruner;
55 import org.opendaylight.controller.cluster.datastore.persisted.AbortTransactionPayload;
56 import org.opendaylight.controller.cluster.datastore.persisted.AbstractIdentifiablePayload;
57 import org.opendaylight.controller.cluster.datastore.persisted.CloseLocalHistoryPayload;
58 import org.opendaylight.controller.cluster.datastore.persisted.CommitTransactionPayload;
59 import org.opendaylight.controller.cluster.datastore.persisted.CreateLocalHistoryPayload;
60 import org.opendaylight.controller.cluster.datastore.persisted.DataTreeCandidateInputOutput.DataTreeCandidateWithVersion;
61 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
62 import org.opendaylight.controller.cluster.datastore.persisted.PayloadVersion;
63 import org.opendaylight.controller.cluster.datastore.persisted.PurgeLocalHistoryPayload;
64 import org.opendaylight.controller.cluster.datastore.persisted.PurgeTransactionPayload;
65 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
66 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshotMetadata;
67 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
68 import org.opendaylight.controller.cluster.datastore.persisted.SkipTransactionsPayload;
69 import org.opendaylight.controller.cluster.datastore.utils.DataTreeModificationOutput;
70 import org.opendaylight.controller.cluster.datastore.utils.ImmutableUnsignedLongSet;
71 import org.opendaylight.controller.cluster.datastore.utils.PruningDataTreeModification;
72 import org.opendaylight.controller.cluster.raft.base.messages.InitiateCaptureSnapshot;
73 import org.opendaylight.controller.cluster.raft.messages.Payload;
74 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
75 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
76 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
77 import org.opendaylight.yangtools.concepts.Identifier;
78 import org.opendaylight.yangtools.concepts.ListenerRegistration;
79 import org.opendaylight.yangtools.yang.common.Empty;
80 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
81 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
82 import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeStreamVersion;
83 import org.opendaylight.yangtools.yang.data.tree.api.ConflictingModificationAppliedException;
84 import org.opendaylight.yangtools.yang.data.tree.api.DataTree;
85 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
86 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidateTip;
87 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeConfiguration;
88 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeModification;
89 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeSnapshot;
90 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeTip;
91 import org.opendaylight.yangtools.yang.data.tree.api.DataValidationFailedException;
92 import org.opendaylight.yangtools.yang.data.tree.api.ModificationType;
93 import org.opendaylight.yangtools.yang.data.tree.api.TreeType;
94 import org.opendaylight.yangtools.yang.data.tree.impl.di.InMemoryDataTreeFactory;
95 import org.opendaylight.yangtools.yang.data.tree.spi.DataTreeCandidates;
96 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
97 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
98 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
99 import org.slf4j.Logger;
100 import org.slf4j.LoggerFactory;
101 import scala.concurrent.duration.FiniteDuration;
102
103 /**
104  * Internal shard state, similar to a DOMStore, but optimized for use in the actor system, e.g. it does not expose
105  * public interfaces and assumes it is only ever called from a single thread.
106  *
107  * <p>
108  * This class is not part of the API contract and is subject to change at any time. It is NOT thread-safe.
109  */
110 @VisibleForTesting
111 // non-final for mocking
112 public class ShardDataTree extends ShardDataTreeTransactionParent {
113     private static final class CommitEntry {
114         final SimpleShardDataTreeCohort cohort;
115         long lastAccess;
116
117         CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
118             this.cohort = requireNonNull(cohort);
119             lastAccess = now;
120         }
121
122         @Override
123         public String toString() {
124             return "CommitEntry [tx=" + cohort.getIdentifier() + ", state=" + cohort.getState() + "]";
125         }
126     }
127
128     private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(FiniteDuration.create(5, TimeUnit.SECONDS));
129     private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
130
131     /**
132      * Process this many transactions in a single batched run. If we exceed this limit, we need to schedule later
133      * execution to finish up the batch. This is necessary in case of a long list of transactions which progress
134      * immediately through their preCommit phase -- if that happens, their completion eats up stack frames and could
135      * result in StackOverflowError.
136      */
137     private static final int MAX_TRANSACTION_BATCH = 100;
138
139     private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
140     private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
141     private final Deque<CommitEntry> pendingTransactions = new ArrayDeque<>();
142     private final Queue<CommitEntry> pendingCommits = new ArrayDeque<>();
143     private final Queue<CommitEntry> pendingFinishCommits = new ArrayDeque<>();
144
145     /**
146      * Callbacks that need to be invoked once a payload is replicated.
147      */
148     private final Map<Payload, Runnable> replicationCallbacks = new HashMap<>();
149
150     private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
151     private final Collection<ShardDataTreeMetadata<?>> metadata;
152     private final DataTree dataTree;
153     private final String logContext;
154     private final Shard shard;
155     private Runnable runOnPendingTransactionsComplete;
156
157     /**
158      * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
159      * {@link DataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
160      * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
161      * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
162      */
163     private DataTreeTip tip;
164
165     private SchemaContext schemaContext;
166     private DataSchemaContextTree dataSchemaContext;
167
168     private int currentTransactionBatch;
169
170     ShardDataTree(final Shard shard, final EffectiveModelContext schemaContext, final DataTree dataTree,
171             final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
172             final String logContext,
173             final ShardDataTreeMetadata<?>... metadata) {
174         this.dataTree = requireNonNull(dataTree);
175         updateSchemaContext(schemaContext);
176
177         this.shard = requireNonNull(shard);
178         this.treeChangeListenerPublisher = requireNonNull(treeChangeListenerPublisher);
179         this.logContext = requireNonNull(logContext);
180         this.metadata = ImmutableList.copyOf(metadata);
181         tip = dataTree;
182     }
183
184     ShardDataTree(final Shard shard, final EffectiveModelContext schemaContext, final TreeType treeType,
185             final YangInstanceIdentifier root,
186             final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
187             final String logContext,
188             final ShardDataTreeMetadata<?>... metadata) {
189         this(shard, schemaContext, createDataTree(treeType, root), treeChangeListenerPublisher, logContext, metadata);
190     }
191
192     private static DataTree createDataTree(final TreeType treeType, final YangInstanceIdentifier root) {
193         final DataTreeConfiguration baseConfig = DataTreeConfiguration.getDefault(treeType);
194         return new InMemoryDataTreeFactory().create(new DataTreeConfiguration.Builder(baseConfig.getTreeType())
195                 .setMandatoryNodesValidation(baseConfig.isMandatoryNodesValidationEnabled())
196                 .setUniqueIndexes(baseConfig.isUniqueIndexEnabled())
197                 .setRootPath(root)
198                 .build());
199     }
200
201     @VisibleForTesting
202     public ShardDataTree(final Shard shard, final EffectiveModelContext schemaContext, final TreeType treeType) {
203         this(shard, schemaContext, treeType, YangInstanceIdentifier.empty(),
204                 new DefaultShardDataTreeChangeListenerPublisher(""), "");
205     }
206
207     final String logContext() {
208         return logContext;
209     }
210
211     final long readTime() {
212         return shard.ticker().read();
213     }
214
215     final DataTree getDataTree() {
216         return dataTree;
217     }
218
219     @VisibleForTesting
220     final SchemaContext getSchemaContext() {
221         return schemaContext;
222     }
223
224     final void updateSchemaContext(final @NonNull EffectiveModelContext newSchemaContext) {
225         dataTree.setEffectiveModelContext(newSchemaContext);
226         schemaContext = newSchemaContext;
227         dataSchemaContext = DataSchemaContextTree.from(newSchemaContext);
228     }
229
230     final void resetTransactionBatch() {
231         currentTransactionBatch = 0;
232     }
233
234     /**
235      * Take a snapshot of current state for later recovery.
236      *
237      * @return A state snapshot
238      */
239     @NonNull ShardDataTreeSnapshot takeStateSnapshot() {
240         final NormalizedNode rootNode = takeSnapshot().readNode(YangInstanceIdentifier.empty()).get();
241         final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
242                 ImmutableMap.builder();
243
244         for (ShardDataTreeMetadata<?> m : metadata) {
245             final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
246             if (meta != null) {
247                 metaBuilder.put(meta.getType(), meta);
248             }
249         }
250
251         return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
252     }
253
254     private boolean anyPendingTransactions() {
255         return !pendingTransactions.isEmpty() || !pendingCommits.isEmpty() || !pendingFinishCommits.isEmpty();
256     }
257
258     private void applySnapshot(final @NonNull ShardDataTreeSnapshot snapshot,
259             final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
260         final Stopwatch elapsed = Stopwatch.createStarted();
261
262         if (anyPendingTransactions()) {
263             LOG.warn("{}: applying state snapshot with pending transactions", logContext);
264         }
265
266         final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
267         if (snapshot instanceof MetadataShardDataTreeSnapshot) {
268             snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
269         } else {
270             snapshotMeta = ImmutableMap.of();
271         }
272
273         for (ShardDataTreeMetadata<?> m : metadata) {
274             final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
275             if (s != null) {
276                 m.applySnapshot(s);
277             } else {
278                 m.reset();
279             }
280         }
281
282         final DataTreeModification unwrapped = newModification();
283         final DataTreeModification mod = wrapper.apply(unwrapped);
284         // delete everything first
285         mod.delete(YangInstanceIdentifier.empty());
286
287         final Optional<NormalizedNode> maybeNode = snapshot.getRootNode();
288         if (maybeNode.isPresent()) {
289             // Add everything from the remote node back
290             mod.write(YangInstanceIdentifier.empty(), maybeNode.get());
291         }
292         mod.ready();
293
294         dataTree.validate(unwrapped);
295         DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
296         dataTree.commit(candidate);
297         notifyListeners(candidate);
298
299         LOG.debug("{}: state snapshot applied in {}", logContext, elapsed);
300     }
301
302     /**
303      * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
304      * does not perform any pruning.
305      *
306      * @param snapshot Snapshot that needs to be applied
307      * @throws DataValidationFailedException when the snapshot fails to apply
308      */
309     final void applySnapshot(final @NonNull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
310         // TODO: we should be taking ShardSnapshotState here and performing forward-compatibility translation
311         applySnapshot(snapshot, UnaryOperator.identity());
312     }
313
314     /**
315      * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
316      * pruning in an attempt to adjust the state to our current SchemaContext.
317      *
318      * @param snapshot Snapshot that needs to be applied
319      * @throws DataValidationFailedException when the snapshot fails to apply
320      */
321     final void applyRecoverySnapshot(final @NonNull ShardSnapshotState snapshot) throws DataValidationFailedException {
322         // TODO: we should be able to reuse the pruner, provided we are not reentrant
323         final ReusableNormalizedNodePruner pruner = ReusableNormalizedNodePruner.forDataSchemaContext(
324             dataSchemaContext);
325         if (snapshot.needsMigration()) {
326             final ReusableNormalizedNodePruner uintPruner = pruner.withUintAdaption();
327             applySnapshot(snapshot.getSnapshot(),
328                 delegate -> new PruningDataTreeModification.Proactive(delegate, dataTree, uintPruner));
329         } else {
330             applySnapshot(snapshot.getSnapshot(),
331                 delegate -> new PruningDataTreeModification.Reactive(delegate, dataTree, pruner));
332         }
333     }
334
335     @SuppressWarnings("checkstyle:IllegalCatch")
336     private void applyRecoveryCandidate(final CommitTransactionPayload payload) throws IOException {
337         final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> entry = payload.acquireCandidate();
338         final DataTreeModification unwrapped = newModification();
339         final PruningDataTreeModification mod = createPruningModification(unwrapped,
340             NormalizedNodeStreamVersion.MAGNESIUM.compareTo(entry.getValue().getVersion()) > 0);
341
342         DataTreeCandidates.applyToModification(mod, entry.getValue().getCandidate());
343         mod.ready();
344         LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
345
346         try {
347             dataTree.validate(unwrapped);
348             dataTree.commit(dataTree.prepare(unwrapped));
349         } catch (Exception e) {
350             File file = new File(System.getProperty("karaf.data", "."),
351                     "failed-recovery-payload-" + logContext + ".out");
352             DataTreeModificationOutput.toFile(file, unwrapped);
353             throw new IllegalStateException(String.format(
354                     "%s: Failed to apply recovery payload. Modification data was written to file %s",
355                     logContext, file), e);
356         }
357
358         allMetadataCommittedTransaction(entry.getKey());
359     }
360
361     private PruningDataTreeModification createPruningModification(final DataTreeModification unwrapped,
362             final boolean uintAdapting) {
363         // TODO: we should be able to reuse the pruner, provided we are not reentrant
364         final ReusableNormalizedNodePruner pruner = ReusableNormalizedNodePruner.forDataSchemaContext(
365             dataSchemaContext);
366         return uintAdapting ? new PruningDataTreeModification.Proactive(unwrapped, dataTree, pruner.withUintAdaption())
367                 : new PruningDataTreeModification.Reactive(unwrapped, dataTree, pruner);
368     }
369
370     /**
371      * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
372      * pruning in an attempt to adjust the state to our current SchemaContext.
373      *
374      * @param payload Payload
375      * @throws IOException when the snapshot fails to deserialize
376      * @throws DataValidationFailedException when the snapshot fails to apply
377      */
378     final void applyRecoveryPayload(final @NonNull Payload payload) throws IOException {
379         if (payload instanceof CommitTransactionPayload) {
380             applyRecoveryCandidate((CommitTransactionPayload) payload);
381         } else if (payload instanceof AbortTransactionPayload) {
382             allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
383         } else if (payload instanceof PurgeTransactionPayload) {
384             allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
385         } else if (payload instanceof CreateLocalHistoryPayload) {
386             allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
387         } else if (payload instanceof CloseLocalHistoryPayload) {
388             allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
389         } else if (payload instanceof PurgeLocalHistoryPayload) {
390             allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
391         } else if (payload instanceof SkipTransactionsPayload) {
392             allMetadataSkipTransactions((SkipTransactionsPayload) payload);
393         } else {
394             LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
395         }
396     }
397
398     private void applyReplicatedCandidate(final CommitTransactionPayload payload)
399             throws DataValidationFailedException, IOException {
400         final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> entry = payload.acquireCandidate();
401         final TransactionIdentifier identifier = entry.getKey();
402         LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
403
404         final DataTreeModification mod = newModification();
405         // TODO: check version here, which will enable us to perform forward-compatibility transformations
406         DataTreeCandidates.applyToModification(mod, entry.getValue().getCandidate());
407         mod.ready();
408
409         LOG.trace("{}: Applying foreign modification {}", logContext, mod);
410         dataTree.validate(mod);
411         final DataTreeCandidate candidate = dataTree.prepare(mod);
412         dataTree.commit(candidate);
413
414         allMetadataCommittedTransaction(identifier);
415         notifyListeners(candidate);
416     }
417
418     /**
419      * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
420      * SchemaContexts match and does not perform any pruning.
421      *
422      * @param identifier Payload identifier as returned from RaftActor
423      * @param payload Payload
424      * @throws IOException when the snapshot fails to deserialize
425      * @throws DataValidationFailedException when the snapshot fails to apply
426      */
427     final void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
428             DataValidationFailedException {
429         /*
430          * This is a bit more involved than it needs to be due to to the fact we do not want to be touching the payload
431          * if we are the leader and it has originated with us.
432          *
433          * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
434          * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
435          * acting in that capacity anymore.
436          *
437          * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
438          * pre-Boron state -- which limits the number of options here.
439          */
440         if (payload instanceof CommitTransactionPayload) {
441             if (identifier == null) {
442                 applyReplicatedCandidate((CommitTransactionPayload) payload);
443             } else {
444                 verify(identifier instanceof TransactionIdentifier);
445                 // if we did not track this transaction before, it means that it came from another leader and we are in
446                 // the process of commiting it while in PreLeader state. That means that it hasnt yet been committed to
447                 // the local DataTree and would be lost if it was only applied via payloadReplicationComplete().
448                 if (!payloadReplicationComplete((TransactionIdentifier) identifier)) {
449                     applyReplicatedCandidate((CommitTransactionPayload) payload);
450                 }
451             }
452
453             // make sure acquireCandidate() is the last call touching the payload data as we want it to be GC-ed.
454             checkRootOverwrite(((CommitTransactionPayload) payload).acquireCandidate().getValue()
455                     .getCandidate());
456         } else if (payload instanceof AbortTransactionPayload) {
457             if (identifier != null) {
458                 payloadReplicationComplete((AbortTransactionPayload) payload);
459             }
460             allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
461         } else if (payload instanceof PurgeTransactionPayload) {
462             if (identifier != null) {
463                 payloadReplicationComplete((PurgeTransactionPayload) payload);
464             }
465             allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
466         } else if (payload instanceof CloseLocalHistoryPayload) {
467             if (identifier != null) {
468                 payloadReplicationComplete((CloseLocalHistoryPayload) payload);
469             }
470             allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
471         } else if (payload instanceof CreateLocalHistoryPayload) {
472             if (identifier != null) {
473                 payloadReplicationComplete((CreateLocalHistoryPayload)payload);
474             }
475             allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
476         } else if (payload instanceof PurgeLocalHistoryPayload) {
477             if (identifier != null) {
478                 payloadReplicationComplete((PurgeLocalHistoryPayload)payload);
479             }
480             allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
481         } else if (payload instanceof SkipTransactionsPayload) {
482             if (identifier != null) {
483                 payloadReplicationComplete((SkipTransactionsPayload)payload);
484             }
485             allMetadataSkipTransactions((SkipTransactionsPayload) payload);
486         } else {
487             LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
488         }
489     }
490
491     private void checkRootOverwrite(final DataTreeCandidate candidate) {
492         final DatastoreContext datastoreContext = shard.getDatastoreContext();
493         if (!datastoreContext.isSnapshotOnRootOverwrite()) {
494             return;
495         }
496
497         if (!datastoreContext.isPersistent()) {
498             // FIXME: why don't we want a snapshot in non-persistent state?
499             return;
500         }
501
502         // top level container ie "/"
503         if (candidate.getRootPath().isEmpty()
504                 && candidate.getRootNode().getModificationType() == ModificationType.WRITE) {
505             LOG.debug("{}: shard root overwritten, enqueuing snapshot", logContext);
506             shard.self().tell(new InitiateCaptureSnapshot(), noSender());
507         }
508     }
509
510     private void replicatePayload(final Identifier id, final Payload payload, final @Nullable Runnable callback) {
511         if (callback != null) {
512             replicationCallbacks.put(payload, callback);
513         }
514         shard.persistPayload(id, payload, true);
515     }
516
517     private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
518         final Runnable callback = replicationCallbacks.remove(payload);
519         if (callback != null) {
520             LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
521             callback.run();
522         } else {
523             LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
524         }
525     }
526
527     private boolean payloadReplicationComplete(final TransactionIdentifier txId) {
528         final CommitEntry current = pendingFinishCommits.peek();
529         if (current == null) {
530             LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
531             allMetadataCommittedTransaction(txId);
532             return false;
533         }
534
535         if (!current.cohort.getIdentifier().equals(txId)) {
536             LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
537                 current.cohort.getIdentifier(), txId);
538             allMetadataCommittedTransaction(txId);
539             return false;
540         }
541
542         finishCommit(current.cohort);
543         return true;
544     }
545
546     private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
547         for (ShardDataTreeMetadata<?> m : metadata) {
548             m.onTransactionAborted(txId);
549         }
550     }
551
552     private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
553         for (ShardDataTreeMetadata<?> m : metadata) {
554             m.onTransactionCommitted(txId);
555         }
556     }
557
558     private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
559         for (ShardDataTreeMetadata<?> m : metadata) {
560             m.onTransactionPurged(txId);
561         }
562     }
563
564     private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
565         for (ShardDataTreeMetadata<?> m : metadata) {
566             m.onHistoryCreated(historyId);
567         }
568     }
569
570     private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
571         for (ShardDataTreeMetadata<?> m : metadata) {
572             m.onHistoryClosed(historyId);
573         }
574     }
575
576     private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
577         for (ShardDataTreeMetadata<?> m : metadata) {
578             m.onHistoryPurged(historyId);
579         }
580     }
581
582     private void allMetadataSkipTransactions(final SkipTransactionsPayload payload) {
583         final var historyId = payload.getIdentifier();
584         final var txIds = payload.getTransactionIds();
585         for (ShardDataTreeMetadata<?> m : metadata) {
586             m.onTransactionsSkipped(historyId, txIds);
587         }
588     }
589
590     /**
591      * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
592      * this method is used for re-establishing state when we are taking over
593      *
594      * @param historyId Local history identifier
595      * @param closed True if the chain should be created in closed state (i.e. pending purge)
596      * @return Transaction chain handle
597      */
598     final ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
599             final boolean closed) {
600         final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
601         final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
602         checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId, existing);
603         return ret;
604     }
605
606     final ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId,
607             final @Nullable Runnable callback) {
608         ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
609         if (chain == null) {
610             chain = new ShardDataTreeTransactionChain(historyId, this);
611             transactionChains.put(historyId, chain);
612             replicatePayload(historyId, CreateLocalHistoryPayload.create(
613                     historyId, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
614         } else if (callback != null) {
615             callback.run();
616         }
617
618         return chain;
619     }
620
621     final @NonNull ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
622         shard.getShardMBean().incrementReadOnlyTransactionCount();
623
624         final var historyId = txId.getHistoryId();
625         return historyId.getHistoryId() == 0 ? newStandaloneReadOnlyTransaction(txId)
626             : ensureTransactionChain(historyId, null).newReadOnlyTransaction(txId);
627     }
628
629     final @NonNull ReadOnlyShardDataTreeTransaction newStandaloneReadOnlyTransaction(final TransactionIdentifier txId) {
630         return new ReadOnlyShardDataTreeTransaction(this, txId, takeSnapshot());
631     }
632
633     final @NonNull ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
634         shard.getShardMBean().incrementReadWriteTransactionCount();
635
636         final var historyId = txId.getHistoryId();
637         return historyId.getHistoryId() == 0 ? newStandaloneReadWriteTransaction(txId)
638             : ensureTransactionChain(historyId, null).newReadWriteTransaction(txId);
639     }
640
641     final @NonNull ReadWriteShardDataTreeTransaction newStandaloneReadWriteTransaction(
642             final TransactionIdentifier txId) {
643         return new ReadWriteShardDataTreeTransaction(this, txId, newModification());
644     }
645
646     @VisibleForTesting
647     final void notifyListeners(final DataTreeCandidate candidate) {
648         treeChangeListenerPublisher.publishChanges(candidate);
649     }
650
651     /**
652      * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
653      * replication callbacks.
654      */
655     final void purgeLeaderState() {
656         for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
657             chain.close();
658         }
659
660         transactionChains.clear();
661         replicationCallbacks.clear();
662     }
663
664     /**
665      * Close a single transaction chain.
666      *
667      * @param id History identifier
668      * @param callback Callback to invoke upon completion, may be null
669      */
670     final void closeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
671         if (commonCloseTransactionChain(id, callback)) {
672             replicatePayload(id, CloseLocalHistoryPayload.create(id,
673                 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
674         }
675     }
676
677     /**
678      * Close a single transaction chain which is received through ask-based protocol. It does not keep a commit record.
679      *
680      * @param id History identifier
681      */
682     final void closeTransactionChain(final LocalHistoryIdentifier id) {
683         commonCloseTransactionChain(id, null);
684     }
685
686     private boolean commonCloseTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
687         final ShardDataTreeTransactionChain chain = transactionChains.get(id);
688         if (chain == null) {
689             LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
690             if (callback != null) {
691                 callback.run();
692             }
693             return false;
694         }
695
696         chain.close();
697         return true;
698     }
699
700     /**
701      * Purge a single transaction chain.
702      *
703      * @param id History identifier
704      * @param callback Callback to invoke upon completion, may be null
705      */
706     final void purgeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
707         final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
708         if (chain == null) {
709             LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
710             if (callback != null) {
711                 callback.run();
712             }
713             return;
714         }
715
716         replicatePayload(id, PurgeLocalHistoryPayload.create(
717                 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
718     }
719
720     final void skipTransactions(final LocalHistoryIdentifier id, final ImmutableUnsignedLongSet transactionIds,
721             final Runnable callback) {
722         final ShardDataTreeTransactionChain chain = transactionChains.get(id);
723         if (chain == null) {
724             LOG.debug("{}: Skipping on non-existent transaction chain {}", logContext, id);
725             if (callback != null) {
726                 callback.run();
727             }
728             return;
729         }
730
731         replicatePayload(id, SkipTransactionsPayload.create(id, transactionIds,
732             shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
733     }
734
735     final Optional<DataTreeCandidate> readCurrentData() {
736         return readNode(YangInstanceIdentifier.empty())
737             .map(state -> DataTreeCandidates.fromNormalizedNode(YangInstanceIdentifier.empty(), state));
738     }
739
740     final void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
741             final Optional<DataTreeCandidate> initialState,
742             final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
743         treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
744     }
745
746     final int getQueueSize() {
747         return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
748     }
749
750     @Override
751     final void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
752         final TransactionIdentifier id = transaction.getIdentifier();
753         LOG.debug("{}: aborting transaction {}", logContext, id);
754         replicatePayload(id, AbortTransactionPayload.create(
755                 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
756     }
757
758     @Override
759     final void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
760         // No-op for free-standing transactions
761     }
762
763     @Override
764     final ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction,
765             final Optional<SortedSet<String>> participatingShardNames) {
766         final DataTreeModification snapshot = transaction.getSnapshot();
767         final TransactionIdentifier id = transaction.getIdentifier();
768         LOG.debug("{}: readying transaction {}", logContext, id);
769         snapshot.ready();
770         LOG.debug("{}: transaction {} ready", logContext, id);
771
772         return createReadyCohort(transaction.getIdentifier(), snapshot, participatingShardNames);
773     }
774
775     final void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
776         LOG.debug("{}: purging transaction {}", logContext, id);
777         replicatePayload(id, PurgeTransactionPayload.create(
778                 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
779     }
780
781     @VisibleForTesting
782     public final Optional<NormalizedNode> readNode(final YangInstanceIdentifier path) {
783         return takeSnapshot().readNode(path);
784     }
785
786     final DataTreeSnapshot takeSnapshot() {
787         return dataTree.takeSnapshot();
788     }
789
790     @VisibleForTesting
791     final DataTreeModification newModification() {
792         return takeSnapshot().newModification();
793     }
794
795     final Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
796         Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
797
798         for (CommitEntry entry: pendingFinishCommits) {
799             ret.add(entry.cohort);
800         }
801
802         for (CommitEntry entry: pendingCommits) {
803             ret.add(entry.cohort);
804         }
805
806         for (CommitEntry entry: pendingTransactions) {
807             ret.add(entry.cohort);
808         }
809
810         pendingFinishCommits.clear();
811         pendingCommits.clear();
812         pendingTransactions.clear();
813         tip = dataTree;
814         return ret;
815     }
816
817     /**
818      * Called some time after {@link #processNextPendingTransaction()} decides to stop processing.
819      */
820     final void resumeNextPendingTransaction() {
821         LOG.debug("{}: attempting to resume transaction processing", logContext);
822         processNextPending();
823     }
824
825     @SuppressWarnings("checkstyle:IllegalCatch")
826     private void processNextPendingTransaction() {
827         ++currentTransactionBatch;
828         if (currentTransactionBatch > MAX_TRANSACTION_BATCH) {
829             LOG.debug("{}: Already processed {}, scheduling continuation", logContext, currentTransactionBatch);
830             shard.scheduleNextPendingTransaction();
831             return;
832         }
833
834         processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
835             final SimpleShardDataTreeCohort cohort = entry.cohort;
836             final DataTreeModification modification = cohort.getDataTreeModification();
837
838             LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
839             Exception cause;
840             try {
841                 tip.validate(modification);
842                 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
843                 cohort.successfulCanCommit();
844                 entry.lastAccess = readTime();
845                 return;
846             } catch (ConflictingModificationAppliedException e) {
847                 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
848                     e.getPath());
849                 cause = new OptimisticLockFailedException("Optimistic lock failed for path " + e.getPath(), e);
850             } catch (DataValidationFailedException e) {
851                 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
852                     e.getPath(), e);
853
854                 // For debugging purposes, allow dumping of the modification. Coupled with the above
855                 // precondition log, it should allow us to understand what went on.
856                 LOG.debug("{}: Store Tx {}: modifications: {}", logContext, cohort.getIdentifier(), modification);
857                 LOG.trace("{}: Current tree: {}", logContext, dataTree);
858                 cause = new TransactionCommitFailedException("Data did not pass validation for path " + e.getPath(), e);
859             } catch (Exception e) {
860                 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
861                 cause = e;
862             }
863
864             // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
865             pendingTransactions.poll().cohort.failedCanCommit(cause);
866         });
867     }
868
869     private void processNextPending() {
870         processNextPendingCommit();
871         processNextPendingTransaction();
872     }
873
874     private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
875             final Consumer<CommitEntry> processor) {
876         while (!queue.isEmpty()) {
877             final CommitEntry entry = queue.peek();
878             final SimpleShardDataTreeCohort cohort = entry.cohort;
879
880             if (cohort.isFailed()) {
881                 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
882                 queue.remove();
883                 continue;
884             }
885
886             if (cohort.getState() == allowedState) {
887                 processor.accept(entry);
888             }
889
890             break;
891         }
892
893         maybeRunOperationOnPendingTransactionsComplete();
894     }
895
896     private void processNextPendingCommit() {
897         processNextPending(pendingCommits, State.COMMIT_PENDING,
898             entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
899     }
900
901     private boolean peekNextPendingCommit() {
902         final CommitEntry first = pendingCommits.peek();
903         return first != null && first.cohort.getState() == State.COMMIT_PENDING;
904     }
905
906     // non-final for mocking
907     void startCanCommit(final SimpleShardDataTreeCohort cohort) {
908         final CommitEntry head = pendingTransactions.peek();
909         if (head == null) {
910             LOG.warn("{}: No transactions enqueued while attempting to start canCommit on {}", logContext, cohort);
911             return;
912         }
913         if (!cohort.equals(head.cohort)) {
914             // The tx isn't at the head of the queue so we can't start canCommit at this point. Here we check if this
915             // tx should be moved ahead of other tx's in the READY state in the pendingTransactions queue. If this tx
916             // has other participating shards, it could deadlock with other tx's accessing the same shards
917             // depending on the order the tx's are readied on each shard
918             // (see https://jira.opendaylight.org/browse/CONTROLLER-1836). Therefore, if the preceding participating
919             // shard names for a preceding pending tx, call it A, in the queue matches that of this tx, then this tx
920             // is allowed to be moved ahead of tx A in the queue so it is processed first to avoid potential deadlock
921             // if tx A is behind this tx in the pendingTransactions queue for a preceding shard. In other words, since
922             // canCommmit for this tx was requested before tx A, honor that request. If this tx is moved to the head of
923             // the queue as a result, then proceed with canCommit.
924
925             Collection<String> precedingShardNames = extractPrecedingShardNames(cohort.getParticipatingShardNames());
926             if (precedingShardNames.isEmpty()) {
927                 LOG.debug("{}: Tx {} is scheduled for canCommit step", logContext, cohort.getIdentifier());
928                 return;
929             }
930
931             LOG.debug("{}: Evaluating tx {} for canCommit -  preceding participating shard names {}",
932                     logContext, cohort.getIdentifier(), precedingShardNames);
933             final Iterator<CommitEntry> iter = pendingTransactions.iterator();
934             int index = -1;
935             int moveToIndex = -1;
936             while (iter.hasNext()) {
937                 final CommitEntry entry = iter.next();
938                 ++index;
939
940                 if (cohort.equals(entry.cohort)) {
941                     if (moveToIndex < 0) {
942                         LOG.debug("{}: Not moving tx {} - cannot proceed with canCommit",
943                                 logContext, cohort.getIdentifier());
944                         return;
945                     }
946
947                     LOG.debug("{}: Moving {} to index {} in the pendingTransactions queue",
948                             logContext, cohort.getIdentifier(), moveToIndex);
949                     iter.remove();
950                     insertEntry(pendingTransactions, entry, moveToIndex);
951
952                     if (!cohort.equals(pendingTransactions.peek().cohort)) {
953                         LOG.debug("{}: Tx {} is not at the head of the queue - cannot proceed with canCommit",
954                                 logContext, cohort.getIdentifier());
955                         return;
956                     }
957
958                     LOG.debug("{}: Tx {} is now at the head of the queue - proceeding with canCommit",
959                             logContext, cohort.getIdentifier());
960                     break;
961                 }
962
963                 if (entry.cohort.getState() != State.READY) {
964                     LOG.debug("{}: Skipping pending transaction {} in state {}",
965                             logContext, entry.cohort.getIdentifier(), entry.cohort.getState());
966                     continue;
967                 }
968
969                 final Collection<String> pendingPrecedingShardNames = extractPrecedingShardNames(
970                         entry.cohort.getParticipatingShardNames());
971
972                 if (precedingShardNames.equals(pendingPrecedingShardNames)) {
973                     if (moveToIndex < 0) {
974                         LOG.debug("{}: Preceding shard names {} for pending tx {} match - saving moveToIndex {}",
975                                 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), index);
976                         moveToIndex = index;
977                     } else {
978                         LOG.debug(
979                             "{}: Preceding shard names {} for pending tx {} match but moveToIndex already set to {}",
980                             logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), moveToIndex);
981                     }
982                 } else {
983                     LOG.debug("{}: Preceding shard names {} for pending tx {} differ - skipping",
984                         logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier());
985                 }
986             }
987         }
988
989         processNextPendingTransaction();
990     }
991
992     private static void insertEntry(final Deque<CommitEntry> queue, final CommitEntry entry, final int atIndex) {
993         if (atIndex == 0) {
994             queue.addFirst(entry);
995             return;
996         }
997
998         LOG.trace("Inserting into Deque at index {}", atIndex);
999
1000         Deque<CommitEntry> tempStack = new ArrayDeque<>(atIndex);
1001         for (int i = 0; i < atIndex; i++) {
1002             tempStack.push(queue.poll());
1003         }
1004
1005         queue.addFirst(entry);
1006
1007         tempStack.forEach(queue::addFirst);
1008     }
1009
1010     private Collection<String> extractPrecedingShardNames(final Optional<SortedSet<String>> participatingShardNames) {
1011         return participatingShardNames.map((Function<SortedSet<String>, Collection<String>>)
1012             set -> set.headSet(shard.getShardName())).orElse(Collections.<String>emptyList());
1013     }
1014
1015     private void failPreCommit(final Throwable cause) {
1016         shard.getShardMBean().incrementFailedTransactionsCount();
1017         pendingTransactions.poll().cohort.failedPreCommit(cause);
1018         processNextPendingTransaction();
1019     }
1020
1021     // non-final for mocking
1022     @SuppressWarnings("checkstyle:IllegalCatch")
1023     void startPreCommit(final SimpleShardDataTreeCohort cohort) {
1024         final CommitEntry entry = pendingTransactions.peek();
1025         checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
1026
1027         final SimpleShardDataTreeCohort current = entry.cohort;
1028         verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
1029
1030         final TransactionIdentifier currentId = current.getIdentifier();
1031         LOG.debug("{}: Preparing transaction {}", logContext, currentId);
1032
1033         final DataTreeCandidateTip candidate;
1034         try {
1035             candidate = tip.prepare(cohort.getDataTreeModification());
1036             LOG.debug("{}: Transaction {} candidate ready", logContext, currentId);
1037         } catch (DataValidationFailedException | RuntimeException e) {
1038             failPreCommit(e);
1039             return;
1040         }
1041
1042         cohort.userPreCommit(candidate, new FutureCallback<>() {
1043             @Override
1044             public void onSuccess(final Empty result) {
1045                 // Set the tip of the data tree.
1046                 tip = verifyNotNull(candidate);
1047
1048                 entry.lastAccess = readTime();
1049
1050                 pendingTransactions.remove();
1051                 pendingCommits.add(entry);
1052
1053                 LOG.debug("{}: Transaction {} prepared", logContext, currentId);
1054
1055                 cohort.successfulPreCommit(candidate);
1056
1057                 processNextPendingTransaction();
1058             }
1059
1060             @Override
1061             public void onFailure(final Throwable failure) {
1062                 failPreCommit(failure);
1063             }
1064         });
1065     }
1066
1067     private void failCommit(final Exception cause) {
1068         shard.getShardMBean().incrementFailedTransactionsCount();
1069         pendingFinishCommits.poll().cohort.failedCommit(cause);
1070         processNextPending();
1071     }
1072
1073     @SuppressWarnings("checkstyle:IllegalCatch")
1074     private void finishCommit(final SimpleShardDataTreeCohort cohort) {
1075         final TransactionIdentifier txId = cohort.getIdentifier();
1076         final DataTreeCandidate candidate = cohort.getCandidate();
1077
1078         LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
1079
1080         if (tip == candidate) {
1081             // All pending candidates have been committed, reset the tip to the data tree.
1082             tip = dataTree;
1083         }
1084
1085         try {
1086             dataTree.commit(candidate);
1087         } catch (Exception e) {
1088             LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
1089             failCommit(e);
1090             return;
1091         }
1092
1093         allMetadataCommittedTransaction(txId);
1094         shard.getShardMBean().incrementCommittedTransactionCount();
1095         shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
1096
1097         // FIXME: propagate journal index
1098         pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO, () -> {
1099             LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
1100             notifyListeners(candidate);
1101
1102             processNextPending();
1103         });
1104     }
1105
1106     // non-final for mocking
1107     void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
1108         final CommitEntry entry = pendingCommits.peek();
1109         checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
1110
1111         final SimpleShardDataTreeCohort current = entry.cohort;
1112         if (!cohort.equals(current)) {
1113             LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
1114             return;
1115         }
1116
1117         LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
1118
1119         final TransactionIdentifier txId = cohort.getIdentifier();
1120         final Payload payload;
1121         try {
1122             payload = CommitTransactionPayload.create(txId, candidate, PayloadVersion.current(),
1123                     shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity());
1124         } catch (IOException e) {
1125             LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
1126             pendingCommits.poll().cohort.failedCommit(e);
1127             processNextPending();
1128             return;
1129         }
1130
1131         // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
1132         // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
1133         // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
1134         // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
1135         // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
1136         // pendingCommits queue.
1137         processNextPendingTransaction();
1138
1139         // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
1140         // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
1141         // in order to properly determine the batchHint flag for the call to persistPayload.
1142         pendingCommits.remove();
1143         pendingFinishCommits.add(entry);
1144
1145         // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
1146         // this transaction for replication.
1147         boolean replicationBatchHint = peekNextPendingCommit();
1148
1149         // Once completed, we will continue via payloadReplicationComplete
1150         shard.persistPayload(txId, payload, replicationBatchHint);
1151
1152         entry.lastAccess = shard.ticker().read();
1153
1154         LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
1155
1156         // Process the next transaction pending commit, if any. If there is one it will be batched with this
1157         // transaction for replication.
1158         processNextPendingCommit();
1159     }
1160
1161     final Collection<ActorRef> getCohortActors() {
1162         return cohortRegistry.getCohortActors();
1163     }
1164
1165     final void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
1166         cohortRegistry.process(sender, message);
1167     }
1168
1169     @Override
1170     final ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1171             final Exception failure) {
1172         final SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId, failure);
1173         pendingTransactions.add(new CommitEntry(cohort, readTime()));
1174         return cohort;
1175     }
1176
1177     @Override
1178     final ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1179             final Optional<SortedSet<String>> participatingShardNames) {
1180         SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId,
1181                 cohortRegistry.createCohort(schemaContext, txId, shard::executeInSelf,
1182                         COMMIT_STEP_TIMEOUT), participatingShardNames);
1183         pendingTransactions.add(new CommitEntry(cohort, readTime()));
1184         return cohort;
1185     }
1186
1187     // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
1188     // the newReadWriteTransaction()
1189     final ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1190             final Optional<SortedSet<String>> participatingShardNames) {
1191         final var historyId = txId.getHistoryId();
1192         if (historyId.getHistoryId() == 0) {
1193             return createReadyCohort(txId, mod, participatingShardNames);
1194         }
1195         return ensureTransactionChain(historyId, null).createReadyCohort(txId, mod, participatingShardNames);
1196     }
1197
1198     @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
1199     final void checkForExpiredTransactions(final long transactionCommitTimeoutMillis,
1200             final Function<SimpleShardDataTreeCohort, OptionalLong> accessTimeUpdater) {
1201         final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
1202         final long now = readTime();
1203
1204         final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
1205             !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
1206         final CommitEntry currentTx = currentQueue.peek();
1207         if (currentTx == null) {
1208             // Empty queue, no-op
1209             return;
1210         }
1211
1212         long delta = now - currentTx.lastAccess;
1213         if (delta < timeout) {
1214             // Not expired yet, bail
1215             return;
1216         }
1217
1218         final OptionalLong updateOpt = accessTimeUpdater.apply(currentTx.cohort);
1219         if (updateOpt.isPresent()) {
1220             final long newAccess =  updateOpt.getAsLong();
1221             final long newDelta = now - newAccess;
1222             if (newDelta < delta) {
1223                 LOG.debug("{}: Updated current transaction {} access time", logContext,
1224                     currentTx.cohort.getIdentifier());
1225                 currentTx.lastAccess = newAccess;
1226                 delta = newDelta;
1227             }
1228
1229             if (delta < timeout) {
1230                 // Not expired yet, bail
1231                 return;
1232             }
1233         }
1234
1235         final long deltaMillis = TimeUnit.NANOSECONDS.toMillis(delta);
1236         final State state = currentTx.cohort.getState();
1237
1238         LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
1239             currentTx.cohort.getIdentifier(), deltaMillis, state);
1240         boolean processNext = true;
1241         final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
1242                 + deltaMillis + "ms");
1243
1244         switch (state) {
1245             case CAN_COMMIT_PENDING:
1246                 currentQueue.remove().cohort.failedCanCommit(cohortFailure);
1247                 break;
1248             case CAN_COMMIT_COMPLETE:
1249                 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
1250                 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
1251                 // in PRE_COMMIT_COMPLETE is changed.
1252                 currentQueue.remove().cohort.reportFailure(cohortFailure);
1253                 break;
1254             case PRE_COMMIT_PENDING:
1255                 currentQueue.remove().cohort.failedPreCommit(cohortFailure);
1256                 break;
1257             case PRE_COMMIT_COMPLETE:
1258                 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
1259                 //        are ready we should commit the transaction, not abort it. Our current software stack does
1260                 //        not allow us to do that consistently, because we persist at the time of commit, hence
1261                 //        we can end up in a state where we have pre-committed a transaction, then a leader failover
1262                 //        occurred ... the new leader does not see the pre-committed transaction and does not have
1263                 //        a running timer. To fix this we really need two persistence events.
1264                 //
1265                 //        The first one, done at pre-commit time will hold the transaction payload. When consensus
1266                 //        is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1267                 //        apply the state in this event.
1268                 //
1269                 //        The second one, done at commit (or abort) time holds only the transaction identifier and
1270                 //        signals to followers that the state should (or should not) be applied.
1271                 //
1272                 //        In order to make the pre-commit timer working across failovers, though, we need
1273                 //        a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1274                 //        restart the timer.
1275                 currentQueue.remove().cohort.reportFailure(cohortFailure);
1276                 break;
1277             case COMMIT_PENDING:
1278                 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1279                     currentTx.cohort.getIdentifier());
1280                 currentTx.lastAccess = now;
1281                 processNext = false;
1282                 return;
1283             case READY:
1284                 currentQueue.remove().cohort.reportFailure(cohortFailure);
1285                 break;
1286             case ABORTED:
1287             case COMMITTED:
1288             case FAILED:
1289             default:
1290                 currentQueue.remove();
1291         }
1292
1293         if (processNext) {
1294             processNextPending();
1295         }
1296     }
1297
1298     // non-final for mocking
1299     boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1300         final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1301                 pendingTransactions).iterator();
1302         if (!it.hasNext()) {
1303             LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1304             return true;
1305         }
1306
1307         // First entry is special, as it may already be committing
1308         final CommitEntry first = it.next();
1309         if (cohort.equals(first.cohort)) {
1310             if (cohort.getState() != State.COMMIT_PENDING) {
1311                 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1312                     cohort.getIdentifier());
1313
1314                 it.remove();
1315                 if (cohort.getCandidate() != null) {
1316                     rebaseTransactions(it, dataTree);
1317                 }
1318
1319                 processNextPending();
1320                 return true;
1321             }
1322
1323             LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1324             return false;
1325         }
1326
1327         DataTreeTip newTip = requireNonNullElse(first.cohort.getCandidate(), dataTree);
1328         while (it.hasNext()) {
1329             final CommitEntry e = it.next();
1330             if (cohort.equals(e.cohort)) {
1331                 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1332
1333                 it.remove();
1334                 if (cohort.getCandidate() != null) {
1335                     rebaseTransactions(it, newTip);
1336                 }
1337
1338                 return true;
1339             } else {
1340                 newTip = requireNonNullElse(e.cohort.getCandidate(), newTip);
1341             }
1342         }
1343
1344         LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1345         return true;
1346     }
1347
1348     @SuppressWarnings("checkstyle:IllegalCatch")
1349     private void rebaseTransactions(final Iterator<CommitEntry> iter, final @NonNull DataTreeTip newTip) {
1350         tip = requireNonNull(newTip);
1351         while (iter.hasNext()) {
1352             final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1353             if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1354                 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1355
1356                 try {
1357                     tip.validate(cohort.getDataTreeModification());
1358                 } catch (DataValidationFailedException | RuntimeException e) {
1359                     LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1360                     cohort.reportFailure(e);
1361                 }
1362             } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1363                 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1364
1365                 try {
1366                     tip.validate(cohort.getDataTreeModification());
1367                     DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1368
1369                     cohort.setNewCandidate(candidate);
1370                     tip = candidate;
1371                 } catch (RuntimeException | DataValidationFailedException e) {
1372                     LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1373                     cohort.reportFailure(e);
1374                 }
1375             }
1376         }
1377     }
1378
1379     final void setRunOnPendingTransactionsComplete(final Runnable operation) {
1380         runOnPendingTransactionsComplete = operation;
1381         maybeRunOperationOnPendingTransactionsComplete();
1382     }
1383
1384     private void maybeRunOperationOnPendingTransactionsComplete() {
1385         if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1386             LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1387                     runOnPendingTransactionsComplete);
1388
1389             runOnPendingTransactionsComplete.run();
1390             runOnPendingTransactionsComplete = null;
1391         }
1392     }
1393
1394     final ShardStats getStats() {
1395         return shard.getShardMBean();
1396     }
1397
1398     final Iterator<SimpleShardDataTreeCohort> cohortIterator() {
1399         return Iterables.transform(Iterables.concat(pendingFinishCommits, pendingCommits, pendingTransactions),
1400             e -> e.cohort).iterator();
1401     }
1402
1403     final void removeTransactionChain(final LocalHistoryIdentifier id) {
1404         if (transactionChains.remove(id) != null) {
1405             LOG.debug("{}: Removed transaction chain {}", logContext, id);
1406         }
1407     }
1408 }