37e65f6a96e5130e53af66372ebb73937cf31332
[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.Function;
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 long readTime() {
185         return shard.ticker().read();
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 {
353             LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
354         }
355     }
356
357     private void applyReplicatedCandidate(final Identifier identifier, final DataTreeCandidate foreign)
358             throws DataValidationFailedException {
359         LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
360
361         final DataTreeModification mod = dataTree.takeSnapshot().newModification();
362         DataTreeCandidates.applyToModification(mod, foreign);
363         mod.ready();
364
365         LOG.trace("{}: Applying foreign modification {}", logContext, mod);
366         dataTree.validate(mod);
367         final DataTreeCandidate candidate = dataTree.prepare(mod);
368         dataTree.commit(candidate);
369
370         notifyListeners(candidate);
371     }
372
373     /**
374      * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
375      * SchemaContexts match and does not perform any pruning.
376      *
377      * @param identifier Payload identifier as returned from RaftActor
378      * @param payload Payload
379      * @throws IOException when the snapshot fails to deserialize
380      * @throws DataValidationFailedException when the snapshot fails to apply
381      */
382     void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
383             DataValidationFailedException {
384         /*
385          * 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
386          * if we are the leader and it has originated with us.
387          *
388          * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
389          * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
390          * acting in that capacity anymore.
391          *
392          * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
393          * pre-Boron state -- which limits the number of options here.
394          */
395         if (payload instanceof CommitTransactionPayload) {
396             final TransactionIdentifier txId;
397             if (identifier == null) {
398                 final Entry<TransactionIdentifier, DataTreeCandidate> e =
399                         ((CommitTransactionPayload) payload).getCandidate();
400                 txId = e.getKey();
401                 applyReplicatedCandidate(txId, e.getValue());
402             } else {
403                 Verify.verify(identifier instanceof TransactionIdentifier);
404                 txId = (TransactionIdentifier) identifier;
405                 payloadReplicationComplete(txId);
406             }
407             allMetadataCommittedTransaction(txId);
408         } else if (payload instanceof AbortTransactionPayload) {
409             if (identifier != null) {
410                 payloadReplicationComplete((AbortTransactionPayload) payload);
411             }
412             allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
413         } else if (payload instanceof PurgeTransactionPayload) {
414             if (identifier != null) {
415                 payloadReplicationComplete((PurgeTransactionPayload) payload);
416             }
417             allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
418         } else if (payload instanceof CloseLocalHistoryPayload) {
419             if (identifier != null) {
420                 payloadReplicationComplete((CloseLocalHistoryPayload) payload);
421             }
422             allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
423         } else if (payload instanceof CreateLocalHistoryPayload) {
424             if (identifier != null) {
425                 payloadReplicationComplete((CreateLocalHistoryPayload)payload);
426             }
427             allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
428         } else if (payload instanceof PurgeLocalHistoryPayload) {
429             if (identifier != null) {
430                 payloadReplicationComplete((PurgeLocalHistoryPayload)payload);
431             }
432             allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
433         } else {
434             LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
435         }
436     }
437
438     private void replicatePayload(final Identifier id, final Payload payload, @Nullable final Runnable callback) {
439         if (callback != null) {
440             replicationCallbacks.put(payload, callback);
441         }
442         shard.persistPayload(id, payload, true);
443     }
444
445     private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
446         final Runnable callback = replicationCallbacks.remove(payload);
447         if (callback != null) {
448             LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
449             callback.run();
450         } else {
451             LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
452         }
453     }
454
455     private void payloadReplicationComplete(final TransactionIdentifier txId) {
456         final CommitEntry current = pendingFinishCommits.peek();
457         if (current == null) {
458             LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
459             return;
460         }
461
462         if (!current.cohort.getIdentifier().equals(txId)) {
463             LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
464                 current.cohort.getIdentifier(), txId);
465             return;
466         }
467
468         finishCommit(current.cohort);
469     }
470
471     private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
472         for (ShardDataTreeMetadata<?> m : metadata) {
473             m.onTransactionAborted(txId);
474         }
475     }
476
477     private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
478         for (ShardDataTreeMetadata<?> m : metadata) {
479             m.onTransactionCommitted(txId);
480         }
481     }
482
483     private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
484         for (ShardDataTreeMetadata<?> m : metadata) {
485             m.onTransactionPurged(txId);
486         }
487     }
488
489     private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
490         for (ShardDataTreeMetadata<?> m : metadata) {
491             m.onHistoryCreated(historyId);
492         }
493     }
494
495     private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
496         for (ShardDataTreeMetadata<?> m : metadata) {
497             m.onHistoryClosed(historyId);
498         }
499     }
500
501     private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
502         for (ShardDataTreeMetadata<?> m : metadata) {
503             m.onHistoryPurged(historyId);
504         }
505     }
506
507     /**
508      * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
509      * this method is used for re-establishing state when we are taking over
510      *
511      * @param historyId Local history identifier
512      * @param closed True if the chain should be created in closed state (i.e. pending purge)
513      * @return Transaction chain handle
514      */
515     ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
516             final boolean closed) {
517         final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
518         final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
519         Preconditions.checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId,
520                 existing);
521         return ret;
522     }
523
524     ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId,
525             @Nullable final Runnable callback) {
526         ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
527         if (chain == null) {
528             chain = new ShardDataTreeTransactionChain(historyId, this);
529             transactionChains.put(historyId, chain);
530             replicatePayload(historyId, CreateLocalHistoryPayload.create(historyId), callback);
531         } else if (callback != null) {
532             callback.run();
533         }
534
535         return chain;
536     }
537
538     ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
539         if (txId.getHistoryId().getHistoryId() == 0) {
540             return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
541         }
542
543         return ensureTransactionChain(txId.getHistoryId(), null).newReadOnlyTransaction(txId);
544     }
545
546     ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
547         if (txId.getHistoryId().getHistoryId() == 0) {
548             return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
549                     .newModification());
550         }
551
552         return ensureTransactionChain(txId.getHistoryId(), null).newReadWriteTransaction(txId);
553     }
554
555     @VisibleForTesting
556     public void notifyListeners(final DataTreeCandidate candidate) {
557         treeChangeListenerPublisher.publishChanges(candidate);
558         dataChangeListenerPublisher.publishChanges(candidate);
559     }
560
561     /**
562      * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
563      * replication callbacks.
564      */
565     void purgeLeaderState() {
566         for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
567             chain.close();
568         }
569
570         transactionChains.clear();
571         replicationCallbacks.clear();
572     }
573
574     /**
575      * Close a single transaction chain.
576      *
577      * @param id History identifier
578      * @param callback Callback to invoke upon completion, may be null
579      */
580     void closeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
581         final ShardDataTreeTransactionChain chain = transactionChains.get(id);
582         if (chain == null) {
583             LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
584             if (callback != null) {
585                 callback.run();
586             }
587             return;
588         }
589
590         chain.close();
591         replicatePayload(id, CloseLocalHistoryPayload.create(id), callback);
592     }
593
594     /**
595      * Purge a single transaction chain.
596      *
597      * @param id History identifier
598      * @param callback Callback to invoke upon completion, may be null
599      */
600     void purgeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
601         final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
602         if (chain == null) {
603             LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
604             if (callback != null) {
605                 callback.run();
606             }
607             return;
608         }
609
610         replicatePayload(id, PurgeLocalHistoryPayload.create(id), callback);
611     }
612
613     void registerDataChangeListener(final YangInstanceIdentifier path,
614             final AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener,
615             final DataChangeScope scope, final Optional<DataTreeCandidate> initialState,
616             final Consumer<ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>>
617                     onRegistration) {
618         dataChangeListenerPublisher.registerDataChangeListener(path, listener, scope, initialState, onRegistration);
619     }
620
621     Optional<DataTreeCandidate> readCurrentData() {
622         final Optional<NormalizedNode<?, ?>> currentState =
623                 dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY);
624         return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
625             YangInstanceIdentifier.EMPTY, currentState.get())) : Optional.<DataTreeCandidate>absent();
626     }
627
628     public void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
629             final Optional<DataTreeCandidate> initialState,
630             final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
631         treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
632     }
633
634     int getQueueSize() {
635         return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
636     }
637
638     @Override
639     void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
640         final TransactionIdentifier id = transaction.getIdentifier();
641         LOG.debug("{}: aborting transaction {}", logContext, id);
642         replicatePayload(id, AbortTransactionPayload.create(id), callback);
643     }
644
645     @Override
646     void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
647         // No-op for free-standing transactions
648
649     }
650
651     @Override
652     ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction) {
653         final DataTreeModification snapshot = transaction.getSnapshot();
654         snapshot.ready();
655
656         return createReadyCohort(transaction.getIdentifier(), snapshot);
657     }
658
659     void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
660         LOG.debug("{}: purging transaction {}", logContext, id);
661         replicatePayload(id, PurgeTransactionPayload.create(id), callback);
662     }
663
664     public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
665         return dataTree.takeSnapshot().readNode(path);
666     }
667
668     DataTreeSnapshot takeSnapshot() {
669         return dataTree.takeSnapshot();
670     }
671
672     @VisibleForTesting
673     public DataTreeModification newModification() {
674         return dataTree.takeSnapshot().newModification();
675     }
676
677     public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
678         Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
679
680         for (CommitEntry entry: pendingFinishCommits) {
681             ret.add(entry.cohort);
682         }
683
684         for (CommitEntry entry: pendingCommits) {
685             ret.add(entry.cohort);
686         }
687
688         for (CommitEntry entry: pendingTransactions) {
689             ret.add(entry.cohort);
690         }
691
692         pendingFinishCommits.clear();
693         pendingCommits.clear();
694         pendingTransactions.clear();
695         tip = dataTree;
696         return ret;
697     }
698
699     /**
700      * Called some time after {@link #processNextPendingTransaction()} decides to stop processing.
701      */
702     void resumeNextPendingTransaction() {
703         LOG.debug("{}: attempting to resume transaction processing", logContext);
704         processNextPending();
705     }
706
707     @SuppressWarnings("checkstyle:IllegalCatch")
708     private void processNextPendingTransaction() {
709         ++currentTransactionBatch;
710         if (currentTransactionBatch > MAX_TRANSACTION_BATCH) {
711             LOG.debug("{}: Already processed {}, scheduling continuation", logContext, currentTransactionBatch);
712             shard.scheduleNextPendingTransaction();
713             return;
714         }
715
716         processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
717             final SimpleShardDataTreeCohort cohort = entry.cohort;
718             final DataTreeModification modification = cohort.getDataTreeModification();
719
720             LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
721             Exception cause;
722             try {
723                 tip.validate(modification);
724                 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
725                 cohort.successfulCanCommit();
726                 entry.lastAccess = readTime();
727                 return;
728             } catch (ConflictingModificationAppliedException e) {
729                 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
730                     e.getPath());
731                 cause = new OptimisticLockFailedException("Optimistic lock failed.", e);
732             } catch (DataValidationFailedException e) {
733                 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
734                     e.getPath(), e);
735
736                 // For debugging purposes, allow dumping of the modification. Coupled with the above
737                 // precondition log, it should allow us to understand what went on.
738                 LOG.debug("{}: Store Tx {}: modifications: {} tree: {}", cohort.getIdentifier(), modification,
739                         dataTree);
740                 cause = new TransactionCommitFailedException("Data did not pass validation.", e);
741             } catch (Exception e) {
742                 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
743                 cause = e;
744             }
745
746             // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
747             pendingTransactions.poll().cohort.failedCanCommit(cause);
748         });
749     }
750
751     private void processNextPending() {
752         processNextPendingCommit();
753         processNextPendingTransaction();
754     }
755
756     private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
757             final Consumer<CommitEntry> processor) {
758         while (!queue.isEmpty()) {
759             final CommitEntry entry = queue.peek();
760             final SimpleShardDataTreeCohort cohort = entry.cohort;
761
762             if (cohort.isFailed()) {
763                 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
764                 queue.remove();
765                 continue;
766             }
767
768             if (cohort.getState() == allowedState) {
769                 processor.accept(entry);
770             }
771
772             break;
773         }
774
775         maybeRunOperationOnPendingTransactionsComplete();
776     }
777
778     private void processNextPendingCommit() {
779         processNextPending(pendingCommits, State.COMMIT_PENDING,
780             entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
781     }
782
783     private boolean peekNextPendingCommit() {
784         final CommitEntry first = pendingCommits.peek();
785         return first != null && first.cohort.getState() == State.COMMIT_PENDING;
786     }
787
788     void startCanCommit(final SimpleShardDataTreeCohort cohort) {
789         final CommitEntry head = pendingTransactions.peek();
790         if (head == null) {
791             LOG.warn("{}: No transactions enqueued while attempting to start canCommit on {}", logContext, cohort);
792             return;
793         }
794         if (!cohort.equals(head.cohort)) {
795             LOG.debug("{}: Transaction {} scheduled for canCommit step", logContext, cohort.getIdentifier());
796             return;
797         }
798
799         processNextPendingTransaction();
800     }
801
802     private void failPreCommit(final Exception cause) {
803         shard.getShardMBean().incrementFailedTransactionsCount();
804         pendingTransactions.poll().cohort.failedPreCommit(cause);
805         processNextPendingTransaction();
806     }
807
808     @SuppressWarnings("checkstyle:IllegalCatch")
809     void startPreCommit(final SimpleShardDataTreeCohort cohort) {
810         final CommitEntry entry = pendingTransactions.peek();
811         Preconditions.checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
812
813         final SimpleShardDataTreeCohort current = entry.cohort;
814         Verify.verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
815
816         LOG.debug("{}: Preparing transaction {}", logContext, current.getIdentifier());
817
818         final DataTreeCandidateTip candidate;
819         try {
820             candidate = tip.prepare(cohort.getDataTreeModification());
821             cohort.userPreCommit(candidate);
822         } catch (ExecutionException | TimeoutException | RuntimeException e) {
823             failPreCommit(e);
824             return;
825         }
826
827         // Set the tip of the data tree.
828         tip = Verify.verifyNotNull(candidate);
829
830         entry.lastAccess = readTime();
831
832         pendingTransactions.remove();
833         pendingCommits.add(entry);
834
835         LOG.debug("{}: Transaction {} prepared", logContext, current.getIdentifier());
836
837         cohort.successfulPreCommit(candidate);
838
839         processNextPendingTransaction();
840     }
841
842     private void failCommit(final Exception cause) {
843         shard.getShardMBean().incrementFailedTransactionsCount();
844         pendingFinishCommits.poll().cohort.failedCommit(cause);
845         processNextPending();
846     }
847
848     @SuppressWarnings("checkstyle:IllegalCatch")
849     private void finishCommit(final SimpleShardDataTreeCohort cohort) {
850         final TransactionIdentifier txId = cohort.getIdentifier();
851         final DataTreeCandidate candidate = cohort.getCandidate();
852
853         LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
854
855         if (tip == candidate) {
856             // All pending candidates have been committed, reset the tip to the data tree.
857             tip = dataTree;
858         }
859
860         try {
861             dataTree.commit(candidate);
862         } catch (Exception e) {
863             LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
864             failCommit(e);
865             return;
866         }
867
868         shard.getShardMBean().incrementCommittedTransactionCount();
869         shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
870
871         // FIXME: propagate journal index
872         pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO);
873
874         LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
875         notifyListeners(candidate);
876
877         processNextPending();
878     }
879
880     void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
881         final CommitEntry entry = pendingCommits.peek();
882         Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
883
884         final SimpleShardDataTreeCohort current = entry.cohort;
885         if (!cohort.equals(current)) {
886             LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
887             return;
888         }
889
890         LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
891
892         final TransactionIdentifier txId = cohort.getIdentifier();
893         final Payload payload;
894         try {
895             payload = CommitTransactionPayload.create(txId, candidate);
896         } catch (IOException e) {
897             LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
898             pendingCommits.poll().cohort.failedCommit(e);
899             processNextPending();
900             return;
901         }
902
903         // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
904         // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
905         // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
906         // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
907         // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
908         // pendingCommits queue.
909         processNextPendingTransaction();
910
911         // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
912         // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
913         // in order to properly determine the batchHint flag for the call to persistPayload.
914         pendingCommits.remove();
915         pendingFinishCommits.add(entry);
916
917         // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
918         // this transaction for replication.
919         boolean replicationBatchHint = peekNextPendingCommit();
920
921         // Once completed, we will continue via payloadReplicationComplete
922         shard.persistPayload(txId, payload, replicationBatchHint);
923
924         entry.lastAccess = shard.ticker().read();
925
926         LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
927
928         // Process the next transaction pending commit, if any. If there is one it will be batched with this
929         // transaction for replication.
930         processNextPendingCommit();
931     }
932
933     Collection<ActorRef> getCohortActors() {
934         return cohortRegistry.getCohortActors();
935     }
936
937     void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
938         cohortRegistry.process(sender, message);
939     }
940
941     @Override
942     ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
943             final Exception failure) {
944         final SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId, failure);
945         pendingTransactions.add(new CommitEntry(cohort, readTime()));
946         return cohort;
947     }
948
949     @Override
950     ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod) {
951         SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId,
952                 cohortRegistry.createCohort(schemaContext, txId, COMMIT_STEP_TIMEOUT));
953         pendingTransactions.add(new CommitEntry(cohort, readTime()));
954         return cohort;
955     }
956
957     // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
958     // the newReadWriteTransaction()
959     ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod) {
960         if (txId.getHistoryId().getHistoryId() == 0) {
961             return createReadyCohort(txId, mod);
962         }
963
964         return ensureTransactionChain(txId.getHistoryId(), null).createReadyCohort(txId, mod);
965     }
966
967     @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
968     void checkForExpiredTransactions(final long transactionCommitTimeoutMillis,
969             final Function<SimpleShardDataTreeCohort, Optional<Long>> accessTimeUpdater) {
970         final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
971         final long now = readTime();
972
973         final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
974             !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
975         final CommitEntry currentTx = currentQueue.peek();
976         if (currentTx == null) {
977             // Empty queue, no-op
978             return;
979         }
980
981         long delta = now - currentTx.lastAccess;
982         if (delta < timeout) {
983             // Not expired yet, bail
984             return;
985         }
986
987         final Optional<Long> updateOpt = accessTimeUpdater.apply(currentTx.cohort);
988         if (updateOpt.isPresent()) {
989             final long newAccess =  updateOpt.get().longValue();
990             final long newDelta = now - newAccess;
991             if (newDelta < delta) {
992                 LOG.debug("{}: Updated current transaction {} access time", logContext,
993                     currentTx.cohort.getIdentifier());
994                 currentTx.lastAccess = newAccess;
995                 delta = newDelta;
996             }
997
998             if (delta < timeout) {
999                 // Not expired yet, bail
1000                 return;
1001             }
1002         }
1003
1004         final long deltaMillis = TimeUnit.NANOSECONDS.toMillis(delta);
1005         final State state = currentTx.cohort.getState();
1006
1007         LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
1008             currentTx.cohort.getIdentifier(), deltaMillis, state);
1009         boolean processNext = true;
1010         final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
1011                 + deltaMillis + "ms");
1012
1013         switch (state) {
1014             case CAN_COMMIT_PENDING:
1015                 currentQueue.remove().cohort.failedCanCommit(cohortFailure);
1016                 break;
1017             case CAN_COMMIT_COMPLETE:
1018                 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
1019                 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
1020                 // in PRE_COMMIT_COMPLETE is changed.
1021                 currentQueue.remove().cohort.reportFailure(cohortFailure);
1022                 break;
1023             case PRE_COMMIT_PENDING:
1024                 currentQueue.remove().cohort.failedPreCommit(cohortFailure);
1025                 break;
1026             case PRE_COMMIT_COMPLETE:
1027                 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
1028                 //        are ready we should commit the transaction, not abort it. Our current software stack does
1029                 //        not allow us to do that consistently, because we persist at the time of commit, hence
1030                 //        we can end up in a state where we have pre-committed a transaction, then a leader failover
1031                 //        occurred ... the new leader does not see the pre-committed transaction and does not have
1032                 //        a running timer. To fix this we really need two persistence events.
1033                 //
1034                 //        The first one, done at pre-commit time will hold the transaction payload. When consensus
1035                 //        is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1036                 //        apply the state in this event.
1037                 //
1038                 //        The second one, done at commit (or abort) time holds only the transaction identifier and
1039                 //        signals to followers that the state should (or should not) be applied.
1040                 //
1041                 //        In order to make the pre-commit timer working across failovers, though, we need
1042                 //        a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1043                 //        restart the timer.
1044                 currentQueue.remove().cohort.reportFailure(cohortFailure);
1045                 break;
1046             case COMMIT_PENDING:
1047                 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1048                     currentTx.cohort.getIdentifier());
1049                 currentTx.lastAccess = now;
1050                 processNext = false;
1051                 return;
1052             case READY:
1053                 currentQueue.remove().cohort.reportFailure(cohortFailure);
1054                 break;
1055             case ABORTED:
1056             case COMMITTED:
1057             case FAILED:
1058             default:
1059                 currentQueue.remove();
1060         }
1061
1062         if (processNext) {
1063             processNextPending();
1064         }
1065     }
1066
1067     boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1068         final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1069                 pendingTransactions).iterator();
1070         if (!it.hasNext()) {
1071             LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1072             return true;
1073         }
1074
1075         // First entry is special, as it may already be committing
1076         final CommitEntry first = it.next();
1077         if (cohort.equals(first.cohort)) {
1078             if (cohort.getState() != State.COMMIT_PENDING) {
1079                 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1080                     cohort.getIdentifier());
1081
1082                 it.remove();
1083                 if (cohort.getCandidate() != null) {
1084                     rebaseTransactions(it, dataTree);
1085                 }
1086
1087                 processNextPending();
1088                 return true;
1089             }
1090
1091             LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1092             return false;
1093         }
1094
1095         TipProducingDataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
1096         while (it.hasNext()) {
1097             final CommitEntry e = it.next();
1098             if (cohort.equals(e.cohort)) {
1099                 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1100
1101                 it.remove();
1102                 if (cohort.getCandidate() != null) {
1103                     rebaseTransactions(it, newTip);
1104                 }
1105
1106                 return true;
1107             } else {
1108                 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), newTip);
1109             }
1110         }
1111
1112         LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1113         return true;
1114     }
1115
1116     @SuppressWarnings("checkstyle:IllegalCatch")
1117     private void rebaseTransactions(final Iterator<CommitEntry> iter, @Nonnull final TipProducingDataTreeTip newTip) {
1118         tip = Preconditions.checkNotNull(newTip);
1119         while (iter.hasNext()) {
1120             final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1121             if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1122                 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1123
1124                 try {
1125                     tip.validate(cohort.getDataTreeModification());
1126                 } catch (DataValidationFailedException | RuntimeException e) {
1127                     LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1128                     cohort.reportFailure(e);
1129                 }
1130             } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1131                 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1132
1133                 try {
1134                     tip.validate(cohort.getDataTreeModification());
1135                     DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1136                     cohort.userPreCommit(candidate);
1137
1138                     cohort.setNewCandidate(candidate);
1139                     tip = candidate;
1140                 } catch (ExecutionException | TimeoutException | RuntimeException | DataValidationFailedException e) {
1141                     LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1142                     cohort.reportFailure(e);
1143                 }
1144             }
1145         }
1146     }
1147
1148     void setRunOnPendingTransactionsComplete(final Runnable operation) {
1149         runOnPendingTransactionsComplete = operation;
1150         maybeRunOperationOnPendingTransactionsComplete();
1151     }
1152
1153     private void maybeRunOperationOnPendingTransactionsComplete() {
1154         if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1155             LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1156                     runOnPendingTransactionsComplete);
1157
1158             runOnPendingTransactionsComplete.run();
1159             runOnPendingTransactionsComplete = null;
1160         }
1161     }
1162
1163     ShardStats getStats() {
1164         return shard.getShardMBean();
1165     }
1166
1167     Iterator<SimpleShardDataTreeCohort> cohortIterator() {
1168         return Iterables.transform(Iterables.concat(pendingFinishCommits, pendingCommits, pendingTransactions),
1169             e -> e.cohort).iterator();
1170     }
1171
1172     void removeTransactionChain(final LocalHistoryIdentifier id) {
1173         if (transactionChains.remove(id) != null) {
1174             LOG.debug("{}: Removed transaction chain {}", logContext, id);
1175         }
1176     }
1177 }