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