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