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