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.Ticker;
18 import com.google.common.base.Verify;
19 import com.google.common.collect.ImmutableList;
20 import com.google.common.collect.ImmutableMap;
21 import com.google.common.collect.ImmutableMap.Builder;
22 import com.google.common.collect.Iterables;
23 import com.google.common.primitives.UnsignedLong;
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.ExecutionException;
36 import java.util.concurrent.TimeUnit;
37 import java.util.concurrent.TimeoutException;
38 import java.util.function.Consumer;
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.DataTreeCandidate;
72 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
73 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
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.TipProducingDataTree;
79 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTreeTip;
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);
110 private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
112 private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
113 private final Queue<CommitEntry> pendingTransactions = new ArrayDeque<>();
114 private final Queue<CommitEntry> pendingCommits = new ArrayDeque<>();
115 private final Queue<CommitEntry> pendingFinishCommits = new ArrayDeque<>();
118 * Callbacks that need to be invoked once a payload is replicated.
120 private final Map<Payload, Runnable> replicationCallbacks = new HashMap<>();
122 private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
123 private final ShardDataChangeListenerPublisher dataChangeListenerPublisher;
124 private final Collection<ShardDataTreeMetadata<?>> metadata;
125 private final TipProducingDataTree dataTree;
126 private final String logContext;
127 private final Shard shard;
128 private Runnable runOnPendingTransactionsComplete;
131 * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
132 * {@link TipProducingDataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
133 * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
134 * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
136 private TipProducingDataTreeTip tip;
138 private SchemaContext schemaContext;
140 ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TipProducingDataTree dataTree,
141 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
142 final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext,
143 final ShardDataTreeMetadata<?>... metadata) {
144 this.dataTree = Preconditions.checkNotNull(dataTree);
145 updateSchemaContext(schemaContext);
147 this.shard = Preconditions.checkNotNull(shard);
148 this.treeChangeListenerPublisher = Preconditions.checkNotNull(treeChangeListenerPublisher);
149 this.dataChangeListenerPublisher = Preconditions.checkNotNull(dataChangeListenerPublisher);
150 this.logContext = Preconditions.checkNotNull(logContext);
151 this.metadata = ImmutableList.copyOf(metadata);
155 ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType,
156 final YangInstanceIdentifier root,
157 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
158 final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext,
159 final ShardDataTreeMetadata<?>... metadata) {
160 this(shard, schemaContext, InMemoryDataTreeFactory.getInstance().create(treeType, root),
161 treeChangeListenerPublisher, dataChangeListenerPublisher, logContext, metadata);
165 public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType) {
166 this(shard, schemaContext, treeType, YangInstanceIdentifier.EMPTY,
167 new DefaultShardDataTreeChangeListenerPublisher(""),
168 new DefaultShardDataChangeListenerPublisher(""), "");
171 final String logContext() {
175 final Ticker ticker() {
176 return shard.ticker();
179 public TipProducingDataTree getDataTree() {
183 SchemaContext getSchemaContext() {
184 return schemaContext;
187 void updateSchemaContext(final SchemaContext newSchemaContext) {
188 dataTree.setSchemaContext(newSchemaContext);
189 this.schemaContext = Preconditions.checkNotNull(newSchemaContext);
193 * Take a snapshot of current state for later recovery.
195 * @return A state snapshot
197 @Nonnull ShardDataTreeSnapshot takeStateSnapshot() {
198 final NormalizedNode<?, ?> rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY).get();
199 final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
200 ImmutableMap.builder();
202 for (ShardDataTreeMetadata<?> m : metadata) {
203 final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
205 metaBuilder.put(meta.getType(), meta);
209 return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
212 private boolean anyPendingTransactions() {
213 return !pendingTransactions.isEmpty() || !pendingCommits.isEmpty() || !pendingFinishCommits.isEmpty();
216 private void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot,
217 final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
218 final Stopwatch elapsed = Stopwatch.createStarted();
220 if (anyPendingTransactions()) {
221 LOG.warn("{}: applying state snapshot with pending transactions", logContext);
224 final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
225 if (snapshot instanceof MetadataShardDataTreeSnapshot) {
226 snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
228 snapshotMeta = ImmutableMap.of();
231 for (ShardDataTreeMetadata<?> m : metadata) {
232 final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
240 final DataTreeModification mod = wrapper.apply(dataTree.takeSnapshot().newModification());
241 // delete everything first
242 mod.delete(YangInstanceIdentifier.EMPTY);
244 final java.util.Optional<NormalizedNode<?, ?>> maybeNode = snapshot.getRootNode();
245 if (maybeNode.isPresent()) {
246 // Add everything from the remote node back
247 mod.write(YangInstanceIdentifier.EMPTY, maybeNode.get());
251 final DataTreeModification unwrapped = unwrap(mod);
252 dataTree.validate(unwrapped);
253 DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
254 dataTree.commit(candidate);
255 notifyListeners(candidate);
257 LOG.debug("{}: state snapshot applied in {}", logContext, elapsed);
261 * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
262 * does not perform any pruning.
264 * @param snapshot Snapshot that needs to be applied
265 * @throws DataValidationFailedException when the snapshot fails to apply
267 void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
268 applySnapshot(snapshot, UnaryOperator.identity());
271 private PruningDataTreeModification wrapWithPruning(final DataTreeModification delegate) {
272 return new PruningDataTreeModification(delegate, dataTree, schemaContext);
275 private static DataTreeModification unwrap(final DataTreeModification modification) {
276 if (modification instanceof PruningDataTreeModification) {
277 return ((PruningDataTreeModification)modification).delegate();
283 * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
284 * pruning in an attempt to adjust the state to our current SchemaContext.
286 * @param snapshot Snapshot that needs to be applied
287 * @throws DataValidationFailedException when the snapshot fails to apply
289 void applyRecoverySnapshot(final @Nonnull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
290 applySnapshot(snapshot, this::wrapWithPruning);
293 @SuppressWarnings("checkstyle:IllegalCatch")
294 private void applyRecoveryCandidate(final DataTreeCandidate candidate) throws DataValidationFailedException {
295 final PruningDataTreeModification mod = wrapWithPruning(dataTree.takeSnapshot().newModification());
296 DataTreeCandidates.applyToModification(mod, candidate);
299 final DataTreeModification unwrapped = mod.delegate();
300 LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
303 dataTree.validate(unwrapped);
304 dataTree.commit(dataTree.prepare(unwrapped));
305 } catch (Exception e) {
306 File file = new File(System.getProperty("karaf.data", "."),
307 "failed-recovery-payload-" + logContext + ".out");
308 DataTreeModificationOutput.toFile(file, unwrapped);
309 throw new IllegalStateException(String.format(
310 "%s: Failed to apply recovery payload. Modification data was written to file %s",
311 logContext, file), e);
316 * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
317 * pruning in an attempt to adjust the state to our current SchemaContext.
319 * @param payload Payload
320 * @throws IOException when the snapshot fails to deserialize
321 * @throws DataValidationFailedException when the snapshot fails to apply
323 void applyRecoveryPayload(final @Nonnull Payload payload) throws IOException, DataValidationFailedException {
324 if (payload instanceof CommitTransactionPayload) {
325 final Entry<TransactionIdentifier, DataTreeCandidate> e =
326 ((CommitTransactionPayload) payload).getCandidate();
327 applyRecoveryCandidate(e.getValue());
328 allMetadataCommittedTransaction(e.getKey());
329 } else if (payload instanceof AbortTransactionPayload) {
330 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
331 } else if (payload instanceof PurgeTransactionPayload) {
332 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
333 } else if (payload instanceof CreateLocalHistoryPayload) {
334 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
335 } else if (payload instanceof CloseLocalHistoryPayload) {
336 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
337 } else if (payload instanceof PurgeLocalHistoryPayload) {
338 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
339 } else if (payload instanceof DataTreeCandidatePayload) {
340 applyRecoveryCandidate(((DataTreeCandidatePayload) payload).getCandidate());
342 LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
346 private void applyReplicatedCandidate(final Identifier identifier, final DataTreeCandidate foreign)
347 throws DataValidationFailedException {
348 LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
350 final DataTreeModification mod = dataTree.takeSnapshot().newModification();
351 DataTreeCandidates.applyToModification(mod, foreign);
354 LOG.trace("{}: Applying foreign modification {}", logContext, mod);
355 dataTree.validate(mod);
356 final DataTreeCandidate candidate = dataTree.prepare(mod);
357 dataTree.commit(candidate);
359 notifyListeners(candidate);
363 * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
364 * SchemaContexts match and does not perform any pruning.
366 * @param identifier Payload identifier as returned from RaftActor
367 * @param payload Payload
368 * @throws IOException when the snapshot fails to deserialize
369 * @throws DataValidationFailedException when the snapshot fails to apply
371 void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
372 DataValidationFailedException {
374 * 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
375 * if we are the leader and it has originated with us.
377 * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
378 * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
379 * acting in that capacity anymore.
381 * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
382 * pre-Boron state -- which limits the number of options here.
384 if (payload instanceof CommitTransactionPayload) {
385 if (identifier == null) {
386 final Entry<TransactionIdentifier, DataTreeCandidate> e =
387 ((CommitTransactionPayload) payload).getCandidate();
388 applyReplicatedCandidate(e.getKey(), e.getValue());
389 allMetadataCommittedTransaction(e.getKey());
391 Verify.verify(identifier instanceof TransactionIdentifier);
392 payloadReplicationComplete((TransactionIdentifier) identifier);
394 } else if (payload instanceof AbortTransactionPayload) {
395 if (identifier != null) {
396 payloadReplicationComplete((AbortTransactionPayload) payload);
398 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
400 } else if (payload instanceof PurgeTransactionPayload) {
401 if (identifier != null) {
402 payloadReplicationComplete((PurgeTransactionPayload) payload);
404 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
406 } else if (payload instanceof CloseLocalHistoryPayload) {
407 if (identifier != null) {
408 payloadReplicationComplete((CloseLocalHistoryPayload) payload);
410 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
412 } else if (payload instanceof CreateLocalHistoryPayload) {
413 if (identifier != null) {
414 payloadReplicationComplete((CreateLocalHistoryPayload)payload);
416 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
418 } else if (payload instanceof PurgeLocalHistoryPayload) {
419 if (identifier != null) {
420 payloadReplicationComplete((PurgeLocalHistoryPayload)payload);
422 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
425 LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
429 private void replicatePayload(final Identifier id, final Payload payload, @Nullable final Runnable callback) {
430 if (callback != null) {
431 replicationCallbacks.put(payload, callback);
433 shard.persistPayload(id, payload, true);
436 private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
437 final Runnable callback = replicationCallbacks.remove(payload);
438 if (callback != null) {
439 LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
442 LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
446 private void payloadReplicationComplete(final TransactionIdentifier txId) {
447 final CommitEntry current = pendingFinishCommits.peek();
448 if (current == null) {
449 LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
453 if (!current.cohort.getIdentifier().equals(txId)) {
454 LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
455 current.cohort.getIdentifier(), txId);
459 finishCommit(current.cohort);
462 private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
463 for (ShardDataTreeMetadata<?> m : metadata) {
464 m.onTransactionAborted(txId);
468 private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
469 for (ShardDataTreeMetadata<?> m : metadata) {
470 m.onTransactionCommitted(txId);
474 private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
475 for (ShardDataTreeMetadata<?> m : metadata) {
476 m.onTransactionPurged(txId);
480 private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
481 for (ShardDataTreeMetadata<?> m : metadata) {
482 m.onHistoryCreated(historyId);
486 private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
487 for (ShardDataTreeMetadata<?> m : metadata) {
488 m.onHistoryClosed(historyId);
492 private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
493 for (ShardDataTreeMetadata<?> m : metadata) {
494 m.onHistoryPurged(historyId);
499 * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
500 * this method is used for re-establishing state when we are taking over
502 * @param historyId Local history identifier
503 * @param closed True if the chain should be created in closed state (i.e. pending purge)
504 * @return Transaction chain handle
506 ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
507 final boolean closed) {
508 final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
509 final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
510 Preconditions.checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId,
515 ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId) {
516 ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
518 chain = new ShardDataTreeTransactionChain(historyId, this);
519 transactionChains.put(historyId, chain);
520 shard.persistPayload(historyId, CreateLocalHistoryPayload.create(historyId), true);
526 ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
527 if (txId.getHistoryId().getHistoryId() == 0) {
528 return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
531 return ensureTransactionChain(txId.getHistoryId()).newReadOnlyTransaction(txId);
534 ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
535 if (txId.getHistoryId().getHistoryId() == 0) {
536 return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
540 return ensureTransactionChain(txId.getHistoryId()).newReadWriteTransaction(txId);
544 public void notifyListeners(final DataTreeCandidate candidate) {
545 treeChangeListenerPublisher.publishChanges(candidate);
546 dataChangeListenerPublisher.publishChanges(candidate);
550 * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
551 * replication callbacks.
553 void purgeLeaderState() {
554 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
558 transactionChains.clear();
559 replicationCallbacks.clear();
563 * Close a single transaction chain.
565 * @param id History identifier
566 * @param callback Callback to invoke upon completion, may be null
568 void closeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
569 final ShardDataTreeTransactionChain chain = transactionChains.get(id);
571 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
572 if (callback != null) {
579 replicatePayload(id, CloseLocalHistoryPayload.create(id), callback);
583 * Purge a single transaction chain.
585 * @param id History identifier
586 * @param callback Callback to invoke upon completion, may be null
588 void purgeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
589 final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
591 LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
592 if (callback != null) {
598 replicatePayload(id, PurgeLocalHistoryPayload.create(id), callback);
601 void registerDataChangeListener(final YangInstanceIdentifier path,
602 final AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener,
603 final DataChangeScope scope, final Optional<DataTreeCandidate> initialState,
604 final Consumer<ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>>
606 dataChangeListenerPublisher.registerDataChangeListener(path, listener, scope, initialState, onRegistration);
609 Optional<DataTreeCandidate> readCurrentData() {
610 final Optional<NormalizedNode<?, ?>> currentState =
611 dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY);
612 return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
613 YangInstanceIdentifier.EMPTY, currentState.get())) : Optional.<DataTreeCandidate>absent();
616 public void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
617 final Optional<DataTreeCandidate> initialState,
618 final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
619 treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
623 return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
627 void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
628 final TransactionIdentifier id = transaction.getIdentifier();
629 LOG.debug("{}: aborting transaction {}", logContext, id);
630 replicatePayload(id, AbortTransactionPayload.create(id), callback);
634 void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
635 // No-op for free-standing transactions
640 ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction) {
641 final DataTreeModification snapshot = transaction.getSnapshot();
644 return createReadyCohort(transaction.getIdentifier(), snapshot);
647 void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
648 LOG.debug("{}: purging transaction {}", logContext, id);
649 replicatePayload(id, PurgeTransactionPayload.create(id), callback);
652 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
653 return dataTree.takeSnapshot().readNode(path);
656 DataTreeSnapshot takeSnapshot() {
657 return dataTree.takeSnapshot();
661 public DataTreeModification newModification() {
662 return dataTree.takeSnapshot().newModification();
666 * Commits a modification.
668 * @deprecated This method violates DataTree containment and will be removed.
672 public DataTreeCandidate commit(final DataTreeModification modification) throws DataValidationFailedException {
673 // Direct modification commit is a utility, which cannot be used while we have transactions in-flight
674 Preconditions.checkState(tip == dataTree, "Cannot modify data tree while transacgitons are pending");
676 modification.ready();
677 dataTree.validate(modification);
678 DataTreeCandidate candidate = dataTree.prepare(modification);
679 dataTree.commit(candidate);
683 public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
684 Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
686 for (CommitEntry entry: pendingFinishCommits) {
687 ret.add(entry.cohort);
690 for (CommitEntry entry: pendingCommits) {
691 ret.add(entry.cohort);
694 for (CommitEntry entry: pendingTransactions) {
695 ret.add(entry.cohort);
698 pendingFinishCommits.clear();
699 pendingCommits.clear();
700 pendingTransactions.clear();
705 @SuppressWarnings("checkstyle:IllegalCatch")
706 private void processNextPendingTransaction() {
707 processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
708 final SimpleShardDataTreeCohort cohort = entry.cohort;
709 final DataTreeModification modification = cohort.getDataTreeModification();
711 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
714 cohort.throwCanCommitFailure();
716 tip.validate(modification);
717 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
718 cohort.successfulCanCommit();
719 entry.lastAccess = ticker().read();
721 } catch (ConflictingModificationAppliedException e) {
722 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
724 cause = new OptimisticLockFailedException("Optimistic lock failed.", e);
725 } catch (DataValidationFailedException e) {
726 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
729 // For debugging purposes, allow dumping of the modification. Coupled with the above
730 // precondition log, it should allow us to understand what went on.
731 LOG.debug("{}: Store Tx {}: modifications: {} tree: {}", cohort.getIdentifier(), modification,
733 cause = new TransactionCommitFailedException("Data did not pass validation.", e);
734 } catch (Exception e) {
735 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
739 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
740 pendingTransactions.poll().cohort.failedCanCommit(cause);
744 private void processNextPending() {
745 processNextPendingCommit();
746 processNextPendingTransaction();
749 private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
750 final Consumer<CommitEntry> processor) {
751 while (!queue.isEmpty()) {
752 final CommitEntry entry = queue.peek();
753 final SimpleShardDataTreeCohort cohort = entry.cohort;
755 if (cohort.isFailed()) {
756 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
761 if (cohort.getState() == allowedState) {
762 processor.accept(entry);
768 maybeRunOperationOnPendingTransactionsComplete();
771 private void processNextPendingCommit() {
772 processNextPending(pendingCommits, State.COMMIT_PENDING,
773 entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
776 private boolean peekNextPendingCommit() {
777 final CommitEntry first = pendingCommits.peek();
778 return first != null && first.cohort.getState() == State.COMMIT_PENDING;
781 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
782 final SimpleShardDataTreeCohort current = pendingTransactions.peek().cohort;
783 if (!cohort.equals(current)) {
784 LOG.debug("{}: Transaction {} scheduled for canCommit step", logContext, cohort.getIdentifier());
788 processNextPendingTransaction();
791 private void failPreCommit(final Exception cause) {
792 shard.getShardMBean().incrementFailedTransactionsCount();
793 pendingTransactions.poll().cohort.failedPreCommit(cause);
794 processNextPendingTransaction();
797 @SuppressWarnings("checkstyle:IllegalCatch")
798 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
799 final CommitEntry entry = pendingTransactions.peek();
800 Preconditions.checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
802 final SimpleShardDataTreeCohort current = entry.cohort;
803 Verify.verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
805 LOG.debug("{}: Preparing transaction {}", logContext, current.getIdentifier());
807 final DataTreeCandidateTip candidate;
809 candidate = tip.prepare(cohort.getDataTreeModification());
810 cohort.userPreCommit(candidate);
811 } catch (ExecutionException | TimeoutException | RuntimeException e) {
816 // Set the tip of the data tree.
817 tip = Verify.verifyNotNull(candidate);
819 entry.lastAccess = ticker().read();
821 pendingTransactions.remove();
822 pendingCommits.add(entry);
824 LOG.debug("{}: Transaction {} prepared", logContext, current.getIdentifier());
826 cohort.successfulPreCommit(candidate);
828 processNextPendingTransaction();
831 private void failCommit(final Exception cause) {
832 shard.getShardMBean().incrementFailedTransactionsCount();
833 pendingFinishCommits.poll().cohort.failedCommit(cause);
834 processNextPending();
837 @SuppressWarnings("checkstyle:IllegalCatch")
838 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
839 final TransactionIdentifier txId = cohort.getIdentifier();
840 final DataTreeCandidate candidate = cohort.getCandidate();
842 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
844 if (tip == candidate) {
845 // All pending candidates have been committed, reset the tip to the data tree.
850 dataTree.commit(candidate);
851 } catch (Exception e) {
852 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
857 shard.getShardMBean().incrementCommittedTransactionCount();
858 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
860 // FIXME: propagate journal index
861 pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO);
863 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
864 notifyListeners(candidate);
866 processNextPending();
869 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
870 final CommitEntry entry = pendingCommits.peek();
871 Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
873 final SimpleShardDataTreeCohort current = entry.cohort;
874 if (!cohort.equals(current)) {
875 LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
879 LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
881 final TransactionIdentifier txId = cohort.getIdentifier();
882 final Payload payload;
884 payload = CommitTransactionPayload.create(txId, candidate);
885 } catch (IOException e) {
886 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
887 pendingCommits.poll().cohort.failedCommit(e);
888 processNextPending();
892 // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
893 // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
894 // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
895 // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
896 // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
897 // pendingCommits queue.
898 processNextPendingTransaction();
900 // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
901 // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
902 // in order to properly determine the batchHint flag for the call to persistPayload.
903 pendingCommits.remove();
904 pendingFinishCommits.add(entry);
906 // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
907 // this transaction for replication.
908 boolean replicationBatchHint = peekNextPendingCommit();
910 // Once completed, we will continue via payloadReplicationComplete
911 shard.persistPayload(txId, payload, replicationBatchHint);
913 entry.lastAccess = shard.ticker().read();
915 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
917 // Process the next transaction pending commit, if any. If there is one it will be batched with this
918 // transaction for replication.
919 processNextPendingCommit();
922 Collection<ActorRef> getCohortActors() {
923 return cohortRegistry.getCohortActors();
926 void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
927 cohortRegistry.process(sender, message);
931 ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
932 final Exception failure) {
933 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort.DeadOnArrival(this, mod, txId, failure);
934 pendingTransactions.add(new CommitEntry(cohort, ticker().read()));
939 ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod) {
940 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort.Normal(this, mod, txId,
941 cohortRegistry.createCohort(schemaContext, txId, COMMIT_STEP_TIMEOUT));
942 pendingTransactions.add(new CommitEntry(cohort, ticker().read()));
946 // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
947 // the newReadWriteTransaction()
948 ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod) {
949 if (txId.getHistoryId().getHistoryId() == 0) {
950 return createReadyCohort(txId, mod);
953 return ensureTransactionChain(txId.getHistoryId()).createReadyCohort(txId, mod);
956 @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
957 void checkForExpiredTransactions(final long transactionCommitTimeoutMillis) {
958 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
959 final long now = ticker().read();
961 final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
962 !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
963 final CommitEntry currentTx = currentQueue.peek();
964 if (currentTx != null && currentTx.lastAccess + timeout < now) {
965 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
966 currentTx.cohort.getIdentifier(), transactionCommitTimeoutMillis, currentTx.cohort.getState());
967 boolean processNext = true;
968 switch (currentTx.cohort.getState()) {
969 case CAN_COMMIT_PENDING:
970 currentQueue.remove().cohort.failedCanCommit(new TimeoutException());
972 case CAN_COMMIT_COMPLETE:
973 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
974 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
975 // in PRE_COMMIT_COMPLETE is changed.
976 currentQueue.remove().cohort.reportFailure(new TimeoutException());
978 case PRE_COMMIT_PENDING:
979 currentQueue.remove().cohort.failedPreCommit(new TimeoutException());
981 case PRE_COMMIT_COMPLETE:
982 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
983 // are ready we should commit the transaction, not abort it. Our current software stack does
984 // not allow us to do that consistently, because we persist at the time of commit, hence
985 // we can end up in a state where we have pre-committed a transaction, then a leader failover
986 // occurred ... the new leader does not see the pre-committed transaction and does not have
987 // a running timer. To fix this we really need two persistence events.
989 // The first one, done at pre-commit time will hold the transaction payload. When consensus
990 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
991 // apply the state in this event.
993 // The second one, done at commit (or abort) time holds only the transaction identifier and
994 // signals to followers that the state should (or should not) be applied.
996 // In order to make the pre-commit timer working across failovers, though, we need
997 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
998 // restart the timer.
999 currentQueue.remove().cohort.reportFailure(new TimeoutException());
1001 case COMMIT_PENDING:
1002 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1003 currentTx.cohort.getIdentifier());
1004 currentTx.lastAccess = now;
1005 processNext = false;
1012 currentQueue.remove();
1016 processNextPending();
1021 boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1022 final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1023 pendingTransactions).iterator();
1024 if (!it.hasNext()) {
1025 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1029 // First entry is special, as it may already be committing
1030 final CommitEntry first = it.next();
1031 if (cohort.equals(first.cohort)) {
1032 if (cohort.getState() != State.COMMIT_PENDING) {
1033 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1034 cohort.getIdentifier());
1037 if (cohort.getCandidate() != null) {
1038 rebaseTransactions(it, dataTree);
1041 processNextPending();
1045 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1049 TipProducingDataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
1050 while (it.hasNext()) {
1051 final CommitEntry e = it.next();
1052 if (cohort.equals(e.cohort)) {
1053 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1056 if (cohort.getCandidate() != null) {
1057 rebaseTransactions(it, newTip);
1062 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), newTip);
1066 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1070 @SuppressWarnings("checkstyle:IllegalCatch")
1071 private void rebaseTransactions(final Iterator<CommitEntry> iter, @Nonnull final TipProducingDataTreeTip newTip) {
1072 tip = Preconditions.checkNotNull(newTip);
1073 while (iter.hasNext()) {
1074 final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1075 if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1076 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1079 tip.validate(cohort.getDataTreeModification());
1080 } catch (DataValidationFailedException | RuntimeException e) {
1081 LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1082 cohort.reportFailure(e);
1084 } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1085 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1088 tip.validate(cohort.getDataTreeModification());
1089 DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1090 cohort.userPreCommit(candidate);
1092 cohort.setNewCandidate(candidate);
1094 } catch (ExecutionException | TimeoutException | RuntimeException | DataValidationFailedException e) {
1095 LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1096 cohort.reportFailure(e);
1102 void setRunOnPendingTransactionsComplete(final Runnable operation) {
1103 runOnPendingTransactionsComplete = operation;
1104 maybeRunOperationOnPendingTransactionsComplete();
1107 private void maybeRunOperationOnPendingTransactionsComplete() {
1108 if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1109 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1110 runOnPendingTransactionsComplete);
1112 runOnPendingTransactionsComplete.run();
1113 runOnPendingTransactionsComplete = null;
1117 ShardStats getStats() {
1118 return shard.getShardMBean();