c316fdfb9e6b768b2ab5850c1068957527b36da5
[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
16 import akka.actor.ActorRef;
17 import akka.util.Timeout;
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.base.MoreObjects;
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(DataTreeCandidate candidate) {
479         final DatastoreContext datastoreContext = shard.getDatastoreContext();
480         if (!datastoreContext.isSnapshotOnRootOverwrite()) {
481             return;
482         }
483
484         if (!datastoreContext.isPersistent()) {
485             return;
486         }
487
488         if (candidate.getRootNode().getModificationType().equals(ModificationType.UNMODIFIED)) {
489             return;
490         }
491
492         // top level container ie "/"
493         if ((candidate.getRootPath().equals(YangInstanceIdentifier.empty())
494                 && candidate.getRootNode().getModificationType().equals(ModificationType.WRITE))) {
495             LOG.debug("{}: shard root overwritten, enqueuing snapshot", logContext);
496             shard.self().tell(new InitiateCaptureSnapshot(), noSender());
497             return;
498         }
499     }
500
501     private void replicatePayload(final Identifier id, final Payload payload, final @Nullable Runnable callback) {
502         if (callback != null) {
503             replicationCallbacks.put(payload, callback);
504         }
505         shard.persistPayload(id, payload, true);
506     }
507
508     private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
509         final Runnable callback = replicationCallbacks.remove(payload);
510         if (callback != null) {
511             LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
512             callback.run();
513         } else {
514             LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
515         }
516     }
517
518     private boolean payloadReplicationComplete(final TransactionIdentifier txId) {
519         final CommitEntry current = pendingFinishCommits.peek();
520         if (current == null) {
521             LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
522             allMetadataCommittedTransaction(txId);
523             return false;
524         }
525
526         if (!current.cohort.getIdentifier().equals(txId)) {
527             LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
528                 current.cohort.getIdentifier(), txId);
529             allMetadataCommittedTransaction(txId);
530             return false;
531         }
532
533         finishCommit(current.cohort);
534         return true;
535     }
536
537     private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
538         for (ShardDataTreeMetadata<?> m : metadata) {
539             m.onTransactionAborted(txId);
540         }
541     }
542
543     private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
544         for (ShardDataTreeMetadata<?> m : metadata) {
545             m.onTransactionCommitted(txId);
546         }
547     }
548
549     private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
550         for (ShardDataTreeMetadata<?> m : metadata) {
551             m.onTransactionPurged(txId);
552         }
553     }
554
555     private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
556         for (ShardDataTreeMetadata<?> m : metadata) {
557             m.onHistoryCreated(historyId);
558         }
559     }
560
561     private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
562         for (ShardDataTreeMetadata<?> m : metadata) {
563             m.onHistoryClosed(historyId);
564         }
565     }
566
567     private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
568         for (ShardDataTreeMetadata<?> m : metadata) {
569             m.onHistoryPurged(historyId);
570         }
571     }
572
573     /**
574      * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
575      * this method is used for re-establishing state when we are taking over
576      *
577      * @param historyId Local history identifier
578      * @param closed True if the chain should be created in closed state (i.e. pending purge)
579      * @return Transaction chain handle
580      */
581     ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
582             final boolean closed) {
583         final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
584         final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
585         checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId, existing);
586         return ret;
587     }
588
589     ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId,
590             final @Nullable Runnable callback) {
591         ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
592         if (chain == null) {
593             chain = new ShardDataTreeTransactionChain(historyId, this);
594             transactionChains.put(historyId, chain);
595             replicatePayload(historyId, CreateLocalHistoryPayload.create(
596                     historyId, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
597         } else if (callback != null) {
598             callback.run();
599         }
600
601         return chain;
602     }
603
604     ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
605         shard.getShardMBean().incrementReadOnlyTransactionCount();
606
607         if (txId.getHistoryId().getHistoryId() == 0) {
608             return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
609         }
610
611         return ensureTransactionChain(txId.getHistoryId(), null).newReadOnlyTransaction(txId);
612     }
613
614     ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
615         shard.getShardMBean().incrementReadWriteTransactionCount();
616
617         if (txId.getHistoryId().getHistoryId() == 0) {
618             return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
619                     .newModification());
620         }
621
622         return ensureTransactionChain(txId.getHistoryId(), null).newReadWriteTransaction(txId);
623     }
624
625     @VisibleForTesting
626     public void notifyListeners(final DataTreeCandidate candidate) {
627         treeChangeListenerPublisher.publishChanges(candidate);
628     }
629
630     /**
631      * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
632      * replication callbacks.
633      */
634     void purgeLeaderState() {
635         for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
636             chain.close();
637         }
638
639         transactionChains.clear();
640         replicationCallbacks.clear();
641     }
642
643     /**
644      * Close a single transaction chain.
645      *
646      * @param id History identifier
647      * @param callback Callback to invoke upon completion, may be null
648      */
649     void closeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
650         if (commonCloseTransactionChain(id, callback)) {
651             replicatePayload(id, CloseLocalHistoryPayload.create(id,
652                 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
653         }
654     }
655
656     /**
657      * Close a single transaction chain which is received through ask-based protocol. It does not keep a commit record.
658      *
659      * @param id History identifier
660      */
661     void closeTransactionChain(final LocalHistoryIdentifier id) {
662         commonCloseTransactionChain(id, null);
663     }
664
665     private boolean commonCloseTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
666         final ShardDataTreeTransactionChain chain = transactionChains.get(id);
667         if (chain == null) {
668             LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
669             if (callback != null) {
670                 callback.run();
671             }
672             return false;
673         }
674
675         chain.close();
676         return true;
677     }
678
679     /**
680      * Purge a single transaction chain.
681      *
682      * @param id History identifier
683      * @param callback Callback to invoke upon completion, may be null
684      */
685     void purgeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
686         final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
687         if (chain == null) {
688             LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
689             if (callback != null) {
690                 callback.run();
691             }
692             return;
693         }
694
695         replicatePayload(id, PurgeLocalHistoryPayload.create(
696                 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
697     }
698
699     Optional<DataTreeCandidate> readCurrentData() {
700         return dataTree.takeSnapshot().readNode(YangInstanceIdentifier.empty())
701                 .map(state -> DataTreeCandidates.fromNormalizedNode(YangInstanceIdentifier.empty(), state));
702     }
703
704     public void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
705             final Optional<DataTreeCandidate> initialState,
706             final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
707         treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
708     }
709
710     int getQueueSize() {
711         return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
712     }
713
714     @Override
715     void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
716         final TransactionIdentifier id = transaction.getIdentifier();
717         LOG.debug("{}: aborting transaction {}", logContext, id);
718         replicatePayload(id, AbortTransactionPayload.create(
719                 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
720     }
721
722     @Override
723     void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
724         // No-op for free-standing transactions
725
726     }
727
728     @Override
729     ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction,
730             final Optional<SortedSet<String>> participatingShardNames) {
731         final DataTreeModification snapshot = transaction.getSnapshot();
732         final TransactionIdentifier id = transaction.getIdentifier();
733         LOG.debug("{}: readying transaction {}", logContext, id);
734         snapshot.ready();
735         LOG.debug("{}: transaction {} ready", logContext, id);
736
737         return createReadyCohort(transaction.getIdentifier(), snapshot, participatingShardNames);
738     }
739
740     void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
741         LOG.debug("{}: purging transaction {}", logContext, id);
742         replicatePayload(id, PurgeTransactionPayload.create(
743                 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
744     }
745
746     public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
747         return dataTree.takeSnapshot().readNode(path);
748     }
749
750     DataTreeSnapshot takeSnapshot() {
751         return dataTree.takeSnapshot();
752     }
753
754     @VisibleForTesting
755     public DataTreeModification newModification() {
756         return dataTree.takeSnapshot().newModification();
757     }
758
759     public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
760         Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
761
762         for (CommitEntry entry: pendingFinishCommits) {
763             ret.add(entry.cohort);
764         }
765
766         for (CommitEntry entry: pendingCommits) {
767             ret.add(entry.cohort);
768         }
769
770         for (CommitEntry entry: pendingTransactions) {
771             ret.add(entry.cohort);
772         }
773
774         pendingFinishCommits.clear();
775         pendingCommits.clear();
776         pendingTransactions.clear();
777         tip = dataTree;
778         return ret;
779     }
780
781     /**
782      * Called some time after {@link #processNextPendingTransaction()} decides to stop processing.
783      */
784     void resumeNextPendingTransaction() {
785         LOG.debug("{}: attempting to resume transaction processing", logContext);
786         processNextPending();
787     }
788
789     @SuppressWarnings("checkstyle:IllegalCatch")
790     private void processNextPendingTransaction() {
791         ++currentTransactionBatch;
792         if (currentTransactionBatch > MAX_TRANSACTION_BATCH) {
793             LOG.debug("{}: Already processed {}, scheduling continuation", logContext, currentTransactionBatch);
794             shard.scheduleNextPendingTransaction();
795             return;
796         }
797
798         processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
799             final SimpleShardDataTreeCohort cohort = entry.cohort;
800             final DataTreeModification modification = cohort.getDataTreeModification();
801
802             LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
803             Exception cause;
804             try {
805                 tip.validate(modification);
806                 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
807                 cohort.successfulCanCommit();
808                 entry.lastAccess = readTime();
809                 return;
810             } catch (ConflictingModificationAppliedException e) {
811                 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
812                     e.getPath());
813                 cause = new OptimisticLockFailedException("Optimistic lock failed for path " + e.getPath(), e);
814             } catch (DataValidationFailedException e) {
815                 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
816                     e.getPath(), e);
817
818                 // For debugging purposes, allow dumping of the modification. Coupled with the above
819                 // precondition log, it should allow us to understand what went on.
820                 LOG.debug("{}: Store Tx {}: modifications: {}", logContext, cohort.getIdentifier(), modification);
821                 LOG.trace("{}: Current tree: {}", logContext, dataTree);
822                 cause = new TransactionCommitFailedException("Data did not pass validation for path " + e.getPath(), e);
823             } catch (Exception e) {
824                 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
825                 cause = e;
826             }
827
828             // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
829             pendingTransactions.poll().cohort.failedCanCommit(cause);
830         });
831     }
832
833     private void processNextPending() {
834         processNextPendingCommit();
835         processNextPendingTransaction();
836     }
837
838     private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
839             final Consumer<CommitEntry> processor) {
840         while (!queue.isEmpty()) {
841             final CommitEntry entry = queue.peek();
842             final SimpleShardDataTreeCohort cohort = entry.cohort;
843
844             if (cohort.isFailed()) {
845                 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
846                 queue.remove();
847                 continue;
848             }
849
850             if (cohort.getState() == allowedState) {
851                 processor.accept(entry);
852             }
853
854             break;
855         }
856
857         maybeRunOperationOnPendingTransactionsComplete();
858     }
859
860     private void processNextPendingCommit() {
861         processNextPending(pendingCommits, State.COMMIT_PENDING,
862             entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
863     }
864
865     private boolean peekNextPendingCommit() {
866         final CommitEntry first = pendingCommits.peek();
867         return first != null && first.cohort.getState() == State.COMMIT_PENDING;
868     }
869
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     @SuppressWarnings("checkstyle:IllegalCatch")
985     void startPreCommit(final SimpleShardDataTreeCohort cohort) {
986         final CommitEntry entry = pendingTransactions.peek();
987         checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
988
989         final SimpleShardDataTreeCohort current = entry.cohort;
990         verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
991
992         final TransactionIdentifier currentId = current.getIdentifier();
993         LOG.debug("{}: Preparing transaction {}", logContext, currentId);
994
995         final DataTreeCandidateTip candidate;
996         try {
997             candidate = tip.prepare(cohort.getDataTreeModification());
998             LOG.debug("{}: Transaction {} candidate ready", logContext, currentId);
999         } catch (DataValidationFailedException | RuntimeException e) {
1000             failPreCommit(e);
1001             return;
1002         }
1003
1004         cohort.userPreCommit(candidate, new FutureCallback<Void>() {
1005             @Override
1006             public void onSuccess(final Void noop) {
1007                 // Set the tip of the data tree.
1008                 tip = verifyNotNull(candidate);
1009
1010                 entry.lastAccess = readTime();
1011
1012                 pendingTransactions.remove();
1013                 pendingCommits.add(entry);
1014
1015                 LOG.debug("{}: Transaction {} prepared", logContext, currentId);
1016
1017                 cohort.successfulPreCommit(candidate);
1018
1019                 processNextPendingTransaction();
1020             }
1021
1022             @Override
1023             public void onFailure(final Throwable failure) {
1024                 failPreCommit(failure);
1025             }
1026         });
1027     }
1028
1029     private void failCommit(final Exception cause) {
1030         shard.getShardMBean().incrementFailedTransactionsCount();
1031         pendingFinishCommits.poll().cohort.failedCommit(cause);
1032         processNextPending();
1033     }
1034
1035     @SuppressWarnings("checkstyle:IllegalCatch")
1036     private void finishCommit(final SimpleShardDataTreeCohort cohort) {
1037         final TransactionIdentifier txId = cohort.getIdentifier();
1038         final DataTreeCandidate candidate = cohort.getCandidate();
1039
1040         LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
1041
1042         if (tip == candidate) {
1043             // All pending candidates have been committed, reset the tip to the data tree.
1044             tip = dataTree;
1045         }
1046
1047         try {
1048             dataTree.commit(candidate);
1049         } catch (Exception e) {
1050             LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
1051             failCommit(e);
1052             return;
1053         }
1054
1055         allMetadataCommittedTransaction(txId);
1056         shard.getShardMBean().incrementCommittedTransactionCount();
1057         shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
1058
1059         // FIXME: propagate journal index
1060         pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO, () -> {
1061             LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
1062             notifyListeners(candidate);
1063
1064             processNextPending();
1065         });
1066     }
1067
1068     void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
1069         final CommitEntry entry = pendingCommits.peek();
1070         checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
1071
1072         final SimpleShardDataTreeCohort current = entry.cohort;
1073         if (!cohort.equals(current)) {
1074             LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
1075             return;
1076         }
1077
1078         LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
1079
1080         final TransactionIdentifier txId = cohort.getIdentifier();
1081         final Payload payload;
1082         try {
1083             payload = CommitTransactionPayload.create(txId, candidate, PayloadVersion.current(),
1084                     shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity());
1085         } catch (IOException e) {
1086             LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
1087             pendingCommits.poll().cohort.failedCommit(e);
1088             processNextPending();
1089             return;
1090         }
1091
1092         // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
1093         // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
1094         // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
1095         // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
1096         // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
1097         // pendingCommits queue.
1098         processNextPendingTransaction();
1099
1100         // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
1101         // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
1102         // in order to properly determine the batchHint flag for the call to persistPayload.
1103         pendingCommits.remove();
1104         pendingFinishCommits.add(entry);
1105
1106         // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
1107         // this transaction for replication.
1108         boolean replicationBatchHint = peekNextPendingCommit();
1109
1110         // Once completed, we will continue via payloadReplicationComplete
1111         shard.persistPayload(txId, payload, replicationBatchHint);
1112
1113         entry.lastAccess = shard.ticker().read();
1114
1115         LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
1116
1117         // Process the next transaction pending commit, if any. If there is one it will be batched with this
1118         // transaction for replication.
1119         processNextPendingCommit();
1120     }
1121
1122     Collection<ActorRef> getCohortActors() {
1123         return cohortRegistry.getCohortActors();
1124     }
1125
1126     void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
1127         cohortRegistry.process(sender, message);
1128     }
1129
1130     @Override
1131     ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1132             final Exception failure) {
1133         final SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId, failure);
1134         pendingTransactions.add(new CommitEntry(cohort, readTime()));
1135         return cohort;
1136     }
1137
1138     @Override
1139     ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1140             final Optional<SortedSet<String>> participatingShardNames) {
1141         SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId,
1142                 cohortRegistry.createCohort(schemaContext, txId, shard::executeInSelf,
1143                         COMMIT_STEP_TIMEOUT), participatingShardNames);
1144         pendingTransactions.add(new CommitEntry(cohort, readTime()));
1145         return cohort;
1146     }
1147
1148     // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
1149     // the newReadWriteTransaction()
1150     ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1151             final Optional<SortedSet<String>> participatingShardNames) {
1152         if (txId.getHistoryId().getHistoryId() == 0) {
1153             return createReadyCohort(txId, mod, participatingShardNames);
1154         }
1155
1156         return ensureTransactionChain(txId.getHistoryId(), null).createReadyCohort(txId, mod, participatingShardNames);
1157     }
1158
1159     @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
1160     void checkForExpiredTransactions(final long transactionCommitTimeoutMillis,
1161             final Function<SimpleShardDataTreeCohort, OptionalLong> accessTimeUpdater) {
1162         final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
1163         final long now = readTime();
1164
1165         final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
1166             !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
1167         final CommitEntry currentTx = currentQueue.peek();
1168         if (currentTx == null) {
1169             // Empty queue, no-op
1170             return;
1171         }
1172
1173         long delta = now - currentTx.lastAccess;
1174         if (delta < timeout) {
1175             // Not expired yet, bail
1176             return;
1177         }
1178
1179         final OptionalLong updateOpt = accessTimeUpdater.apply(currentTx.cohort);
1180         if (updateOpt.isPresent()) {
1181             final long newAccess =  updateOpt.getAsLong();
1182             final long newDelta = now - newAccess;
1183             if (newDelta < delta) {
1184                 LOG.debug("{}: Updated current transaction {} access time", logContext,
1185                     currentTx.cohort.getIdentifier());
1186                 currentTx.lastAccess = newAccess;
1187                 delta = newDelta;
1188             }
1189
1190             if (delta < timeout) {
1191                 // Not expired yet, bail
1192                 return;
1193             }
1194         }
1195
1196         final long deltaMillis = TimeUnit.NANOSECONDS.toMillis(delta);
1197         final State state = currentTx.cohort.getState();
1198
1199         LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
1200             currentTx.cohort.getIdentifier(), deltaMillis, state);
1201         boolean processNext = true;
1202         final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
1203                 + deltaMillis + "ms");
1204
1205         switch (state) {
1206             case CAN_COMMIT_PENDING:
1207                 currentQueue.remove().cohort.failedCanCommit(cohortFailure);
1208                 break;
1209             case CAN_COMMIT_COMPLETE:
1210                 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
1211                 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
1212                 // in PRE_COMMIT_COMPLETE is changed.
1213                 currentQueue.remove().cohort.reportFailure(cohortFailure);
1214                 break;
1215             case PRE_COMMIT_PENDING:
1216                 currentQueue.remove().cohort.failedPreCommit(cohortFailure);
1217                 break;
1218             case PRE_COMMIT_COMPLETE:
1219                 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
1220                 //        are ready we should commit the transaction, not abort it. Our current software stack does
1221                 //        not allow us to do that consistently, because we persist at the time of commit, hence
1222                 //        we can end up in a state where we have pre-committed a transaction, then a leader failover
1223                 //        occurred ... the new leader does not see the pre-committed transaction and does not have
1224                 //        a running timer. To fix this we really need two persistence events.
1225                 //
1226                 //        The first one, done at pre-commit time will hold the transaction payload. When consensus
1227                 //        is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1228                 //        apply the state in this event.
1229                 //
1230                 //        The second one, done at commit (or abort) time holds only the transaction identifier and
1231                 //        signals to followers that the state should (or should not) be applied.
1232                 //
1233                 //        In order to make the pre-commit timer working across failovers, though, we need
1234                 //        a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1235                 //        restart the timer.
1236                 currentQueue.remove().cohort.reportFailure(cohortFailure);
1237                 break;
1238             case COMMIT_PENDING:
1239                 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1240                     currentTx.cohort.getIdentifier());
1241                 currentTx.lastAccess = now;
1242                 processNext = false;
1243                 return;
1244             case READY:
1245                 currentQueue.remove().cohort.reportFailure(cohortFailure);
1246                 break;
1247             case ABORTED:
1248             case COMMITTED:
1249             case FAILED:
1250             default:
1251                 currentQueue.remove();
1252         }
1253
1254         if (processNext) {
1255             processNextPending();
1256         }
1257     }
1258
1259     boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1260         final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1261                 pendingTransactions).iterator();
1262         if (!it.hasNext()) {
1263             LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1264             return true;
1265         }
1266
1267         // First entry is special, as it may already be committing
1268         final CommitEntry first = it.next();
1269         if (cohort.equals(first.cohort)) {
1270             if (cohort.getState() != State.COMMIT_PENDING) {
1271                 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1272                     cohort.getIdentifier());
1273
1274                 it.remove();
1275                 if (cohort.getCandidate() != null) {
1276                     rebaseTransactions(it, dataTree);
1277                 }
1278
1279                 processNextPending();
1280                 return true;
1281             }
1282
1283             LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1284             return false;
1285         }
1286
1287         DataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
1288         while (it.hasNext()) {
1289             final CommitEntry e = it.next();
1290             if (cohort.equals(e.cohort)) {
1291                 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1292
1293                 it.remove();
1294                 if (cohort.getCandidate() != null) {
1295                     rebaseTransactions(it, newTip);
1296                 }
1297
1298                 return true;
1299             } else {
1300                 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), newTip);
1301             }
1302         }
1303
1304         LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1305         return true;
1306     }
1307
1308     @SuppressWarnings("checkstyle:IllegalCatch")
1309     private void rebaseTransactions(final Iterator<CommitEntry> iter, final @NonNull DataTreeTip newTip) {
1310         tip = requireNonNull(newTip);
1311         while (iter.hasNext()) {
1312             final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1313             if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1314                 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1315
1316                 try {
1317                     tip.validate(cohort.getDataTreeModification());
1318                 } catch (DataValidationFailedException | RuntimeException e) {
1319                     LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1320                     cohort.reportFailure(e);
1321                 }
1322             } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1323                 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1324
1325                 try {
1326                     tip.validate(cohort.getDataTreeModification());
1327                     DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1328
1329                     cohort.setNewCandidate(candidate);
1330                     tip = candidate;
1331                 } catch (RuntimeException | DataValidationFailedException e) {
1332                     LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1333                     cohort.reportFailure(e);
1334                 }
1335             }
1336         }
1337     }
1338
1339     void setRunOnPendingTransactionsComplete(final Runnable operation) {
1340         runOnPendingTransactionsComplete = operation;
1341         maybeRunOperationOnPendingTransactionsComplete();
1342     }
1343
1344     private void maybeRunOperationOnPendingTransactionsComplete() {
1345         if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1346             LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1347                     runOnPendingTransactionsComplete);
1348
1349             runOnPendingTransactionsComplete.run();
1350             runOnPendingTransactionsComplete = null;
1351         }
1352     }
1353
1354     ShardStats getStats() {
1355         return shard.getShardMBean();
1356     }
1357
1358     Iterator<SimpleShardDataTreeCohort> cohortIterator() {
1359         return Iterables.transform(Iterables.concat(pendingFinishCommits, pendingCommits, pendingTransactions),
1360             e -> e.cohort).iterator();
1361     }
1362
1363     void removeTransactionChain(final LocalHistoryIdentifier id) {
1364         if (transactionChains.remove(id) != null) {
1365             LOG.debug("{}: Removed transaction chain {}", logContext, id);
1366         }
1367     }
1368 }