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