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