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