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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
25 import java.io.IOException;
26 import java.util.ArrayDeque;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.HashMap;
30 import java.util.Iterator;
32 import java.util.Map.Entry;
33 import java.util.Queue;
34 import java.util.concurrent.ExecutionException;
35 import java.util.concurrent.TimeUnit;
36 import java.util.concurrent.TimeoutException;
37 import java.util.function.Consumer;
38 import java.util.function.UnaryOperator;
39 import javax.annotation.Nonnull;
40 import javax.annotation.Nullable;
41 import javax.annotation.concurrent.NotThreadSafe;
42 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
43 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
44 import org.opendaylight.controller.cluster.datastore.DataTreeCohortActorRegistry.CohortRegistryCommand;
45 import org.opendaylight.controller.cluster.datastore.ShardDataTreeCohort.State;
46 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
47 import org.opendaylight.controller.cluster.datastore.persisted.AbortTransactionPayload;
48 import org.opendaylight.controller.cluster.datastore.persisted.AbstractIdentifiablePayload;
49 import org.opendaylight.controller.cluster.datastore.persisted.CloseLocalHistoryPayload;
50 import org.opendaylight.controller.cluster.datastore.persisted.CommitTransactionPayload;
51 import org.opendaylight.controller.cluster.datastore.persisted.CreateLocalHistoryPayload;
52 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
53 import org.opendaylight.controller.cluster.datastore.persisted.PurgeLocalHistoryPayload;
54 import org.opendaylight.controller.cluster.datastore.persisted.PurgeTransactionPayload;
55 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
56 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshotMetadata;
57 import org.opendaylight.controller.cluster.datastore.utils.DataTreeModificationOutput;
58 import org.opendaylight.controller.cluster.datastore.utils.PruningDataTreeModification;
59 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
60 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
61 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
62 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
63 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
64 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
65 import org.opendaylight.yangtools.concepts.Identifier;
66 import org.opendaylight.yangtools.concepts.ListenerRegistration;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
68 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
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.DataTreeModification;
74 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
75 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeTip;
76 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
77 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
78 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTreeTip;
79 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
80 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
81 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
84 import scala.concurrent.duration.Duration;
87 * Internal shard state, similar to a DOMStore, but optimized for use in the actor system,
88 * e.g. it does not expose public interfaces and assumes it is only ever called from a
92 * This class is not part of the API contract and is subject to change at any time.
95 public class ShardDataTree extends ShardDataTreeTransactionParent {
96 private static final class CommitEntry {
97 final SimpleShardDataTreeCohort cohort;
100 CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
101 this.cohort = Preconditions.checkNotNull(cohort);
106 private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(Duration.create(5, TimeUnit.SECONDS));
107 private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
110 * Process this many transactions in a single batched run. If we exceed this limit, we need to schedule later
111 * execution to finish up the batch. This is necessary in case of a long list of transactions which progress
112 * immediately through their preCommit phase -- if that happens, their completion eats up stack frames and could
113 * result in StackOverflowError.
115 private static final int MAX_TRANSACTION_BATCH = 100;
117 private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
118 private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
119 private final Queue<CommitEntry> pendingTransactions = new ArrayDeque<>();
120 private final Queue<CommitEntry> pendingCommits = new ArrayDeque<>();
121 private final Queue<CommitEntry> pendingFinishCommits = new ArrayDeque<>();
124 * Callbacks that need to be invoked once a payload is replicated.
126 private final Map<Payload, Runnable> replicationCallbacks = new HashMap<>();
128 private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
129 private final ShardDataChangeListenerPublisher dataChangeListenerPublisher;
130 private final Collection<ShardDataTreeMetadata<?>> metadata;
131 private final TipProducingDataTree dataTree;
132 private final String logContext;
133 private final Shard shard;
134 private Runnable runOnPendingTransactionsComplete;
137 * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
138 * {@link TipProducingDataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
139 * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
140 * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
142 private TipProducingDataTreeTip tip;
144 private SchemaContext schemaContext;
146 private int currentTransactionBatch;
148 ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TipProducingDataTree dataTree,
149 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
150 final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext,
151 final ShardDataTreeMetadata<?>... metadata) {
152 this.dataTree = Preconditions.checkNotNull(dataTree);
153 updateSchemaContext(schemaContext);
155 this.shard = Preconditions.checkNotNull(shard);
156 this.treeChangeListenerPublisher = Preconditions.checkNotNull(treeChangeListenerPublisher);
157 this.dataChangeListenerPublisher = Preconditions.checkNotNull(dataChangeListenerPublisher);
158 this.logContext = Preconditions.checkNotNull(logContext);
159 this.metadata = ImmutableList.copyOf(metadata);
163 ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType,
164 final YangInstanceIdentifier root,
165 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
166 final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext,
167 final ShardDataTreeMetadata<?>... metadata) {
168 this(shard, schemaContext, InMemoryDataTreeFactory.getInstance().create(treeType, root),
169 treeChangeListenerPublisher, dataChangeListenerPublisher, logContext, metadata);
173 public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType) {
174 this(shard, schemaContext, treeType, YangInstanceIdentifier.EMPTY,
175 new DefaultShardDataTreeChangeListenerPublisher(""),
176 new DefaultShardDataChangeListenerPublisher(""), "");
179 final String logContext() {
183 final long readTime() {
184 return shard.ticker().read();
187 public TipProducingDataTree getDataTree() {
191 SchemaContext getSchemaContext() {
192 return schemaContext;
195 void updateSchemaContext(final SchemaContext newSchemaContext) {
196 dataTree.setSchemaContext(newSchemaContext);
197 this.schemaContext = Preconditions.checkNotNull(newSchemaContext);
200 void resetTransactionBatch() {
201 currentTransactionBatch = 0;
205 * Take a snapshot of current state for later recovery.
207 * @return A state snapshot
209 @Nonnull ShardDataTreeSnapshot takeStateSnapshot() {
210 final NormalizedNode<?, ?> rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY).get();
211 final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
212 ImmutableMap.builder();
214 for (ShardDataTreeMetadata<?> m : metadata) {
215 final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
217 metaBuilder.put(meta.getType(), meta);
221 return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
224 private boolean anyPendingTransactions() {
225 return !pendingTransactions.isEmpty() || !pendingCommits.isEmpty() || !pendingFinishCommits.isEmpty();
228 private void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot,
229 final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
230 final Stopwatch elapsed = Stopwatch.createStarted();
232 if (anyPendingTransactions()) {
233 LOG.warn("{}: applying state snapshot with pending transactions", logContext);
236 final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
237 if (snapshot instanceof MetadataShardDataTreeSnapshot) {
238 snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
240 snapshotMeta = ImmutableMap.of();
243 for (ShardDataTreeMetadata<?> m : metadata) {
244 final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
252 final DataTreeModification mod = wrapper.apply(dataTree.takeSnapshot().newModification());
253 // delete everything first
254 mod.delete(YangInstanceIdentifier.EMPTY);
256 final java.util.Optional<NormalizedNode<?, ?>> maybeNode = snapshot.getRootNode();
257 if (maybeNode.isPresent()) {
258 // Add everything from the remote node back
259 mod.write(YangInstanceIdentifier.EMPTY, maybeNode.get());
263 final DataTreeModification unwrapped = unwrap(mod);
264 dataTree.validate(unwrapped);
265 DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
266 dataTree.commit(candidate);
267 notifyListeners(candidate);
269 LOG.debug("{}: state snapshot applied in {}", logContext, elapsed);
273 * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
274 * does not perform any pruning.
276 * @param snapshot Snapshot that needs to be applied
277 * @throws DataValidationFailedException when the snapshot fails to apply
279 void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
280 applySnapshot(snapshot, UnaryOperator.identity());
283 private PruningDataTreeModification wrapWithPruning(final DataTreeModification delegate) {
284 return new PruningDataTreeModification(delegate, dataTree, schemaContext);
287 private static DataTreeModification unwrap(final DataTreeModification modification) {
288 if (modification instanceof PruningDataTreeModification) {
289 return ((PruningDataTreeModification)modification).delegate();
295 * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
296 * pruning in an attempt to adjust the state to our current SchemaContext.
298 * @param snapshot Snapshot that needs to be applied
299 * @throws DataValidationFailedException when the snapshot fails to apply
301 void applyRecoverySnapshot(final @Nonnull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
302 applySnapshot(snapshot, this::wrapWithPruning);
305 @SuppressWarnings("checkstyle:IllegalCatch")
306 private void applyRecoveryCandidate(final DataTreeCandidate candidate) throws DataValidationFailedException {
307 final PruningDataTreeModification mod = wrapWithPruning(dataTree.takeSnapshot().newModification());
308 DataTreeCandidates.applyToModification(mod, candidate);
311 final DataTreeModification unwrapped = mod.delegate();
312 LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
315 dataTree.validate(unwrapped);
316 dataTree.commit(dataTree.prepare(unwrapped));
317 } catch (Exception e) {
318 File file = new File(System.getProperty("karaf.data", "."),
319 "failed-recovery-payload-" + logContext + ".out");
320 DataTreeModificationOutput.toFile(file, unwrapped);
321 throw new IllegalStateException(String.format(
322 "%s: Failed to apply recovery payload. Modification data was written to file %s",
323 logContext, file), e);
328 * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
329 * pruning in an attempt to adjust the state to our current SchemaContext.
331 * @param payload Payload
332 * @throws IOException when the snapshot fails to deserialize
333 * @throws DataValidationFailedException when the snapshot fails to apply
335 void applyRecoveryPayload(final @Nonnull Payload payload) throws IOException, DataValidationFailedException {
336 if (payload instanceof CommitTransactionPayload) {
337 final Entry<TransactionIdentifier, DataTreeCandidate> e =
338 ((CommitTransactionPayload) payload).getCandidate();
339 applyRecoveryCandidate(e.getValue());
340 allMetadataCommittedTransaction(e.getKey());
341 } else if (payload instanceof AbortTransactionPayload) {
342 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
343 } else if (payload instanceof PurgeTransactionPayload) {
344 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
345 } else if (payload instanceof CreateLocalHistoryPayload) {
346 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
347 } else if (payload instanceof CloseLocalHistoryPayload) {
348 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
349 } else if (payload instanceof PurgeLocalHistoryPayload) {
350 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
351 } else if (payload instanceof DataTreeCandidatePayload) {
352 applyRecoveryCandidate(((DataTreeCandidatePayload) payload).getCandidate());
354 LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
358 private void applyReplicatedCandidate(final Identifier identifier, final DataTreeCandidate foreign)
359 throws DataValidationFailedException {
360 LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
362 final DataTreeModification mod = dataTree.takeSnapshot().newModification();
363 DataTreeCandidates.applyToModification(mod, foreign);
366 LOG.trace("{}: Applying foreign modification {}", logContext, mod);
367 dataTree.validate(mod);
368 final DataTreeCandidate candidate = dataTree.prepare(mod);
369 dataTree.commit(candidate);
371 notifyListeners(candidate);
375 * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
376 * SchemaContexts match and does not perform any pruning.
378 * @param identifier Payload identifier as returned from RaftActor
379 * @param payload Payload
380 * @throws IOException when the snapshot fails to deserialize
381 * @throws DataValidationFailedException when the snapshot fails to apply
383 void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
384 DataValidationFailedException {
386 * 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
387 * if we are the leader and it has originated with us.
389 * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
390 * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
391 * acting in that capacity anymore.
393 * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
394 * pre-Boron state -- which limits the number of options here.
396 if (payload instanceof CommitTransactionPayload) {
397 final TransactionIdentifier txId;
398 if (identifier == null) {
399 final Entry<TransactionIdentifier, DataTreeCandidate> e =
400 ((CommitTransactionPayload) payload).getCandidate();
402 applyReplicatedCandidate(txId, e.getValue());
404 Verify.verify(identifier instanceof TransactionIdentifier);
405 txId = (TransactionIdentifier) identifier;
406 payloadReplicationComplete(txId);
408 allMetadataCommittedTransaction(txId);
409 } else if (payload instanceof AbortTransactionPayload) {
410 if (identifier != null) {
411 payloadReplicationComplete((AbortTransactionPayload) payload);
413 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
414 } else if (payload instanceof PurgeTransactionPayload) {
415 if (identifier != null) {
416 payloadReplicationComplete((PurgeTransactionPayload) payload);
418 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
419 } else if (payload instanceof CloseLocalHistoryPayload) {
420 if (identifier != null) {
421 payloadReplicationComplete((CloseLocalHistoryPayload) payload);
423 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
424 } else if (payload instanceof CreateLocalHistoryPayload) {
425 if (identifier != null) {
426 payloadReplicationComplete((CreateLocalHistoryPayload)payload);
428 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
429 } else if (payload instanceof PurgeLocalHistoryPayload) {
430 if (identifier != null) {
431 payloadReplicationComplete((PurgeLocalHistoryPayload)payload);
433 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
435 LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
439 private void replicatePayload(final Identifier id, final Payload payload, @Nullable final Runnable callback) {
440 if (callback != null) {
441 replicationCallbacks.put(payload, callback);
443 shard.persistPayload(id, payload, true);
446 private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
447 final Runnable callback = replicationCallbacks.remove(payload);
448 if (callback != null) {
449 LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
452 LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
456 private void payloadReplicationComplete(final TransactionIdentifier txId) {
457 final CommitEntry current = pendingFinishCommits.peek();
458 if (current == null) {
459 LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
463 if (!current.cohort.getIdentifier().equals(txId)) {
464 LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
465 current.cohort.getIdentifier(), txId);
469 finishCommit(current.cohort);
472 private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
473 for (ShardDataTreeMetadata<?> m : metadata) {
474 m.onTransactionAborted(txId);
478 private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
479 for (ShardDataTreeMetadata<?> m : metadata) {
480 m.onTransactionCommitted(txId);
484 private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
485 for (ShardDataTreeMetadata<?> m : metadata) {
486 m.onTransactionPurged(txId);
490 private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
491 for (ShardDataTreeMetadata<?> m : metadata) {
492 m.onHistoryCreated(historyId);
496 private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
497 for (ShardDataTreeMetadata<?> m : metadata) {
498 m.onHistoryClosed(historyId);
502 private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
503 for (ShardDataTreeMetadata<?> m : metadata) {
504 m.onHistoryPurged(historyId);
509 * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
510 * this method is used for re-establishing state when we are taking over
512 * @param historyId Local history identifier
513 * @param closed True if the chain should be created in closed state (i.e. pending purge)
514 * @return Transaction chain handle
516 ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
517 final boolean closed) {
518 final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
519 final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
520 Preconditions.checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId,
525 ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId,
526 @Nullable final Runnable callback) {
527 ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
529 chain = new ShardDataTreeTransactionChain(historyId, this);
530 transactionChains.put(historyId, chain);
531 replicatePayload(historyId, CreateLocalHistoryPayload.create(historyId), callback);
532 } else if (callback != null) {
539 ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
540 if (txId.getHistoryId().getHistoryId() == 0) {
541 return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
544 return ensureTransactionChain(txId.getHistoryId(), null).newReadOnlyTransaction(txId);
547 ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
548 if (txId.getHistoryId().getHistoryId() == 0) {
549 return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
553 return ensureTransactionChain(txId.getHistoryId(), null).newReadWriteTransaction(txId);
557 public void notifyListeners(final DataTreeCandidate candidate) {
558 treeChangeListenerPublisher.publishChanges(candidate);
559 dataChangeListenerPublisher.publishChanges(candidate);
563 * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
564 * replication callbacks.
566 void purgeLeaderState() {
567 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
571 transactionChains.clear();
572 replicationCallbacks.clear();
576 * Close a single transaction chain.
578 * @param id History identifier
579 * @param callback Callback to invoke upon completion, may be null
581 void closeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
582 final ShardDataTreeTransactionChain chain = transactionChains.get(id);
584 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
585 if (callback != null) {
592 replicatePayload(id, CloseLocalHistoryPayload.create(id), callback);
596 * Purge a single transaction chain.
598 * @param id History identifier
599 * @param callback Callback to invoke upon completion, may be null
601 void purgeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
602 final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
604 LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
605 if (callback != null) {
611 replicatePayload(id, PurgeLocalHistoryPayload.create(id), callback);
614 void registerDataChangeListener(final YangInstanceIdentifier path,
615 final AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener,
616 final DataChangeScope scope, final Optional<DataTreeCandidate> initialState,
617 final Consumer<ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>>
619 dataChangeListenerPublisher.registerDataChangeListener(path, listener, scope, initialState, onRegistration);
622 Optional<DataTreeCandidate> readCurrentData() {
623 final Optional<NormalizedNode<?, ?>> currentState =
624 dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY);
625 return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
626 YangInstanceIdentifier.EMPTY, currentState.get())) : Optional.<DataTreeCandidate>absent();
629 public void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
630 final Optional<DataTreeCandidate> initialState,
631 final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
632 treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
636 return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
640 void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
641 final TransactionIdentifier id = transaction.getIdentifier();
642 LOG.debug("{}: aborting transaction {}", logContext, id);
643 replicatePayload(id, AbortTransactionPayload.create(id), callback);
647 void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
648 // No-op for free-standing transactions
653 ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction) {
654 final DataTreeModification snapshot = transaction.getSnapshot();
657 return createReadyCohort(transaction.getIdentifier(), snapshot);
660 void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
661 LOG.debug("{}: purging transaction {}", logContext, id);
662 replicatePayload(id, PurgeTransactionPayload.create(id), callback);
665 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
666 return dataTree.takeSnapshot().readNode(path);
669 DataTreeSnapshot takeSnapshot() {
670 return dataTree.takeSnapshot();
674 public DataTreeModification newModification() {
675 return dataTree.takeSnapshot().newModification();
679 * Commits a modification.
681 * @deprecated This method violates DataTree containment and will be removed.
685 public DataTreeCandidate commit(final DataTreeModification modification) throws DataValidationFailedException {
686 // Direct modification commit is a utility, which cannot be used while we have transactions in-flight
687 Preconditions.checkState(tip == dataTree, "Cannot modify data tree while transacgitons are pending");
689 modification.ready();
690 dataTree.validate(modification);
691 DataTreeCandidate candidate = dataTree.prepare(modification);
692 dataTree.commit(candidate);
696 public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
697 Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
699 for (CommitEntry entry: pendingFinishCommits) {
700 ret.add(entry.cohort);
703 for (CommitEntry entry: pendingCommits) {
704 ret.add(entry.cohort);
707 for (CommitEntry entry: pendingTransactions) {
708 ret.add(entry.cohort);
711 pendingFinishCommits.clear();
712 pendingCommits.clear();
713 pendingTransactions.clear();
719 * Called some time after {@link #processNextPendingTransaction()} decides to stop processing.
721 void resumeNextPendingTransaction() {
722 LOG.debug("{}: attempting to resume transaction processing", logContext);
723 processNextPending();
726 @SuppressWarnings("checkstyle:IllegalCatch")
727 private void processNextPendingTransaction() {
728 ++currentTransactionBatch;
729 if (currentTransactionBatch > MAX_TRANSACTION_BATCH) {
730 LOG.debug("{}: Already processed {}, scheduling continuation", logContext, currentTransactionBatch);
731 shard.scheduleNextPendingTransaction();
735 processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
736 final SimpleShardDataTreeCohort cohort = entry.cohort;
737 final DataTreeModification modification = cohort.getDataTreeModification();
739 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
742 tip.validate(modification);
743 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
744 cohort.successfulCanCommit();
745 entry.lastAccess = readTime();
747 } catch (ConflictingModificationAppliedException e) {
748 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
750 cause = new OptimisticLockFailedException("Optimistic lock failed.", e);
751 } catch (DataValidationFailedException e) {
752 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
755 // For debugging purposes, allow dumping of the modification. Coupled with the above
756 // precondition log, it should allow us to understand what went on.
757 LOG.debug("{}: Store Tx {}: modifications: {} tree: {}", cohort.getIdentifier(), modification,
759 cause = new TransactionCommitFailedException("Data did not pass validation.", e);
760 } catch (Exception e) {
761 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
765 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
766 pendingTransactions.poll().cohort.failedCanCommit(cause);
770 private void processNextPending() {
771 processNextPendingCommit();
772 processNextPendingTransaction();
775 private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
776 final Consumer<CommitEntry> processor) {
777 while (!queue.isEmpty()) {
778 final CommitEntry entry = queue.peek();
779 final SimpleShardDataTreeCohort cohort = entry.cohort;
781 if (cohort.isFailed()) {
782 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
787 if (cohort.getState() == allowedState) {
788 processor.accept(entry);
794 maybeRunOperationOnPendingTransactionsComplete();
797 private void processNextPendingCommit() {
798 processNextPending(pendingCommits, State.COMMIT_PENDING,
799 entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
802 private boolean peekNextPendingCommit() {
803 final CommitEntry first = pendingCommits.peek();
804 return first != null && first.cohort.getState() == State.COMMIT_PENDING;
807 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
808 final CommitEntry head = pendingTransactions.peek();
810 LOG.warn("{}: No transactions enqueued while attempting to start canCommit on {}", logContext, cohort);
813 if (!cohort.equals(head.cohort)) {
814 LOG.debug("{}: Transaction {} scheduled for canCommit step", logContext, cohort.getIdentifier());
818 processNextPendingTransaction();
821 private void failPreCommit(final Exception cause) {
822 shard.getShardMBean().incrementFailedTransactionsCount();
823 pendingTransactions.poll().cohort.failedPreCommit(cause);
824 processNextPendingTransaction();
827 @SuppressWarnings("checkstyle:IllegalCatch")
828 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
829 final CommitEntry entry = pendingTransactions.peek();
830 Preconditions.checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
832 final SimpleShardDataTreeCohort current = entry.cohort;
833 Verify.verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
835 LOG.debug("{}: Preparing transaction {}", logContext, current.getIdentifier());
837 final DataTreeCandidateTip candidate;
839 candidate = tip.prepare(cohort.getDataTreeModification());
840 cohort.userPreCommit(candidate);
841 } catch (ExecutionException | TimeoutException | RuntimeException e) {
846 // Set the tip of the data tree.
847 tip = Verify.verifyNotNull(candidate);
849 entry.lastAccess = readTime();
851 pendingTransactions.remove();
852 pendingCommits.add(entry);
854 LOG.debug("{}: Transaction {} prepared", logContext, current.getIdentifier());
856 cohort.successfulPreCommit(candidate);
858 processNextPendingTransaction();
861 private void failCommit(final Exception cause) {
862 shard.getShardMBean().incrementFailedTransactionsCount();
863 pendingFinishCommits.poll().cohort.failedCommit(cause);
864 processNextPending();
867 @SuppressWarnings("checkstyle:IllegalCatch")
868 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
869 final TransactionIdentifier txId = cohort.getIdentifier();
870 final DataTreeCandidate candidate = cohort.getCandidate();
872 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
874 if (tip == candidate) {
875 // All pending candidates have been committed, reset the tip to the data tree.
880 dataTree.commit(candidate);
881 } catch (Exception e) {
882 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
887 shard.getShardMBean().incrementCommittedTransactionCount();
888 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
890 // FIXME: propagate journal index
891 pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO);
893 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
894 notifyListeners(candidate);
896 processNextPending();
899 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
900 final CommitEntry entry = pendingCommits.peek();
901 Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
903 final SimpleShardDataTreeCohort current = entry.cohort;
904 if (!cohort.equals(current)) {
905 LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
909 LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
911 final TransactionIdentifier txId = cohort.getIdentifier();
912 final Payload payload;
914 payload = CommitTransactionPayload.create(txId, candidate);
915 } catch (IOException e) {
916 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
917 pendingCommits.poll().cohort.failedCommit(e);
918 processNextPending();
922 // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
923 // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
924 // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
925 // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
926 // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
927 // pendingCommits queue.
928 processNextPendingTransaction();
930 // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
931 // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
932 // in order to properly determine the batchHint flag for the call to persistPayload.
933 pendingCommits.remove();
934 pendingFinishCommits.add(entry);
936 // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
937 // this transaction for replication.
938 boolean replicationBatchHint = peekNextPendingCommit();
940 // Once completed, we will continue via payloadReplicationComplete
941 shard.persistPayload(txId, payload, replicationBatchHint);
943 entry.lastAccess = shard.ticker().read();
945 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
947 // Process the next transaction pending commit, if any. If there is one it will be batched with this
948 // transaction for replication.
949 processNextPendingCommit();
952 Collection<ActorRef> getCohortActors() {
953 return cohortRegistry.getCohortActors();
956 void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
957 cohortRegistry.process(sender, message);
961 ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
962 final Exception failure) {
963 final SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId, failure);
964 pendingTransactions.add(new CommitEntry(cohort, readTime()));
969 ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod) {
970 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId,
971 cohortRegistry.createCohort(schemaContext, txId, COMMIT_STEP_TIMEOUT));
972 pendingTransactions.add(new CommitEntry(cohort, readTime()));
976 // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
977 // the newReadWriteTransaction()
978 ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod) {
979 if (txId.getHistoryId().getHistoryId() == 0) {
980 return createReadyCohort(txId, mod);
983 return ensureTransactionChain(txId.getHistoryId(), null).createReadyCohort(txId, mod);
986 @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
987 void checkForExpiredTransactions(final long transactionCommitTimeoutMillis) {
988 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
989 final long now = readTime();
991 final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
992 !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
993 final CommitEntry currentTx = currentQueue.peek();
994 if (currentTx != null && currentTx.lastAccess + timeout < now) {
995 final State state = currentTx.cohort.getState();
996 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
997 currentTx.cohort.getIdentifier(), transactionCommitTimeoutMillis, state);
998 boolean processNext = true;
999 final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
1000 + transactionCommitTimeoutMillis + "ms");
1003 case CAN_COMMIT_PENDING:
1004 currentQueue.remove().cohort.failedCanCommit(cohortFailure);
1006 case CAN_COMMIT_COMPLETE:
1007 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
1008 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
1009 // in PRE_COMMIT_COMPLETE is changed.
1010 currentQueue.remove().cohort.reportFailure(cohortFailure);
1012 case PRE_COMMIT_PENDING:
1013 currentQueue.remove().cohort.failedPreCommit(cohortFailure);
1015 case PRE_COMMIT_COMPLETE:
1016 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
1017 // are ready we should commit the transaction, not abort it. Our current software stack does
1018 // not allow us to do that consistently, because we persist at the time of commit, hence
1019 // we can end up in a state where we have pre-committed a transaction, then a leader failover
1020 // occurred ... the new leader does not see the pre-committed transaction and does not have
1021 // a running timer. To fix this we really need two persistence events.
1023 // The first one, done at pre-commit time will hold the transaction payload. When consensus
1024 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1025 // apply the state in this event.
1027 // The second one, done at commit (or abort) time holds only the transaction identifier and
1028 // signals to followers that the state should (or should not) be applied.
1030 // In order to make the pre-commit timer working across failovers, though, we need
1031 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1032 // restart the timer.
1033 currentQueue.remove().cohort.reportFailure(cohortFailure);
1035 case COMMIT_PENDING:
1036 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1037 currentTx.cohort.getIdentifier());
1038 currentTx.lastAccess = now;
1039 processNext = false;
1042 currentQueue.remove().cohort.reportFailure(cohortFailure);
1048 currentQueue.remove();
1052 processNextPending();
1057 boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1058 final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1059 pendingTransactions).iterator();
1060 if (!it.hasNext()) {
1061 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1065 // First entry is special, as it may already be committing
1066 final CommitEntry first = it.next();
1067 if (cohort.equals(first.cohort)) {
1068 if (cohort.getState() != State.COMMIT_PENDING) {
1069 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1070 cohort.getIdentifier());
1073 if (cohort.getCandidate() != null) {
1074 rebaseTransactions(it, dataTree);
1077 processNextPending();
1081 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1085 TipProducingDataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
1086 while (it.hasNext()) {
1087 final CommitEntry e = it.next();
1088 if (cohort.equals(e.cohort)) {
1089 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1092 if (cohort.getCandidate() != null) {
1093 rebaseTransactions(it, newTip);
1098 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), newTip);
1102 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1106 @SuppressWarnings("checkstyle:IllegalCatch")
1107 private void rebaseTransactions(final Iterator<CommitEntry> iter, @Nonnull final TipProducingDataTreeTip newTip) {
1108 tip = Preconditions.checkNotNull(newTip);
1109 while (iter.hasNext()) {
1110 final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1111 if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1112 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1115 tip.validate(cohort.getDataTreeModification());
1116 } catch (DataValidationFailedException | RuntimeException e) {
1117 LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1118 cohort.reportFailure(e);
1120 } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1121 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1124 tip.validate(cohort.getDataTreeModification());
1125 DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1126 cohort.userPreCommit(candidate);
1128 cohort.setNewCandidate(candidate);
1130 } catch (ExecutionException | TimeoutException | RuntimeException | DataValidationFailedException e) {
1131 LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1132 cohort.reportFailure(e);
1138 void setRunOnPendingTransactionsComplete(final Runnable operation) {
1139 runOnPendingTransactionsComplete = operation;
1140 maybeRunOperationOnPendingTransactionsComplete();
1143 private void maybeRunOperationOnPendingTransactionsComplete() {
1144 if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1145 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1146 runOnPendingTransactionsComplete);
1148 runOnPendingTransactionsComplete.run();
1149 runOnPendingTransactionsComplete = null;
1153 ShardStats getStats() {
1154 return shard.getShardMBean();
1157 Iterator<SimpleShardDataTreeCohort> cohortIterator() {
1158 return Iterables.transform(Iterables.concat(pendingFinishCommits, pendingCommits, pendingTransactions),
1159 e -> e.cohort).iterator();
1162 void removeTransactionChain(final LocalHistoryIdentifier id) {
1163 if (transactionChains.remove(id) != null) {
1164 LOG.debug("{}: Removed transaction chain {}", logContext, id);