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