e8469d439d7df19b6fc5828574492beadf5109f1
[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.AbstractMap.SimpleEntry;
28 import java.util.ArrayDeque;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.HashMap;
32 import java.util.Iterator;
33 import java.util.Map;
34 import java.util.Map.Entry;
35 import java.util.Queue;
36 import java.util.concurrent.ExecutionException;
37 import java.util.concurrent.TimeUnit;
38 import java.util.concurrent.TimeoutException;
39 import java.util.function.Consumer;
40 import java.util.function.UnaryOperator;
41 import javax.annotation.Nonnull;
42 import javax.annotation.Nullable;
43 import javax.annotation.concurrent.NotThreadSafe;
44 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
45 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
46 import org.opendaylight.controller.cluster.datastore.DataTreeCohortActorRegistry.CohortRegistryCommand;
47 import org.opendaylight.controller.cluster.datastore.ShardDataTreeCohort.State;
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.controller.md.sal.dom.store.impl.DataChangeListenerRegistration;
67 import org.opendaylight.yangtools.concepts.Identifier;
68 import org.opendaylight.yangtools.concepts.ListenerRegistration;
69 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
70 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
72 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
73 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
74 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
75 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
76 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
77 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeTip;
78 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
79 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
80 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTreeTip;
81 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
82 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
83 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
84 import org.slf4j.Logger;
85 import org.slf4j.LoggerFactory;
86 import scala.concurrent.duration.Duration;
87
88 /**
89  * Internal shard state, similar to a DOMStore, but optimized for use in the actor system,
90  * e.g. it does not expose public interfaces and assumes it is only ever called from a
91  * single thread.
92  *
93  * <p>
94  * This class is not part of the API contract and is subject to change at any time.
95  */
96 @NotThreadSafe
97 public class ShardDataTree extends ShardDataTreeTransactionParent {
98     private static final class CommitEntry {
99         final SimpleShardDataTreeCohort cohort;
100         long lastAccess;
101
102         CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
103             this.cohort = Preconditions.checkNotNull(cohort);
104             lastAccess = now;
105         }
106     }
107
108     private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(Duration.create(5, TimeUnit.SECONDS));
109     private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
110
111     private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
112
113     private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
114     private final Queue<CommitEntry> pendingTransactions = new ArrayDeque<>();
115     private final Queue<CommitEntry> pendingCommits = new ArrayDeque<>();
116     private final Queue<CommitEntry> pendingFinishCommits = new ArrayDeque<>();
117
118     /**
119      * Callbacks that need to be invoked once a payload is replicated.
120      */
121     private final Map<Payload, Runnable> replicationCallbacks = new HashMap<>();
122
123     private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
124     private final ShardDataChangeListenerPublisher dataChangeListenerPublisher;
125     private final Collection<ShardDataTreeMetadata<?>> metadata;
126     private final TipProducingDataTree dataTree;
127     private final String logContext;
128     private final Shard shard;
129     private Runnable runOnPendingTransactionsComplete;
130
131     /**
132      * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
133      * {@link TipProducingDataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
134      * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
135      * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
136      */
137     private TipProducingDataTreeTip tip;
138
139     private SchemaContext schemaContext;
140
141     public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TipProducingDataTree dataTree,
142             final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
143             final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext,
144             final ShardDataTreeMetadata<?>... metadata) {
145         this.dataTree = Preconditions.checkNotNull(dataTree);
146         updateSchemaContext(schemaContext);
147
148         this.shard = Preconditions.checkNotNull(shard);
149         this.treeChangeListenerPublisher = Preconditions.checkNotNull(treeChangeListenerPublisher);
150         this.dataChangeListenerPublisher = Preconditions.checkNotNull(dataChangeListenerPublisher);
151         this.logContext = Preconditions.checkNotNull(logContext);
152         this.metadata = ImmutableList.copyOf(metadata);
153         tip = dataTree;
154     }
155
156     public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType,
157             final YangInstanceIdentifier root,
158             final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
159             final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext) {
160         this(shard, schemaContext, InMemoryDataTreeFactory.getInstance().create(treeType, root),
161                 treeChangeListenerPublisher, dataChangeListenerPublisher, logContext);
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 CloseLocalHistoryPayload) {
412             if (identifier != null) {
413                 payloadReplicationComplete((CloseLocalHistoryPayload) payload);
414             } else {
415                 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
416             }
417         } else if (payload instanceof CreateLocalHistoryPayload) {
418             if (identifier != null) {
419                 payloadReplicationComplete((CreateLocalHistoryPayload)payload);
420             } else {
421                 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
422             }
423         } else if (payload instanceof PurgeLocalHistoryPayload) {
424             if (identifier != null) {
425                 payloadReplicationComplete((PurgeLocalHistoryPayload)payload);
426             } else {
427                 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
428             }
429         } else {
430             LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
431         }
432     }
433
434     private void replicatePayload(final Identifier id, final Payload payload, @Nullable final Runnable callback) {
435         if (callback != null) {
436             replicationCallbacks.put(payload, callback);
437         }
438         shard.persistPayload(id, payload, true);
439     }
440
441     private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
442         final Runnable callback = replicationCallbacks.remove(payload);
443         if (callback != null) {
444             LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
445             callback.run();
446         } else {
447             LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
448         }
449     }
450
451     private void payloadReplicationComplete(final TransactionIdentifier txId) {
452         final CommitEntry current = pendingFinishCommits.peek();
453         if (current == null) {
454             LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
455             return;
456         }
457
458         if (!current.cohort.getIdentifier().equals(txId)) {
459             LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
460                 current.cohort.getIdentifier(), txId);
461             return;
462         }
463
464         finishCommit(current.cohort);
465     }
466
467     private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
468         for (ShardDataTreeMetadata<?> m : metadata) {
469             m.onTransactionAborted(txId);
470         }
471     }
472
473     private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
474         for (ShardDataTreeMetadata<?> m : metadata) {
475             m.onTransactionCommitted(txId);
476         }
477     }
478
479     private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
480         for (ShardDataTreeMetadata<?> m : metadata) {
481             m.onTransactionPurged(txId);
482         }
483     }
484
485     private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
486         for (ShardDataTreeMetadata<?> m : metadata) {
487             m.onHistoryCreated(historyId);
488         }
489     }
490
491     private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
492         for (ShardDataTreeMetadata<?> m : metadata) {
493             m.onHistoryClosed(historyId);
494         }
495     }
496
497     private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
498         for (ShardDataTreeMetadata<?> m : metadata) {
499             m.onHistoryPurged(historyId);
500         }
501     }
502
503     /**
504      * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
505      * this method is used for re-establishing state when we are taking over
506      *
507      * @param historyId Local history identifier
508      * @param closed True if the chain should be created in closed state (i.e. pending purge)
509      * @return Transaction chain handle
510      */
511     ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
512             final boolean closed) {
513         final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
514         final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
515         Preconditions.checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId,
516                 existing);
517         return ret;
518     }
519
520     ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId) {
521         ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
522         if (chain == null) {
523             chain = new ShardDataTreeTransactionChain(historyId, this);
524             transactionChains.put(historyId, chain);
525             shard.persistPayload(historyId, CreateLocalHistoryPayload.create(historyId), true);
526         }
527
528         return chain;
529     }
530
531     ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
532         if (txId.getHistoryId().getHistoryId() == 0) {
533             return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
534         }
535
536         return ensureTransactionChain(txId.getHistoryId()).newReadOnlyTransaction(txId);
537     }
538
539     ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
540         if (txId.getHistoryId().getHistoryId() == 0) {
541             return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
542                     .newModification());
543         }
544
545         return ensureTransactionChain(txId.getHistoryId()).newReadWriteTransaction(txId);
546     }
547
548     @VisibleForTesting
549     public void notifyListeners(final DataTreeCandidate candidate) {
550         treeChangeListenerPublisher.publishChanges(candidate, logContext);
551         dataChangeListenerPublisher.publishChanges(candidate, logContext);
552     }
553
554     void notifyOfInitialData(final DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
555             NormalizedNode<?, ?>>> listenerReg, final Optional<DataTreeCandidate> currentState) {
556         if (currentState.isPresent()) {
557             ShardDataChangeListenerPublisher localPublisher = dataChangeListenerPublisher.newInstance();
558             localPublisher.registerDataChangeListener(listenerReg.getPath(), listenerReg.getInstance(),
559                     listenerReg.getScope());
560             localPublisher.publishChanges(currentState.get(), logContext);
561         }
562     }
563
564     void notifyOfInitialData(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
565             final Optional<DataTreeCandidate> currentState) {
566         if (currentState.isPresent()) {
567             ShardDataTreeChangeListenerPublisher localPublisher = treeChangeListenerPublisher.newInstance();
568             localPublisher.registerTreeChangeListener(path, listener);
569             localPublisher.publishChanges(currentState.get(), logContext);
570         }
571     }
572
573     /**
574      * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
575      * replication callbacks.
576      */
577     void purgeLeaderState() {
578         for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
579             chain.close();
580         }
581
582         transactionChains.clear();
583         replicationCallbacks.clear();
584     }
585
586     /**
587      * Close a single transaction chain.
588      *
589      * @param id History identifier
590      * @param callback Callback to invoke upon completion, may be null
591      */
592     void closeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
593         final ShardDataTreeTransactionChain chain = transactionChains.get(id);
594         if (chain == null) {
595             LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
596             if (callback != null) {
597                 callback.run();
598             }
599             return;
600         }
601
602         chain.close();
603         replicatePayload(id, CloseLocalHistoryPayload.create(id), callback);
604     }
605
606     /**
607      * Purge a single transaction chain.
608      *
609      * @param id History identifier
610      * @param callback Callback to invoke upon completion, may be null
611      */
612     void purgeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
613         final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
614         if (chain == null) {
615             LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
616             if (callback != null) {
617                 callback.run();
618             }
619             return;
620         }
621
622         replicatePayload(id, PurgeLocalHistoryPayload.create(id), callback);
623     }
624
625     Entry<DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>,
626             Optional<DataTreeCandidate>> registerChangeListener(final YangInstanceIdentifier path,
627                     final AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener,
628                     final DataChangeScope scope) {
629         DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> reg =
630                 dataChangeListenerPublisher.registerDataChangeListener(path, listener, scope);
631
632         return new SimpleEntry<>(reg, readCurrentData());
633     }
634
635     private Optional<DataTreeCandidate> readCurrentData() {
636         final Optional<NormalizedNode<?, ?>> currentState =
637                 dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY);
638         return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
639             YangInstanceIdentifier.EMPTY, currentState.get())) : Optional.<DataTreeCandidate>absent();
640     }
641
642     public Entry<ListenerRegistration<DOMDataTreeChangeListener>, Optional<DataTreeCandidate>>
643             registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener) {
644         final ListenerRegistration<DOMDataTreeChangeListener> reg =
645                 treeChangeListenerPublisher.registerTreeChangeListener(path, listener);
646
647         return new SimpleEntry<>(reg, readCurrentData());
648     }
649
650     int getQueueSize() {
651         return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
652     }
653
654     @Override
655     void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
656         final TransactionIdentifier id = transaction.getIdentifier();
657         LOG.debug("{}: aborting transaction {}", logContext, id);
658         replicatePayload(id, AbortTransactionPayload.create(id), callback);
659     }
660
661
662     @Override
663     void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
664         LOG.debug("{}: purging transaction {}", logContext, id);
665         replicatePayload(id, PurgeTransactionPayload.create(id), callback);
666     }
667
668     @Override
669     ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction) {
670         final DataTreeModification snapshot = transaction.getSnapshot();
671         snapshot.ready();
672
673         return createReadyCohort(transaction.getIdentifier(), snapshot);
674     }
675
676     public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
677         return dataTree.takeSnapshot().readNode(path);
678     }
679
680     DataTreeSnapshot takeSnapshot() {
681         return dataTree.takeSnapshot();
682     }
683
684     @VisibleForTesting
685     public DataTreeModification newModification() {
686         return dataTree.takeSnapshot().newModification();
687     }
688
689     /**
690      * Commits a modification.
691      *
692      * @deprecated This method violates DataTree containment and will be removed.
693      */
694     @VisibleForTesting
695     @Deprecated
696     public DataTreeCandidate commit(final DataTreeModification modification) throws DataValidationFailedException {
697         // Direct modification commit is a utility, which cannot be used while we have transactions in-flight
698         Preconditions.checkState(tip == dataTree, "Cannot modify data tree while transacgitons are pending");
699
700         modification.ready();
701         dataTree.validate(modification);
702         DataTreeCandidate candidate = dataTree.prepare(modification);
703         dataTree.commit(candidate);
704         return candidate;
705     }
706
707     public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
708         Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
709
710         for (CommitEntry entry: pendingFinishCommits) {
711             ret.add(entry.cohort);
712         }
713
714         for (CommitEntry entry: pendingCommits) {
715             ret.add(entry.cohort);
716         }
717
718         for (CommitEntry entry: pendingTransactions) {
719             ret.add(entry.cohort);
720         }
721
722         pendingFinishCommits.clear();
723         pendingCommits.clear();
724         pendingTransactions.clear();
725         tip = dataTree;
726         return ret;
727     }
728
729     @SuppressWarnings("checkstyle:IllegalCatch")
730     private void processNextPendingTransaction() {
731         processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
732             final SimpleShardDataTreeCohort cohort = entry.cohort;
733             final DataTreeModification modification = cohort.getDataTreeModification();
734
735             LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
736             Exception cause;
737             try {
738                 tip.validate(modification);
739                 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
740                 cohort.successfulCanCommit();
741                 entry.lastAccess = ticker().read();
742                 return;
743             } catch (ConflictingModificationAppliedException e) {
744                 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
745                     e.getPath());
746                 cause = new OptimisticLockFailedException("Optimistic lock failed.", e);
747             } catch (DataValidationFailedException e) {
748                 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
749                     e.getPath(), e);
750
751                 // For debugging purposes, allow dumping of the modification. Coupled with the above
752                 // precondition log, it should allow us to understand what went on.
753                 LOG.debug("{}: Store Tx {}: modifications: {} tree: {}", cohort.getIdentifier(), modification,
754                         dataTree);
755                 cause = new TransactionCommitFailedException("Data did not pass validation.", e);
756             } catch (Exception e) {
757                 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
758                 cause = e;
759             }
760
761             // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
762             pendingTransactions.poll().cohort.failedCanCommit(cause);
763         });
764     }
765
766     private void processNextPending() {
767         processNextPendingCommit();
768         processNextPendingTransaction();
769     }
770
771     private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
772             final Consumer<CommitEntry> processor) {
773         while (!queue.isEmpty()) {
774             final CommitEntry entry = queue.peek();
775             final SimpleShardDataTreeCohort cohort = entry.cohort;
776
777             if (cohort.isFailed()) {
778                 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
779                 queue.remove();
780                 continue;
781             }
782
783             if (cohort.getState() == allowedState) {
784                 processor.accept(entry);
785             }
786
787             break;
788         }
789
790         maybeRunOperationOnPendingTransactionsComplete();
791     }
792
793     private void processNextPendingCommit() {
794         processNextPending(pendingCommits, State.COMMIT_PENDING,
795             entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
796     }
797
798     private boolean peekNextPendingCommit() {
799         final CommitEntry first = pendingCommits.peek();
800         return first != null && first.cohort.getState() == State.COMMIT_PENDING;
801     }
802
803     void startCanCommit(final SimpleShardDataTreeCohort cohort) {
804         final SimpleShardDataTreeCohort current = pendingTransactions.peek().cohort;
805         if (!cohort.equals(current)) {
806             LOG.debug("{}: Transaction {} scheduled for canCommit step", logContext, cohort.getIdentifier());
807             return;
808         }
809
810         processNextPendingTransaction();
811     }
812
813     private void failPreCommit(final Exception cause) {
814         shard.getShardMBean().incrementFailedTransactionsCount();
815         pendingTransactions.poll().cohort.failedPreCommit(cause);
816         processNextPendingTransaction();
817     }
818
819     @SuppressWarnings("checkstyle:IllegalCatch")
820     void startPreCommit(final SimpleShardDataTreeCohort cohort) {
821         final CommitEntry entry = pendingTransactions.peek();
822         Preconditions.checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
823
824         final SimpleShardDataTreeCohort current = entry.cohort;
825         Verify.verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
826
827         LOG.debug("{}: Preparing transaction {}", logContext, current.getIdentifier());
828
829         final DataTreeCandidateTip candidate;
830         try {
831             candidate = tip.prepare(cohort.getDataTreeModification());
832             cohort.userPreCommit(candidate);
833         } catch (ExecutionException | TimeoutException | RuntimeException e) {
834             failPreCommit(e);
835             return;
836         }
837
838         // Set the tip of the data tree.
839         tip = Verify.verifyNotNull(candidate);
840
841         entry.lastAccess = ticker().read();
842
843         pendingTransactions.remove();
844         pendingCommits.add(entry);
845
846         LOG.debug("{}: Transaction {} prepared", logContext, current.getIdentifier());
847
848         cohort.successfulPreCommit(candidate);
849
850         processNextPendingTransaction();
851     }
852
853     private void failCommit(final Exception cause) {
854         shard.getShardMBean().incrementFailedTransactionsCount();
855         pendingFinishCommits.poll().cohort.failedCommit(cause);
856         processNextPending();
857     }
858
859     @SuppressWarnings("checkstyle:IllegalCatch")
860     private void finishCommit(final SimpleShardDataTreeCohort cohort) {
861         final TransactionIdentifier txId = cohort.getIdentifier();
862         final DataTreeCandidate candidate = cohort.getCandidate();
863
864         LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
865
866         if (tip == candidate) {
867             // All pending candidates have been committed, reset the tip to the data tree.
868             tip = dataTree;
869         }
870
871         try {
872             dataTree.commit(candidate);
873         } catch (Exception e) {
874             LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
875             failCommit(e);
876             return;
877         }
878
879         shard.getShardMBean().incrementCommittedTransactionCount();
880         shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
881
882         // FIXME: propagate journal index
883         pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO);
884
885         LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
886         notifyListeners(candidate);
887
888         processNextPending();
889     }
890
891     void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
892         final CommitEntry entry = pendingCommits.peek();
893         Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
894
895         final SimpleShardDataTreeCohort current = entry.cohort;
896         if (!cohort.equals(current)) {
897             LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
898             return;
899         }
900
901         LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
902
903         final TransactionIdentifier txId = cohort.getIdentifier();
904         final Payload payload;
905         try {
906             payload = CommitTransactionPayload.create(txId, candidate);
907         } catch (IOException e) {
908             LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
909             pendingCommits.poll().cohort.failedCommit(e);
910             processNextPending();
911             return;
912         }
913
914         // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
915         // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
916         // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
917         // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
918         // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
919         // pendingCommits queue.
920         processNextPendingTransaction();
921
922         // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
923         // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
924         // in order to properly determine the batchHint flag for the call to persistPayload.
925         pendingCommits.remove();
926         pendingFinishCommits.add(entry);
927
928         // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
929         // this transaction for replication.
930         boolean replicationBatchHint = peekNextPendingCommit();
931
932         // Once completed, we will continue via payloadReplicationComplete
933         shard.persistPayload(txId, payload, replicationBatchHint);
934
935         entry.lastAccess = shard.ticker().read();
936
937         LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
938
939         // Process the next transaction pending commit, if any. If there is one it will be batched with this
940         // transaction for replication.
941         processNextPendingCommit();
942     }
943
944     Collection<ActorRef> getCohortActors() {
945         return cohortRegistry.getCohortActors();
946     }
947
948     void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
949         cohortRegistry.process(sender, message);
950     }
951
952     @Override
953     ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId,
954             final DataTreeModification modification) {
955         SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, modification, txId,
956                 cohortRegistry.createCohort(schemaContext, txId, COMMIT_STEP_TIMEOUT));
957         pendingTransactions.add(new CommitEntry(cohort, ticker().read()));
958         return cohort;
959     }
960
961     @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
962     void checkForExpiredTransactions(final long transactionCommitTimeoutMillis) {
963         final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
964         final long now = ticker().read();
965
966         final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
967             !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
968         final CommitEntry currentTx = currentQueue.peek();
969         if (currentTx != null && currentTx.lastAccess + timeout < now) {
970             LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
971                     currentTx.cohort.getIdentifier(), transactionCommitTimeoutMillis, currentTx.cohort.getState());
972             boolean processNext = true;
973             switch (currentTx.cohort.getState()) {
974                 case CAN_COMMIT_PENDING:
975                     currentQueue.remove().cohort.failedCanCommit(new TimeoutException());
976                     break;
977                 case CAN_COMMIT_COMPLETE:
978                     // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
979                     // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
980                     // in PRE_COMMIT_COMPLETE is changed.
981                     currentQueue.remove().cohort.reportFailure(new TimeoutException());
982                     break;
983                 case PRE_COMMIT_PENDING:
984                     currentQueue.remove().cohort.failedPreCommit(new TimeoutException());
985                     break;
986                 case PRE_COMMIT_COMPLETE:
987                     // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
988                     //        are ready we should commit the transaction, not abort it. Our current software stack does
989                     //        not allow us to do that consistently, because we persist at the time of commit, hence
990                     //        we can end up in a state where we have pre-committed a transaction, then a leader failover
991                     //        occurred ... the new leader does not see the pre-committed transaction and does not have
992                     //        a running timer. To fix this we really need two persistence events.
993                     //
994                     //        The first one, done at pre-commit time will hold the transaction payload. When consensus
995                     //        is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
996                     //        apply the state in this event.
997                     //
998                     //        The second one, done at commit (or abort) time holds only the transaction identifier and
999                     //        signals to followers that the state should (or should not) be applied.
1000                     //
1001                     //        In order to make the pre-commit timer working across failovers, though, we need
1002                     //        a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1003                     //        restart the timer.
1004                     currentQueue.remove().cohort.reportFailure(new TimeoutException());
1005                     break;
1006                 case COMMIT_PENDING:
1007                     LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1008                         currentTx.cohort.getIdentifier());
1009                     currentTx.lastAccess = now;
1010                     processNext = false;
1011                     return;
1012                 case ABORTED:
1013                 case COMMITTED:
1014                 case FAILED:
1015                 case READY:
1016                 default:
1017                     currentQueue.remove();
1018             }
1019
1020             if (processNext) {
1021                 processNextPending();
1022             }
1023         }
1024     }
1025
1026     boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1027         final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1028                 pendingTransactions).iterator();
1029         if (!it.hasNext()) {
1030             LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1031             return true;
1032         }
1033
1034         // First entry is special, as it may already be committing
1035         final CommitEntry first = it.next();
1036         if (cohort.equals(first.cohort)) {
1037             if (cohort.getState() != State.COMMIT_PENDING) {
1038                 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1039                     cohort.getIdentifier());
1040
1041                 it.remove();
1042                 if (cohort.getCandidate() != null) {
1043                     rebaseTransactions(it, dataTree);
1044                 }
1045
1046                 processNextPending();
1047                 return true;
1048             }
1049
1050             LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1051             return false;
1052         }
1053
1054         TipProducingDataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
1055         while (it.hasNext()) {
1056             final CommitEntry e = it.next();
1057             if (cohort.equals(e.cohort)) {
1058                 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1059
1060                 it.remove();
1061                 if (cohort.getCandidate() != null) {
1062                     rebaseTransactions(it, newTip);
1063                 }
1064
1065                 return true;
1066             } else {
1067                 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), newTip);
1068             }
1069         }
1070
1071         LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1072         return true;
1073     }
1074
1075     @SuppressWarnings("checkstyle:IllegalCatch")
1076     private void rebaseTransactions(final Iterator<CommitEntry> iter, @Nonnull final TipProducingDataTreeTip newTip) {
1077         tip = Preconditions.checkNotNull(newTip);
1078         while (iter.hasNext()) {
1079             final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1080             if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1081                 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1082
1083                 try {
1084                     tip.validate(cohort.getDataTreeModification());
1085                 } catch (DataValidationFailedException | RuntimeException e) {
1086                     LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1087                     cohort.reportFailure(e);
1088                 }
1089             } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1090                 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1091
1092                 try {
1093                     tip.validate(cohort.getDataTreeModification());
1094                     DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1095                     cohort.userPreCommit(candidate);
1096
1097                     cohort.setNewCandidate(candidate);
1098                     tip = candidate;
1099                 } catch (ExecutionException | TimeoutException | RuntimeException | DataValidationFailedException e) {
1100                     LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1101                     cohort.reportFailure(e);
1102                 }
1103             }
1104         }
1105     }
1106
1107     void setRunOnPendingTransactionsComplete(final Runnable operation) {
1108         runOnPendingTransactionsComplete = operation;
1109         maybeRunOperationOnPendingTransactionsComplete();
1110     }
1111
1112     private void maybeRunOperationOnPendingTransactionsComplete() {
1113         if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1114             LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1115                     runOnPendingTransactionsComplete);
1116
1117             runOnPendingTransactionsComplete.run();
1118             runOnPendingTransactionsComplete = null;
1119         }
1120     }
1121 }