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