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.HashMap;
31 import java.util.Iterator;
33 import java.util.Map.Entry;
34 import java.util.Queue;
35 import java.util.concurrent.TimeUnit;
36 import java.util.concurrent.TimeoutException;
37 import java.util.function.Consumer;
38 import java.util.function.Function;
39 import java.util.function.UnaryOperator;
40 import javax.annotation.Nonnull;
41 import javax.annotation.Nullable;
42 import javax.annotation.concurrent.NotThreadSafe;
43 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
44 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
45 import org.opendaylight.controller.cluster.datastore.DataTreeCohortActorRegistry.CohortRegistryCommand;
46 import org.opendaylight.controller.cluster.datastore.ShardDataTreeCohort.State;
47 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
48 import org.opendaylight.controller.cluster.datastore.persisted.AbortTransactionPayload;
49 import org.opendaylight.controller.cluster.datastore.persisted.AbstractIdentifiablePayload;
50 import org.opendaylight.controller.cluster.datastore.persisted.CloseLocalHistoryPayload;
51 import org.opendaylight.controller.cluster.datastore.persisted.CommitTransactionPayload;
52 import org.opendaylight.controller.cluster.datastore.persisted.CreateLocalHistoryPayload;
53 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
54 import org.opendaylight.controller.cluster.datastore.persisted.PurgeLocalHistoryPayload;
55 import org.opendaylight.controller.cluster.datastore.persisted.PurgeTransactionPayload;
56 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
57 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshotMetadata;
58 import org.opendaylight.controller.cluster.datastore.utils.DataTreeModificationOutput;
59 import org.opendaylight.controller.cluster.datastore.utils.PruningDataTreeModification;
60 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
61 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
62 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
63 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
64 import org.opendaylight.yangtools.concepts.Identifier;
65 import org.opendaylight.yangtools.concepts.ListenerRegistration;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
67 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
69 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
70 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
71 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
72 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
73 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
74 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
75 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
76 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeTip;
77 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
78 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
79 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
80 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
81 import org.slf4j.Logger;
82 import org.slf4j.LoggerFactory;
83 import scala.concurrent.duration.Duration;
86 * Internal shard state, similar to a DOMStore, but optimized for use in the actor system,
87 * e.g. it does not expose public interfaces and assumes it is only ever called from a
91 * This class is not part of the API contract and is subject to change at any time.
94 public class ShardDataTree extends ShardDataTreeTransactionParent {
95 private static final class CommitEntry {
96 final SimpleShardDataTreeCohort cohort;
99 CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
100 this.cohort = Preconditions.checkNotNull(cohort);
105 private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(Duration.create(5, TimeUnit.SECONDS));
106 private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
109 * Process this many transactions in a single batched run. If we exceed this limit, we need to schedule later
110 * execution to finish up the batch. This is necessary in case of a long list of transactions which progress
111 * immediately through their preCommit phase -- if that happens, their completion eats up stack frames and could
112 * result in StackOverflowError.
114 private static final int MAX_TRANSACTION_BATCH = 100;
116 private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
117 private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
118 private final Queue<CommitEntry> pendingTransactions = new ArrayDeque<>();
119 private final Queue<CommitEntry> pendingCommits = new ArrayDeque<>();
120 private final Queue<CommitEntry> pendingFinishCommits = new ArrayDeque<>();
123 * Callbacks that need to be invoked once a payload is replicated.
125 private final Map<Payload, Runnable> replicationCallbacks = new HashMap<>();
127 private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
128 private final Collection<ShardDataTreeMetadata<?>> metadata;
129 private final DataTree dataTree;
130 private final String logContext;
131 private final Shard shard;
132 private Runnable runOnPendingTransactionsComplete;
135 * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
136 * {@link DataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
137 * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
138 * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
140 private DataTreeTip tip;
142 private SchemaContext schemaContext;
144 private int currentTransactionBatch;
146 ShardDataTree(final Shard shard, final SchemaContext schemaContext, final DataTree dataTree,
147 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
148 final String logContext,
149 final ShardDataTreeMetadata<?>... metadata) {
150 this.dataTree = Preconditions.checkNotNull(dataTree);
151 updateSchemaContext(schemaContext);
153 this.shard = Preconditions.checkNotNull(shard);
154 this.treeChangeListenerPublisher = Preconditions.checkNotNull(treeChangeListenerPublisher);
155 this.logContext = Preconditions.checkNotNull(logContext);
156 this.metadata = ImmutableList.copyOf(metadata);
160 ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType,
161 final YangInstanceIdentifier root,
162 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
163 final String logContext,
164 final ShardDataTreeMetadata<?>... metadata) {
165 this(shard, schemaContext, createDataTree(treeType, root), treeChangeListenerPublisher, logContext, metadata);
168 private static DataTree createDataTree(final TreeType treeType, final YangInstanceIdentifier root) {
169 final DataTreeConfiguration baseConfig = DataTreeConfiguration.getDefault(treeType);
170 return new InMemoryDataTreeFactory().create(new DataTreeConfiguration.Builder(baseConfig.getTreeType())
171 .setMandatoryNodesValidation(baseConfig.isMandatoryNodesValidationEnabled())
172 .setUniqueIndexes(baseConfig.isUniqueIndexEnabled())
178 public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType) {
179 this(shard, schemaContext, treeType, YangInstanceIdentifier.EMPTY,
180 new DefaultShardDataTreeChangeListenerPublisher(""), "");
183 final String logContext() {
187 final long readTime() {
188 return shard.ticker().read();
191 public DataTree getDataTree() {
195 SchemaContext getSchemaContext() {
196 return schemaContext;
199 void updateSchemaContext(final SchemaContext newSchemaContext) {
200 dataTree.setSchemaContext(newSchemaContext);
201 this.schemaContext = Preconditions.checkNotNull(newSchemaContext);
204 void resetTransactionBatch() {
205 currentTransactionBatch = 0;
209 * Take a snapshot of current state for later recovery.
211 * @return A state snapshot
213 @Nonnull ShardDataTreeSnapshot takeStateSnapshot() {
214 final NormalizedNode<?, ?> rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY).get();
215 final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
216 ImmutableMap.builder();
218 for (ShardDataTreeMetadata<?> m : metadata) {
219 final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
221 metaBuilder.put(meta.getType(), meta);
225 return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
228 private boolean anyPendingTransactions() {
229 return !pendingTransactions.isEmpty() || !pendingCommits.isEmpty() || !pendingFinishCommits.isEmpty();
232 private void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot,
233 final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
234 final Stopwatch elapsed = Stopwatch.createStarted();
236 if (anyPendingTransactions()) {
237 LOG.warn("{}: applying state snapshot with pending transactions", logContext);
240 final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
241 if (snapshot instanceof MetadataShardDataTreeSnapshot) {
242 snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
244 snapshotMeta = ImmutableMap.of();
247 for (ShardDataTreeMetadata<?> m : metadata) {
248 final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
256 final DataTreeModification mod = wrapper.apply(dataTree.takeSnapshot().newModification());
257 // delete everything first
258 mod.delete(YangInstanceIdentifier.EMPTY);
260 final java.util.Optional<NormalizedNode<?, ?>> maybeNode = snapshot.getRootNode();
261 if (maybeNode.isPresent()) {
262 // Add everything from the remote node back
263 mod.write(YangInstanceIdentifier.EMPTY, maybeNode.get());
267 final DataTreeModification unwrapped = unwrap(mod);
268 dataTree.validate(unwrapped);
269 DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
270 dataTree.commit(candidate);
271 notifyListeners(candidate);
273 LOG.debug("{}: state snapshot applied in {}", logContext, elapsed);
277 * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
278 * does not perform any pruning.
280 * @param snapshot Snapshot that needs to be applied
281 * @throws DataValidationFailedException when the snapshot fails to apply
283 void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
284 applySnapshot(snapshot, UnaryOperator.identity());
287 private PruningDataTreeModification wrapWithPruning(final DataTreeModification delegate) {
288 return new PruningDataTreeModification(delegate, dataTree, schemaContext);
291 private static DataTreeModification unwrap(final DataTreeModification modification) {
292 if (modification instanceof PruningDataTreeModification) {
293 return ((PruningDataTreeModification)modification).delegate();
299 * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
300 * pruning in an attempt to adjust the state to our current SchemaContext.
302 * @param snapshot Snapshot that needs to be applied
303 * @throws DataValidationFailedException when the snapshot fails to apply
305 void applyRecoverySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
306 applySnapshot(snapshot, this::wrapWithPruning);
309 @SuppressWarnings("checkstyle:IllegalCatch")
310 private void applyRecoveryCandidate(final DataTreeCandidate candidate) throws DataValidationFailedException {
311 final PruningDataTreeModification mod = wrapWithPruning(dataTree.takeSnapshot().newModification());
312 DataTreeCandidates.applyToModification(mod, candidate);
315 final DataTreeModification unwrapped = mod.delegate();
316 LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
319 dataTree.validate(unwrapped);
320 dataTree.commit(dataTree.prepare(unwrapped));
321 } catch (Exception e) {
322 File file = new File(System.getProperty("karaf.data", "."),
323 "failed-recovery-payload-" + logContext + ".out");
324 DataTreeModificationOutput.toFile(file, unwrapped);
325 throw new IllegalStateException(String.format(
326 "%s: Failed to apply recovery payload. Modification data was written to file %s",
327 logContext, file), e);
332 * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
333 * pruning in an attempt to adjust the state to our current SchemaContext.
335 * @param payload Payload
336 * @throws IOException when the snapshot fails to deserialize
337 * @throws DataValidationFailedException when the snapshot fails to apply
339 void applyRecoveryPayload(@Nonnull final Payload payload) throws IOException, DataValidationFailedException {
340 if (payload instanceof CommitTransactionPayload) {
341 final Entry<TransactionIdentifier, DataTreeCandidate> e =
342 ((CommitTransactionPayload) payload).getCandidate();
343 applyRecoveryCandidate(e.getValue());
344 allMetadataCommittedTransaction(e.getKey());
345 } else if (payload instanceof AbortTransactionPayload) {
346 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
347 } else if (payload instanceof PurgeTransactionPayload) {
348 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
349 } else if (payload instanceof CreateLocalHistoryPayload) {
350 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
351 } else if (payload instanceof CloseLocalHistoryPayload) {
352 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
353 } else if (payload instanceof PurgeLocalHistoryPayload) {
354 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
356 LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
360 private void applyReplicatedCandidate(final Identifier identifier, final DataTreeCandidate foreign)
361 throws DataValidationFailedException {
362 LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
364 final DataTreeModification mod = dataTree.takeSnapshot().newModification();
365 DataTreeCandidates.applyToModification(mod, foreign);
368 LOG.trace("{}: Applying foreign modification {}", logContext, mod);
369 dataTree.validate(mod);
370 final DataTreeCandidate candidate = dataTree.prepare(mod);
371 dataTree.commit(candidate);
373 notifyListeners(candidate);
377 * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
378 * SchemaContexts match and does not perform any pruning.
380 * @param identifier Payload identifier as returned from RaftActor
381 * @param payload Payload
382 * @throws IOException when the snapshot fails to deserialize
383 * @throws DataValidationFailedException when the snapshot fails to apply
385 void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
386 DataValidationFailedException {
388 * 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
389 * if we are the leader and it has originated with us.
391 * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
392 * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
393 * acting in that capacity anymore.
395 * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
396 * pre-Boron state -- which limits the number of options here.
398 if (payload instanceof CommitTransactionPayload) {
399 final TransactionIdentifier txId;
400 if (identifier == null) {
401 final Entry<TransactionIdentifier, DataTreeCandidate> e =
402 ((CommitTransactionPayload) payload).getCandidate();
404 applyReplicatedCandidate(txId, e.getValue());
406 Verify.verify(identifier instanceof TransactionIdentifier);
407 txId = (TransactionIdentifier) identifier;
408 payloadReplicationComplete(txId);
410 allMetadataCommittedTransaction(txId);
411 } else if (payload instanceof AbortTransactionPayload) {
412 if (identifier != null) {
413 payloadReplicationComplete((AbortTransactionPayload) payload);
415 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
416 } else if (payload instanceof PurgeTransactionPayload) {
417 if (identifier != null) {
418 payloadReplicationComplete((PurgeTransactionPayload) payload);
420 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
421 } else if (payload instanceof CloseLocalHistoryPayload) {
422 if (identifier != null) {
423 payloadReplicationComplete((CloseLocalHistoryPayload) payload);
425 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
426 } else if (payload instanceof CreateLocalHistoryPayload) {
427 if (identifier != null) {
428 payloadReplicationComplete((CreateLocalHistoryPayload)payload);
430 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
431 } else if (payload instanceof PurgeLocalHistoryPayload) {
432 if (identifier != null) {
433 payloadReplicationComplete((PurgeLocalHistoryPayload)payload);
435 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
437 LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
441 private void replicatePayload(final Identifier id, final Payload payload, @Nullable final Runnable callback) {
442 if (callback != null) {
443 replicationCallbacks.put(payload, callback);
445 shard.persistPayload(id, payload, true);
448 private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
449 final Runnable callback = replicationCallbacks.remove(payload);
450 if (callback != null) {
451 LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
454 LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
458 private void payloadReplicationComplete(final TransactionIdentifier txId) {
459 final CommitEntry current = pendingFinishCommits.peek();
460 if (current == null) {
461 LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
465 if (!current.cohort.getIdentifier().equals(txId)) {
466 LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
467 current.cohort.getIdentifier(), txId);
471 finishCommit(current.cohort);
474 private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
475 for (ShardDataTreeMetadata<?> m : metadata) {
476 m.onTransactionAborted(txId);
480 private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
481 for (ShardDataTreeMetadata<?> m : metadata) {
482 m.onTransactionCommitted(txId);
486 private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
487 for (ShardDataTreeMetadata<?> m : metadata) {
488 m.onTransactionPurged(txId);
492 private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
493 for (ShardDataTreeMetadata<?> m : metadata) {
494 m.onHistoryCreated(historyId);
498 private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
499 for (ShardDataTreeMetadata<?> m : metadata) {
500 m.onHistoryClosed(historyId);
504 private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
505 for (ShardDataTreeMetadata<?> m : metadata) {
506 m.onHistoryPurged(historyId);
511 * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
512 * this method is used for re-establishing state when we are taking over
514 * @param historyId Local history identifier
515 * @param closed True if the chain should be created in closed state (i.e. pending purge)
516 * @return Transaction chain handle
518 ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
519 final boolean closed) {
520 final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
521 final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
522 Preconditions.checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId,
527 ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId,
528 @Nullable final Runnable callback) {
529 ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
531 chain = new ShardDataTreeTransactionChain(historyId, this);
532 transactionChains.put(historyId, chain);
533 replicatePayload(historyId, CreateLocalHistoryPayload.create(historyId), callback);
534 } else if (callback != null) {
541 ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
542 if (txId.getHistoryId().getHistoryId() == 0) {
543 return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
546 return ensureTransactionChain(txId.getHistoryId(), null).newReadOnlyTransaction(txId);
549 ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
550 if (txId.getHistoryId().getHistoryId() == 0) {
551 return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
555 return ensureTransactionChain(txId.getHistoryId(), null).newReadWriteTransaction(txId);
559 public void notifyListeners(final DataTreeCandidate candidate) {
560 treeChangeListenerPublisher.publishChanges(candidate);
564 * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
565 * replication callbacks.
567 void purgeLeaderState() {
568 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
572 transactionChains.clear();
573 replicationCallbacks.clear();
577 * Close a single transaction chain.
579 * @param id History identifier
580 * @param callback Callback to invoke upon completion, may be null
582 void closeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
583 final ShardDataTreeTransactionChain chain = transactionChains.get(id);
585 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
586 if (callback != null) {
593 replicatePayload(id, CloseLocalHistoryPayload.create(id), callback);
597 * Purge a single transaction chain.
599 * @param id History identifier
600 * @param callback Callback to invoke upon completion, may be null
602 void purgeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
603 final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
605 LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
606 if (callback != null) {
612 replicatePayload(id, PurgeLocalHistoryPayload.create(id), callback);
615 Optional<DataTreeCandidate> readCurrentData() {
616 final java.util.Optional<NormalizedNode<?, ?>> currentState =
617 dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY);
618 return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
619 YangInstanceIdentifier.EMPTY, currentState.get())) : Optional.<DataTreeCandidate>absent();
622 public void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
623 final Optional<DataTreeCandidate> initialState,
624 final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
625 treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
629 return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
633 void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
634 final TransactionIdentifier id = transaction.getIdentifier();
635 LOG.debug("{}: aborting transaction {}", logContext, id);
636 replicatePayload(id, AbortTransactionPayload.create(id), callback);
640 void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
641 // No-op for free-standing transactions
646 ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction) {
647 final DataTreeModification snapshot = transaction.getSnapshot();
650 return createReadyCohort(transaction.getIdentifier(), snapshot);
653 void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
654 LOG.debug("{}: purging transaction {}", logContext, id);
655 replicatePayload(id, PurgeTransactionPayload.create(id), callback);
658 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
659 return Optional.fromJavaUtil(dataTree.takeSnapshot().readNode(path));
662 DataTreeSnapshot takeSnapshot() {
663 return dataTree.takeSnapshot();
667 public DataTreeModification newModification() {
668 return dataTree.takeSnapshot().newModification();
671 public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
672 Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
674 for (CommitEntry entry: pendingFinishCommits) {
675 ret.add(entry.cohort);
678 for (CommitEntry entry: pendingCommits) {
679 ret.add(entry.cohort);
682 for (CommitEntry entry: pendingTransactions) {
683 ret.add(entry.cohort);
686 pendingFinishCommits.clear();
687 pendingCommits.clear();
688 pendingTransactions.clear();
694 * Called some time after {@link #processNextPendingTransaction()} decides to stop processing.
696 void resumeNextPendingTransaction() {
697 LOG.debug("{}: attempting to resume transaction processing", logContext);
698 processNextPending();
701 @SuppressWarnings("checkstyle:IllegalCatch")
702 private void processNextPendingTransaction() {
703 ++currentTransactionBatch;
704 if (currentTransactionBatch > MAX_TRANSACTION_BATCH) {
705 LOG.debug("{}: Already processed {}, scheduling continuation", logContext, currentTransactionBatch);
706 shard.scheduleNextPendingTransaction();
710 processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
711 final SimpleShardDataTreeCohort cohort = entry.cohort;
712 final DataTreeModification modification = cohort.getDataTreeModification();
714 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
717 tip.validate(modification);
718 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
719 cohort.successfulCanCommit();
720 entry.lastAccess = readTime();
722 } catch (ConflictingModificationAppliedException e) {
723 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
725 cause = new OptimisticLockFailedException("Optimistic lock failed for path " + e.getPath(), e);
726 } catch (DataValidationFailedException e) {
727 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
730 // For debugging purposes, allow dumping of the modification. Coupled with the above
731 // precondition log, it should allow us to understand what went on.
732 LOG.debug("{}: Store Tx {}: modifications: {} tree: {}", cohort.getIdentifier(), modification,
734 cause = new TransactionCommitFailedException("Data did not pass validation for path " + e.getPath(), e);
735 } catch (Exception e) {
736 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
740 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
741 pendingTransactions.poll().cohort.failedCanCommit(cause);
745 private void processNextPending() {
746 processNextPendingCommit();
747 processNextPendingTransaction();
750 private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
751 final Consumer<CommitEntry> processor) {
752 while (!queue.isEmpty()) {
753 final CommitEntry entry = queue.peek();
754 final SimpleShardDataTreeCohort cohort = entry.cohort;
756 if (cohort.isFailed()) {
757 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
762 if (cohort.getState() == allowedState) {
763 processor.accept(entry);
769 maybeRunOperationOnPendingTransactionsComplete();
772 private void processNextPendingCommit() {
773 processNextPending(pendingCommits, State.COMMIT_PENDING,
774 entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
777 private boolean peekNextPendingCommit() {
778 final CommitEntry first = pendingCommits.peek();
779 return first != null && first.cohort.getState() == State.COMMIT_PENDING;
782 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
783 final CommitEntry head = pendingTransactions.peek();
785 LOG.warn("{}: No transactions enqueued while attempting to start canCommit on {}", logContext, cohort);
788 if (!cohort.equals(head.cohort)) {
789 LOG.debug("{}: Transaction {} scheduled for canCommit step", logContext, cohort.getIdentifier());
793 processNextPendingTransaction();
796 private void failPreCommit(final Throwable cause) {
797 shard.getShardMBean().incrementFailedTransactionsCount();
798 pendingTransactions.poll().cohort.failedPreCommit(cause);
799 processNextPendingTransaction();
802 @SuppressWarnings("checkstyle:IllegalCatch")
803 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
804 final CommitEntry entry = pendingTransactions.peek();
805 Preconditions.checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
807 final SimpleShardDataTreeCohort current = entry.cohort;
808 Verify.verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
810 LOG.debug("{}: Preparing transaction {}", logContext, current.getIdentifier());
812 final DataTreeCandidateTip candidate;
814 candidate = tip.prepare(cohort.getDataTreeModification());
815 } catch (RuntimeException e) {
820 cohort.userPreCommit(candidate, new FutureCallback<Void>() {
822 public void onSuccess(final Void noop) {
823 // Set the tip of the data tree.
824 tip = Verify.verifyNotNull(candidate);
826 entry.lastAccess = readTime();
828 pendingTransactions.remove();
829 pendingCommits.add(entry);
831 LOG.debug("{}: Transaction {} prepared", logContext, current.getIdentifier());
833 cohort.successfulPreCommit(candidate);
835 processNextPendingTransaction();
839 public void onFailure(final Throwable failure) {
840 failPreCommit(failure);
845 private void failCommit(final Exception cause) {
846 shard.getShardMBean().incrementFailedTransactionsCount();
847 pendingFinishCommits.poll().cohort.failedCommit(cause);
848 processNextPending();
851 @SuppressWarnings("checkstyle:IllegalCatch")
852 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
853 final TransactionIdentifier txId = cohort.getIdentifier();
854 final DataTreeCandidate candidate = cohort.getCandidate();
856 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
858 if (tip == candidate) {
859 // All pending candidates have been committed, reset the tip to the data tree.
864 dataTree.commit(candidate);
865 } catch (Exception e) {
866 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
871 shard.getShardMBean().incrementCommittedTransactionCount();
872 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
874 // FIXME: propagate journal index
875 pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO, () -> {
876 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
877 notifyListeners(candidate);
879 processNextPending();
883 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
884 final CommitEntry entry = pendingCommits.peek();
885 Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
887 final SimpleShardDataTreeCohort current = entry.cohort;
888 if (!cohort.equals(current)) {
889 LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
893 LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
895 final TransactionIdentifier txId = cohort.getIdentifier();
896 final Payload payload;
898 payload = CommitTransactionPayload.create(txId, candidate);
899 } catch (IOException e) {
900 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
901 pendingCommits.poll().cohort.failedCommit(e);
902 processNextPending();
906 // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
907 // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
908 // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
909 // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
910 // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
911 // pendingCommits queue.
912 processNextPendingTransaction();
914 // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
915 // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
916 // in order to properly determine the batchHint flag for the call to persistPayload.
917 pendingCommits.remove();
918 pendingFinishCommits.add(entry);
920 // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
921 // this transaction for replication.
922 boolean replicationBatchHint = peekNextPendingCommit();
924 // Once completed, we will continue via payloadReplicationComplete
925 shard.persistPayload(txId, payload, replicationBatchHint);
927 entry.lastAccess = shard.ticker().read();
929 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
931 // Process the next transaction pending commit, if any. If there is one it will be batched with this
932 // transaction for replication.
933 processNextPendingCommit();
936 Collection<ActorRef> getCohortActors() {
937 return cohortRegistry.getCohortActors();
940 void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
941 cohortRegistry.process(sender, message);
945 ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
946 final Exception failure) {
947 final SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId, failure);
948 pendingTransactions.add(new CommitEntry(cohort, readTime()));
953 ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod) {
954 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId,
955 cohortRegistry.createCohort(schemaContext, txId, runnable -> shard.executeInSelf(runnable),
956 COMMIT_STEP_TIMEOUT));
957 pendingTransactions.add(new CommitEntry(cohort, readTime()));
961 // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
962 // the newReadWriteTransaction()
963 ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod) {
964 if (txId.getHistoryId().getHistoryId() == 0) {
965 return createReadyCohort(txId, mod);
968 return ensureTransactionChain(txId.getHistoryId(), null).createReadyCohort(txId, mod);
971 @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
972 void checkForExpiredTransactions(final long transactionCommitTimeoutMillis,
973 final Function<SimpleShardDataTreeCohort, Optional<Long>> accessTimeUpdater) {
974 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
975 final long now = readTime();
977 final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
978 !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
979 final CommitEntry currentTx = currentQueue.peek();
980 if (currentTx == null) {
981 // Empty queue, no-op
985 long delta = now - currentTx.lastAccess;
986 if (delta < timeout) {
987 // Not expired yet, bail
991 final Optional<Long> updateOpt = accessTimeUpdater.apply(currentTx.cohort);
992 if (updateOpt.isPresent()) {
993 final long newAccess = updateOpt.get().longValue();
994 final long newDelta = now - newAccess;
995 if (newDelta < delta) {
996 LOG.debug("{}: Updated current transaction {} access time", logContext,
997 currentTx.cohort.getIdentifier());
998 currentTx.lastAccess = newAccess;
1002 if (delta < timeout) {
1003 // Not expired yet, bail
1008 final long deltaMillis = TimeUnit.NANOSECONDS.toMillis(delta);
1009 final State state = currentTx.cohort.getState();
1011 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
1012 currentTx.cohort.getIdentifier(), deltaMillis, state);
1013 boolean processNext = true;
1014 final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
1015 + deltaMillis + "ms");
1018 case CAN_COMMIT_PENDING:
1019 currentQueue.remove().cohort.failedCanCommit(cohortFailure);
1021 case CAN_COMMIT_COMPLETE:
1022 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
1023 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
1024 // in PRE_COMMIT_COMPLETE is changed.
1025 currentQueue.remove().cohort.reportFailure(cohortFailure);
1027 case PRE_COMMIT_PENDING:
1028 currentQueue.remove().cohort.failedPreCommit(cohortFailure);
1030 case PRE_COMMIT_COMPLETE:
1031 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
1032 // are ready we should commit the transaction, not abort it. Our current software stack does
1033 // not allow us to do that consistently, because we persist at the time of commit, hence
1034 // we can end up in a state where we have pre-committed a transaction, then a leader failover
1035 // occurred ... the new leader does not see the pre-committed transaction and does not have
1036 // a running timer. To fix this we really need two persistence events.
1038 // The first one, done at pre-commit time will hold the transaction payload. When consensus
1039 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1040 // apply the state in this event.
1042 // The second one, done at commit (or abort) time holds only the transaction identifier and
1043 // signals to followers that the state should (or should not) be applied.
1045 // In order to make the pre-commit timer working across failovers, though, we need
1046 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1047 // restart the timer.
1048 currentQueue.remove().cohort.reportFailure(cohortFailure);
1050 case COMMIT_PENDING:
1051 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1052 currentTx.cohort.getIdentifier());
1053 currentTx.lastAccess = now;
1054 processNext = false;
1057 currentQueue.remove().cohort.reportFailure(cohortFailure);
1063 currentQueue.remove();
1067 processNextPending();
1071 boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1072 final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1073 pendingTransactions).iterator();
1074 if (!it.hasNext()) {
1075 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1079 // First entry is special, as it may already be committing
1080 final CommitEntry first = it.next();
1081 if (cohort.equals(first.cohort)) {
1082 if (cohort.getState() != State.COMMIT_PENDING) {
1083 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1084 cohort.getIdentifier());
1087 if (cohort.getCandidate() != null) {
1088 rebaseTransactions(it, dataTree);
1091 processNextPending();
1095 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1099 DataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
1100 while (it.hasNext()) {
1101 final CommitEntry e = it.next();
1102 if (cohort.equals(e.cohort)) {
1103 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1106 if (cohort.getCandidate() != null) {
1107 rebaseTransactions(it, newTip);
1112 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), newTip);
1116 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1120 @SuppressWarnings("checkstyle:IllegalCatch")
1121 private void rebaseTransactions(final Iterator<CommitEntry> iter, @Nonnull final DataTreeTip newTip) {
1122 tip = Preconditions.checkNotNull(newTip);
1123 while (iter.hasNext()) {
1124 final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1125 if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1126 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1129 tip.validate(cohort.getDataTreeModification());
1130 } catch (DataValidationFailedException | RuntimeException e) {
1131 LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1132 cohort.reportFailure(e);
1134 } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1135 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1138 tip.validate(cohort.getDataTreeModification());
1139 DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1141 cohort.setNewCandidate(candidate);
1143 } catch (RuntimeException | DataValidationFailedException e) {
1144 LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1145 cohort.reportFailure(e);
1151 void setRunOnPendingTransactionsComplete(final Runnable operation) {
1152 runOnPendingTransactionsComplete = operation;
1153 maybeRunOperationOnPendingTransactionsComplete();
1156 private void maybeRunOperationOnPendingTransactionsComplete() {
1157 if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1158 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1159 runOnPendingTransactionsComplete);
1161 runOnPendingTransactionsComplete.run();
1162 runOnPendingTransactionsComplete = null;
1166 ShardStats getStats() {
1167 return shard.getShardMBean();
1170 Iterator<SimpleShardDataTreeCohort> cohortIterator() {
1171 return Iterables.transform(Iterables.concat(pendingFinishCommits, pendingCommits, pendingTransactions),
1172 e -> e.cohort).iterator();
1175 void removeTransactionChain(final LocalHistoryIdentifier id) {
1176 if (transactionChains.remove(id) != null) {
1177 LOG.debug("{}: Removed transaction chain {}", logContext, id);