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