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