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 static akka.actor.ActorRef.noSender;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verify;
13 import static com.google.common.base.Verify.verifyNotNull;
14 import static java.util.Objects.requireNonNull;
15 import static java.util.Objects.requireNonNullElse;
17 import akka.actor.ActorRef;
18 import akka.util.Timeout;
19 import com.google.common.annotations.VisibleForTesting;
20 import com.google.common.base.Stopwatch;
21 import com.google.common.collect.ImmutableList;
22 import com.google.common.collect.ImmutableMap;
23 import com.google.common.collect.ImmutableMap.Builder;
24 import com.google.common.collect.Iterables;
25 import com.google.common.primitives.UnsignedLong;
26 import com.google.common.util.concurrent.FutureCallback;
27 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
29 import java.io.IOException;
30 import java.util.ArrayDeque;
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.Collections;
34 import java.util.Deque;
35 import java.util.HashMap;
36 import java.util.Iterator;
38 import java.util.Map.Entry;
39 import java.util.Optional;
40 import java.util.OptionalLong;
41 import java.util.Queue;
42 import java.util.SortedSet;
43 import java.util.concurrent.TimeUnit;
44 import java.util.concurrent.TimeoutException;
45 import java.util.function.Consumer;
46 import java.util.function.Function;
47 import java.util.function.UnaryOperator;
48 import org.eclipse.jdt.annotation.NonNull;
49 import org.eclipse.jdt.annotation.Nullable;
50 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
51 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
52 import org.opendaylight.controller.cluster.datastore.DataTreeCohortActorRegistry.CohortRegistryCommand;
53 import org.opendaylight.controller.cluster.datastore.ShardDataTreeCohort.State;
54 import org.opendaylight.controller.cluster.datastore.node.utils.transformer.ReusableNormalizedNodePruner;
55 import org.opendaylight.controller.cluster.datastore.persisted.AbortTransactionPayload;
56 import org.opendaylight.controller.cluster.datastore.persisted.AbstractIdentifiablePayload;
57 import org.opendaylight.controller.cluster.datastore.persisted.CloseLocalHistoryPayload;
58 import org.opendaylight.controller.cluster.datastore.persisted.CommitTransactionPayload;
59 import org.opendaylight.controller.cluster.datastore.persisted.CreateLocalHistoryPayload;
60 import org.opendaylight.controller.cluster.datastore.persisted.DataTreeCandidateInputOutput.DataTreeCandidateWithVersion;
61 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
62 import org.opendaylight.controller.cluster.datastore.persisted.PayloadVersion;
63 import org.opendaylight.controller.cluster.datastore.persisted.PurgeLocalHistoryPayload;
64 import org.opendaylight.controller.cluster.datastore.persisted.PurgeTransactionPayload;
65 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
66 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshotMetadata;
67 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
68 import org.opendaylight.controller.cluster.datastore.persisted.SkipTransactionsPayload;
69 import org.opendaylight.controller.cluster.datastore.utils.DataTreeModificationOutput;
70 import org.opendaylight.controller.cluster.datastore.utils.ImmutableUnsignedLongSet;
71 import org.opendaylight.controller.cluster.datastore.utils.PruningDataTreeModification;
72 import org.opendaylight.controller.cluster.raft.base.messages.InitiateCaptureSnapshot;
73 import org.opendaylight.controller.cluster.raft.messages.Payload;
74 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
75 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
76 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
77 import org.opendaylight.yangtools.concepts.Identifier;
78 import org.opendaylight.yangtools.concepts.ListenerRegistration;
79 import org.opendaylight.yangtools.yang.common.Empty;
80 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
81 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
82 import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeStreamVersion;
83 import org.opendaylight.yangtools.yang.data.tree.api.ConflictingModificationAppliedException;
84 import org.opendaylight.yangtools.yang.data.tree.api.DataTree;
85 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
86 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidateTip;
87 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeConfiguration;
88 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeModification;
89 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeSnapshot;
90 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeTip;
91 import org.opendaylight.yangtools.yang.data.tree.api.DataValidationFailedException;
92 import org.opendaylight.yangtools.yang.data.tree.api.ModificationType;
93 import org.opendaylight.yangtools.yang.data.tree.api.TreeType;
94 import org.opendaylight.yangtools.yang.data.tree.impl.di.InMemoryDataTreeFactory;
95 import org.opendaylight.yangtools.yang.data.tree.spi.DataTreeCandidates;
96 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
97 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
98 import org.slf4j.Logger;
99 import org.slf4j.LoggerFactory;
100 import scala.concurrent.duration.FiniteDuration;
103 * Internal shard state, similar to a DOMStore, but optimized for use in the actor system, e.g. it does not expose
104 * public interfaces and assumes it is only ever called from a single thread.
107 * This class is not part of the API contract and is subject to change at any time. It is NOT thread-safe.
110 // non-final for mocking
111 public class ShardDataTree extends ShardDataTreeTransactionParent {
112 private static final class CommitEntry {
113 final SimpleShardDataTreeCohort cohort;
116 CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
117 this.cohort = requireNonNull(cohort);
122 public String toString() {
123 return "CommitEntry [tx=" + cohort.getIdentifier() + ", state=" + cohort.getState() + "]";
127 private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(FiniteDuration.create(5, TimeUnit.SECONDS));
128 private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
131 * Process this many transactions in a single batched run. If we exceed this limit, we need to schedule later
132 * execution to finish up the batch. This is necessary in case of a long list of transactions which progress
133 * immediately through their preCommit phase -- if that happens, their completion eats up stack frames and could
134 * result in StackOverflowError.
136 private static final int MAX_TRANSACTION_BATCH = 100;
138 private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
139 private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
140 private final Deque<CommitEntry> pendingTransactions = new ArrayDeque<>();
141 private final Queue<CommitEntry> pendingCommits = new ArrayDeque<>();
142 private final Queue<CommitEntry> pendingFinishCommits = new ArrayDeque<>();
145 * Callbacks that need to be invoked once a payload is replicated.
147 private final Map<Payload, Runnable> replicationCallbacks = new HashMap<>();
149 private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
150 private final Collection<ShardDataTreeMetadata<?>> metadata;
151 private final DataTree dataTree;
152 private final String logContext;
153 private final Shard shard;
154 private Runnable runOnPendingTransactionsComplete;
157 * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
158 * {@link DataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
159 * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
160 * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
162 private DataTreeTip tip;
164 private EffectiveModelContext schemaContext;
165 private DataSchemaContextTree dataSchemaContext;
167 private int currentTransactionBatch;
169 ShardDataTree(final Shard shard, final EffectiveModelContext schemaContext, final DataTree dataTree,
170 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
171 final String logContext,
172 final ShardDataTreeMetadata<?>... metadata) {
173 this.dataTree = requireNonNull(dataTree);
174 updateSchemaContext(schemaContext);
176 this.shard = requireNonNull(shard);
177 this.treeChangeListenerPublisher = requireNonNull(treeChangeListenerPublisher);
178 this.logContext = requireNonNull(logContext);
179 this.metadata = ImmutableList.copyOf(metadata);
183 ShardDataTree(final Shard shard, final EffectiveModelContext schemaContext, final TreeType treeType,
184 final YangInstanceIdentifier root,
185 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
186 final String logContext,
187 final ShardDataTreeMetadata<?>... metadata) {
188 this(shard, schemaContext, createDataTree(treeType, root), treeChangeListenerPublisher, logContext, metadata);
191 private static DataTree createDataTree(final TreeType treeType, final YangInstanceIdentifier root) {
192 final DataTreeConfiguration baseConfig = DataTreeConfiguration.getDefault(treeType);
193 return new InMemoryDataTreeFactory().create(new DataTreeConfiguration.Builder(baseConfig.getTreeType())
194 .setMandatoryNodesValidation(baseConfig.isMandatoryNodesValidationEnabled())
195 .setUniqueIndexes(baseConfig.isUniqueIndexEnabled())
201 public ShardDataTree(final Shard shard, final EffectiveModelContext schemaContext, final TreeType treeType) {
202 this(shard, schemaContext, treeType, YangInstanceIdentifier.of(),
203 new DefaultShardDataTreeChangeListenerPublisher(""), "");
206 final String logContext() {
210 final long readTime() {
211 return shard.ticker().read();
214 final DataTree getDataTree() {
219 final EffectiveModelContext getSchemaContext() {
220 return schemaContext;
223 final void updateSchemaContext(final @NonNull EffectiveModelContext newSchemaContext) {
224 dataTree.setEffectiveModelContext(newSchemaContext);
225 schemaContext = newSchemaContext;
226 dataSchemaContext = DataSchemaContextTree.from(newSchemaContext);
229 final void resetTransactionBatch() {
230 currentTransactionBatch = 0;
234 * Take a snapshot of current state for later recovery.
236 * @return A state snapshot
238 @NonNull ShardDataTreeSnapshot takeStateSnapshot() {
239 final NormalizedNode rootNode = takeSnapshot().readNode(YangInstanceIdentifier.of()).orElseThrow();
240 final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
241 ImmutableMap.builder();
243 for (ShardDataTreeMetadata<?> m : metadata) {
244 final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
246 metaBuilder.put(meta.getType(), meta);
250 return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
253 private boolean anyPendingTransactions() {
254 return !pendingTransactions.isEmpty() || !pendingCommits.isEmpty() || !pendingFinishCommits.isEmpty();
257 private void applySnapshot(final @NonNull ShardDataTreeSnapshot snapshot,
258 final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
259 final Stopwatch elapsed = Stopwatch.createStarted();
261 if (anyPendingTransactions()) {
262 LOG.warn("{}: applying state snapshot with pending transactions", logContext);
265 final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
266 if (snapshot instanceof MetadataShardDataTreeSnapshot metaSnapshot) {
267 snapshotMeta = metaSnapshot.getMetadata();
269 snapshotMeta = ImmutableMap.of();
272 for (var m : metadata) {
273 final var s = snapshotMeta.get(m.getSupportedType());
281 final DataTreeModification unwrapped = newModification();
282 final DataTreeModification mod = wrapper.apply(unwrapped);
283 // delete everything first
284 mod.delete(YangInstanceIdentifier.of());
286 snapshot.getRootNode().ifPresent(rootNode -> {
287 // Add everything from the remote node back
288 mod.write(YangInstanceIdentifier.of(), rootNode);
293 dataTree.validate(unwrapped);
294 DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
295 dataTree.commit(candidate);
296 notifyListeners(candidate);
298 LOG.debug("{}: state snapshot applied in {}", logContext, elapsed);
302 * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
303 * does not perform any pruning.
305 * @param snapshot Snapshot that needs to be applied
306 * @throws DataValidationFailedException when the snapshot fails to apply
308 final void applySnapshot(final @NonNull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
309 // TODO: we should be taking ShardSnapshotState here and performing forward-compatibility translation
310 applySnapshot(snapshot, UnaryOperator.identity());
314 * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
315 * pruning in an attempt to adjust the state to our current SchemaContext.
317 * @param snapshot Snapshot that needs to be applied
318 * @throws DataValidationFailedException when the snapshot fails to apply
320 final void applyRecoverySnapshot(final @NonNull ShardSnapshotState snapshot) throws DataValidationFailedException {
321 // TODO: we should be able to reuse the pruner, provided we are not reentrant
322 final ReusableNormalizedNodePruner pruner = ReusableNormalizedNodePruner.forDataSchemaContext(
324 if (snapshot.needsMigration()) {
325 final ReusableNormalizedNodePruner uintPruner = pruner.withUintAdaption();
326 applySnapshot(snapshot.getSnapshot(),
327 delegate -> new PruningDataTreeModification.Proactive(delegate, dataTree, uintPruner));
329 applySnapshot(snapshot.getSnapshot(),
330 delegate -> new PruningDataTreeModification.Reactive(delegate, dataTree, pruner));
334 @SuppressWarnings("checkstyle:IllegalCatch")
335 private void applyRecoveryCandidate(final CommitTransactionPayload payload) throws IOException {
336 final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> entry = payload.acquireCandidate();
337 final DataTreeModification unwrapped = newModification();
338 final PruningDataTreeModification mod = createPruningModification(unwrapped,
339 NormalizedNodeStreamVersion.MAGNESIUM.compareTo(entry.getValue().version()) > 0);
341 DataTreeCandidates.applyToModification(mod, entry.getValue().candidate());
343 LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
346 dataTree.validate(unwrapped);
347 dataTree.commit(dataTree.prepare(unwrapped));
348 } catch (Exception e) {
349 File file = new File(System.getProperty("karaf.data", "."),
350 "failed-recovery-payload-" + logContext + ".out");
351 DataTreeModificationOutput.toFile(file, unwrapped);
352 throw new IllegalStateException(String.format(
353 "%s: Failed to apply recovery payload. Modification data was written to file %s",
354 logContext, file), e);
357 allMetadataCommittedTransaction(entry.getKey());
360 private PruningDataTreeModification createPruningModification(final DataTreeModification unwrapped,
361 final boolean uintAdapting) {
362 // TODO: we should be able to reuse the pruner, provided we are not reentrant
363 final ReusableNormalizedNodePruner pruner = ReusableNormalizedNodePruner.forDataSchemaContext(
365 return uintAdapting ? new PruningDataTreeModification.Proactive(unwrapped, dataTree, pruner.withUintAdaption())
366 : new PruningDataTreeModification.Reactive(unwrapped, dataTree, pruner);
370 * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
371 * pruning in an attempt to adjust the state to our current SchemaContext.
373 * @param payload Payload
374 * @throws IOException when the snapshot fails to deserialize
375 * @throws DataValidationFailedException when the snapshot fails to apply
377 final void applyRecoveryPayload(final @NonNull Payload payload) throws IOException {
378 if (payload instanceof CommitTransactionPayload commit) {
379 applyRecoveryCandidate(commit);
380 } else if (payload instanceof AbortTransactionPayload abort) {
381 allMetadataAbortedTransaction(abort.getIdentifier());
382 } else if (payload instanceof PurgeTransactionPayload purge) {
383 allMetadataPurgedTransaction(purge.getIdentifier());
384 } else if (payload instanceof CreateLocalHistoryPayload create) {
385 allMetadataCreatedLocalHistory(create.getIdentifier());
386 } else if (payload instanceof CloseLocalHistoryPayload close) {
387 allMetadataClosedLocalHistory(close.getIdentifier());
388 } else if (payload instanceof PurgeLocalHistoryPayload purge) {
389 allMetadataPurgedLocalHistory(purge.getIdentifier());
390 } else if (payload instanceof SkipTransactionsPayload skip) {
391 allMetadataSkipTransactions(skip);
393 LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
397 private void applyReplicatedCandidate(final CommitTransactionPayload payload)
398 throws DataValidationFailedException, IOException {
399 final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> entry = payload.acquireCandidate();
400 final TransactionIdentifier identifier = entry.getKey();
401 LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
403 final DataTreeModification mod = newModification();
404 // TODO: check version here, which will enable us to perform forward-compatibility transformations
405 DataTreeCandidates.applyToModification(mod, entry.getValue().candidate());
408 LOG.trace("{}: Applying foreign modification {}", logContext, mod);
409 dataTree.validate(mod);
410 final DataTreeCandidate candidate = dataTree.prepare(mod);
411 dataTree.commit(candidate);
413 allMetadataCommittedTransaction(identifier);
414 notifyListeners(candidate);
418 * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
419 * SchemaContexts match and does not perform any pruning.
421 * @param identifier Payload identifier as returned from RaftActor
422 * @param payload Payload
423 * @throws IOException when the snapshot fails to deserialize
424 * @throws DataValidationFailedException when the snapshot fails to apply
426 final void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
427 DataValidationFailedException {
429 * 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
430 * if we are the leader and it has originated with us.
432 * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
433 * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
434 * acting in that capacity anymore.
436 * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
437 * pre-Boron state -- which limits the number of options here.
439 if (payload instanceof CommitTransactionPayload commit) {
440 if (identifier == null) {
441 applyReplicatedCandidate(commit);
443 verify(identifier instanceof TransactionIdentifier);
444 // if we did not track this transaction before, it means that it came from another leader and we are in
445 // the process of commiting it while in PreLeader state. That means that it hasnt yet been committed to
446 // the local DataTree and would be lost if it was only applied via payloadReplicationComplete().
447 if (!payloadReplicationComplete((TransactionIdentifier) identifier)) {
448 applyReplicatedCandidate(commit);
452 // make sure acquireCandidate() is the last call touching the payload data as we want it to be GC-ed.
453 checkRootOverwrite(((CommitTransactionPayload) payload).acquireCandidate().getValue().candidate());
454 } else if (payload instanceof AbortTransactionPayload abort) {
455 if (identifier != null) {
456 payloadReplicationComplete(abort);
458 allMetadataAbortedTransaction(abort.getIdentifier());
459 } else if (payload instanceof PurgeTransactionPayload purge) {
460 if (identifier != null) {
461 payloadReplicationComplete(purge);
463 allMetadataPurgedTransaction(purge.getIdentifier());
464 } else if (payload instanceof CloseLocalHistoryPayload close) {
465 if (identifier != null) {
466 payloadReplicationComplete(close);
468 allMetadataClosedLocalHistory(close.getIdentifier());
469 } else if (payload instanceof CreateLocalHistoryPayload create) {
470 if (identifier != null) {
471 payloadReplicationComplete(create);
473 allMetadataCreatedLocalHistory(create.getIdentifier());
474 } else if (payload instanceof PurgeLocalHistoryPayload purge) {
475 if (identifier != null) {
476 payloadReplicationComplete(purge);
478 allMetadataPurgedLocalHistory(purge.getIdentifier());
479 } else if (payload instanceof SkipTransactionsPayload skip) {
480 if (identifier != null) {
481 payloadReplicationComplete(skip);
483 allMetadataSkipTransactions(skip);
485 LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
489 private void checkRootOverwrite(final DataTreeCandidate candidate) {
490 final DatastoreContext datastoreContext = shard.getDatastoreContext();
491 if (!datastoreContext.isSnapshotOnRootOverwrite()) {
495 if (!datastoreContext.isPersistent()) {
496 // FIXME: why don't we want a snapshot in non-persistent state?
500 // top level container ie "/"
501 if (candidate.getRootPath().isEmpty() && candidate.getRootNode().modificationType() == ModificationType.WRITE) {
502 LOG.debug("{}: shard root overwritten, enqueuing snapshot", logContext);
503 shard.self().tell(new InitiateCaptureSnapshot(), noSender());
507 private void replicatePayload(final Identifier id, final Payload payload, final @Nullable Runnable callback) {
508 if (callback != null) {
509 replicationCallbacks.put(payload, callback);
511 shard.persistPayload(id, payload, true);
514 private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
515 final Runnable callback = replicationCallbacks.remove(payload);
516 if (callback != null) {
517 LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
520 LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
524 private boolean payloadReplicationComplete(final TransactionIdentifier txId) {
525 final CommitEntry current = pendingFinishCommits.peek();
526 if (current == null) {
527 LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
528 allMetadataCommittedTransaction(txId);
532 if (!current.cohort.getIdentifier().equals(txId)) {
533 LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
534 current.cohort.getIdentifier(), txId);
535 allMetadataCommittedTransaction(txId);
539 finishCommit(current.cohort);
543 private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
544 for (ShardDataTreeMetadata<?> m : metadata) {
545 m.onTransactionAborted(txId);
549 private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
550 for (ShardDataTreeMetadata<?> m : metadata) {
551 m.onTransactionCommitted(txId);
555 private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
556 for (ShardDataTreeMetadata<?> m : metadata) {
557 m.onTransactionPurged(txId);
561 private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
562 for (ShardDataTreeMetadata<?> m : metadata) {
563 m.onHistoryCreated(historyId);
567 private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
568 for (ShardDataTreeMetadata<?> m : metadata) {
569 m.onHistoryClosed(historyId);
573 private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
574 for (ShardDataTreeMetadata<?> m : metadata) {
575 m.onHistoryPurged(historyId);
579 private void allMetadataSkipTransactions(final SkipTransactionsPayload payload) {
580 final var historyId = payload.getIdentifier();
581 final var txIds = payload.getTransactionIds();
582 for (ShardDataTreeMetadata<?> m : metadata) {
583 m.onTransactionsSkipped(historyId, txIds);
588 * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
589 * this method is used for re-establishing state when we are taking over
591 * @param historyId Local history identifier
592 * @param closed True if the chain should be created in closed state (i.e. pending purge)
593 * @return Transaction chain handle
595 final ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
596 final boolean closed) {
597 final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
598 final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
599 checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId, existing);
603 final ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId,
604 final @Nullable Runnable callback) {
605 ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
607 chain = new ShardDataTreeTransactionChain(historyId, this);
608 transactionChains.put(historyId, chain);
609 replicatePayload(historyId, CreateLocalHistoryPayload.create(
610 historyId, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
611 } else if (callback != null) {
618 final @NonNull ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
619 shard.getShardMBean().incrementReadOnlyTransactionCount();
621 final var historyId = txId.getHistoryId();
622 return historyId.getHistoryId() == 0 ? newStandaloneReadOnlyTransaction(txId)
623 : ensureTransactionChain(historyId, null).newReadOnlyTransaction(txId);
626 final @NonNull ReadOnlyShardDataTreeTransaction newStandaloneReadOnlyTransaction(final TransactionIdentifier txId) {
627 return new ReadOnlyShardDataTreeTransaction(this, txId, takeSnapshot());
630 final @NonNull ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
631 shard.getShardMBean().incrementReadWriteTransactionCount();
633 final var historyId = txId.getHistoryId();
634 return historyId.getHistoryId() == 0 ? newStandaloneReadWriteTransaction(txId)
635 : ensureTransactionChain(historyId, null).newReadWriteTransaction(txId);
638 final @NonNull ReadWriteShardDataTreeTransaction newStandaloneReadWriteTransaction(
639 final TransactionIdentifier txId) {
640 return new ReadWriteShardDataTreeTransaction(this, txId, newModification());
644 final void notifyListeners(final DataTreeCandidate candidate) {
645 treeChangeListenerPublisher.publishChanges(candidate);
649 * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
650 * replication callbacks.
652 final void purgeLeaderState() {
653 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
657 transactionChains.clear();
658 replicationCallbacks.clear();
662 * Close a single transaction chain.
664 * @param id History identifier
665 * @param callback Callback to invoke upon completion, may be null
667 final void closeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
668 if (commonCloseTransactionChain(id, callback)) {
669 replicatePayload(id, CloseLocalHistoryPayload.create(id,
670 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
675 * Close a single transaction chain which is received through ask-based protocol. It does not keep a commit record.
677 * @param id History identifier
679 final void closeTransactionChain(final LocalHistoryIdentifier id) {
680 commonCloseTransactionChain(id, null);
683 private boolean commonCloseTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
684 final ShardDataTreeTransactionChain chain = transactionChains.get(id);
686 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
687 if (callback != null) {
698 * Purge a single transaction chain.
700 * @param id History identifier
701 * @param callback Callback to invoke upon completion, may be null
703 final void purgeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
704 final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
706 LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
707 if (callback != null) {
713 replicatePayload(id, PurgeLocalHistoryPayload.create(
714 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
717 final void skipTransactions(final LocalHistoryIdentifier id, final ImmutableUnsignedLongSet transactionIds,
718 final Runnable callback) {
719 final ShardDataTreeTransactionChain chain = transactionChains.get(id);
721 LOG.debug("{}: Skipping on non-existent transaction chain {}", logContext, id);
722 if (callback != null) {
728 replicatePayload(id, SkipTransactionsPayload.create(id, transactionIds,
729 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
732 final Optional<DataTreeCandidate> readCurrentData() {
733 return readNode(YangInstanceIdentifier.of())
734 .map(state -> DataTreeCandidates.fromNormalizedNode(YangInstanceIdentifier.of(), state));
737 final void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
738 final Optional<DataTreeCandidate> initialState,
739 final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
740 treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
743 final int getQueueSize() {
744 return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
748 final void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
749 final TransactionIdentifier id = transaction.getIdentifier();
750 LOG.debug("{}: aborting transaction {}", logContext, id);
751 replicatePayload(id, AbortTransactionPayload.create(
752 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
756 final void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
757 // No-op for free-standing transactions
761 final ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction,
762 final Optional<SortedSet<String>> participatingShardNames) {
763 final DataTreeModification snapshot = transaction.getSnapshot();
764 final TransactionIdentifier id = transaction.getIdentifier();
765 LOG.debug("{}: readying transaction {}", logContext, id);
767 LOG.debug("{}: transaction {} ready", logContext, id);
769 return createReadyCohort(transaction.getIdentifier(), snapshot, participatingShardNames);
772 final void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
773 LOG.debug("{}: purging transaction {}", logContext, id);
774 replicatePayload(id, PurgeTransactionPayload.create(
775 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
779 public final Optional<NormalizedNode> readNode(final YangInstanceIdentifier path) {
780 return takeSnapshot().readNode(path);
783 final DataTreeSnapshot takeSnapshot() {
784 return dataTree.takeSnapshot();
788 final DataTreeModification newModification() {
789 return takeSnapshot().newModification();
792 final Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
793 Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
795 for (CommitEntry entry: pendingFinishCommits) {
796 ret.add(entry.cohort);
799 for (CommitEntry entry: pendingCommits) {
800 ret.add(entry.cohort);
803 for (CommitEntry entry: pendingTransactions) {
804 ret.add(entry.cohort);
807 pendingFinishCommits.clear();
808 pendingCommits.clear();
809 pendingTransactions.clear();
815 * Called some time after {@link #processNextPendingTransaction()} decides to stop processing.
817 final void resumeNextPendingTransaction() {
818 LOG.debug("{}: attempting to resume transaction processing", logContext);
819 processNextPending();
822 @SuppressWarnings("checkstyle:IllegalCatch")
823 private void processNextPendingTransaction() {
824 ++currentTransactionBatch;
825 if (currentTransactionBatch > MAX_TRANSACTION_BATCH) {
826 LOG.debug("{}: Already processed {}, scheduling continuation", logContext, currentTransactionBatch);
827 shard.scheduleNextPendingTransaction();
831 processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
832 final SimpleShardDataTreeCohort cohort = entry.cohort;
833 final DataTreeModification modification = cohort.getDataTreeModification();
835 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
838 tip.validate(modification);
839 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
840 cohort.successfulCanCommit();
841 entry.lastAccess = readTime();
843 } catch (ConflictingModificationAppliedException e) {
844 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
846 cause = new OptimisticLockFailedException("Optimistic lock failed for path " + e.getPath(), e);
847 } catch (DataValidationFailedException e) {
848 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
851 // For debugging purposes, allow dumping of the modification. Coupled with the above
852 // precondition log, it should allow us to understand what went on.
853 LOG.debug("{}: Store Tx {}: modifications: {}", logContext, cohort.getIdentifier(), modification);
854 LOG.trace("{}: Current tree: {}", logContext, dataTree);
855 cause = new TransactionCommitFailedException("Data did not pass validation for path " + e.getPath(), e);
856 } catch (Exception e) {
857 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
861 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
862 pendingTransactions.poll().cohort.failedCanCommit(cause);
866 private void processNextPending() {
867 processNextPendingCommit();
868 processNextPendingTransaction();
871 private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
872 final Consumer<CommitEntry> processor) {
873 while (!queue.isEmpty()) {
874 final CommitEntry entry = queue.peek();
875 final SimpleShardDataTreeCohort cohort = entry.cohort;
877 if (cohort.isFailed()) {
878 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
883 if (cohort.getState() == allowedState) {
884 processor.accept(entry);
890 maybeRunOperationOnPendingTransactionsComplete();
893 private void processNextPendingCommit() {
894 processNextPending(pendingCommits, State.COMMIT_PENDING,
895 entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
898 private boolean peekNextPendingCommit() {
899 final CommitEntry first = pendingCommits.peek();
900 return first != null && first.cohort.getState() == State.COMMIT_PENDING;
903 // non-final for mocking
904 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
905 final CommitEntry head = pendingTransactions.peek();
907 LOG.warn("{}: No transactions enqueued while attempting to start canCommit on {}", logContext, cohort);
910 if (!cohort.equals(head.cohort)) {
911 // The tx isn't at the head of the queue so we can't start canCommit at this point. Here we check if this
912 // tx should be moved ahead of other tx's in the READY state in the pendingTransactions queue. If this tx
913 // has other participating shards, it could deadlock with other tx's accessing the same shards
914 // depending on the order the tx's are readied on each shard
915 // (see https://jira.opendaylight.org/browse/CONTROLLER-1836). Therefore, if the preceding participating
916 // shard names for a preceding pending tx, call it A, in the queue matches that of this tx, then this tx
917 // is allowed to be moved ahead of tx A in the queue so it is processed first to avoid potential deadlock
918 // if tx A is behind this tx in the pendingTransactions queue for a preceding shard. In other words, since
919 // canCommmit for this tx was requested before tx A, honor that request. If this tx is moved to the head of
920 // the queue as a result, then proceed with canCommit.
922 Collection<String> precedingShardNames = extractPrecedingShardNames(cohort.getParticipatingShardNames());
923 if (precedingShardNames.isEmpty()) {
924 LOG.debug("{}: Tx {} is scheduled for canCommit step", logContext, cohort.getIdentifier());
928 LOG.debug("{}: Evaluating tx {} for canCommit - preceding participating shard names {}",
929 logContext, cohort.getIdentifier(), precedingShardNames);
930 final Iterator<CommitEntry> iter = pendingTransactions.iterator();
932 int moveToIndex = -1;
933 while (iter.hasNext()) {
934 final CommitEntry entry = iter.next();
937 if (cohort.equals(entry.cohort)) {
938 if (moveToIndex < 0) {
939 LOG.debug("{}: Not moving tx {} - cannot proceed with canCommit",
940 logContext, cohort.getIdentifier());
944 LOG.debug("{}: Moving {} to index {} in the pendingTransactions queue",
945 logContext, cohort.getIdentifier(), moveToIndex);
947 insertEntry(pendingTransactions, entry, moveToIndex);
949 if (!cohort.equals(pendingTransactions.peek().cohort)) {
950 LOG.debug("{}: Tx {} is not at the head of the queue - cannot proceed with canCommit",
951 logContext, cohort.getIdentifier());
955 LOG.debug("{}: Tx {} is now at the head of the queue - proceeding with canCommit",
956 logContext, cohort.getIdentifier());
960 if (entry.cohort.getState() != State.READY) {
961 LOG.debug("{}: Skipping pending transaction {} in state {}",
962 logContext, entry.cohort.getIdentifier(), entry.cohort.getState());
966 final Collection<String> pendingPrecedingShardNames = extractPrecedingShardNames(
967 entry.cohort.getParticipatingShardNames());
969 if (precedingShardNames.equals(pendingPrecedingShardNames)) {
970 if (moveToIndex < 0) {
971 LOG.debug("{}: Preceding shard names {} for pending tx {} match - saving moveToIndex {}",
972 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), index);
976 "{}: Preceding shard names {} for pending tx {} match but moveToIndex already set to {}",
977 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), moveToIndex);
980 LOG.debug("{}: Preceding shard names {} for pending tx {} differ - skipping",
981 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier());
986 processNextPendingTransaction();
989 private static void insertEntry(final Deque<CommitEntry> queue, final CommitEntry entry, final int atIndex) {
991 queue.addFirst(entry);
995 LOG.trace("Inserting into Deque at index {}", atIndex);
997 Deque<CommitEntry> tempStack = new ArrayDeque<>(atIndex);
998 for (int i = 0; i < atIndex; i++) {
999 tempStack.push(queue.poll());
1002 queue.addFirst(entry);
1004 tempStack.forEach(queue::addFirst);
1007 private Collection<String> extractPrecedingShardNames(final Optional<SortedSet<String>> participatingShardNames) {
1008 return participatingShardNames.map((Function<SortedSet<String>, Collection<String>>)
1009 set -> set.headSet(shard.getShardName())).orElse(Collections.<String>emptyList());
1012 private void failPreCommit(final Throwable cause) {
1013 shard.getShardMBean().incrementFailedTransactionsCount();
1014 pendingTransactions.poll().cohort.failedPreCommit(cause);
1015 processNextPendingTransaction();
1018 // non-final for mocking
1019 @SuppressWarnings("checkstyle:IllegalCatch")
1020 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
1021 final CommitEntry entry = pendingTransactions.peek();
1022 checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
1024 final SimpleShardDataTreeCohort current = entry.cohort;
1025 verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
1027 final TransactionIdentifier currentId = current.getIdentifier();
1028 LOG.debug("{}: Preparing transaction {}", logContext, currentId);
1030 final DataTreeCandidateTip candidate;
1032 candidate = tip.prepare(cohort.getDataTreeModification());
1033 LOG.debug("{}: Transaction {} candidate ready", logContext, currentId);
1034 } catch (DataValidationFailedException | RuntimeException e) {
1039 cohort.userPreCommit(candidate, new FutureCallback<>() {
1041 public void onSuccess(final Empty result) {
1042 // Set the tip of the data tree.
1043 tip = verifyNotNull(candidate);
1045 entry.lastAccess = readTime();
1047 pendingTransactions.remove();
1048 pendingCommits.add(entry);
1050 LOG.debug("{}: Transaction {} prepared", logContext, currentId);
1052 cohort.successfulPreCommit(candidate);
1054 processNextPendingTransaction();
1058 public void onFailure(final Throwable failure) {
1059 failPreCommit(failure);
1064 private void failCommit(final Exception cause) {
1065 shard.getShardMBean().incrementFailedTransactionsCount();
1066 pendingFinishCommits.poll().cohort.failedCommit(cause);
1067 processNextPending();
1070 @SuppressWarnings("checkstyle:IllegalCatch")
1071 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
1072 final TransactionIdentifier txId = cohort.getIdentifier();
1073 final DataTreeCandidate candidate = cohort.getCandidate();
1075 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
1077 if (tip == candidate) {
1078 // All pending candidates have been committed, reset the tip to the data tree.
1083 dataTree.commit(candidate);
1084 } catch (Exception e) {
1085 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
1090 allMetadataCommittedTransaction(txId);
1091 shard.getShardMBean().incrementCommittedTransactionCount();
1092 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
1094 // FIXME: propagate journal index
1095 pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO, () -> {
1096 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
1097 notifyListeners(candidate);
1099 processNextPending();
1103 // non-final for mocking
1104 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
1105 final CommitEntry entry = pendingCommits.peek();
1106 checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
1108 final SimpleShardDataTreeCohort current = entry.cohort;
1109 if (!cohort.equals(current)) {
1110 LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
1114 LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
1116 final TransactionIdentifier txId = cohort.getIdentifier();
1117 final Payload payload;
1119 payload = CommitTransactionPayload.create(txId, candidate, PayloadVersion.current(),
1120 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity());
1121 } catch (IOException e) {
1122 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
1123 pendingCommits.poll().cohort.failedCommit(e);
1124 processNextPending();
1128 // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
1129 // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
1130 // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
1131 // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
1132 // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
1133 // pendingCommits queue.
1134 processNextPendingTransaction();
1136 // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
1137 // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
1138 // in order to properly determine the batchHint flag for the call to persistPayload.
1139 pendingCommits.remove();
1140 pendingFinishCommits.add(entry);
1142 // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
1143 // this transaction for replication.
1144 boolean replicationBatchHint = peekNextPendingCommit();
1146 // Once completed, we will continue via payloadReplicationComplete
1147 shard.persistPayload(txId, payload, replicationBatchHint);
1149 entry.lastAccess = shard.ticker().read();
1151 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
1153 // Process the next transaction pending commit, if any. If there is one it will be batched with this
1154 // transaction for replication.
1155 processNextPendingCommit();
1158 final Collection<ActorRef> getCohortActors() {
1159 return cohortRegistry.getCohortActors();
1162 final void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
1163 cohortRegistry.process(sender, message);
1167 final ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1168 final Exception failure) {
1169 final SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId, failure);
1170 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1175 final ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1176 final Optional<SortedSet<String>> participatingShardNames) {
1177 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId,
1178 cohortRegistry.createCohort(schemaContext, txId, shard::executeInSelf,
1179 COMMIT_STEP_TIMEOUT), participatingShardNames);
1180 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1184 // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
1185 // the newReadWriteTransaction()
1186 final ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1187 final Optional<SortedSet<String>> participatingShardNames) {
1188 final var historyId = txId.getHistoryId();
1189 if (historyId.getHistoryId() == 0) {
1190 return createReadyCohort(txId, mod, participatingShardNames);
1192 return ensureTransactionChain(historyId, null).createReadyCohort(txId, mod, participatingShardNames);
1195 @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
1196 final void checkForExpiredTransactions(final long transactionCommitTimeoutMillis,
1197 final Function<SimpleShardDataTreeCohort, OptionalLong> accessTimeUpdater) {
1198 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
1199 final long now = readTime();
1201 final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
1202 !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
1203 final CommitEntry currentTx = currentQueue.peek();
1204 if (currentTx == null) {
1205 // Empty queue, no-op
1209 long delta = now - currentTx.lastAccess;
1210 if (delta < timeout) {
1211 // Not expired yet, bail
1215 final OptionalLong updateOpt = accessTimeUpdater.apply(currentTx.cohort);
1216 if (updateOpt.isPresent()) {
1217 final long newAccess = updateOpt.orElseThrow();
1218 final long newDelta = now - newAccess;
1219 if (newDelta < delta) {
1220 LOG.debug("{}: Updated current transaction {} access time", logContext,
1221 currentTx.cohort.getIdentifier());
1222 currentTx.lastAccess = newAccess;
1226 if (delta < timeout) {
1227 // Not expired yet, bail
1232 final long deltaMillis = TimeUnit.NANOSECONDS.toMillis(delta);
1233 final State state = currentTx.cohort.getState();
1235 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
1236 currentTx.cohort.getIdentifier(), deltaMillis, state);
1237 boolean processNext = true;
1238 final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
1239 + deltaMillis + "ms");
1242 case CAN_COMMIT_PENDING:
1243 currentQueue.remove().cohort.failedCanCommit(cohortFailure);
1245 case CAN_COMMIT_COMPLETE:
1246 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
1247 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
1248 // in PRE_COMMIT_COMPLETE is changed.
1249 currentQueue.remove().cohort.reportFailure(cohortFailure);
1251 case PRE_COMMIT_PENDING:
1252 currentQueue.remove().cohort.failedPreCommit(cohortFailure);
1254 case PRE_COMMIT_COMPLETE:
1255 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
1256 // are ready we should commit the transaction, not abort it. Our current software stack does
1257 // not allow us to do that consistently, because we persist at the time of commit, hence
1258 // we can end up in a state where we have pre-committed a transaction, then a leader failover
1259 // occurred ... the new leader does not see the pre-committed transaction and does not have
1260 // a running timer. To fix this we really need two persistence events.
1262 // The first one, done at pre-commit time will hold the transaction payload. When consensus
1263 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1264 // apply the state in this event.
1266 // The second one, done at commit (or abort) time holds only the transaction identifier and
1267 // signals to followers that the state should (or should not) be applied.
1269 // In order to make the pre-commit timer working across failovers, though, we need
1270 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1271 // restart the timer.
1272 currentQueue.remove().cohort.reportFailure(cohortFailure);
1274 case COMMIT_PENDING:
1275 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1276 currentTx.cohort.getIdentifier());
1277 currentTx.lastAccess = now;
1278 processNext = false;
1281 currentQueue.remove().cohort.reportFailure(cohortFailure);
1287 currentQueue.remove();
1291 processNextPending();
1295 // non-final for mocking
1296 boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1297 final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1298 pendingTransactions).iterator();
1299 if (!it.hasNext()) {
1300 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1304 // First entry is special, as it may already be committing
1305 final CommitEntry first = it.next();
1306 if (cohort.equals(first.cohort)) {
1307 if (cohort.getState() != State.COMMIT_PENDING) {
1308 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1309 cohort.getIdentifier());
1312 if (cohort.getCandidate() != null) {
1313 rebaseTransactions(it, dataTree);
1316 processNextPending();
1320 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1324 DataTreeTip newTip = requireNonNullElse(first.cohort.getCandidate(), dataTree);
1325 while (it.hasNext()) {
1326 final CommitEntry e = it.next();
1327 if (cohort.equals(e.cohort)) {
1328 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1331 if (cohort.getCandidate() != null) {
1332 rebaseTransactions(it, newTip);
1338 newTip = requireNonNullElse(e.cohort.getCandidate(), newTip);
1341 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1345 @SuppressWarnings("checkstyle:IllegalCatch")
1346 private void rebaseTransactions(final Iterator<CommitEntry> iter, final @NonNull DataTreeTip newTip) {
1347 tip = requireNonNull(newTip);
1348 while (iter.hasNext()) {
1349 final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1350 if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1351 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1354 tip.validate(cohort.getDataTreeModification());
1355 } catch (DataValidationFailedException | RuntimeException e) {
1356 LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1357 cohort.reportFailure(e);
1359 } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1360 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1363 tip.validate(cohort.getDataTreeModification());
1364 DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1366 cohort.setNewCandidate(candidate);
1368 } catch (RuntimeException | DataValidationFailedException e) {
1369 LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1370 cohort.reportFailure(e);
1376 final void setRunOnPendingTransactionsComplete(final Runnable operation) {
1377 runOnPendingTransactionsComplete = operation;
1378 maybeRunOperationOnPendingTransactionsComplete();
1381 private void maybeRunOperationOnPendingTransactionsComplete() {
1382 if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1383 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1384 runOnPendingTransactionsComplete);
1386 runOnPendingTransactionsComplete.run();
1387 runOnPendingTransactionsComplete = null;
1391 final ShardStats getStats() {
1392 return shard.getShardMBean();
1395 final Iterator<SimpleShardDataTreeCohort> cohortIterator() {
1396 return Iterables.transform(Iterables.concat(pendingFinishCommits, pendingCommits, pendingTransactions),
1397 e -> e.cohort).iterator();
1400 final void removeTransactionChain(final LocalHistoryIdentifier id) {
1401 if (transactionChains.remove(id) != null) {
1402 LOG.debug("{}: Removed transaction chain {}", logContext, id);