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