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 com.google.common.base.Preconditions.checkState;
11 import static com.google.common.base.Verify.verify;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
15 import akka.actor.ActorRef;
16 import akka.util.Timeout;
17 import com.google.common.annotations.VisibleForTesting;
18 import com.google.common.base.MoreObjects;
19 import com.google.common.base.Stopwatch;
20 import com.google.common.collect.ImmutableList;
21 import com.google.common.collect.ImmutableMap;
22 import com.google.common.collect.ImmutableMap.Builder;
23 import com.google.common.collect.Iterables;
24 import com.google.common.primitives.UnsignedLong;
25 import com.google.common.util.concurrent.FutureCallback;
26 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
28 import java.io.IOException;
29 import java.util.ArrayDeque;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.Deque;
34 import java.util.HashMap;
35 import java.util.Iterator;
37 import java.util.Map.Entry;
38 import java.util.Optional;
39 import java.util.OptionalLong;
40 import java.util.Queue;
41 import java.util.SortedSet;
42 import java.util.concurrent.TimeUnit;
43 import java.util.concurrent.TimeoutException;
44 import java.util.function.Consumer;
45 import java.util.function.Function;
46 import java.util.function.UnaryOperator;
47 import org.eclipse.jdt.annotation.NonNull;
48 import org.eclipse.jdt.annotation.Nullable;
49 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
50 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
51 import org.opendaylight.controller.cluster.datastore.DataTreeCohortActorRegistry.CohortRegistryCommand;
52 import org.opendaylight.controller.cluster.datastore.ShardDataTreeCohort.State;
53 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
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.protobuff.client.messages.Payload;
71 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
72 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
73 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
74 import org.opendaylight.yangtools.concepts.Identifier;
75 import org.opendaylight.yangtools.concepts.ListenerRegistration;
76 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
77 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
78 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
79 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
80 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
81 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
82 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
83 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
84 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
85 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
86 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeTip;
87 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
88 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
89 import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeStreamVersion;
90 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
91 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
92 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
93 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
94 import org.slf4j.Logger;
95 import org.slf4j.LoggerFactory;
96 import scala.concurrent.duration.FiniteDuration;
99 * Internal shard state, similar to a DOMStore, but optimized for use in the actor system, e.g. it does not expose
100 * public interfaces and assumes it is only ever called from a single thread.
103 * This class is not part of the API contract and is subject to change at any time. It is NOT thread-safe.
105 public class ShardDataTree extends ShardDataTreeTransactionParent {
106 private static final class CommitEntry {
107 final SimpleShardDataTreeCohort cohort;
110 CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
111 this.cohort = requireNonNull(cohort);
116 public String toString() {
117 return "CommitEntry [tx=" + cohort.getIdentifier() + ", state=" + cohort.getState() + "]";
121 private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(FiniteDuration.create(5, TimeUnit.SECONDS));
122 private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
125 * Process this many transactions in a single batched run. If we exceed this limit, we need to schedule later
126 * execution to finish up the batch. This is necessary in case of a long list of transactions which progress
127 * immediately through their preCommit phase -- if that happens, their completion eats up stack frames and could
128 * result in StackOverflowError.
130 private static final int MAX_TRANSACTION_BATCH = 100;
132 private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
133 private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
134 private final Deque<CommitEntry> pendingTransactions = new ArrayDeque<>();
135 private final Queue<CommitEntry> pendingCommits = new ArrayDeque<>();
136 private final Queue<CommitEntry> pendingFinishCommits = new ArrayDeque<>();
139 * Callbacks that need to be invoked once a payload is replicated.
141 private final Map<Payload, Runnable> replicationCallbacks = new HashMap<>();
143 private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
144 private final Collection<ShardDataTreeMetadata<?>> metadata;
145 private final DataTree dataTree;
146 private final String logContext;
147 private final Shard shard;
148 private Runnable runOnPendingTransactionsComplete;
151 * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
152 * {@link DataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
153 * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
154 * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
156 private DataTreeTip tip;
158 private SchemaContext schemaContext;
159 private DataSchemaContextTree dataSchemaContext;
161 private int currentTransactionBatch;
163 ShardDataTree(final Shard shard, final EffectiveModelContext schemaContext, final DataTree dataTree,
164 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
165 final String logContext,
166 final ShardDataTreeMetadata<?>... metadata) {
167 this.dataTree = requireNonNull(dataTree);
168 updateSchemaContext(schemaContext);
170 this.shard = requireNonNull(shard);
171 this.treeChangeListenerPublisher = requireNonNull(treeChangeListenerPublisher);
172 this.logContext = requireNonNull(logContext);
173 this.metadata = ImmutableList.copyOf(metadata);
177 ShardDataTree(final Shard shard, final EffectiveModelContext schemaContext, final TreeType treeType,
178 final YangInstanceIdentifier root,
179 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
180 final String logContext,
181 final ShardDataTreeMetadata<?>... metadata) {
182 this(shard, schemaContext, createDataTree(treeType, root), treeChangeListenerPublisher, logContext, metadata);
185 private static DataTree createDataTree(final TreeType treeType, final YangInstanceIdentifier root) {
186 final DataTreeConfiguration baseConfig = DataTreeConfiguration.getDefault(treeType);
187 return new InMemoryDataTreeFactory().create(new DataTreeConfiguration.Builder(baseConfig.getTreeType())
188 .setMandatoryNodesValidation(baseConfig.isMandatoryNodesValidationEnabled())
189 .setUniqueIndexes(baseConfig.isUniqueIndexEnabled())
195 public ShardDataTree(final Shard shard, final EffectiveModelContext schemaContext, final TreeType treeType) {
196 this(shard, schemaContext, treeType, YangInstanceIdentifier.empty(),
197 new DefaultShardDataTreeChangeListenerPublisher(""), "");
200 final String logContext() {
204 final long readTime() {
205 return shard.ticker().read();
208 public DataTree getDataTree() {
212 SchemaContext getSchemaContext() {
213 return schemaContext;
216 void updateSchemaContext(final @NonNull EffectiveModelContext newSchemaContext) {
217 dataTree.setEffectiveModelContext(newSchemaContext);
218 this.schemaContext = newSchemaContext;
219 this.dataSchemaContext = DataSchemaContextTree.from(newSchemaContext);
222 void resetTransactionBatch() {
223 currentTransactionBatch = 0;
227 * Take a snapshot of current state for later recovery.
229 * @return A state snapshot
231 @NonNull ShardDataTreeSnapshot takeStateSnapshot() {
232 final NormalizedNode<?, ?> rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.empty()).get();
233 final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
234 ImmutableMap.builder();
236 for (ShardDataTreeMetadata<?> m : metadata) {
237 final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
239 metaBuilder.put(meta.getType(), meta);
243 return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
246 private boolean anyPendingTransactions() {
247 return !pendingTransactions.isEmpty() || !pendingCommits.isEmpty() || !pendingFinishCommits.isEmpty();
250 private void applySnapshot(final @NonNull ShardDataTreeSnapshot snapshot,
251 final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
252 final Stopwatch elapsed = Stopwatch.createStarted();
254 if (anyPendingTransactions()) {
255 LOG.warn("{}: applying state snapshot with pending transactions", logContext);
258 final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
259 if (snapshot instanceof MetadataShardDataTreeSnapshot) {
260 snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
262 snapshotMeta = ImmutableMap.of();
265 for (ShardDataTreeMetadata<?> m : metadata) {
266 final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
274 final DataTreeModification unwrapped = dataTree.takeSnapshot().newModification();
275 final DataTreeModification mod = wrapper.apply(unwrapped);
276 // delete everything first
277 mod.delete(YangInstanceIdentifier.empty());
279 final Optional<NormalizedNode<?, ?>> maybeNode = snapshot.getRootNode();
280 if (maybeNode.isPresent()) {
281 // Add everything from the remote node back
282 mod.write(YangInstanceIdentifier.empty(), maybeNode.get());
286 dataTree.validate(unwrapped);
287 DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
288 dataTree.commit(candidate);
289 notifyListeners(candidate);
291 LOG.debug("{}: state snapshot applied in {}", logContext, elapsed);
295 * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
296 * does not perform any pruning.
298 * @param snapshot Snapshot that needs to be applied
299 * @throws DataValidationFailedException when the snapshot fails to apply
301 void applySnapshot(final @NonNull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
302 // TODO: we should be taking ShardSnapshotState here and performing forward-compatibility translation
303 applySnapshot(snapshot, UnaryOperator.identity());
307 * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
308 * pruning in an attempt to adjust the state to our current SchemaContext.
310 * @param snapshot Snapshot that needs to be applied
311 * @throws DataValidationFailedException when the snapshot fails to apply
313 void applyRecoverySnapshot(final @NonNull ShardSnapshotState snapshot) throws DataValidationFailedException {
314 // TODO: we should be able to reuse the pruner, provided we are not reentrant
315 final ReusableNormalizedNodePruner pruner = ReusableNormalizedNodePruner.forDataSchemaContext(
317 if (snapshot.needsMigration()) {
318 final ReusableNormalizedNodePruner uintPruner = pruner.withUintAdaption();
319 applySnapshot(snapshot.getSnapshot(),
320 delegate -> new PruningDataTreeModification.Proactive(delegate, dataTree, uintPruner));
322 applySnapshot(snapshot.getSnapshot(),
323 delegate -> new PruningDataTreeModification.Reactive(delegate, dataTree, pruner));
327 @SuppressWarnings("checkstyle:IllegalCatch")
328 private void applyRecoveryCandidate(final CommitTransactionPayload payload) throws IOException {
329 final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> entry = payload.acquireCandidate();
330 final DataTreeModification unwrapped = dataTree.takeSnapshot().newModification();
331 final PruningDataTreeModification mod = createPruningModification(unwrapped,
332 NormalizedNodeStreamVersion.MAGNESIUM.compareTo(entry.getValue().getVersion()) > 0);
334 DataTreeCandidates.applyToModification(mod, entry.getValue().getCandidate());
336 LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
339 dataTree.validate(unwrapped);
340 dataTree.commit(dataTree.prepare(unwrapped));
341 } catch (Exception e) {
342 File file = new File(System.getProperty("karaf.data", "."),
343 "failed-recovery-payload-" + logContext + ".out");
344 DataTreeModificationOutput.toFile(file, unwrapped);
345 throw new IllegalStateException(String.format(
346 "%s: Failed to apply recovery payload. Modification data was written to file %s",
347 logContext, file), e);
350 allMetadataCommittedTransaction(entry.getKey());
353 private PruningDataTreeModification createPruningModification(final DataTreeModification unwrapped,
354 final boolean uintAdapting) {
355 // TODO: we should be able to reuse the pruner, provided we are not reentrant
356 final ReusableNormalizedNodePruner pruner = ReusableNormalizedNodePruner.forDataSchemaContext(
358 return uintAdapting ? new PruningDataTreeModification.Proactive(unwrapped, dataTree, pruner.withUintAdaption())
359 : new PruningDataTreeModification.Reactive(unwrapped, dataTree, pruner);
363 * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
364 * pruning in an attempt to adjust the state to our current SchemaContext.
366 * @param payload Payload
367 * @throws IOException when the snapshot fails to deserialize
368 * @throws DataValidationFailedException when the snapshot fails to apply
370 void applyRecoveryPayload(final @NonNull Payload payload) throws IOException {
371 if (payload instanceof CommitTransactionPayload) {
372 applyRecoveryCandidate((CommitTransactionPayload) payload);
373 } else if (payload instanceof AbortTransactionPayload) {
374 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
375 } else if (payload instanceof PurgeTransactionPayload) {
376 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
377 } else if (payload instanceof CreateLocalHistoryPayload) {
378 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
379 } else if (payload instanceof CloseLocalHistoryPayload) {
380 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
381 } else if (payload instanceof PurgeLocalHistoryPayload) {
382 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
384 LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
388 private void applyReplicatedCandidate(final CommitTransactionPayload payload)
389 throws DataValidationFailedException, IOException {
390 final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> entry = payload.acquireCandidate();
391 final TransactionIdentifier identifier = entry.getKey();
392 LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
394 final DataTreeModification mod = dataTree.takeSnapshot().newModification();
395 // TODO: check version here, which will enable us to perform forward-compatibility transformations
396 DataTreeCandidates.applyToModification(mod, entry.getValue().getCandidate());
399 LOG.trace("{}: Applying foreign modification {}", logContext, mod);
400 dataTree.validate(mod);
401 final DataTreeCandidate candidate = dataTree.prepare(mod);
402 dataTree.commit(candidate);
404 allMetadataCommittedTransaction(identifier);
405 notifyListeners(candidate);
409 * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
410 * SchemaContexts match and does not perform any pruning.
412 * @param identifier Payload identifier as returned from RaftActor
413 * @param payload Payload
414 * @throws IOException when the snapshot fails to deserialize
415 * @throws DataValidationFailedException when the snapshot fails to apply
417 void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
418 DataValidationFailedException {
420 * 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
421 * if we are the leader and it has originated with us.
423 * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
424 * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
425 * acting in that capacity anymore.
427 * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
428 * pre-Boron state -- which limits the number of options here.
430 if (payload instanceof CommitTransactionPayload) {
431 if (identifier == null) {
432 applyReplicatedCandidate((CommitTransactionPayload) payload);
434 verify(identifier instanceof TransactionIdentifier);
435 // if we did not track this transaction before, it means that it came from another leader and we are in
436 // the process of commiting it while in PreLeader state. That means that it hasnt yet been committed to
437 // the local DataTree and would be lost if it was only applied via payloadReplicationComplete().
438 if (!payloadReplicationComplete((TransactionIdentifier) identifier)) {
439 applyReplicatedCandidate((CommitTransactionPayload) payload);
442 } else if (payload instanceof AbortTransactionPayload) {
443 if (identifier != null) {
444 payloadReplicationComplete((AbortTransactionPayload) payload);
446 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
447 } else if (payload instanceof PurgeTransactionPayload) {
448 if (identifier != null) {
449 payloadReplicationComplete((PurgeTransactionPayload) payload);
451 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
452 } else if (payload instanceof CloseLocalHistoryPayload) {
453 if (identifier != null) {
454 payloadReplicationComplete((CloseLocalHistoryPayload) payload);
456 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
457 } else if (payload instanceof CreateLocalHistoryPayload) {
458 if (identifier != null) {
459 payloadReplicationComplete((CreateLocalHistoryPayload)payload);
461 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
462 } else if (payload instanceof PurgeLocalHistoryPayload) {
463 if (identifier != null) {
464 payloadReplicationComplete((PurgeLocalHistoryPayload)payload);
466 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
468 LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
472 private void replicatePayload(final Identifier id, final Payload payload, final @Nullable Runnable callback) {
473 if (callback != null) {
474 replicationCallbacks.put(payload, callback);
476 shard.persistPayload(id, payload, true);
479 private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
480 final Runnable callback = replicationCallbacks.remove(payload);
481 if (callback != null) {
482 LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
485 LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
489 private boolean payloadReplicationComplete(final TransactionIdentifier txId) {
490 final CommitEntry current = pendingFinishCommits.peek();
491 if (current == null) {
492 LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
493 allMetadataCommittedTransaction(txId);
497 if (!current.cohort.getIdentifier().equals(txId)) {
498 LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
499 current.cohort.getIdentifier(), txId);
500 allMetadataCommittedTransaction(txId);
504 finishCommit(current.cohort);
508 private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
509 for (ShardDataTreeMetadata<?> m : metadata) {
510 m.onTransactionAborted(txId);
514 private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
515 for (ShardDataTreeMetadata<?> m : metadata) {
516 m.onTransactionCommitted(txId);
520 private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
521 for (ShardDataTreeMetadata<?> m : metadata) {
522 m.onTransactionPurged(txId);
526 private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
527 for (ShardDataTreeMetadata<?> m : metadata) {
528 m.onHistoryCreated(historyId);
532 private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
533 for (ShardDataTreeMetadata<?> m : metadata) {
534 m.onHistoryClosed(historyId);
538 private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
539 for (ShardDataTreeMetadata<?> m : metadata) {
540 m.onHistoryPurged(historyId);
545 * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
546 * this method is used for re-establishing state when we are taking over
548 * @param historyId Local history identifier
549 * @param closed True if the chain should be created in closed state (i.e. pending purge)
550 * @return Transaction chain handle
552 ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
553 final boolean closed) {
554 final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
555 final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
556 checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId, existing);
560 ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId,
561 final @Nullable Runnable callback) {
562 ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
564 chain = new ShardDataTreeTransactionChain(historyId, this);
565 transactionChains.put(historyId, chain);
566 replicatePayload(historyId, CreateLocalHistoryPayload.create(
567 historyId, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
568 } else if (callback != null) {
575 ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
576 shard.getShardMBean().incrementReadOnlyTransactionCount();
578 if (txId.getHistoryId().getHistoryId() == 0) {
579 return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
582 return ensureTransactionChain(txId.getHistoryId(), null).newReadOnlyTransaction(txId);
585 ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
586 shard.getShardMBean().incrementReadWriteTransactionCount();
588 if (txId.getHistoryId().getHistoryId() == 0) {
589 return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
593 return ensureTransactionChain(txId.getHistoryId(), null).newReadWriteTransaction(txId);
597 public void notifyListeners(final DataTreeCandidate candidate) {
598 treeChangeListenerPublisher.publishChanges(candidate);
602 * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
603 * replication callbacks.
605 void purgeLeaderState() {
606 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
610 transactionChains.clear();
611 replicationCallbacks.clear();
615 * Close a single transaction chain.
617 * @param id History identifier
618 * @param callback Callback to invoke upon completion, may be null
620 void closeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
621 if (commonCloseTransactionChain(id, callback)) {
622 replicatePayload(id, CloseLocalHistoryPayload.create(id,
623 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
628 * Close a single transaction chain which is received through ask-based protocol. It does not keep a commit record.
630 * @param id History identifier
632 void closeTransactionChain(final LocalHistoryIdentifier id) {
633 commonCloseTransactionChain(id, null);
636 private boolean commonCloseTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
637 final ShardDataTreeTransactionChain chain = transactionChains.get(id);
639 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
640 if (callback != null) {
651 * Purge a single transaction chain.
653 * @param id History identifier
654 * @param callback Callback to invoke upon completion, may be null
656 void purgeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
657 final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
659 LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
660 if (callback != null) {
666 replicatePayload(id, PurgeLocalHistoryPayload.create(
667 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
670 Optional<DataTreeCandidate> readCurrentData() {
671 return dataTree.takeSnapshot().readNode(YangInstanceIdentifier.empty())
672 .map(state -> DataTreeCandidates.fromNormalizedNode(YangInstanceIdentifier.empty(), state));
675 public void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
676 final Optional<DataTreeCandidate> initialState,
677 final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
678 treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
682 return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
686 void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
687 final TransactionIdentifier id = transaction.getIdentifier();
688 LOG.debug("{}: aborting transaction {}", logContext, id);
689 replicatePayload(id, AbortTransactionPayload.create(
690 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
694 void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
695 // No-op for free-standing transactions
700 ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction,
701 final Optional<SortedSet<String>> participatingShardNames) {
702 final DataTreeModification snapshot = transaction.getSnapshot();
703 final TransactionIdentifier id = transaction.getIdentifier();
704 LOG.debug("{}: readying transaction {}", logContext, id);
706 LOG.debug("{}: transaction {} ready", logContext, id);
708 return createReadyCohort(transaction.getIdentifier(), snapshot, participatingShardNames);
711 void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
712 LOG.debug("{}: purging transaction {}", logContext, id);
713 replicatePayload(id, PurgeTransactionPayload.create(
714 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
717 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
718 return dataTree.takeSnapshot().readNode(path);
721 DataTreeSnapshot takeSnapshot() {
722 return dataTree.takeSnapshot();
726 public DataTreeModification newModification() {
727 return dataTree.takeSnapshot().newModification();
730 public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
731 Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
733 for (CommitEntry entry: pendingFinishCommits) {
734 ret.add(entry.cohort);
737 for (CommitEntry entry: pendingCommits) {
738 ret.add(entry.cohort);
741 for (CommitEntry entry: pendingTransactions) {
742 ret.add(entry.cohort);
745 pendingFinishCommits.clear();
746 pendingCommits.clear();
747 pendingTransactions.clear();
753 * Called some time after {@link #processNextPendingTransaction()} decides to stop processing.
755 void resumeNextPendingTransaction() {
756 LOG.debug("{}: attempting to resume transaction processing", logContext);
757 processNextPending();
760 @SuppressWarnings("checkstyle:IllegalCatch")
761 private void processNextPendingTransaction() {
762 ++currentTransactionBatch;
763 if (currentTransactionBatch > MAX_TRANSACTION_BATCH) {
764 LOG.debug("{}: Already processed {}, scheduling continuation", logContext, currentTransactionBatch);
765 shard.scheduleNextPendingTransaction();
769 processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
770 final SimpleShardDataTreeCohort cohort = entry.cohort;
771 final DataTreeModification modification = cohort.getDataTreeModification();
773 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
776 tip.validate(modification);
777 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
778 cohort.successfulCanCommit();
779 entry.lastAccess = readTime();
781 } catch (ConflictingModificationAppliedException e) {
782 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
784 cause = new OptimisticLockFailedException("Optimistic lock failed for path " + e.getPath(), e);
785 } catch (DataValidationFailedException e) {
786 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
789 // For debugging purposes, allow dumping of the modification. Coupled with the above
790 // precondition log, it should allow us to understand what went on.
791 LOG.debug("{}: Store Tx {}: modifications: {}", logContext, cohort.getIdentifier(), modification);
792 LOG.trace("{}: Current tree: {}", logContext, dataTree);
793 cause = new TransactionCommitFailedException("Data did not pass validation for path " + e.getPath(), e);
794 } catch (Exception e) {
795 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
799 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
800 pendingTransactions.poll().cohort.failedCanCommit(cause);
804 private void processNextPending() {
805 processNextPendingCommit();
806 processNextPendingTransaction();
809 private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
810 final Consumer<CommitEntry> processor) {
811 while (!queue.isEmpty()) {
812 final CommitEntry entry = queue.peek();
813 final SimpleShardDataTreeCohort cohort = entry.cohort;
815 if (cohort.isFailed()) {
816 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
821 if (cohort.getState() == allowedState) {
822 processor.accept(entry);
828 maybeRunOperationOnPendingTransactionsComplete();
831 private void processNextPendingCommit() {
832 processNextPending(pendingCommits, State.COMMIT_PENDING,
833 entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
836 private boolean peekNextPendingCommit() {
837 final CommitEntry first = pendingCommits.peek();
838 return first != null && first.cohort.getState() == State.COMMIT_PENDING;
841 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
842 final CommitEntry head = pendingTransactions.peek();
844 LOG.warn("{}: No transactions enqueued while attempting to start canCommit on {}", logContext, cohort);
847 if (!cohort.equals(head.cohort)) {
848 // The tx isn't at the head of the queue so we can't start canCommit at this point. Here we check if this
849 // tx should be moved ahead of other tx's in the READY state in the pendingTransactions queue. If this tx
850 // has other participating shards, it could deadlock with other tx's accessing the same shards
851 // depending on the order the tx's are readied on each shard
852 // (see https://jira.opendaylight.org/browse/CONTROLLER-1836). Therefore, if the preceding participating
853 // shard names for a preceding pending tx, call it A, in the queue matches that of this tx, then this tx
854 // is allowed to be moved ahead of tx A in the queue so it is processed first to avoid potential deadlock
855 // if tx A is behind this tx in the pendingTransactions queue for a preceding shard. In other words, since
856 // canCommmit for this tx was requested before tx A, honor that request. If this tx is moved to the head of
857 // the queue as a result, then proceed with canCommit.
859 Collection<String> precedingShardNames = extractPrecedingShardNames(cohort.getParticipatingShardNames());
860 if (precedingShardNames.isEmpty()) {
861 LOG.debug("{}: Tx {} is scheduled for canCommit step", logContext, cohort.getIdentifier());
865 LOG.debug("{}: Evaluating tx {} for canCommit - preceding participating shard names {}",
866 logContext, cohort.getIdentifier(), precedingShardNames);
867 final Iterator<CommitEntry> iter = pendingTransactions.iterator();
869 int moveToIndex = -1;
870 while (iter.hasNext()) {
871 final CommitEntry entry = iter.next();
874 if (cohort.equals(entry.cohort)) {
875 if (moveToIndex < 0) {
876 LOG.debug("{}: Not moving tx {} - cannot proceed with canCommit",
877 logContext, cohort.getIdentifier());
881 LOG.debug("{}: Moving {} to index {} in the pendingTransactions queue",
882 logContext, cohort.getIdentifier(), moveToIndex);
884 insertEntry(pendingTransactions, entry, moveToIndex);
886 if (!cohort.equals(pendingTransactions.peek().cohort)) {
887 LOG.debug("{}: Tx {} is not at the head of the queue - cannot proceed with canCommit",
888 logContext, cohort.getIdentifier());
892 LOG.debug("{}: Tx {} is now at the head of the queue - proceeding with canCommit",
893 logContext, cohort.getIdentifier());
897 if (entry.cohort.getState() != State.READY) {
898 LOG.debug("{}: Skipping pending transaction {} in state {}",
899 logContext, entry.cohort.getIdentifier(), entry.cohort.getState());
903 final Collection<String> pendingPrecedingShardNames = extractPrecedingShardNames(
904 entry.cohort.getParticipatingShardNames());
906 if (precedingShardNames.equals(pendingPrecedingShardNames)) {
907 if (moveToIndex < 0) {
908 LOG.debug("{}: Preceding shard names {} for pending tx {} match - saving moveToIndex {}",
909 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), index);
913 "{}: Preceding shard names {} for pending tx {} match but moveToIndex already set to {}",
914 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), moveToIndex);
917 LOG.debug("{}: Preceding shard names {} for pending tx {} differ - skipping",
918 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier());
923 processNextPendingTransaction();
926 private static void insertEntry(final Deque<CommitEntry> queue, final CommitEntry entry, final int atIndex) {
928 queue.addFirst(entry);
932 LOG.trace("Inserting into Deque at index {}", atIndex);
934 Deque<CommitEntry> tempStack = new ArrayDeque<>(atIndex);
935 for (int i = 0; i < atIndex; i++) {
936 tempStack.push(queue.poll());
939 queue.addFirst(entry);
941 tempStack.forEach(queue::addFirst);
944 private Collection<String> extractPrecedingShardNames(final Optional<SortedSet<String>> participatingShardNames) {
945 return participatingShardNames.map((Function<SortedSet<String>, Collection<String>>)
946 set -> set.headSet(shard.getShardName())).orElse(Collections.<String>emptyList());
949 private void failPreCommit(final Throwable cause) {
950 shard.getShardMBean().incrementFailedTransactionsCount();
951 pendingTransactions.poll().cohort.failedPreCommit(cause);
952 processNextPendingTransaction();
955 @SuppressWarnings("checkstyle:IllegalCatch")
956 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
957 final CommitEntry entry = pendingTransactions.peek();
958 checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
960 final SimpleShardDataTreeCohort current = entry.cohort;
961 verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
963 final TransactionIdentifier currentId = current.getIdentifier();
964 LOG.debug("{}: Preparing transaction {}", logContext, currentId);
966 final DataTreeCandidateTip candidate;
968 candidate = tip.prepare(cohort.getDataTreeModification());
969 LOG.debug("{}: Transaction {} candidate ready", logContext, currentId);
970 } catch (DataValidationFailedException | RuntimeException e) {
975 cohort.userPreCommit(candidate, new FutureCallback<Void>() {
977 public void onSuccess(final Void noop) {
978 // Set the tip of the data tree.
979 tip = verifyNotNull(candidate);
981 entry.lastAccess = readTime();
983 pendingTransactions.remove();
984 pendingCommits.add(entry);
986 LOG.debug("{}: Transaction {} prepared", logContext, currentId);
988 cohort.successfulPreCommit(candidate);
990 processNextPendingTransaction();
994 public void onFailure(final Throwable failure) {
995 failPreCommit(failure);
1000 private void failCommit(final Exception cause) {
1001 shard.getShardMBean().incrementFailedTransactionsCount();
1002 pendingFinishCommits.poll().cohort.failedCommit(cause);
1003 processNextPending();
1006 @SuppressWarnings("checkstyle:IllegalCatch")
1007 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
1008 final TransactionIdentifier txId = cohort.getIdentifier();
1009 final DataTreeCandidate candidate = cohort.getCandidate();
1011 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
1013 if (tip == candidate) {
1014 // All pending candidates have been committed, reset the tip to the data tree.
1019 dataTree.commit(candidate);
1020 } catch (Exception e) {
1021 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
1026 allMetadataCommittedTransaction(txId);
1027 shard.getShardMBean().incrementCommittedTransactionCount();
1028 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
1030 // FIXME: propagate journal index
1031 pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO, () -> {
1032 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
1033 notifyListeners(candidate);
1035 processNextPending();
1039 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
1040 final CommitEntry entry = pendingCommits.peek();
1041 checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
1043 final SimpleShardDataTreeCohort current = entry.cohort;
1044 if (!cohort.equals(current)) {
1045 LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
1049 LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
1051 final TransactionIdentifier txId = cohort.getIdentifier();
1052 final Payload payload;
1054 payload = CommitTransactionPayload.create(txId, candidate, PayloadVersion.current(),
1055 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity());
1056 } catch (IOException e) {
1057 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
1058 pendingCommits.poll().cohort.failedCommit(e);
1059 processNextPending();
1063 // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
1064 // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
1065 // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
1066 // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
1067 // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
1068 // pendingCommits queue.
1069 processNextPendingTransaction();
1071 // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
1072 // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
1073 // in order to properly determine the batchHint flag for the call to persistPayload.
1074 pendingCommits.remove();
1075 pendingFinishCommits.add(entry);
1077 // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
1078 // this transaction for replication.
1079 boolean replicationBatchHint = peekNextPendingCommit();
1081 // Once completed, we will continue via payloadReplicationComplete
1082 shard.persistPayload(txId, payload, replicationBatchHint);
1084 entry.lastAccess = shard.ticker().read();
1086 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
1088 // Process the next transaction pending commit, if any. If there is one it will be batched with this
1089 // transaction for replication.
1090 processNextPendingCommit();
1093 Collection<ActorRef> getCohortActors() {
1094 return cohortRegistry.getCohortActors();
1097 void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
1098 cohortRegistry.process(sender, message);
1102 ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1103 final Exception failure) {
1104 final SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId, failure);
1105 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1110 ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1111 final Optional<SortedSet<String>> participatingShardNames) {
1112 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId,
1113 cohortRegistry.createCohort(schemaContext, txId, shard::executeInSelf,
1114 COMMIT_STEP_TIMEOUT), participatingShardNames);
1115 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1119 // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
1120 // the newReadWriteTransaction()
1121 ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1122 final Optional<SortedSet<String>> participatingShardNames) {
1123 if (txId.getHistoryId().getHistoryId() == 0) {
1124 return createReadyCohort(txId, mod, participatingShardNames);
1127 return ensureTransactionChain(txId.getHistoryId(), null).createReadyCohort(txId, mod, participatingShardNames);
1130 @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
1131 void checkForExpiredTransactions(final long transactionCommitTimeoutMillis,
1132 final Function<SimpleShardDataTreeCohort, OptionalLong> accessTimeUpdater) {
1133 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
1134 final long now = readTime();
1136 final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
1137 !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
1138 final CommitEntry currentTx = currentQueue.peek();
1139 if (currentTx == null) {
1140 // Empty queue, no-op
1144 long delta = now - currentTx.lastAccess;
1145 if (delta < timeout) {
1146 // Not expired yet, bail
1150 final OptionalLong updateOpt = accessTimeUpdater.apply(currentTx.cohort);
1151 if (updateOpt.isPresent()) {
1152 final long newAccess = updateOpt.getAsLong();
1153 final long newDelta = now - newAccess;
1154 if (newDelta < delta) {
1155 LOG.debug("{}: Updated current transaction {} access time", logContext,
1156 currentTx.cohort.getIdentifier());
1157 currentTx.lastAccess = newAccess;
1161 if (delta < timeout) {
1162 // Not expired yet, bail
1167 final long deltaMillis = TimeUnit.NANOSECONDS.toMillis(delta);
1168 final State state = currentTx.cohort.getState();
1170 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
1171 currentTx.cohort.getIdentifier(), deltaMillis, state);
1172 boolean processNext = true;
1173 final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
1174 + deltaMillis + "ms");
1177 case CAN_COMMIT_PENDING:
1178 currentQueue.remove().cohort.failedCanCommit(cohortFailure);
1180 case CAN_COMMIT_COMPLETE:
1181 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
1182 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
1183 // in PRE_COMMIT_COMPLETE is changed.
1184 currentQueue.remove().cohort.reportFailure(cohortFailure);
1186 case PRE_COMMIT_PENDING:
1187 currentQueue.remove().cohort.failedPreCommit(cohortFailure);
1189 case PRE_COMMIT_COMPLETE:
1190 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
1191 // are ready we should commit the transaction, not abort it. Our current software stack does
1192 // not allow us to do that consistently, because we persist at the time of commit, hence
1193 // we can end up in a state where we have pre-committed a transaction, then a leader failover
1194 // occurred ... the new leader does not see the pre-committed transaction and does not have
1195 // a running timer. To fix this we really need two persistence events.
1197 // The first one, done at pre-commit time will hold the transaction payload. When consensus
1198 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1199 // apply the state in this event.
1201 // The second one, done at commit (or abort) time holds only the transaction identifier and
1202 // signals to followers that the state should (or should not) be applied.
1204 // In order to make the pre-commit timer working across failovers, though, we need
1205 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1206 // restart the timer.
1207 currentQueue.remove().cohort.reportFailure(cohortFailure);
1209 case COMMIT_PENDING:
1210 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1211 currentTx.cohort.getIdentifier());
1212 currentTx.lastAccess = now;
1213 processNext = false;
1216 currentQueue.remove().cohort.reportFailure(cohortFailure);
1222 currentQueue.remove();
1226 processNextPending();
1230 boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1231 final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1232 pendingTransactions).iterator();
1233 if (!it.hasNext()) {
1234 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1238 // First entry is special, as it may already be committing
1239 final CommitEntry first = it.next();
1240 if (cohort.equals(first.cohort)) {
1241 if (cohort.getState() != State.COMMIT_PENDING) {
1242 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1243 cohort.getIdentifier());
1246 if (cohort.getCandidate() != null) {
1247 rebaseTransactions(it, dataTree);
1250 processNextPending();
1254 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1258 DataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
1259 while (it.hasNext()) {
1260 final CommitEntry e = it.next();
1261 if (cohort.equals(e.cohort)) {
1262 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1265 if (cohort.getCandidate() != null) {
1266 rebaseTransactions(it, newTip);
1271 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), newTip);
1275 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1279 @SuppressWarnings("checkstyle:IllegalCatch")
1280 private void rebaseTransactions(final Iterator<CommitEntry> iter, final @NonNull DataTreeTip newTip) {
1281 tip = requireNonNull(newTip);
1282 while (iter.hasNext()) {
1283 final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1284 if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1285 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1288 tip.validate(cohort.getDataTreeModification());
1289 } catch (DataValidationFailedException | RuntimeException e) {
1290 LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1291 cohort.reportFailure(e);
1293 } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1294 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1297 tip.validate(cohort.getDataTreeModification());
1298 DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1300 cohort.setNewCandidate(candidate);
1302 } catch (RuntimeException | DataValidationFailedException e) {
1303 LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1304 cohort.reportFailure(e);
1310 void setRunOnPendingTransactionsComplete(final Runnable operation) {
1311 runOnPendingTransactionsComplete = operation;
1312 maybeRunOperationOnPendingTransactionsComplete();
1315 private void maybeRunOperationOnPendingTransactionsComplete() {
1316 if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1317 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1318 runOnPendingTransactionsComplete);
1320 runOnPendingTransactionsComplete.run();
1321 runOnPendingTransactionsComplete = null;
1325 ShardStats getStats() {
1326 return shard.getShardMBean();
1329 Iterator<SimpleShardDataTreeCohort> cohortIterator() {
1330 return Iterables.transform(Iterables.concat(pendingFinishCommits, pendingCommits, pendingTransactions),
1331 e -> e.cohort).iterator();
1334 void removeTransactionChain(final LocalHistoryIdentifier id) {
1335 if (transactionChains.remove(id) != null) {
1336 LOG.debug("{}: Removed transaction chain {}", logContext, id);