2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.datastore;
10 import static akka.actor.ActorRef.noSender;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verify;
13 import static com.google.common.base.Verify.verifyNotNull;
14 import static java.util.Objects.requireNonNull;
15 import static java.util.Objects.requireNonNullElse;
17 import akka.actor.ActorRef;
18 import akka.util.Timeout;
19 import com.google.common.annotations.VisibleForTesting;
20 import com.google.common.base.Stopwatch;
21 import com.google.common.collect.ImmutableList;
22 import com.google.common.collect.ImmutableMap;
23 import com.google.common.collect.ImmutableMap.Builder;
24 import com.google.common.collect.Iterables;
25 import com.google.common.primitives.UnsignedLong;
26 import com.google.common.util.concurrent.FutureCallback;
27 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
29 import java.io.IOException;
30 import java.util.ArrayDeque;
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.Collections;
34 import java.util.Deque;
35 import java.util.HashMap;
36 import java.util.Iterator;
38 import java.util.Map.Entry;
39 import java.util.Optional;
40 import java.util.OptionalLong;
41 import java.util.Queue;
42 import java.util.SortedSet;
43 import java.util.concurrent.TimeUnit;
44 import java.util.concurrent.TimeoutException;
45 import java.util.function.Consumer;
46 import java.util.function.Function;
47 import java.util.function.UnaryOperator;
48 import org.eclipse.jdt.annotation.NonNull;
49 import org.eclipse.jdt.annotation.Nullable;
50 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
51 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
52 import org.opendaylight.controller.cluster.datastore.DataTreeCohortActorRegistry.CohortRegistryCommand;
53 import org.opendaylight.controller.cluster.datastore.ShardDataTreeCohort.State;
54 import org.opendaylight.controller.cluster.datastore.node.utils.transformer.ReusableNormalizedNodePruner;
55 import org.opendaylight.controller.cluster.datastore.persisted.AbortTransactionPayload;
56 import org.opendaylight.controller.cluster.datastore.persisted.AbstractIdentifiablePayload;
57 import org.opendaylight.controller.cluster.datastore.persisted.CloseLocalHistoryPayload;
58 import org.opendaylight.controller.cluster.datastore.persisted.CommitTransactionPayload;
59 import org.opendaylight.controller.cluster.datastore.persisted.CreateLocalHistoryPayload;
60 import org.opendaylight.controller.cluster.datastore.persisted.DataTreeCandidateInputOutput.DataTreeCandidateWithVersion;
61 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
62 import org.opendaylight.controller.cluster.datastore.persisted.PayloadVersion;
63 import org.opendaylight.controller.cluster.datastore.persisted.PurgeLocalHistoryPayload;
64 import org.opendaylight.controller.cluster.datastore.persisted.PurgeTransactionPayload;
65 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
66 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshotMetadata;
67 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
68 import org.opendaylight.controller.cluster.datastore.utils.DataTreeModificationOutput;
69 import org.opendaylight.controller.cluster.datastore.utils.PruningDataTreeModification;
70 import org.opendaylight.controller.cluster.raft.base.messages.InitiateCaptureSnapshot;
71 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
72 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
73 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
74 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
75 import org.opendaylight.yangtools.concepts.Identifier;
76 import org.opendaylight.yangtools.concepts.ListenerRegistration;
77 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
78 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
79 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
80 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
81 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
82 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
83 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
84 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
85 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
86 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
87 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeTip;
88 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
89 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
90 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
91 import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeStreamVersion;
92 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
93 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
94 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
95 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
96 import org.slf4j.Logger;
97 import org.slf4j.LoggerFactory;
98 import scala.concurrent.duration.FiniteDuration;
101 * Internal shard state, similar to a DOMStore, but optimized for use in the actor system, e.g. it does not expose
102 * public interfaces and assumes it is only ever called from a single thread.
105 * This class is not part of the API contract and is subject to change at any time. It is NOT thread-safe.
107 public class ShardDataTree extends ShardDataTreeTransactionParent {
108 private static final class CommitEntry {
109 final SimpleShardDataTreeCohort cohort;
112 CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
113 this.cohort = requireNonNull(cohort);
118 public String toString() {
119 return "CommitEntry [tx=" + cohort.getIdentifier() + ", state=" + cohort.getState() + "]";
123 private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(FiniteDuration.create(5, TimeUnit.SECONDS));
124 private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
127 * Process this many transactions in a single batched run. If we exceed this limit, we need to schedule later
128 * execution to finish up the batch. This is necessary in case of a long list of transactions which progress
129 * immediately through their preCommit phase -- if that happens, their completion eats up stack frames and could
130 * result in StackOverflowError.
132 private static final int MAX_TRANSACTION_BATCH = 100;
134 private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
135 private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
136 private final Deque<CommitEntry> pendingTransactions = new ArrayDeque<>();
137 private final Queue<CommitEntry> pendingCommits = new ArrayDeque<>();
138 private final Queue<CommitEntry> pendingFinishCommits = new ArrayDeque<>();
141 * Callbacks that need to be invoked once a payload is replicated.
143 private final Map<Payload, Runnable> replicationCallbacks = new HashMap<>();
145 private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
146 private final Collection<ShardDataTreeMetadata<?>> metadata;
147 private final DataTree dataTree;
148 private final String logContext;
149 private final Shard shard;
150 private Runnable runOnPendingTransactionsComplete;
153 * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
154 * {@link DataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
155 * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
156 * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
158 private DataTreeTip tip;
160 private SchemaContext schemaContext;
161 private DataSchemaContextTree dataSchemaContext;
163 private int currentTransactionBatch;
165 ShardDataTree(final Shard shard, final EffectiveModelContext schemaContext, final DataTree dataTree,
166 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
167 final String logContext,
168 final ShardDataTreeMetadata<?>... metadata) {
169 this.dataTree = requireNonNull(dataTree);
170 updateSchemaContext(schemaContext);
172 this.shard = requireNonNull(shard);
173 this.treeChangeListenerPublisher = requireNonNull(treeChangeListenerPublisher);
174 this.logContext = requireNonNull(logContext);
175 this.metadata = ImmutableList.copyOf(metadata);
179 ShardDataTree(final Shard shard, final EffectiveModelContext schemaContext, final TreeType treeType,
180 final YangInstanceIdentifier root,
181 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
182 final String logContext,
183 final ShardDataTreeMetadata<?>... metadata) {
184 this(shard, schemaContext, createDataTree(treeType, root), treeChangeListenerPublisher, logContext, metadata);
187 private static DataTree createDataTree(final TreeType treeType, final YangInstanceIdentifier root) {
188 final DataTreeConfiguration baseConfig = DataTreeConfiguration.getDefault(treeType);
189 return new InMemoryDataTreeFactory().create(new DataTreeConfiguration.Builder(baseConfig.getTreeType())
190 .setMandatoryNodesValidation(baseConfig.isMandatoryNodesValidationEnabled())
191 .setUniqueIndexes(baseConfig.isUniqueIndexEnabled())
197 public ShardDataTree(final Shard shard, final EffectiveModelContext schemaContext, final TreeType treeType) {
198 this(shard, schemaContext, treeType, YangInstanceIdentifier.empty(),
199 new DefaultShardDataTreeChangeListenerPublisher(""), "");
202 final String logContext() {
206 final long readTime() {
207 return shard.ticker().read();
210 public DataTree getDataTree() {
214 SchemaContext getSchemaContext() {
215 return schemaContext;
218 void updateSchemaContext(final @NonNull EffectiveModelContext newSchemaContext) {
219 dataTree.setEffectiveModelContext(newSchemaContext);
220 this.schemaContext = newSchemaContext;
221 this.dataSchemaContext = DataSchemaContextTree.from(newSchemaContext);
224 void resetTransactionBatch() {
225 currentTransactionBatch = 0;
229 * Take a snapshot of current state for later recovery.
231 * @return A state snapshot
233 @NonNull ShardDataTreeSnapshot takeStateSnapshot() {
234 final NormalizedNode rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.empty()).get();
235 final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
236 ImmutableMap.builder();
238 for (ShardDataTreeMetadata<?> m : metadata) {
239 final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
241 metaBuilder.put(meta.getType(), meta);
245 return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
248 private boolean anyPendingTransactions() {
249 return !pendingTransactions.isEmpty() || !pendingCommits.isEmpty() || !pendingFinishCommits.isEmpty();
252 private void applySnapshot(final @NonNull ShardDataTreeSnapshot snapshot,
253 final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
254 final Stopwatch elapsed = Stopwatch.createStarted();
256 if (anyPendingTransactions()) {
257 LOG.warn("{}: applying state snapshot with pending transactions", logContext);
260 final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
261 if (snapshot instanceof MetadataShardDataTreeSnapshot) {
262 snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
264 snapshotMeta = ImmutableMap.of();
267 for (ShardDataTreeMetadata<?> m : metadata) {
268 final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
276 final DataTreeModification unwrapped = dataTree.takeSnapshot().newModification();
277 final DataTreeModification mod = wrapper.apply(unwrapped);
278 // delete everything first
279 mod.delete(YangInstanceIdentifier.empty());
281 final Optional<NormalizedNode> maybeNode = snapshot.getRootNode();
282 if (maybeNode.isPresent()) {
283 // Add everything from the remote node back
284 mod.write(YangInstanceIdentifier.empty(), maybeNode.get());
288 dataTree.validate(unwrapped);
289 DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
290 dataTree.commit(candidate);
291 notifyListeners(candidate);
293 LOG.debug("{}: state snapshot applied in {}", logContext, elapsed);
297 * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
298 * does not perform any pruning.
300 * @param snapshot Snapshot that needs to be applied
301 * @throws DataValidationFailedException when the snapshot fails to apply
303 void applySnapshot(final @NonNull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
304 // TODO: we should be taking ShardSnapshotState here and performing forward-compatibility translation
305 applySnapshot(snapshot, UnaryOperator.identity());
309 * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
310 * pruning in an attempt to adjust the state to our current SchemaContext.
312 * @param snapshot Snapshot that needs to be applied
313 * @throws DataValidationFailedException when the snapshot fails to apply
315 void applyRecoverySnapshot(final @NonNull ShardSnapshotState snapshot) throws DataValidationFailedException {
316 // TODO: we should be able to reuse the pruner, provided we are not reentrant
317 final ReusableNormalizedNodePruner pruner = ReusableNormalizedNodePruner.forDataSchemaContext(
319 if (snapshot.needsMigration()) {
320 final ReusableNormalizedNodePruner uintPruner = pruner.withUintAdaption();
321 applySnapshot(snapshot.getSnapshot(),
322 delegate -> new PruningDataTreeModification.Proactive(delegate, dataTree, uintPruner));
324 applySnapshot(snapshot.getSnapshot(),
325 delegate -> new PruningDataTreeModification.Reactive(delegate, dataTree, pruner));
329 @SuppressWarnings("checkstyle:IllegalCatch")
330 private void applyRecoveryCandidate(final CommitTransactionPayload payload) throws IOException {
331 final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> entry = payload.acquireCandidate();
332 final DataTreeModification unwrapped = dataTree.takeSnapshot().newModification();
333 final PruningDataTreeModification mod = createPruningModification(unwrapped,
334 NormalizedNodeStreamVersion.MAGNESIUM.compareTo(entry.getValue().getVersion()) > 0);
336 DataTreeCandidates.applyToModification(mod, entry.getValue().getCandidate());
338 LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
341 dataTree.validate(unwrapped);
342 dataTree.commit(dataTree.prepare(unwrapped));
343 } catch (Exception e) {
344 File file = new File(System.getProperty("karaf.data", "."),
345 "failed-recovery-payload-" + logContext + ".out");
346 DataTreeModificationOutput.toFile(file, unwrapped);
347 throw new IllegalStateException(String.format(
348 "%s: Failed to apply recovery payload. Modification data was written to file %s",
349 logContext, file), e);
352 allMetadataCommittedTransaction(entry.getKey());
355 private PruningDataTreeModification createPruningModification(final DataTreeModification unwrapped,
356 final boolean uintAdapting) {
357 // TODO: we should be able to reuse the pruner, provided we are not reentrant
358 final ReusableNormalizedNodePruner pruner = ReusableNormalizedNodePruner.forDataSchemaContext(
360 return uintAdapting ? new PruningDataTreeModification.Proactive(unwrapped, dataTree, pruner.withUintAdaption())
361 : new PruningDataTreeModification.Reactive(unwrapped, dataTree, pruner);
365 * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
366 * pruning in an attempt to adjust the state to our current SchemaContext.
368 * @param payload Payload
369 * @throws IOException when the snapshot fails to deserialize
370 * @throws DataValidationFailedException when the snapshot fails to apply
372 void applyRecoveryPayload(final @NonNull Payload payload) throws IOException {
373 if (payload instanceof CommitTransactionPayload) {
374 applyRecoveryCandidate((CommitTransactionPayload) payload);
375 } else if (payload instanceof AbortTransactionPayload) {
376 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
377 } else if (payload instanceof PurgeTransactionPayload) {
378 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
379 } else if (payload instanceof CreateLocalHistoryPayload) {
380 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
381 } else if (payload instanceof CloseLocalHistoryPayload) {
382 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
383 } else if (payload instanceof PurgeLocalHistoryPayload) {
384 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
386 LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
390 private void applyReplicatedCandidate(final CommitTransactionPayload payload)
391 throws DataValidationFailedException, IOException {
392 final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> entry = payload.acquireCandidate();
393 final TransactionIdentifier identifier = entry.getKey();
394 LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
396 final DataTreeModification mod = dataTree.takeSnapshot().newModification();
397 // TODO: check version here, which will enable us to perform forward-compatibility transformations
398 DataTreeCandidates.applyToModification(mod, entry.getValue().getCandidate());
401 LOG.trace("{}: Applying foreign modification {}", logContext, mod);
402 dataTree.validate(mod);
403 final DataTreeCandidate candidate = dataTree.prepare(mod);
404 dataTree.commit(candidate);
406 allMetadataCommittedTransaction(identifier);
407 notifyListeners(candidate);
411 * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
412 * SchemaContexts match and does not perform any pruning.
414 * @param identifier Payload identifier as returned from RaftActor
415 * @param payload Payload
416 * @throws IOException when the snapshot fails to deserialize
417 * @throws DataValidationFailedException when the snapshot fails to apply
419 void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
420 DataValidationFailedException {
422 * 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
423 * if we are the leader and it has originated with us.
425 * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
426 * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
427 * acting in that capacity anymore.
429 * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
430 * pre-Boron state -- which limits the number of options here.
432 if (payload instanceof CommitTransactionPayload) {
433 if (identifier == null) {
434 applyReplicatedCandidate((CommitTransactionPayload) payload);
436 verify(identifier instanceof TransactionIdentifier);
437 // if we did not track this transaction before, it means that it came from another leader and we are in
438 // the process of commiting it while in PreLeader state. That means that it hasnt yet been committed to
439 // the local DataTree and would be lost if it was only applied via payloadReplicationComplete().
440 if (!payloadReplicationComplete((TransactionIdentifier) identifier)) {
441 applyReplicatedCandidate((CommitTransactionPayload) payload);
445 // make sure acquireCandidate() is the last call touching the payload data as we want it to be GC-ed.
446 checkRootOverwrite(((CommitTransactionPayload) payload).acquireCandidate().getValue()
448 } else if (payload instanceof AbortTransactionPayload) {
449 if (identifier != null) {
450 payloadReplicationComplete((AbortTransactionPayload) payload);
452 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
453 } else if (payload instanceof PurgeTransactionPayload) {
454 if (identifier != null) {
455 payloadReplicationComplete((PurgeTransactionPayload) payload);
457 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
458 } else if (payload instanceof CloseLocalHistoryPayload) {
459 if (identifier != null) {
460 payloadReplicationComplete((CloseLocalHistoryPayload) payload);
462 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
463 } else if (payload instanceof CreateLocalHistoryPayload) {
464 if (identifier != null) {
465 payloadReplicationComplete((CreateLocalHistoryPayload)payload);
467 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
468 } else if (payload instanceof PurgeLocalHistoryPayload) {
469 if (identifier != null) {
470 payloadReplicationComplete((PurgeLocalHistoryPayload)payload);
472 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
474 LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
478 private void checkRootOverwrite(final DataTreeCandidate candidate) {
479 final DatastoreContext datastoreContext = shard.getDatastoreContext();
480 if (!datastoreContext.isSnapshotOnRootOverwrite()) {
484 if (!datastoreContext.isPersistent()) {
485 // FIXME: why don't we want a snapshot in non-persistent state?
489 // top level container ie "/"
490 if (candidate.getRootPath().isEmpty()
491 && candidate.getRootNode().getModificationType() == ModificationType.WRITE) {
492 LOG.debug("{}: shard root overwritten, enqueuing snapshot", logContext);
493 shard.self().tell(new InitiateCaptureSnapshot(), noSender());
497 private void replicatePayload(final Identifier id, final Payload payload, final @Nullable Runnable callback) {
498 if (callback != null) {
499 replicationCallbacks.put(payload, callback);
501 shard.persistPayload(id, payload, true);
504 private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
505 final Runnable callback = replicationCallbacks.remove(payload);
506 if (callback != null) {
507 LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
510 LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
514 private boolean payloadReplicationComplete(final TransactionIdentifier txId) {
515 final CommitEntry current = pendingFinishCommits.peek();
516 if (current == null) {
517 LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
518 allMetadataCommittedTransaction(txId);
522 if (!current.cohort.getIdentifier().equals(txId)) {
523 LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
524 current.cohort.getIdentifier(), txId);
525 allMetadataCommittedTransaction(txId);
529 finishCommit(current.cohort);
533 private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
534 for (ShardDataTreeMetadata<?> m : metadata) {
535 m.onTransactionAborted(txId);
539 private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
540 for (ShardDataTreeMetadata<?> m : metadata) {
541 m.onTransactionCommitted(txId);
545 private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
546 for (ShardDataTreeMetadata<?> m : metadata) {
547 m.onTransactionPurged(txId);
551 private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
552 for (ShardDataTreeMetadata<?> m : metadata) {
553 m.onHistoryCreated(historyId);
557 private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
558 for (ShardDataTreeMetadata<?> m : metadata) {
559 m.onHistoryClosed(historyId);
563 private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
564 for (ShardDataTreeMetadata<?> m : metadata) {
565 m.onHistoryPurged(historyId);
570 * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
571 * this method is used for re-establishing state when we are taking over
573 * @param historyId Local history identifier
574 * @param closed True if the chain should be created in closed state (i.e. pending purge)
575 * @return Transaction chain handle
577 ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
578 final boolean closed) {
579 final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
580 final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
581 checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId, existing);
585 ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId,
586 final @Nullable Runnable callback) {
587 ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
589 chain = new ShardDataTreeTransactionChain(historyId, this);
590 transactionChains.put(historyId, chain);
591 replicatePayload(historyId, CreateLocalHistoryPayload.create(
592 historyId, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
593 } else if (callback != null) {
600 ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
601 shard.getShardMBean().incrementReadOnlyTransactionCount();
603 if (txId.getHistoryId().getHistoryId() == 0) {
604 return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
607 return ensureTransactionChain(txId.getHistoryId(), null).newReadOnlyTransaction(txId);
610 ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
611 shard.getShardMBean().incrementReadWriteTransactionCount();
613 if (txId.getHistoryId().getHistoryId() == 0) {
614 return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
618 return ensureTransactionChain(txId.getHistoryId(), null).newReadWriteTransaction(txId);
622 public void notifyListeners(final DataTreeCandidate candidate) {
623 treeChangeListenerPublisher.publishChanges(candidate);
627 * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
628 * replication callbacks.
630 void purgeLeaderState() {
631 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
635 transactionChains.clear();
636 replicationCallbacks.clear();
640 * Close a single transaction chain.
642 * @param id History identifier
643 * @param callback Callback to invoke upon completion, may be null
645 void closeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
646 if (commonCloseTransactionChain(id, callback)) {
647 replicatePayload(id, CloseLocalHistoryPayload.create(id,
648 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
653 * Close a single transaction chain which is received through ask-based protocol. It does not keep a commit record.
655 * @param id History identifier
657 void closeTransactionChain(final LocalHistoryIdentifier id) {
658 commonCloseTransactionChain(id, null);
661 private boolean commonCloseTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
662 final ShardDataTreeTransactionChain chain = transactionChains.get(id);
664 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
665 if (callback != null) {
676 * Purge a single transaction chain.
678 * @param id History identifier
679 * @param callback Callback to invoke upon completion, may be null
681 void purgeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
682 final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
684 LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
685 if (callback != null) {
691 replicatePayload(id, PurgeLocalHistoryPayload.create(
692 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
695 Optional<DataTreeCandidate> readCurrentData() {
696 return dataTree.takeSnapshot().readNode(YangInstanceIdentifier.empty())
697 .map(state -> DataTreeCandidates.fromNormalizedNode(YangInstanceIdentifier.empty(), state));
700 public void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
701 final Optional<DataTreeCandidate> initialState,
702 final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
703 treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
707 return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
711 void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
712 final TransactionIdentifier id = transaction.getIdentifier();
713 LOG.debug("{}: aborting transaction {}", logContext, id);
714 replicatePayload(id, AbortTransactionPayload.create(
715 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
719 void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
720 // No-op for free-standing transactions
725 ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction,
726 final Optional<SortedSet<String>> participatingShardNames) {
727 final DataTreeModification snapshot = transaction.getSnapshot();
728 final TransactionIdentifier id = transaction.getIdentifier();
729 LOG.debug("{}: readying transaction {}", logContext, id);
731 LOG.debug("{}: transaction {} ready", logContext, id);
733 return createReadyCohort(transaction.getIdentifier(), snapshot, participatingShardNames);
736 void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
737 LOG.debug("{}: purging transaction {}", logContext, id);
738 replicatePayload(id, PurgeTransactionPayload.create(
739 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
742 public Optional<NormalizedNode> readNode(final YangInstanceIdentifier path) {
743 return dataTree.takeSnapshot().readNode(path);
746 DataTreeSnapshot takeSnapshot() {
747 return dataTree.takeSnapshot();
751 public DataTreeModification newModification() {
752 return dataTree.takeSnapshot().newModification();
755 public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
756 Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
758 for (CommitEntry entry: pendingFinishCommits) {
759 ret.add(entry.cohort);
762 for (CommitEntry entry: pendingCommits) {
763 ret.add(entry.cohort);
766 for (CommitEntry entry: pendingTransactions) {
767 ret.add(entry.cohort);
770 pendingFinishCommits.clear();
771 pendingCommits.clear();
772 pendingTransactions.clear();
778 * Called some time after {@link #processNextPendingTransaction()} decides to stop processing.
780 void resumeNextPendingTransaction() {
781 LOG.debug("{}: attempting to resume transaction processing", logContext);
782 processNextPending();
785 @SuppressWarnings("checkstyle:IllegalCatch")
786 private void processNextPendingTransaction() {
787 ++currentTransactionBatch;
788 if (currentTransactionBatch > MAX_TRANSACTION_BATCH) {
789 LOG.debug("{}: Already processed {}, scheduling continuation", logContext, currentTransactionBatch);
790 shard.scheduleNextPendingTransaction();
794 processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
795 final SimpleShardDataTreeCohort cohort = entry.cohort;
796 final DataTreeModification modification = cohort.getDataTreeModification();
798 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
801 tip.validate(modification);
802 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
803 cohort.successfulCanCommit();
804 entry.lastAccess = readTime();
806 } catch (ConflictingModificationAppliedException e) {
807 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
809 cause = new OptimisticLockFailedException("Optimistic lock failed for path " + e.getPath(), e);
810 } catch (DataValidationFailedException e) {
811 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
814 // For debugging purposes, allow dumping of the modification. Coupled with the above
815 // precondition log, it should allow us to understand what went on.
816 LOG.debug("{}: Store Tx {}: modifications: {}", logContext, cohort.getIdentifier(), modification);
817 LOG.trace("{}: Current tree: {}", logContext, dataTree);
818 cause = new TransactionCommitFailedException("Data did not pass validation for path " + e.getPath(), e);
819 } catch (Exception e) {
820 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
824 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
825 pendingTransactions.poll().cohort.failedCanCommit(cause);
829 private void processNextPending() {
830 processNextPendingCommit();
831 processNextPendingTransaction();
834 private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
835 final Consumer<CommitEntry> processor) {
836 while (!queue.isEmpty()) {
837 final CommitEntry entry = queue.peek();
838 final SimpleShardDataTreeCohort cohort = entry.cohort;
840 if (cohort.isFailed()) {
841 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
846 if (cohort.getState() == allowedState) {
847 processor.accept(entry);
853 maybeRunOperationOnPendingTransactionsComplete();
856 private void processNextPendingCommit() {
857 processNextPending(pendingCommits, State.COMMIT_PENDING,
858 entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
861 private boolean peekNextPendingCommit() {
862 final CommitEntry first = pendingCommits.peek();
863 return first != null && first.cohort.getState() == State.COMMIT_PENDING;
866 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
867 final CommitEntry head = pendingTransactions.peek();
869 LOG.warn("{}: No transactions enqueued while attempting to start canCommit on {}", logContext, cohort);
872 if (!cohort.equals(head.cohort)) {
873 // The tx isn't at the head of the queue so we can't start canCommit at this point. Here we check if this
874 // tx should be moved ahead of other tx's in the READY state in the pendingTransactions queue. If this tx
875 // has other participating shards, it could deadlock with other tx's accessing the same shards
876 // depending on the order the tx's are readied on each shard
877 // (see https://jira.opendaylight.org/browse/CONTROLLER-1836). Therefore, if the preceding participating
878 // shard names for a preceding pending tx, call it A, in the queue matches that of this tx, then this tx
879 // is allowed to be moved ahead of tx A in the queue so it is processed first to avoid potential deadlock
880 // if tx A is behind this tx in the pendingTransactions queue for a preceding shard. In other words, since
881 // canCommmit for this tx was requested before tx A, honor that request. If this tx is moved to the head of
882 // the queue as a result, then proceed with canCommit.
884 Collection<String> precedingShardNames = extractPrecedingShardNames(cohort.getParticipatingShardNames());
885 if (precedingShardNames.isEmpty()) {
886 LOG.debug("{}: Tx {} is scheduled for canCommit step", logContext, cohort.getIdentifier());
890 LOG.debug("{}: Evaluating tx {} for canCommit - preceding participating shard names {}",
891 logContext, cohort.getIdentifier(), precedingShardNames);
892 final Iterator<CommitEntry> iter = pendingTransactions.iterator();
894 int moveToIndex = -1;
895 while (iter.hasNext()) {
896 final CommitEntry entry = iter.next();
899 if (cohort.equals(entry.cohort)) {
900 if (moveToIndex < 0) {
901 LOG.debug("{}: Not moving tx {} - cannot proceed with canCommit",
902 logContext, cohort.getIdentifier());
906 LOG.debug("{}: Moving {} to index {} in the pendingTransactions queue",
907 logContext, cohort.getIdentifier(), moveToIndex);
909 insertEntry(pendingTransactions, entry, moveToIndex);
911 if (!cohort.equals(pendingTransactions.peek().cohort)) {
912 LOG.debug("{}: Tx {} is not at the head of the queue - cannot proceed with canCommit",
913 logContext, cohort.getIdentifier());
917 LOG.debug("{}: Tx {} is now at the head of the queue - proceeding with canCommit",
918 logContext, cohort.getIdentifier());
922 if (entry.cohort.getState() != State.READY) {
923 LOG.debug("{}: Skipping pending transaction {} in state {}",
924 logContext, entry.cohort.getIdentifier(), entry.cohort.getState());
928 final Collection<String> pendingPrecedingShardNames = extractPrecedingShardNames(
929 entry.cohort.getParticipatingShardNames());
931 if (precedingShardNames.equals(pendingPrecedingShardNames)) {
932 if (moveToIndex < 0) {
933 LOG.debug("{}: Preceding shard names {} for pending tx {} match - saving moveToIndex {}",
934 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), index);
938 "{}: Preceding shard names {} for pending tx {} match but moveToIndex already set to {}",
939 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), moveToIndex);
942 LOG.debug("{}: Preceding shard names {} for pending tx {} differ - skipping",
943 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier());
948 processNextPendingTransaction();
951 private static void insertEntry(final Deque<CommitEntry> queue, final CommitEntry entry, final int atIndex) {
953 queue.addFirst(entry);
957 LOG.trace("Inserting into Deque at index {}", atIndex);
959 Deque<CommitEntry> tempStack = new ArrayDeque<>(atIndex);
960 for (int i = 0; i < atIndex; i++) {
961 tempStack.push(queue.poll());
964 queue.addFirst(entry);
966 tempStack.forEach(queue::addFirst);
969 private Collection<String> extractPrecedingShardNames(final Optional<SortedSet<String>> participatingShardNames) {
970 return participatingShardNames.map((Function<SortedSet<String>, Collection<String>>)
971 set -> set.headSet(shard.getShardName())).orElse(Collections.<String>emptyList());
974 private void failPreCommit(final Throwable cause) {
975 shard.getShardMBean().incrementFailedTransactionsCount();
976 pendingTransactions.poll().cohort.failedPreCommit(cause);
977 processNextPendingTransaction();
980 @SuppressWarnings("checkstyle:IllegalCatch")
981 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
982 final CommitEntry entry = pendingTransactions.peek();
983 checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
985 final SimpleShardDataTreeCohort current = entry.cohort;
986 verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
988 final TransactionIdentifier currentId = current.getIdentifier();
989 LOG.debug("{}: Preparing transaction {}", logContext, currentId);
991 final DataTreeCandidateTip candidate;
993 candidate = tip.prepare(cohort.getDataTreeModification());
994 LOG.debug("{}: Transaction {} candidate ready", logContext, currentId);
995 } catch (DataValidationFailedException | RuntimeException e) {
1000 cohort.userPreCommit(candidate, new FutureCallback<Void>() {
1002 public void onSuccess(final Void noop) {
1003 // Set the tip of the data tree.
1004 tip = verifyNotNull(candidate);
1006 entry.lastAccess = readTime();
1008 pendingTransactions.remove();
1009 pendingCommits.add(entry);
1011 LOG.debug("{}: Transaction {} prepared", logContext, currentId);
1013 cohort.successfulPreCommit(candidate);
1015 processNextPendingTransaction();
1019 public void onFailure(final Throwable failure) {
1020 failPreCommit(failure);
1025 private void failCommit(final Exception cause) {
1026 shard.getShardMBean().incrementFailedTransactionsCount();
1027 pendingFinishCommits.poll().cohort.failedCommit(cause);
1028 processNextPending();
1031 @SuppressWarnings("checkstyle:IllegalCatch")
1032 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
1033 final TransactionIdentifier txId = cohort.getIdentifier();
1034 final DataTreeCandidate candidate = cohort.getCandidate();
1036 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
1038 if (tip == candidate) {
1039 // All pending candidates have been committed, reset the tip to the data tree.
1044 dataTree.commit(candidate);
1045 } catch (Exception e) {
1046 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
1051 allMetadataCommittedTransaction(txId);
1052 shard.getShardMBean().incrementCommittedTransactionCount();
1053 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
1055 // FIXME: propagate journal index
1056 pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO, () -> {
1057 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
1058 notifyListeners(candidate);
1060 processNextPending();
1064 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
1065 final CommitEntry entry = pendingCommits.peek();
1066 checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
1068 final SimpleShardDataTreeCohort current = entry.cohort;
1069 if (!cohort.equals(current)) {
1070 LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
1074 LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
1076 final TransactionIdentifier txId = cohort.getIdentifier();
1077 final Payload payload;
1079 payload = CommitTransactionPayload.create(txId, candidate, PayloadVersion.current(),
1080 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity());
1081 } catch (IOException e) {
1082 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
1083 pendingCommits.poll().cohort.failedCommit(e);
1084 processNextPending();
1088 // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
1089 // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
1090 // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
1091 // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
1092 // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
1093 // pendingCommits queue.
1094 processNextPendingTransaction();
1096 // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
1097 // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
1098 // in order to properly determine the batchHint flag for the call to persistPayload.
1099 pendingCommits.remove();
1100 pendingFinishCommits.add(entry);
1102 // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
1103 // this transaction for replication.
1104 boolean replicationBatchHint = peekNextPendingCommit();
1106 // Once completed, we will continue via payloadReplicationComplete
1107 shard.persistPayload(txId, payload, replicationBatchHint);
1109 entry.lastAccess = shard.ticker().read();
1111 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
1113 // Process the next transaction pending commit, if any. If there is one it will be batched with this
1114 // transaction for replication.
1115 processNextPendingCommit();
1118 Collection<ActorRef> getCohortActors() {
1119 return cohortRegistry.getCohortActors();
1122 void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
1123 cohortRegistry.process(sender, message);
1127 ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1128 final Exception failure) {
1129 final SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId, failure);
1130 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1135 ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1136 final Optional<SortedSet<String>> participatingShardNames) {
1137 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId,
1138 cohortRegistry.createCohort(schemaContext, txId, shard::executeInSelf,
1139 COMMIT_STEP_TIMEOUT), participatingShardNames);
1140 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1144 // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
1145 // the newReadWriteTransaction()
1146 ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1147 final Optional<SortedSet<String>> participatingShardNames) {
1148 if (txId.getHistoryId().getHistoryId() == 0) {
1149 return createReadyCohort(txId, mod, participatingShardNames);
1152 return ensureTransactionChain(txId.getHistoryId(), null).createReadyCohort(txId, mod, participatingShardNames);
1155 @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
1156 void checkForExpiredTransactions(final long transactionCommitTimeoutMillis,
1157 final Function<SimpleShardDataTreeCohort, OptionalLong> accessTimeUpdater) {
1158 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
1159 final long now = readTime();
1161 final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
1162 !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
1163 final CommitEntry currentTx = currentQueue.peek();
1164 if (currentTx == null) {
1165 // Empty queue, no-op
1169 long delta = now - currentTx.lastAccess;
1170 if (delta < timeout) {
1171 // Not expired yet, bail
1175 final OptionalLong updateOpt = accessTimeUpdater.apply(currentTx.cohort);
1176 if (updateOpt.isPresent()) {
1177 final long newAccess = updateOpt.getAsLong();
1178 final long newDelta = now - newAccess;
1179 if (newDelta < delta) {
1180 LOG.debug("{}: Updated current transaction {} access time", logContext,
1181 currentTx.cohort.getIdentifier());
1182 currentTx.lastAccess = newAccess;
1186 if (delta < timeout) {
1187 // Not expired yet, bail
1192 final long deltaMillis = TimeUnit.NANOSECONDS.toMillis(delta);
1193 final State state = currentTx.cohort.getState();
1195 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
1196 currentTx.cohort.getIdentifier(), deltaMillis, state);
1197 boolean processNext = true;
1198 final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
1199 + deltaMillis + "ms");
1202 case CAN_COMMIT_PENDING:
1203 currentQueue.remove().cohort.failedCanCommit(cohortFailure);
1205 case CAN_COMMIT_COMPLETE:
1206 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
1207 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
1208 // in PRE_COMMIT_COMPLETE is changed.
1209 currentQueue.remove().cohort.reportFailure(cohortFailure);
1211 case PRE_COMMIT_PENDING:
1212 currentQueue.remove().cohort.failedPreCommit(cohortFailure);
1214 case PRE_COMMIT_COMPLETE:
1215 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
1216 // are ready we should commit the transaction, not abort it. Our current software stack does
1217 // not allow us to do that consistently, because we persist at the time of commit, hence
1218 // we can end up in a state where we have pre-committed a transaction, then a leader failover
1219 // occurred ... the new leader does not see the pre-committed transaction and does not have
1220 // a running timer. To fix this we really need two persistence events.
1222 // The first one, done at pre-commit time will hold the transaction payload. When consensus
1223 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1224 // apply the state in this event.
1226 // The second one, done at commit (or abort) time holds only the transaction identifier and
1227 // signals to followers that the state should (or should not) be applied.
1229 // In order to make the pre-commit timer working across failovers, though, we need
1230 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1231 // restart the timer.
1232 currentQueue.remove().cohort.reportFailure(cohortFailure);
1234 case COMMIT_PENDING:
1235 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1236 currentTx.cohort.getIdentifier());
1237 currentTx.lastAccess = now;
1238 processNext = false;
1241 currentQueue.remove().cohort.reportFailure(cohortFailure);
1247 currentQueue.remove();
1251 processNextPending();
1255 boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1256 final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1257 pendingTransactions).iterator();
1258 if (!it.hasNext()) {
1259 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1263 // First entry is special, as it may already be committing
1264 final CommitEntry first = it.next();
1265 if (cohort.equals(first.cohort)) {
1266 if (cohort.getState() != State.COMMIT_PENDING) {
1267 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1268 cohort.getIdentifier());
1271 if (cohort.getCandidate() != null) {
1272 rebaseTransactions(it, dataTree);
1275 processNextPending();
1279 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1283 DataTreeTip newTip = requireNonNullElse(first.cohort.getCandidate(), dataTree);
1284 while (it.hasNext()) {
1285 final CommitEntry e = it.next();
1286 if (cohort.equals(e.cohort)) {
1287 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1290 if (cohort.getCandidate() != null) {
1291 rebaseTransactions(it, newTip);
1296 newTip = requireNonNullElse(e.cohort.getCandidate(), newTip);
1300 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1304 @SuppressWarnings("checkstyle:IllegalCatch")
1305 private void rebaseTransactions(final Iterator<CommitEntry> iter, final @NonNull DataTreeTip newTip) {
1306 tip = requireNonNull(newTip);
1307 while (iter.hasNext()) {
1308 final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1309 if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1310 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1313 tip.validate(cohort.getDataTreeModification());
1314 } catch (DataValidationFailedException | RuntimeException e) {
1315 LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1316 cohort.reportFailure(e);
1318 } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1319 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1322 tip.validate(cohort.getDataTreeModification());
1323 DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1325 cohort.setNewCandidate(candidate);
1327 } catch (RuntimeException | DataValidationFailedException e) {
1328 LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1329 cohort.reportFailure(e);
1335 void setRunOnPendingTransactionsComplete(final Runnable operation) {
1336 runOnPendingTransactionsComplete = operation;
1337 maybeRunOperationOnPendingTransactionsComplete();
1340 private void maybeRunOperationOnPendingTransactionsComplete() {
1341 if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1342 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1343 runOnPendingTransactionsComplete);
1345 runOnPendingTransactionsComplete.run();
1346 runOnPendingTransactionsComplete = null;
1350 ShardStats getStats() {
1351 return shard.getShardMBean();
1354 Iterator<SimpleShardDataTreeCohort> cohortIterator() {
1355 return Iterables.transform(Iterables.concat(pendingFinishCommits, pendingCommits, pendingTransactions),
1356 e -> e.cohort).iterator();
1359 void removeTransactionChain(final LocalHistoryIdentifier id) {
1360 if (transactionChains.remove(id) != null) {
1361 LOG.debug("{}: Removed transaction chain {}", logContext, id);