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.Optional;
15 import com.google.common.base.Preconditions;
16 import com.google.common.base.Stopwatch;
17 import com.google.common.base.Verify;
18 import com.google.common.collect.ImmutableList;
19 import com.google.common.collect.ImmutableMap;
20 import com.google.common.collect.ImmutableMap.Builder;
21 import com.google.common.collect.Iterables;
22 import com.google.common.primitives.UnsignedLong;
23 import com.google.common.util.concurrent.FutureCallback;
24 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
26 import java.io.IOException;
27 import java.util.ArrayDeque;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.Deque;
32 import java.util.HashMap;
33 import java.util.Iterator;
35 import java.util.Map.Entry;
36 import java.util.Queue;
37 import java.util.SortedSet;
38 import java.util.concurrent.TimeUnit;
39 import java.util.concurrent.TimeoutException;
40 import java.util.function.Consumer;
41 import java.util.function.Function;
42 import java.util.function.UnaryOperator;
43 import javax.annotation.Nonnull;
44 import javax.annotation.Nullable;
45 import javax.annotation.concurrent.NotThreadSafe;
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.model.api.SchemaContext;
84 import org.slf4j.Logger;
85 import org.slf4j.LoggerFactory;
86 import scala.concurrent.duration.Duration;
89 * Internal shard state, similar to a DOMStore, but optimized for use in the actor system,
90 * e.g. it does not expose public interfaces and assumes it is only ever called from a
94 * This class is not part of the API contract and is subject to change at any time.
97 public class ShardDataTree extends ShardDataTreeTransactionParent {
98 private static final class CommitEntry {
99 final SimpleShardDataTreeCohort cohort;
102 CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
103 this.cohort = Preconditions.checkNotNull(cohort);
108 public String toString() {
109 return "CommitEntry [tx=" + cohort.getIdentifier() + ", state=" + cohort.getState() + "]";
113 private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(Duration.create(5, TimeUnit.SECONDS));
114 private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
117 * Process this many transactions in a single batched run. If we exceed this limit, we need to schedule later
118 * execution to finish up the batch. This is necessary in case of a long list of transactions which progress
119 * immediately through their preCommit phase -- if that happens, their completion eats up stack frames and could
120 * result in StackOverflowError.
122 private static final int MAX_TRANSACTION_BATCH = 100;
124 private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
125 private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
126 private final Deque<CommitEntry> pendingTransactions = new ArrayDeque<>();
127 private final Queue<CommitEntry> pendingCommits = new ArrayDeque<>();
128 private final Queue<CommitEntry> pendingFinishCommits = new ArrayDeque<>();
131 * Callbacks that need to be invoked once a payload is replicated.
133 private final Map<Payload, Runnable> replicationCallbacks = new HashMap<>();
135 private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
136 private final Collection<ShardDataTreeMetadata<?>> metadata;
137 private final DataTree dataTree;
138 private final String logContext;
139 private final Shard shard;
140 private Runnable runOnPendingTransactionsComplete;
143 * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
144 * {@link DataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
145 * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
146 * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
148 private DataTreeTip tip;
150 private SchemaContext schemaContext;
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);
212 void resetTransactionBatch() {
213 currentTransactionBatch = 0;
217 * Take a snapshot of current state for later recovery.
219 * @return A state snapshot
221 @Nonnull ShardDataTreeSnapshot takeStateSnapshot() {
222 final NormalizedNode<?, ?> rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY).get();
223 final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
224 ImmutableMap.builder();
226 for (ShardDataTreeMetadata<?> m : metadata) {
227 final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
229 metaBuilder.put(meta.getType(), meta);
233 return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
236 private boolean anyPendingTransactions() {
237 return !pendingTransactions.isEmpty() || !pendingCommits.isEmpty() || !pendingFinishCommits.isEmpty();
240 private void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot,
241 final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
242 final Stopwatch elapsed = Stopwatch.createStarted();
244 if (anyPendingTransactions()) {
245 LOG.warn("{}: applying state snapshot with pending transactions", logContext);
248 final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
249 if (snapshot instanceof MetadataShardDataTreeSnapshot) {
250 snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
252 snapshotMeta = ImmutableMap.of();
255 for (ShardDataTreeMetadata<?> m : metadata) {
256 final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
264 final DataTreeModification mod = wrapper.apply(dataTree.takeSnapshot().newModification());
265 // delete everything first
266 mod.delete(YangInstanceIdentifier.EMPTY);
268 final java.util.Optional<NormalizedNode<?, ?>> maybeNode = snapshot.getRootNode();
269 if (maybeNode.isPresent()) {
270 // Add everything from the remote node back
271 mod.write(YangInstanceIdentifier.EMPTY, maybeNode.get());
275 final DataTreeModification unwrapped = unwrap(mod);
276 dataTree.validate(unwrapped);
277 DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
278 dataTree.commit(candidate);
279 notifyListeners(candidate);
281 LOG.debug("{}: state snapshot applied in {}", logContext, elapsed);
285 * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
286 * does not perform any pruning.
288 * @param snapshot Snapshot that needs to be applied
289 * @throws DataValidationFailedException when the snapshot fails to apply
291 void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
292 applySnapshot(snapshot, UnaryOperator.identity());
295 private PruningDataTreeModification wrapWithPruning(final DataTreeModification delegate) {
296 return new PruningDataTreeModification(delegate, dataTree, schemaContext);
299 private static DataTreeModification unwrap(final DataTreeModification modification) {
300 if (modification instanceof PruningDataTreeModification) {
301 return ((PruningDataTreeModification)modification).delegate();
307 * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
308 * pruning in an attempt to adjust the state to our current SchemaContext.
310 * @param snapshot Snapshot that needs to be applied
311 * @throws DataValidationFailedException when the snapshot fails to apply
313 void applyRecoverySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
314 applySnapshot(snapshot, this::wrapWithPruning);
317 @SuppressWarnings("checkstyle:IllegalCatch")
318 private void applyRecoveryCandidate(final DataTreeCandidate candidate) throws DataValidationFailedException {
319 final PruningDataTreeModification mod = wrapWithPruning(dataTree.takeSnapshot().newModification());
320 DataTreeCandidates.applyToModification(mod, candidate);
323 final DataTreeModification unwrapped = mod.delegate();
324 LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
327 dataTree.validate(unwrapped);
328 dataTree.commit(dataTree.prepare(unwrapped));
329 } catch (Exception e) {
330 File file = new File(System.getProperty("karaf.data", "."),
331 "failed-recovery-payload-" + logContext + ".out");
332 DataTreeModificationOutput.toFile(file, unwrapped);
333 throw new IllegalStateException(String.format(
334 "%s: Failed to apply recovery payload. Modification data was written to file %s",
335 logContext, file), e);
340 * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
341 * pruning in an attempt to adjust the state to our current SchemaContext.
343 * @param payload Payload
344 * @throws IOException when the snapshot fails to deserialize
345 * @throws DataValidationFailedException when the snapshot fails to apply
347 void applyRecoveryPayload(@Nonnull final Payload payload) throws IOException, DataValidationFailedException {
348 if (payload instanceof CommitTransactionPayload) {
349 final Entry<TransactionIdentifier, DataTreeCandidate> e =
350 ((CommitTransactionPayload) payload).getCandidate();
351 applyRecoveryCandidate(e.getValue());
352 allMetadataCommittedTransaction(e.getKey());
353 } else if (payload instanceof AbortTransactionPayload) {
354 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
355 } else if (payload instanceof PurgeTransactionPayload) {
356 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
357 } else if (payload instanceof CreateLocalHistoryPayload) {
358 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
359 } else if (payload instanceof CloseLocalHistoryPayload) {
360 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
361 } else if (payload instanceof PurgeLocalHistoryPayload) {
362 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
364 LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
368 private void applyReplicatedCandidate(final Identifier identifier, final DataTreeCandidate foreign)
369 throws DataValidationFailedException {
370 LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
372 final DataTreeModification mod = dataTree.takeSnapshot().newModification();
373 DataTreeCandidates.applyToModification(mod, foreign);
376 LOG.trace("{}: Applying foreign modification {}", logContext, mod);
377 dataTree.validate(mod);
378 final DataTreeCandidate candidate = dataTree.prepare(mod);
379 dataTree.commit(candidate);
381 notifyListeners(candidate);
385 * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
386 * SchemaContexts match and does not perform any pruning.
388 * @param identifier Payload identifier as returned from RaftActor
389 * @param payload Payload
390 * @throws IOException when the snapshot fails to deserialize
391 * @throws DataValidationFailedException when the snapshot fails to apply
393 void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
394 DataValidationFailedException {
396 * 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
397 * if we are the leader and it has originated with us.
399 * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
400 * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
401 * acting in that capacity anymore.
403 * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
404 * pre-Boron state -- which limits the number of options here.
406 if (payload instanceof CommitTransactionPayload) {
407 final TransactionIdentifier txId;
408 if (identifier == null) {
409 final Entry<TransactionIdentifier, DataTreeCandidate> e =
410 ((CommitTransactionPayload) payload).getCandidate();
412 applyReplicatedCandidate(txId, e.getValue());
414 Verify.verify(identifier instanceof TransactionIdentifier);
415 txId = (TransactionIdentifier) identifier;
416 payloadReplicationComplete(txId);
418 allMetadataCommittedTransaction(txId);
419 } else if (payload instanceof AbortTransactionPayload) {
420 if (identifier != null) {
421 payloadReplicationComplete((AbortTransactionPayload) payload);
423 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
424 } else if (payload instanceof PurgeTransactionPayload) {
425 if (identifier != null) {
426 payloadReplicationComplete((PurgeTransactionPayload) payload);
428 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
429 } else if (payload instanceof CloseLocalHistoryPayload) {
430 if (identifier != null) {
431 payloadReplicationComplete((CloseLocalHistoryPayload) payload);
433 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
434 } else if (payload instanceof CreateLocalHistoryPayload) {
435 if (identifier != null) {
436 payloadReplicationComplete((CreateLocalHistoryPayload)payload);
438 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
439 } else if (payload instanceof PurgeLocalHistoryPayload) {
440 if (identifier != null) {
441 payloadReplicationComplete((PurgeLocalHistoryPayload)payload);
443 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
445 LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
449 private void replicatePayload(final Identifier id, final Payload payload, @Nullable final Runnable callback) {
450 if (callback != null) {
451 replicationCallbacks.put(payload, callback);
453 shard.persistPayload(id, payload, true);
456 private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
457 final Runnable callback = replicationCallbacks.remove(payload);
458 if (callback != null) {
459 LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
462 LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
466 private void payloadReplicationComplete(final TransactionIdentifier txId) {
467 final CommitEntry current = pendingFinishCommits.peek();
468 if (current == null) {
469 LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
473 if (!current.cohort.getIdentifier().equals(txId)) {
474 LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
475 current.cohort.getIdentifier(), 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 @Nullable final Runnable callback) {
537 ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
539 chain = new ShardDataTreeTransactionChain(historyId, this);
540 transactionChains.put(historyId, chain);
541 replicatePayload(historyId, CreateLocalHistoryPayload.create(historyId), callback);
542 } else if (callback != null) {
549 ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
550 if (txId.getHistoryId().getHistoryId() == 0) {
551 return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
554 return ensureTransactionChain(txId.getHistoryId(), null).newReadOnlyTransaction(txId);
557 ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
558 if (txId.getHistoryId().getHistoryId() == 0) {
559 return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
563 return ensureTransactionChain(txId.getHistoryId(), null).newReadWriteTransaction(txId);
567 public void notifyListeners(final DataTreeCandidate candidate) {
568 treeChangeListenerPublisher.publishChanges(candidate);
572 * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
573 * replication callbacks.
575 void purgeLeaderState() {
576 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
580 transactionChains.clear();
581 replicationCallbacks.clear();
585 * Close a single transaction chain.
587 * @param id History identifier
588 * @param callback Callback to invoke upon completion, may be null
590 void closeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
591 final ShardDataTreeTransactionChain chain = transactionChains.get(id);
593 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
594 if (callback != null) {
601 replicatePayload(id, CloseLocalHistoryPayload.create(id), callback);
605 * Purge a single transaction chain.
607 * @param id History identifier
608 * @param callback Callback to invoke upon completion, may be null
610 void purgeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
611 final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
613 LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
614 if (callback != null) {
620 replicatePayload(id, PurgeLocalHistoryPayload.create(id), callback);
623 Optional<DataTreeCandidate> readCurrentData() {
624 final java.util.Optional<NormalizedNode<?, ?>> currentState =
625 dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY);
626 return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
627 YangInstanceIdentifier.EMPTY, currentState.get())) : Optional.<DataTreeCandidate>absent();
630 public void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
631 final Optional<DataTreeCandidate> initialState,
632 final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
633 treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
637 return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
641 void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
642 final TransactionIdentifier id = transaction.getIdentifier();
643 LOG.debug("{}: aborting transaction {}", logContext, id);
644 replicatePayload(id, AbortTransactionPayload.create(id), callback);
648 void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
649 // No-op for free-standing transactions
654 ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction,
655 final java.util.Optional<SortedSet<String>> participatingShardNames) {
656 final DataTreeModification snapshot = transaction.getSnapshot();
659 return createReadyCohort(transaction.getIdentifier(), snapshot, participatingShardNames);
662 void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
663 LOG.debug("{}: purging transaction {}", logContext, id);
664 replicatePayload(id, PurgeTransactionPayload.create(id), callback);
667 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
668 return Optional.fromJavaUtil(dataTree.takeSnapshot().readNode(path));
671 DataTreeSnapshot takeSnapshot() {
672 return dataTree.takeSnapshot();
676 public DataTreeModification newModification() {
677 return dataTree.takeSnapshot().newModification();
680 public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
681 Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
683 for (CommitEntry entry: pendingFinishCommits) {
684 ret.add(entry.cohort);
687 for (CommitEntry entry: pendingCommits) {
688 ret.add(entry.cohort);
691 for (CommitEntry entry: pendingTransactions) {
692 ret.add(entry.cohort);
695 pendingFinishCommits.clear();
696 pendingCommits.clear();
697 pendingTransactions.clear();
703 * Called some time after {@link #processNextPendingTransaction()} decides to stop processing.
705 void resumeNextPendingTransaction() {
706 LOG.debug("{}: attempting to resume transaction processing", logContext);
707 processNextPending();
710 @SuppressWarnings("checkstyle:IllegalCatch")
711 private void processNextPendingTransaction() {
712 ++currentTransactionBatch;
713 if (currentTransactionBatch > MAX_TRANSACTION_BATCH) {
714 LOG.debug("{}: Already processed {}, scheduling continuation", logContext, currentTransactionBatch);
715 shard.scheduleNextPendingTransaction();
719 processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
720 final SimpleShardDataTreeCohort cohort = entry.cohort;
721 final DataTreeModification modification = cohort.getDataTreeModification();
723 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
726 tip.validate(modification);
727 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
728 cohort.successfulCanCommit();
729 entry.lastAccess = readTime();
731 } catch (ConflictingModificationAppliedException e) {
732 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
734 cause = new OptimisticLockFailedException("Optimistic lock failed for path " + e.getPath(), e);
735 } catch (DataValidationFailedException e) {
736 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
739 // For debugging purposes, allow dumping of the modification. Coupled with the above
740 // precondition log, it should allow us to understand what went on.
741 LOG.debug("{}: Store Tx {}: modifications: {} tree: {}", cohort.getIdentifier(), modification,
743 cause = new TransactionCommitFailedException("Data did not pass validation for path " + e.getPath(), e);
744 } catch (Exception e) {
745 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
749 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
750 pendingTransactions.poll().cohort.failedCanCommit(cause);
754 private void processNextPending() {
755 processNextPendingCommit();
756 processNextPendingTransaction();
759 private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
760 final Consumer<CommitEntry> processor) {
761 while (!queue.isEmpty()) {
762 final CommitEntry entry = queue.peek();
763 final SimpleShardDataTreeCohort cohort = entry.cohort;
765 if (cohort.isFailed()) {
766 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
771 if (cohort.getState() == allowedState) {
772 processor.accept(entry);
778 maybeRunOperationOnPendingTransactionsComplete();
781 private void processNextPendingCommit() {
782 processNextPending(pendingCommits, State.COMMIT_PENDING,
783 entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
786 private boolean peekNextPendingCommit() {
787 final CommitEntry first = pendingCommits.peek();
788 return first != null && first.cohort.getState() == State.COMMIT_PENDING;
791 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
792 final CommitEntry head = pendingTransactions.peek();
794 LOG.warn("{}: No transactions enqueued while attempting to start canCommit on {}", logContext, cohort);
797 if (!cohort.equals(head.cohort)) {
798 // The tx isn't at the head of the queue so we can't start canCommit at this point. Here we check if this
799 // tx should be moved ahead of other tx's in the READY state in the pendingTransactions queue. If this tx
800 // has other participating shards, it could deadlock with other tx's accessing the same shards
801 // depending on the order the tx's are readied on each shard
802 // (see https://jira.opendaylight.org/browse/CONTROLLER-1836). Therefore, if the preceding participating
803 // shard names for a preceding pending tx, call it A, in the queue matches that of this tx, then this tx
804 // is allowed to be moved ahead of tx A in the queue so it is processed first to avoid potential deadlock
805 // if tx A is behind this tx in the pendingTransactions queue for a preceding shard. In other words, since
806 // canCommmit for this tx was requested before tx A, honor that request. If this tx is moved to the head of
807 // the queue as a result, then proceed with canCommit.
809 Collection<String> precedingShardNames = extractPrecedingShardNames(cohort.getParticipatingShardNames());
810 if (precedingShardNames.isEmpty()) {
811 LOG.debug("{}: Tx {} is scheduled for canCommit step", logContext, cohort.getIdentifier());
815 LOG.debug("{}: Evaluating tx {} for canCommit - preceding participating shard names {}",
816 logContext, cohort.getIdentifier(), precedingShardNames);
817 final Iterator<CommitEntry> iter = pendingTransactions.iterator();
819 int moveToIndex = -1;
820 while (iter.hasNext()) {
821 final CommitEntry entry = iter.next();
824 if (cohort.equals(entry.cohort)) {
825 if (moveToIndex < 0) {
826 LOG.debug("{}: Not moving tx {} - cannot proceed with canCommit",
827 logContext, cohort.getIdentifier());
831 LOG.debug("{}: Moving {} to index {} in the pendingTransactions queue",
832 logContext, cohort.getIdentifier(), moveToIndex);
834 insertEntry(pendingTransactions, entry, moveToIndex);
836 if (!cohort.equals(pendingTransactions.peek().cohort)) {
837 LOG.debug("{}: Tx {} is not at the head of the queue - cannot proceed with canCommit",
838 logContext, cohort.getIdentifier());
842 LOG.debug("{}: Tx {} is now at the head of the queue - proceeding with canCommit",
843 logContext, cohort.getIdentifier());
847 if (entry.cohort.getState() != State.READY) {
848 LOG.debug("{}: Skipping pending transaction {} in state {}",
849 logContext, entry.cohort.getIdentifier(), entry.cohort.getState());
853 final Collection<String> pendingPrecedingShardNames = extractPrecedingShardNames(
854 entry.cohort.getParticipatingShardNames());
856 if (precedingShardNames.equals(pendingPrecedingShardNames)) {
857 if (moveToIndex < 0) {
858 LOG.debug("{}: Preceding shard names {} for pending tx {} match - saving moveToIndex {}",
859 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), index);
863 "{}: Preceding shard names {} for pending tx {} match but moveToIndex already set to {}",
864 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), moveToIndex);
867 LOG.debug("{}: Preceding shard names {} for pending tx {} differ - skipping",
868 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier());
873 processNextPendingTransaction();
876 private void insertEntry(Deque<CommitEntry> queue, CommitEntry entry, int atIndex) {
878 queue.addFirst(entry);
882 LOG.trace("Inserting into Deque at index {}", atIndex);
884 Deque<CommitEntry> tempStack = new ArrayDeque<>(atIndex);
885 for (int i = 0; i < atIndex; i++) {
886 tempStack.push(queue.poll());
889 queue.addFirst(entry);
891 tempStack.forEach(queue::addFirst);
894 private Collection<String> extractPrecedingShardNames(
895 java.util.Optional<SortedSet<String>> participatingShardNames) {
896 return participatingShardNames.map((Function<SortedSet<String>, Collection<String>>)
897 set -> set.headSet(shard.getShardName())).orElse(Collections.<String>emptyList());
900 private void failPreCommit(final Throwable cause) {
901 shard.getShardMBean().incrementFailedTransactionsCount();
902 pendingTransactions.poll().cohort.failedPreCommit(cause);
903 processNextPendingTransaction();
906 @SuppressWarnings("checkstyle:IllegalCatch")
907 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
908 final CommitEntry entry = pendingTransactions.peek();
909 Preconditions.checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
911 final SimpleShardDataTreeCohort current = entry.cohort;
912 Verify.verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
914 LOG.debug("{}: Preparing transaction {}", logContext, current.getIdentifier());
916 final DataTreeCandidateTip candidate;
918 candidate = tip.prepare(cohort.getDataTreeModification());
919 } catch (RuntimeException e) {
924 cohort.userPreCommit(candidate, new FutureCallback<Void>() {
926 public void onSuccess(final Void noop) {
927 // Set the tip of the data tree.
928 tip = Verify.verifyNotNull(candidate);
930 entry.lastAccess = readTime();
932 pendingTransactions.remove();
933 pendingCommits.add(entry);
935 LOG.debug("{}: Transaction {} prepared", logContext, current.getIdentifier());
937 cohort.successfulPreCommit(candidate);
939 processNextPendingTransaction();
943 public void onFailure(final Throwable failure) {
944 failPreCommit(failure);
949 private void failCommit(final Exception cause) {
950 shard.getShardMBean().incrementFailedTransactionsCount();
951 pendingFinishCommits.poll().cohort.failedCommit(cause);
952 processNextPending();
955 @SuppressWarnings("checkstyle:IllegalCatch")
956 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
957 final TransactionIdentifier txId = cohort.getIdentifier();
958 final DataTreeCandidate candidate = cohort.getCandidate();
960 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
962 if (tip == candidate) {
963 // All pending candidates have been committed, reset the tip to the data tree.
968 dataTree.commit(candidate);
969 } catch (Exception e) {
970 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
975 shard.getShardMBean().incrementCommittedTransactionCount();
976 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
978 // FIXME: propagate journal index
979 pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO, () -> {
980 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
981 notifyListeners(candidate);
983 processNextPending();
987 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
988 final CommitEntry entry = pendingCommits.peek();
989 Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
991 final SimpleShardDataTreeCohort current = entry.cohort;
992 if (!cohort.equals(current)) {
993 LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
997 LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
999 final TransactionIdentifier txId = cohort.getIdentifier();
1000 final Payload payload;
1002 payload = CommitTransactionPayload.create(txId, candidate);
1003 } catch (IOException e) {
1004 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
1005 pendingCommits.poll().cohort.failedCommit(e);
1006 processNextPending();
1010 // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
1011 // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
1012 // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
1013 // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
1014 // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
1015 // pendingCommits queue.
1016 processNextPendingTransaction();
1018 // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
1019 // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
1020 // in order to properly determine the batchHint flag for the call to persistPayload.
1021 pendingCommits.remove();
1022 pendingFinishCommits.add(entry);
1024 // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
1025 // this transaction for replication.
1026 boolean replicationBatchHint = peekNextPendingCommit();
1028 // Once completed, we will continue via payloadReplicationComplete
1029 shard.persistPayload(txId, payload, replicationBatchHint);
1031 entry.lastAccess = shard.ticker().read();
1033 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
1035 // Process the next transaction pending commit, if any. If there is one it will be batched with this
1036 // transaction for replication.
1037 processNextPendingCommit();
1040 Collection<ActorRef> getCohortActors() {
1041 return cohortRegistry.getCohortActors();
1044 void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
1045 cohortRegistry.process(sender, message);
1049 ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1050 final Exception failure) {
1051 final SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId, failure);
1052 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1057 ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1058 final java.util.Optional<SortedSet<String>> participatingShardNames) {
1059 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId,
1060 cohortRegistry.createCohort(schemaContext, txId, runnable -> shard.executeInSelf(runnable),
1061 COMMIT_STEP_TIMEOUT), participatingShardNames);
1062 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1066 // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
1067 // the newReadWriteTransaction()
1068 ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1069 final java.util.Optional<SortedSet<String>> participatingShardNames) {
1070 if (txId.getHistoryId().getHistoryId() == 0) {
1071 return createReadyCohort(txId, mod, participatingShardNames);
1074 return ensureTransactionChain(txId.getHistoryId(), null).createReadyCohort(txId, mod, participatingShardNames);
1077 @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
1078 void checkForExpiredTransactions(final long transactionCommitTimeoutMillis,
1079 final Function<SimpleShardDataTreeCohort, Optional<Long>> accessTimeUpdater) {
1080 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
1081 final long now = readTime();
1083 final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
1084 !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
1085 final CommitEntry currentTx = currentQueue.peek();
1086 if (currentTx == null) {
1087 // Empty queue, no-op
1091 long delta = now - currentTx.lastAccess;
1092 if (delta < timeout) {
1093 // Not expired yet, bail
1097 final Optional<Long> updateOpt = accessTimeUpdater.apply(currentTx.cohort);
1098 if (updateOpt.isPresent()) {
1099 final long newAccess = updateOpt.get().longValue();
1100 final long newDelta = now - newAccess;
1101 if (newDelta < delta) {
1102 LOG.debug("{}: Updated current transaction {} access time", logContext,
1103 currentTx.cohort.getIdentifier());
1104 currentTx.lastAccess = newAccess;
1108 if (delta < timeout) {
1109 // Not expired yet, bail
1114 final long deltaMillis = TimeUnit.NANOSECONDS.toMillis(delta);
1115 final State state = currentTx.cohort.getState();
1117 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
1118 currentTx.cohort.getIdentifier(), deltaMillis, state);
1119 boolean processNext = true;
1120 final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
1121 + deltaMillis + "ms");
1124 case CAN_COMMIT_PENDING:
1125 currentQueue.remove().cohort.failedCanCommit(cohortFailure);
1127 case CAN_COMMIT_COMPLETE:
1128 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
1129 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
1130 // in PRE_COMMIT_COMPLETE is changed.
1131 currentQueue.remove().cohort.reportFailure(cohortFailure);
1133 case PRE_COMMIT_PENDING:
1134 currentQueue.remove().cohort.failedPreCommit(cohortFailure);
1136 case PRE_COMMIT_COMPLETE:
1137 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
1138 // are ready we should commit the transaction, not abort it. Our current software stack does
1139 // not allow us to do that consistently, because we persist at the time of commit, hence
1140 // we can end up in a state where we have pre-committed a transaction, then a leader failover
1141 // occurred ... the new leader does not see the pre-committed transaction and does not have
1142 // a running timer. To fix this we really need two persistence events.
1144 // The first one, done at pre-commit time will hold the transaction payload. When consensus
1145 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1146 // apply the state in this event.
1148 // The second one, done at commit (or abort) time holds only the transaction identifier and
1149 // signals to followers that the state should (or should not) be applied.
1151 // In order to make the pre-commit timer working across failovers, though, we need
1152 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1153 // restart the timer.
1154 currentQueue.remove().cohort.reportFailure(cohortFailure);
1156 case COMMIT_PENDING:
1157 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1158 currentTx.cohort.getIdentifier());
1159 currentTx.lastAccess = now;
1160 processNext = false;
1163 currentQueue.remove().cohort.reportFailure(cohortFailure);
1169 currentQueue.remove();
1173 processNextPending();
1177 boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1178 final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1179 pendingTransactions).iterator();
1180 if (!it.hasNext()) {
1181 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1185 // First entry is special, as it may already be committing
1186 final CommitEntry first = it.next();
1187 if (cohort.equals(first.cohort)) {
1188 if (cohort.getState() != State.COMMIT_PENDING) {
1189 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1190 cohort.getIdentifier());
1193 if (cohort.getCandidate() != null) {
1194 rebaseTransactions(it, dataTree);
1197 processNextPending();
1201 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1205 DataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
1206 while (it.hasNext()) {
1207 final CommitEntry e = it.next();
1208 if (cohort.equals(e.cohort)) {
1209 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1212 if (cohort.getCandidate() != null) {
1213 rebaseTransactions(it, newTip);
1218 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), newTip);
1222 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1226 @SuppressWarnings("checkstyle:IllegalCatch")
1227 private void rebaseTransactions(final Iterator<CommitEntry> iter, @Nonnull final DataTreeTip newTip) {
1228 tip = Preconditions.checkNotNull(newTip);
1229 while (iter.hasNext()) {
1230 final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1231 if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1232 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1235 tip.validate(cohort.getDataTreeModification());
1236 } catch (DataValidationFailedException | RuntimeException e) {
1237 LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1238 cohort.reportFailure(e);
1240 } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1241 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1244 tip.validate(cohort.getDataTreeModification());
1245 DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1247 cohort.setNewCandidate(candidate);
1249 } catch (RuntimeException | DataValidationFailedException e) {
1250 LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1251 cohort.reportFailure(e);
1257 void setRunOnPendingTransactionsComplete(final Runnable operation) {
1258 runOnPendingTransactionsComplete = operation;
1259 maybeRunOperationOnPendingTransactionsComplete();
1262 private void maybeRunOperationOnPendingTransactionsComplete() {
1263 if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1264 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1265 runOnPendingTransactionsComplete);
1267 runOnPendingTransactionsComplete.run();
1268 runOnPendingTransactionsComplete = null;
1272 ShardStats getStats() {
1273 return shard.getShardMBean();
1276 Iterator<SimpleShardDataTreeCohort> cohortIterator() {
1277 return Iterables.transform(Iterables.concat(pendingFinishCommits, pendingCommits, pendingTransactions),
1278 e -> e.cohort).iterator();
1281 void removeTransactionChain(final LocalHistoryIdentifier id) {
1282 if (transactionChains.remove(id) != null) {
1283 LOG.debug("{}: Removed transaction chain {}", logContext, id);