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