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