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.utils.DataTreeModificationOutput;
70 import org.opendaylight.controller.cluster.datastore.utils.PruningDataTreeModification;
71 import org.opendaylight.controller.cluster.raft.base.messages.InitiateCaptureSnapshot;
72 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
73 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
74 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
75 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
76 import org.opendaylight.yangtools.concepts.Identifier;
77 import org.opendaylight.yangtools.concepts.ListenerRegistration;
78 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
79 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
80 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
81 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
82 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
83 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
84 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
85 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
86 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
87 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
88 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeTip;
89 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
90 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
91 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
92 import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeStreamVersion;
93 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
94 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
95 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
96 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
97 import org.slf4j.Logger;
98 import org.slf4j.LoggerFactory;
99 import scala.concurrent.duration.FiniteDuration;
102 * Internal shard state, similar to a DOMStore, but optimized for use in the actor system, e.g. it does not expose
103 * public interfaces and assumes it is only ever called from a single thread.
106 * This class is not part of the API contract and is subject to change at any time. It is NOT thread-safe.
108 public class ShardDataTree extends ShardDataTreeTransactionParent {
109 private static final class CommitEntry {
110 final SimpleShardDataTreeCohort cohort;
113 CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
114 this.cohort = requireNonNull(cohort);
119 public String toString() {
120 return "CommitEntry [tx=" + cohort.getIdentifier() + ", state=" + cohort.getState() + "]";
124 private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(FiniteDuration.create(5, TimeUnit.SECONDS));
125 private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
128 * Process this many transactions in a single batched run. If we exceed this limit, we need to schedule later
129 * execution to finish up the batch. This is necessary in case of a long list of transactions which progress
130 * immediately through their preCommit phase -- if that happens, their completion eats up stack frames and could
131 * result in StackOverflowError.
133 private static final int MAX_TRANSACTION_BATCH = 100;
135 private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
136 private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
137 private final Deque<CommitEntry> pendingTransactions = new ArrayDeque<>();
138 private final Queue<CommitEntry> pendingCommits = new ArrayDeque<>();
139 private final Queue<CommitEntry> pendingFinishCommits = new ArrayDeque<>();
142 * Callbacks that need to be invoked once a payload is replicated.
144 private final Map<Payload, Runnable> replicationCallbacks = new HashMap<>();
146 private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
147 private final Collection<ShardDataTreeMetadata<?>> metadata;
148 private final DataTree dataTree;
149 private final String logContext;
150 private final Shard shard;
151 private Runnable runOnPendingTransactionsComplete;
154 * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
155 * {@link DataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
156 * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
157 * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
159 private DataTreeTip tip;
161 private SchemaContext schemaContext;
162 private DataSchemaContextTree dataSchemaContext;
164 private int currentTransactionBatch;
166 ShardDataTree(final Shard shard, final EffectiveModelContext schemaContext, final DataTree dataTree,
167 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
168 final String logContext,
169 final ShardDataTreeMetadata<?>... metadata) {
170 this.dataTree = requireNonNull(dataTree);
171 updateSchemaContext(schemaContext);
173 this.shard = requireNonNull(shard);
174 this.treeChangeListenerPublisher = requireNonNull(treeChangeListenerPublisher);
175 this.logContext = requireNonNull(logContext);
176 this.metadata = ImmutableList.copyOf(metadata);
180 ShardDataTree(final Shard shard, final EffectiveModelContext schemaContext, final TreeType treeType,
181 final YangInstanceIdentifier root,
182 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
183 final String logContext,
184 final ShardDataTreeMetadata<?>... metadata) {
185 this(shard, schemaContext, createDataTree(treeType, root), treeChangeListenerPublisher, logContext, metadata);
188 private static DataTree createDataTree(final TreeType treeType, final YangInstanceIdentifier root) {
189 final DataTreeConfiguration baseConfig = DataTreeConfiguration.getDefault(treeType);
190 return new InMemoryDataTreeFactory().create(new DataTreeConfiguration.Builder(baseConfig.getTreeType())
191 .setMandatoryNodesValidation(baseConfig.isMandatoryNodesValidationEnabled())
192 .setUniqueIndexes(baseConfig.isUniqueIndexEnabled())
198 public ShardDataTree(final Shard shard, final EffectiveModelContext schemaContext, final TreeType treeType) {
199 this(shard, schemaContext, treeType, YangInstanceIdentifier.empty(),
200 new DefaultShardDataTreeChangeListenerPublisher(""), "");
203 final String logContext() {
207 final long readTime() {
208 return shard.ticker().read();
211 public DataTree getDataTree() {
215 SchemaContext getSchemaContext() {
216 return schemaContext;
219 void updateSchemaContext(final @NonNull EffectiveModelContext newSchemaContext) {
220 dataTree.setEffectiveModelContext(newSchemaContext);
221 this.schemaContext = newSchemaContext;
222 this.dataSchemaContext = DataSchemaContextTree.from(newSchemaContext);
225 void resetTransactionBatch() {
226 currentTransactionBatch = 0;
230 * Take a snapshot of current state for later recovery.
232 * @return A state snapshot
234 @NonNull ShardDataTreeSnapshot takeStateSnapshot() {
235 final NormalizedNode<?, ?> rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.empty()).get();
236 final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
237 ImmutableMap.builder();
239 for (ShardDataTreeMetadata<?> m : metadata) {
240 final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
242 metaBuilder.put(meta.getType(), meta);
246 return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
249 private boolean anyPendingTransactions() {
250 return !pendingTransactions.isEmpty() || !pendingCommits.isEmpty() || !pendingFinishCommits.isEmpty();
253 private void applySnapshot(final @NonNull ShardDataTreeSnapshot snapshot,
254 final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
255 final Stopwatch elapsed = Stopwatch.createStarted();
257 if (anyPendingTransactions()) {
258 LOG.warn("{}: applying state snapshot with pending transactions", logContext);
261 final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
262 if (snapshot instanceof MetadataShardDataTreeSnapshot) {
263 snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
265 snapshotMeta = ImmutableMap.of();
268 for (ShardDataTreeMetadata<?> m : metadata) {
269 final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
277 final DataTreeModification unwrapped = dataTree.takeSnapshot().newModification();
278 final DataTreeModification mod = wrapper.apply(unwrapped);
279 // delete everything first
280 mod.delete(YangInstanceIdentifier.empty());
282 final Optional<NormalizedNode<?, ?>> maybeNode = snapshot.getRootNode();
283 if (maybeNode.isPresent()) {
284 // Add everything from the remote node back
285 mod.write(YangInstanceIdentifier.empty(), maybeNode.get());
289 dataTree.validate(unwrapped);
290 DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
291 dataTree.commit(candidate);
292 notifyListeners(candidate);
294 LOG.debug("{}: state snapshot applied in {}", logContext, elapsed);
298 * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
299 * does not perform any pruning.
301 * @param snapshot Snapshot that needs to be applied
302 * @throws DataValidationFailedException when the snapshot fails to apply
304 void applySnapshot(final @NonNull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
305 // TODO: we should be taking ShardSnapshotState here and performing forward-compatibility translation
306 applySnapshot(snapshot, UnaryOperator.identity());
310 * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
311 * pruning in an attempt to adjust the state to our current SchemaContext.
313 * @param snapshot Snapshot that needs to be applied
314 * @throws DataValidationFailedException when the snapshot fails to apply
316 void applyRecoverySnapshot(final @NonNull ShardSnapshotState snapshot) throws DataValidationFailedException {
317 // TODO: we should be able to reuse the pruner, provided we are not reentrant
318 final ReusableNormalizedNodePruner pruner = ReusableNormalizedNodePruner.forDataSchemaContext(
320 if (snapshot.needsMigration()) {
321 final ReusableNormalizedNodePruner uintPruner = pruner.withUintAdaption();
322 applySnapshot(snapshot.getSnapshot(),
323 delegate -> new PruningDataTreeModification.Proactive(delegate, dataTree, uintPruner));
325 applySnapshot(snapshot.getSnapshot(),
326 delegate -> new PruningDataTreeModification.Reactive(delegate, dataTree, pruner));
330 @SuppressWarnings("checkstyle:IllegalCatch")
331 private void applyRecoveryCandidate(final CommitTransactionPayload payload) throws IOException {
332 final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> entry = payload.acquireCandidate();
333 final DataTreeModification unwrapped = dataTree.takeSnapshot().newModification();
334 final PruningDataTreeModification mod = createPruningModification(unwrapped,
335 NormalizedNodeStreamVersion.MAGNESIUM.compareTo(entry.getValue().getVersion()) > 0);
337 DataTreeCandidates.applyToModification(mod, entry.getValue().getCandidate());
339 LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
342 dataTree.validate(unwrapped);
343 dataTree.commit(dataTree.prepare(unwrapped));
344 } catch (Exception e) {
345 File file = new File(System.getProperty("karaf.data", "."),
346 "failed-recovery-payload-" + logContext + ".out");
347 DataTreeModificationOutput.toFile(file, unwrapped);
348 throw new IllegalStateException(String.format(
349 "%s: Failed to apply recovery payload. Modification data was written to file %s",
350 logContext, file), e);
353 allMetadataCommittedTransaction(entry.getKey());
356 private PruningDataTreeModification createPruningModification(final DataTreeModification unwrapped,
357 final boolean uintAdapting) {
358 // TODO: we should be able to reuse the pruner, provided we are not reentrant
359 final ReusableNormalizedNodePruner pruner = ReusableNormalizedNodePruner.forDataSchemaContext(
361 return uintAdapting ? new PruningDataTreeModification.Proactive(unwrapped, dataTree, pruner.withUintAdaption())
362 : new PruningDataTreeModification.Reactive(unwrapped, dataTree, pruner);
366 * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
367 * pruning in an attempt to adjust the state to our current SchemaContext.
369 * @param payload Payload
370 * @throws IOException when the snapshot fails to deserialize
371 * @throws DataValidationFailedException when the snapshot fails to apply
373 void applyRecoveryPayload(final @NonNull Payload payload) throws IOException {
374 if (payload instanceof CommitTransactionPayload) {
375 applyRecoveryCandidate((CommitTransactionPayload) payload);
376 } else if (payload instanceof AbortTransactionPayload) {
377 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
378 } else if (payload instanceof PurgeTransactionPayload) {
379 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
380 } else if (payload instanceof CreateLocalHistoryPayload) {
381 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
382 } else if (payload instanceof CloseLocalHistoryPayload) {
383 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
384 } else if (payload instanceof PurgeLocalHistoryPayload) {
385 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
387 LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
391 private void applyReplicatedCandidate(final CommitTransactionPayload payload)
392 throws DataValidationFailedException, IOException {
393 final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> entry = payload.acquireCandidate();
394 final TransactionIdentifier identifier = entry.getKey();
395 LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
397 final DataTreeModification mod = dataTree.takeSnapshot().newModification();
398 // TODO: check version here, which will enable us to perform forward-compatibility transformations
399 DataTreeCandidates.applyToModification(mod, entry.getValue().getCandidate());
402 LOG.trace("{}: Applying foreign modification {}", logContext, mod);
403 dataTree.validate(mod);
404 final DataTreeCandidate candidate = dataTree.prepare(mod);
405 dataTree.commit(candidate);
407 allMetadataCommittedTransaction(identifier);
408 notifyListeners(candidate);
412 * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
413 * SchemaContexts match and does not perform any pruning.
415 * @param identifier Payload identifier as returned from RaftActor
416 * @param payload Payload
417 * @throws IOException when the snapshot fails to deserialize
418 * @throws DataValidationFailedException when the snapshot fails to apply
420 void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
421 DataValidationFailedException {
423 * 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
424 * if we are the leader and it has originated with us.
426 * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
427 * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
428 * acting in that capacity anymore.
430 * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
431 * pre-Boron state -- which limits the number of options here.
433 if (payload instanceof CommitTransactionPayload) {
434 if (identifier == null) {
435 applyReplicatedCandidate((CommitTransactionPayload) payload);
437 verify(identifier instanceof TransactionIdentifier);
438 // if we did not track this transaction before, it means that it came from another leader and we are in
439 // the process of commiting it while in PreLeader state. That means that it hasnt yet been committed to
440 // the local DataTree and would be lost if it was only applied via payloadReplicationComplete().
441 if (!payloadReplicationComplete((TransactionIdentifier) identifier)) {
442 applyReplicatedCandidate((CommitTransactionPayload) payload);
446 // make sure acquireCandidate() is the last call touching the payload data as we want it to be GC-ed.
447 checkRootOverwrite(((CommitTransactionPayload) payload).acquireCandidate().getValue()
449 } else if (payload instanceof AbortTransactionPayload) {
450 if (identifier != null) {
451 payloadReplicationComplete((AbortTransactionPayload) payload);
453 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
454 } else if (payload instanceof PurgeTransactionPayload) {
455 if (identifier != null) {
456 payloadReplicationComplete((PurgeTransactionPayload) payload);
458 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
459 } else if (payload instanceof CloseLocalHistoryPayload) {
460 if (identifier != null) {
461 payloadReplicationComplete((CloseLocalHistoryPayload) payload);
463 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
464 } else if (payload instanceof CreateLocalHistoryPayload) {
465 if (identifier != null) {
466 payloadReplicationComplete((CreateLocalHistoryPayload)payload);
468 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
469 } else if (payload instanceof PurgeLocalHistoryPayload) {
470 if (identifier != null) {
471 payloadReplicationComplete((PurgeLocalHistoryPayload)payload);
473 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
475 LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
479 private void checkRootOverwrite(final DataTreeCandidate candidate) {
480 final DatastoreContext datastoreContext = shard.getDatastoreContext();
481 if (!datastoreContext.isSnapshotOnRootOverwrite()) {
485 if (!datastoreContext.isPersistent()) {
486 // FIXME: why don't we want a snapshot in non-persistent state?
490 // top level container ie "/"
491 if (candidate.getRootPath().isEmpty()
492 && candidate.getRootNode().getModificationType() == ModificationType.WRITE) {
493 LOG.debug("{}: shard root overwritten, enqueuing snapshot", logContext);
494 shard.self().tell(new InitiateCaptureSnapshot(), noSender());
498 private void replicatePayload(final Identifier id, final Payload payload, final @Nullable Runnable callback) {
499 if (callback != null) {
500 replicationCallbacks.put(payload, callback);
502 shard.persistPayload(id, payload, true);
505 private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
506 final Runnable callback = replicationCallbacks.remove(payload);
507 if (callback != null) {
508 LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
511 LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
515 private boolean payloadReplicationComplete(final TransactionIdentifier txId) {
516 final CommitEntry current = pendingFinishCommits.peek();
517 if (current == null) {
518 LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
519 allMetadataCommittedTransaction(txId);
523 if (!current.cohort.getIdentifier().equals(txId)) {
524 LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
525 current.cohort.getIdentifier(), txId);
526 allMetadataCommittedTransaction(txId);
530 finishCommit(current.cohort);
534 private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
535 for (ShardDataTreeMetadata<?> m : metadata) {
536 m.onTransactionAborted(txId);
540 private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
541 for (ShardDataTreeMetadata<?> m : metadata) {
542 m.onTransactionCommitted(txId);
546 private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
547 for (ShardDataTreeMetadata<?> m : metadata) {
548 m.onTransactionPurged(txId);
552 private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
553 for (ShardDataTreeMetadata<?> m : metadata) {
554 m.onHistoryCreated(historyId);
558 private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
559 for (ShardDataTreeMetadata<?> m : metadata) {
560 m.onHistoryClosed(historyId);
564 private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
565 for (ShardDataTreeMetadata<?> m : metadata) {
566 m.onHistoryPurged(historyId);
571 * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
572 * this method is used for re-establishing state when we are taking over
574 * @param historyId Local history identifier
575 * @param closed True if the chain should be created in closed state (i.e. pending purge)
576 * @return Transaction chain handle
578 ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
579 final boolean closed) {
580 final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
581 final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
582 checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId, existing);
586 ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId,
587 final @Nullable Runnable callback) {
588 ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
590 chain = new ShardDataTreeTransactionChain(historyId, this);
591 transactionChains.put(historyId, chain);
592 replicatePayload(historyId, CreateLocalHistoryPayload.create(
593 historyId, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
594 } else if (callback != null) {
601 ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
602 shard.getShardMBean().incrementReadOnlyTransactionCount();
604 if (txId.getHistoryId().getHistoryId() == 0) {
605 return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
608 return ensureTransactionChain(txId.getHistoryId(), null).newReadOnlyTransaction(txId);
611 ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
612 shard.getShardMBean().incrementReadWriteTransactionCount();
614 if (txId.getHistoryId().getHistoryId() == 0) {
615 return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
619 return ensureTransactionChain(txId.getHistoryId(), null).newReadWriteTransaction(txId);
623 public void notifyListeners(final DataTreeCandidate candidate) {
624 treeChangeListenerPublisher.publishChanges(candidate);
628 * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
629 * replication callbacks.
631 void purgeLeaderState() {
632 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
636 transactionChains.clear();
637 replicationCallbacks.clear();
641 * Close a single transaction chain.
643 * @param id History identifier
644 * @param callback Callback to invoke upon completion, may be null
646 void closeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
647 if (commonCloseTransactionChain(id, callback)) {
648 replicatePayload(id, CloseLocalHistoryPayload.create(id,
649 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
654 * Close a single transaction chain which is received through ask-based protocol. It does not keep a commit record.
656 * @param id History identifier
658 void closeTransactionChain(final LocalHistoryIdentifier id) {
659 commonCloseTransactionChain(id, null);
662 private boolean commonCloseTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
663 final ShardDataTreeTransactionChain chain = transactionChains.get(id);
665 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
666 if (callback != null) {
677 * Purge a single transaction chain.
679 * @param id History identifier
680 * @param callback Callback to invoke upon completion, may be null
682 void purgeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
683 final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
685 LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
686 if (callback != null) {
692 replicatePayload(id, PurgeLocalHistoryPayload.create(
693 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
696 Optional<DataTreeCandidate> readCurrentData() {
697 return dataTree.takeSnapshot().readNode(YangInstanceIdentifier.empty())
698 .map(state -> DataTreeCandidates.fromNormalizedNode(YangInstanceIdentifier.empty(), state));
701 public void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
702 final Optional<DataTreeCandidate> initialState,
703 final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
704 treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
708 return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
712 void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
713 final TransactionIdentifier id = transaction.getIdentifier();
714 LOG.debug("{}: aborting transaction {}", logContext, id);
715 replicatePayload(id, AbortTransactionPayload.create(
716 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
720 void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
721 // No-op for free-standing transactions
726 ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction,
727 final Optional<SortedSet<String>> participatingShardNames) {
728 final DataTreeModification snapshot = transaction.getSnapshot();
729 final TransactionIdentifier id = transaction.getIdentifier();
730 LOG.debug("{}: readying transaction {}", logContext, id);
732 LOG.debug("{}: transaction {} ready", logContext, id);
734 return createReadyCohort(transaction.getIdentifier(), snapshot, participatingShardNames);
737 void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
738 LOG.debug("{}: purging transaction {}", logContext, id);
739 replicatePayload(id, PurgeTransactionPayload.create(
740 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
743 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
744 return dataTree.takeSnapshot().readNode(path);
747 DataTreeSnapshot takeSnapshot() {
748 return dataTree.takeSnapshot();
752 public DataTreeModification newModification() {
753 return dataTree.takeSnapshot().newModification();
756 public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
757 Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
759 for (CommitEntry entry: pendingFinishCommits) {
760 ret.add(entry.cohort);
763 for (CommitEntry entry: pendingCommits) {
764 ret.add(entry.cohort);
767 for (CommitEntry entry: pendingTransactions) {
768 ret.add(entry.cohort);
771 pendingFinishCommits.clear();
772 pendingCommits.clear();
773 pendingTransactions.clear();
779 * Called some time after {@link #processNextPendingTransaction()} decides to stop processing.
781 void resumeNextPendingTransaction() {
782 LOG.debug("{}: attempting to resume transaction processing", logContext);
783 processNextPending();
786 @SuppressWarnings("checkstyle:IllegalCatch")
787 private void processNextPendingTransaction() {
788 ++currentTransactionBatch;
789 if (currentTransactionBatch > MAX_TRANSACTION_BATCH) {
790 LOG.debug("{}: Already processed {}, scheduling continuation", logContext, currentTransactionBatch);
791 shard.scheduleNextPendingTransaction();
795 processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
796 final SimpleShardDataTreeCohort cohort = entry.cohort;
797 final DataTreeModification modification = cohort.getDataTreeModification();
799 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
802 tip.validate(modification);
803 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
804 cohort.successfulCanCommit();
805 entry.lastAccess = readTime();
807 } catch (ConflictingModificationAppliedException e) {
808 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
810 cause = new OptimisticLockFailedException("Optimistic lock failed for path " + e.getPath(), e);
811 } catch (DataValidationFailedException e) {
812 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
815 // For debugging purposes, allow dumping of the modification. Coupled with the above
816 // precondition log, it should allow us to understand what went on.
817 LOG.debug("{}: Store Tx {}: modifications: {}", logContext, cohort.getIdentifier(), modification);
818 LOG.trace("{}: Current tree: {}", logContext, dataTree);
819 cause = new TransactionCommitFailedException("Data did not pass validation for path " + e.getPath(), e);
820 } catch (Exception e) {
821 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
825 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
826 pendingTransactions.poll().cohort.failedCanCommit(cause);
830 private void processNextPending() {
831 processNextPendingCommit();
832 processNextPendingTransaction();
835 private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
836 final Consumer<CommitEntry> processor) {
837 while (!queue.isEmpty()) {
838 final CommitEntry entry = queue.peek();
839 final SimpleShardDataTreeCohort cohort = entry.cohort;
841 if (cohort.isFailed()) {
842 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
847 if (cohort.getState() == allowedState) {
848 processor.accept(entry);
854 maybeRunOperationOnPendingTransactionsComplete();
857 private void processNextPendingCommit() {
858 processNextPending(pendingCommits, State.COMMIT_PENDING,
859 entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
862 private boolean peekNextPendingCommit() {
863 final CommitEntry first = pendingCommits.peek();
864 return first != null && first.cohort.getState() == State.COMMIT_PENDING;
867 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
868 final CommitEntry head = pendingTransactions.peek();
870 LOG.warn("{}: No transactions enqueued while attempting to start canCommit on {}", logContext, cohort);
873 if (!cohort.equals(head.cohort)) {
874 // The tx isn't at the head of the queue so we can't start canCommit at this point. Here we check if this
875 // tx should be moved ahead of other tx's in the READY state in the pendingTransactions queue. If this tx
876 // has other participating shards, it could deadlock with other tx's accessing the same shards
877 // depending on the order the tx's are readied on each shard
878 // (see https://jira.opendaylight.org/browse/CONTROLLER-1836). Therefore, if the preceding participating
879 // shard names for a preceding pending tx, call it A, in the queue matches that of this tx, then this tx
880 // is allowed to be moved ahead of tx A in the queue so it is processed first to avoid potential deadlock
881 // if tx A is behind this tx in the pendingTransactions queue for a preceding shard. In other words, since
882 // canCommmit for this tx was requested before tx A, honor that request. If this tx is moved to the head of
883 // the queue as a result, then proceed with canCommit.
885 Collection<String> precedingShardNames = extractPrecedingShardNames(cohort.getParticipatingShardNames());
886 if (precedingShardNames.isEmpty()) {
887 LOG.debug("{}: Tx {} is scheduled for canCommit step", logContext, cohort.getIdentifier());
891 LOG.debug("{}: Evaluating tx {} for canCommit - preceding participating shard names {}",
892 logContext, cohort.getIdentifier(), precedingShardNames);
893 final Iterator<CommitEntry> iter = pendingTransactions.iterator();
895 int moveToIndex = -1;
896 while (iter.hasNext()) {
897 final CommitEntry entry = iter.next();
900 if (cohort.equals(entry.cohort)) {
901 if (moveToIndex < 0) {
902 LOG.debug("{}: Not moving tx {} - cannot proceed with canCommit",
903 logContext, cohort.getIdentifier());
907 LOG.debug("{}: Moving {} to index {} in the pendingTransactions queue",
908 logContext, cohort.getIdentifier(), moveToIndex);
910 insertEntry(pendingTransactions, entry, moveToIndex);
912 if (!cohort.equals(pendingTransactions.peek().cohort)) {
913 LOG.debug("{}: Tx {} is not at the head of the queue - cannot proceed with canCommit",
914 logContext, cohort.getIdentifier());
918 LOG.debug("{}: Tx {} is now at the head of the queue - proceeding with canCommit",
919 logContext, cohort.getIdentifier());
923 if (entry.cohort.getState() != State.READY) {
924 LOG.debug("{}: Skipping pending transaction {} in state {}",
925 logContext, entry.cohort.getIdentifier(), entry.cohort.getState());
929 final Collection<String> pendingPrecedingShardNames = extractPrecedingShardNames(
930 entry.cohort.getParticipatingShardNames());
932 if (precedingShardNames.equals(pendingPrecedingShardNames)) {
933 if (moveToIndex < 0) {
934 LOG.debug("{}: Preceding shard names {} for pending tx {} match - saving moveToIndex {}",
935 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), index);
939 "{}: Preceding shard names {} for pending tx {} match but moveToIndex already set to {}",
940 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), moveToIndex);
943 LOG.debug("{}: Preceding shard names {} for pending tx {} differ - skipping",
944 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier());
949 processNextPendingTransaction();
952 private static void insertEntry(final Deque<CommitEntry> queue, final CommitEntry entry, final int atIndex) {
954 queue.addFirst(entry);
958 LOG.trace("Inserting into Deque at index {}", atIndex);
960 Deque<CommitEntry> tempStack = new ArrayDeque<>(atIndex);
961 for (int i = 0; i < atIndex; i++) {
962 tempStack.push(queue.poll());
965 queue.addFirst(entry);
967 tempStack.forEach(queue::addFirst);
970 private Collection<String> extractPrecedingShardNames(final Optional<SortedSet<String>> participatingShardNames) {
971 return participatingShardNames.map((Function<SortedSet<String>, Collection<String>>)
972 set -> set.headSet(shard.getShardName())).orElse(Collections.<String>emptyList());
975 private void failPreCommit(final Throwable cause) {
976 shard.getShardMBean().incrementFailedTransactionsCount();
977 pendingTransactions.poll().cohort.failedPreCommit(cause);
978 processNextPendingTransaction();
981 @SuppressWarnings("checkstyle:IllegalCatch")
982 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
983 final CommitEntry entry = pendingTransactions.peek();
984 checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
986 final SimpleShardDataTreeCohort current = entry.cohort;
987 verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
989 final TransactionIdentifier currentId = current.getIdentifier();
990 LOG.debug("{}: Preparing transaction {}", logContext, currentId);
992 final DataTreeCandidateTip candidate;
994 candidate = tip.prepare(cohort.getDataTreeModification());
995 LOG.debug("{}: Transaction {} candidate ready", logContext, currentId);
996 } catch (DataValidationFailedException | RuntimeException e) {
1001 cohort.userPreCommit(candidate, new FutureCallback<Void>() {
1003 public void onSuccess(final Void noop) {
1004 // Set the tip of the data tree.
1005 tip = verifyNotNull(candidate);
1007 entry.lastAccess = readTime();
1009 pendingTransactions.remove();
1010 pendingCommits.add(entry);
1012 LOG.debug("{}: Transaction {} prepared", logContext, currentId);
1014 cohort.successfulPreCommit(candidate);
1016 processNextPendingTransaction();
1020 public void onFailure(final Throwable failure) {
1021 failPreCommit(failure);
1026 private void failCommit(final Exception cause) {
1027 shard.getShardMBean().incrementFailedTransactionsCount();
1028 pendingFinishCommits.poll().cohort.failedCommit(cause);
1029 processNextPending();
1032 @SuppressWarnings("checkstyle:IllegalCatch")
1033 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
1034 final TransactionIdentifier txId = cohort.getIdentifier();
1035 final DataTreeCandidate candidate = cohort.getCandidate();
1037 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
1039 if (tip == candidate) {
1040 // All pending candidates have been committed, reset the tip to the data tree.
1045 dataTree.commit(candidate);
1046 } catch (Exception e) {
1047 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
1052 allMetadataCommittedTransaction(txId);
1053 shard.getShardMBean().incrementCommittedTransactionCount();
1054 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
1056 // FIXME: propagate journal index
1057 pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO, () -> {
1058 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
1059 notifyListeners(candidate);
1061 processNextPending();
1065 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
1066 final CommitEntry entry = pendingCommits.peek();
1067 checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
1069 final SimpleShardDataTreeCohort current = entry.cohort;
1070 if (!cohort.equals(current)) {
1071 LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
1075 LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
1077 final TransactionIdentifier txId = cohort.getIdentifier();
1078 final Payload payload;
1080 payload = CommitTransactionPayload.create(txId, candidate, PayloadVersion.current(),
1081 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity());
1082 } catch (IOException e) {
1083 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
1084 pendingCommits.poll().cohort.failedCommit(e);
1085 processNextPending();
1089 // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
1090 // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
1091 // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
1092 // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
1093 // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
1094 // pendingCommits queue.
1095 processNextPendingTransaction();
1097 // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
1098 // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
1099 // in order to properly determine the batchHint flag for the call to persistPayload.
1100 pendingCommits.remove();
1101 pendingFinishCommits.add(entry);
1103 // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
1104 // this transaction for replication.
1105 boolean replicationBatchHint = peekNextPendingCommit();
1107 // Once completed, we will continue via payloadReplicationComplete
1108 shard.persistPayload(txId, payload, replicationBatchHint);
1110 entry.lastAccess = shard.ticker().read();
1112 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
1114 // Process the next transaction pending commit, if any. If there is one it will be batched with this
1115 // transaction for replication.
1116 processNextPendingCommit();
1119 Collection<ActorRef> getCohortActors() {
1120 return cohortRegistry.getCohortActors();
1123 void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
1124 cohortRegistry.process(sender, message);
1128 ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1129 final Exception failure) {
1130 final SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId, failure);
1131 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1136 ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1137 final Optional<SortedSet<String>> participatingShardNames) {
1138 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId,
1139 cohortRegistry.createCohort(schemaContext, txId, shard::executeInSelf,
1140 COMMIT_STEP_TIMEOUT), participatingShardNames);
1141 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1145 // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
1146 // the newReadWriteTransaction()
1147 ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1148 final Optional<SortedSet<String>> participatingShardNames) {
1149 if (txId.getHistoryId().getHistoryId() == 0) {
1150 return createReadyCohort(txId, mod, participatingShardNames);
1153 return ensureTransactionChain(txId.getHistoryId(), null).createReadyCohort(txId, mod, participatingShardNames);
1156 @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
1157 void checkForExpiredTransactions(final long transactionCommitTimeoutMillis,
1158 final Function<SimpleShardDataTreeCohort, OptionalLong> accessTimeUpdater) {
1159 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
1160 final long now = readTime();
1162 final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
1163 !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
1164 final CommitEntry currentTx = currentQueue.peek();
1165 if (currentTx == null) {
1166 // Empty queue, no-op
1170 long delta = now - currentTx.lastAccess;
1171 if (delta < timeout) {
1172 // Not expired yet, bail
1176 final OptionalLong updateOpt = accessTimeUpdater.apply(currentTx.cohort);
1177 if (updateOpt.isPresent()) {
1178 final long newAccess = updateOpt.getAsLong();
1179 final long newDelta = now - newAccess;
1180 if (newDelta < delta) {
1181 LOG.debug("{}: Updated current transaction {} access time", logContext,
1182 currentTx.cohort.getIdentifier());
1183 currentTx.lastAccess = newAccess;
1187 if (delta < timeout) {
1188 // Not expired yet, bail
1193 final long deltaMillis = TimeUnit.NANOSECONDS.toMillis(delta);
1194 final State state = currentTx.cohort.getState();
1196 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
1197 currentTx.cohort.getIdentifier(), deltaMillis, state);
1198 boolean processNext = true;
1199 final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
1200 + deltaMillis + "ms");
1203 case CAN_COMMIT_PENDING:
1204 currentQueue.remove().cohort.failedCanCommit(cohortFailure);
1206 case CAN_COMMIT_COMPLETE:
1207 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
1208 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
1209 // in PRE_COMMIT_COMPLETE is changed.
1210 currentQueue.remove().cohort.reportFailure(cohortFailure);
1212 case PRE_COMMIT_PENDING:
1213 currentQueue.remove().cohort.failedPreCommit(cohortFailure);
1215 case PRE_COMMIT_COMPLETE:
1216 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
1217 // are ready we should commit the transaction, not abort it. Our current software stack does
1218 // not allow us to do that consistently, because we persist at the time of commit, hence
1219 // we can end up in a state where we have pre-committed a transaction, then a leader failover
1220 // occurred ... the new leader does not see the pre-committed transaction and does not have
1221 // a running timer. To fix this we really need two persistence events.
1223 // The first one, done at pre-commit time will hold the transaction payload. When consensus
1224 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1225 // apply the state in this event.
1227 // The second one, done at commit (or abort) time holds only the transaction identifier and
1228 // signals to followers that the state should (or should not) be applied.
1230 // In order to make the pre-commit timer working across failovers, though, we need
1231 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1232 // restart the timer.
1233 currentQueue.remove().cohort.reportFailure(cohortFailure);
1235 case COMMIT_PENDING:
1236 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1237 currentTx.cohort.getIdentifier());
1238 currentTx.lastAccess = now;
1239 processNext = false;
1242 currentQueue.remove().cohort.reportFailure(cohortFailure);
1248 currentQueue.remove();
1252 processNextPending();
1256 boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1257 final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1258 pendingTransactions).iterator();
1259 if (!it.hasNext()) {
1260 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1264 // First entry is special, as it may already be committing
1265 final CommitEntry first = it.next();
1266 if (cohort.equals(first.cohort)) {
1267 if (cohort.getState() != State.COMMIT_PENDING) {
1268 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1269 cohort.getIdentifier());
1272 if (cohort.getCandidate() != null) {
1273 rebaseTransactions(it, dataTree);
1276 processNextPending();
1280 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1284 DataTreeTip newTip = requireNonNullElse(first.cohort.getCandidate(), dataTree);
1285 while (it.hasNext()) {
1286 final CommitEntry e = it.next();
1287 if (cohort.equals(e.cohort)) {
1288 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1291 if (cohort.getCandidate() != null) {
1292 rebaseTransactions(it, newTip);
1297 newTip = requireNonNullElse(e.cohort.getCandidate(), newTip);
1301 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1305 @SuppressWarnings("checkstyle:IllegalCatch")
1306 private void rebaseTransactions(final Iterator<CommitEntry> iter, final @NonNull DataTreeTip newTip) {
1307 tip = requireNonNull(newTip);
1308 while (iter.hasNext()) {
1309 final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1310 if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1311 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1314 tip.validate(cohort.getDataTreeModification());
1315 } catch (DataValidationFailedException | RuntimeException e) {
1316 LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1317 cohort.reportFailure(e);
1319 } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1320 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1323 tip.validate(cohort.getDataTreeModification());
1324 DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1326 cohort.setNewCandidate(candidate);
1328 } catch (RuntimeException | DataValidationFailedException e) {
1329 LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1330 cohort.reportFailure(e);
1336 void setRunOnPendingTransactionsComplete(final Runnable operation) {
1337 runOnPendingTransactionsComplete = operation;
1338 maybeRunOperationOnPendingTransactionsComplete();
1341 private void maybeRunOperationOnPendingTransactionsComplete() {
1342 if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1343 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1344 runOnPendingTransactionsComplete);
1346 runOnPendingTransactionsComplete.run();
1347 runOnPendingTransactionsComplete = null;
1351 ShardStats getStats() {
1352 return shard.getShardMBean();
1355 Iterator<SimpleShardDataTreeCohort> cohortIterator() {
1356 return Iterables.transform(Iterables.concat(pendingFinishCommits, pendingCommits, pendingTransactions),
1357 e -> e.cohort).iterator();
1360 void removeTransactionChain(final LocalHistoryIdentifier id) {
1361 if (transactionChains.remove(id) != null) {
1362 LOG.debug("{}: Removed transaction chain {}", logContext, id);