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