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.SchemaContext;
93 import org.slf4j.Logger;
94 import org.slf4j.LoggerFactory;
95 import scala.concurrent.duration.FiniteDuration;
98 * Internal shard state, similar to a DOMStore, but optimized for use in the actor system, e.g. it does not expose
99 * public interfaces and assumes it is only ever called from a single thread.
102 * This class is not part of the API contract and is subject to change at any time. It is NOT thread-safe.
104 public class ShardDataTree extends ShardDataTreeTransactionParent {
105 private static final class CommitEntry {
106 final SimpleShardDataTreeCohort cohort;
109 CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
110 this.cohort = requireNonNull(cohort);
115 public String toString() {
116 return "CommitEntry [tx=" + cohort.getIdentifier() + ", state=" + cohort.getState() + "]";
120 private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(FiniteDuration.create(5, TimeUnit.SECONDS));
121 private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
124 * Process this many transactions in a single batched run. If we exceed this limit, we need to schedule later
125 * execution to finish up the batch. This is necessary in case of a long list of transactions which progress
126 * immediately through their preCommit phase -- if that happens, their completion eats up stack frames and could
127 * result in StackOverflowError.
129 private static final int MAX_TRANSACTION_BATCH = 100;
131 private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
132 private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
133 private final Deque<CommitEntry> pendingTransactions = new ArrayDeque<>();
134 private final Queue<CommitEntry> pendingCommits = new ArrayDeque<>();
135 private final Queue<CommitEntry> pendingFinishCommits = new ArrayDeque<>();
138 * Callbacks that need to be invoked once a payload is replicated.
140 private final Map<Payload, Runnable> replicationCallbacks = new HashMap<>();
142 private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
143 private final Collection<ShardDataTreeMetadata<?>> metadata;
144 private final DataTree dataTree;
145 private final String logContext;
146 private final Shard shard;
147 private Runnable runOnPendingTransactionsComplete;
150 * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
151 * {@link DataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
152 * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
153 * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
155 private DataTreeTip tip;
157 private SchemaContext schemaContext;
158 private DataSchemaContextTree dataSchemaContext;
160 private int currentTransactionBatch;
162 ShardDataTree(final Shard shard, final SchemaContext schemaContext, final DataTree dataTree,
163 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
164 final String logContext,
165 final ShardDataTreeMetadata<?>... metadata) {
166 this.dataTree = requireNonNull(dataTree);
167 updateSchemaContext(schemaContext);
169 this.shard = requireNonNull(shard);
170 this.treeChangeListenerPublisher = requireNonNull(treeChangeListenerPublisher);
171 this.logContext = requireNonNull(logContext);
172 this.metadata = ImmutableList.copyOf(metadata);
176 ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType,
177 final YangInstanceIdentifier root,
178 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
179 final String logContext,
180 final ShardDataTreeMetadata<?>... metadata) {
181 this(shard, schemaContext, createDataTree(treeType, root), treeChangeListenerPublisher, logContext, metadata);
184 private static DataTree createDataTree(final TreeType treeType, final YangInstanceIdentifier root) {
185 final DataTreeConfiguration baseConfig = DataTreeConfiguration.getDefault(treeType);
186 return new InMemoryDataTreeFactory().create(new DataTreeConfiguration.Builder(baseConfig.getTreeType())
187 .setMandatoryNodesValidation(baseConfig.isMandatoryNodesValidationEnabled())
188 .setUniqueIndexes(baseConfig.isUniqueIndexEnabled())
194 public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType) {
195 this(shard, schemaContext, treeType, YangInstanceIdentifier.empty(),
196 new DefaultShardDataTreeChangeListenerPublisher(""), "");
199 final String logContext() {
203 final long readTime() {
204 return shard.ticker().read();
207 public DataTree getDataTree() {
211 SchemaContext getSchemaContext() {
212 return schemaContext;
215 void updateSchemaContext(final SchemaContext newSchemaContext) {
216 dataTree.setSchemaContext(newSchemaContext);
217 this.schemaContext = requireNonNull(newSchemaContext);
218 this.dataSchemaContext = DataSchemaContextTree.from(newSchemaContext);
221 void resetTransactionBatch() {
222 currentTransactionBatch = 0;
226 * Take a snapshot of current state for later recovery.
228 * @return A state snapshot
230 @NonNull ShardDataTreeSnapshot takeStateSnapshot() {
231 final NormalizedNode<?, ?> rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.empty()).get();
232 final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
233 ImmutableMap.builder();
235 for (ShardDataTreeMetadata<?> m : metadata) {
236 final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
238 metaBuilder.put(meta.getType(), meta);
242 return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
245 private boolean anyPendingTransactions() {
246 return !pendingTransactions.isEmpty() || !pendingCommits.isEmpty() || !pendingFinishCommits.isEmpty();
249 private void applySnapshot(final @NonNull ShardDataTreeSnapshot snapshot,
250 final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
251 final Stopwatch elapsed = Stopwatch.createStarted();
253 if (anyPendingTransactions()) {
254 LOG.warn("{}: applying state snapshot with pending transactions", logContext);
257 final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
258 if (snapshot instanceof MetadataShardDataTreeSnapshot) {
259 snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
261 snapshotMeta = ImmutableMap.of();
264 for (ShardDataTreeMetadata<?> m : metadata) {
265 final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
273 final DataTreeModification unwrapped = dataTree.takeSnapshot().newModification();
274 final DataTreeModification mod = wrapper.apply(unwrapped);
275 // delete everything first
276 mod.delete(YangInstanceIdentifier.empty());
278 final Optional<NormalizedNode<?, ?>> maybeNode = snapshot.getRootNode();
279 if (maybeNode.isPresent()) {
280 // Add everything from the remote node back
281 mod.write(YangInstanceIdentifier.empty(), maybeNode.get());
285 dataTree.validate(unwrapped);
286 DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
287 dataTree.commit(candidate);
288 notifyListeners(candidate);
290 LOG.debug("{}: state snapshot applied in {}", logContext, elapsed);
294 * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
295 * does not perform any pruning.
297 * @param snapshot Snapshot that needs to be applied
298 * @throws DataValidationFailedException when the snapshot fails to apply
300 void applySnapshot(final @NonNull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
301 // TODO: we should be taking ShardSnapshotState here and performing forward-compatibility translation
302 applySnapshot(snapshot, UnaryOperator.identity());
306 * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
307 * pruning in an attempt to adjust the state to our current SchemaContext.
309 * @param snapshot Snapshot that needs to be applied
310 * @throws DataValidationFailedException when the snapshot fails to apply
312 void applyRecoverySnapshot(final @NonNull ShardSnapshotState snapshot) throws DataValidationFailedException {
313 // TODO: we should be able to reuse the pruner, provided we are not reentrant
314 final ReusableNormalizedNodePruner pruner = ReusableNormalizedNodePruner.forDataSchemaContext(
316 if (snapshot.needsMigration()) {
317 final ReusableNormalizedNodePruner uintPruner = pruner.withUintAdaption();
318 applySnapshot(snapshot.getSnapshot(),
319 delegate -> new PruningDataTreeModification.Proactive(delegate, dataTree, uintPruner));
321 applySnapshot(snapshot.getSnapshot(),
322 delegate -> new PruningDataTreeModification.Reactive(delegate, dataTree, pruner));
326 @SuppressWarnings("checkstyle:IllegalCatch")
327 private void applyRecoveryCandidate(final CommitTransactionPayload payload) throws IOException {
328 final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> entry = payload.acquireCandidate();
329 final DataTreeModification unwrapped = dataTree.takeSnapshot().newModification();
330 final PruningDataTreeModification mod = createPruningModification(unwrapped,
331 NormalizedNodeStreamVersion.MAGNESIUM.compareTo(entry.getValue().getVersion()) > 0);
333 DataTreeCandidates.applyToModification(mod, entry.getValue().getCandidate());
335 LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
338 dataTree.validate(unwrapped);
339 dataTree.commit(dataTree.prepare(unwrapped));
340 } catch (Exception e) {
341 File file = new File(System.getProperty("karaf.data", "."),
342 "failed-recovery-payload-" + logContext + ".out");
343 DataTreeModificationOutput.toFile(file, unwrapped);
344 throw new IllegalStateException(String.format(
345 "%s: Failed to apply recovery payload. Modification data was written to file %s",
346 logContext, file), e);
349 allMetadataCommittedTransaction(entry.getKey());
352 private PruningDataTreeModification createPruningModification(final DataTreeModification unwrapped,
353 final boolean uintAdapting) {
354 // TODO: we should be able to reuse the pruner, provided we are not reentrant
355 final ReusableNormalizedNodePruner pruner = ReusableNormalizedNodePruner.forDataSchemaContext(
357 return uintAdapting ? new PruningDataTreeModification.Proactive(unwrapped, dataTree, pruner.withUintAdaption())
358 : new PruningDataTreeModification.Reactive(unwrapped, dataTree, pruner);
362 * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
363 * pruning in an attempt to adjust the state to our current SchemaContext.
365 * @param payload Payload
366 * @throws IOException when the snapshot fails to deserialize
367 * @throws DataValidationFailedException when the snapshot fails to apply
369 void applyRecoveryPayload(final @NonNull Payload payload) throws IOException {
370 if (payload instanceof CommitTransactionPayload) {
371 applyRecoveryCandidate((CommitTransactionPayload) payload);
372 } else if (payload instanceof AbortTransactionPayload) {
373 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
374 } else if (payload instanceof PurgeTransactionPayload) {
375 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
376 } else if (payload instanceof CreateLocalHistoryPayload) {
377 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
378 } else if (payload instanceof CloseLocalHistoryPayload) {
379 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
380 } else if (payload instanceof PurgeLocalHistoryPayload) {
381 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
383 LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
387 private void applyReplicatedCandidate(final CommitTransactionPayload payload)
388 throws DataValidationFailedException, IOException {
389 final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> entry = payload.acquireCandidate();
390 final TransactionIdentifier identifier = entry.getKey();
391 LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
393 final DataTreeModification mod = dataTree.takeSnapshot().newModification();
394 // TODO: check version here, which will enable us to perform forward-compatibility transformations
395 DataTreeCandidates.applyToModification(mod, entry.getValue().getCandidate());
398 LOG.trace("{}: Applying foreign modification {}", logContext, mod);
399 dataTree.validate(mod);
400 final DataTreeCandidate candidate = dataTree.prepare(mod);
401 dataTree.commit(candidate);
403 allMetadataCommittedTransaction(identifier);
404 notifyListeners(candidate);
408 * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
409 * SchemaContexts match and does not perform any pruning.
411 * @param identifier Payload identifier as returned from RaftActor
412 * @param payload Payload
413 * @throws IOException when the snapshot fails to deserialize
414 * @throws DataValidationFailedException when the snapshot fails to apply
416 void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
417 DataValidationFailedException {
419 * 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
420 * if we are the leader and it has originated with us.
422 * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
423 * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
424 * acting in that capacity anymore.
426 * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
427 * pre-Boron state -- which limits the number of options here.
429 if (payload instanceof CommitTransactionPayload) {
430 if (identifier == null) {
431 applyReplicatedCandidate((CommitTransactionPayload) payload);
433 verify(identifier instanceof TransactionIdentifier);
434 // if we did not track this transaction before, it means that it came from another leader and we are in
435 // the process of commiting it while in PreLeader state. That means that it hasnt yet been committed to
436 // the local DataTree and would be lost if it was only applied via payloadReplicationComplete().
437 if (!payloadReplicationComplete((TransactionIdentifier) identifier)) {
438 applyReplicatedCandidate((CommitTransactionPayload) payload);
441 } else if (payload instanceof AbortTransactionPayload) {
442 if (identifier != null) {
443 payloadReplicationComplete((AbortTransactionPayload) payload);
445 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
446 } else if (payload instanceof PurgeTransactionPayload) {
447 if (identifier != null) {
448 payloadReplicationComplete((PurgeTransactionPayload) payload);
450 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
451 } else if (payload instanceof CloseLocalHistoryPayload) {
452 if (identifier != null) {
453 payloadReplicationComplete((CloseLocalHistoryPayload) payload);
455 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
456 } else if (payload instanceof CreateLocalHistoryPayload) {
457 if (identifier != null) {
458 payloadReplicationComplete((CreateLocalHistoryPayload)payload);
460 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
461 } else if (payload instanceof PurgeLocalHistoryPayload) {
462 if (identifier != null) {
463 payloadReplicationComplete((PurgeLocalHistoryPayload)payload);
465 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
467 LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
471 private void replicatePayload(final Identifier id, final Payload payload, final @Nullable Runnable callback) {
472 if (callback != null) {
473 replicationCallbacks.put(payload, callback);
475 shard.persistPayload(id, payload, true);
478 private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
479 final Runnable callback = replicationCallbacks.remove(payload);
480 if (callback != null) {
481 LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
484 LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
488 private boolean payloadReplicationComplete(final TransactionIdentifier txId) {
489 final CommitEntry current = pendingFinishCommits.peek();
490 if (current == null) {
491 LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
492 allMetadataCommittedTransaction(txId);
496 if (!current.cohort.getIdentifier().equals(txId)) {
497 LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
498 current.cohort.getIdentifier(), txId);
499 allMetadataCommittedTransaction(txId);
503 finishCommit(current.cohort);
507 private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
508 for (ShardDataTreeMetadata<?> m : metadata) {
509 m.onTransactionAborted(txId);
513 private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
514 for (ShardDataTreeMetadata<?> m : metadata) {
515 m.onTransactionCommitted(txId);
519 private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
520 for (ShardDataTreeMetadata<?> m : metadata) {
521 m.onTransactionPurged(txId);
525 private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
526 for (ShardDataTreeMetadata<?> m : metadata) {
527 m.onHistoryCreated(historyId);
531 private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
532 for (ShardDataTreeMetadata<?> m : metadata) {
533 m.onHistoryClosed(historyId);
537 private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
538 for (ShardDataTreeMetadata<?> m : metadata) {
539 m.onHistoryPurged(historyId);
544 * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
545 * this method is used for re-establishing state when we are taking over
547 * @param historyId Local history identifier
548 * @param closed True if the chain should be created in closed state (i.e. pending purge)
549 * @return Transaction chain handle
551 ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
552 final boolean closed) {
553 final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
554 final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
555 checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId, existing);
559 ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId,
560 final @Nullable Runnable callback) {
561 ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
563 chain = new ShardDataTreeTransactionChain(historyId, this);
564 transactionChains.put(historyId, chain);
565 replicatePayload(historyId, CreateLocalHistoryPayload.create(
566 historyId, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
567 } else if (callback != null) {
574 ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
575 shard.getShardMBean().incrementReadOnlyTransactionCount();
577 if (txId.getHistoryId().getHistoryId() == 0) {
578 return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
581 return ensureTransactionChain(txId.getHistoryId(), null).newReadOnlyTransaction(txId);
584 ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
585 shard.getShardMBean().incrementReadWriteTransactionCount();
587 if (txId.getHistoryId().getHistoryId() == 0) {
588 return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
592 return ensureTransactionChain(txId.getHistoryId(), null).newReadWriteTransaction(txId);
596 public void notifyListeners(final DataTreeCandidate candidate) {
597 treeChangeListenerPublisher.publishChanges(candidate);
601 * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
602 * replication callbacks.
604 void purgeLeaderState() {
605 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
609 transactionChains.clear();
610 replicationCallbacks.clear();
614 * Close a single transaction chain.
616 * @param id History identifier
617 * @param callback Callback to invoke upon completion, may be null
619 void closeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
620 if (commonCloseTransactionChain(id, callback)) {
621 replicatePayload(id, CloseLocalHistoryPayload.create(id,
622 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
627 * Close a single transaction chain which is received through ask-based protocol. It does not keep a commit record.
629 * @param id History identifier
631 void closeTransactionChain(final LocalHistoryIdentifier id) {
632 commonCloseTransactionChain(id, null);
635 private boolean commonCloseTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
636 final ShardDataTreeTransactionChain chain = transactionChains.get(id);
638 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
639 if (callback != null) {
650 * Purge a single transaction chain.
652 * @param id History identifier
653 * @param callback Callback to invoke upon completion, may be null
655 void purgeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
656 final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
658 LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
659 if (callback != null) {
665 replicatePayload(id, PurgeLocalHistoryPayload.create(
666 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
669 Optional<DataTreeCandidate> readCurrentData() {
670 return dataTree.takeSnapshot().readNode(YangInstanceIdentifier.empty())
671 .map(state -> DataTreeCandidates.fromNormalizedNode(YangInstanceIdentifier.empty(), state));
674 public void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
675 final Optional<DataTreeCandidate> initialState,
676 final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
677 treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
681 return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
685 void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
686 final TransactionIdentifier id = transaction.getIdentifier();
687 LOG.debug("{}: aborting transaction {}", logContext, id);
688 replicatePayload(id, AbortTransactionPayload.create(
689 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
693 void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
694 // No-op for free-standing transactions
699 ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction,
700 final Optional<SortedSet<String>> participatingShardNames) {
701 final DataTreeModification snapshot = transaction.getSnapshot();
702 final TransactionIdentifier id = transaction.getIdentifier();
703 LOG.debug("{}: readying transaction {}", logContext, id);
705 LOG.debug("{}: transaction {} ready", logContext, id);
707 return createReadyCohort(transaction.getIdentifier(), snapshot, participatingShardNames);
710 void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
711 LOG.debug("{}: purging transaction {}", logContext, id);
712 replicatePayload(id, PurgeTransactionPayload.create(
713 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
716 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
717 return dataTree.takeSnapshot().readNode(path);
720 DataTreeSnapshot takeSnapshot() {
721 return dataTree.takeSnapshot();
725 public DataTreeModification newModification() {
726 return dataTree.takeSnapshot().newModification();
729 public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
730 Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
732 for (CommitEntry entry: pendingFinishCommits) {
733 ret.add(entry.cohort);
736 for (CommitEntry entry: pendingCommits) {
737 ret.add(entry.cohort);
740 for (CommitEntry entry: pendingTransactions) {
741 ret.add(entry.cohort);
744 pendingFinishCommits.clear();
745 pendingCommits.clear();
746 pendingTransactions.clear();
752 * Called some time after {@link #processNextPendingTransaction()} decides to stop processing.
754 void resumeNextPendingTransaction() {
755 LOG.debug("{}: attempting to resume transaction processing", logContext);
756 processNextPending();
759 @SuppressWarnings("checkstyle:IllegalCatch")
760 private void processNextPendingTransaction() {
761 ++currentTransactionBatch;
762 if (currentTransactionBatch > MAX_TRANSACTION_BATCH) {
763 LOG.debug("{}: Already processed {}, scheduling continuation", logContext, currentTransactionBatch);
764 shard.scheduleNextPendingTransaction();
768 processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
769 final SimpleShardDataTreeCohort cohort = entry.cohort;
770 final DataTreeModification modification = cohort.getDataTreeModification();
772 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
775 tip.validate(modification);
776 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
777 cohort.successfulCanCommit();
778 entry.lastAccess = readTime();
780 } catch (ConflictingModificationAppliedException e) {
781 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
783 cause = new OptimisticLockFailedException("Optimistic lock failed for path " + e.getPath(), e);
784 } catch (DataValidationFailedException e) {
785 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
788 // For debugging purposes, allow dumping of the modification. Coupled with the above
789 // precondition log, it should allow us to understand what went on.
790 LOG.debug("{}: Store Tx {}: modifications: {}", logContext, cohort.getIdentifier(), modification);
791 LOG.trace("{}: Current tree: {}", logContext, dataTree);
792 cause = new TransactionCommitFailedException("Data did not pass validation for path " + e.getPath(), e);
793 } catch (Exception e) {
794 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
798 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
799 pendingTransactions.poll().cohort.failedCanCommit(cause);
803 private void processNextPending() {
804 processNextPendingCommit();
805 processNextPendingTransaction();
808 private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
809 final Consumer<CommitEntry> processor) {
810 while (!queue.isEmpty()) {
811 final CommitEntry entry = queue.peek();
812 final SimpleShardDataTreeCohort cohort = entry.cohort;
814 if (cohort.isFailed()) {
815 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
820 if (cohort.getState() == allowedState) {
821 processor.accept(entry);
827 maybeRunOperationOnPendingTransactionsComplete();
830 private void processNextPendingCommit() {
831 processNextPending(pendingCommits, State.COMMIT_PENDING,
832 entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
835 private boolean peekNextPendingCommit() {
836 final CommitEntry first = pendingCommits.peek();
837 return first != null && first.cohort.getState() == State.COMMIT_PENDING;
840 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
841 final CommitEntry head = pendingTransactions.peek();
843 LOG.warn("{}: No transactions enqueued while attempting to start canCommit on {}", logContext, cohort);
846 if (!cohort.equals(head.cohort)) {
847 // The tx isn't at the head of the queue so we can't start canCommit at this point. Here we check if this
848 // tx should be moved ahead of other tx's in the READY state in the pendingTransactions queue. If this tx
849 // has other participating shards, it could deadlock with other tx's accessing the same shards
850 // depending on the order the tx's are readied on each shard
851 // (see https://jira.opendaylight.org/browse/CONTROLLER-1836). Therefore, if the preceding participating
852 // shard names for a preceding pending tx, call it A, in the queue matches that of this tx, then this tx
853 // is allowed to be moved ahead of tx A in the queue so it is processed first to avoid potential deadlock
854 // if tx A is behind this tx in the pendingTransactions queue for a preceding shard. In other words, since
855 // canCommmit for this tx was requested before tx A, honor that request. If this tx is moved to the head of
856 // the queue as a result, then proceed with canCommit.
858 Collection<String> precedingShardNames = extractPrecedingShardNames(cohort.getParticipatingShardNames());
859 if (precedingShardNames.isEmpty()) {
860 LOG.debug("{}: Tx {} is scheduled for canCommit step", logContext, cohort.getIdentifier());
864 LOG.debug("{}: Evaluating tx {} for canCommit - preceding participating shard names {}",
865 logContext, cohort.getIdentifier(), precedingShardNames);
866 final Iterator<CommitEntry> iter = pendingTransactions.iterator();
868 int moveToIndex = -1;
869 while (iter.hasNext()) {
870 final CommitEntry entry = iter.next();
873 if (cohort.equals(entry.cohort)) {
874 if (moveToIndex < 0) {
875 LOG.debug("{}: Not moving tx {} - cannot proceed with canCommit",
876 logContext, cohort.getIdentifier());
880 LOG.debug("{}: Moving {} to index {} in the pendingTransactions queue",
881 logContext, cohort.getIdentifier(), moveToIndex);
883 insertEntry(pendingTransactions, entry, moveToIndex);
885 if (!cohort.equals(pendingTransactions.peek().cohort)) {
886 LOG.debug("{}: Tx {} is not at the head of the queue - cannot proceed with canCommit",
887 logContext, cohort.getIdentifier());
891 LOG.debug("{}: Tx {} is now at the head of the queue - proceeding with canCommit",
892 logContext, cohort.getIdentifier());
896 if (entry.cohort.getState() != State.READY) {
897 LOG.debug("{}: Skipping pending transaction {} in state {}",
898 logContext, entry.cohort.getIdentifier(), entry.cohort.getState());
902 final Collection<String> pendingPrecedingShardNames = extractPrecedingShardNames(
903 entry.cohort.getParticipatingShardNames());
905 if (precedingShardNames.equals(pendingPrecedingShardNames)) {
906 if (moveToIndex < 0) {
907 LOG.debug("{}: Preceding shard names {} for pending tx {} match - saving moveToIndex {}",
908 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), index);
912 "{}: Preceding shard names {} for pending tx {} match but moveToIndex already set to {}",
913 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), moveToIndex);
916 LOG.debug("{}: Preceding shard names {} for pending tx {} differ - skipping",
917 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier());
922 processNextPendingTransaction();
925 private static void insertEntry(final Deque<CommitEntry> queue, final CommitEntry entry, final int atIndex) {
927 queue.addFirst(entry);
931 LOG.trace("Inserting into Deque at index {}", atIndex);
933 Deque<CommitEntry> tempStack = new ArrayDeque<>(atIndex);
934 for (int i = 0; i < atIndex; i++) {
935 tempStack.push(queue.poll());
938 queue.addFirst(entry);
940 tempStack.forEach(queue::addFirst);
943 private Collection<String> extractPrecedingShardNames(final Optional<SortedSet<String>> participatingShardNames) {
944 return participatingShardNames.map((Function<SortedSet<String>, Collection<String>>)
945 set -> set.headSet(shard.getShardName())).orElse(Collections.<String>emptyList());
948 private void failPreCommit(final Throwable cause) {
949 shard.getShardMBean().incrementFailedTransactionsCount();
950 pendingTransactions.poll().cohort.failedPreCommit(cause);
951 processNextPendingTransaction();
954 @SuppressWarnings("checkstyle:IllegalCatch")
955 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
956 final CommitEntry entry = pendingTransactions.peek();
957 checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
959 final SimpleShardDataTreeCohort current = entry.cohort;
960 verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
962 final TransactionIdentifier currentId = current.getIdentifier();
963 LOG.debug("{}: Preparing transaction {}", logContext, currentId);
965 final DataTreeCandidateTip candidate;
967 candidate = tip.prepare(cohort.getDataTreeModification());
968 LOG.debug("{}: Transaction {} candidate ready", logContext, currentId);
969 } catch (DataValidationFailedException | RuntimeException e) {
974 cohort.userPreCommit(candidate, new FutureCallback<Void>() {
976 public void onSuccess(final Void noop) {
977 // Set the tip of the data tree.
978 tip = verifyNotNull(candidate);
980 entry.lastAccess = readTime();
982 pendingTransactions.remove();
983 pendingCommits.add(entry);
985 LOG.debug("{}: Transaction {} prepared", logContext, currentId);
987 cohort.successfulPreCommit(candidate);
989 processNextPendingTransaction();
993 public void onFailure(final Throwable failure) {
994 failPreCommit(failure);
999 private void failCommit(final Exception cause) {
1000 shard.getShardMBean().incrementFailedTransactionsCount();
1001 pendingFinishCommits.poll().cohort.failedCommit(cause);
1002 processNextPending();
1005 @SuppressWarnings("checkstyle:IllegalCatch")
1006 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
1007 final TransactionIdentifier txId = cohort.getIdentifier();
1008 final DataTreeCandidate candidate = cohort.getCandidate();
1010 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
1012 if (tip == candidate) {
1013 // All pending candidates have been committed, reset the tip to the data tree.
1018 dataTree.commit(candidate);
1019 } catch (Exception e) {
1020 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
1025 allMetadataCommittedTransaction(txId);
1026 shard.getShardMBean().incrementCommittedTransactionCount();
1027 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
1029 // FIXME: propagate journal index
1030 pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO, () -> {
1031 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
1032 notifyListeners(candidate);
1034 processNextPending();
1038 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
1039 final CommitEntry entry = pendingCommits.peek();
1040 checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
1042 final SimpleShardDataTreeCohort current = entry.cohort;
1043 if (!cohort.equals(current)) {
1044 LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
1048 LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
1050 final TransactionIdentifier txId = cohort.getIdentifier();
1051 final Payload payload;
1053 payload = CommitTransactionPayload.create(txId, candidate, PayloadVersion.current(),
1054 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity());
1055 } catch (IOException e) {
1056 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
1057 pendingCommits.poll().cohort.failedCommit(e);
1058 processNextPending();
1062 // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
1063 // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
1064 // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
1065 // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
1066 // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
1067 // pendingCommits queue.
1068 processNextPendingTransaction();
1070 // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
1071 // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
1072 // in order to properly determine the batchHint flag for the call to persistPayload.
1073 pendingCommits.remove();
1074 pendingFinishCommits.add(entry);
1076 // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
1077 // this transaction for replication.
1078 boolean replicationBatchHint = peekNextPendingCommit();
1080 // Once completed, we will continue via payloadReplicationComplete
1081 shard.persistPayload(txId, payload, replicationBatchHint);
1083 entry.lastAccess = shard.ticker().read();
1085 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
1087 // Process the next transaction pending commit, if any. If there is one it will be batched with this
1088 // transaction for replication.
1089 processNextPendingCommit();
1092 Collection<ActorRef> getCohortActors() {
1093 return cohortRegistry.getCohortActors();
1096 void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
1097 cohortRegistry.process(sender, message);
1101 ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1102 final Exception failure) {
1103 final SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId, failure);
1104 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1109 ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1110 final Optional<SortedSet<String>> participatingShardNames) {
1111 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId,
1112 cohortRegistry.createCohort(schemaContext, txId, shard::executeInSelf,
1113 COMMIT_STEP_TIMEOUT), participatingShardNames);
1114 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1118 // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
1119 // the newReadWriteTransaction()
1120 ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1121 final Optional<SortedSet<String>> participatingShardNames) {
1122 if (txId.getHistoryId().getHistoryId() == 0) {
1123 return createReadyCohort(txId, mod, participatingShardNames);
1126 return ensureTransactionChain(txId.getHistoryId(), null).createReadyCohort(txId, mod, participatingShardNames);
1129 @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
1130 void checkForExpiredTransactions(final long transactionCommitTimeoutMillis,
1131 final Function<SimpleShardDataTreeCohort, OptionalLong> accessTimeUpdater) {
1132 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
1133 final long now = readTime();
1135 final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
1136 !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
1137 final CommitEntry currentTx = currentQueue.peek();
1138 if (currentTx == null) {
1139 // Empty queue, no-op
1143 long delta = now - currentTx.lastAccess;
1144 if (delta < timeout) {
1145 // Not expired yet, bail
1149 final OptionalLong updateOpt = accessTimeUpdater.apply(currentTx.cohort);
1150 if (updateOpt.isPresent()) {
1151 final long newAccess = updateOpt.getAsLong();
1152 final long newDelta = now - newAccess;
1153 if (newDelta < delta) {
1154 LOG.debug("{}: Updated current transaction {} access time", logContext,
1155 currentTx.cohort.getIdentifier());
1156 currentTx.lastAccess = newAccess;
1160 if (delta < timeout) {
1161 // Not expired yet, bail
1166 final long deltaMillis = TimeUnit.NANOSECONDS.toMillis(delta);
1167 final State state = currentTx.cohort.getState();
1169 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
1170 currentTx.cohort.getIdentifier(), deltaMillis, state);
1171 boolean processNext = true;
1172 final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
1173 + deltaMillis + "ms");
1176 case CAN_COMMIT_PENDING:
1177 currentQueue.remove().cohort.failedCanCommit(cohortFailure);
1179 case CAN_COMMIT_COMPLETE:
1180 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
1181 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
1182 // in PRE_COMMIT_COMPLETE is changed.
1183 currentQueue.remove().cohort.reportFailure(cohortFailure);
1185 case PRE_COMMIT_PENDING:
1186 currentQueue.remove().cohort.failedPreCommit(cohortFailure);
1188 case PRE_COMMIT_COMPLETE:
1189 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
1190 // are ready we should commit the transaction, not abort it. Our current software stack does
1191 // not allow us to do that consistently, because we persist at the time of commit, hence
1192 // we can end up in a state where we have pre-committed a transaction, then a leader failover
1193 // occurred ... the new leader does not see the pre-committed transaction and does not have
1194 // a running timer. To fix this we really need two persistence events.
1196 // The first one, done at pre-commit time will hold the transaction payload. When consensus
1197 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1198 // apply the state in this event.
1200 // The second one, done at commit (or abort) time holds only the transaction identifier and
1201 // signals to followers that the state should (or should not) be applied.
1203 // In order to make the pre-commit timer working across failovers, though, we need
1204 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1205 // restart the timer.
1206 currentQueue.remove().cohort.reportFailure(cohortFailure);
1208 case COMMIT_PENDING:
1209 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1210 currentTx.cohort.getIdentifier());
1211 currentTx.lastAccess = now;
1212 processNext = false;
1215 currentQueue.remove().cohort.reportFailure(cohortFailure);
1221 currentQueue.remove();
1225 processNextPending();
1229 boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1230 final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1231 pendingTransactions).iterator();
1232 if (!it.hasNext()) {
1233 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1237 // First entry is special, as it may already be committing
1238 final CommitEntry first = it.next();
1239 if (cohort.equals(first.cohort)) {
1240 if (cohort.getState() != State.COMMIT_PENDING) {
1241 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1242 cohort.getIdentifier());
1245 if (cohort.getCandidate() != null) {
1246 rebaseTransactions(it, dataTree);
1249 processNextPending();
1253 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1257 DataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
1258 while (it.hasNext()) {
1259 final CommitEntry e = it.next();
1260 if (cohort.equals(e.cohort)) {
1261 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1264 if (cohort.getCandidate() != null) {
1265 rebaseTransactions(it, newTip);
1270 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), newTip);
1274 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1278 @SuppressWarnings("checkstyle:IllegalCatch")
1279 private void rebaseTransactions(final Iterator<CommitEntry> iter, final @NonNull DataTreeTip newTip) {
1280 tip = requireNonNull(newTip);
1281 while (iter.hasNext()) {
1282 final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1283 if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1284 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1287 tip.validate(cohort.getDataTreeModification());
1288 } catch (DataValidationFailedException | RuntimeException e) {
1289 LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1290 cohort.reportFailure(e);
1292 } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1293 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1296 tip.validate(cohort.getDataTreeModification());
1297 DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1299 cohort.setNewCandidate(candidate);
1301 } catch (RuntimeException | DataValidationFailedException e) {
1302 LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1303 cohort.reportFailure(e);
1309 void setRunOnPendingTransactionsComplete(final Runnable operation) {
1310 runOnPendingTransactionsComplete = operation;
1311 maybeRunOperationOnPendingTransactionsComplete();
1314 private void maybeRunOperationOnPendingTransactionsComplete() {
1315 if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1316 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1317 runOnPendingTransactionsComplete);
1319 runOnPendingTransactionsComplete.run();
1320 runOnPendingTransactionsComplete = null;
1324 ShardStats getStats() {
1325 return shard.getShardMBean();
1328 Iterator<SimpleShardDataTreeCohort> cohortIterator() {
1329 return Iterables.transform(Iterables.concat(pendingFinishCommits, pendingCommits, pendingTransactions),
1330 e -> e.cohort).iterator();
1333 void removeTransactionChain(final LocalHistoryIdentifier id) {
1334 if (transactionChains.remove(id) != null) {
1335 LOG.debug("{}: Removed transaction chain {}", logContext, id);