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.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
62 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
63 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
64 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
65 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
66 import org.opendaylight.yangtools.concepts.Identifier;
67 import org.opendaylight.yangtools.concepts.ListenerRegistration;
68 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
69 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
71 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
72 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
73 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
74 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
75 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
76 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
77 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
78 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeTip;
79 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
80 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
81 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
82 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
85 import scala.concurrent.duration.Duration;
88 * Internal shard state, similar to a DOMStore, but optimized for use in the actor system,
89 * e.g. it does not expose public interfaces and assumes it is only ever called from a
93 * This class is not part of the API contract and is subject to change at any time.
96 public class ShardDataTree extends ShardDataTreeTransactionParent {
97 private static final class CommitEntry {
98 final SimpleShardDataTreeCohort cohort;
101 CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
102 this.cohort = Preconditions.checkNotNull(cohort);
107 private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(Duration.create(5, TimeUnit.SECONDS));
108 private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
111 * Process this many transactions in a single batched run. If we exceed this limit, we need to schedule later
112 * execution to finish up the batch. This is necessary in case of a long list of transactions which progress
113 * immediately through their preCommit phase -- if that happens, their completion eats up stack frames and could
114 * result in StackOverflowError.
116 private static final int MAX_TRANSACTION_BATCH = 100;
118 private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
119 private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
120 private final Queue<CommitEntry> pendingTransactions = new ArrayDeque<>();
121 private final Queue<CommitEntry> pendingCommits = new ArrayDeque<>();
122 private final Queue<CommitEntry> pendingFinishCommits = new ArrayDeque<>();
125 * Callbacks that need to be invoked once a payload is replicated.
127 private final Map<Payload, Runnable> replicationCallbacks = new HashMap<>();
129 private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
130 private final ShardDataChangeListenerPublisher dataChangeListenerPublisher;
131 private final Collection<ShardDataTreeMetadata<?>> metadata;
132 private final DataTree dataTree;
133 private final String logContext;
134 private final Shard shard;
135 private Runnable runOnPendingTransactionsComplete;
138 * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
139 * {@link DataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
140 * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
141 * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
143 private DataTreeTip tip;
145 private SchemaContext schemaContext;
147 private int currentTransactionBatch;
149 ShardDataTree(final Shard shard, final SchemaContext schemaContext, final DataTree dataTree,
150 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
151 final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext,
152 final ShardDataTreeMetadata<?>... metadata) {
153 this.dataTree = Preconditions.checkNotNull(dataTree);
154 updateSchemaContext(schemaContext);
156 this.shard = Preconditions.checkNotNull(shard);
157 this.treeChangeListenerPublisher = Preconditions.checkNotNull(treeChangeListenerPublisher);
158 this.dataChangeListenerPublisher = Preconditions.checkNotNull(dataChangeListenerPublisher);
159 this.logContext = Preconditions.checkNotNull(logContext);
160 this.metadata = ImmutableList.copyOf(metadata);
164 ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType,
165 final YangInstanceIdentifier root,
166 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
167 final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext,
168 final ShardDataTreeMetadata<?>... metadata) {
169 this(shard, schemaContext, createDataTree(treeType, root), treeChangeListenerPublisher,
170 dataChangeListenerPublisher, logContext, metadata);
173 private static DataTree createDataTree(final TreeType treeType, final YangInstanceIdentifier root) {
174 final DataTreeConfiguration baseConfig = DataTreeConfiguration.getDefault(treeType);
175 return new InMemoryDataTreeFactory().create(new DataTreeConfiguration.Builder(baseConfig.getTreeType())
176 .setMandatoryNodesValidation(baseConfig.isMandatoryNodesValidationEnabled())
177 .setUniqueIndexes(baseConfig.isUniqueIndexEnabled())
183 public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType) {
184 this(shard, schemaContext, treeType, YangInstanceIdentifier.EMPTY,
185 new DefaultShardDataTreeChangeListenerPublisher(""),
186 new DefaultShardDataChangeListenerPublisher(""), "");
189 final String logContext() {
193 final long readTime() {
194 return shard.ticker().read();
197 public DataTree getDataTree() {
201 SchemaContext getSchemaContext() {
202 return schemaContext;
205 void updateSchemaContext(final SchemaContext newSchemaContext) {
206 dataTree.setSchemaContext(newSchemaContext);
207 this.schemaContext = Preconditions.checkNotNull(newSchemaContext);
210 void resetTransactionBatch() {
211 currentTransactionBatch = 0;
215 * Take a snapshot of current state for later recovery.
217 * @return A state snapshot
219 @Nonnull ShardDataTreeSnapshot takeStateSnapshot() {
220 final NormalizedNode<?, ?> rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY).get();
221 final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
222 ImmutableMap.builder();
224 for (ShardDataTreeMetadata<?> m : metadata) {
225 final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
227 metaBuilder.put(meta.getType(), meta);
231 return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
234 private boolean anyPendingTransactions() {
235 return !pendingTransactions.isEmpty() || !pendingCommits.isEmpty() || !pendingFinishCommits.isEmpty();
238 private void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot,
239 final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
240 final Stopwatch elapsed = Stopwatch.createStarted();
242 if (anyPendingTransactions()) {
243 LOG.warn("{}: applying state snapshot with pending transactions", logContext);
246 final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
247 if (snapshot instanceof MetadataShardDataTreeSnapshot) {
248 snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
250 snapshotMeta = ImmutableMap.of();
253 for (ShardDataTreeMetadata<?> m : metadata) {
254 final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
262 final DataTreeModification mod = wrapper.apply(dataTree.takeSnapshot().newModification());
263 // delete everything first
264 mod.delete(YangInstanceIdentifier.EMPTY);
266 final java.util.Optional<NormalizedNode<?, ?>> maybeNode = snapshot.getRootNode();
267 if (maybeNode.isPresent()) {
268 // Add everything from the remote node back
269 mod.write(YangInstanceIdentifier.EMPTY, maybeNode.get());
273 final DataTreeModification unwrapped = unwrap(mod);
274 dataTree.validate(unwrapped);
275 DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
276 dataTree.commit(candidate);
277 notifyListeners(candidate);
279 LOG.debug("{}: state snapshot applied in {}", logContext, elapsed);
283 * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
284 * does not perform any pruning.
286 * @param snapshot Snapshot that needs to be applied
287 * @throws DataValidationFailedException when the snapshot fails to apply
289 void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
290 applySnapshot(snapshot, UnaryOperator.identity());
293 private PruningDataTreeModification wrapWithPruning(final DataTreeModification delegate) {
294 return new PruningDataTreeModification(delegate, dataTree, schemaContext);
297 private static DataTreeModification unwrap(final DataTreeModification modification) {
298 if (modification instanceof PruningDataTreeModification) {
299 return ((PruningDataTreeModification)modification).delegate();
305 * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
306 * pruning in an attempt to adjust the state to our current SchemaContext.
308 * @param snapshot Snapshot that needs to be applied
309 * @throws DataValidationFailedException when the snapshot fails to apply
311 void applyRecoverySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
312 applySnapshot(snapshot, this::wrapWithPruning);
315 @SuppressWarnings("checkstyle:IllegalCatch")
316 private void applyRecoveryCandidate(final DataTreeCandidate candidate) throws DataValidationFailedException {
317 final PruningDataTreeModification mod = wrapWithPruning(dataTree.takeSnapshot().newModification());
318 DataTreeCandidates.applyToModification(mod, candidate);
321 final DataTreeModification unwrapped = mod.delegate();
322 LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
325 dataTree.validate(unwrapped);
326 dataTree.commit(dataTree.prepare(unwrapped));
327 } catch (Exception e) {
328 File file = new File(System.getProperty("karaf.data", "."),
329 "failed-recovery-payload-" + logContext + ".out");
330 DataTreeModificationOutput.toFile(file, unwrapped);
331 throw new IllegalStateException(String.format(
332 "%s: Failed to apply recovery payload. Modification data was written to file %s",
333 logContext, file), e);
338 * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
339 * pruning in an attempt to adjust the state to our current SchemaContext.
341 * @param payload Payload
342 * @throws IOException when the snapshot fails to deserialize
343 * @throws DataValidationFailedException when the snapshot fails to apply
345 void applyRecoveryPayload(@Nonnull final Payload payload) throws IOException, DataValidationFailedException {
346 if (payload instanceof CommitTransactionPayload) {
347 final Entry<TransactionIdentifier, DataTreeCandidate> e =
348 ((CommitTransactionPayload) payload).getCandidate();
349 applyRecoveryCandidate(e.getValue());
350 allMetadataCommittedTransaction(e.getKey());
351 } else if (payload instanceof AbortTransactionPayload) {
352 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
353 } else if (payload instanceof PurgeTransactionPayload) {
354 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
355 } else if (payload instanceof CreateLocalHistoryPayload) {
356 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
357 } else if (payload instanceof CloseLocalHistoryPayload) {
358 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
359 } else if (payload instanceof PurgeLocalHistoryPayload) {
360 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
362 LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
366 private void applyReplicatedCandidate(final Identifier identifier, final DataTreeCandidate foreign)
367 throws DataValidationFailedException {
368 LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
370 final DataTreeModification mod = dataTree.takeSnapshot().newModification();
371 DataTreeCandidates.applyToModification(mod, foreign);
374 LOG.trace("{}: Applying foreign modification {}", logContext, mod);
375 dataTree.validate(mod);
376 final DataTreeCandidate candidate = dataTree.prepare(mod);
377 dataTree.commit(candidate);
379 notifyListeners(candidate);
383 * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
384 * SchemaContexts match and does not perform any pruning.
386 * @param identifier Payload identifier as returned from RaftActor
387 * @param payload Payload
388 * @throws IOException when the snapshot fails to deserialize
389 * @throws DataValidationFailedException when the snapshot fails to apply
391 void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
392 DataValidationFailedException {
394 * 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
395 * if we are the leader and it has originated with us.
397 * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
398 * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
399 * acting in that capacity anymore.
401 * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
402 * pre-Boron state -- which limits the number of options here.
404 if (payload instanceof CommitTransactionPayload) {
405 final TransactionIdentifier txId;
406 if (identifier == null) {
407 final Entry<TransactionIdentifier, DataTreeCandidate> e =
408 ((CommitTransactionPayload) payload).getCandidate();
410 applyReplicatedCandidate(txId, e.getValue());
412 Verify.verify(identifier instanceof TransactionIdentifier);
413 txId = (TransactionIdentifier) identifier;
414 payloadReplicationComplete(txId);
416 allMetadataCommittedTransaction(txId);
417 } else if (payload instanceof AbortTransactionPayload) {
418 if (identifier != null) {
419 payloadReplicationComplete((AbortTransactionPayload) payload);
421 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
422 } else if (payload instanceof PurgeTransactionPayload) {
423 if (identifier != null) {
424 payloadReplicationComplete((PurgeTransactionPayload) payload);
426 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
427 } else if (payload instanceof CloseLocalHistoryPayload) {
428 if (identifier != null) {
429 payloadReplicationComplete((CloseLocalHistoryPayload) payload);
431 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
432 } else if (payload instanceof CreateLocalHistoryPayload) {
433 if (identifier != null) {
434 payloadReplicationComplete((CreateLocalHistoryPayload)payload);
436 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
437 } else if (payload instanceof PurgeLocalHistoryPayload) {
438 if (identifier != null) {
439 payloadReplicationComplete((PurgeLocalHistoryPayload)payload);
441 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
443 LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
447 private void replicatePayload(final Identifier id, final Payload payload, @Nullable final Runnable callback) {
448 if (callback != null) {
449 replicationCallbacks.put(payload, callback);
451 shard.persistPayload(id, payload, true);
454 private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
455 final Runnable callback = replicationCallbacks.remove(payload);
456 if (callback != null) {
457 LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
460 LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
464 private void payloadReplicationComplete(final TransactionIdentifier txId) {
465 final CommitEntry current = pendingFinishCommits.peek();
466 if (current == null) {
467 LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
471 if (!current.cohort.getIdentifier().equals(txId)) {
472 LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
473 current.cohort.getIdentifier(), txId);
477 finishCommit(current.cohort);
480 private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
481 for (ShardDataTreeMetadata<?> m : metadata) {
482 m.onTransactionAborted(txId);
486 private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
487 for (ShardDataTreeMetadata<?> m : metadata) {
488 m.onTransactionCommitted(txId);
492 private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
493 for (ShardDataTreeMetadata<?> m : metadata) {
494 m.onTransactionPurged(txId);
498 private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
499 for (ShardDataTreeMetadata<?> m : metadata) {
500 m.onHistoryCreated(historyId);
504 private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
505 for (ShardDataTreeMetadata<?> m : metadata) {
506 m.onHistoryClosed(historyId);
510 private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
511 for (ShardDataTreeMetadata<?> m : metadata) {
512 m.onHistoryPurged(historyId);
517 * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
518 * this method is used for re-establishing state when we are taking over
520 * @param historyId Local history identifier
521 * @param closed True if the chain should be created in closed state (i.e. pending purge)
522 * @return Transaction chain handle
524 ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
525 final boolean closed) {
526 final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
527 final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
528 Preconditions.checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId,
533 ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId,
534 @Nullable final Runnable callback) {
535 ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
537 chain = new ShardDataTreeTransactionChain(historyId, this);
538 transactionChains.put(historyId, chain);
539 replicatePayload(historyId, CreateLocalHistoryPayload.create(historyId), callback);
540 } else if (callback != null) {
547 ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
548 if (txId.getHistoryId().getHistoryId() == 0) {
549 return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
552 return ensureTransactionChain(txId.getHistoryId(), null).newReadOnlyTransaction(txId);
555 ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
556 if (txId.getHistoryId().getHistoryId() == 0) {
557 return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
561 return ensureTransactionChain(txId.getHistoryId(), null).newReadWriteTransaction(txId);
565 public void notifyListeners(final DataTreeCandidate candidate) {
566 treeChangeListenerPublisher.publishChanges(candidate);
567 dataChangeListenerPublisher.publishChanges(candidate);
571 * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
572 * replication callbacks.
574 void purgeLeaderState() {
575 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
579 transactionChains.clear();
580 replicationCallbacks.clear();
584 * Close a single transaction chain.
586 * @param id History identifier
587 * @param callback Callback to invoke upon completion, may be null
589 void closeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
590 final ShardDataTreeTransactionChain chain = transactionChains.get(id);
592 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
593 if (callback != null) {
600 replicatePayload(id, CloseLocalHistoryPayload.create(id), callback);
604 * Purge a single transaction chain.
606 * @param id History identifier
607 * @param callback Callback to invoke upon completion, may be null
609 void purgeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
610 final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
612 LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
613 if (callback != null) {
619 replicatePayload(id, PurgeLocalHistoryPayload.create(id), callback);
622 void registerDataChangeListener(final YangInstanceIdentifier path,
623 final AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener,
624 final DataChangeScope scope, final Optional<DataTreeCandidate> initialState,
625 final Consumer<ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>>
627 dataChangeListenerPublisher.registerDataChangeListener(path, listener, scope, initialState, onRegistration);
630 Optional<DataTreeCandidate> readCurrentData() {
631 final java.util.Optional<NormalizedNode<?, ?>> currentState =
632 dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY);
633 return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
634 YangInstanceIdentifier.EMPTY, currentState.get())) : Optional.<DataTreeCandidate>absent();
637 public void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
638 final Optional<DataTreeCandidate> initialState,
639 final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
640 treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
644 return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
648 void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
649 final TransactionIdentifier id = transaction.getIdentifier();
650 LOG.debug("{}: aborting transaction {}", logContext, id);
651 replicatePayload(id, AbortTransactionPayload.create(id), callback);
655 void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
656 // No-op for free-standing transactions
661 ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction) {
662 final DataTreeModification snapshot = transaction.getSnapshot();
665 return createReadyCohort(transaction.getIdentifier(), snapshot);
668 void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
669 LOG.debug("{}: purging transaction {}", logContext, id);
670 replicatePayload(id, PurgeTransactionPayload.create(id), callback);
673 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
674 return Optional.fromJavaUtil(dataTree.takeSnapshot().readNode(path));
677 DataTreeSnapshot takeSnapshot() {
678 return dataTree.takeSnapshot();
682 public DataTreeModification newModification() {
683 return dataTree.takeSnapshot().newModification();
686 public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
687 Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
689 for (CommitEntry entry: pendingFinishCommits) {
690 ret.add(entry.cohort);
693 for (CommitEntry entry: pendingCommits) {
694 ret.add(entry.cohort);
697 for (CommitEntry entry: pendingTransactions) {
698 ret.add(entry.cohort);
701 pendingFinishCommits.clear();
702 pendingCommits.clear();
703 pendingTransactions.clear();
709 * Called some time after {@link #processNextPendingTransaction()} decides to stop processing.
711 void resumeNextPendingTransaction() {
712 LOG.debug("{}: attempting to resume transaction processing", logContext);
713 processNextPending();
716 @SuppressWarnings("checkstyle:IllegalCatch")
717 private void processNextPendingTransaction() {
718 ++currentTransactionBatch;
719 if (currentTransactionBatch > MAX_TRANSACTION_BATCH) {
720 LOG.debug("{}: Already processed {}, scheduling continuation", logContext, currentTransactionBatch);
721 shard.scheduleNextPendingTransaction();
725 processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
726 final SimpleShardDataTreeCohort cohort = entry.cohort;
727 final DataTreeModification modification = cohort.getDataTreeModification();
729 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
732 tip.validate(modification);
733 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
734 cohort.successfulCanCommit();
735 entry.lastAccess = readTime();
737 } catch (ConflictingModificationAppliedException e) {
738 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
740 cause = new OptimisticLockFailedException("Optimistic lock failed.", e);
741 } catch (DataValidationFailedException e) {
742 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
745 // For debugging purposes, allow dumping of the modification. Coupled with the above
746 // precondition log, it should allow us to understand what went on.
747 LOG.debug("{}: Store Tx {}: modifications: {} tree: {}", cohort.getIdentifier(), modification,
749 cause = new TransactionCommitFailedException("Data did not pass validation.", e);
750 } catch (Exception e) {
751 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
755 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
756 pendingTransactions.poll().cohort.failedCanCommit(cause);
760 private void processNextPending() {
761 processNextPendingCommit();
762 processNextPendingTransaction();
765 private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
766 final Consumer<CommitEntry> processor) {
767 while (!queue.isEmpty()) {
768 final CommitEntry entry = queue.peek();
769 final SimpleShardDataTreeCohort cohort = entry.cohort;
771 if (cohort.isFailed()) {
772 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
777 if (cohort.getState() == allowedState) {
778 processor.accept(entry);
784 maybeRunOperationOnPendingTransactionsComplete();
787 private void processNextPendingCommit() {
788 processNextPending(pendingCommits, State.COMMIT_PENDING,
789 entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
792 private boolean peekNextPendingCommit() {
793 final CommitEntry first = pendingCommits.peek();
794 return first != null && first.cohort.getState() == State.COMMIT_PENDING;
797 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
798 final CommitEntry head = pendingTransactions.peek();
800 LOG.warn("{}: No transactions enqueued while attempting to start canCommit on {}", logContext, cohort);
803 if (!cohort.equals(head.cohort)) {
804 LOG.debug("{}: Transaction {} scheduled for canCommit step", logContext, cohort.getIdentifier());
808 processNextPendingTransaction();
811 private void failPreCommit(final Throwable cause) {
812 shard.getShardMBean().incrementFailedTransactionsCount();
813 pendingTransactions.poll().cohort.failedPreCommit(cause);
814 processNextPendingTransaction();
817 @SuppressWarnings("checkstyle:IllegalCatch")
818 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
819 final CommitEntry entry = pendingTransactions.peek();
820 Preconditions.checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
822 final SimpleShardDataTreeCohort current = entry.cohort;
823 Verify.verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
825 LOG.debug("{}: Preparing transaction {}", logContext, current.getIdentifier());
827 final DataTreeCandidateTip candidate;
829 candidate = tip.prepare(cohort.getDataTreeModification());
830 } catch (RuntimeException e) {
835 cohort.userPreCommit(candidate, new FutureCallback<Void>() {
837 public void onSuccess(final Void noop) {
838 // Set the tip of the data tree.
839 tip = Verify.verifyNotNull(candidate);
841 entry.lastAccess = readTime();
843 pendingTransactions.remove();
844 pendingCommits.add(entry);
846 LOG.debug("{}: Transaction {} prepared", logContext, current.getIdentifier());
848 cohort.successfulPreCommit(candidate);
850 processNextPendingTransaction();
854 public void onFailure(final Throwable failure) {
855 failPreCommit(failure);
860 private void failCommit(final Exception cause) {
861 shard.getShardMBean().incrementFailedTransactionsCount();
862 pendingFinishCommits.poll().cohort.failedCommit(cause);
863 processNextPending();
866 @SuppressWarnings("checkstyle:IllegalCatch")
867 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
868 final TransactionIdentifier txId = cohort.getIdentifier();
869 final DataTreeCandidate candidate = cohort.getCandidate();
871 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
873 if (tip == candidate) {
874 // All pending candidates have been committed, reset the tip to the data tree.
879 dataTree.commit(candidate);
880 } catch (Exception e) {
881 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
886 shard.getShardMBean().incrementCommittedTransactionCount();
887 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
889 // FIXME: propagate journal index
890 pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO, () -> {
891 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
892 notifyListeners(candidate);
894 processNextPending();
898 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
899 final CommitEntry entry = pendingCommits.peek();
900 Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
902 final SimpleShardDataTreeCohort current = entry.cohort;
903 if (!cohort.equals(current)) {
904 LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
908 LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
910 final TransactionIdentifier txId = cohort.getIdentifier();
911 final Payload payload;
913 payload = CommitTransactionPayload.create(txId, candidate);
914 } catch (IOException e) {
915 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
916 pendingCommits.poll().cohort.failedCommit(e);
917 processNextPending();
921 // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
922 // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
923 // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
924 // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
925 // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
926 // pendingCommits queue.
927 processNextPendingTransaction();
929 // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
930 // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
931 // in order to properly determine the batchHint flag for the call to persistPayload.
932 pendingCommits.remove();
933 pendingFinishCommits.add(entry);
935 // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
936 // this transaction for replication.
937 boolean replicationBatchHint = peekNextPendingCommit();
939 // Once completed, we will continue via payloadReplicationComplete
940 shard.persistPayload(txId, payload, replicationBatchHint);
942 entry.lastAccess = shard.ticker().read();
944 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
946 // Process the next transaction pending commit, if any. If there is one it will be batched with this
947 // transaction for replication.
948 processNextPendingCommit();
951 Collection<ActorRef> getCohortActors() {
952 return cohortRegistry.getCohortActors();
955 void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
956 cohortRegistry.process(sender, message);
960 ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
961 final Exception failure) {
962 final SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId, failure);
963 pendingTransactions.add(new CommitEntry(cohort, readTime()));
968 ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod) {
969 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId,
970 cohortRegistry.createCohort(schemaContext, txId, runnable -> shard.executeInSelf(runnable),
971 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 Function<SimpleShardDataTreeCohort, Optional<Long>> accessTimeUpdater) {
989 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
990 final long now = readTime();
992 final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
993 !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
994 final CommitEntry currentTx = currentQueue.peek();
995 if (currentTx == null) {
996 // Empty queue, no-op
1000 long delta = now - currentTx.lastAccess;
1001 if (delta < timeout) {
1002 // Not expired yet, bail
1006 final Optional<Long> updateOpt = accessTimeUpdater.apply(currentTx.cohort);
1007 if (updateOpt.isPresent()) {
1008 final long newAccess = updateOpt.get().longValue();
1009 final long newDelta = now - newAccess;
1010 if (newDelta < delta) {
1011 LOG.debug("{}: Updated current transaction {} access time", logContext,
1012 currentTx.cohort.getIdentifier());
1013 currentTx.lastAccess = newAccess;
1017 if (delta < timeout) {
1018 // Not expired yet, bail
1023 final long deltaMillis = TimeUnit.NANOSECONDS.toMillis(delta);
1024 final State state = currentTx.cohort.getState();
1026 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
1027 currentTx.cohort.getIdentifier(), deltaMillis, state);
1028 boolean processNext = true;
1029 final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
1030 + deltaMillis + "ms");
1033 case CAN_COMMIT_PENDING:
1034 currentQueue.remove().cohort.failedCanCommit(cohortFailure);
1036 case CAN_COMMIT_COMPLETE:
1037 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
1038 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
1039 // in PRE_COMMIT_COMPLETE is changed.
1040 currentQueue.remove().cohort.reportFailure(cohortFailure);
1042 case PRE_COMMIT_PENDING:
1043 currentQueue.remove().cohort.failedPreCommit(cohortFailure);
1045 case PRE_COMMIT_COMPLETE:
1046 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
1047 // are ready we should commit the transaction, not abort it. Our current software stack does
1048 // not allow us to do that consistently, because we persist at the time of commit, hence
1049 // we can end up in a state where we have pre-committed a transaction, then a leader failover
1050 // occurred ... the new leader does not see the pre-committed transaction and does not have
1051 // a running timer. To fix this we really need two persistence events.
1053 // The first one, done at pre-commit time will hold the transaction payload. When consensus
1054 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1055 // apply the state in this event.
1057 // The second one, done at commit (or abort) time holds only the transaction identifier and
1058 // signals to followers that the state should (or should not) be applied.
1060 // In order to make the pre-commit timer working across failovers, though, we need
1061 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1062 // restart the timer.
1063 currentQueue.remove().cohort.reportFailure(cohortFailure);
1065 case COMMIT_PENDING:
1066 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1067 currentTx.cohort.getIdentifier());
1068 currentTx.lastAccess = now;
1069 processNext = false;
1072 currentQueue.remove().cohort.reportFailure(cohortFailure);
1078 currentQueue.remove();
1082 processNextPending();
1086 boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1087 final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1088 pendingTransactions).iterator();
1089 if (!it.hasNext()) {
1090 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1094 // First entry is special, as it may already be committing
1095 final CommitEntry first = it.next();
1096 if (cohort.equals(first.cohort)) {
1097 if (cohort.getState() != State.COMMIT_PENDING) {
1098 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1099 cohort.getIdentifier());
1102 if (cohort.getCandidate() != null) {
1103 rebaseTransactions(it, dataTree);
1106 processNextPending();
1110 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1114 DataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
1115 while (it.hasNext()) {
1116 final CommitEntry e = it.next();
1117 if (cohort.equals(e.cohort)) {
1118 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1121 if (cohort.getCandidate() != null) {
1122 rebaseTransactions(it, newTip);
1127 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), newTip);
1131 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1135 @SuppressWarnings("checkstyle:IllegalCatch")
1136 private void rebaseTransactions(final Iterator<CommitEntry> iter, @Nonnull final DataTreeTip newTip) {
1137 tip = Preconditions.checkNotNull(newTip);
1138 while (iter.hasNext()) {
1139 final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1140 if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1141 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1144 tip.validate(cohort.getDataTreeModification());
1145 } catch (DataValidationFailedException | RuntimeException e) {
1146 LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1147 cohort.reportFailure(e);
1149 } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1150 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1153 tip.validate(cohort.getDataTreeModification());
1154 DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1156 cohort.setNewCandidate(candidate);
1158 } catch (RuntimeException | DataValidationFailedException e) {
1159 LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1160 cohort.reportFailure(e);
1166 void setRunOnPendingTransactionsComplete(final Runnable operation) {
1167 runOnPendingTransactionsComplete = operation;
1168 maybeRunOperationOnPendingTransactionsComplete();
1171 private void maybeRunOperationOnPendingTransactionsComplete() {
1172 if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1173 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1174 runOnPendingTransactionsComplete);
1176 runOnPendingTransactionsComplete.run();
1177 runOnPendingTransactionsComplete = null;
1181 ShardStats getStats() {
1182 return shard.getShardMBean();
1185 Iterator<SimpleShardDataTreeCohort> cohortIterator() {
1186 return Iterables.transform(Iterables.concat(pendingFinishCommits, pendingCommits, pendingTransactions),
1187 e -> e.cohort).iterator();
1190 void removeTransactionChain(final LocalHistoryIdentifier id) {
1191 if (transactionChains.remove(id) != null) {
1192 LOG.debug("{}: Removed transaction chain {}", logContext, id);