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