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 akka.actor.ActorRef;
11 import akka.util.Timeout;
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.MoreObjects;
14 import com.google.common.base.Optional;
15 import com.google.common.base.Preconditions;
16 import com.google.common.base.Stopwatch;
17 import com.google.common.base.Verify;
18 import com.google.common.collect.ImmutableList;
19 import com.google.common.collect.ImmutableMap;
20 import com.google.common.collect.ImmutableMap.Builder;
21 import com.google.common.collect.Iterables;
22 import com.google.common.primitives.UnsignedLong;
23 import com.google.common.util.concurrent.FutureCallback;
24 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
26 import java.io.IOException;
27 import java.util.ArrayDeque;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.Deque;
32 import java.util.HashMap;
33 import java.util.Iterator;
35 import java.util.Map.Entry;
36 import java.util.OptionalLong;
37 import java.util.Queue;
38 import java.util.SortedSet;
39 import java.util.concurrent.TimeUnit;
40 import java.util.concurrent.TimeoutException;
41 import java.util.function.Consumer;
42 import java.util.function.Function;
43 import java.util.function.UnaryOperator;
44 import org.eclipse.jdt.annotation.NonNull;
45 import org.eclipse.jdt.annotation.Nullable;
46 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
47 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
48 import org.opendaylight.controller.cluster.datastore.DataTreeCohortActorRegistry.CohortRegistryCommand;
49 import org.opendaylight.controller.cluster.datastore.ShardDataTreeCohort.State;
50 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
51 import org.opendaylight.controller.cluster.datastore.persisted.AbortTransactionPayload;
52 import org.opendaylight.controller.cluster.datastore.persisted.AbstractIdentifiablePayload;
53 import org.opendaylight.controller.cluster.datastore.persisted.CloseLocalHistoryPayload;
54 import org.opendaylight.controller.cluster.datastore.persisted.CommitTransactionPayload;
55 import org.opendaylight.controller.cluster.datastore.persisted.CreateLocalHistoryPayload;
56 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
57 import org.opendaylight.controller.cluster.datastore.persisted.PurgeLocalHistoryPayload;
58 import org.opendaylight.controller.cluster.datastore.persisted.PurgeTransactionPayload;
59 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
60 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshotMetadata;
61 import org.opendaylight.controller.cluster.datastore.utils.DataTreeModificationOutput;
62 import org.opendaylight.controller.cluster.datastore.utils.PruningDataTreeModification;
63 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
64 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
65 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
66 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
67 import org.opendaylight.yangtools.concepts.Identifier;
68 import org.opendaylight.yangtools.concepts.ListenerRegistration;
69 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
70 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
72 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
73 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
74 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
75 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
76 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
77 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
78 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
79 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeTip;
80 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
81 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
82 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
83 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
84 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
85 import org.slf4j.Logger;
86 import org.slf4j.LoggerFactory;
87 import scala.concurrent.duration.FiniteDuration;
90 * Internal shard state, similar to a DOMStore, but optimized for use in the actor system, e.g. it does not expose
91 * public interfaces and assumes it is only ever called from a single thread.
94 * This class is not part of the API contract and is subject to change at any time. It is NOT thread-safe.
96 public class ShardDataTree extends ShardDataTreeTransactionParent {
97 private static final class CommitEntry {
98 final SimpleShardDataTreeCohort cohort;
101 CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
102 this.cohort = Preconditions.checkNotNull(cohort);
107 public String toString() {
108 return "CommitEntry [tx=" + cohort.getIdentifier() + ", state=" + cohort.getState() + "]";
112 private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(FiniteDuration.create(5, TimeUnit.SECONDS));
113 private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
116 * Process this many transactions in a single batched run. If we exceed this limit, we need to schedule later
117 * execution to finish up the batch. This is necessary in case of a long list of transactions which progress
118 * immediately through their preCommit phase -- if that happens, their completion eats up stack frames and could
119 * result in StackOverflowError.
121 private static final int MAX_TRANSACTION_BATCH = 100;
123 private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
124 private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
125 private final Deque<CommitEntry> pendingTransactions = new ArrayDeque<>();
126 private final Queue<CommitEntry> pendingCommits = new ArrayDeque<>();
127 private final Queue<CommitEntry> pendingFinishCommits = new ArrayDeque<>();
130 * Callbacks that need to be invoked once a payload is replicated.
132 private final Map<Payload, Runnable> replicationCallbacks = new HashMap<>();
134 private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
135 private final Collection<ShardDataTreeMetadata<?>> metadata;
136 private final DataTree dataTree;
137 private final String logContext;
138 private final Shard shard;
139 private Runnable runOnPendingTransactionsComplete;
142 * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
143 * {@link DataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
144 * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
145 * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
147 private DataTreeTip tip;
149 private SchemaContext schemaContext;
150 private DataSchemaContextTree dataSchemaContext;
152 private int currentTransactionBatch;
154 ShardDataTree(final Shard shard, final SchemaContext schemaContext, final DataTree dataTree,
155 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
156 final String logContext,
157 final ShardDataTreeMetadata<?>... metadata) {
158 this.dataTree = Preconditions.checkNotNull(dataTree);
159 updateSchemaContext(schemaContext);
161 this.shard = Preconditions.checkNotNull(shard);
162 this.treeChangeListenerPublisher = Preconditions.checkNotNull(treeChangeListenerPublisher);
163 this.logContext = Preconditions.checkNotNull(logContext);
164 this.metadata = ImmutableList.copyOf(metadata);
168 ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType,
169 final YangInstanceIdentifier root,
170 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
171 final String logContext,
172 final ShardDataTreeMetadata<?>... metadata) {
173 this(shard, schemaContext, createDataTree(treeType, root), treeChangeListenerPublisher, logContext, metadata);
176 private static DataTree createDataTree(final TreeType treeType, final YangInstanceIdentifier root) {
177 final DataTreeConfiguration baseConfig = DataTreeConfiguration.getDefault(treeType);
178 return new InMemoryDataTreeFactory().create(new DataTreeConfiguration.Builder(baseConfig.getTreeType())
179 .setMandatoryNodesValidation(baseConfig.isMandatoryNodesValidationEnabled())
180 .setUniqueIndexes(baseConfig.isUniqueIndexEnabled())
186 public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType) {
187 this(shard, schemaContext, treeType, YangInstanceIdentifier.EMPTY,
188 new DefaultShardDataTreeChangeListenerPublisher(""), "");
191 final String logContext() {
195 final long readTime() {
196 return shard.ticker().read();
199 public DataTree getDataTree() {
203 SchemaContext getSchemaContext() {
204 return schemaContext;
207 void updateSchemaContext(final SchemaContext newSchemaContext) {
208 dataTree.setSchemaContext(newSchemaContext);
209 this.schemaContext = Preconditions.checkNotNull(newSchemaContext);
210 this.dataSchemaContext = DataSchemaContextTree.from(newSchemaContext);
213 void resetTransactionBatch() {
214 currentTransactionBatch = 0;
218 * Take a snapshot of current state for later recovery.
220 * @return A state snapshot
222 @NonNull ShardDataTreeSnapshot takeStateSnapshot() {
223 final NormalizedNode<?, ?> rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY).get();
224 final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
225 ImmutableMap.builder();
227 for (ShardDataTreeMetadata<?> m : metadata) {
228 final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
230 metaBuilder.put(meta.getType(), meta);
234 return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
237 private boolean anyPendingTransactions() {
238 return !pendingTransactions.isEmpty() || !pendingCommits.isEmpty() || !pendingFinishCommits.isEmpty();
241 private void applySnapshot(final @NonNull ShardDataTreeSnapshot snapshot,
242 final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
243 final Stopwatch elapsed = Stopwatch.createStarted();
245 if (anyPendingTransactions()) {
246 LOG.warn("{}: applying state snapshot with pending transactions", logContext);
249 final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
250 if (snapshot instanceof MetadataShardDataTreeSnapshot) {
251 snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
253 snapshotMeta = ImmutableMap.of();
256 for (ShardDataTreeMetadata<?> m : metadata) {
257 final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
265 final DataTreeModification mod = wrapper.apply(dataTree.takeSnapshot().newModification());
266 // delete everything first
267 mod.delete(YangInstanceIdentifier.EMPTY);
269 final java.util.Optional<NormalizedNode<?, ?>> maybeNode = snapshot.getRootNode();
270 if (maybeNode.isPresent()) {
271 // Add everything from the remote node back
272 mod.write(YangInstanceIdentifier.EMPTY, maybeNode.get());
276 final DataTreeModification unwrapped = unwrap(mod);
277 dataTree.validate(unwrapped);
278 DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
279 dataTree.commit(candidate);
280 notifyListeners(candidate);
282 LOG.debug("{}: state snapshot applied in {}", logContext, elapsed);
286 * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
287 * does not perform any pruning.
289 * @param snapshot Snapshot that needs to be applied
290 * @throws DataValidationFailedException when the snapshot fails to apply
292 void applySnapshot(final @NonNull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
293 applySnapshot(snapshot, UnaryOperator.identity());
296 private PruningDataTreeModification wrapWithPruning(final DataTreeModification delegate) {
297 return new PruningDataTreeModification(delegate, dataTree, dataSchemaContext);
300 private static DataTreeModification unwrap(final DataTreeModification modification) {
301 if (modification instanceof PruningDataTreeModification) {
302 return ((PruningDataTreeModification)modification).delegate();
308 * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
309 * pruning in an attempt to adjust the state to our current SchemaContext.
311 * @param snapshot Snapshot that needs to be applied
312 * @throws DataValidationFailedException when the snapshot fails to apply
314 void applyRecoverySnapshot(final @NonNull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
315 applySnapshot(snapshot, this::wrapWithPruning);
318 @SuppressWarnings("checkstyle:IllegalCatch")
319 private void applyRecoveryCandidate(final DataTreeCandidate candidate) {
320 final PruningDataTreeModification mod = wrapWithPruning(dataTree.takeSnapshot().newModification());
321 DataTreeCandidates.applyToModification(mod, candidate);
324 final DataTreeModification unwrapped = mod.delegate();
325 LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
328 dataTree.validate(unwrapped);
329 dataTree.commit(dataTree.prepare(unwrapped));
330 } catch (Exception e) {
331 File file = new File(System.getProperty("karaf.data", "."),
332 "failed-recovery-payload-" + logContext + ".out");
333 DataTreeModificationOutput.toFile(file, unwrapped);
334 throw new IllegalStateException(String.format(
335 "%s: Failed to apply recovery payload. Modification data was written to file %s",
336 logContext, file), e);
341 * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
342 * pruning in an attempt to adjust the state to our current SchemaContext.
344 * @param payload Payload
345 * @throws IOException when the snapshot fails to deserialize
346 * @throws DataValidationFailedException when the snapshot fails to apply
348 void applyRecoveryPayload(final @NonNull Payload payload) throws IOException {
349 if (payload instanceof CommitTransactionPayload) {
350 final Entry<TransactionIdentifier, DataTreeCandidate> e =
351 ((CommitTransactionPayload) payload).getCandidate();
352 applyRecoveryCandidate(e.getValue());
353 allMetadataCommittedTransaction(e.getKey());
354 } else if (payload instanceof AbortTransactionPayload) {
355 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
356 } else if (payload instanceof PurgeTransactionPayload) {
357 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
358 } else if (payload instanceof CreateLocalHistoryPayload) {
359 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
360 } else if (payload instanceof CloseLocalHistoryPayload) {
361 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
362 } else if (payload instanceof PurgeLocalHistoryPayload) {
363 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
365 LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
369 private void applyReplicatedCandidate(final TransactionIdentifier identifier, final DataTreeCandidate foreign)
370 throws DataValidationFailedException {
371 LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
373 final DataTreeModification mod = dataTree.takeSnapshot().newModification();
374 DataTreeCandidates.applyToModification(mod, foreign);
377 LOG.trace("{}: Applying foreign modification {}", logContext, mod);
378 dataTree.validate(mod);
379 final DataTreeCandidate candidate = dataTree.prepare(mod);
380 dataTree.commit(candidate);
382 allMetadataCommittedTransaction(identifier);
383 notifyListeners(candidate);
387 * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
388 * SchemaContexts match and does not perform any pruning.
390 * @param identifier Payload identifier as returned from RaftActor
391 * @param payload Payload
392 * @throws IOException when the snapshot fails to deserialize
393 * @throws DataValidationFailedException when the snapshot fails to apply
395 void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
396 DataValidationFailedException {
398 * 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
399 * if we are the leader and it has originated with us.
401 * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
402 * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
403 * acting in that capacity anymore.
405 * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
406 * pre-Boron state -- which limits the number of options here.
408 if (payload instanceof CommitTransactionPayload) {
409 if (identifier == null) {
410 final Entry<TransactionIdentifier, DataTreeCandidate> e =
411 ((CommitTransactionPayload) payload).getCandidate();
412 applyReplicatedCandidate(e.getKey(), e.getValue());
414 Verify.verify(identifier instanceof TransactionIdentifier);
415 payloadReplicationComplete((TransactionIdentifier) identifier);
417 } else if (payload instanceof AbortTransactionPayload) {
418 if (identifier != null) {
419 payloadReplicationComplete((AbortTransactionPayload) payload);
421 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
422 } else if (payload instanceof PurgeTransactionPayload) {
423 if (identifier != null) {
424 payloadReplicationComplete((PurgeTransactionPayload) payload);
426 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
427 } else if (payload instanceof CloseLocalHistoryPayload) {
428 if (identifier != null) {
429 payloadReplicationComplete((CloseLocalHistoryPayload) payload);
431 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
432 } else if (payload instanceof CreateLocalHistoryPayload) {
433 if (identifier != null) {
434 payloadReplicationComplete((CreateLocalHistoryPayload)payload);
436 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
437 } else if (payload instanceof PurgeLocalHistoryPayload) {
438 if (identifier != null) {
439 payloadReplicationComplete((PurgeLocalHistoryPayload)payload);
441 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
443 LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
447 private void replicatePayload(final Identifier id, final Payload payload, final @Nullable Runnable callback) {
448 if (callback != null) {
449 replicationCallbacks.put(payload, callback);
451 shard.persistPayload(id, payload, true);
454 private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
455 final Runnable callback = replicationCallbacks.remove(payload);
456 if (callback != null) {
457 LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
460 LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
464 private void payloadReplicationComplete(final TransactionIdentifier txId) {
465 final CommitEntry current = pendingFinishCommits.peek();
466 if (current == null) {
467 LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
468 allMetadataCommittedTransaction(txId);
472 if (!current.cohort.getIdentifier().equals(txId)) {
473 LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
474 current.cohort.getIdentifier(), txId);
475 allMetadataCommittedTransaction(txId);
479 finishCommit(current.cohort);
482 private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
483 for (ShardDataTreeMetadata<?> m : metadata) {
484 m.onTransactionAborted(txId);
488 private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
489 for (ShardDataTreeMetadata<?> m : metadata) {
490 m.onTransactionCommitted(txId);
494 private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
495 for (ShardDataTreeMetadata<?> m : metadata) {
496 m.onTransactionPurged(txId);
500 private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
501 for (ShardDataTreeMetadata<?> m : metadata) {
502 m.onHistoryCreated(historyId);
506 private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
507 for (ShardDataTreeMetadata<?> m : metadata) {
508 m.onHistoryClosed(historyId);
512 private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
513 for (ShardDataTreeMetadata<?> m : metadata) {
514 m.onHistoryPurged(historyId);
519 * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
520 * this method is used for re-establishing state when we are taking over
522 * @param historyId Local history identifier
523 * @param closed True if the chain should be created in closed state (i.e. pending purge)
524 * @return Transaction chain handle
526 ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
527 final boolean closed) {
528 final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
529 final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
530 Preconditions.checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId,
535 ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId,
536 final @Nullable Runnable callback) {
537 ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
539 chain = new ShardDataTreeTransactionChain(historyId, this);
540 transactionChains.put(historyId, chain);
541 replicatePayload(historyId, CreateLocalHistoryPayload.create(
542 historyId, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
543 } else if (callback != null) {
550 ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
551 shard.getShardMBean().incrementReadOnlyTransactionCount();
553 if (txId.getHistoryId().getHistoryId() == 0) {
554 return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
557 return ensureTransactionChain(txId.getHistoryId(), null).newReadOnlyTransaction(txId);
560 ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
561 shard.getShardMBean().incrementReadWriteTransactionCount();
563 if (txId.getHistoryId().getHistoryId() == 0) {
564 return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
568 return ensureTransactionChain(txId.getHistoryId(), null).newReadWriteTransaction(txId);
572 public void notifyListeners(final DataTreeCandidate candidate) {
573 treeChangeListenerPublisher.publishChanges(candidate);
577 * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
578 * replication callbacks.
580 void purgeLeaderState() {
581 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
585 transactionChains.clear();
586 replicationCallbacks.clear();
590 * Close a single transaction chain.
592 * @param id History identifier
593 * @param callback Callback to invoke upon completion, may be null
595 void closeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
596 if (commonCloseTransactionChain(id, callback)) {
597 replicatePayload(id, CloseLocalHistoryPayload.create(id,
598 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
603 * Close a single transaction chain which is received through ask-based protocol. It does not keep a commit record.
605 * @param id History identifier
607 void closeTransactionChain(final LocalHistoryIdentifier id) {
608 commonCloseTransactionChain(id, null);
611 private boolean commonCloseTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
612 final ShardDataTreeTransactionChain chain = transactionChains.get(id);
614 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
615 if (callback != null) {
626 * Purge a single transaction chain.
628 * @param id History identifier
629 * @param callback Callback to invoke upon completion, may be null
631 void purgeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
632 final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
634 LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
635 if (callback != null) {
641 replicatePayload(id, PurgeLocalHistoryPayload.create(
642 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
645 Optional<DataTreeCandidate> readCurrentData() {
646 final java.util.Optional<NormalizedNode<?, ?>> currentState =
647 dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY);
648 return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
649 YangInstanceIdentifier.EMPTY, currentState.get())) : Optional.<DataTreeCandidate>absent();
652 public void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
653 final Optional<DataTreeCandidate> initialState,
654 final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
655 treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
659 return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
663 void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
664 final TransactionIdentifier id = transaction.getIdentifier();
665 LOG.debug("{}: aborting transaction {}", logContext, id);
666 replicatePayload(id, AbortTransactionPayload.create(
667 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
671 void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
672 // No-op for free-standing transactions
677 ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction,
678 final java.util.Optional<SortedSet<String>> participatingShardNames) {
679 final DataTreeModification snapshot = transaction.getSnapshot();
680 final TransactionIdentifier id = transaction.getIdentifier();
681 LOG.debug("{}: readying transaction {}", logContext, id);
683 LOG.debug("{}: transaction {} ready", logContext, id);
685 return createReadyCohort(transaction.getIdentifier(), snapshot, participatingShardNames);
688 void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
689 LOG.debug("{}: purging transaction {}", logContext, id);
690 replicatePayload(id, PurgeTransactionPayload.create(
691 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
694 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
695 return Optional.fromJavaUtil(dataTree.takeSnapshot().readNode(path));
698 DataTreeSnapshot takeSnapshot() {
699 return dataTree.takeSnapshot();
703 public DataTreeModification newModification() {
704 return dataTree.takeSnapshot().newModification();
707 public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
708 Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
710 for (CommitEntry entry: pendingFinishCommits) {
711 ret.add(entry.cohort);
714 for (CommitEntry entry: pendingCommits) {
715 ret.add(entry.cohort);
718 for (CommitEntry entry: pendingTransactions) {
719 ret.add(entry.cohort);
722 pendingFinishCommits.clear();
723 pendingCommits.clear();
724 pendingTransactions.clear();
730 * Called some time after {@link #processNextPendingTransaction()} decides to stop processing.
732 void resumeNextPendingTransaction() {
733 LOG.debug("{}: attempting to resume transaction processing", logContext);
734 processNextPending();
737 @SuppressWarnings("checkstyle:IllegalCatch")
738 private void processNextPendingTransaction() {
739 ++currentTransactionBatch;
740 if (currentTransactionBatch > MAX_TRANSACTION_BATCH) {
741 LOG.debug("{}: Already processed {}, scheduling continuation", logContext, currentTransactionBatch);
742 shard.scheduleNextPendingTransaction();
746 processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
747 final SimpleShardDataTreeCohort cohort = entry.cohort;
748 final DataTreeModification modification = cohort.getDataTreeModification();
750 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
753 tip.validate(modification);
754 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
755 cohort.successfulCanCommit();
756 entry.lastAccess = readTime();
758 } catch (ConflictingModificationAppliedException e) {
759 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
761 cause = new OptimisticLockFailedException("Optimistic lock failed for path " + e.getPath(), e);
762 } catch (DataValidationFailedException e) {
763 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
766 // For debugging purposes, allow dumping of the modification. Coupled with the above
767 // precondition log, it should allow us to understand what went on.
768 LOG.debug("{}: Store Tx {}: modifications: {} tree: {}", logContext, cohort.getIdentifier(),
769 modification, dataTree);
770 cause = new TransactionCommitFailedException("Data did not pass validation for path " + e.getPath(), e);
771 } catch (Exception e) {
772 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
776 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
777 pendingTransactions.poll().cohort.failedCanCommit(cause);
781 private void processNextPending() {
782 processNextPendingCommit();
783 processNextPendingTransaction();
786 private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
787 final Consumer<CommitEntry> processor) {
788 while (!queue.isEmpty()) {
789 final CommitEntry entry = queue.peek();
790 final SimpleShardDataTreeCohort cohort = entry.cohort;
792 if (cohort.isFailed()) {
793 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
798 if (cohort.getState() == allowedState) {
799 processor.accept(entry);
805 maybeRunOperationOnPendingTransactionsComplete();
808 private void processNextPendingCommit() {
809 processNextPending(pendingCommits, State.COMMIT_PENDING,
810 entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
813 private boolean peekNextPendingCommit() {
814 final CommitEntry first = pendingCommits.peek();
815 return first != null && first.cohort.getState() == State.COMMIT_PENDING;
818 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
819 final CommitEntry head = pendingTransactions.peek();
821 LOG.warn("{}: No transactions enqueued while attempting to start canCommit on {}", logContext, cohort);
824 if (!cohort.equals(head.cohort)) {
825 // The tx isn't at the head of the queue so we can't start canCommit at this point. Here we check if this
826 // tx should be moved ahead of other tx's in the READY state in the pendingTransactions queue. If this tx
827 // has other participating shards, it could deadlock with other tx's accessing the same shards
828 // depending on the order the tx's are readied on each shard
829 // (see https://jira.opendaylight.org/browse/CONTROLLER-1836). Therefore, if the preceding participating
830 // shard names for a preceding pending tx, call it A, in the queue matches that of this tx, then this tx
831 // is allowed to be moved ahead of tx A in the queue so it is processed first to avoid potential deadlock
832 // if tx A is behind this tx in the pendingTransactions queue for a preceding shard. In other words, since
833 // canCommmit for this tx was requested before tx A, honor that request. If this tx is moved to the head of
834 // the queue as a result, then proceed with canCommit.
836 Collection<String> precedingShardNames = extractPrecedingShardNames(cohort.getParticipatingShardNames());
837 if (precedingShardNames.isEmpty()) {
838 LOG.debug("{}: Tx {} is scheduled for canCommit step", logContext, cohort.getIdentifier());
842 LOG.debug("{}: Evaluating tx {} for canCommit - preceding participating shard names {}",
843 logContext, cohort.getIdentifier(), precedingShardNames);
844 final Iterator<CommitEntry> iter = pendingTransactions.iterator();
846 int moveToIndex = -1;
847 while (iter.hasNext()) {
848 final CommitEntry entry = iter.next();
851 if (cohort.equals(entry.cohort)) {
852 if (moveToIndex < 0) {
853 LOG.debug("{}: Not moving tx {} - cannot proceed with canCommit",
854 logContext, cohort.getIdentifier());
858 LOG.debug("{}: Moving {} to index {} in the pendingTransactions queue",
859 logContext, cohort.getIdentifier(), moveToIndex);
861 insertEntry(pendingTransactions, entry, moveToIndex);
863 if (!cohort.equals(pendingTransactions.peek().cohort)) {
864 LOG.debug("{}: Tx {} is not at the head of the queue - cannot proceed with canCommit",
865 logContext, cohort.getIdentifier());
869 LOG.debug("{}: Tx {} is now at the head of the queue - proceeding with canCommit",
870 logContext, cohort.getIdentifier());
874 if (entry.cohort.getState() != State.READY) {
875 LOG.debug("{}: Skipping pending transaction {} in state {}",
876 logContext, entry.cohort.getIdentifier(), entry.cohort.getState());
880 final Collection<String> pendingPrecedingShardNames = extractPrecedingShardNames(
881 entry.cohort.getParticipatingShardNames());
883 if (precedingShardNames.equals(pendingPrecedingShardNames)) {
884 if (moveToIndex < 0) {
885 LOG.debug("{}: Preceding shard names {} for pending tx {} match - saving moveToIndex {}",
886 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), index);
890 "{}: Preceding shard names {} for pending tx {} match but moveToIndex already set to {}",
891 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), moveToIndex);
894 LOG.debug("{}: Preceding shard names {} for pending tx {} differ - skipping",
895 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier());
900 processNextPendingTransaction();
903 private static void insertEntry(final Deque<CommitEntry> queue, final CommitEntry entry, final int atIndex) {
905 queue.addFirst(entry);
909 LOG.trace("Inserting into Deque at index {}", atIndex);
911 Deque<CommitEntry> tempStack = new ArrayDeque<>(atIndex);
912 for (int i = 0; i < atIndex; i++) {
913 tempStack.push(queue.poll());
916 queue.addFirst(entry);
918 tempStack.forEach(queue::addFirst);
921 private Collection<String> extractPrecedingShardNames(
922 final java.util.Optional<SortedSet<String>> participatingShardNames) {
923 return participatingShardNames.map((Function<SortedSet<String>, Collection<String>>)
924 set -> set.headSet(shard.getShardName())).orElse(Collections.<String>emptyList());
927 private void failPreCommit(final Throwable cause) {
928 shard.getShardMBean().incrementFailedTransactionsCount();
929 pendingTransactions.poll().cohort.failedPreCommit(cause);
930 processNextPendingTransaction();
933 @SuppressWarnings("checkstyle:IllegalCatch")
934 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
935 final CommitEntry entry = pendingTransactions.peek();
936 Preconditions.checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
938 final SimpleShardDataTreeCohort current = entry.cohort;
939 Verify.verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
941 final TransactionIdentifier currentId = current.getIdentifier();
942 LOG.debug("{}: Preparing transaction {}", logContext, currentId);
944 final DataTreeCandidateTip candidate;
946 candidate = tip.prepare(cohort.getDataTreeModification());
947 LOG.debug("{}: Transaction {} candidate ready", logContext, currentId);
948 } catch (RuntimeException e) {
953 cohort.userPreCommit(candidate, new FutureCallback<Void>() {
955 public void onSuccess(final Void noop) {
956 // Set the tip of the data tree.
957 tip = Verify.verifyNotNull(candidate);
959 entry.lastAccess = readTime();
961 pendingTransactions.remove();
962 pendingCommits.add(entry);
964 LOG.debug("{}: Transaction {} prepared", logContext, currentId);
966 cohort.successfulPreCommit(candidate);
968 processNextPendingTransaction();
972 public void onFailure(final Throwable failure) {
973 failPreCommit(failure);
978 private void failCommit(final Exception cause) {
979 shard.getShardMBean().incrementFailedTransactionsCount();
980 pendingFinishCommits.poll().cohort.failedCommit(cause);
981 processNextPending();
984 @SuppressWarnings("checkstyle:IllegalCatch")
985 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
986 final TransactionIdentifier txId = cohort.getIdentifier();
987 final DataTreeCandidate candidate = cohort.getCandidate();
989 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
991 if (tip == candidate) {
992 // All pending candidates have been committed, reset the tip to the data tree.
997 dataTree.commit(candidate);
998 } catch (Exception e) {
999 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
1004 allMetadataCommittedTransaction(txId);
1005 shard.getShardMBean().incrementCommittedTransactionCount();
1006 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
1008 // FIXME: propagate journal index
1009 pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO, () -> {
1010 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
1011 notifyListeners(candidate);
1013 processNextPending();
1017 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
1018 final CommitEntry entry = pendingCommits.peek();
1019 Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
1021 final SimpleShardDataTreeCohort current = entry.cohort;
1022 if (!cohort.equals(current)) {
1023 LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
1027 LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
1029 final TransactionIdentifier txId = cohort.getIdentifier();
1030 final Payload payload;
1032 payload = CommitTransactionPayload.create(txId, candidate,
1033 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity());
1034 } catch (IOException e) {
1035 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
1036 pendingCommits.poll().cohort.failedCommit(e);
1037 processNextPending();
1041 // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
1042 // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
1043 // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
1044 // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
1045 // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
1046 // pendingCommits queue.
1047 processNextPendingTransaction();
1049 // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
1050 // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
1051 // in order to properly determine the batchHint flag for the call to persistPayload.
1052 pendingCommits.remove();
1053 pendingFinishCommits.add(entry);
1055 // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
1056 // this transaction for replication.
1057 boolean replicationBatchHint = peekNextPendingCommit();
1059 // Once completed, we will continue via payloadReplicationComplete
1060 shard.persistPayload(txId, payload, replicationBatchHint);
1062 entry.lastAccess = shard.ticker().read();
1064 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
1066 // Process the next transaction pending commit, if any. If there is one it will be batched with this
1067 // transaction for replication.
1068 processNextPendingCommit();
1071 Collection<ActorRef> getCohortActors() {
1072 return cohortRegistry.getCohortActors();
1075 void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
1076 cohortRegistry.process(sender, message);
1080 ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1081 final Exception failure) {
1082 final SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId, failure);
1083 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1088 ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1089 final java.util.Optional<SortedSet<String>> participatingShardNames) {
1090 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId,
1091 cohortRegistry.createCohort(schemaContext, txId, shard::executeInSelf,
1092 COMMIT_STEP_TIMEOUT), participatingShardNames);
1093 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1097 // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
1098 // the newReadWriteTransaction()
1099 ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1100 final java.util.Optional<SortedSet<String>> participatingShardNames) {
1101 if (txId.getHistoryId().getHistoryId() == 0) {
1102 return createReadyCohort(txId, mod, participatingShardNames);
1105 return ensureTransactionChain(txId.getHistoryId(), null).createReadyCohort(txId, mod, participatingShardNames);
1108 @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
1109 void checkForExpiredTransactions(final long transactionCommitTimeoutMillis,
1110 final Function<SimpleShardDataTreeCohort, OptionalLong> accessTimeUpdater) {
1111 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
1112 final long now = readTime();
1114 final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
1115 !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
1116 final CommitEntry currentTx = currentQueue.peek();
1117 if (currentTx == null) {
1118 // Empty queue, no-op
1122 long delta = now - currentTx.lastAccess;
1123 if (delta < timeout) {
1124 // Not expired yet, bail
1128 final OptionalLong updateOpt = accessTimeUpdater.apply(currentTx.cohort);
1129 if (updateOpt.isPresent()) {
1130 final long newAccess = updateOpt.getAsLong();
1131 final long newDelta = now - newAccess;
1132 if (newDelta < delta) {
1133 LOG.debug("{}: Updated current transaction {} access time", logContext,
1134 currentTx.cohort.getIdentifier());
1135 currentTx.lastAccess = newAccess;
1139 if (delta < timeout) {
1140 // Not expired yet, bail
1145 final long deltaMillis = TimeUnit.NANOSECONDS.toMillis(delta);
1146 final State state = currentTx.cohort.getState();
1148 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
1149 currentTx.cohort.getIdentifier(), deltaMillis, state);
1150 boolean processNext = true;
1151 final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
1152 + deltaMillis + "ms");
1155 case CAN_COMMIT_PENDING:
1156 currentQueue.remove().cohort.failedCanCommit(cohortFailure);
1158 case CAN_COMMIT_COMPLETE:
1159 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
1160 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
1161 // in PRE_COMMIT_COMPLETE is changed.
1162 currentQueue.remove().cohort.reportFailure(cohortFailure);
1164 case PRE_COMMIT_PENDING:
1165 currentQueue.remove().cohort.failedPreCommit(cohortFailure);
1167 case PRE_COMMIT_COMPLETE:
1168 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
1169 // are ready we should commit the transaction, not abort it. Our current software stack does
1170 // not allow us to do that consistently, because we persist at the time of commit, hence
1171 // we can end up in a state where we have pre-committed a transaction, then a leader failover
1172 // occurred ... the new leader does not see the pre-committed transaction and does not have
1173 // a running timer. To fix this we really need two persistence events.
1175 // The first one, done at pre-commit time will hold the transaction payload. When consensus
1176 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1177 // apply the state in this event.
1179 // The second one, done at commit (or abort) time holds only the transaction identifier and
1180 // signals to followers that the state should (or should not) be applied.
1182 // In order to make the pre-commit timer working across failovers, though, we need
1183 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1184 // restart the timer.
1185 currentQueue.remove().cohort.reportFailure(cohortFailure);
1187 case COMMIT_PENDING:
1188 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1189 currentTx.cohort.getIdentifier());
1190 currentTx.lastAccess = now;
1191 processNext = false;
1194 currentQueue.remove().cohort.reportFailure(cohortFailure);
1200 currentQueue.remove();
1204 processNextPending();
1208 boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1209 final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1210 pendingTransactions).iterator();
1211 if (!it.hasNext()) {
1212 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1216 // First entry is special, as it may already be committing
1217 final CommitEntry first = it.next();
1218 if (cohort.equals(first.cohort)) {
1219 if (cohort.getState() != State.COMMIT_PENDING) {
1220 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1221 cohort.getIdentifier());
1224 if (cohort.getCandidate() != null) {
1225 rebaseTransactions(it, dataTree);
1228 processNextPending();
1232 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1236 DataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
1237 while (it.hasNext()) {
1238 final CommitEntry e = it.next();
1239 if (cohort.equals(e.cohort)) {
1240 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1243 if (cohort.getCandidate() != null) {
1244 rebaseTransactions(it, newTip);
1249 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), newTip);
1253 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1257 @SuppressWarnings("checkstyle:IllegalCatch")
1258 private void rebaseTransactions(final Iterator<CommitEntry> iter, final @NonNull DataTreeTip newTip) {
1259 tip = Preconditions.checkNotNull(newTip);
1260 while (iter.hasNext()) {
1261 final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1262 if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1263 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1266 tip.validate(cohort.getDataTreeModification());
1267 } catch (DataValidationFailedException | RuntimeException e) {
1268 LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1269 cohort.reportFailure(e);
1271 } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1272 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1275 tip.validate(cohort.getDataTreeModification());
1276 DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1278 cohort.setNewCandidate(candidate);
1280 } catch (RuntimeException | DataValidationFailedException e) {
1281 LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1282 cohort.reportFailure(e);
1288 void setRunOnPendingTransactionsComplete(final Runnable operation) {
1289 runOnPendingTransactionsComplete = operation;
1290 maybeRunOperationOnPendingTransactionsComplete();
1293 private void maybeRunOperationOnPendingTransactionsComplete() {
1294 if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1295 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1296 runOnPendingTransactionsComplete);
1298 runOnPendingTransactionsComplete.run();
1299 runOnPendingTransactionsComplete = null;
1303 ShardStats getStats() {
1304 return shard.getShardMBean();
1307 Iterator<SimpleShardDataTreeCohort> cohortIterator() {
1308 return Iterables.transform(Iterables.concat(pendingFinishCommits, pendingCommits, pendingTransactions),
1309 e -> e.cohort).iterator();
1312 void removeTransactionChain(final LocalHistoryIdentifier id) {
1313 if (transactionChains.remove(id) != null) {
1314 LOG.debug("{}: Removed transaction chain {}", logContext, id);