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.Queue;
37 import java.util.SortedSet;
38 import java.util.concurrent.TimeUnit;
39 import java.util.concurrent.TimeoutException;
40 import java.util.function.Consumer;
41 import java.util.function.Function;
42 import java.util.function.UnaryOperator;
43 import javax.annotation.Nonnull;
44 import javax.annotation.Nullable;
45 import javax.annotation.concurrent.NotThreadSafe;
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.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
65 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
66 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
67 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
68 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
69 import org.opendaylight.yangtools.concepts.Identifier;
70 import org.opendaylight.yangtools.concepts.ListenerRegistration;
71 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
72 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
74 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
75 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
76 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
77 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
78 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
79 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
80 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
81 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeTip;
82 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
83 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
84 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
85 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
86 import org.slf4j.Logger;
87 import org.slf4j.LoggerFactory;
88 import scala.concurrent.duration.Duration;
91 * Internal shard state, similar to a DOMStore, but optimized for use in the actor system,
92 * e.g. it does not expose public interfaces and assumes it is only ever called from a
96 * This class is not part of the API contract and is subject to change at any time.
99 public class ShardDataTree extends ShardDataTreeTransactionParent {
100 private static final class CommitEntry {
101 final SimpleShardDataTreeCohort cohort;
104 CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
105 this.cohort = Preconditions.checkNotNull(cohort);
110 public String toString() {
111 return "CommitEntry [tx=" + cohort.getIdentifier() + ", state=" + cohort.getState() + "]";
115 private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(Duration.create(5, TimeUnit.SECONDS));
116 private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
119 * Process this many transactions in a single batched run. If we exceed this limit, we need to schedule later
120 * execution to finish up the batch. This is necessary in case of a long list of transactions which progress
121 * immediately through their preCommit phase -- if that happens, their completion eats up stack frames and could
122 * result in StackOverflowError.
124 private static final int MAX_TRANSACTION_BATCH = 100;
126 private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
127 private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
128 private final Deque<CommitEntry> pendingTransactions = new ArrayDeque<>();
129 private final Queue<CommitEntry> pendingCommits = new ArrayDeque<>();
130 private final Queue<CommitEntry> pendingFinishCommits = new ArrayDeque<>();
133 * Callbacks that need to be invoked once a payload is replicated.
135 private final Map<Payload, Runnable> replicationCallbacks = new HashMap<>();
137 private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
138 private final ShardDataChangeListenerPublisher dataChangeListenerPublisher;
139 private final Collection<ShardDataTreeMetadata<?>> metadata;
140 private final DataTree dataTree;
141 private final String logContext;
142 private final Shard shard;
143 private Runnable runOnPendingTransactionsComplete;
146 * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
147 * {@link DataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
148 * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
149 * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
151 private DataTreeTip tip;
153 private SchemaContext schemaContext;
155 private int currentTransactionBatch;
157 ShardDataTree(final Shard shard, final SchemaContext schemaContext, final DataTree dataTree,
158 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
159 final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext,
160 final ShardDataTreeMetadata<?>... metadata) {
161 this.dataTree = Preconditions.checkNotNull(dataTree);
162 updateSchemaContext(schemaContext);
164 this.shard = Preconditions.checkNotNull(shard);
165 this.treeChangeListenerPublisher = Preconditions.checkNotNull(treeChangeListenerPublisher);
166 this.dataChangeListenerPublisher = Preconditions.checkNotNull(dataChangeListenerPublisher);
167 this.logContext = Preconditions.checkNotNull(logContext);
168 this.metadata = ImmutableList.copyOf(metadata);
172 ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType,
173 final YangInstanceIdentifier root,
174 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
175 final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext,
176 final ShardDataTreeMetadata<?>... metadata) {
177 this(shard, schemaContext, createDataTree(treeType, root), treeChangeListenerPublisher,
178 dataChangeListenerPublisher, 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(""),
194 new DefaultShardDataChangeListenerPublisher(""), "");
197 final String logContext() {
201 final long readTime() {
202 return shard.ticker().read();
205 public DataTree getDataTree() {
209 SchemaContext getSchemaContext() {
210 return schemaContext;
213 void updateSchemaContext(final SchemaContext newSchemaContext) {
214 dataTree.setSchemaContext(newSchemaContext);
215 this.schemaContext = Preconditions.checkNotNull(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(@Nonnull final 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 mod = wrapper.apply(dataTree.takeSnapshot().newModification());
271 // delete everything first
272 mod.delete(YangInstanceIdentifier.EMPTY);
274 final java.util.Optional<NormalizedNode<?, ?>> maybeNode = snapshot.getRootNode();
275 if (maybeNode.isPresent()) {
276 // Add everything from the remote node back
277 mod.write(YangInstanceIdentifier.EMPTY, maybeNode.get());
281 final DataTreeModification unwrapped = unwrap(mod);
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(@Nonnull final ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
298 applySnapshot(snapshot, UnaryOperator.identity());
301 private PruningDataTreeModification wrapWithPruning(final DataTreeModification delegate) {
302 return new PruningDataTreeModification(delegate, dataTree, schemaContext);
305 private static DataTreeModification unwrap(final DataTreeModification modification) {
306 if (modification instanceof PruningDataTreeModification) {
307 return ((PruningDataTreeModification)modification).delegate();
313 * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
314 * pruning in an attempt to adjust the state to our current SchemaContext.
316 * @param snapshot Snapshot that needs to be applied
317 * @throws DataValidationFailedException when the snapshot fails to apply
319 void applyRecoverySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
320 applySnapshot(snapshot, this::wrapWithPruning);
323 @SuppressWarnings("checkstyle:IllegalCatch")
324 private void applyRecoveryCandidate(final DataTreeCandidate candidate) throws DataValidationFailedException {
325 final PruningDataTreeModification mod = wrapWithPruning(dataTree.takeSnapshot().newModification());
326 DataTreeCandidates.applyToModification(mod, candidate);
329 final DataTreeModification unwrapped = mod.delegate();
330 LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
333 dataTree.validate(unwrapped);
334 dataTree.commit(dataTree.prepare(unwrapped));
335 } catch (Exception e) {
336 File file = new File(System.getProperty("karaf.data", "."),
337 "failed-recovery-payload-" + logContext + ".out");
338 DataTreeModificationOutput.toFile(file, unwrapped);
339 throw new IllegalStateException(String.format(
340 "%s: Failed to apply recovery payload. Modification data was written to file %s",
341 logContext, file), e);
346 * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
347 * pruning in an attempt to adjust the state to our current SchemaContext.
349 * @param payload Payload
350 * @throws IOException when the snapshot fails to deserialize
351 * @throws DataValidationFailedException when the snapshot fails to apply
353 void applyRecoveryPayload(@Nonnull final Payload payload) throws IOException, DataValidationFailedException {
354 if (payload instanceof CommitTransactionPayload) {
355 final Entry<TransactionIdentifier, DataTreeCandidate> e =
356 ((CommitTransactionPayload) payload).getCandidate();
357 applyRecoveryCandidate(e.getValue());
358 allMetadataCommittedTransaction(e.getKey());
359 } else if (payload instanceof AbortTransactionPayload) {
360 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
361 } else if (payload instanceof PurgeTransactionPayload) {
362 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
363 } else if (payload instanceof CreateLocalHistoryPayload) {
364 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
365 } else if (payload instanceof CloseLocalHistoryPayload) {
366 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
367 } else if (payload instanceof PurgeLocalHistoryPayload) {
368 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
370 LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
374 private void applyReplicatedCandidate(final Identifier identifier, final DataTreeCandidate foreign)
375 throws DataValidationFailedException {
376 LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
378 final DataTreeModification mod = dataTree.takeSnapshot().newModification();
379 DataTreeCandidates.applyToModification(mod, foreign);
382 LOG.trace("{}: Applying foreign modification {}", logContext, mod);
383 dataTree.validate(mod);
384 final DataTreeCandidate candidate = dataTree.prepare(mod);
385 dataTree.commit(candidate);
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 final TransactionIdentifier txId;
414 if (identifier == null) {
415 final Entry<TransactionIdentifier, DataTreeCandidate> e =
416 ((CommitTransactionPayload) payload).getCandidate();
418 applyReplicatedCandidate(txId, e.getValue());
420 Verify.verify(identifier instanceof TransactionIdentifier);
421 txId = (TransactionIdentifier) identifier;
422 payloadReplicationComplete(txId);
424 allMetadataCommittedTransaction(txId);
425 } else if (payload instanceof AbortTransactionPayload) {
426 if (identifier != null) {
427 payloadReplicationComplete((AbortTransactionPayload) payload);
429 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
430 } else if (payload instanceof PurgeTransactionPayload) {
431 if (identifier != null) {
432 payloadReplicationComplete((PurgeTransactionPayload) payload);
434 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
435 } else if (payload instanceof CloseLocalHistoryPayload) {
436 if (identifier != null) {
437 payloadReplicationComplete((CloseLocalHistoryPayload) payload);
439 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
440 } else if (payload instanceof CreateLocalHistoryPayload) {
441 if (identifier != null) {
442 payloadReplicationComplete((CreateLocalHistoryPayload)payload);
444 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
445 } else if (payload instanceof PurgeLocalHistoryPayload) {
446 if (identifier != null) {
447 payloadReplicationComplete((PurgeLocalHistoryPayload)payload);
449 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
451 LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
455 private void replicatePayload(final Identifier id, final Payload payload, @Nullable final Runnable callback) {
456 if (callback != null) {
457 replicationCallbacks.put(payload, callback);
459 shard.persistPayload(id, payload, true);
462 private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
463 final Runnable callback = replicationCallbacks.remove(payload);
464 if (callback != null) {
465 LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
468 LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
472 private void payloadReplicationComplete(final TransactionIdentifier txId) {
473 final CommitEntry current = pendingFinishCommits.peek();
474 if (current == null) {
475 LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
479 if (!current.cohort.getIdentifier().equals(txId)) {
480 LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
481 current.cohort.getIdentifier(), txId);
485 finishCommit(current.cohort);
488 private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
489 for (ShardDataTreeMetadata<?> m : metadata) {
490 m.onTransactionAborted(txId);
494 private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
495 for (ShardDataTreeMetadata<?> m : metadata) {
496 m.onTransactionCommitted(txId);
500 private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
501 for (ShardDataTreeMetadata<?> m : metadata) {
502 m.onTransactionPurged(txId);
506 private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
507 for (ShardDataTreeMetadata<?> m : metadata) {
508 m.onHistoryCreated(historyId);
512 private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
513 for (ShardDataTreeMetadata<?> m : metadata) {
514 m.onHistoryClosed(historyId);
518 private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
519 for (ShardDataTreeMetadata<?> m : metadata) {
520 m.onHistoryPurged(historyId);
525 * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
526 * this method is used for re-establishing state when we are taking over
528 * @param historyId Local history identifier
529 * @param closed True if the chain should be created in closed state (i.e. pending purge)
530 * @return Transaction chain handle
532 ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
533 final boolean closed) {
534 final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
535 final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
536 Preconditions.checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId,
541 ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId,
542 @Nullable final Runnable callback) {
543 ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
545 chain = new ShardDataTreeTransactionChain(historyId, this);
546 transactionChains.put(historyId, chain);
547 replicatePayload(historyId, CreateLocalHistoryPayload.create(historyId), callback);
548 } else if (callback != null) {
555 ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
556 if (txId.getHistoryId().getHistoryId() == 0) {
557 return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
560 return ensureTransactionChain(txId.getHistoryId(), null).newReadOnlyTransaction(txId);
563 ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
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);
575 dataChangeListenerPublisher.publishChanges(candidate);
579 * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
580 * replication callbacks.
582 void purgeLeaderState() {
583 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
587 transactionChains.clear();
588 replicationCallbacks.clear();
592 * Close a single transaction chain.
594 * @param id History identifier
595 * @param callback Callback to invoke upon completion, may be null
597 void closeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
598 final ShardDataTreeTransactionChain chain = transactionChains.get(id);
600 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
601 if (callback != null) {
608 replicatePayload(id, CloseLocalHistoryPayload.create(id), callback);
612 * Purge a single transaction chain.
614 * @param id History identifier
615 * @param callback Callback to invoke upon completion, may be null
617 void purgeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
618 final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
620 LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
621 if (callback != null) {
627 replicatePayload(id, PurgeLocalHistoryPayload.create(id), callback);
630 void registerDataChangeListener(final YangInstanceIdentifier path,
631 final AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener,
632 final DataChangeScope scope, final Optional<DataTreeCandidate> initialState,
633 final Consumer<ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>>
635 dataChangeListenerPublisher.registerDataChangeListener(path, listener, scope, initialState, onRegistration);
638 Optional<DataTreeCandidate> readCurrentData() {
639 final java.util.Optional<NormalizedNode<?, ?>> currentState =
640 dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY);
641 return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
642 YangInstanceIdentifier.EMPTY, currentState.get())) : Optional.<DataTreeCandidate>absent();
645 public void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
646 final Optional<DataTreeCandidate> initialState,
647 final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
648 treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
652 return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
656 void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
657 final TransactionIdentifier id = transaction.getIdentifier();
658 LOG.debug("{}: aborting transaction {}", logContext, id);
659 replicatePayload(id, AbortTransactionPayload.create(id), callback);
663 void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
664 // No-op for free-standing transactions
669 ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction,
670 final java.util.Optional<SortedSet<String>> participatingShardNames) {
671 final DataTreeModification snapshot = transaction.getSnapshot();
674 return createReadyCohort(transaction.getIdentifier(), snapshot, participatingShardNames);
677 void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
678 LOG.debug("{}: purging transaction {}", logContext, id);
679 replicatePayload(id, PurgeTransactionPayload.create(id), callback);
682 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
683 return Optional.fromJavaUtil(dataTree.takeSnapshot().readNode(path));
686 DataTreeSnapshot takeSnapshot() {
687 return dataTree.takeSnapshot();
691 public DataTreeModification newModification() {
692 return dataTree.takeSnapshot().newModification();
695 public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
696 Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
698 for (CommitEntry entry: pendingFinishCommits) {
699 ret.add(entry.cohort);
702 for (CommitEntry entry: pendingCommits) {
703 ret.add(entry.cohort);
706 for (CommitEntry entry: pendingTransactions) {
707 ret.add(entry.cohort);
710 pendingFinishCommits.clear();
711 pendingCommits.clear();
712 pendingTransactions.clear();
718 * Called some time after {@link #processNextPendingTransaction()} decides to stop processing.
720 void resumeNextPendingTransaction() {
721 LOG.debug("{}: attempting to resume transaction processing", logContext);
722 processNextPending();
725 @SuppressWarnings("checkstyle:IllegalCatch")
726 private void processNextPendingTransaction() {
727 ++currentTransactionBatch;
728 if (currentTransactionBatch > MAX_TRANSACTION_BATCH) {
729 LOG.debug("{}: Already processed {}, scheduling continuation", logContext, currentTransactionBatch);
730 shard.scheduleNextPendingTransaction();
734 processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
735 final SimpleShardDataTreeCohort cohort = entry.cohort;
736 final DataTreeModification modification = cohort.getDataTreeModification();
738 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
741 tip.validate(modification);
742 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
743 cohort.successfulCanCommit();
744 entry.lastAccess = readTime();
746 } catch (ConflictingModificationAppliedException e) {
747 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
749 cause = new OptimisticLockFailedException("Optimistic lock failed for path " + e.getPath(), e);
750 } catch (DataValidationFailedException e) {
751 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
754 // For debugging purposes, allow dumping of the modification. Coupled with the above
755 // precondition log, it should allow us to understand what went on.
756 LOG.debug("{}: Store Tx {}: modifications: {} tree: {}", cohort.getIdentifier(), modification,
758 cause = new TransactionCommitFailedException("Data did not pass validation for path " + e.getPath(), e);
759 } catch (Exception e) {
760 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
764 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
765 pendingTransactions.poll().cohort.failedCanCommit(cause);
769 private void processNextPending() {
770 processNextPendingCommit();
771 processNextPendingTransaction();
774 private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
775 final Consumer<CommitEntry> processor) {
776 while (!queue.isEmpty()) {
777 final CommitEntry entry = queue.peek();
778 final SimpleShardDataTreeCohort cohort = entry.cohort;
780 if (cohort.isFailed()) {
781 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
786 if (cohort.getState() == allowedState) {
787 processor.accept(entry);
793 maybeRunOperationOnPendingTransactionsComplete();
796 private void processNextPendingCommit() {
797 processNextPending(pendingCommits, State.COMMIT_PENDING,
798 entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
801 private boolean peekNextPendingCommit() {
802 final CommitEntry first = pendingCommits.peek();
803 return first != null && first.cohort.getState() == State.COMMIT_PENDING;
806 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
807 final CommitEntry head = pendingTransactions.peek();
809 LOG.warn("{}: No transactions enqueued while attempting to start canCommit on {}", logContext, cohort);
812 if (!cohort.equals(head.cohort)) {
813 // The tx isn't at the head of the queue so we can't start canCommit at this point. Here we check if this
814 // tx should be moved ahead of other tx's in the READY state in the pendingTransactions queue. If this tx
815 // has other participating shards, it could deadlock with other tx's accessing the same shards
816 // depending on the order the tx's are readied on each shard
817 // (see https://jira.opendaylight.org/browse/CONTROLLER-1836). Therefore, if the preceding participating
818 // shard names for a preceding pending tx, call it A, in the queue matches that of this tx, then this tx
819 // is allowed to be moved ahead of tx A in the queue so it is processed first to avoid potential deadlock
820 // if tx A is behind this tx in the pendingTransactions queue for a preceding shard. In other words, since
821 // canCommmit for this tx was requested before tx A, honor that request. If this tx is moved to the head of
822 // the queue as a result, then proceed with canCommit.
824 Collection<String> precedingShardNames = extractPrecedingShardNames(cohort.getParticipatingShardNames());
825 if (precedingShardNames.isEmpty()) {
826 LOG.debug("{}: Tx {} is scheduled for canCommit step", logContext, cohort.getIdentifier());
830 LOG.debug("{}: Evaluating tx {} for canCommit - preceding participating shard names {}",
831 logContext, cohort.getIdentifier(), precedingShardNames);
832 final Iterator<CommitEntry> iter = pendingTransactions.iterator();
834 int moveToIndex = -1;
835 while (iter.hasNext()) {
836 final CommitEntry entry = iter.next();
839 if (cohort.equals(entry.cohort)) {
840 if (moveToIndex < 0) {
841 LOG.debug("{}: Not moving tx {} - cannot proceed with canCommit",
842 logContext, cohort.getIdentifier());
846 LOG.debug("{}: Moving {} to index {} in the pendingTransactions queue",
847 logContext, cohort.getIdentifier(), moveToIndex);
849 insertEntry(pendingTransactions, entry, moveToIndex);
851 if (!cohort.equals(pendingTransactions.peek().cohort)) {
852 LOG.debug("{}: Tx {} is not at the head of the queue - cannot proceed with canCommit",
853 logContext, cohort.getIdentifier());
857 LOG.debug("{}: Tx {} is now at the head of the queue - proceeding with canCommit",
858 logContext, cohort.getIdentifier());
862 if (entry.cohort.getState() != State.READY) {
863 LOG.debug("{}: Skipping pending transaction {} in state {}",
864 logContext, entry.cohort.getIdentifier(), entry.cohort.getState());
868 final Collection<String> pendingPrecedingShardNames = extractPrecedingShardNames(
869 entry.cohort.getParticipatingShardNames());
871 if (precedingShardNames.equals(pendingPrecedingShardNames)) {
872 if (moveToIndex < 0) {
873 LOG.debug("{}: Preceding shard names {} for pending tx {} match - saving moveToIndex {}",
874 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), index);
878 "{}: Preceding shard names {} for pending tx {} match but moveToIndex already set to {}",
879 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), moveToIndex);
882 LOG.debug("{}: Preceding shard names {} for pending tx {} differ - skipping",
883 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier());
888 processNextPendingTransaction();
891 private void insertEntry(Deque<CommitEntry> queue, CommitEntry entry, int atIndex) {
893 queue.addFirst(entry);
897 LOG.trace("Inserting into Deque at index {}", atIndex);
899 Deque<CommitEntry> tempStack = new ArrayDeque<>(atIndex);
900 for (int i = 0; i < atIndex; i++) {
901 tempStack.push(queue.poll());
904 queue.addFirst(entry);
906 tempStack.forEach(queue::addFirst);
909 private Collection<String> extractPrecedingShardNames(
910 java.util.Optional<SortedSet<String>> participatingShardNames) {
911 return participatingShardNames.map((Function<SortedSet<String>, Collection<String>>)
912 set -> set.headSet(shard.getShardName())).orElse(Collections.<String>emptyList());
915 private void failPreCommit(final Throwable cause) {
916 shard.getShardMBean().incrementFailedTransactionsCount();
917 pendingTransactions.poll().cohort.failedPreCommit(cause);
918 processNextPendingTransaction();
921 @SuppressWarnings("checkstyle:IllegalCatch")
922 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
923 final CommitEntry entry = pendingTransactions.peek();
924 Preconditions.checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
926 final SimpleShardDataTreeCohort current = entry.cohort;
927 Verify.verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
929 LOG.debug("{}: Preparing transaction {}", logContext, current.getIdentifier());
931 final DataTreeCandidateTip candidate;
933 candidate = tip.prepare(cohort.getDataTreeModification());
934 } catch (RuntimeException e) {
939 cohort.userPreCommit(candidate, new FutureCallback<Void>() {
941 public void onSuccess(final Void noop) {
942 // Set the tip of the data tree.
943 tip = Verify.verifyNotNull(candidate);
945 entry.lastAccess = readTime();
947 pendingTransactions.remove();
948 pendingCommits.add(entry);
950 LOG.debug("{}: Transaction {} prepared", logContext, current.getIdentifier());
952 cohort.successfulPreCommit(candidate);
954 processNextPendingTransaction();
958 public void onFailure(final Throwable failure) {
959 failPreCommit(failure);
964 private void failCommit(final Exception cause) {
965 shard.getShardMBean().incrementFailedTransactionsCount();
966 pendingFinishCommits.poll().cohort.failedCommit(cause);
967 processNextPending();
970 @SuppressWarnings("checkstyle:IllegalCatch")
971 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
972 final TransactionIdentifier txId = cohort.getIdentifier();
973 final DataTreeCandidate candidate = cohort.getCandidate();
975 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
977 if (tip == candidate) {
978 // All pending candidates have been committed, reset the tip to the data tree.
983 dataTree.commit(candidate);
984 } catch (Exception e) {
985 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
990 shard.getShardMBean().incrementCommittedTransactionCount();
991 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
993 // FIXME: propagate journal index
994 pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO, () -> {
995 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
996 notifyListeners(candidate);
998 processNextPending();
1002 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
1003 final CommitEntry entry = pendingCommits.peek();
1004 Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
1006 final SimpleShardDataTreeCohort current = entry.cohort;
1007 if (!cohort.equals(current)) {
1008 LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
1012 LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
1014 final TransactionIdentifier txId = cohort.getIdentifier();
1015 final Payload payload;
1017 payload = CommitTransactionPayload.create(txId, candidate);
1018 } catch (IOException e) {
1019 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
1020 pendingCommits.poll().cohort.failedCommit(e);
1021 processNextPending();
1025 // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
1026 // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
1027 // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
1028 // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
1029 // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
1030 // pendingCommits queue.
1031 processNextPendingTransaction();
1033 // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
1034 // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
1035 // in order to properly determine the batchHint flag for the call to persistPayload.
1036 pendingCommits.remove();
1037 pendingFinishCommits.add(entry);
1039 // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
1040 // this transaction for replication.
1041 boolean replicationBatchHint = peekNextPendingCommit();
1043 // Once completed, we will continue via payloadReplicationComplete
1044 shard.persistPayload(txId, payload, replicationBatchHint);
1046 entry.lastAccess = shard.ticker().read();
1048 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
1050 // Process the next transaction pending commit, if any. If there is one it will be batched with this
1051 // transaction for replication.
1052 processNextPendingCommit();
1055 Collection<ActorRef> getCohortActors() {
1056 return cohortRegistry.getCohortActors();
1059 void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
1060 cohortRegistry.process(sender, message);
1064 ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1065 final Exception failure) {
1066 final SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId, failure);
1067 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1072 ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1073 final java.util.Optional<SortedSet<String>> participatingShardNames) {
1074 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId,
1075 cohortRegistry.createCohort(schemaContext, txId, runnable -> shard.executeInSelf(runnable),
1076 COMMIT_STEP_TIMEOUT), participatingShardNames);
1077 pendingTransactions.add(new CommitEntry(cohort, readTime()));
1081 // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
1082 // the newReadWriteTransaction()
1083 ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1084 final java.util.Optional<SortedSet<String>> participatingShardNames) {
1085 if (txId.getHistoryId().getHistoryId() == 0) {
1086 return createReadyCohort(txId, mod, participatingShardNames);
1089 return ensureTransactionChain(txId.getHistoryId(), null).createReadyCohort(txId, mod, participatingShardNames);
1092 @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
1093 void checkForExpiredTransactions(final long transactionCommitTimeoutMillis,
1094 final Function<SimpleShardDataTreeCohort, Optional<Long>> accessTimeUpdater) {
1095 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
1096 final long now = readTime();
1098 final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
1099 !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
1100 final CommitEntry currentTx = currentQueue.peek();
1101 if (currentTx == null) {
1102 // Empty queue, no-op
1106 long delta = now - currentTx.lastAccess;
1107 if (delta < timeout) {
1108 // Not expired yet, bail
1112 final Optional<Long> updateOpt = accessTimeUpdater.apply(currentTx.cohort);
1113 if (updateOpt.isPresent()) {
1114 final long newAccess = updateOpt.get().longValue();
1115 final long newDelta = now - newAccess;
1116 if (newDelta < delta) {
1117 LOG.debug("{}: Updated current transaction {} access time", logContext,
1118 currentTx.cohort.getIdentifier());
1119 currentTx.lastAccess = newAccess;
1123 if (delta < timeout) {
1124 // Not expired yet, bail
1129 final long deltaMillis = TimeUnit.NANOSECONDS.toMillis(delta);
1130 final State state = currentTx.cohort.getState();
1132 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
1133 currentTx.cohort.getIdentifier(), deltaMillis, state);
1134 boolean processNext = true;
1135 final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
1136 + deltaMillis + "ms");
1139 case CAN_COMMIT_PENDING:
1140 currentQueue.remove().cohort.failedCanCommit(cohortFailure);
1142 case CAN_COMMIT_COMPLETE:
1143 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
1144 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
1145 // in PRE_COMMIT_COMPLETE is changed.
1146 currentQueue.remove().cohort.reportFailure(cohortFailure);
1148 case PRE_COMMIT_PENDING:
1149 currentQueue.remove().cohort.failedPreCommit(cohortFailure);
1151 case PRE_COMMIT_COMPLETE:
1152 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
1153 // are ready we should commit the transaction, not abort it. Our current software stack does
1154 // not allow us to do that consistently, because we persist at the time of commit, hence
1155 // we can end up in a state where we have pre-committed a transaction, then a leader failover
1156 // occurred ... the new leader does not see the pre-committed transaction and does not have
1157 // a running timer. To fix this we really need two persistence events.
1159 // The first one, done at pre-commit time will hold the transaction payload. When consensus
1160 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1161 // apply the state in this event.
1163 // The second one, done at commit (or abort) time holds only the transaction identifier and
1164 // signals to followers that the state should (or should not) be applied.
1166 // In order to make the pre-commit timer working across failovers, though, we need
1167 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1168 // restart the timer.
1169 currentQueue.remove().cohort.reportFailure(cohortFailure);
1171 case COMMIT_PENDING:
1172 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1173 currentTx.cohort.getIdentifier());
1174 currentTx.lastAccess = now;
1175 processNext = false;
1178 currentQueue.remove().cohort.reportFailure(cohortFailure);
1184 currentQueue.remove();
1188 processNextPending();
1192 boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1193 final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1194 pendingTransactions).iterator();
1195 if (!it.hasNext()) {
1196 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1200 // First entry is special, as it may already be committing
1201 final CommitEntry first = it.next();
1202 if (cohort.equals(first.cohort)) {
1203 if (cohort.getState() != State.COMMIT_PENDING) {
1204 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1205 cohort.getIdentifier());
1208 if (cohort.getCandidate() != null) {
1209 rebaseTransactions(it, dataTree);
1212 processNextPending();
1216 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1220 DataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
1221 while (it.hasNext()) {
1222 final CommitEntry e = it.next();
1223 if (cohort.equals(e.cohort)) {
1224 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1227 if (cohort.getCandidate() != null) {
1228 rebaseTransactions(it, newTip);
1233 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), newTip);
1237 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1241 @SuppressWarnings("checkstyle:IllegalCatch")
1242 private void rebaseTransactions(final Iterator<CommitEntry> iter, @Nonnull final DataTreeTip newTip) {
1243 tip = Preconditions.checkNotNull(newTip);
1244 while (iter.hasNext()) {
1245 final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1246 if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1247 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1250 tip.validate(cohort.getDataTreeModification());
1251 } catch (DataValidationFailedException | RuntimeException e) {
1252 LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1253 cohort.reportFailure(e);
1255 } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1256 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1259 tip.validate(cohort.getDataTreeModification());
1260 DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1262 cohort.setNewCandidate(candidate);
1264 } catch (RuntimeException | DataValidationFailedException e) {
1265 LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1266 cohort.reportFailure(e);
1272 void setRunOnPendingTransactionsComplete(final Runnable operation) {
1273 runOnPendingTransactionsComplete = operation;
1274 maybeRunOperationOnPendingTransactionsComplete();
1277 private void maybeRunOperationOnPendingTransactionsComplete() {
1278 if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1279 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1280 runOnPendingTransactionsComplete);
1282 runOnPendingTransactionsComplete.run();
1283 runOnPendingTransactionsComplete = null;
1287 ShardStats getStats() {
1288 return shard.getShardMBean();
1291 Iterator<SimpleShardDataTreeCohort> cohortIterator() {
1292 return Iterables.transform(Iterables.concat(pendingFinishCommits, pendingCommits, pendingTransactions),
1293 e -> e.cohort).iterator();
1296 void removeTransactionChain(final LocalHistoryIdentifier id) {
1297 if (transactionChains.remove(id) != null) {
1298 LOG.debug("{}: Removed transaction chain {}", logContext, id);