6e4ee7d9e13f7dd4899c24833f65538eb255a42f
[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.Preconditions;
15 import com.google.common.base.Stopwatch;
16 import com.google.common.base.Verify;
17 import com.google.common.collect.ImmutableList;
18 import com.google.common.collect.ImmutableMap;
19 import com.google.common.collect.ImmutableMap.Builder;
20 import com.google.common.collect.Iterables;
21 import com.google.common.primitives.UnsignedLong;
22 import com.google.common.util.concurrent.FutureCallback;
23 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
24 import java.io.File;
25 import java.io.IOException;
26 import java.util.ArrayDeque;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.Deque;
31 import java.util.HashMap;
32 import java.util.Iterator;
33 import java.util.Map;
34 import java.util.Map.Entry;
35 import java.util.Optional;
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 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         return dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY)
647                 .map(state -> DataTreeCandidates.fromNormalizedNode(YangInstanceIdentifier.EMPTY, state));
648     }
649
650     public void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
651             final Optional<DataTreeCandidate> initialState,
652             final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
653         treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
654     }
655
656     int getQueueSize() {
657         return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
658     }
659
660     @Override
661     void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
662         final TransactionIdentifier id = transaction.getIdentifier();
663         LOG.debug("{}: aborting transaction {}", logContext, id);
664         replicatePayload(id, AbortTransactionPayload.create(
665                 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
666     }
667
668     @Override
669     void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
670         // No-op for free-standing transactions
671
672     }
673
674     @Override
675     ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction,
676             final Optional<SortedSet<String>> participatingShardNames) {
677         final DataTreeModification snapshot = transaction.getSnapshot();
678         final TransactionIdentifier id = transaction.getIdentifier();
679         LOG.debug("{}: readying transaction {}", logContext, id);
680         snapshot.ready();
681         LOG.debug("{}: transaction {} ready", logContext, id);
682
683         return createReadyCohort(transaction.getIdentifier(), snapshot, participatingShardNames);
684     }
685
686     void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
687         LOG.debug("{}: purging transaction {}", logContext, id);
688         replicatePayload(id, PurgeTransactionPayload.create(
689                 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
690     }
691
692     public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
693         return dataTree.takeSnapshot().readNode(path);
694     }
695
696     DataTreeSnapshot takeSnapshot() {
697         return dataTree.takeSnapshot();
698     }
699
700     @VisibleForTesting
701     public DataTreeModification newModification() {
702         return dataTree.takeSnapshot().newModification();
703     }
704
705     public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
706         Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
707
708         for (CommitEntry entry: pendingFinishCommits) {
709             ret.add(entry.cohort);
710         }
711
712         for (CommitEntry entry: pendingCommits) {
713             ret.add(entry.cohort);
714         }
715
716         for (CommitEntry entry: pendingTransactions) {
717             ret.add(entry.cohort);
718         }
719
720         pendingFinishCommits.clear();
721         pendingCommits.clear();
722         pendingTransactions.clear();
723         tip = dataTree;
724         return ret;
725     }
726
727     /**
728      * Called some time after {@link #processNextPendingTransaction()} decides to stop processing.
729      */
730     void resumeNextPendingTransaction() {
731         LOG.debug("{}: attempting to resume transaction processing", logContext);
732         processNextPending();
733     }
734
735     @SuppressWarnings("checkstyle:IllegalCatch")
736     private void processNextPendingTransaction() {
737         ++currentTransactionBatch;
738         if (currentTransactionBatch > MAX_TRANSACTION_BATCH) {
739             LOG.debug("{}: Already processed {}, scheduling continuation", logContext, currentTransactionBatch);
740             shard.scheduleNextPendingTransaction();
741             return;
742         }
743
744         processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
745             final SimpleShardDataTreeCohort cohort = entry.cohort;
746             final DataTreeModification modification = cohort.getDataTreeModification();
747
748             LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
749             Exception cause;
750             try {
751                 tip.validate(modification);
752                 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
753                 cohort.successfulCanCommit();
754                 entry.lastAccess = readTime();
755                 return;
756             } catch (ConflictingModificationAppliedException e) {
757                 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
758                     e.getPath());
759                 cause = new OptimisticLockFailedException("Optimistic lock failed for path " + e.getPath(), e);
760             } catch (DataValidationFailedException e) {
761                 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
762                     e.getPath(), e);
763
764                 // For debugging purposes, allow dumping of the modification. Coupled with the above
765                 // precondition log, it should allow us to understand what went on.
766                 LOG.debug("{}: Store Tx {}: modifications: {}", logContext, cohort.getIdentifier(), modification);
767                 LOG.trace("{}: Current tree: {}", logContext, dataTree);
768                 cause = new TransactionCommitFailedException("Data did not pass validation for path " + e.getPath(), e);
769             } catch (Exception e) {
770                 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
771                 cause = e;
772             }
773
774             // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
775             pendingTransactions.poll().cohort.failedCanCommit(cause);
776         });
777     }
778
779     private void processNextPending() {
780         processNextPendingCommit();
781         processNextPendingTransaction();
782     }
783
784     private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
785             final Consumer<CommitEntry> processor) {
786         while (!queue.isEmpty()) {
787             final CommitEntry entry = queue.peek();
788             final SimpleShardDataTreeCohort cohort = entry.cohort;
789
790             if (cohort.isFailed()) {
791                 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
792                 queue.remove();
793                 continue;
794             }
795
796             if (cohort.getState() == allowedState) {
797                 processor.accept(entry);
798             }
799
800             break;
801         }
802
803         maybeRunOperationOnPendingTransactionsComplete();
804     }
805
806     private void processNextPendingCommit() {
807         processNextPending(pendingCommits, State.COMMIT_PENDING,
808             entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
809     }
810
811     private boolean peekNextPendingCommit() {
812         final CommitEntry first = pendingCommits.peek();
813         return first != null && first.cohort.getState() == State.COMMIT_PENDING;
814     }
815
816     void startCanCommit(final SimpleShardDataTreeCohort cohort) {
817         final CommitEntry head = pendingTransactions.peek();
818         if (head == null) {
819             LOG.warn("{}: No transactions enqueued while attempting to start canCommit on {}", logContext, cohort);
820             return;
821         }
822         if (!cohort.equals(head.cohort)) {
823             // The tx isn't at the head of the queue so we can't start canCommit at this point. Here we check if this
824             // tx should be moved ahead of other tx's in the READY state in the pendingTransactions queue. If this tx
825             // has other participating shards, it could deadlock with other tx's accessing the same shards
826             // depending on the order the tx's are readied on each shard
827             // (see https://jira.opendaylight.org/browse/CONTROLLER-1836). Therefore, if the preceding participating
828             // shard names for a preceding pending tx, call it A, in the queue matches that of this tx, then this tx
829             // is allowed to be moved ahead of tx A in the queue so it is processed first to avoid potential deadlock
830             // if tx A is behind this tx in the pendingTransactions queue for a preceding shard. In other words, since
831             // canCommmit for this tx was requested before tx A, honor that request. If this tx is moved to the head of
832             // the queue as a result, then proceed with canCommit.
833
834             Collection<String> precedingShardNames = extractPrecedingShardNames(cohort.getParticipatingShardNames());
835             if (precedingShardNames.isEmpty()) {
836                 LOG.debug("{}: Tx {} is scheduled for canCommit step", logContext, cohort.getIdentifier());
837                 return;
838             }
839
840             LOG.debug("{}: Evaluating tx {} for canCommit -  preceding participating shard names {}",
841                     logContext, cohort.getIdentifier(), precedingShardNames);
842             final Iterator<CommitEntry> iter = pendingTransactions.iterator();
843             int index = -1;
844             int moveToIndex = -1;
845             while (iter.hasNext()) {
846                 final CommitEntry entry = iter.next();
847                 ++index;
848
849                 if (cohort.equals(entry.cohort)) {
850                     if (moveToIndex < 0) {
851                         LOG.debug("{}: Not moving tx {} - cannot proceed with canCommit",
852                                 logContext, cohort.getIdentifier());
853                         return;
854                     }
855
856                     LOG.debug("{}: Moving {} to index {} in the pendingTransactions queue",
857                             logContext, cohort.getIdentifier(), moveToIndex);
858                     iter.remove();
859                     insertEntry(pendingTransactions, entry, moveToIndex);
860
861                     if (!cohort.equals(pendingTransactions.peek().cohort)) {
862                         LOG.debug("{}: Tx {} is not at the head of the queue - cannot proceed with canCommit",
863                                 logContext, cohort.getIdentifier());
864                         return;
865                     }
866
867                     LOG.debug("{}: Tx {} is now at the head of the queue - proceeding with canCommit",
868                             logContext, cohort.getIdentifier());
869                     break;
870                 }
871
872                 if (entry.cohort.getState() != State.READY) {
873                     LOG.debug("{}: Skipping pending transaction {} in state {}",
874                             logContext, entry.cohort.getIdentifier(), entry.cohort.getState());
875                     continue;
876                 }
877
878                 final Collection<String> pendingPrecedingShardNames = extractPrecedingShardNames(
879                         entry.cohort.getParticipatingShardNames());
880
881                 if (precedingShardNames.equals(pendingPrecedingShardNames)) {
882                     if (moveToIndex < 0) {
883                         LOG.debug("{}: Preceding shard names {} for pending tx {} match - saving moveToIndex {}",
884                                 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), index);
885                         moveToIndex = index;
886                     } else {
887                         LOG.debug(
888                             "{}: Preceding shard names {} for pending tx {} match but moveToIndex already set to {}",
889                             logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), moveToIndex);
890                     }
891                 } else {
892                     LOG.debug("{}: Preceding shard names {} for pending tx {} differ - skipping",
893                         logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier());
894                 }
895             }
896         }
897
898         processNextPendingTransaction();
899     }
900
901     private static void insertEntry(final Deque<CommitEntry> queue, final CommitEntry entry, final int atIndex) {
902         if (atIndex == 0) {
903             queue.addFirst(entry);
904             return;
905         }
906
907         LOG.trace("Inserting into Deque at index {}", atIndex);
908
909         Deque<CommitEntry> tempStack = new ArrayDeque<>(atIndex);
910         for (int i = 0; i < atIndex; i++) {
911             tempStack.push(queue.poll());
912         }
913
914         queue.addFirst(entry);
915
916         tempStack.forEach(queue::addFirst);
917     }
918
919     private Collection<String> extractPrecedingShardNames(final Optional<SortedSet<String>> participatingShardNames) {
920         return participatingShardNames.map((Function<SortedSet<String>, Collection<String>>)
921             set -> set.headSet(shard.getShardName())).orElse(Collections.<String>emptyList());
922     }
923
924     private void failPreCommit(final Throwable cause) {
925         shard.getShardMBean().incrementFailedTransactionsCount();
926         pendingTransactions.poll().cohort.failedPreCommit(cause);
927         processNextPendingTransaction();
928     }
929
930     @SuppressWarnings("checkstyle:IllegalCatch")
931     void startPreCommit(final SimpleShardDataTreeCohort cohort) {
932         final CommitEntry entry = pendingTransactions.peek();
933         Preconditions.checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
934
935         final SimpleShardDataTreeCohort current = entry.cohort;
936         Verify.verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
937
938         final TransactionIdentifier currentId = current.getIdentifier();
939         LOG.debug("{}: Preparing transaction {}", logContext, currentId);
940
941         final DataTreeCandidateTip candidate;
942         try {
943             candidate = tip.prepare(cohort.getDataTreeModification());
944             LOG.debug("{}: Transaction {} candidate ready", logContext, currentId);
945         } catch (RuntimeException e) {
946             failPreCommit(e);
947             return;
948         }
949
950         cohort.userPreCommit(candidate, new FutureCallback<Void>() {
951             @Override
952             public void onSuccess(final Void noop) {
953                 // Set the tip of the data tree.
954                 tip = Verify.verifyNotNull(candidate);
955
956                 entry.lastAccess = readTime();
957
958                 pendingTransactions.remove();
959                 pendingCommits.add(entry);
960
961                 LOG.debug("{}: Transaction {} prepared", logContext, currentId);
962
963                 cohort.successfulPreCommit(candidate);
964
965                 processNextPendingTransaction();
966             }
967
968             @Override
969             public void onFailure(final Throwable failure) {
970                 failPreCommit(failure);
971             }
972         });
973     }
974
975     private void failCommit(final Exception cause) {
976         shard.getShardMBean().incrementFailedTransactionsCount();
977         pendingFinishCommits.poll().cohort.failedCommit(cause);
978         processNextPending();
979     }
980
981     @SuppressWarnings("checkstyle:IllegalCatch")
982     private void finishCommit(final SimpleShardDataTreeCohort cohort) {
983         final TransactionIdentifier txId = cohort.getIdentifier();
984         final DataTreeCandidate candidate = cohort.getCandidate();
985
986         LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
987
988         if (tip == candidate) {
989             // All pending candidates have been committed, reset the tip to the data tree.
990             tip = dataTree;
991         }
992
993         try {
994             dataTree.commit(candidate);
995         } catch (Exception e) {
996             LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
997             failCommit(e);
998             return;
999         }
1000
1001         allMetadataCommittedTransaction(txId);
1002         shard.getShardMBean().incrementCommittedTransactionCount();
1003         shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
1004
1005         // FIXME: propagate journal index
1006         pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO, () -> {
1007             LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
1008             notifyListeners(candidate);
1009
1010             processNextPending();
1011         });
1012     }
1013
1014     void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
1015         final CommitEntry entry = pendingCommits.peek();
1016         Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
1017
1018         final SimpleShardDataTreeCohort current = entry.cohort;
1019         if (!cohort.equals(current)) {
1020             LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
1021             return;
1022         }
1023
1024         LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
1025
1026         final TransactionIdentifier txId = cohort.getIdentifier();
1027         final Payload payload;
1028         try {
1029             payload = CommitTransactionPayload.create(txId, candidate,
1030                     shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity());
1031         } catch (IOException e) {
1032             LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
1033             pendingCommits.poll().cohort.failedCommit(e);
1034             processNextPending();
1035             return;
1036         }
1037
1038         // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
1039         // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
1040         // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
1041         // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
1042         // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
1043         // pendingCommits queue.
1044         processNextPendingTransaction();
1045
1046         // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
1047         // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
1048         // in order to properly determine the batchHint flag for the call to persistPayload.
1049         pendingCommits.remove();
1050         pendingFinishCommits.add(entry);
1051
1052         // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
1053         // this transaction for replication.
1054         boolean replicationBatchHint = peekNextPendingCommit();
1055
1056         // Once completed, we will continue via payloadReplicationComplete
1057         shard.persistPayload(txId, payload, replicationBatchHint);
1058
1059         entry.lastAccess = shard.ticker().read();
1060
1061         LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
1062
1063         // Process the next transaction pending commit, if any. If there is one it will be batched with this
1064         // transaction for replication.
1065         processNextPendingCommit();
1066     }
1067
1068     Collection<ActorRef> getCohortActors() {
1069         return cohortRegistry.getCohortActors();
1070     }
1071
1072     void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
1073         cohortRegistry.process(sender, message);
1074     }
1075
1076     @Override
1077     ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1078             final Exception failure) {
1079         final SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId, failure);
1080         pendingTransactions.add(new CommitEntry(cohort, readTime()));
1081         return cohort;
1082     }
1083
1084     @Override
1085     ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1086             final Optional<SortedSet<String>> participatingShardNames) {
1087         SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId,
1088                 cohortRegistry.createCohort(schemaContext, txId, shard::executeInSelf,
1089                         COMMIT_STEP_TIMEOUT), participatingShardNames);
1090         pendingTransactions.add(new CommitEntry(cohort, readTime()));
1091         return cohort;
1092     }
1093
1094     // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
1095     // the newReadWriteTransaction()
1096     ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1097             final Optional<SortedSet<String>> participatingShardNames) {
1098         if (txId.getHistoryId().getHistoryId() == 0) {
1099             return createReadyCohort(txId, mod, participatingShardNames);
1100         }
1101
1102         return ensureTransactionChain(txId.getHistoryId(), null).createReadyCohort(txId, mod, participatingShardNames);
1103     }
1104
1105     @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
1106     void checkForExpiredTransactions(final long transactionCommitTimeoutMillis,
1107             final Function<SimpleShardDataTreeCohort, OptionalLong> accessTimeUpdater) {
1108         final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
1109         final long now = readTime();
1110
1111         final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
1112             !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
1113         final CommitEntry currentTx = currentQueue.peek();
1114         if (currentTx == null) {
1115             // Empty queue, no-op
1116             return;
1117         }
1118
1119         long delta = now - currentTx.lastAccess;
1120         if (delta < timeout) {
1121             // Not expired yet, bail
1122             return;
1123         }
1124
1125         final OptionalLong updateOpt = accessTimeUpdater.apply(currentTx.cohort);
1126         if (updateOpt.isPresent()) {
1127             final long newAccess =  updateOpt.getAsLong();
1128             final long newDelta = now - newAccess;
1129             if (newDelta < delta) {
1130                 LOG.debug("{}: Updated current transaction {} access time", logContext,
1131                     currentTx.cohort.getIdentifier());
1132                 currentTx.lastAccess = newAccess;
1133                 delta = newDelta;
1134             }
1135
1136             if (delta < timeout) {
1137                 // Not expired yet, bail
1138                 return;
1139             }
1140         }
1141
1142         final long deltaMillis = TimeUnit.NANOSECONDS.toMillis(delta);
1143         final State state = currentTx.cohort.getState();
1144
1145         LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
1146             currentTx.cohort.getIdentifier(), deltaMillis, state);
1147         boolean processNext = true;
1148         final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
1149                 + deltaMillis + "ms");
1150
1151         switch (state) {
1152             case CAN_COMMIT_PENDING:
1153                 currentQueue.remove().cohort.failedCanCommit(cohortFailure);
1154                 break;
1155             case CAN_COMMIT_COMPLETE:
1156                 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
1157                 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
1158                 // in PRE_COMMIT_COMPLETE is changed.
1159                 currentQueue.remove().cohort.reportFailure(cohortFailure);
1160                 break;
1161             case PRE_COMMIT_PENDING:
1162                 currentQueue.remove().cohort.failedPreCommit(cohortFailure);
1163                 break;
1164             case PRE_COMMIT_COMPLETE:
1165                 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
1166                 //        are ready we should commit the transaction, not abort it. Our current software stack does
1167                 //        not allow us to do that consistently, because we persist at the time of commit, hence
1168                 //        we can end up in a state where we have pre-committed a transaction, then a leader failover
1169                 //        occurred ... the new leader does not see the pre-committed transaction and does not have
1170                 //        a running timer. To fix this we really need two persistence events.
1171                 //
1172                 //        The first one, done at pre-commit time will hold the transaction payload. When consensus
1173                 //        is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1174                 //        apply the state in this event.
1175                 //
1176                 //        The second one, done at commit (or abort) time holds only the transaction identifier and
1177                 //        signals to followers that the state should (or should not) be applied.
1178                 //
1179                 //        In order to make the pre-commit timer working across failovers, though, we need
1180                 //        a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1181                 //        restart the timer.
1182                 currentQueue.remove().cohort.reportFailure(cohortFailure);
1183                 break;
1184             case COMMIT_PENDING:
1185                 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1186                     currentTx.cohort.getIdentifier());
1187                 currentTx.lastAccess = now;
1188                 processNext = false;
1189                 return;
1190             case READY:
1191                 currentQueue.remove().cohort.reportFailure(cohortFailure);
1192                 break;
1193             case ABORTED:
1194             case COMMITTED:
1195             case FAILED:
1196             default:
1197                 currentQueue.remove();
1198         }
1199
1200         if (processNext) {
1201             processNextPending();
1202         }
1203     }
1204
1205     boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1206         final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1207                 pendingTransactions).iterator();
1208         if (!it.hasNext()) {
1209             LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1210             return true;
1211         }
1212
1213         // First entry is special, as it may already be committing
1214         final CommitEntry first = it.next();
1215         if (cohort.equals(first.cohort)) {
1216             if (cohort.getState() != State.COMMIT_PENDING) {
1217                 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1218                     cohort.getIdentifier());
1219
1220                 it.remove();
1221                 if (cohort.getCandidate() != null) {
1222                     rebaseTransactions(it, dataTree);
1223                 }
1224
1225                 processNextPending();
1226                 return true;
1227             }
1228
1229             LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1230             return false;
1231         }
1232
1233         DataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
1234         while (it.hasNext()) {
1235             final CommitEntry e = it.next();
1236             if (cohort.equals(e.cohort)) {
1237                 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1238
1239                 it.remove();
1240                 if (cohort.getCandidate() != null) {
1241                     rebaseTransactions(it, newTip);
1242                 }
1243
1244                 return true;
1245             } else {
1246                 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), newTip);
1247             }
1248         }
1249
1250         LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1251         return true;
1252     }
1253
1254     @SuppressWarnings("checkstyle:IllegalCatch")
1255     private void rebaseTransactions(final Iterator<CommitEntry> iter, final @NonNull DataTreeTip newTip) {
1256         tip = Preconditions.checkNotNull(newTip);
1257         while (iter.hasNext()) {
1258             final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1259             if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1260                 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1261
1262                 try {
1263                     tip.validate(cohort.getDataTreeModification());
1264                 } catch (DataValidationFailedException | RuntimeException e) {
1265                     LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1266                     cohort.reportFailure(e);
1267                 }
1268             } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1269                 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1270
1271                 try {
1272                     tip.validate(cohort.getDataTreeModification());
1273                     DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1274
1275                     cohort.setNewCandidate(candidate);
1276                     tip = candidate;
1277                 } catch (RuntimeException | DataValidationFailedException e) {
1278                     LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1279                     cohort.reportFailure(e);
1280                 }
1281             }
1282         }
1283     }
1284
1285     void setRunOnPendingTransactionsComplete(final Runnable operation) {
1286         runOnPendingTransactionsComplete = operation;
1287         maybeRunOperationOnPendingTransactionsComplete();
1288     }
1289
1290     private void maybeRunOperationOnPendingTransactionsComplete() {
1291         if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1292             LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1293                     runOnPendingTransactionsComplete);
1294
1295             runOnPendingTransactionsComplete.run();
1296             runOnPendingTransactionsComplete = null;
1297         }
1298     }
1299
1300     ShardStats getStats() {
1301         return shard.getShardMBean();
1302     }
1303
1304     Iterator<SimpleShardDataTreeCohort> cohortIterator() {
1305         return Iterables.transform(Iterables.concat(pendingFinishCommits, pendingCommits, pendingTransactions),
1306             e -> e.cohort).iterator();
1307     }
1308
1309     void removeTransactionChain(final LocalHistoryIdentifier id) {
1310         if (transactionChains.remove(id) != null) {
1311             LOG.debug("{}: Removed transaction chain {}", logContext, id);
1312         }
1313     }
1314 }