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.jmx.mbeans.shard.ShardStats;
55 import org.opendaylight.controller.cluster.datastore.node.utils.transformer.ReusableNormalizedNodePruner;
56 import org.opendaylight.controller.cluster.datastore.persisted.AbortTransactionPayload;
57 import org.opendaylight.controller.cluster.datastore.persisted.AbstractIdentifiablePayload;
58 import org.opendaylight.controller.cluster.datastore.persisted.CloseLocalHistoryPayload;
59 import org.opendaylight.controller.cluster.datastore.persisted.CommitTransactionPayload;
60 import org.opendaylight.controller.cluster.datastore.persisted.CreateLocalHistoryPayload;
61 import org.opendaylight.controller.cluster.datastore.persisted.DataTreeCandidateInputOutput.DataTreeCandidateWithVersion;
62 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
63 import org.opendaylight.controller.cluster.datastore.persisted.PayloadVersion;
64 import org.opendaylight.controller.cluster.datastore.persisted.PurgeLocalHistoryPayload;
65 import org.opendaylight.controller.cluster.datastore.persisted.PurgeTransactionPayload;
66 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
67 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshotMetadata;
68 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
69 import org.opendaylight.controller.cluster.datastore.persisted.SkipTransactionsPayload;
70 import org.opendaylight.controller.cluster.datastore.utils.DataTreeModificationOutput;
71 import org.opendaylight.controller.cluster.datastore.utils.ImmutableUnsignedLongSet;
72 import org.opendaylight.controller.cluster.datastore.utils.PruningDataTreeModification;
73 import org.opendaylight.controller.cluster.raft.base.messages.InitiateCaptureSnapshot;
74 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
75 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
76 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
77 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
78 import org.opendaylight.yangtools.concepts.Identifier;
79 import org.opendaylight.yangtools.concepts.ListenerRegistration;
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.api.schema.tree.ConflictingModificationAppliedException;
83 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
84 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
85 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
86 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
87 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
88 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
89 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
90 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeTip;
91 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
92 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
93 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
94 import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeStreamVersion;
95 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
96 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
97 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
98 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
99 import org.slf4j.Logger;
100 import org.slf4j.LoggerFactory;
101 import scala.concurrent.duration.FiniteDuration;
104 * Internal shard state, similar to a DOMStore, but optimized for use in the actor system, e.g. it does not expose
105 * public interfaces and assumes it is only ever called from a single thread.
108 * This class is not part of the API contract and is subject to change at any time. It is NOT thread-safe.
110 public class ShardDataTree extends ShardDataTreeTransactionParent {
111 private static final class CommitEntry {
112 final SimpleShardDataTreeCohort cohort;
115 CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
116 this.cohort = requireNonNull(cohort);
121 public String toString() {
122 return "CommitEntry [tx=" + cohort.getIdentifier() + ", state=" + cohort.getState() + "]";
126 private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(FiniteDuration.create(5, TimeUnit.SECONDS));
127 private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
130 * Process this many transactions in a single batched run. If we exceed this limit, we need to schedule later
131 * execution to finish up the batch. This is necessary in case of a long list of transactions which progress
132 * immediately through their preCommit phase -- if that happens, their completion eats up stack frames and could
133 * result in StackOverflowError.
135 private static final int MAX_TRANSACTION_BATCH = 100;
137 private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
138 private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
139 private final Deque<CommitEntry> pendingTransactions = new ArrayDeque<>();
140 private final Queue<CommitEntry> pendingCommits = new ArrayDeque<>();
141 private final Queue<CommitEntry> pendingFinishCommits = new ArrayDeque<>();
144 * Callbacks that need to be invoked once a payload is replicated.
146 private final Map<Payload, Runnable> replicationCallbacks = new HashMap<>();
148 private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
149 private final Collection<ShardDataTreeMetadata<?>> metadata;
150 private final DataTree dataTree;
151 private final String logContext;
152 private final Shard shard;
153 private Runnable runOnPendingTransactionsComplete;
156 * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
157 * {@link DataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
158 * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
159 * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
161 private DataTreeTip tip;
163 private SchemaContext schemaContext;
164 private DataSchemaContextTree dataSchemaContext;
166 private int currentTransactionBatch;
168 ShardDataTree(final Shard shard, final EffectiveModelContext schemaContext, final DataTree dataTree,
169 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
170 final String logContext,
171 final ShardDataTreeMetadata<?>... metadata) {
172 this.dataTree = requireNonNull(dataTree);
173 updateSchemaContext(schemaContext);
175 this.shard = requireNonNull(shard);
176 this.treeChangeListenerPublisher = requireNonNull(treeChangeListenerPublisher);
177 this.logContext = requireNonNull(logContext);
178 this.metadata = ImmutableList.copyOf(metadata);
182 ShardDataTree(final Shard shard, final EffectiveModelContext schemaContext, final TreeType treeType,
183 final YangInstanceIdentifier root,
184 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
185 final String logContext,
186 final ShardDataTreeMetadata<?>... metadata) {
187 this(shard, schemaContext, createDataTree(treeType, root), treeChangeListenerPublisher, logContext, metadata);
190 private static DataTree createDataTree(final TreeType treeType, final YangInstanceIdentifier root) {
191 final DataTreeConfiguration baseConfig = DataTreeConfiguration.getDefault(treeType);
192 return new InMemoryDataTreeFactory().create(new DataTreeConfiguration.Builder(baseConfig.getTreeType())
193 .setMandatoryNodesValidation(baseConfig.isMandatoryNodesValidationEnabled())
194 .setUniqueIndexes(baseConfig.isUniqueIndexEnabled())
200 public ShardDataTree(final Shard shard, final EffectiveModelContext schemaContext, final TreeType treeType) {
201 this(shard, schemaContext, treeType, YangInstanceIdentifier.empty(),
202 new DefaultShardDataTreeChangeListenerPublisher(""), "");
205 final String logContext() {
209 final long readTime() {
210 return shard.ticker().read();
213 public DataTree getDataTree() {
217 SchemaContext getSchemaContext() {
218 return schemaContext;
221 void updateSchemaContext(final @NonNull EffectiveModelContext newSchemaContext) {
222 dataTree.setEffectiveModelContext(newSchemaContext);
223 schemaContext = newSchemaContext;
224 dataSchemaContext = DataSchemaContextTree.from(newSchemaContext);
227 void resetTransactionBatch() {
228 currentTransactionBatch = 0;
232 * Take a snapshot of current state for later recovery.
234 * @return A state snapshot
236 @NonNull ShardDataTreeSnapshot takeStateSnapshot() {
237 final NormalizedNode<?, ?> rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.empty()).get();
238 final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
239 ImmutableMap.builder();
241 for (ShardDataTreeMetadata<?> m : metadata) {
242 final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
244 metaBuilder.put(meta.getType(), meta);
248 return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
251 private boolean anyPendingTransactions() {
252 return !pendingTransactions.isEmpty() || !pendingCommits.isEmpty() || !pendingFinishCommits.isEmpty();
255 private void applySnapshot(final @NonNull ShardDataTreeSnapshot snapshot,
256 final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
257 final Stopwatch elapsed = Stopwatch.createStarted();
259 if (anyPendingTransactions()) {
260 LOG.warn("{}: applying state snapshot with pending transactions", logContext);
263 final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
264 if (snapshot instanceof MetadataShardDataTreeSnapshot) {
265 snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
267 snapshotMeta = ImmutableMap.of();
270 for (ShardDataTreeMetadata<?> m : metadata) {
271 final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
279 final DataTreeModification unwrapped = dataTree.takeSnapshot().newModification();
280 final DataTreeModification mod = wrapper.apply(unwrapped);
281 // delete everything first
282 mod.delete(YangInstanceIdentifier.empty());
284 final Optional<NormalizedNode<?, ?>> maybeNode = snapshot.getRootNode();
285 if (maybeNode.isPresent()) {
286 // Add everything from the remote node back
287 mod.write(YangInstanceIdentifier.empty(), maybeNode.get());
291 dataTree.validate(unwrapped);
292 DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
293 dataTree.commit(candidate);
294 notifyListeners(candidate);
296 LOG.debug("{}: state snapshot applied in {}", logContext, elapsed);
300 * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
301 * does not perform any pruning.
303 * @param snapshot Snapshot that needs to be applied
304 * @throws DataValidationFailedException when the snapshot fails to apply
306 void applySnapshot(final @NonNull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
307 // TODO: we should be taking ShardSnapshotState here and performing forward-compatibility translation
308 applySnapshot(snapshot, UnaryOperator.identity());
312 * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
313 * pruning in an attempt to adjust the state to our current SchemaContext.
315 * @param snapshot Snapshot that needs to be applied
316 * @throws DataValidationFailedException when the snapshot fails to apply
318 void applyRecoverySnapshot(final @NonNull ShardSnapshotState snapshot) throws DataValidationFailedException {
319 // TODO: we should be able to reuse the pruner, provided we are not reentrant
320 final ReusableNormalizedNodePruner pruner = ReusableNormalizedNodePruner.forDataSchemaContext(
322 if (snapshot.needsMigration()) {
323 final ReusableNormalizedNodePruner uintPruner = pruner.withUintAdaption();
324 applySnapshot(snapshot.getSnapshot(),
325 delegate -> new PruningDataTreeModification.Proactive(delegate, dataTree, uintPruner));
327 applySnapshot(snapshot.getSnapshot(),
328 delegate -> new PruningDataTreeModification.Reactive(delegate, dataTree, pruner));
332 @SuppressWarnings("checkstyle:IllegalCatch")
333 private void applyRecoveryCandidate(final CommitTransactionPayload payload) throws IOException {
334 final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> entry = payload.acquireCandidate();
335 final DataTreeModification unwrapped = dataTree.takeSnapshot().newModification();
336 final PruningDataTreeModification mod = createPruningModification(unwrapped,
337 NormalizedNodeStreamVersion.MAGNESIUM.compareTo(entry.getValue().getVersion()) > 0);
339 DataTreeCandidates.applyToModification(mod, entry.getValue().getCandidate());
341 LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
344 dataTree.validate(unwrapped);
345 dataTree.commit(dataTree.prepare(unwrapped));
346 } catch (Exception e) {
347 File file = new File(System.getProperty("karaf.data", "."),
348 "failed-recovery-payload-" + logContext + ".out");
349 DataTreeModificationOutput.toFile(file, unwrapped);
350 throw new IllegalStateException(String.format(
351 "%s: Failed to apply recovery payload. Modification data was written to file %s",
352 logContext, file), e);
355 allMetadataCommittedTransaction(entry.getKey());
358 private PruningDataTreeModification createPruningModification(final DataTreeModification unwrapped,
359 final boolean uintAdapting) {
360 // TODO: we should be able to reuse the pruner, provided we are not reentrant
361 final ReusableNormalizedNodePruner pruner = ReusableNormalizedNodePruner.forDataSchemaContext(
363 return uintAdapting ? new PruningDataTreeModification.Proactive(unwrapped, dataTree, pruner.withUintAdaption())
364 : new PruningDataTreeModification.Reactive(unwrapped, dataTree, pruner);
368 * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
369 * pruning in an attempt to adjust the state to our current SchemaContext.
371 * @param payload Payload
372 * @throws IOException when the snapshot fails to deserialize
373 * @throws DataValidationFailedException when the snapshot fails to apply
375 void applyRecoveryPayload(final @NonNull Payload payload) throws IOException {
376 if (payload instanceof CommitTransactionPayload) {
377 applyRecoveryCandidate((CommitTransactionPayload) payload);
378 } else if (payload instanceof AbortTransactionPayload) {
379 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
380 } else if (payload instanceof PurgeTransactionPayload) {
381 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
382 } else if (payload instanceof CreateLocalHistoryPayload) {
383 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
384 } else if (payload instanceof CloseLocalHistoryPayload) {
385 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
386 } else if (payload instanceof PurgeLocalHistoryPayload) {
387 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
388 } else if (payload instanceof SkipTransactionsPayload) {
389 allMetadataSkipTransactions((SkipTransactionsPayload) payload);
391 LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
395 private void applyReplicatedCandidate(final CommitTransactionPayload payload)
396 throws DataValidationFailedException, IOException {
397 final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> entry = payload.acquireCandidate();
398 final TransactionIdentifier identifier = entry.getKey();
399 LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
401 final DataTreeModification mod = dataTree.takeSnapshot().newModification();
402 // TODO: check version here, which will enable us to perform forward-compatibility transformations
403 DataTreeCandidates.applyToModification(mod, entry.getValue().getCandidate());
406 LOG.trace("{}: Applying foreign modification {}", logContext, mod);
407 dataTree.validate(mod);
408 final DataTreeCandidate candidate = dataTree.prepare(mod);
409 dataTree.commit(candidate);
411 allMetadataCommittedTransaction(identifier);
412 notifyListeners(candidate);
416 * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
417 * SchemaContexts match and does not perform any pruning.
419 * @param identifier Payload identifier as returned from RaftActor
420 * @param payload Payload
421 * @throws IOException when the snapshot fails to deserialize
422 * @throws DataValidationFailedException when the snapshot fails to apply
424 void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
425 DataValidationFailedException {
427 * 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
428 * if we are the leader and it has originated with us.
430 * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
431 * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
432 * acting in that capacity anymore.
434 * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
435 * pre-Boron state -- which limits the number of options here.
437 if (payload instanceof CommitTransactionPayload) {
438 if (identifier == null) {
439 applyReplicatedCandidate((CommitTransactionPayload) payload);
441 verify(identifier instanceof TransactionIdentifier);
442 // if we did not track this transaction before, it means that it came from another leader and we are in
443 // the process of commiting it while in PreLeader state. That means that it hasnt yet been committed to
444 // the local DataTree and would be lost if it was only applied via payloadReplicationComplete().
445 if (!payloadReplicationComplete((TransactionIdentifier) identifier)) {
446 applyReplicatedCandidate((CommitTransactionPayload) payload);
450 // make sure acquireCandidate() is the last call touching the payload data as we want it to be GC-ed.
451 checkRootOverwrite(((CommitTransactionPayload) payload).acquireCandidate().getValue()
453 } else if (payload instanceof AbortTransactionPayload) {
454 if (identifier != null) {
455 payloadReplicationComplete((AbortTransactionPayload) payload);
457 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
458 } else if (payload instanceof PurgeTransactionPayload) {
459 if (identifier != null) {
460 payloadReplicationComplete((PurgeTransactionPayload) payload);
462 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
463 } else if (payload instanceof CloseLocalHistoryPayload) {
464 if (identifier != null) {
465 payloadReplicationComplete((CloseLocalHistoryPayload) payload);
467 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
468 } else if (payload instanceof CreateLocalHistoryPayload) {
469 if (identifier != null) {
470 payloadReplicationComplete((CreateLocalHistoryPayload)payload);
472 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
473 } else if (payload instanceof PurgeLocalHistoryPayload) {
474 if (identifier != null) {
475 payloadReplicationComplete((PurgeLocalHistoryPayload)payload);
477 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
478 } else if (payload instanceof SkipTransactionsPayload) {
479 if (identifier != null) {
480 payloadReplicationComplete((SkipTransactionsPayload)payload);
482 allMetadataSkipTransactions((SkipTransactionsPayload) payload);
484 LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
488 private void checkRootOverwrite(final DataTreeCandidate candidate) {
489 final DatastoreContext datastoreContext = shard.getDatastoreContext();
490 if (!datastoreContext.isSnapshotOnRootOverwrite()) {
494 if (!datastoreContext.isPersistent()) {
495 // FIXME: why don't we want a snapshot in non-persistent state?
499 // top level container ie "/"
500 if (candidate.getRootPath().isEmpty()
501 && candidate.getRootNode().getModificationType() == 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 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 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 ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
619 shard.getShardMBean().incrementReadOnlyTransactionCount();
621 if (txId.getHistoryId().getHistoryId() == 0) {
622 return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
625 return ensureTransactionChain(txId.getHistoryId(), null).newReadOnlyTransaction(txId);
628 ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
629 shard.getShardMBean().incrementReadWriteTransactionCount();
631 if (txId.getHistoryId().getHistoryId() == 0) {
632 return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
636 return ensureTransactionChain(txId.getHistoryId(), null).newReadWriteTransaction(txId);
640 public void notifyListeners(final DataTreeCandidate candidate) {
641 treeChangeListenerPublisher.publishChanges(candidate);
645 * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
646 * replication callbacks.
648 void purgeLeaderState() {
649 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
653 transactionChains.clear();
654 replicationCallbacks.clear();
658 * Close a single transaction chain.
660 * @param id History identifier
661 * @param callback Callback to invoke upon completion, may be null
663 void closeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
664 if (commonCloseTransactionChain(id, callback)) {
665 replicatePayload(id, CloseLocalHistoryPayload.create(id,
666 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
671 * Close a single transaction chain which is received through ask-based protocol. It does not keep a commit record.
673 * @param id History identifier
675 void closeTransactionChain(final LocalHistoryIdentifier id) {
676 commonCloseTransactionChain(id, null);
679 private boolean commonCloseTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
680 final ShardDataTreeTransactionChain chain = transactionChains.get(id);
682 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
683 if (callback != null) {
694 * Purge a single transaction chain.
696 * @param id History identifier
697 * @param callback Callback to invoke upon completion, may be null
699 void purgeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
700 final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
702 LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
703 if (callback != null) {
709 replicatePayload(id, PurgeLocalHistoryPayload.create(
710 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
713 final void skipTransactions(final LocalHistoryIdentifier id, final ImmutableUnsignedLongSet transactionIds,
714 final Runnable callback) {
715 final ShardDataTreeTransactionChain chain = transactionChains.get(id);
717 LOG.debug("{}: Skipping on non-existent transaction chain {}", logContext, id);
718 if (callback != null) {
724 replicatePayload(id, SkipTransactionsPayload.create(id, transactionIds,
725 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
728 final Optional<DataTreeCandidate> readCurrentData() {
729 return dataTree.takeSnapshot().readNode(YangInstanceIdentifier.empty())
730 .map(state -> DataTreeCandidates.fromNormalizedNode(YangInstanceIdentifier.empty(), state));
733 public void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
734 final Optional<DataTreeCandidate> initialState,
735 final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
736 treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
740 return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
744 void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
745 final TransactionIdentifier id = transaction.getIdentifier();
746 LOG.debug("{}: aborting transaction {}", logContext, id);
747 replicatePayload(id, AbortTransactionPayload.create(
748 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
752 void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
753 // No-op for free-standing transactions
758 ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction,
759 final Optional<SortedSet<String>> participatingShardNames) {
760 final DataTreeModification snapshot = transaction.getSnapshot();
761 final TransactionIdentifier id = transaction.getIdentifier();
762 LOG.debug("{}: readying transaction {}", logContext, id);
764 LOG.debug("{}: transaction {} ready", logContext, id);
766 return createReadyCohort(transaction.getIdentifier(), snapshot, participatingShardNames);
769 void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
770 LOG.debug("{}: purging transaction {}", logContext, id);
771 replicatePayload(id, PurgeTransactionPayload.create(
772 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
775 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
776 return dataTree.takeSnapshot().readNode(path);
779 DataTreeSnapshot takeSnapshot() {
780 return dataTree.takeSnapshot();
784 public DataTreeModification newModification() {
785 return dataTree.takeSnapshot().newModification();
788 public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
789 Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
791 for (CommitEntry entry: pendingFinishCommits) {
792 ret.add(entry.cohort);
795 for (CommitEntry entry: pendingCommits) {
796 ret.add(entry.cohort);
799 for (CommitEntry entry: pendingTransactions) {
800 ret.add(entry.cohort);
803 pendingFinishCommits.clear();
804 pendingCommits.clear();
805 pendingTransactions.clear();
811 * Called some time after {@link #processNextPendingTransaction()} decides to stop processing.
813 void resumeNextPendingTransaction() {
814 LOG.debug("{}: attempting to resume transaction processing", logContext);
815 processNextPending();
818 @SuppressWarnings("checkstyle:IllegalCatch")
819 private void processNextPendingTransaction() {
820 ++currentTransactionBatch;
821 if (currentTransactionBatch > MAX_TRANSACTION_BATCH) {
822 LOG.debug("{}: Already processed {}, scheduling continuation", logContext, currentTransactionBatch);
823 shard.scheduleNextPendingTransaction();
827 processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
828 final SimpleShardDataTreeCohort cohort = entry.cohort;
829 final DataTreeModification modification = cohort.getDataTreeModification();
831 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
834 tip.validate(modification);
835 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
836 cohort.successfulCanCommit();
837 entry.lastAccess = readTime();
839 } catch (ConflictingModificationAppliedException e) {
840 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
842 cause = new OptimisticLockFailedException("Optimistic lock failed for path " + e.getPath(), e);
843 } catch (DataValidationFailedException e) {
844 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
847 // For debugging purposes, allow dumping of the modification. Coupled with the above
848 // precondition log, it should allow us to understand what went on.
849 LOG.debug("{}: Store Tx {}: modifications: {}", logContext, cohort.getIdentifier(), modification);
850 LOG.trace("{}: Current tree: {}", logContext, dataTree);
851 cause = new TransactionCommitFailedException("Data did not pass validation for path " + e.getPath(), e);
852 } catch (Exception e) {
853 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
857 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
858 pendingTransactions.poll().cohort.failedCanCommit(cause);
862 private void processNextPending() {
863 processNextPendingCommit();
864 processNextPendingTransaction();
867 private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
868 final Consumer<CommitEntry> processor) {
869 while (!queue.isEmpty()) {
870 final CommitEntry entry = queue.peek();
871 final SimpleShardDataTreeCohort cohort = entry.cohort;
873 if (cohort.isFailed()) {
874 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
879 if (cohort.getState() == allowedState) {
880 processor.accept(entry);
886 maybeRunOperationOnPendingTransactionsComplete();
889 private void processNextPendingCommit() {
890 processNextPending(pendingCommits, State.COMMIT_PENDING,
891 entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
894 private boolean peekNextPendingCommit() {
895 final CommitEntry first = pendingCommits.peek();
896 return first != null && first.cohort.getState() == State.COMMIT_PENDING;
899 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
900 final CommitEntry head = pendingTransactions.peek();
902 LOG.warn("{}: No transactions enqueued while attempting to start canCommit on {}", logContext, cohort);
905 if (!cohort.equals(head.cohort)) {
906 // The tx isn't at the head of the queue so we can't start canCommit at this point. Here we check if this
907 // tx should be moved ahead of other tx's in the READY state in the pendingTransactions queue. If this tx
908 // has other participating shards, it could deadlock with other tx's accessing the same shards
909 // depending on the order the tx's are readied on each shard
910 // (see https://jira.opendaylight.org/browse/CONTROLLER-1836). Therefore, if the preceding participating
911 // shard names for a preceding pending tx, call it A, in the queue matches that of this tx, then this tx
912 // is allowed to be moved ahead of tx A in the queue so it is processed first to avoid potential deadlock
913 // if tx A is behind this tx in the pendingTransactions queue for a preceding shard. In other words, since
914 // canCommmit for this tx was requested before tx A, honor that request. If this tx is moved to the head of
915 // the queue as a result, then proceed with canCommit.
917 Collection<String> precedingShardNames = extractPrecedingShardNames(cohort.getParticipatingShardNames());
918 if (precedingShardNames.isEmpty()) {
919 LOG.debug("{}: Tx {} is scheduled for canCommit step", logContext, cohort.getIdentifier());
923 LOG.debug("{}: Evaluating tx {} for canCommit - preceding participating shard names {}",
924 logContext, cohort.getIdentifier(), precedingShardNames);
925 final Iterator<CommitEntry> iter = pendingTransactions.iterator();
927 int moveToIndex = -1;
928 while (iter.hasNext()) {
929 final CommitEntry entry = iter.next();
932 if (cohort.equals(entry.cohort)) {
933 if (moveToIndex < 0) {
934 LOG.debug("{}: Not moving tx {} - cannot proceed with canCommit",
935 logContext, cohort.getIdentifier());
939 LOG.debug("{}: Moving {} to index {} in the pendingTransactions queue",
940 logContext, cohort.getIdentifier(), moveToIndex);
942 insertEntry(pendingTransactions, entry, moveToIndex);
944 if (!cohort.equals(pendingTransactions.peek().cohort)) {
945 LOG.debug("{}: Tx {} is not at the head of the queue - cannot proceed with canCommit",
946 logContext, cohort.getIdentifier());
950 LOG.debug("{}: Tx {} is now at the head of the queue - proceeding with canCommit",
951 logContext, cohort.getIdentifier());
955 if (entry.cohort.getState() != State.READY) {
956 LOG.debug("{}: Skipping pending transaction {} in state {}",
957 logContext, entry.cohort.getIdentifier(), entry.cohort.getState());
961 final Collection<String> pendingPrecedingShardNames = extractPrecedingShardNames(
962 entry.cohort.getParticipatingShardNames());
964 if (precedingShardNames.equals(pendingPrecedingShardNames)) {
965 if (moveToIndex < 0) {
966 LOG.debug("{}: Preceding shard names {} for pending tx {} match - saving moveToIndex {}",
967 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), index);
971 "{}: Preceding shard names {} for pending tx {} match but moveToIndex already set to {}",
972 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), moveToIndex);
975 LOG.debug("{}: Preceding shard names {} for pending tx {} differ - skipping",
976 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier());
981 processNextPendingTransaction();
984 private static void insertEntry(final Deque<CommitEntry> queue, final CommitEntry entry, final int atIndex) {
986 queue.addFirst(entry);
990 LOG.trace("Inserting into Deque at index {}", atIndex);
992 Deque<CommitEntry> tempStack = new ArrayDeque<>(atIndex);
993 for (int i = 0; i < atIndex; i++) {
994 tempStack.push(queue.poll());
997 queue.addFirst(entry);
999 tempStack.forEach(queue::addFirst);
1002 private Collection<String> extractPrecedingShardNames(final Optional<SortedSet<String>> participatingShardNames) {
1003 return participatingShardNames.map((Function<SortedSet<String>, Collection<String>>)
1004 set -> set.headSet(shard.getShardName())).orElse(Collections.<String>emptyList());
1007 private void failPreCommit(final Throwable cause) {
1008 shard.getShardMBean().incrementFailedTransactionsCount();
1009 pendingTransactions.poll().cohort.failedPreCommit(cause);
1010 processNextPendingTransaction();
1013 @SuppressWarnings("checkstyle:IllegalCatch")
1014 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
1015 final CommitEntry entry = pendingTransactions.peek();
1016 checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
1018 final SimpleShardDataTreeCohort current = entry.cohort;
1019 verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
1021 final TransactionIdentifier currentId = current.getIdentifier();
1022 LOG.debug("{}: Preparing transaction {}", logContext, currentId);
1024 final DataTreeCandidateTip candidate;
1026 candidate = tip.prepare(cohort.getDataTreeModification());
1027 LOG.debug("{}: Transaction {} candidate ready", logContext, currentId);
1028 } catch (DataValidationFailedException | RuntimeException e) {
1033 cohort.userPreCommit(candidate, new FutureCallback<Void>() {
1035 public void onSuccess(final Void noop) {
1036 // Set the tip of the data tree.
1037 tip = verifyNotNull(candidate);
1039 entry.lastAccess = readTime();
1041 pendingTransactions.remove();
1042 pendingCommits.add(entry);
1044 LOG.debug("{}: Transaction {} prepared", logContext, currentId);
1046 cohort.successfulPreCommit(candidate);
1048 processNextPendingTransaction();
1052 public void onFailure(final Throwable failure) {
1053 failPreCommit(failure);
1058 private void failCommit(final Exception cause) {
1059 shard.getShardMBean().incrementFailedTransactionsCount();
1060 pendingFinishCommits.poll().cohort.failedCommit(cause);
1061 processNextPending();
1064 @SuppressWarnings("checkstyle:IllegalCatch")
1065 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
1066 final TransactionIdentifier txId = cohort.getIdentifier();
1067 final DataTreeCandidate candidate = cohort.getCandidate();
1069 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
1071 if (tip == candidate) {
1072 // All pending candidates have been committed, reset the tip to the data tree.
1077 dataTree.commit(candidate);
1078 } catch (Exception e) {
1079 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
1084 allMetadataCommittedTransaction(txId);
1085 shard.getShardMBean().incrementCommittedTransactionCount();
1086 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
1088 // FIXME: propagate journal index
1089 pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO, () -> {
1090 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
1091 notifyListeners(candidate);
1093 processNextPending();
1097 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
1098 final CommitEntry entry = pendingCommits.peek();
1099 checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
1101 final SimpleShardDataTreeCohort current = entry.cohort;
1102 if (!cohort.equals(current)) {
1103 LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
1107 LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
1109 final TransactionIdentifier txId = cohort.getIdentifier();
1110 final Payload payload;
1112 payload = CommitTransactionPayload.create(txId, candidate, PayloadVersion.current(),
1113 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity());
1114 } catch (IOException e) {
1115 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
1116 pendingCommits.poll().cohort.failedCommit(e);
1117 processNextPending();
1121 // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
1122 // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
1123 // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
1124 // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
1125 // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
1126 // pendingCommits queue.
1127 processNextPendingTransaction();
1129 // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
1130 // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
1131 // in order to properly determine the batchHint flag for the call to persistPayload.
1132 pendingCommits.remove();
1133 pendingFinishCommits.add(entry);
1135 // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
1136 // this transaction for replication.
1137 boolean replicationBatchHint = peekNextPendingCommit();
1139 // Once completed, we will continue via payloadReplicationComplete
1140 shard.persistPayload(txId, payload, replicationBatchHint);
1142 entry.lastAccess = shard.ticker().read();
1144 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
1146 // Process the next transaction pending commit, if any. If there is one it will be batched with this
1147 // transaction for replication.
1148 processNextPendingCommit();
1151 Collection<ActorRef> getCohortActors() {
1152 return cohortRegistry.getCohortActors();
1155 void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
1156 cohortRegistry.process(sender, message);
1160 ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1161 final Exception failure) {
1162 final SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId, failure);
1163 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1168 ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1169 final Optional<SortedSet<String>> participatingShardNames) {
1170 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId,
1171 cohortRegistry.createCohort(schemaContext, txId, shard::executeInSelf,
1172 COMMIT_STEP_TIMEOUT), participatingShardNames);
1173 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1177 // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
1178 // the newReadWriteTransaction()
1179 ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1180 final Optional<SortedSet<String>> participatingShardNames) {
1181 if (txId.getHistoryId().getHistoryId() == 0) {
1182 return createReadyCohort(txId, mod, participatingShardNames);
1185 return ensureTransactionChain(txId.getHistoryId(), null).createReadyCohort(txId, mod, participatingShardNames);
1188 @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
1189 void checkForExpiredTransactions(final long transactionCommitTimeoutMillis,
1190 final Function<SimpleShardDataTreeCohort, OptionalLong> accessTimeUpdater) {
1191 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
1192 final long now = readTime();
1194 final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
1195 !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
1196 final CommitEntry currentTx = currentQueue.peek();
1197 if (currentTx == null) {
1198 // Empty queue, no-op
1202 long delta = now - currentTx.lastAccess;
1203 if (delta < timeout) {
1204 // Not expired yet, bail
1208 final OptionalLong updateOpt = accessTimeUpdater.apply(currentTx.cohort);
1209 if (updateOpt.isPresent()) {
1210 final long newAccess = updateOpt.getAsLong();
1211 final long newDelta = now - newAccess;
1212 if (newDelta < delta) {
1213 LOG.debug("{}: Updated current transaction {} access time", logContext,
1214 currentTx.cohort.getIdentifier());
1215 currentTx.lastAccess = newAccess;
1219 if (delta < timeout) {
1220 // Not expired yet, bail
1225 final long deltaMillis = TimeUnit.NANOSECONDS.toMillis(delta);
1226 final State state = currentTx.cohort.getState();
1228 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
1229 currentTx.cohort.getIdentifier(), deltaMillis, state);
1230 boolean processNext = true;
1231 final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
1232 + deltaMillis + "ms");
1235 case CAN_COMMIT_PENDING:
1236 currentQueue.remove().cohort.failedCanCommit(cohortFailure);
1238 case CAN_COMMIT_COMPLETE:
1239 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
1240 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
1241 // in PRE_COMMIT_COMPLETE is changed.
1242 currentQueue.remove().cohort.reportFailure(cohortFailure);
1244 case PRE_COMMIT_PENDING:
1245 currentQueue.remove().cohort.failedPreCommit(cohortFailure);
1247 case PRE_COMMIT_COMPLETE:
1248 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
1249 // are ready we should commit the transaction, not abort it. Our current software stack does
1250 // not allow us to do that consistently, because we persist at the time of commit, hence
1251 // we can end up in a state where we have pre-committed a transaction, then a leader failover
1252 // occurred ... the new leader does not see the pre-committed transaction and does not have
1253 // a running timer. To fix this we really need two persistence events.
1255 // The first one, done at pre-commit time will hold the transaction payload. When consensus
1256 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1257 // apply the state in this event.
1259 // The second one, done at commit (or abort) time holds only the transaction identifier and
1260 // signals to followers that the state should (or should not) be applied.
1262 // In order to make the pre-commit timer working across failovers, though, we need
1263 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1264 // restart the timer.
1265 currentQueue.remove().cohort.reportFailure(cohortFailure);
1267 case COMMIT_PENDING:
1268 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1269 currentTx.cohort.getIdentifier());
1270 currentTx.lastAccess = now;
1271 processNext = false;
1274 currentQueue.remove().cohort.reportFailure(cohortFailure);
1280 currentQueue.remove();
1284 processNextPending();
1288 boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1289 final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1290 pendingTransactions).iterator();
1291 if (!it.hasNext()) {
1292 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1296 // First entry is special, as it may already be committing
1297 final CommitEntry first = it.next();
1298 if (cohort.equals(first.cohort)) {
1299 if (cohort.getState() != State.COMMIT_PENDING) {
1300 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1301 cohort.getIdentifier());
1304 if (cohort.getCandidate() != null) {
1305 rebaseTransactions(it, dataTree);
1308 processNextPending();
1312 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1316 DataTreeTip newTip = requireNonNullElse(first.cohort.getCandidate(), dataTree);
1317 while (it.hasNext()) {
1318 final CommitEntry e = it.next();
1319 if (cohort.equals(e.cohort)) {
1320 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1323 if (cohort.getCandidate() != null) {
1324 rebaseTransactions(it, newTip);
1329 newTip = requireNonNullElse(e.cohort.getCandidate(), newTip);
1333 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1337 @SuppressWarnings("checkstyle:IllegalCatch")
1338 private void rebaseTransactions(final Iterator<CommitEntry> iter, final @NonNull DataTreeTip newTip) {
1339 tip = requireNonNull(newTip);
1340 while (iter.hasNext()) {
1341 final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1342 if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1343 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1346 tip.validate(cohort.getDataTreeModification());
1347 } catch (DataValidationFailedException | RuntimeException e) {
1348 LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1349 cohort.reportFailure(e);
1351 } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1352 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1355 tip.validate(cohort.getDataTreeModification());
1356 DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1358 cohort.setNewCandidate(candidate);
1360 } catch (RuntimeException | DataValidationFailedException e) {
1361 LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1362 cohort.reportFailure(e);
1368 void setRunOnPendingTransactionsComplete(final Runnable operation) {
1369 runOnPendingTransactionsComplete = operation;
1370 maybeRunOperationOnPendingTransactionsComplete();
1373 private void maybeRunOperationOnPendingTransactionsComplete() {
1374 if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1375 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1376 runOnPendingTransactionsComplete);
1378 runOnPendingTransactionsComplete.run();
1379 runOnPendingTransactionsComplete = null;
1383 ShardStats getStats() {
1384 return shard.getShardMBean();
1387 Iterator<SimpleShardDataTreeCohort> cohortIterator() {
1388 return Iterables.transform(Iterables.concat(pendingFinishCommits, pendingCommits, pendingTransactions),
1389 e -> e.cohort).iterator();
1392 void removeTransactionChain(final LocalHistoryIdentifier id) {
1393 if (transactionChains.remove(id) != null) {
1394 LOG.debug("{}: Removed transaction chain {}", logContext, id);