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