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.PurgeLocalHistoryPayload;
63 import org.opendaylight.controller.cluster.datastore.persisted.PurgeTransactionPayload;
64 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
65 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshotMetadata;
66 import org.opendaylight.controller.cluster.datastore.utils.DataTreeModificationOutput;
67 import org.opendaylight.controller.cluster.datastore.utils.PruningDataTreeModification;
68 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
69 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
70 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
71 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
72 import org.opendaylight.yangtools.concepts.Identifier;
73 import org.opendaylight.yangtools.concepts.ListenerRegistration;
74 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
75 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
76 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
77 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
78 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
79 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
80 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
81 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
82 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
83 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
84 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeTip;
85 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
86 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
87 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
88 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
89 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
90 import org.slf4j.Logger;
91 import org.slf4j.LoggerFactory;
92 import scala.concurrent.duration.FiniteDuration;
95 * Internal shard state, similar to a DOMStore, but optimized for use in the actor system, e.g. it does not expose
96 * public interfaces and assumes it is only ever called from a single thread.
99 * This class is not part of the API contract and is subject to change at any time. It is NOT thread-safe.
101 public class ShardDataTree extends ShardDataTreeTransactionParent {
102 private static final class CommitEntry {
103 final SimpleShardDataTreeCohort cohort;
106 CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
107 this.cohort = requireNonNull(cohort);
112 public String toString() {
113 return "CommitEntry [tx=" + cohort.getIdentifier() + ", state=" + cohort.getState() + "]";
117 private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(FiniteDuration.create(5, TimeUnit.SECONDS));
118 private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
121 * Process this many transactions in a single batched run. If we exceed this limit, we need to schedule later
122 * execution to finish up the batch. This is necessary in case of a long list of transactions which progress
123 * immediately through their preCommit phase -- if that happens, their completion eats up stack frames and could
124 * result in StackOverflowError.
126 private static final int MAX_TRANSACTION_BATCH = 100;
128 private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
129 private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
130 private final Deque<CommitEntry> pendingTransactions = new ArrayDeque<>();
131 private final Queue<CommitEntry> pendingCommits = new ArrayDeque<>();
132 private final Queue<CommitEntry> pendingFinishCommits = new ArrayDeque<>();
135 * Callbacks that need to be invoked once a payload is replicated.
137 private final Map<Payload, Runnable> replicationCallbacks = new HashMap<>();
139 private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
140 private final Collection<ShardDataTreeMetadata<?>> metadata;
141 private final DataTree dataTree;
142 private final String logContext;
143 private final Shard shard;
144 private Runnable runOnPendingTransactionsComplete;
147 * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
148 * {@link DataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
149 * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
150 * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
152 private DataTreeTip tip;
154 private SchemaContext schemaContext;
155 private DataSchemaContextTree dataSchemaContext;
157 private int currentTransactionBatch;
159 ShardDataTree(final Shard shard, final SchemaContext schemaContext, final DataTree dataTree,
160 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
161 final String logContext,
162 final ShardDataTreeMetadata<?>... metadata) {
163 this.dataTree = requireNonNull(dataTree);
164 updateSchemaContext(schemaContext);
166 this.shard = requireNonNull(shard);
167 this.treeChangeListenerPublisher = requireNonNull(treeChangeListenerPublisher);
168 this.logContext = requireNonNull(logContext);
169 this.metadata = ImmutableList.copyOf(metadata);
173 ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType,
174 final YangInstanceIdentifier root,
175 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
176 final String logContext,
177 final ShardDataTreeMetadata<?>... metadata) {
178 this(shard, schemaContext, createDataTree(treeType, root), treeChangeListenerPublisher, logContext, metadata);
181 private static DataTree createDataTree(final TreeType treeType, final YangInstanceIdentifier root) {
182 final DataTreeConfiguration baseConfig = DataTreeConfiguration.getDefault(treeType);
183 return new InMemoryDataTreeFactory().create(new DataTreeConfiguration.Builder(baseConfig.getTreeType())
184 .setMandatoryNodesValidation(baseConfig.isMandatoryNodesValidationEnabled())
185 .setUniqueIndexes(baseConfig.isUniqueIndexEnabled())
191 public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType) {
192 this(shard, schemaContext, treeType, YangInstanceIdentifier.empty(),
193 new DefaultShardDataTreeChangeListenerPublisher(""), "");
196 final String logContext() {
200 final long readTime() {
201 return shard.ticker().read();
204 public DataTree getDataTree() {
208 SchemaContext getSchemaContext() {
209 return schemaContext;
212 void updateSchemaContext(final SchemaContext newSchemaContext) {
213 dataTree.setSchemaContext(newSchemaContext);
214 this.schemaContext = requireNonNull(newSchemaContext);
215 this.dataSchemaContext = DataSchemaContextTree.from(newSchemaContext);
218 void resetTransactionBatch() {
219 currentTransactionBatch = 0;
223 * Take a snapshot of current state for later recovery.
225 * @return A state snapshot
227 @NonNull ShardDataTreeSnapshot takeStateSnapshot() {
228 final NormalizedNode<?, ?> rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.empty()).get();
229 final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
230 ImmutableMap.builder();
232 for (ShardDataTreeMetadata<?> m : metadata) {
233 final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
235 metaBuilder.put(meta.getType(), meta);
239 return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
242 private boolean anyPendingTransactions() {
243 return !pendingTransactions.isEmpty() || !pendingCommits.isEmpty() || !pendingFinishCommits.isEmpty();
246 private void applySnapshot(final @NonNull ShardDataTreeSnapshot snapshot,
247 final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
248 final Stopwatch elapsed = Stopwatch.createStarted();
250 if (anyPendingTransactions()) {
251 LOG.warn("{}: applying state snapshot with pending transactions", logContext);
254 final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
255 if (snapshot instanceof MetadataShardDataTreeSnapshot) {
256 snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
258 snapshotMeta = ImmutableMap.of();
261 for (ShardDataTreeMetadata<?> m : metadata) {
262 final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
270 final DataTreeModification unwrapped = dataTree.takeSnapshot().newModification();
271 final DataTreeModification mod = wrapper.apply(unwrapped);
272 // delete everything first
273 mod.delete(YangInstanceIdentifier.empty());
275 final Optional<NormalizedNode<?, ?>> maybeNode = snapshot.getRootNode();
276 if (maybeNode.isPresent()) {
277 // Add everything from the remote node back
278 mod.write(YangInstanceIdentifier.empty(), maybeNode.get());
282 dataTree.validate(unwrapped);
283 DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
284 dataTree.commit(candidate);
285 notifyListeners(candidate);
287 LOG.debug("{}: state snapshot applied in {}", logContext, elapsed);
291 * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
292 * does not perform any pruning.
294 * @param snapshot Snapshot that needs to be applied
295 * @throws DataValidationFailedException when the snapshot fails to apply
297 void applySnapshot(final @NonNull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
298 applySnapshot(snapshot, UnaryOperator.identity());
301 private PruningDataTreeModification wrapWithPruning(final DataTreeModification delegate) {
302 return new PruningDataTreeModification(delegate, dataTree,
303 // TODO: we should be able to reuse the pruner, provided we are not reentrant
304 ReusableNormalizedNodePruner.forDataSchemaContext(dataSchemaContext));
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 CommitTransactionPayload payload) throws IOException {
320 final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> entry = payload.getCandidate();
321 final DataTreeModification unwrapped = dataTree.takeSnapshot().newModification();
322 // FIXME: CONTROLLER-1923: examine version first
323 final PruningDataTreeModification mod = wrapWithPruning(unwrapped);
324 DataTreeCandidates.applyToModification(mod, entry.getValue().getCandidate());
327 LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
330 dataTree.validate(unwrapped);
331 dataTree.commit(dataTree.prepare(unwrapped));
332 } catch (Exception e) {
333 File file = new File(System.getProperty("karaf.data", "."),
334 "failed-recovery-payload-" + logContext + ".out");
335 DataTreeModificationOutput.toFile(file, unwrapped);
336 throw new IllegalStateException(String.format(
337 "%s: Failed to apply recovery payload. Modification data was written to file %s",
338 logContext, file), e);
341 allMetadataCommittedTransaction(entry.getKey());
345 * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
346 * pruning in an attempt to adjust the state to our current SchemaContext.
348 * @param payload Payload
349 * @throws IOException when the snapshot fails to deserialize
350 * @throws DataValidationFailedException when the snapshot fails to apply
352 void applyRecoveryPayload(final @NonNull Payload payload) throws IOException {
353 if (payload instanceof CommitTransactionPayload) {
354 applyRecoveryCandidate((CommitTransactionPayload) payload);
355 } else if (payload instanceof AbortTransactionPayload) {
356 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
357 } else if (payload instanceof PurgeTransactionPayload) {
358 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
359 } else if (payload instanceof CreateLocalHistoryPayload) {
360 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
361 } else if (payload instanceof CloseLocalHistoryPayload) {
362 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
363 } else if (payload instanceof PurgeLocalHistoryPayload) {
364 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
366 LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
370 private void applyReplicatedCandidate(final CommitTransactionPayload payload)
371 throws DataValidationFailedException, IOException {
372 final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> entry = payload.getCandidate();
373 final TransactionIdentifier identifier = entry.getKey();
374 LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
376 final DataTreeModification mod = dataTree.takeSnapshot().newModification();
377 // TODO: check version here, which will enable us to perform forward-compatibility transformations
378 DataTreeCandidates.applyToModification(mod, entry.getValue().getCandidate());
381 LOG.trace("{}: Applying foreign modification {}", logContext, mod);
382 dataTree.validate(mod);
383 final DataTreeCandidate candidate = dataTree.prepare(mod);
384 dataTree.commit(candidate);
386 allMetadataCommittedTransaction(identifier);
387 notifyListeners(candidate);
391 * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
392 * SchemaContexts match and does not perform any pruning.
394 * @param identifier Payload identifier as returned from RaftActor
395 * @param payload Payload
396 * @throws IOException when the snapshot fails to deserialize
397 * @throws DataValidationFailedException when the snapshot fails to apply
399 void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
400 DataValidationFailedException {
402 * 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
403 * if we are the leader and it has originated with us.
405 * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
406 * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
407 * acting in that capacity anymore.
409 * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
410 * pre-Boron state -- which limits the number of options here.
412 if (payload instanceof CommitTransactionPayload) {
413 if (identifier == null) {
414 applyReplicatedCandidate((CommitTransactionPayload) payload);
416 verify(identifier instanceof TransactionIdentifier);
417 payloadReplicationComplete((TransactionIdentifier) identifier);
419 } else if (payload instanceof AbortTransactionPayload) {
420 if (identifier != null) {
421 payloadReplicationComplete((AbortTransactionPayload) payload);
423 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
424 } else if (payload instanceof PurgeTransactionPayload) {
425 if (identifier != null) {
426 payloadReplicationComplete((PurgeTransactionPayload) payload);
428 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
429 } else if (payload instanceof CloseLocalHistoryPayload) {
430 if (identifier != null) {
431 payloadReplicationComplete((CloseLocalHistoryPayload) payload);
433 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
434 } else if (payload instanceof CreateLocalHistoryPayload) {
435 if (identifier != null) {
436 payloadReplicationComplete((CreateLocalHistoryPayload)payload);
438 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
439 } else if (payload instanceof PurgeLocalHistoryPayload) {
440 if (identifier != null) {
441 payloadReplicationComplete((PurgeLocalHistoryPayload)payload);
443 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
445 LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
449 private void replicatePayload(final Identifier id, final Payload payload, final @Nullable Runnable callback) {
450 if (callback != null) {
451 replicationCallbacks.put(payload, callback);
453 shard.persistPayload(id, payload, true);
456 private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
457 final Runnable callback = replicationCallbacks.remove(payload);
458 if (callback != null) {
459 LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
462 LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
466 private void payloadReplicationComplete(final TransactionIdentifier txId) {
467 final CommitEntry current = pendingFinishCommits.peek();
468 if (current == null) {
469 LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
470 allMetadataCommittedTransaction(txId);
474 if (!current.cohort.getIdentifier().equals(txId)) {
475 LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
476 current.cohort.getIdentifier(), txId);
477 allMetadataCommittedTransaction(txId);
481 finishCommit(current.cohort);
484 private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
485 for (ShardDataTreeMetadata<?> m : metadata) {
486 m.onTransactionAborted(txId);
490 private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
491 for (ShardDataTreeMetadata<?> m : metadata) {
492 m.onTransactionCommitted(txId);
496 private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
497 for (ShardDataTreeMetadata<?> m : metadata) {
498 m.onTransactionPurged(txId);
502 private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
503 for (ShardDataTreeMetadata<?> m : metadata) {
504 m.onHistoryCreated(historyId);
508 private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
509 for (ShardDataTreeMetadata<?> m : metadata) {
510 m.onHistoryClosed(historyId);
514 private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
515 for (ShardDataTreeMetadata<?> m : metadata) {
516 m.onHistoryPurged(historyId);
521 * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
522 * this method is used for re-establishing state when we are taking over
524 * @param historyId Local history identifier
525 * @param closed True if the chain should be created in closed state (i.e. pending purge)
526 * @return Transaction chain handle
528 ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
529 final boolean closed) {
530 final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
531 final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
532 checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId, existing);
536 ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId,
537 final @Nullable Runnable callback) {
538 ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
540 chain = new ShardDataTreeTransactionChain(historyId, this);
541 transactionChains.put(historyId, chain);
542 replicatePayload(historyId, CreateLocalHistoryPayload.create(
543 historyId, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
544 } else if (callback != null) {
551 ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
552 shard.getShardMBean().incrementReadOnlyTransactionCount();
554 if (txId.getHistoryId().getHistoryId() == 0) {
555 return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
558 return ensureTransactionChain(txId.getHistoryId(), null).newReadOnlyTransaction(txId);
561 ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
562 shard.getShardMBean().incrementReadWriteTransactionCount();
564 if (txId.getHistoryId().getHistoryId() == 0) {
565 return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
569 return ensureTransactionChain(txId.getHistoryId(), null).newReadWriteTransaction(txId);
573 public void notifyListeners(final DataTreeCandidate candidate) {
574 treeChangeListenerPublisher.publishChanges(candidate);
578 * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
579 * replication callbacks.
581 void purgeLeaderState() {
582 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
586 transactionChains.clear();
587 replicationCallbacks.clear();
591 * Close a single transaction chain.
593 * @param id History identifier
594 * @param callback Callback to invoke upon completion, may be null
596 void closeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
597 if (commonCloseTransactionChain(id, callback)) {
598 replicatePayload(id, CloseLocalHistoryPayload.create(id,
599 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
604 * Close a single transaction chain which is received through ask-based protocol. It does not keep a commit record.
606 * @param id History identifier
608 void closeTransactionChain(final LocalHistoryIdentifier id) {
609 commonCloseTransactionChain(id, null);
612 private boolean commonCloseTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
613 final ShardDataTreeTransactionChain chain = transactionChains.get(id);
615 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
616 if (callback != null) {
627 * Purge a single transaction chain.
629 * @param id History identifier
630 * @param callback Callback to invoke upon completion, may be null
632 void purgeTransactionChain(final LocalHistoryIdentifier id, final @Nullable Runnable callback) {
633 final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
635 LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
636 if (callback != null) {
642 replicatePayload(id, PurgeLocalHistoryPayload.create(
643 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
646 Optional<DataTreeCandidate> readCurrentData() {
647 return dataTree.takeSnapshot().readNode(YangInstanceIdentifier.empty())
648 .map(state -> DataTreeCandidates.fromNormalizedNode(YangInstanceIdentifier.empty(), state));
651 public void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
652 final Optional<DataTreeCandidate> initialState,
653 final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
654 treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
658 return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
662 void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
663 final TransactionIdentifier id = transaction.getIdentifier();
664 LOG.debug("{}: aborting transaction {}", logContext, id);
665 replicatePayload(id, AbortTransactionPayload.create(
666 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
670 void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
671 // No-op for free-standing transactions
676 ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction,
677 final Optional<SortedSet<String>> participatingShardNames) {
678 final DataTreeModification snapshot = transaction.getSnapshot();
679 final TransactionIdentifier id = transaction.getIdentifier();
680 LOG.debug("{}: readying transaction {}", logContext, id);
682 LOG.debug("{}: transaction {} ready", logContext, id);
684 return createReadyCohort(transaction.getIdentifier(), snapshot, participatingShardNames);
687 void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
688 LOG.debug("{}: purging transaction {}", logContext, id);
689 replicatePayload(id, PurgeTransactionPayload.create(
690 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
693 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
694 return dataTree.takeSnapshot().readNode(path);
697 DataTreeSnapshot takeSnapshot() {
698 return dataTree.takeSnapshot();
702 public DataTreeModification newModification() {
703 return dataTree.takeSnapshot().newModification();
706 public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
707 Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
709 for (CommitEntry entry: pendingFinishCommits) {
710 ret.add(entry.cohort);
713 for (CommitEntry entry: pendingCommits) {
714 ret.add(entry.cohort);
717 for (CommitEntry entry: pendingTransactions) {
718 ret.add(entry.cohort);
721 pendingFinishCommits.clear();
722 pendingCommits.clear();
723 pendingTransactions.clear();
729 * Called some time after {@link #processNextPendingTransaction()} decides to stop processing.
731 void resumeNextPendingTransaction() {
732 LOG.debug("{}: attempting to resume transaction processing", logContext);
733 processNextPending();
736 @SuppressWarnings("checkstyle:IllegalCatch")
737 private void processNextPendingTransaction() {
738 ++currentTransactionBatch;
739 if (currentTransactionBatch > MAX_TRANSACTION_BATCH) {
740 LOG.debug("{}: Already processed {}, scheduling continuation", logContext, currentTransactionBatch);
741 shard.scheduleNextPendingTransaction();
745 processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
746 final SimpleShardDataTreeCohort cohort = entry.cohort;
747 final DataTreeModification modification = cohort.getDataTreeModification();
749 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
752 tip.validate(modification);
753 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
754 cohort.successfulCanCommit();
755 entry.lastAccess = readTime();
757 } catch (ConflictingModificationAppliedException e) {
758 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
760 cause = new OptimisticLockFailedException("Optimistic lock failed for path " + e.getPath(), e);
761 } catch (DataValidationFailedException e) {
762 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
765 // For debugging purposes, allow dumping of the modification. Coupled with the above
766 // precondition log, it should allow us to understand what went on.
767 LOG.debug("{}: Store Tx {}: modifications: {}", logContext, cohort.getIdentifier(), modification);
768 LOG.trace("{}: Current tree: {}", logContext, dataTree);
769 cause = new TransactionCommitFailedException("Data did not pass validation for path " + e.getPath(), e);
770 } catch (Exception e) {
771 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
775 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
776 pendingTransactions.poll().cohort.failedCanCommit(cause);
780 private void processNextPending() {
781 processNextPendingCommit();
782 processNextPendingTransaction();
785 private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
786 final Consumer<CommitEntry> processor) {
787 while (!queue.isEmpty()) {
788 final CommitEntry entry = queue.peek();
789 final SimpleShardDataTreeCohort cohort = entry.cohort;
791 if (cohort.isFailed()) {
792 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
797 if (cohort.getState() == allowedState) {
798 processor.accept(entry);
804 maybeRunOperationOnPendingTransactionsComplete();
807 private void processNextPendingCommit() {
808 processNextPending(pendingCommits, State.COMMIT_PENDING,
809 entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
812 private boolean peekNextPendingCommit() {
813 final CommitEntry first = pendingCommits.peek();
814 return first != null && first.cohort.getState() == State.COMMIT_PENDING;
817 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
818 final CommitEntry head = pendingTransactions.peek();
820 LOG.warn("{}: No transactions enqueued while attempting to start canCommit on {}", logContext, cohort);
823 if (!cohort.equals(head.cohort)) {
824 // The tx isn't at the head of the queue so we can't start canCommit at this point. Here we check if this
825 // tx should be moved ahead of other tx's in the READY state in the pendingTransactions queue. If this tx
826 // has other participating shards, it could deadlock with other tx's accessing the same shards
827 // depending on the order the tx's are readied on each shard
828 // (see https://jira.opendaylight.org/browse/CONTROLLER-1836). Therefore, if the preceding participating
829 // shard names for a preceding pending tx, call it A, in the queue matches that of this tx, then this tx
830 // is allowed to be moved ahead of tx A in the queue so it is processed first to avoid potential deadlock
831 // if tx A is behind this tx in the pendingTransactions queue for a preceding shard. In other words, since
832 // canCommmit for this tx was requested before tx A, honor that request. If this tx is moved to the head of
833 // the queue as a result, then proceed with canCommit.
835 Collection<String> precedingShardNames = extractPrecedingShardNames(cohort.getParticipatingShardNames());
836 if (precedingShardNames.isEmpty()) {
837 LOG.debug("{}: Tx {} is scheduled for canCommit step", logContext, cohort.getIdentifier());
841 LOG.debug("{}: Evaluating tx {} for canCommit - preceding participating shard names {}",
842 logContext, cohort.getIdentifier(), precedingShardNames);
843 final Iterator<CommitEntry> iter = pendingTransactions.iterator();
845 int moveToIndex = -1;
846 while (iter.hasNext()) {
847 final CommitEntry entry = iter.next();
850 if (cohort.equals(entry.cohort)) {
851 if (moveToIndex < 0) {
852 LOG.debug("{}: Not moving tx {} - cannot proceed with canCommit",
853 logContext, cohort.getIdentifier());
857 LOG.debug("{}: Moving {} to index {} in the pendingTransactions queue",
858 logContext, cohort.getIdentifier(), moveToIndex);
860 insertEntry(pendingTransactions, entry, moveToIndex);
862 if (!cohort.equals(pendingTransactions.peek().cohort)) {
863 LOG.debug("{}: Tx {} is not at the head of the queue - cannot proceed with canCommit",
864 logContext, cohort.getIdentifier());
868 LOG.debug("{}: Tx {} is now at the head of the queue - proceeding with canCommit",
869 logContext, cohort.getIdentifier());
873 if (entry.cohort.getState() != State.READY) {
874 LOG.debug("{}: Skipping pending transaction {} in state {}",
875 logContext, entry.cohort.getIdentifier(), entry.cohort.getState());
879 final Collection<String> pendingPrecedingShardNames = extractPrecedingShardNames(
880 entry.cohort.getParticipatingShardNames());
882 if (precedingShardNames.equals(pendingPrecedingShardNames)) {
883 if (moveToIndex < 0) {
884 LOG.debug("{}: Preceding shard names {} for pending tx {} match - saving moveToIndex {}",
885 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), index);
889 "{}: Preceding shard names {} for pending tx {} match but moveToIndex already set to {}",
890 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), moveToIndex);
893 LOG.debug("{}: Preceding shard names {} for pending tx {} differ - skipping",
894 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier());
899 processNextPendingTransaction();
902 private static void insertEntry(final Deque<CommitEntry> queue, final CommitEntry entry, final int atIndex) {
904 queue.addFirst(entry);
908 LOG.trace("Inserting into Deque at index {}", atIndex);
910 Deque<CommitEntry> tempStack = new ArrayDeque<>(atIndex);
911 for (int i = 0; i < atIndex; i++) {
912 tempStack.push(queue.poll());
915 queue.addFirst(entry);
917 tempStack.forEach(queue::addFirst);
920 private Collection<String> extractPrecedingShardNames(final Optional<SortedSet<String>> participatingShardNames) {
921 return participatingShardNames.map((Function<SortedSet<String>, Collection<String>>)
922 set -> set.headSet(shard.getShardName())).orElse(Collections.<String>emptyList());
925 private void failPreCommit(final Throwable cause) {
926 shard.getShardMBean().incrementFailedTransactionsCount();
927 pendingTransactions.poll().cohort.failedPreCommit(cause);
928 processNextPendingTransaction();
931 @SuppressWarnings("checkstyle:IllegalCatch")
932 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
933 final CommitEntry entry = pendingTransactions.peek();
934 checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
936 final SimpleShardDataTreeCohort current = entry.cohort;
937 verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
939 final TransactionIdentifier currentId = current.getIdentifier();
940 LOG.debug("{}: Preparing transaction {}", logContext, currentId);
942 final DataTreeCandidateTip candidate;
944 candidate = tip.prepare(cohort.getDataTreeModification());
945 LOG.debug("{}: Transaction {} candidate ready", logContext, currentId);
946 } catch (DataValidationFailedException | RuntimeException e) {
951 cohort.userPreCommit(candidate, new FutureCallback<Void>() {
953 public void onSuccess(final Void noop) {
954 // Set the tip of the data tree.
955 tip = verifyNotNull(candidate);
957 entry.lastAccess = readTime();
959 pendingTransactions.remove();
960 pendingCommits.add(entry);
962 LOG.debug("{}: Transaction {} prepared", logContext, currentId);
964 cohort.successfulPreCommit(candidate);
966 processNextPendingTransaction();
970 public void onFailure(final Throwable failure) {
971 failPreCommit(failure);
976 private void failCommit(final Exception cause) {
977 shard.getShardMBean().incrementFailedTransactionsCount();
978 pendingFinishCommits.poll().cohort.failedCommit(cause);
979 processNextPending();
982 @SuppressWarnings("checkstyle:IllegalCatch")
983 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
984 final TransactionIdentifier txId = cohort.getIdentifier();
985 final DataTreeCandidate candidate = cohort.getCandidate();
987 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
989 if (tip == candidate) {
990 // All pending candidates have been committed, reset the tip to the data tree.
995 dataTree.commit(candidate);
996 } catch (Exception e) {
997 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
1002 allMetadataCommittedTransaction(txId);
1003 shard.getShardMBean().incrementCommittedTransactionCount();
1004 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
1006 // FIXME: propagate journal index
1007 pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO, () -> {
1008 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
1009 notifyListeners(candidate);
1011 processNextPending();
1015 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
1016 final CommitEntry entry = pendingCommits.peek();
1017 checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
1019 final SimpleShardDataTreeCohort current = entry.cohort;
1020 if (!cohort.equals(current)) {
1021 LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
1025 LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
1027 final TransactionIdentifier txId = cohort.getIdentifier();
1028 final Payload payload;
1030 payload = CommitTransactionPayload.create(txId, candidate,
1031 shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity());
1032 } catch (IOException e) {
1033 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
1034 pendingCommits.poll().cohort.failedCommit(e);
1035 processNextPending();
1039 // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
1040 // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
1041 // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
1042 // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
1043 // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
1044 // pendingCommits queue.
1045 processNextPendingTransaction();
1047 // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
1048 // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
1049 // in order to properly determine the batchHint flag for the call to persistPayload.
1050 pendingCommits.remove();
1051 pendingFinishCommits.add(entry);
1053 // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
1054 // this transaction for replication.
1055 boolean replicationBatchHint = peekNextPendingCommit();
1057 // Once completed, we will continue via payloadReplicationComplete
1058 shard.persistPayload(txId, payload, replicationBatchHint);
1060 entry.lastAccess = shard.ticker().read();
1062 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
1064 // Process the next transaction pending commit, if any. If there is one it will be batched with this
1065 // transaction for replication.
1066 processNextPendingCommit();
1069 Collection<ActorRef> getCohortActors() {
1070 return cohortRegistry.getCohortActors();
1073 void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
1074 cohortRegistry.process(sender, message);
1078 ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1079 final Exception failure) {
1080 final SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId, failure);
1081 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1086 ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1087 final Optional<SortedSet<String>> participatingShardNames) {
1088 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId,
1089 cohortRegistry.createCohort(schemaContext, txId, shard::executeInSelf,
1090 COMMIT_STEP_TIMEOUT), participatingShardNames);
1091 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1095 // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
1096 // the newReadWriteTransaction()
1097 ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1098 final Optional<SortedSet<String>> participatingShardNames) {
1099 if (txId.getHistoryId().getHistoryId() == 0) {
1100 return createReadyCohort(txId, mod, participatingShardNames);
1103 return ensureTransactionChain(txId.getHistoryId(), null).createReadyCohort(txId, mod, participatingShardNames);
1106 @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
1107 void checkForExpiredTransactions(final long transactionCommitTimeoutMillis,
1108 final Function<SimpleShardDataTreeCohort, OptionalLong> accessTimeUpdater) {
1109 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
1110 final long now = readTime();
1112 final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
1113 !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
1114 final CommitEntry currentTx = currentQueue.peek();
1115 if (currentTx == null) {
1116 // Empty queue, no-op
1120 long delta = now - currentTx.lastAccess;
1121 if (delta < timeout) {
1122 // Not expired yet, bail
1126 final OptionalLong updateOpt = accessTimeUpdater.apply(currentTx.cohort);
1127 if (updateOpt.isPresent()) {
1128 final long newAccess = updateOpt.getAsLong();
1129 final long newDelta = now - newAccess;
1130 if (newDelta < delta) {
1131 LOG.debug("{}: Updated current transaction {} access time", logContext,
1132 currentTx.cohort.getIdentifier());
1133 currentTx.lastAccess = newAccess;
1137 if (delta < timeout) {
1138 // Not expired yet, bail
1143 final long deltaMillis = TimeUnit.NANOSECONDS.toMillis(delta);
1144 final State state = currentTx.cohort.getState();
1146 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
1147 currentTx.cohort.getIdentifier(), deltaMillis, state);
1148 boolean processNext = true;
1149 final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
1150 + deltaMillis + "ms");
1153 case CAN_COMMIT_PENDING:
1154 currentQueue.remove().cohort.failedCanCommit(cohortFailure);
1156 case CAN_COMMIT_COMPLETE:
1157 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
1158 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
1159 // in PRE_COMMIT_COMPLETE is changed.
1160 currentQueue.remove().cohort.reportFailure(cohortFailure);
1162 case PRE_COMMIT_PENDING:
1163 currentQueue.remove().cohort.failedPreCommit(cohortFailure);
1165 case PRE_COMMIT_COMPLETE:
1166 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
1167 // are ready we should commit the transaction, not abort it. Our current software stack does
1168 // not allow us to do that consistently, because we persist at the time of commit, hence
1169 // we can end up in a state where we have pre-committed a transaction, then a leader failover
1170 // occurred ... the new leader does not see the pre-committed transaction and does not have
1171 // a running timer. To fix this we really need two persistence events.
1173 // The first one, done at pre-commit time will hold the transaction payload. When consensus
1174 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1175 // apply the state in this event.
1177 // The second one, done at commit (or abort) time holds only the transaction identifier and
1178 // signals to followers that the state should (or should not) be applied.
1180 // In order to make the pre-commit timer working across failovers, though, we need
1181 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1182 // restart the timer.
1183 currentQueue.remove().cohort.reportFailure(cohortFailure);
1185 case COMMIT_PENDING:
1186 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1187 currentTx.cohort.getIdentifier());
1188 currentTx.lastAccess = now;
1189 processNext = false;
1192 currentQueue.remove().cohort.reportFailure(cohortFailure);
1198 currentQueue.remove();
1202 processNextPending();
1206 boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1207 final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1208 pendingTransactions).iterator();
1209 if (!it.hasNext()) {
1210 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1214 // First entry is special, as it may already be committing
1215 final CommitEntry first = it.next();
1216 if (cohort.equals(first.cohort)) {
1217 if (cohort.getState() != State.COMMIT_PENDING) {
1218 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1219 cohort.getIdentifier());
1222 if (cohort.getCandidate() != null) {
1223 rebaseTransactions(it, dataTree);
1226 processNextPending();
1230 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1234 DataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
1235 while (it.hasNext()) {
1236 final CommitEntry e = it.next();
1237 if (cohort.equals(e.cohort)) {
1238 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1241 if (cohort.getCandidate() != null) {
1242 rebaseTransactions(it, newTip);
1247 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), newTip);
1251 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1255 @SuppressWarnings("checkstyle:IllegalCatch")
1256 private void rebaseTransactions(final Iterator<CommitEntry> iter, final @NonNull DataTreeTip newTip) {
1257 tip = requireNonNull(newTip);
1258 while (iter.hasNext()) {
1259 final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1260 if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1261 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1264 tip.validate(cohort.getDataTreeModification());
1265 } catch (DataValidationFailedException | RuntimeException e) {
1266 LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1267 cohort.reportFailure(e);
1269 } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1270 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1273 tip.validate(cohort.getDataTreeModification());
1274 DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1276 cohort.setNewCandidate(candidate);
1278 } catch (RuntimeException | DataValidationFailedException e) {
1279 LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1280 cohort.reportFailure(e);
1286 void setRunOnPendingTransactionsComplete(final Runnable operation) {
1287 runOnPendingTransactionsComplete = operation;
1288 maybeRunOperationOnPendingTransactionsComplete();
1291 private void maybeRunOperationOnPendingTransactionsComplete() {
1292 if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1293 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1294 runOnPendingTransactionsComplete);
1296 runOnPendingTransactionsComplete.run();
1297 runOnPendingTransactionsComplete = null;
1301 ShardStats getStats() {
1302 return shard.getShardMBean();
1305 Iterator<SimpleShardDataTreeCohort> cohortIterator() {
1306 return Iterables.transform(Iterables.concat(pendingFinishCommits, pendingCommits, pendingTransactions),
1307 e -> e.cohort).iterator();
1310 void removeTransactionChain(final LocalHistoryIdentifier id) {
1311 if (transactionChains.remove(id) != null) {
1312 LOG.debug("{}: Removed transaction chain {}", logContext, id);