2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.cluster.datastore;
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.Preconditions;
15 import com.google.common.base.Stopwatch;
16 import com.google.common.base.Verify;
17 import com.google.common.collect.ImmutableList;
18 import com.google.common.collect.ImmutableMap;
19 import com.google.common.collect.ImmutableMap.Builder;
20 import com.google.common.collect.Iterables;
21 import com.google.common.primitives.UnsignedLong;
22 import com.google.common.util.concurrent.FutureCallback;
23 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
25 import java.io.IOException;
26 import java.util.ArrayDeque;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.Deque;
31 import java.util.HashMap;
32 import java.util.Iterator;
34 import java.util.Map.Entry;
35 import java.util.Optional;
36 import java.util.OptionalLong;
37 import java.util.Queue;
38 import java.util.SortedSet;
39 import java.util.concurrent.TimeUnit;
40 import java.util.concurrent.TimeoutException;
41 import java.util.function.Consumer;
42 import java.util.function.Function;
43 import java.util.function.UnaryOperator;
44 import org.eclipse.jdt.annotation.NonNull;
45 import org.eclipse.jdt.annotation.Nullable;
46 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
47 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
48 import org.opendaylight.controller.cluster.datastore.DataTreeCohortActorRegistry.CohortRegistryCommand;
49 import org.opendaylight.controller.cluster.datastore.ShardDataTreeCohort.State;
50 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
51 import org.opendaylight.controller.cluster.datastore.persisted.AbortTransactionPayload;
52 import org.opendaylight.controller.cluster.datastore.persisted.AbstractIdentifiablePayload;
53 import org.opendaylight.controller.cluster.datastore.persisted.CloseLocalHistoryPayload;
54 import org.opendaylight.controller.cluster.datastore.persisted.CommitTransactionPayload;
55 import org.opendaylight.controller.cluster.datastore.persisted.CreateLocalHistoryPayload;
56 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
57 import org.opendaylight.controller.cluster.datastore.persisted.PurgeLocalHistoryPayload;
58 import org.opendaylight.controller.cluster.datastore.persisted.PurgeTransactionPayload;
59 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
60 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshotMetadata;
61 import org.opendaylight.controller.cluster.datastore.utils.DataTreeModificationOutput;
62 import org.opendaylight.controller.cluster.datastore.utils.PruningDataTreeModification;
63 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
64 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
65 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
66 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
67 import org.opendaylight.yangtools.concepts.Identifier;
68 import org.opendaylight.yangtools.concepts.ListenerRegistration;
69 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
70 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
72 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
73 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
74 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
75 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
76 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
77 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
78 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
79 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeTip;
80 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
81 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
82 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
83 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
84 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
85 import org.slf4j.Logger;
86 import org.slf4j.LoggerFactory;
87 import scala.concurrent.duration.FiniteDuration;
90 * Internal shard state, similar to a DOMStore, but optimized for use in the actor system, e.g. it does not expose
91 * public interfaces and assumes it is only ever called from a single thread.
94 * This class is not part of the API contract and is subject to change at any time. It is NOT thread-safe.
96 public class ShardDataTree extends ShardDataTreeTransactionParent {
97 private static final class CommitEntry {
98 final SimpleShardDataTreeCohort cohort;
101 CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
102 this.cohort = Preconditions.checkNotNull(cohort);
107 public String toString() {
108 return "CommitEntry [tx=" + cohort.getIdentifier() + ", state=" + cohort.getState() + "]";
112 private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(FiniteDuration.create(5, TimeUnit.SECONDS));
113 private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
116 * Process this many transactions in a single batched run. If we exceed this limit, we need to schedule later
117 * execution to finish up the batch. This is necessary in case of a long list of transactions which progress
118 * immediately through their preCommit phase -- if that happens, their completion eats up stack frames and could
119 * result in StackOverflowError.
121 private static final int MAX_TRANSACTION_BATCH = 100;
123 private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
124 private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
125 private final Deque<CommitEntry> pendingTransactions = new ArrayDeque<>();
126 private final Queue<CommitEntry> pendingCommits = new ArrayDeque<>();
127 private final Queue<CommitEntry> pendingFinishCommits = new ArrayDeque<>();
130 * Callbacks that need to be invoked once a payload is replicated.
132 private final Map<Payload, Runnable> replicationCallbacks = new HashMap<>();
134 private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
135 private final Collection<ShardDataTreeMetadata<?>> metadata;
136 private final DataTree dataTree;
137 private final String logContext;
138 private final Shard shard;
139 private Runnable runOnPendingTransactionsComplete;
142 * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
143 * {@link DataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
144 * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
145 * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
147 private DataTreeTip tip;
149 private SchemaContext schemaContext;
150 private DataSchemaContextTree dataSchemaContext;
152 private int currentTransactionBatch;
154 ShardDataTree(final Shard shard, final SchemaContext schemaContext, final DataTree dataTree,
155 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
156 final String logContext,
157 final ShardDataTreeMetadata<?>... metadata) {
158 this.dataTree = Preconditions.checkNotNull(dataTree);
159 updateSchemaContext(schemaContext);
161 this.shard = Preconditions.checkNotNull(shard);
162 this.treeChangeListenerPublisher = Preconditions.checkNotNull(treeChangeListenerPublisher);
163 this.logContext = Preconditions.checkNotNull(logContext);
164 this.metadata = ImmutableList.copyOf(metadata);
168 ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType,
169 final YangInstanceIdentifier root,
170 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
171 final String logContext,
172 final ShardDataTreeMetadata<?>... metadata) {
173 this(shard, schemaContext, createDataTree(treeType, root), treeChangeListenerPublisher, logContext, metadata);
176 private static DataTree createDataTree(final TreeType treeType, final YangInstanceIdentifier root) {
177 final DataTreeConfiguration baseConfig = DataTreeConfiguration.getDefault(treeType);
178 return new InMemoryDataTreeFactory().create(new DataTreeConfiguration.Builder(baseConfig.getTreeType())
179 .setMandatoryNodesValidation(baseConfig.isMandatoryNodesValidationEnabled())
180 .setUniqueIndexes(baseConfig.isUniqueIndexEnabled())
186 public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType) {
187 this(shard, schemaContext, treeType, YangInstanceIdentifier.EMPTY,
188 new DefaultShardDataTreeChangeListenerPublisher(""), "");
191 final String logContext() {
195 final long readTime() {
196 return shard.ticker().read();
199 public DataTree getDataTree() {
203 SchemaContext getSchemaContext() {
204 return schemaContext;
207 void updateSchemaContext(final SchemaContext newSchemaContext) {
208 dataTree.setSchemaContext(newSchemaContext);
209 this.schemaContext = Preconditions.checkNotNull(newSchemaContext);
210 this.dataSchemaContext = DataSchemaContextTree.from(newSchemaContext);
213 void resetTransactionBatch() {
214 currentTransactionBatch = 0;
218 * Take a snapshot of current state for later recovery.
220 * @return A state snapshot
222 @NonNull ShardDataTreeSnapshot takeStateSnapshot() {
223 final NormalizedNode<?, ?> rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY).get();
224 final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
225 ImmutableMap.builder();
227 for (ShardDataTreeMetadata<?> m : metadata) {
228 final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
230 metaBuilder.put(meta.getType(), meta);
234 return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
237 private boolean anyPendingTransactions() {
238 return !pendingTransactions.isEmpty() || !pendingCommits.isEmpty() || !pendingFinishCommits.isEmpty();
241 private void applySnapshot(final @NonNull ShardDataTreeSnapshot snapshot,
242 final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
243 final Stopwatch elapsed = Stopwatch.createStarted();
245 if (anyPendingTransactions()) {
246 LOG.warn("{}: applying state snapshot with pending transactions", logContext);
249 final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
250 if (snapshot instanceof MetadataShardDataTreeSnapshot) {
251 snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
253 snapshotMeta = ImmutableMap.of();
256 for (ShardDataTreeMetadata<?> m : metadata) {
257 final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
265 final DataTreeModification mod = wrapper.apply(dataTree.takeSnapshot().newModification());
266 // delete everything first
267 mod.delete(YangInstanceIdentifier.EMPTY);
269 final Optional<NormalizedNode<?, ?>> maybeNode = snapshot.getRootNode();
270 if (maybeNode.isPresent()) {
271 // Add everything from the remote node back
272 mod.write(YangInstanceIdentifier.EMPTY, maybeNode.get());
276 final DataTreeModification unwrapped = unwrap(mod);
277 dataTree.validate(unwrapped);
278 DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
279 dataTree.commit(candidate);
280 notifyListeners(candidate);
282 LOG.debug("{}: state snapshot applied in {}", logContext, elapsed);
286 * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
287 * does not perform any pruning.
289 * @param snapshot Snapshot that needs to be applied
290 * @throws DataValidationFailedException when the snapshot fails to apply
292 void applySnapshot(final @NonNull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
293 applySnapshot(snapshot, UnaryOperator.identity());
296 private PruningDataTreeModification wrapWithPruning(final DataTreeModification delegate) {
297 return new PruningDataTreeModification(delegate, dataTree, dataSchemaContext);
300 private static DataTreeModification unwrap(final DataTreeModification modification) {
301 if (modification instanceof PruningDataTreeModification) {
302 return ((PruningDataTreeModification)modification).delegate();
308 * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
309 * pruning in an attempt to adjust the state to our current SchemaContext.
311 * @param snapshot Snapshot that needs to be applied
312 * @throws DataValidationFailedException when the snapshot fails to apply
314 void applyRecoverySnapshot(final @NonNull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
315 applySnapshot(snapshot, this::wrapWithPruning);
318 @SuppressWarnings("checkstyle:IllegalCatch")
319 private void applyRecoveryCandidate(final DataTreeCandidate candidate) {
320 final PruningDataTreeModification mod = wrapWithPruning(dataTree.takeSnapshot().newModification());
321 DataTreeCandidates.applyToModification(mod, candidate);
324 final DataTreeModification unwrapped = mod.delegate();
325 LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
328 dataTree.validate(unwrapped);
329 dataTree.commit(dataTree.prepare(unwrapped));
330 } catch (Exception e) {
331 File file = new File(System.getProperty("karaf.data", "."),
332 "failed-recovery-payload-" + logContext + ".out");
333 DataTreeModificationOutput.toFile(file, unwrapped);
334 throw new IllegalStateException(String.format(
335 "%s: Failed to apply recovery payload. Modification data was written to file %s",
336 logContext, file), e);
341 * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
342 * pruning in an attempt to adjust the state to our current SchemaContext.
344 * @param payload Payload
345 * @throws IOException when the snapshot fails to deserialize
346 * @throws DataValidationFailedException when the snapshot fails to apply
348 void applyRecoveryPayload(final @NonNull Payload payload) throws IOException {
349 if (payload instanceof CommitTransactionPayload) {
350 final Entry<TransactionIdentifier, DataTreeCandidate> e =
351 ((CommitTransactionPayload) payload).getCandidate();
352 applyRecoveryCandidate(e.getValue());
353 allMetadataCommittedTransaction(e.getKey());
354 } else if (payload instanceof AbortTransactionPayload) {
355 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
356 } else if (payload instanceof PurgeTransactionPayload) {
357 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
358 } else if (payload instanceof CreateLocalHistoryPayload) {
359 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
360 } else if (payload instanceof CloseLocalHistoryPayload) {
361 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
362 } else if (payload instanceof PurgeLocalHistoryPayload) {
363 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
365 LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
369 private void applyReplicatedCandidate(final TransactionIdentifier identifier, final DataTreeCandidate foreign)
370 throws DataValidationFailedException {
371 LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
373 final DataTreeModification mod = dataTree.takeSnapshot().newModification();
374 DataTreeCandidates.applyToModification(mod, foreign);
377 LOG.trace("{}: Applying foreign modification {}", logContext, mod);
378 dataTree.validate(mod);
379 final DataTreeCandidate candidate = dataTree.prepare(mod);
380 dataTree.commit(candidate);
382 allMetadataCommittedTransaction(identifier);
383 notifyListeners(candidate);
387 * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
388 * SchemaContexts match and does not perform any pruning.
390 * @param identifier Payload identifier as returned from RaftActor
391 * @param payload Payload
392 * @throws IOException when the snapshot fails to deserialize
393 * @throws DataValidationFailedException when the snapshot fails to apply
395 void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
396 DataValidationFailedException {
398 * 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
399 * if we are the leader and it has originated with us.
401 * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
402 * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
403 * acting in that capacity anymore.
405 * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
406 * pre-Boron state -- which limits the number of options here.
408 if (payload instanceof CommitTransactionPayload) {
409 if (identifier == null) {
410 final Entry<TransactionIdentifier, DataTreeCandidate> e =
411 ((CommitTransactionPayload) payload).getCandidate();
412 applyReplicatedCandidate(e.getKey(), e.getValue());
414 Verify.verify(identifier instanceof TransactionIdentifier);
415 payloadReplicationComplete((TransactionIdentifier) identifier);
417 } else if (payload instanceof AbortTransactionPayload) {
418 if (identifier != null) {
419 payloadReplicationComplete((AbortTransactionPayload) payload);
421 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
422 } else if (payload instanceof PurgeTransactionPayload) {
423 if (identifier != null) {
424 payloadReplicationComplete((PurgeTransactionPayload) payload);
426 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
427 } else if (payload instanceof CloseLocalHistoryPayload) {
428 if (identifier != null) {
429 payloadReplicationComplete((CloseLocalHistoryPayload) payload);
431 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
432 } else if (payload instanceof CreateLocalHistoryPayload) {
433 if (identifier != null) {
434 payloadReplicationComplete((CreateLocalHistoryPayload)payload);
436 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
437 } else if (payload instanceof PurgeLocalHistoryPayload) {
438 if (identifier != null) {
439 payloadReplicationComplete((PurgeLocalHistoryPayload)payload);
441 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
443 LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
447 private void replicatePayload(final Identifier id, final Payload payload, final @Nullable Runnable callback) {
448 if (callback != null) {
449 replicationCallbacks.put(payload, callback);
451 shard.persistPayload(id, payload, true);
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);
460 LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
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 allMetadataCommittedTransaction(txId);
472 if (!current.cohort.getIdentifier().equals(txId)) {
473 LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
474 current.cohort.getIdentifier(), txId);
475 allMetadataCommittedTransaction(txId);
479 finishCommit(current.cohort);
482 private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
483 for (ShardDataTreeMetadata<?> m : metadata) {
484 m.onTransactionAborted(txId);
488 private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
489 for (ShardDataTreeMetadata<?> m : metadata) {
490 m.onTransactionCommitted(txId);
494 private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
495 for (ShardDataTreeMetadata<?> m : metadata) {
496 m.onTransactionPurged(txId);
500 private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
501 for (ShardDataTreeMetadata<?> m : metadata) {
502 m.onHistoryCreated(historyId);
506 private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
507 for (ShardDataTreeMetadata<?> m : metadata) {
508 m.onHistoryClosed(historyId);
512 private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
513 for (ShardDataTreeMetadata<?> m : metadata) {
514 m.onHistoryPurged(historyId);
519 * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
520 * this method is used for re-establishing state when we are taking over
522 * @param historyId Local history identifier
523 * @param closed True if the chain should be created in closed state (i.e. pending purge)
524 * @return Transaction chain handle
526 ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
527 final boolean closed) {
528 final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
529 final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
530 Preconditions.checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId,
535 ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId,
536 final @Nullable Runnable callback) {
537 ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
539 chain = new ShardDataTreeTransactionChain(historyId, this);
540 transactionChains.put(historyId, chain);
541 replicatePayload(historyId, CreateLocalHistoryPayload.create(
542 historyId, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
543 } else if (callback != null) {
550 ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
551 shard.getShardMBean().incrementReadOnlyTransactionCount();
553 if (txId.getHistoryId().getHistoryId() == 0) {
554 return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
557 return ensureTransactionChain(txId.getHistoryId(), null).newReadOnlyTransaction(txId);
560 ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
561 shard.getShardMBean().incrementReadWriteTransactionCount();
563 if (txId.getHistoryId().getHistoryId() == 0) {
564 return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
568 return ensureTransactionChain(txId.getHistoryId(), null).newReadWriteTransaction(txId);
572 public void notifyListeners(final DataTreeCandidate candidate) {
573 treeChangeListenerPublisher.publishChanges(candidate);
577 * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
578 * replication callbacks.
580 void purgeLeaderState() {
581 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
585 transactionChains.clear();
586 replicationCallbacks.clear();
590 * Close a single transaction chain.
592 * @param id History identifier
593 * @param callback Callback to invoke upon completion, may be null
595 void closeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
596 if (commonCloseTransactionChain(id, callback)) {
597 replicatePayload(id, CloseLocalHistoryPayload.create(id,
598 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
603 * Close a single transaction chain which is received through ask-based protocol. It does not keep a commit record.
605 * @param id History identifier
607 void closeTransactionChain(final LocalHistoryIdentifier id) {
608 commonCloseTransactionChain(id, null);
611 private boolean commonCloseTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
612 final ShardDataTreeTransactionChain chain = transactionChains.get(id);
614 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
615 if (callback != null) {
626 * Purge a single transaction chain.
628 * @param id History identifier
629 * @param callback Callback to invoke upon completion, may be null
631 void purgeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
632 final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
634 LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
635 if (callback != null) {
641 replicatePayload(id, PurgeLocalHistoryPayload.create(
642 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
645 Optional<DataTreeCandidate> readCurrentData() {
646 return dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY)
647 .map(state -> DataTreeCandidates.fromNormalizedNode(YangInstanceIdentifier.EMPTY, state));
650 public void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
651 final Optional<DataTreeCandidate> initialState,
652 final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
653 treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
657 return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
661 void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
662 final TransactionIdentifier id = transaction.getIdentifier();
663 LOG.debug("{}: aborting transaction {}", logContext, id);
664 replicatePayload(id, AbortTransactionPayload.create(
665 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
669 void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
670 // No-op for free-standing transactions
675 ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction,
676 final Optional<SortedSet<String>> participatingShardNames) {
677 final DataTreeModification snapshot = transaction.getSnapshot();
678 final TransactionIdentifier id = transaction.getIdentifier();
679 LOG.debug("{}: readying transaction {}", logContext, id);
681 LOG.debug("{}: transaction {} ready", logContext, id);
683 return createReadyCohort(transaction.getIdentifier(), snapshot, participatingShardNames);
686 void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
687 LOG.debug("{}: purging transaction {}", logContext, id);
688 replicatePayload(id, PurgeTransactionPayload.create(
689 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
692 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
693 return dataTree.takeSnapshot().readNode(path);
696 DataTreeSnapshot takeSnapshot() {
697 return dataTree.takeSnapshot();
701 public DataTreeModification newModification() {
702 return dataTree.takeSnapshot().newModification();
705 public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
706 Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
708 for (CommitEntry entry: pendingFinishCommits) {
709 ret.add(entry.cohort);
712 for (CommitEntry entry: pendingCommits) {
713 ret.add(entry.cohort);
716 for (CommitEntry entry: pendingTransactions) {
717 ret.add(entry.cohort);
720 pendingFinishCommits.clear();
721 pendingCommits.clear();
722 pendingTransactions.clear();
728 * Called some time after {@link #processNextPendingTransaction()} decides to stop processing.
730 void resumeNextPendingTransaction() {
731 LOG.debug("{}: attempting to resume transaction processing", logContext);
732 processNextPending();
735 @SuppressWarnings("checkstyle:IllegalCatch")
736 private void processNextPendingTransaction() {
737 ++currentTransactionBatch;
738 if (currentTransactionBatch > MAX_TRANSACTION_BATCH) {
739 LOG.debug("{}: Already processed {}, scheduling continuation", logContext, currentTransactionBatch);
740 shard.scheduleNextPendingTransaction();
744 processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
745 final SimpleShardDataTreeCohort cohort = entry.cohort;
746 final DataTreeModification modification = cohort.getDataTreeModification();
748 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
751 tip.validate(modification);
752 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
753 cohort.successfulCanCommit();
754 entry.lastAccess = readTime();
756 } catch (ConflictingModificationAppliedException e) {
757 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
759 cause = new OptimisticLockFailedException("Optimistic lock failed for path " + e.getPath(), e);
760 } catch (DataValidationFailedException e) {
761 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
764 // For debugging purposes, allow dumping of the modification. Coupled with the above
765 // precondition log, it should allow us to understand what went on.
766 LOG.debug("{}: Store Tx {}: modifications: {} tree: {}", logContext, cohort.getIdentifier(),
767 modification, dataTree);
768 cause = new TransactionCommitFailedException("Data did not pass validation for path " + e.getPath(), e);
769 } catch (Exception e) {
770 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
774 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
775 pendingTransactions.poll().cohort.failedCanCommit(cause);
779 private void processNextPending() {
780 processNextPendingCommit();
781 processNextPendingTransaction();
784 private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
785 final Consumer<CommitEntry> processor) {
786 while (!queue.isEmpty()) {
787 final CommitEntry entry = queue.peek();
788 final SimpleShardDataTreeCohort cohort = entry.cohort;
790 if (cohort.isFailed()) {
791 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
796 if (cohort.getState() == allowedState) {
797 processor.accept(entry);
803 maybeRunOperationOnPendingTransactionsComplete();
806 private void processNextPendingCommit() {
807 processNextPending(pendingCommits, State.COMMIT_PENDING,
808 entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
811 private boolean peekNextPendingCommit() {
812 final CommitEntry first = pendingCommits.peek();
813 return first != null && first.cohort.getState() == State.COMMIT_PENDING;
816 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
817 final CommitEntry head = pendingTransactions.peek();
819 LOG.warn("{}: No transactions enqueued while attempting to start canCommit on {}", logContext, cohort);
822 if (!cohort.equals(head.cohort)) {
823 // The tx isn't at the head of the queue so we can't start canCommit at this point. Here we check if this
824 // tx should be moved ahead of other tx's in the READY state in the pendingTransactions queue. If this tx
825 // has other participating shards, it could deadlock with other tx's accessing the same shards
826 // depending on the order the tx's are readied on each shard
827 // (see https://jira.opendaylight.org/browse/CONTROLLER-1836). Therefore, if the preceding participating
828 // shard names for a preceding pending tx, call it A, in the queue matches that of this tx, then this tx
829 // is allowed to be moved ahead of tx A in the queue so it is processed first to avoid potential deadlock
830 // if tx A is behind this tx in the pendingTransactions queue for a preceding shard. In other words, since
831 // canCommmit for this tx was requested before tx A, honor that request. If this tx is moved to the head of
832 // the queue as a result, then proceed with canCommit.
834 Collection<String> precedingShardNames = extractPrecedingShardNames(cohort.getParticipatingShardNames());
835 if (precedingShardNames.isEmpty()) {
836 LOG.debug("{}: Tx {} is scheduled for canCommit step", logContext, cohort.getIdentifier());
840 LOG.debug("{}: Evaluating tx {} for canCommit - preceding participating shard names {}",
841 logContext, cohort.getIdentifier(), precedingShardNames);
842 final Iterator<CommitEntry> iter = pendingTransactions.iterator();
844 int moveToIndex = -1;
845 while (iter.hasNext()) {
846 final CommitEntry entry = iter.next();
849 if (cohort.equals(entry.cohort)) {
850 if (moveToIndex < 0) {
851 LOG.debug("{}: Not moving tx {} - cannot proceed with canCommit",
852 logContext, cohort.getIdentifier());
856 LOG.debug("{}: Moving {} to index {} in the pendingTransactions queue",
857 logContext, cohort.getIdentifier(), moveToIndex);
859 insertEntry(pendingTransactions, entry, moveToIndex);
861 if (!cohort.equals(pendingTransactions.peek().cohort)) {
862 LOG.debug("{}: Tx {} is not at the head of the queue - cannot proceed with canCommit",
863 logContext, cohort.getIdentifier());
867 LOG.debug("{}: Tx {} is now at the head of the queue - proceeding with canCommit",
868 logContext, cohort.getIdentifier());
872 if (entry.cohort.getState() != State.READY) {
873 LOG.debug("{}: Skipping pending transaction {} in state {}",
874 logContext, entry.cohort.getIdentifier(), entry.cohort.getState());
878 final Collection<String> pendingPrecedingShardNames = extractPrecedingShardNames(
879 entry.cohort.getParticipatingShardNames());
881 if (precedingShardNames.equals(pendingPrecedingShardNames)) {
882 if (moveToIndex < 0) {
883 LOG.debug("{}: Preceding shard names {} for pending tx {} match - saving moveToIndex {}",
884 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), index);
888 "{}: Preceding shard names {} for pending tx {} match but moveToIndex already set to {}",
889 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), moveToIndex);
892 LOG.debug("{}: Preceding shard names {} for pending tx {} differ - skipping",
893 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier());
898 processNextPendingTransaction();
901 private static void insertEntry(final Deque<CommitEntry> queue, final CommitEntry entry, final int atIndex) {
903 queue.addFirst(entry);
907 LOG.trace("Inserting into Deque at index {}", atIndex);
909 Deque<CommitEntry> tempStack = new ArrayDeque<>(atIndex);
910 for (int i = 0; i < atIndex; i++) {
911 tempStack.push(queue.poll());
914 queue.addFirst(entry);
916 tempStack.forEach(queue::addFirst);
919 private Collection<String> extractPrecedingShardNames(final Optional<SortedSet<String>> participatingShardNames) {
920 return participatingShardNames.map((Function<SortedSet<String>, Collection<String>>)
921 set -> set.headSet(shard.getShardName())).orElse(Collections.<String>emptyList());
924 private void failPreCommit(final Throwable cause) {
925 shard.getShardMBean().incrementFailedTransactionsCount();
926 pendingTransactions.poll().cohort.failedPreCommit(cause);
927 processNextPendingTransaction();
930 @SuppressWarnings("checkstyle:IllegalCatch")
931 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
932 final CommitEntry entry = pendingTransactions.peek();
933 Preconditions.checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
935 final SimpleShardDataTreeCohort current = entry.cohort;
936 Verify.verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
938 final TransactionIdentifier currentId = current.getIdentifier();
939 LOG.debug("{}: Preparing transaction {}", logContext, currentId);
941 final DataTreeCandidateTip candidate;
943 candidate = tip.prepare(cohort.getDataTreeModification());
944 LOG.debug("{}: Transaction {} candidate ready", logContext, currentId);
945 } catch (RuntimeException e) {
950 cohort.userPreCommit(candidate, new FutureCallback<Void>() {
952 public void onSuccess(final Void noop) {
953 // Set the tip of the data tree.
954 tip = Verify.verifyNotNull(candidate);
956 entry.lastAccess = readTime();
958 pendingTransactions.remove();
959 pendingCommits.add(entry);
961 LOG.debug("{}: Transaction {} prepared", logContext, currentId);
963 cohort.successfulPreCommit(candidate);
965 processNextPendingTransaction();
969 public void onFailure(final Throwable failure) {
970 failPreCommit(failure);
975 private void failCommit(final Exception cause) {
976 shard.getShardMBean().incrementFailedTransactionsCount();
977 pendingFinishCommits.poll().cohort.failedCommit(cause);
978 processNextPending();
981 @SuppressWarnings("checkstyle:IllegalCatch")
982 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
983 final TransactionIdentifier txId = cohort.getIdentifier();
984 final DataTreeCandidate candidate = cohort.getCandidate();
986 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
988 if (tip == candidate) {
989 // All pending candidates have been committed, reset the tip to the data tree.
994 dataTree.commit(candidate);
995 } catch (Exception e) {
996 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
1001 allMetadataCommittedTransaction(txId);
1002 shard.getShardMBean().incrementCommittedTransactionCount();
1003 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
1005 // FIXME: propagate journal index
1006 pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO, () -> {
1007 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
1008 notifyListeners(candidate);
1010 processNextPending();
1014 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
1015 final CommitEntry entry = pendingCommits.peek();
1016 Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
1018 final SimpleShardDataTreeCohort current = entry.cohort;
1019 if (!cohort.equals(current)) {
1020 LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
1024 LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
1026 final TransactionIdentifier txId = cohort.getIdentifier();
1027 final Payload payload;
1029 payload = CommitTransactionPayload.create(txId, candidate,
1030 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity());
1031 } catch (IOException e) {
1032 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
1033 pendingCommits.poll().cohort.failedCommit(e);
1034 processNextPending();
1038 // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
1039 // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
1040 // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
1041 // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
1042 // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
1043 // pendingCommits queue.
1044 processNextPendingTransaction();
1046 // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
1047 // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
1048 // in order to properly determine the batchHint flag for the call to persistPayload.
1049 pendingCommits.remove();
1050 pendingFinishCommits.add(entry);
1052 // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
1053 // this transaction for replication.
1054 boolean replicationBatchHint = peekNextPendingCommit();
1056 // Once completed, we will continue via payloadReplicationComplete
1057 shard.persistPayload(txId, payload, replicationBatchHint);
1059 entry.lastAccess = shard.ticker().read();
1061 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
1063 // Process the next transaction pending commit, if any. If there is one it will be batched with this
1064 // transaction for replication.
1065 processNextPendingCommit();
1068 Collection<ActorRef> getCohortActors() {
1069 return cohortRegistry.getCohortActors();
1072 void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
1073 cohortRegistry.process(sender, message);
1077 ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1078 final Exception failure) {
1079 final SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId, failure);
1080 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1085 ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1086 final Optional<SortedSet<String>> participatingShardNames) {
1087 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId,
1088 cohortRegistry.createCohort(schemaContext, txId, shard::executeInSelf,
1089 COMMIT_STEP_TIMEOUT), participatingShardNames);
1090 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1094 // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
1095 // the newReadWriteTransaction()
1096 ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1097 final Optional<SortedSet<String>> participatingShardNames) {
1098 if (txId.getHistoryId().getHistoryId() == 0) {
1099 return createReadyCohort(txId, mod, participatingShardNames);
1102 return ensureTransactionChain(txId.getHistoryId(), null).createReadyCohort(txId, mod, participatingShardNames);
1105 @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
1106 void checkForExpiredTransactions(final long transactionCommitTimeoutMillis,
1107 final Function<SimpleShardDataTreeCohort, OptionalLong> accessTimeUpdater) {
1108 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
1109 final long now = readTime();
1111 final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
1112 !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
1113 final CommitEntry currentTx = currentQueue.peek();
1114 if (currentTx == null) {
1115 // Empty queue, no-op
1119 long delta = now - currentTx.lastAccess;
1120 if (delta < timeout) {
1121 // Not expired yet, bail
1125 final OptionalLong updateOpt = accessTimeUpdater.apply(currentTx.cohort);
1126 if (updateOpt.isPresent()) {
1127 final long newAccess = updateOpt.getAsLong();
1128 final long newDelta = now - newAccess;
1129 if (newDelta < delta) {
1130 LOG.debug("{}: Updated current transaction {} access time", logContext,
1131 currentTx.cohort.getIdentifier());
1132 currentTx.lastAccess = newAccess;
1136 if (delta < timeout) {
1137 // Not expired yet, bail
1142 final long deltaMillis = TimeUnit.NANOSECONDS.toMillis(delta);
1143 final State state = currentTx.cohort.getState();
1145 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
1146 currentTx.cohort.getIdentifier(), deltaMillis, state);
1147 boolean processNext = true;
1148 final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
1149 + deltaMillis + "ms");
1152 case CAN_COMMIT_PENDING:
1153 currentQueue.remove().cohort.failedCanCommit(cohortFailure);
1155 case CAN_COMMIT_COMPLETE:
1156 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
1157 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
1158 // in PRE_COMMIT_COMPLETE is changed.
1159 currentQueue.remove().cohort.reportFailure(cohortFailure);
1161 case PRE_COMMIT_PENDING:
1162 currentQueue.remove().cohort.failedPreCommit(cohortFailure);
1164 case PRE_COMMIT_COMPLETE:
1165 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
1166 // are ready we should commit the transaction, not abort it. Our current software stack does
1167 // not allow us to do that consistently, because we persist at the time of commit, hence
1168 // we can end up in a state where we have pre-committed a transaction, then a leader failover
1169 // occurred ... the new leader does not see the pre-committed transaction and does not have
1170 // a running timer. To fix this we really need two persistence events.
1172 // The first one, done at pre-commit time will hold the transaction payload. When consensus
1173 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1174 // apply the state in this event.
1176 // The second one, done at commit (or abort) time holds only the transaction identifier and
1177 // signals to followers that the state should (or should not) be applied.
1179 // In order to make the pre-commit timer working across failovers, though, we need
1180 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1181 // restart the timer.
1182 currentQueue.remove().cohort.reportFailure(cohortFailure);
1184 case COMMIT_PENDING:
1185 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1186 currentTx.cohort.getIdentifier());
1187 currentTx.lastAccess = now;
1188 processNext = false;
1191 currentQueue.remove().cohort.reportFailure(cohortFailure);
1197 currentQueue.remove();
1201 processNextPending();
1205 boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1206 final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1207 pendingTransactions).iterator();
1208 if (!it.hasNext()) {
1209 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1213 // First entry is special, as it may already be committing
1214 final CommitEntry first = it.next();
1215 if (cohort.equals(first.cohort)) {
1216 if (cohort.getState() != State.COMMIT_PENDING) {
1217 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1218 cohort.getIdentifier());
1221 if (cohort.getCandidate() != null) {
1222 rebaseTransactions(it, dataTree);
1225 processNextPending();
1229 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1233 DataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
1234 while (it.hasNext()) {
1235 final CommitEntry e = it.next();
1236 if (cohort.equals(e.cohort)) {
1237 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1240 if (cohort.getCandidate() != null) {
1241 rebaseTransactions(it, newTip);
1246 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), newTip);
1250 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1254 @SuppressWarnings("checkstyle:IllegalCatch")
1255 private void rebaseTransactions(final Iterator<CommitEntry> iter, final @NonNull DataTreeTip newTip) {
1256 tip = Preconditions.checkNotNull(newTip);
1257 while (iter.hasNext()) {
1258 final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1259 if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1260 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1263 tip.validate(cohort.getDataTreeModification());
1264 } catch (DataValidationFailedException | RuntimeException e) {
1265 LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1266 cohort.reportFailure(e);
1268 } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1269 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1272 tip.validate(cohort.getDataTreeModification());
1273 DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1275 cohort.setNewCandidate(candidate);
1277 } catch (RuntimeException | DataValidationFailedException e) {
1278 LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1279 cohort.reportFailure(e);
1285 void setRunOnPendingTransactionsComplete(final Runnable operation) {
1286 runOnPendingTransactionsComplete = operation;
1287 maybeRunOperationOnPendingTransactionsComplete();
1290 private void maybeRunOperationOnPendingTransactionsComplete() {
1291 if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1292 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1293 runOnPendingTransactionsComplete);
1295 runOnPendingTransactionsComplete.run();
1296 runOnPendingTransactionsComplete = null;
1300 ShardStats getStats() {
1301 return shard.getShardMBean();
1304 Iterator<SimpleShardDataTreeCohort> cohortIterator() {
1305 return Iterables.transform(Iterables.concat(pendingFinishCommits, pendingCommits, pendingTransactions),
1306 e -> e.cohort).iterator();
1309 void removeTransactionChain(final LocalHistoryIdentifier id) {
1310 if (transactionChains.remove(id) != null) {
1311 LOG.debug("{}: Removed transaction chain {}", logContext, id);