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