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