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.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.getCandidate();
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(DataTreeCandidate candidate) {
479 final DatastoreContext datastoreContext = shard.getDatastoreContext();
480 if (!datastoreContext.isSnapshotOnRootOverwrite()) {
484 if (!datastoreContext.isPersistent()) {
488 if (candidate.getRootNode().getModificationType().equals(ModificationType.UNMODIFIED)) {
492 // top level container ie "/"
493 if ((candidate.getRootPath().equals(YangInstanceIdentifier.empty())
494 && candidate.getRootNode().getModificationType().equals(ModificationType.WRITE))) {
495 LOG.debug("{}: shard root overwritten, enqueuing snapshot", logContext);
496 shard.self().tell(new InitiateCaptureSnapshot(), noSender());
501 private void replicatePayload(final Identifier id, final Payload payload, final @Nullable Runnable callback) {
502 if (callback != null) {
503 replicationCallbacks.put(payload, callback);
505 shard.persistPayload(id, payload, true);
508 private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
509 final Runnable callback = replicationCallbacks.remove(payload);
510 if (callback != null) {
511 LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
514 LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
518 private boolean payloadReplicationComplete(final TransactionIdentifier txId) {
519 final CommitEntry current = pendingFinishCommits.peek();
520 if (current == null) {
521 LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
522 allMetadataCommittedTransaction(txId);
526 if (!current.cohort.getIdentifier().equals(txId)) {
527 LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
528 current.cohort.getIdentifier(), txId);
529 allMetadataCommittedTransaction(txId);
533 finishCommit(current.cohort);
537 private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
538 for (ShardDataTreeMetadata<?> m : metadata) {
539 m.onTransactionAborted(txId);
543 private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
544 for (ShardDataTreeMetadata<?> m : metadata) {
545 m.onTransactionCommitted(txId);
549 private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
550 for (ShardDataTreeMetadata<?> m : metadata) {
551 m.onTransactionPurged(txId);
555 private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
556 for (ShardDataTreeMetadata<?> m : metadata) {
557 m.onHistoryCreated(historyId);
561 private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
562 for (ShardDataTreeMetadata<?> m : metadata) {
563 m.onHistoryClosed(historyId);
567 private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
568 for (ShardDataTreeMetadata<?> m : metadata) {
569 m.onHistoryPurged(historyId);
574 * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
575 * this method is used for re-establishing state when we are taking over
577 * @param historyId Local history identifier
578 * @param closed True if the chain should be created in closed state (i.e. pending purge)
579 * @return Transaction chain handle
581 ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
582 final boolean closed) {
583 final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
584 final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
585 checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId, existing);
589 ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId,
590 final @Nullable Runnable callback) {
591 ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
593 chain = new ShardDataTreeTransactionChain(historyId, this);
594 transactionChains.put(historyId, chain);
595 replicatePayload(historyId, CreateLocalHistoryPayload.create(
596 historyId, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
597 } else if (callback != null) {
604 ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
605 shard.getShardMBean().incrementReadOnlyTransactionCount();
607 if (txId.getHistoryId().getHistoryId() == 0) {
608 return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
611 return ensureTransactionChain(txId.getHistoryId(), null).newReadOnlyTransaction(txId);
614 ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
615 shard.getShardMBean().incrementReadWriteTransactionCount();
617 if (txId.getHistoryId().getHistoryId() == 0) {
618 return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
622 return ensureTransactionChain(txId.getHistoryId(), null).newReadWriteTransaction(txId);
626 public void notifyListeners(final DataTreeCandidate candidate) {
627 treeChangeListenerPublisher.publishChanges(candidate);
631 * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
632 * replication callbacks.
634 void purgeLeaderState() {
635 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
639 transactionChains.clear();
640 replicationCallbacks.clear();
644 * Close a single transaction chain.
646 * @param id History identifier
647 * @param callback Callback to invoke upon completion, may be null
649 void closeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
650 if (commonCloseTransactionChain(id, callback)) {
651 replicatePayload(id, CloseLocalHistoryPayload.create(id,
652 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
657 * Close a single transaction chain which is received through ask-based protocol. It does not keep a commit record.
659 * @param id History identifier
661 void closeTransactionChain(final LocalHistoryIdentifier id) {
662 commonCloseTransactionChain(id, null);
665 private boolean commonCloseTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
666 final ShardDataTreeTransactionChain chain = transactionChains.get(id);
668 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
669 if (callback != null) {
680 * Purge a single transaction chain.
682 * @param id History identifier
683 * @param callback Callback to invoke upon completion, may be null
685 void purgeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
686 final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
688 LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
689 if (callback != null) {
695 replicatePayload(id, PurgeLocalHistoryPayload.create(
696 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
699 Optional<DataTreeCandidate> readCurrentData() {
700 return dataTree.takeSnapshot().readNode(YangInstanceIdentifier.empty())
701 .map(state -> DataTreeCandidates.fromNormalizedNode(YangInstanceIdentifier.empty(), state));
704 public void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
705 final Optional<DataTreeCandidate> initialState,
706 final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
707 treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
711 return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
715 void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
716 final TransactionIdentifier id = transaction.getIdentifier();
717 LOG.debug("{}: aborting transaction {}", logContext, id);
718 replicatePayload(id, AbortTransactionPayload.create(
719 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
723 void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
724 // No-op for free-standing transactions
729 ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction,
730 final Optional<SortedSet<String>> participatingShardNames) {
731 final DataTreeModification snapshot = transaction.getSnapshot();
732 final TransactionIdentifier id = transaction.getIdentifier();
733 LOG.debug("{}: readying transaction {}", logContext, id);
735 LOG.debug("{}: transaction {} ready", logContext, id);
737 return createReadyCohort(transaction.getIdentifier(), snapshot, participatingShardNames);
740 void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
741 LOG.debug("{}: purging transaction {}", logContext, id);
742 replicatePayload(id, PurgeTransactionPayload.create(
743 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
746 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
747 return dataTree.takeSnapshot().readNode(path);
750 DataTreeSnapshot takeSnapshot() {
751 return dataTree.takeSnapshot();
755 public DataTreeModification newModification() {
756 return dataTree.takeSnapshot().newModification();
759 public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
760 Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
762 for (CommitEntry entry: pendingFinishCommits) {
763 ret.add(entry.cohort);
766 for (CommitEntry entry: pendingCommits) {
767 ret.add(entry.cohort);
770 for (CommitEntry entry: pendingTransactions) {
771 ret.add(entry.cohort);
774 pendingFinishCommits.clear();
775 pendingCommits.clear();
776 pendingTransactions.clear();
782 * Called some time after {@link #processNextPendingTransaction()} decides to stop processing.
784 void resumeNextPendingTransaction() {
785 LOG.debug("{}: attempting to resume transaction processing", logContext);
786 processNextPending();
789 @SuppressWarnings("checkstyle:IllegalCatch")
790 private void processNextPendingTransaction() {
791 ++currentTransactionBatch;
792 if (currentTransactionBatch > MAX_TRANSACTION_BATCH) {
793 LOG.debug("{}: Already processed {}, scheduling continuation", logContext, currentTransactionBatch);
794 shard.scheduleNextPendingTransaction();
798 processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
799 final SimpleShardDataTreeCohort cohort = entry.cohort;
800 final DataTreeModification modification = cohort.getDataTreeModification();
802 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
805 tip.validate(modification);
806 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
807 cohort.successfulCanCommit();
808 entry.lastAccess = readTime();
810 } catch (ConflictingModificationAppliedException e) {
811 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
813 cause = new OptimisticLockFailedException("Optimistic lock failed for path " + e.getPath(), e);
814 } catch (DataValidationFailedException e) {
815 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
818 // For debugging purposes, allow dumping of the modification. Coupled with the above
819 // precondition log, it should allow us to understand what went on.
820 LOG.debug("{}: Store Tx {}: modifications: {}", logContext, cohort.getIdentifier(), modification);
821 LOG.trace("{}: Current tree: {}", logContext, dataTree);
822 cause = new TransactionCommitFailedException("Data did not pass validation for path " + e.getPath(), e);
823 } catch (Exception e) {
824 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
828 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
829 pendingTransactions.poll().cohort.failedCanCommit(cause);
833 private void processNextPending() {
834 processNextPendingCommit();
835 processNextPendingTransaction();
838 private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
839 final Consumer<CommitEntry> processor) {
840 while (!queue.isEmpty()) {
841 final CommitEntry entry = queue.peek();
842 final SimpleShardDataTreeCohort cohort = entry.cohort;
844 if (cohort.isFailed()) {
845 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
850 if (cohort.getState() == allowedState) {
851 processor.accept(entry);
857 maybeRunOperationOnPendingTransactionsComplete();
860 private void processNextPendingCommit() {
861 processNextPending(pendingCommits, State.COMMIT_PENDING,
862 entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
865 private boolean peekNextPendingCommit() {
866 final CommitEntry first = pendingCommits.peek();
867 return first != null && first.cohort.getState() == State.COMMIT_PENDING;
870 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
871 final CommitEntry head = pendingTransactions.peek();
873 LOG.warn("{}: No transactions enqueued while attempting to start canCommit on {}", logContext, cohort);
876 if (!cohort.equals(head.cohort)) {
877 // The tx isn't at the head of the queue so we can't start canCommit at this point. Here we check if this
878 // tx should be moved ahead of other tx's in the READY state in the pendingTransactions queue. If this tx
879 // has other participating shards, it could deadlock with other tx's accessing the same shards
880 // depending on the order the tx's are readied on each shard
881 // (see https://jira.opendaylight.org/browse/CONTROLLER-1836). Therefore, if the preceding participating
882 // shard names for a preceding pending tx, call it A, in the queue matches that of this tx, then this tx
883 // is allowed to be moved ahead of tx A in the queue so it is processed first to avoid potential deadlock
884 // if tx A is behind this tx in the pendingTransactions queue for a preceding shard. In other words, since
885 // canCommmit for this tx was requested before tx A, honor that request. If this tx is moved to the head of
886 // the queue as a result, then proceed with canCommit.
888 Collection<String> precedingShardNames = extractPrecedingShardNames(cohort.getParticipatingShardNames());
889 if (precedingShardNames.isEmpty()) {
890 LOG.debug("{}: Tx {} is scheduled for canCommit step", logContext, cohort.getIdentifier());
894 LOG.debug("{}: Evaluating tx {} for canCommit - preceding participating shard names {}",
895 logContext, cohort.getIdentifier(), precedingShardNames);
896 final Iterator<CommitEntry> iter = pendingTransactions.iterator();
898 int moveToIndex = -1;
899 while (iter.hasNext()) {
900 final CommitEntry entry = iter.next();
903 if (cohort.equals(entry.cohort)) {
904 if (moveToIndex < 0) {
905 LOG.debug("{}: Not moving tx {} - cannot proceed with canCommit",
906 logContext, cohort.getIdentifier());
910 LOG.debug("{}: Moving {} to index {} in the pendingTransactions queue",
911 logContext, cohort.getIdentifier(), moveToIndex);
913 insertEntry(pendingTransactions, entry, moveToIndex);
915 if (!cohort.equals(pendingTransactions.peek().cohort)) {
916 LOG.debug("{}: Tx {} is not at the head of the queue - cannot proceed with canCommit",
917 logContext, cohort.getIdentifier());
921 LOG.debug("{}: Tx {} is now at the head of the queue - proceeding with canCommit",
922 logContext, cohort.getIdentifier());
926 if (entry.cohort.getState() != State.READY) {
927 LOG.debug("{}: Skipping pending transaction {} in state {}",
928 logContext, entry.cohort.getIdentifier(), entry.cohort.getState());
932 final Collection<String> pendingPrecedingShardNames = extractPrecedingShardNames(
933 entry.cohort.getParticipatingShardNames());
935 if (precedingShardNames.equals(pendingPrecedingShardNames)) {
936 if (moveToIndex < 0) {
937 LOG.debug("{}: Preceding shard names {} for pending tx {} match - saving moveToIndex {}",
938 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), index);
942 "{}: Preceding shard names {} for pending tx {} match but moveToIndex already set to {}",
943 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), moveToIndex);
946 LOG.debug("{}: Preceding shard names {} for pending tx {} differ - skipping",
947 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier());
952 processNextPendingTransaction();
955 private static void insertEntry(final Deque<CommitEntry> queue, final CommitEntry entry, final int atIndex) {
957 queue.addFirst(entry);
961 LOG.trace("Inserting into Deque at index {}", atIndex);
963 Deque<CommitEntry> tempStack = new ArrayDeque<>(atIndex);
964 for (int i = 0; i < atIndex; i++) {
965 tempStack.push(queue.poll());
968 queue.addFirst(entry);
970 tempStack.forEach(queue::addFirst);
973 private Collection<String> extractPrecedingShardNames(final Optional<SortedSet<String>> participatingShardNames) {
974 return participatingShardNames.map((Function<SortedSet<String>, Collection<String>>)
975 set -> set.headSet(shard.getShardName())).orElse(Collections.<String>emptyList());
978 private void failPreCommit(final Throwable cause) {
979 shard.getShardMBean().incrementFailedTransactionsCount();
980 pendingTransactions.poll().cohort.failedPreCommit(cause);
981 processNextPendingTransaction();
984 @SuppressWarnings("checkstyle:IllegalCatch")
985 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
986 final CommitEntry entry = pendingTransactions.peek();
987 checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
989 final SimpleShardDataTreeCohort current = entry.cohort;
990 verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
992 final TransactionIdentifier currentId = current.getIdentifier();
993 LOG.debug("{}: Preparing transaction {}", logContext, currentId);
995 final DataTreeCandidateTip candidate;
997 candidate = tip.prepare(cohort.getDataTreeModification());
998 LOG.debug("{}: Transaction {} candidate ready", logContext, currentId);
999 } catch (DataValidationFailedException | RuntimeException e) {
1004 cohort.userPreCommit(candidate, new FutureCallback<Void>() {
1006 public void onSuccess(final Void noop) {
1007 // Set the tip of the data tree.
1008 tip = verifyNotNull(candidate);
1010 entry.lastAccess = readTime();
1012 pendingTransactions.remove();
1013 pendingCommits.add(entry);
1015 LOG.debug("{}: Transaction {} prepared", logContext, currentId);
1017 cohort.successfulPreCommit(candidate);
1019 processNextPendingTransaction();
1023 public void onFailure(final Throwable failure) {
1024 failPreCommit(failure);
1029 private void failCommit(final Exception cause) {
1030 shard.getShardMBean().incrementFailedTransactionsCount();
1031 pendingFinishCommits.poll().cohort.failedCommit(cause);
1032 processNextPending();
1035 @SuppressWarnings("checkstyle:IllegalCatch")
1036 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
1037 final TransactionIdentifier txId = cohort.getIdentifier();
1038 final DataTreeCandidate candidate = cohort.getCandidate();
1040 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
1042 if (tip == candidate) {
1043 // All pending candidates have been committed, reset the tip to the data tree.
1048 dataTree.commit(candidate);
1049 } catch (Exception e) {
1050 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
1055 allMetadataCommittedTransaction(txId);
1056 shard.getShardMBean().incrementCommittedTransactionCount();
1057 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
1059 // FIXME: propagate journal index
1060 pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO, () -> {
1061 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
1062 notifyListeners(candidate);
1064 processNextPending();
1068 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
1069 final CommitEntry entry = pendingCommits.peek();
1070 checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
1072 final SimpleShardDataTreeCohort current = entry.cohort;
1073 if (!cohort.equals(current)) {
1074 LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
1078 LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
1080 final TransactionIdentifier txId = cohort.getIdentifier();
1081 final Payload payload;
1083 payload = CommitTransactionPayload.create(txId, candidate, PayloadVersion.current(),
1084 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity());
1085 } catch (IOException e) {
1086 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
1087 pendingCommits.poll().cohort.failedCommit(e);
1088 processNextPending();
1092 // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
1093 // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
1094 // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
1095 // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
1096 // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
1097 // pendingCommits queue.
1098 processNextPendingTransaction();
1100 // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
1101 // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
1102 // in order to properly determine the batchHint flag for the call to persistPayload.
1103 pendingCommits.remove();
1104 pendingFinishCommits.add(entry);
1106 // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
1107 // this transaction for replication.
1108 boolean replicationBatchHint = peekNextPendingCommit();
1110 // Once completed, we will continue via payloadReplicationComplete
1111 shard.persistPayload(txId, payload, replicationBatchHint);
1113 entry.lastAccess = shard.ticker().read();
1115 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
1117 // Process the next transaction pending commit, if any. If there is one it will be batched with this
1118 // transaction for replication.
1119 processNextPendingCommit();
1122 Collection<ActorRef> getCohortActors() {
1123 return cohortRegistry.getCohortActors();
1126 void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
1127 cohortRegistry.process(sender, message);
1131 ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1132 final Exception failure) {
1133 final SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId, failure);
1134 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1139 ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1140 final Optional<SortedSet<String>> participatingShardNames) {
1141 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId,
1142 cohortRegistry.createCohort(schemaContext, txId, shard::executeInSelf,
1143 COMMIT_STEP_TIMEOUT), participatingShardNames);
1144 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1148 // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
1149 // the newReadWriteTransaction()
1150 ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1151 final Optional<SortedSet<String>> participatingShardNames) {
1152 if (txId.getHistoryId().getHistoryId() == 0) {
1153 return createReadyCohort(txId, mod, participatingShardNames);
1156 return ensureTransactionChain(txId.getHistoryId(), null).createReadyCohort(txId, mod, participatingShardNames);
1159 @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
1160 void checkForExpiredTransactions(final long transactionCommitTimeoutMillis,
1161 final Function<SimpleShardDataTreeCohort, OptionalLong> accessTimeUpdater) {
1162 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
1163 final long now = readTime();
1165 final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
1166 !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
1167 final CommitEntry currentTx = currentQueue.peek();
1168 if (currentTx == null) {
1169 // Empty queue, no-op
1173 long delta = now - currentTx.lastAccess;
1174 if (delta < timeout) {
1175 // Not expired yet, bail
1179 final OptionalLong updateOpt = accessTimeUpdater.apply(currentTx.cohort);
1180 if (updateOpt.isPresent()) {
1181 final long newAccess = updateOpt.getAsLong();
1182 final long newDelta = now - newAccess;
1183 if (newDelta < delta) {
1184 LOG.debug("{}: Updated current transaction {} access time", logContext,
1185 currentTx.cohort.getIdentifier());
1186 currentTx.lastAccess = newAccess;
1190 if (delta < timeout) {
1191 // Not expired yet, bail
1196 final long deltaMillis = TimeUnit.NANOSECONDS.toMillis(delta);
1197 final State state = currentTx.cohort.getState();
1199 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
1200 currentTx.cohort.getIdentifier(), deltaMillis, state);
1201 boolean processNext = true;
1202 final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
1203 + deltaMillis + "ms");
1206 case CAN_COMMIT_PENDING:
1207 currentQueue.remove().cohort.failedCanCommit(cohortFailure);
1209 case CAN_COMMIT_COMPLETE:
1210 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
1211 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
1212 // in PRE_COMMIT_COMPLETE is changed.
1213 currentQueue.remove().cohort.reportFailure(cohortFailure);
1215 case PRE_COMMIT_PENDING:
1216 currentQueue.remove().cohort.failedPreCommit(cohortFailure);
1218 case PRE_COMMIT_COMPLETE:
1219 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
1220 // are ready we should commit the transaction, not abort it. Our current software stack does
1221 // not allow us to do that consistently, because we persist at the time of commit, hence
1222 // we can end up in a state where we have pre-committed a transaction, then a leader failover
1223 // occurred ... the new leader does not see the pre-committed transaction and does not have
1224 // a running timer. To fix this we really need two persistence events.
1226 // The first one, done at pre-commit time will hold the transaction payload. When consensus
1227 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1228 // apply the state in this event.
1230 // The second one, done at commit (or abort) time holds only the transaction identifier and
1231 // signals to followers that the state should (or should not) be applied.
1233 // In order to make the pre-commit timer working across failovers, though, we need
1234 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1235 // restart the timer.
1236 currentQueue.remove().cohort.reportFailure(cohortFailure);
1238 case COMMIT_PENDING:
1239 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1240 currentTx.cohort.getIdentifier());
1241 currentTx.lastAccess = now;
1242 processNext = false;
1245 currentQueue.remove().cohort.reportFailure(cohortFailure);
1251 currentQueue.remove();
1255 processNextPending();
1259 boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1260 final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1261 pendingTransactions).iterator();
1262 if (!it.hasNext()) {
1263 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1267 // First entry is special, as it may already be committing
1268 final CommitEntry first = it.next();
1269 if (cohort.equals(first.cohort)) {
1270 if (cohort.getState() != State.COMMIT_PENDING) {
1271 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1272 cohort.getIdentifier());
1275 if (cohort.getCandidate() != null) {
1276 rebaseTransactions(it, dataTree);
1279 processNextPending();
1283 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1287 DataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
1288 while (it.hasNext()) {
1289 final CommitEntry e = it.next();
1290 if (cohort.equals(e.cohort)) {
1291 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1294 if (cohort.getCandidate() != null) {
1295 rebaseTransactions(it, newTip);
1300 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), newTip);
1304 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1308 @SuppressWarnings("checkstyle:IllegalCatch")
1309 private void rebaseTransactions(final Iterator<CommitEntry> iter, final @NonNull DataTreeTip newTip) {
1310 tip = requireNonNull(newTip);
1311 while (iter.hasNext()) {
1312 final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1313 if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1314 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1317 tip.validate(cohort.getDataTreeModification());
1318 } catch (DataValidationFailedException | RuntimeException e) {
1319 LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1320 cohort.reportFailure(e);
1322 } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1323 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1326 tip.validate(cohort.getDataTreeModification());
1327 DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1329 cohort.setNewCandidate(candidate);
1331 } catch (RuntimeException | DataValidationFailedException e) {
1332 LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1333 cohort.reportFailure(e);
1339 void setRunOnPendingTransactionsComplete(final Runnable operation) {
1340 runOnPendingTransactionsComplete = operation;
1341 maybeRunOperationOnPendingTransactionsComplete();
1344 private void maybeRunOperationOnPendingTransactionsComplete() {
1345 if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1346 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1347 runOnPendingTransactionsComplete);
1349 runOnPendingTransactionsComplete.run();
1350 runOnPendingTransactionsComplete = null;
1354 ShardStats getStats() {
1355 return shard.getShardMBean();
1358 Iterator<SimpleShardDataTreeCohort> cohortIterator() {
1359 return Iterables.transform(Iterables.concat(pendingFinishCommits, pendingCommits, pendingTransactions),
1360 e -> e.cohort).iterator();
1363 void removeTransactionChain(final LocalHistoryIdentifier id) {
1364 if (transactionChains.remove(id) != null) {
1365 LOG.debug("{}: Removed transaction chain {}", logContext, id);