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