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