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