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;
16 import akka.actor.ActorRef;
17 import akka.util.Timeout;
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.base.MoreObjects;
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.getCandidate();
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(DataTreeCandidate candidate) {
480 final DatastoreContext datastoreContext = shard.getDatastoreContext();
481 if (!datastoreContext.isSnapshotOnRootOverwrite()) {
485 if (!datastoreContext.isPersistent()) {
489 if (candidate.getRootNode().getModificationType().equals(ModificationType.UNMODIFIED)) {
493 // top level container ie "/"
494 if ((candidate.getRootPath().equals(YangInstanceIdentifier.empty())
495 && candidate.getRootNode().getModificationType().equals(ModificationType.WRITE))) {
496 LOG.debug("{}: shard root overwritten, enqueuing snapshot", logContext);
497 shard.self().tell(new InitiateCaptureSnapshot(), noSender());
502 private void replicatePayload(final Identifier id, final Payload payload, final @Nullable Runnable callback) {
503 if (callback != null) {
504 replicationCallbacks.put(payload, callback);
506 shard.persistPayload(id, payload, true);
509 private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
510 final Runnable callback = replicationCallbacks.remove(payload);
511 if (callback != null) {
512 LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
515 LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
519 private boolean payloadReplicationComplete(final TransactionIdentifier txId) {
520 final CommitEntry current = pendingFinishCommits.peek();
521 if (current == null) {
522 LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
523 allMetadataCommittedTransaction(txId);
527 if (!current.cohort.getIdentifier().equals(txId)) {
528 LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
529 current.cohort.getIdentifier(), txId);
530 allMetadataCommittedTransaction(txId);
534 finishCommit(current.cohort);
538 private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
539 for (ShardDataTreeMetadata<?> m : metadata) {
540 m.onTransactionAborted(txId);
544 private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
545 for (ShardDataTreeMetadata<?> m : metadata) {
546 m.onTransactionCommitted(txId);
550 private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
551 for (ShardDataTreeMetadata<?> m : metadata) {
552 m.onTransactionPurged(txId);
556 private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
557 for (ShardDataTreeMetadata<?> m : metadata) {
558 m.onHistoryCreated(historyId);
562 private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
563 for (ShardDataTreeMetadata<?> m : metadata) {
564 m.onHistoryClosed(historyId);
568 private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
569 for (ShardDataTreeMetadata<?> m : metadata) {
570 m.onHistoryPurged(historyId);
575 * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
576 * this method is used for re-establishing state when we are taking over
578 * @param historyId Local history identifier
579 * @param closed True if the chain should be created in closed state (i.e. pending purge)
580 * @return Transaction chain handle
582 ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
583 final boolean closed) {
584 final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
585 final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
586 checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId, existing);
590 ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId,
591 final @Nullable Runnable callback) {
592 ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
594 chain = new ShardDataTreeTransactionChain(historyId, this);
595 transactionChains.put(historyId, chain);
596 replicatePayload(historyId, CreateLocalHistoryPayload.create(
597 historyId, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
598 } else if (callback != null) {
605 ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
606 shard.getShardMBean().incrementReadOnlyTransactionCount();
608 if (txId.getHistoryId().getHistoryId() == 0) {
609 return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
612 return ensureTransactionChain(txId.getHistoryId(), null).newReadOnlyTransaction(txId);
615 ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
616 shard.getShardMBean().incrementReadWriteTransactionCount();
618 if (txId.getHistoryId().getHistoryId() == 0) {
619 return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
623 return ensureTransactionChain(txId.getHistoryId(), null).newReadWriteTransaction(txId);
627 public void notifyListeners(final DataTreeCandidate candidate) {
628 treeChangeListenerPublisher.publishChanges(candidate);
632 * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
633 * replication callbacks.
635 void purgeLeaderState() {
636 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
640 transactionChains.clear();
641 replicationCallbacks.clear();
645 * Close a single transaction chain.
647 * @param id History identifier
648 * @param callback Callback to invoke upon completion, may be null
650 void closeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
651 if (commonCloseTransactionChain(id, callback)) {
652 replicatePayload(id, CloseLocalHistoryPayload.create(id,
653 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
658 * Close a single transaction chain which is received through ask-based protocol. It does not keep a commit record.
660 * @param id History identifier
662 void closeTransactionChain(final LocalHistoryIdentifier id) {
663 commonCloseTransactionChain(id, null);
666 private boolean commonCloseTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
667 final ShardDataTreeTransactionChain chain = transactionChains.get(id);
669 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
670 if (callback != null) {
681 * Purge a single transaction chain.
683 * @param id History identifier
684 * @param callback Callback to invoke upon completion, may be null
686 void purgeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
687 final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
689 LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
690 if (callback != null) {
696 replicatePayload(id, PurgeLocalHistoryPayload.create(
697 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
700 Optional<DataTreeCandidate> readCurrentData() {
701 return dataTree.takeSnapshot().readNode(YangInstanceIdentifier.empty())
702 .map(state -> DataTreeCandidates.fromNormalizedNode(YangInstanceIdentifier.empty(), state));
705 public void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
706 final Optional<DataTreeCandidate> initialState,
707 final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
708 treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
712 return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
716 void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
717 final TransactionIdentifier id = transaction.getIdentifier();
718 LOG.debug("{}: aborting transaction {}", logContext, id);
719 replicatePayload(id, AbortTransactionPayload.create(
720 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
724 void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
725 // No-op for free-standing transactions
730 ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction,
731 final Optional<SortedSet<String>> participatingShardNames) {
732 final DataTreeModification snapshot = transaction.getSnapshot();
733 final TransactionIdentifier id = transaction.getIdentifier();
734 LOG.debug("{}: readying transaction {}", logContext, id);
736 LOG.debug("{}: transaction {} ready", logContext, id);
738 return createReadyCohort(transaction.getIdentifier(), snapshot, participatingShardNames);
741 void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
742 LOG.debug("{}: purging transaction {}", logContext, id);
743 replicatePayload(id, PurgeTransactionPayload.create(
744 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
747 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
748 return dataTree.takeSnapshot().readNode(path);
751 DataTreeSnapshot takeSnapshot() {
752 return dataTree.takeSnapshot();
756 public DataTreeModification newModification() {
757 return dataTree.takeSnapshot().newModification();
760 public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
761 Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
763 for (CommitEntry entry: pendingFinishCommits) {
764 ret.add(entry.cohort);
767 for (CommitEntry entry: pendingCommits) {
768 ret.add(entry.cohort);
771 for (CommitEntry entry: pendingTransactions) {
772 ret.add(entry.cohort);
775 pendingFinishCommits.clear();
776 pendingCommits.clear();
777 pendingTransactions.clear();
783 * Called some time after {@link #processNextPendingTransaction()} decides to stop processing.
785 void resumeNextPendingTransaction() {
786 LOG.debug("{}: attempting to resume transaction processing", logContext);
787 processNextPending();
790 @SuppressWarnings("checkstyle:IllegalCatch")
791 private void processNextPendingTransaction() {
792 ++currentTransactionBatch;
793 if (currentTransactionBatch > MAX_TRANSACTION_BATCH) {
794 LOG.debug("{}: Already processed {}, scheduling continuation", logContext, currentTransactionBatch);
795 shard.scheduleNextPendingTransaction();
799 processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
800 final SimpleShardDataTreeCohort cohort = entry.cohort;
801 final DataTreeModification modification = cohort.getDataTreeModification();
803 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
806 tip.validate(modification);
807 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
808 cohort.successfulCanCommit();
809 entry.lastAccess = readTime();
811 } catch (ConflictingModificationAppliedException e) {
812 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
814 cause = new OptimisticLockFailedException("Optimistic lock failed for path " + e.getPath(), e);
815 } catch (DataValidationFailedException e) {
816 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
819 // For debugging purposes, allow dumping of the modification. Coupled with the above
820 // precondition log, it should allow us to understand what went on.
821 LOG.debug("{}: Store Tx {}: modifications: {}", logContext, cohort.getIdentifier(), modification);
822 LOG.trace("{}: Current tree: {}", logContext, dataTree);
823 cause = new TransactionCommitFailedException("Data did not pass validation for path " + e.getPath(), e);
824 } catch (Exception e) {
825 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
829 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
830 pendingTransactions.poll().cohort.failedCanCommit(cause);
834 private void processNextPending() {
835 processNextPendingCommit();
836 processNextPendingTransaction();
839 private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
840 final Consumer<CommitEntry> processor) {
841 while (!queue.isEmpty()) {
842 final CommitEntry entry = queue.peek();
843 final SimpleShardDataTreeCohort cohort = entry.cohort;
845 if (cohort.isFailed()) {
846 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
851 if (cohort.getState() == allowedState) {
852 processor.accept(entry);
858 maybeRunOperationOnPendingTransactionsComplete();
861 private void processNextPendingCommit() {
862 processNextPending(pendingCommits, State.COMMIT_PENDING,
863 entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
866 private boolean peekNextPendingCommit() {
867 final CommitEntry first = pendingCommits.peek();
868 return first != null && first.cohort.getState() == State.COMMIT_PENDING;
871 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
872 final CommitEntry head = pendingTransactions.peek();
874 LOG.warn("{}: No transactions enqueued while attempting to start canCommit on {}", logContext, cohort);
877 if (!cohort.equals(head.cohort)) {
878 // The tx isn't at the head of the queue so we can't start canCommit at this point. Here we check if this
879 // tx should be moved ahead of other tx's in the READY state in the pendingTransactions queue. If this tx
880 // has other participating shards, it could deadlock with other tx's accessing the same shards
881 // depending on the order the tx's are readied on each shard
882 // (see https://jira.opendaylight.org/browse/CONTROLLER-1836). Therefore, if the preceding participating
883 // shard names for a preceding pending tx, call it A, in the queue matches that of this tx, then this tx
884 // is allowed to be moved ahead of tx A in the queue so it is processed first to avoid potential deadlock
885 // if tx A is behind this tx in the pendingTransactions queue for a preceding shard. In other words, since
886 // canCommmit for this tx was requested before tx A, honor that request. If this tx is moved to the head of
887 // the queue as a result, then proceed with canCommit.
889 Collection<String> precedingShardNames = extractPrecedingShardNames(cohort.getParticipatingShardNames());
890 if (precedingShardNames.isEmpty()) {
891 LOG.debug("{}: Tx {} is scheduled for canCommit step", logContext, cohort.getIdentifier());
895 LOG.debug("{}: Evaluating tx {} for canCommit - preceding participating shard names {}",
896 logContext, cohort.getIdentifier(), precedingShardNames);
897 final Iterator<CommitEntry> iter = pendingTransactions.iterator();
899 int moveToIndex = -1;
900 while (iter.hasNext()) {
901 final CommitEntry entry = iter.next();
904 if (cohort.equals(entry.cohort)) {
905 if (moveToIndex < 0) {
906 LOG.debug("{}: Not moving tx {} - cannot proceed with canCommit",
907 logContext, cohort.getIdentifier());
911 LOG.debug("{}: Moving {} to index {} in the pendingTransactions queue",
912 logContext, cohort.getIdentifier(), moveToIndex);
914 insertEntry(pendingTransactions, entry, moveToIndex);
916 if (!cohort.equals(pendingTransactions.peek().cohort)) {
917 LOG.debug("{}: Tx {} is not at the head of the queue - cannot proceed with canCommit",
918 logContext, cohort.getIdentifier());
922 LOG.debug("{}: Tx {} is now at the head of the queue - proceeding with canCommit",
923 logContext, cohort.getIdentifier());
927 if (entry.cohort.getState() != State.READY) {
928 LOG.debug("{}: Skipping pending transaction {} in state {}",
929 logContext, entry.cohort.getIdentifier(), entry.cohort.getState());
933 final Collection<String> pendingPrecedingShardNames = extractPrecedingShardNames(
934 entry.cohort.getParticipatingShardNames());
936 if (precedingShardNames.equals(pendingPrecedingShardNames)) {
937 if (moveToIndex < 0) {
938 LOG.debug("{}: Preceding shard names {} for pending tx {} match - saving moveToIndex {}",
939 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), index);
943 "{}: Preceding shard names {} for pending tx {} match but moveToIndex already set to {}",
944 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), moveToIndex);
947 LOG.debug("{}: Preceding shard names {} for pending tx {} differ - skipping",
948 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier());
953 processNextPendingTransaction();
956 private static void insertEntry(final Deque<CommitEntry> queue, final CommitEntry entry, final int atIndex) {
958 queue.addFirst(entry);
962 LOG.trace("Inserting into Deque at index {}", atIndex);
964 Deque<CommitEntry> tempStack = new ArrayDeque<>(atIndex);
965 for (int i = 0; i < atIndex; i++) {
966 tempStack.push(queue.poll());
969 queue.addFirst(entry);
971 tempStack.forEach(queue::addFirst);
974 private Collection<String> extractPrecedingShardNames(final Optional<SortedSet<String>> participatingShardNames) {
975 return participatingShardNames.map((Function<SortedSet<String>, Collection<String>>)
976 set -> set.headSet(shard.getShardName())).orElse(Collections.<String>emptyList());
979 private void failPreCommit(final Throwable cause) {
980 shard.getShardMBean().incrementFailedTransactionsCount();
981 pendingTransactions.poll().cohort.failedPreCommit(cause);
982 processNextPendingTransaction();
985 @SuppressWarnings("checkstyle:IllegalCatch")
986 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
987 final CommitEntry entry = pendingTransactions.peek();
988 checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
990 final SimpleShardDataTreeCohort current = entry.cohort;
991 verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
993 final TransactionIdentifier currentId = current.getIdentifier();
994 LOG.debug("{}: Preparing transaction {}", logContext, currentId);
996 final DataTreeCandidateTip candidate;
998 candidate = tip.prepare(cohort.getDataTreeModification());
999 LOG.debug("{}: Transaction {} candidate ready", logContext, currentId);
1000 } catch (DataValidationFailedException | RuntimeException e) {
1005 cohort.userPreCommit(candidate, new FutureCallback<Void>() {
1007 public void onSuccess(final Void noop) {
1008 // Set the tip of the data tree.
1009 tip = verifyNotNull(candidate);
1011 entry.lastAccess = readTime();
1013 pendingTransactions.remove();
1014 pendingCommits.add(entry);
1016 LOG.debug("{}: Transaction {} prepared", logContext, currentId);
1018 cohort.successfulPreCommit(candidate);
1020 processNextPendingTransaction();
1024 public void onFailure(final Throwable failure) {
1025 failPreCommit(failure);
1030 private void failCommit(final Exception cause) {
1031 shard.getShardMBean().incrementFailedTransactionsCount();
1032 pendingFinishCommits.poll().cohort.failedCommit(cause);
1033 processNextPending();
1036 @SuppressWarnings("checkstyle:IllegalCatch")
1037 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
1038 final TransactionIdentifier txId = cohort.getIdentifier();
1039 final DataTreeCandidate candidate = cohort.getCandidate();
1041 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
1043 if (tip == candidate) {
1044 // All pending candidates have been committed, reset the tip to the data tree.
1049 dataTree.commit(candidate);
1050 } catch (Exception e) {
1051 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
1056 allMetadataCommittedTransaction(txId);
1057 shard.getShardMBean().incrementCommittedTransactionCount();
1058 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
1060 // FIXME: propagate journal index
1061 pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO, () -> {
1062 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
1063 notifyListeners(candidate);
1065 processNextPending();
1069 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
1070 final CommitEntry entry = pendingCommits.peek();
1071 checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
1073 final SimpleShardDataTreeCohort current = entry.cohort;
1074 if (!cohort.equals(current)) {
1075 LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
1079 LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
1081 final TransactionIdentifier txId = cohort.getIdentifier();
1082 final Payload payload;
1084 payload = CommitTransactionPayload.create(txId, candidate, PayloadVersion.current(),
1085 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity());
1086 } catch (IOException e) {
1087 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
1088 pendingCommits.poll().cohort.failedCommit(e);
1089 processNextPending();
1093 // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
1094 // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
1095 // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
1096 // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
1097 // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
1098 // pendingCommits queue.
1099 processNextPendingTransaction();
1101 // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
1102 // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
1103 // in order to properly determine the batchHint flag for the call to persistPayload.
1104 pendingCommits.remove();
1105 pendingFinishCommits.add(entry);
1107 // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
1108 // this transaction for replication.
1109 boolean replicationBatchHint = peekNextPendingCommit();
1111 // Once completed, we will continue via payloadReplicationComplete
1112 shard.persistPayload(txId, payload, replicationBatchHint);
1114 entry.lastAccess = shard.ticker().read();
1116 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
1118 // Process the next transaction pending commit, if any. If there is one it will be batched with this
1119 // transaction for replication.
1120 processNextPendingCommit();
1123 Collection<ActorRef> getCohortActors() {
1124 return cohortRegistry.getCohortActors();
1127 void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
1128 cohortRegistry.process(sender, message);
1132 ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1133 final Exception failure) {
1134 final SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId, failure);
1135 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1140 ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1141 final Optional<SortedSet<String>> participatingShardNames) {
1142 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId,
1143 cohortRegistry.createCohort(schemaContext, txId, shard::executeInSelf,
1144 COMMIT_STEP_TIMEOUT), participatingShardNames);
1145 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1149 // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
1150 // the newReadWriteTransaction()
1151 ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1152 final Optional<SortedSet<String>> participatingShardNames) {
1153 if (txId.getHistoryId().getHistoryId() == 0) {
1154 return createReadyCohort(txId, mod, participatingShardNames);
1157 return ensureTransactionChain(txId.getHistoryId(), null).createReadyCohort(txId, mod, participatingShardNames);
1160 @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
1161 void checkForExpiredTransactions(final long transactionCommitTimeoutMillis,
1162 final Function<SimpleShardDataTreeCohort, OptionalLong> accessTimeUpdater) {
1163 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
1164 final long now = readTime();
1166 final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
1167 !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
1168 final CommitEntry currentTx = currentQueue.peek();
1169 if (currentTx == null) {
1170 // Empty queue, no-op
1174 long delta = now - currentTx.lastAccess;
1175 if (delta < timeout) {
1176 // Not expired yet, bail
1180 final OptionalLong updateOpt = accessTimeUpdater.apply(currentTx.cohort);
1181 if (updateOpt.isPresent()) {
1182 final long newAccess = updateOpt.getAsLong();
1183 final long newDelta = now - newAccess;
1184 if (newDelta < delta) {
1185 LOG.debug("{}: Updated current transaction {} access time", logContext,
1186 currentTx.cohort.getIdentifier());
1187 currentTx.lastAccess = newAccess;
1191 if (delta < timeout) {
1192 // Not expired yet, bail
1197 final long deltaMillis = TimeUnit.NANOSECONDS.toMillis(delta);
1198 final State state = currentTx.cohort.getState();
1200 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
1201 currentTx.cohort.getIdentifier(), deltaMillis, state);
1202 boolean processNext = true;
1203 final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
1204 + deltaMillis + "ms");
1207 case CAN_COMMIT_PENDING:
1208 currentQueue.remove().cohort.failedCanCommit(cohortFailure);
1210 case CAN_COMMIT_COMPLETE:
1211 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
1212 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
1213 // in PRE_COMMIT_COMPLETE is changed.
1214 currentQueue.remove().cohort.reportFailure(cohortFailure);
1216 case PRE_COMMIT_PENDING:
1217 currentQueue.remove().cohort.failedPreCommit(cohortFailure);
1219 case PRE_COMMIT_COMPLETE:
1220 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
1221 // are ready we should commit the transaction, not abort it. Our current software stack does
1222 // not allow us to do that consistently, because we persist at the time of commit, hence
1223 // we can end up in a state where we have pre-committed a transaction, then a leader failover
1224 // occurred ... the new leader does not see the pre-committed transaction and does not have
1225 // a running timer. To fix this we really need two persistence events.
1227 // The first one, done at pre-commit time will hold the transaction payload. When consensus
1228 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1229 // apply the state in this event.
1231 // The second one, done at commit (or abort) time holds only the transaction identifier and
1232 // signals to followers that the state should (or should not) be applied.
1234 // In order to make the pre-commit timer working across failovers, though, we need
1235 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1236 // restart the timer.
1237 currentQueue.remove().cohort.reportFailure(cohortFailure);
1239 case COMMIT_PENDING:
1240 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1241 currentTx.cohort.getIdentifier());
1242 currentTx.lastAccess = now;
1243 processNext = false;
1246 currentQueue.remove().cohort.reportFailure(cohortFailure);
1252 currentQueue.remove();
1256 processNextPending();
1260 boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1261 final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1262 pendingTransactions).iterator();
1263 if (!it.hasNext()) {
1264 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1268 // First entry is special, as it may already be committing
1269 final CommitEntry first = it.next();
1270 if (cohort.equals(first.cohort)) {
1271 if (cohort.getState() != State.COMMIT_PENDING) {
1272 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1273 cohort.getIdentifier());
1276 if (cohort.getCandidate() != null) {
1277 rebaseTransactions(it, dataTree);
1280 processNextPending();
1284 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1288 DataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
1289 while (it.hasNext()) {
1290 final CommitEntry e = it.next();
1291 if (cohort.equals(e.cohort)) {
1292 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1295 if (cohort.getCandidate() != null) {
1296 rebaseTransactions(it, newTip);
1301 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), newTip);
1305 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1309 @SuppressWarnings("checkstyle:IllegalCatch")
1310 private void rebaseTransactions(final Iterator<CommitEntry> iter, final @NonNull DataTreeTip newTip) {
1311 tip = requireNonNull(newTip);
1312 while (iter.hasNext()) {
1313 final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1314 if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1315 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1318 tip.validate(cohort.getDataTreeModification());
1319 } catch (DataValidationFailedException | RuntimeException e) {
1320 LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1321 cohort.reportFailure(e);
1323 } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1324 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1327 tip.validate(cohort.getDataTreeModification());
1328 DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1330 cohort.setNewCandidate(candidate);
1332 } catch (RuntimeException | DataValidationFailedException e) {
1333 LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1334 cohort.reportFailure(e);
1340 void setRunOnPendingTransactionsComplete(final Runnable operation) {
1341 runOnPendingTransactionsComplete = operation;
1342 maybeRunOperationOnPendingTransactionsComplete();
1345 private void maybeRunOperationOnPendingTransactionsComplete() {
1346 if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1347 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1348 runOnPendingTransactionsComplete);
1350 runOnPendingTransactionsComplete.run();
1351 runOnPendingTransactionsComplete = null;
1355 ShardStats getStats() {
1356 return shard.getShardMBean();
1359 Iterator<SimpleShardDataTreeCohort> cohortIterator() {
1360 return Iterables.transform(Iterables.concat(pendingFinishCommits, pendingCommits, pendingTransactions),
1361 e -> e.cohort).iterator();
1364 void removeTransactionChain(final LocalHistoryIdentifier id) {
1365 if (transactionChains.remove(id) != null) {
1366 LOG.debug("{}: Removed transaction chain {}", logContext, id);