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.AbstractMap.SimpleEntry;
28 import java.util.ArrayDeque;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.HashMap;
32 import java.util.Iterator;
34 import java.util.Map.Entry;
35 import java.util.Queue;
36 import java.util.concurrent.ExecutionException;
37 import java.util.concurrent.TimeUnit;
38 import java.util.concurrent.TimeoutException;
39 import java.util.function.UnaryOperator;
40 import javax.annotation.Nonnull;
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.persisted.CommitTransactionPayload;
47 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
48 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
49 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshotMetadata;
50 import org.opendaylight.controller.cluster.datastore.utils.DataTreeModificationOutput;
51 import org.opendaylight.controller.cluster.datastore.utils.PruningDataTreeModification;
52 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
53 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
54 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
55 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
56 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
57 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
58 import org.opendaylight.controller.md.sal.dom.store.impl.DataChangeListenerRegistration;
59 import org.opendaylight.yangtools.concepts.Identifier;
60 import org.opendaylight.yangtools.concepts.ListenerRegistration;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
62 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
64 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
65 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
66 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
67 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
68 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
69 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeTip;
70 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
71 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
72 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
73 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTreeTip;
74 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
75 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
76 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
79 import scala.concurrent.duration.Duration;
82 * Internal shard state, similar to a DOMStore, but optimized for use in the actor system,
83 * e.g. it does not expose public interfaces and assumes it is only ever called from a
87 * This class is not part of the API contract and is subject to change at any time.
90 public class ShardDataTree extends ShardDataTreeTransactionParent {
91 private static final class CommitEntry {
92 final SimpleShardDataTreeCohort cohort;
95 CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
96 this.cohort = Preconditions.checkNotNull(cohort);
101 private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(Duration.create(5, TimeUnit.SECONDS));
102 private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
104 private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
105 private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
106 private final Queue<CommitEntry> pendingTransactions = new ArrayDeque<>();
107 private final Queue<CommitEntry> pendingCommits = new ArrayDeque<>();
108 private final Queue<CommitEntry> pendingFinishCommits = new ArrayDeque<>();
109 private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
110 private final ShardDataChangeListenerPublisher dataChangeListenerPublisher;
111 private final Collection<ShardDataTreeMetadata<?>> metadata;
112 private final TipProducingDataTree dataTree;
113 private final String logContext;
114 private final Shard shard;
115 private Runnable runOnPendingTransactionsComplete;
118 * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
119 * {@link TipProducingDataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
120 * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
121 * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
123 private TipProducingDataTreeTip tip;
125 private SchemaContext schemaContext;
127 public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TipProducingDataTree dataTree,
128 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
129 final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext,
130 final ShardDataTreeMetadata<?>... metadata) {
131 this.dataTree = Preconditions.checkNotNull(dataTree);
132 updateSchemaContext(schemaContext);
134 this.shard = Preconditions.checkNotNull(shard);
135 this.treeChangeListenerPublisher = Preconditions.checkNotNull(treeChangeListenerPublisher);
136 this.dataChangeListenerPublisher = Preconditions.checkNotNull(dataChangeListenerPublisher);
137 this.logContext = Preconditions.checkNotNull(logContext);
138 this.metadata = ImmutableList.copyOf(metadata);
142 public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType,
143 final YangInstanceIdentifier root,
144 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
145 final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext) {
146 this(shard, schemaContext, InMemoryDataTreeFactory.getInstance().create(treeType, root),
147 treeChangeListenerPublisher, dataChangeListenerPublisher, logContext);
151 public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType) {
152 this(shard, schemaContext, treeType, YangInstanceIdentifier.EMPTY,
153 new DefaultShardDataTreeChangeListenerPublisher(),
154 new DefaultShardDataChangeListenerPublisher(), "");
157 final String logContext() {
161 final Ticker ticker() {
162 return shard.ticker();
165 public TipProducingDataTree getDataTree() {
169 SchemaContext getSchemaContext() {
170 return schemaContext;
173 void updateSchemaContext(final SchemaContext newSchemaContext) {
174 dataTree.setSchemaContext(newSchemaContext);
175 this.schemaContext = Preconditions.checkNotNull(newSchemaContext);
179 * Take a snapshot of current state for later recovery.
181 * @return A state snapshot
183 @Nonnull ShardDataTreeSnapshot takeStateSnapshot() {
184 final NormalizedNode<?, ?> rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY).get();
185 final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
186 ImmutableMap.builder();
188 for (ShardDataTreeMetadata<?> m : metadata) {
189 final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
191 metaBuilder.put(meta.getType(), meta);
195 return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
198 private boolean anyPendingTransactions() {
199 return !pendingTransactions.isEmpty() || !pendingCommits.isEmpty() || !pendingFinishCommits.isEmpty();
202 private void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot,
203 final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
204 final Stopwatch elapsed = Stopwatch.createStarted();
206 if (anyPendingTransactions()) {
207 LOG.warn("{}: applying state snapshot with pending transactions", logContext);
210 final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
211 if (snapshot instanceof MetadataShardDataTreeSnapshot) {
212 snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
214 snapshotMeta = ImmutableMap.of();
217 for (ShardDataTreeMetadata<?> m : metadata) {
218 final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
226 final DataTreeModification mod = wrapper.apply(dataTree.takeSnapshot().newModification());
227 // delete everything first
228 mod.delete(YangInstanceIdentifier.EMPTY);
230 final java.util.Optional<NormalizedNode<?, ?>> maybeNode = snapshot.getRootNode();
231 if (maybeNode.isPresent()) {
232 // Add everything from the remote node back
233 mod.write(YangInstanceIdentifier.EMPTY, maybeNode.get());
237 final DataTreeModification unwrapped = unwrap(mod);
238 dataTree.validate(unwrapped);
239 DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
240 dataTree.commit(candidate);
241 notifyListeners(candidate);
243 LOG.debug("{}: state snapshot applied in %s", logContext, elapsed);
247 * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
248 * does not perform any pruning.
250 * @param snapshot Snapshot that needs to be applied
251 * @throws DataValidationFailedException when the snapshot fails to apply
253 void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
254 applySnapshot(snapshot, UnaryOperator.identity());
257 private PruningDataTreeModification wrapWithPruning(final DataTreeModification delegate) {
258 return new PruningDataTreeModification(delegate, dataTree, schemaContext);
261 private static DataTreeModification unwrap(final DataTreeModification modification) {
262 if (modification instanceof PruningDataTreeModification) {
263 return ((PruningDataTreeModification)modification).delegate();
269 * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
270 * pruning in an attempt to adjust the state to our current SchemaContext.
272 * @param snapshot Snapshot that needs to be applied
273 * @throws DataValidationFailedException when the snapshot fails to apply
275 void applyRecoverySnapshot(final @Nonnull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
276 applySnapshot(snapshot, this::wrapWithPruning);
279 @SuppressWarnings("checkstyle:IllegalCatch")
280 private void applyRecoveryCandidate(final DataTreeCandidate candidate) throws DataValidationFailedException {
281 final PruningDataTreeModification mod = wrapWithPruning(dataTree.takeSnapshot().newModification());
282 DataTreeCandidates.applyToModification(mod, candidate);
285 final DataTreeModification unwrapped = mod.delegate();
286 LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
289 dataTree.validate(unwrapped);
290 dataTree.commit(dataTree.prepare(unwrapped));
291 } catch (Exception e) {
292 File file = new File(System.getProperty("karaf.data", "."),
293 "failed-recovery-payload-" + logContext + ".out");
294 DataTreeModificationOutput.toFile(file, unwrapped);
295 throw new IllegalStateException(String.format(
296 "%s: Failed to apply recovery payload. Modification data was written to file %s",
297 logContext, file), e);
302 * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
303 * pruning in an attempt to adjust the state to our current SchemaContext.
305 * @param payload Payload
306 * @throws IOException when the snapshot fails to deserialize
307 * @throws DataValidationFailedException when the snapshot fails to apply
309 void applyRecoveryPayload(final @Nonnull Payload payload) throws IOException, DataValidationFailedException {
310 if (payload instanceof CommitTransactionPayload) {
311 final Entry<TransactionIdentifier, DataTreeCandidate> e =
312 ((CommitTransactionPayload) payload).getCandidate();
313 applyRecoveryCandidate(e.getValue());
314 allMetadataCommittedTransaction(e.getKey());
315 } else if (payload instanceof DataTreeCandidatePayload) {
316 applyRecoveryCandidate(((DataTreeCandidatePayload) payload).getCandidate());
318 LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
322 private void applyReplicatedCandidate(final Identifier identifier, final DataTreeCandidate foreign)
323 throws DataValidationFailedException {
324 LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
326 final DataTreeModification mod = dataTree.takeSnapshot().newModification();
327 DataTreeCandidates.applyToModification(mod, foreign);
330 LOG.trace("{}: Applying foreign modification {}", logContext, mod);
331 dataTree.validate(mod);
332 final DataTreeCandidate candidate = dataTree.prepare(mod);
333 dataTree.commit(candidate);
335 notifyListeners(candidate);
339 * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
340 * SchemaContexts match and does not perform any pruning.
342 * @param identifier Payload identifier as returned from RaftActor
343 * @param payload Payload
344 * @throws IOException when the snapshot fails to deserialize
345 * @throws DataValidationFailedException when the snapshot fails to apply
347 void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
348 DataValidationFailedException {
350 * 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
351 * if we are the leader and it has originated with us.
353 * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
354 * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
355 * acting in that capacity anymore.
357 * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
358 * pre-Boron state -- which limits the number of options here.
360 if (payload instanceof CommitTransactionPayload) {
361 if (identifier == null) {
362 final Entry<TransactionIdentifier, DataTreeCandidate> e =
363 ((CommitTransactionPayload) payload).getCandidate();
364 applyReplicatedCandidate(e.getKey(), e.getValue());
365 allMetadataCommittedTransaction(e.getKey());
367 Verify.verify(identifier instanceof TransactionIdentifier);
368 payloadReplicationComplete((TransactionIdentifier) identifier);
371 LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
375 private void payloadReplicationComplete(final TransactionIdentifier txId) {
376 final CommitEntry current = pendingFinishCommits.peek();
377 if (current == null) {
378 LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
382 if (!current.cohort.getIdentifier().equals(txId)) {
383 LOG.warn("{}: Head of queue is {}, ignoring consensus on transaction {}", logContext,
384 current.cohort.getIdentifier(), txId);
388 finishCommit(current.cohort);
391 private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
392 for (ShardDataTreeMetadata<?> m : metadata) {
393 m.onTransactionCommitted(txId);
397 ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier localHistoryIdentifier) {
398 ShardDataTreeTransactionChain chain = transactionChains.get(localHistoryIdentifier);
400 chain = new ShardDataTreeTransactionChain(localHistoryIdentifier, this);
401 transactionChains.put(localHistoryIdentifier, chain);
407 ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
408 if (txId.getHistoryId().getHistoryId() == 0) {
409 return new ReadOnlyShardDataTreeTransaction(txId, dataTree.takeSnapshot());
412 return ensureTransactionChain(txId.getHistoryId()).newReadOnlyTransaction(txId);
415 ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
416 if (txId.getHistoryId().getHistoryId() == 0) {
417 return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
421 return ensureTransactionChain(txId.getHistoryId()).newReadWriteTransaction(txId);
425 public void notifyListeners(final DataTreeCandidate candidate) {
426 treeChangeListenerPublisher.publishChanges(candidate, logContext);
427 dataChangeListenerPublisher.publishChanges(candidate, logContext);
430 void notifyOfInitialData(final DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
431 NormalizedNode<?, ?>>> listenerReg, final Optional<DataTreeCandidate> currentState) {
432 if (currentState.isPresent()) {
433 ShardDataChangeListenerPublisher localPublisher = dataChangeListenerPublisher.newInstance();
434 localPublisher.registerDataChangeListener(listenerReg.getPath(), listenerReg.getInstance(),
435 listenerReg.getScope());
436 localPublisher.publishChanges(currentState.get(), logContext);
440 void notifyOfInitialData(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
441 final Optional<DataTreeCandidate> currentState) {
442 if (currentState.isPresent()) {
443 ShardDataTreeChangeListenerPublisher localPublisher = treeChangeListenerPublisher.newInstance();
444 localPublisher.registerTreeChangeListener(path, listener);
445 localPublisher.publishChanges(currentState.get(), logContext);
449 void closeAllTransactionChains() {
450 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
454 transactionChains.clear();
457 void closeTransactionChain(final LocalHistoryIdentifier transactionChainId) {
458 final ShardDataTreeTransactionChain chain = transactionChains.remove(transactionChainId);
462 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, transactionChainId);
466 Entry<DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>,
467 Optional<DataTreeCandidate>> registerChangeListener(final YangInstanceIdentifier path,
468 final AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener,
469 final DataChangeScope scope) {
470 DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> reg =
471 dataChangeListenerPublisher.registerDataChangeListener(path, listener, scope);
473 return new SimpleEntry<>(reg, readCurrentData());
476 private Optional<DataTreeCandidate> readCurrentData() {
477 final Optional<NormalizedNode<?, ?>> currentState =
478 dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY);
479 return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
480 YangInstanceIdentifier.EMPTY, currentState.get())) : Optional.<DataTreeCandidate>absent();
483 public Entry<ListenerRegistration<DOMDataTreeChangeListener>, Optional<DataTreeCandidate>>
484 registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener) {
485 final ListenerRegistration<DOMDataTreeChangeListener> reg =
486 treeChangeListenerPublisher.registerTreeChangeListener(path, listener);
488 return new SimpleEntry<>(reg, readCurrentData());
492 return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
496 void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction) {
501 ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction) {
502 final DataTreeModification snapshot = transaction.getSnapshot();
505 return createReadyCohort(transaction.getIdentifier(), snapshot);
508 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
509 return dataTree.takeSnapshot().readNode(path);
512 DataTreeSnapshot takeSnapshot() {
513 return dataTree.takeSnapshot();
517 public DataTreeModification newModification() {
518 return dataTree.takeSnapshot().newModification();
522 * Commits a modification.
524 * @deprecated This method violates DataTree containment and will be removed.
528 public DataTreeCandidate commit(final DataTreeModification modification) throws DataValidationFailedException {
529 // Direct modification commit is a utility, which cannot be used while we have transactions in-flight
530 Preconditions.checkState(tip == dataTree, "Cannot modify data tree while transacgitons are pending");
532 modification.ready();
533 dataTree.validate(modification);
534 DataTreeCandidate candidate = dataTree.prepare(modification);
535 dataTree.commit(candidate);
539 public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
540 Collection<ShardDataTreeCohort> ret = new ArrayList<>(pendingTransactions.size() + pendingCommits.size()
541 + pendingFinishCommits.size());
543 for (CommitEntry entry: pendingFinishCommits) {
544 ret.add(entry.cohort);
547 for (CommitEntry entry: pendingCommits) {
548 ret.add(entry.cohort);
551 for (CommitEntry entry: pendingTransactions) {
552 ret.add(entry.cohort);
555 pendingFinishCommits.clear();
556 pendingCommits.clear();
557 pendingTransactions.clear();
562 @SuppressWarnings("checkstyle:IllegalCatch")
563 private void processNextPendingTransaction() {
564 while (!pendingTransactions.isEmpty()) {
565 final CommitEntry entry = pendingTransactions.peek();
566 final SimpleShardDataTreeCohort cohort = entry.cohort;
567 final DataTreeModification modification = cohort.getDataTreeModification();
569 if (cohort.isFailed()) {
570 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
571 pendingTransactions.remove();
575 if (cohort.getState() != State.CAN_COMMIT_PENDING) {
579 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
582 tip.validate(modification);
583 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
584 cohort.successfulCanCommit();
585 entry.lastAccess = shard.ticker().read();
587 } catch (ConflictingModificationAppliedException e) {
588 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
590 cause = new OptimisticLockFailedException("Optimistic lock failed.", e);
591 } catch (DataValidationFailedException e) {
592 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
595 // For debugging purposes, allow dumping of the modification. Coupled with the above
596 // precondition log, it should allow us to understand what went on.
597 LOG.debug("{}: Store Tx {}: modifications: {} tree: {}", cohort.getIdentifier(), modification,
599 cause = new TransactionCommitFailedException("Data did not pass validation.", e);
600 } catch (Exception e) {
601 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
605 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
606 pendingTransactions.poll().cohort.failedCanCommit(cause);
609 maybeRunOperationOnPendingTransactionsComplete();
612 private void processNextPendingCommit() {
613 while (!pendingCommits.isEmpty()) {
614 final CommitEntry entry = pendingCommits.peek();
615 final SimpleShardDataTreeCohort cohort = entry.cohort;
617 if (cohort.isFailed()) {
618 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
619 pendingCommits.remove();
623 if (cohort.getState() == State.COMMIT_PENDING) {
624 startCommit(cohort, cohort.getCandidate());
630 maybeRunOperationOnPendingTransactionsComplete();
633 private void processNextPending() {
634 processNextPendingCommit();
635 processNextPendingTransaction();
638 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
639 final SimpleShardDataTreeCohort current = pendingTransactions.peek().cohort;
640 if (!cohort.equals(current)) {
641 LOG.debug("{}: Transaction {} scheduled for canCommit step", logContext, cohort.getIdentifier());
645 processNextPendingTransaction();
648 private void failPreCommit(final Exception cause) {
649 shard.getShardMBean().incrementFailedTransactionsCount();
650 pendingTransactions.poll().cohort.failedPreCommit(cause);
651 processNextPendingTransaction();
654 @SuppressWarnings("checkstyle:IllegalCatch")
655 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
656 final CommitEntry entry = pendingTransactions.peek();
657 Preconditions.checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
659 final SimpleShardDataTreeCohort current = entry.cohort;
660 Verify.verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
661 final DataTreeCandidateTip candidate;
663 candidate = tip.prepare(cohort.getDataTreeModification());
664 } catch (Exception e) {
670 cohort.userPreCommit(candidate);
671 } catch (ExecutionException | TimeoutException e) {
676 // Set the tip of the data tree.
677 tip = Verify.verifyNotNull(candidate);
679 entry.lastAccess = shard.ticker().read();
681 pendingTransactions.remove();
682 pendingCommits.add(entry);
683 cohort.successfulPreCommit(candidate);
685 processNextPendingTransaction();
688 private void failCommit(final Exception cause) {
689 shard.getShardMBean().incrementFailedTransactionsCount();
690 pendingFinishCommits.poll().cohort.failedCommit(cause);
691 processNextPending();
694 @SuppressWarnings("checkstyle:IllegalCatch")
695 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
696 final TransactionIdentifier txId = cohort.getIdentifier();
697 final DataTreeCandidate candidate = cohort.getCandidate();
699 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
701 if (tip == candidate) {
702 // All pending candidates have been committed, reset the tip to the data tree.
707 dataTree.commit(candidate);
708 } catch (Exception e) {
709 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
714 shard.getShardMBean().incrementCommittedTransactionCount();
715 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
717 // FIXME: propagate journal index
718 pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO);
720 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
721 notifyListeners(candidate);
723 processNextPending();
726 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
727 final CommitEntry entry = pendingCommits.peek();
728 Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
730 final SimpleShardDataTreeCohort current = entry.cohort;
731 if (!cohort.equals(current)) {
732 LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
736 if (shard.canSkipPayload() || candidate.getRootNode().getModificationType() == ModificationType.UNMODIFIED) {
737 LOG.debug("{}: No replication required, proceeding to finish commit", logContext);
738 pendingCommits.remove();
739 pendingFinishCommits.add(entry);
740 finishCommit(cohort);
744 final TransactionIdentifier txId = cohort.getIdentifier();
745 final Payload payload;
747 payload = CommitTransactionPayload.create(txId, candidate);
749 // Once completed, we will continue via payloadReplicationComplete
750 entry.lastAccess = shard.ticker().read();
751 shard.persistPayload(txId, payload);
753 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
755 pendingCommits.remove();
756 pendingFinishCommits.add(entry);
757 } catch (IOException e) {
758 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
759 pendingCommits.poll().cohort.failedCommit(e);
763 processNextPending();
766 void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
767 cohortRegistry.process(sender, message);
771 ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId,
772 final DataTreeModification modification) {
773 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, modification, txId,
774 cohortRegistry.createCohort(schemaContext, txId, COMMIT_STEP_TIMEOUT));
775 pendingTransactions.add(new CommitEntry(cohort, shard.ticker().read()));
779 @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
780 void checkForExpiredTransactions(final long transactionCommitTimeoutMillis) {
781 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
782 final long now = shard.ticker().read();
784 final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
785 !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
786 final CommitEntry currentTx = currentQueue.peek();
787 if (currentTx != null && currentTx.lastAccess + timeout < now) {
788 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
789 currentTx.cohort.getIdentifier(), transactionCommitTimeoutMillis, currentTx.cohort.getState());
790 boolean processNext = true;
791 switch (currentTx.cohort.getState()) {
792 case CAN_COMMIT_PENDING:
793 currentQueue.remove().cohort.failedCanCommit(new TimeoutException());
795 case CAN_COMMIT_COMPLETE:
796 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
797 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
798 // in PRE_COMMIT_COMPLETE is changed.
799 currentQueue.remove().cohort.reportFailure(new TimeoutException());
801 case PRE_COMMIT_PENDING:
802 currentQueue.remove().cohort.failedPreCommit(new TimeoutException());
804 case PRE_COMMIT_COMPLETE:
805 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
806 // are ready we should commit the transaction, not abort it. Our current software stack does
807 // not allow us to do that consistently, because we persist at the time of commit, hence
808 // we can end up in a state where we have pre-committed a transaction, then a leader failover
809 // occurred ... the new leader does not see the pre-committed transaction and does not have
810 // a running timer. To fix this we really need two persistence events.
812 // The first one, done at pre-commit time will hold the transaction payload. When consensus
813 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
814 // apply the state in this event.
816 // The second one, done at commit (or abort) time holds only the transaction identifier and
817 // signals to followers that the state should (or should not) be applied.
819 // In order to make the pre-commit timer working across failovers, though, we need
820 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
821 // restart the timer.
822 currentQueue.remove().cohort.reportFailure(new TimeoutException());
825 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
826 currentTx.cohort.getIdentifier());
827 currentTx.lastAccess = now;
835 currentQueue.remove();
839 processNextPending();
844 boolean startAbort(final SimpleShardDataTreeCohort cohort) {
845 final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
846 pendingTransactions).iterator();
848 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
852 // First entry is special, as it may already be committing
853 final CommitEntry first = it.next();
854 if (cohort.equals(first.cohort)) {
855 if (cohort.getState() != State.COMMIT_PENDING) {
856 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
857 cohort.getIdentifier());
860 if (cohort.getCandidate() != null) {
861 rebaseTransactions(it, dataTree);
864 processNextPending();
868 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
872 TipProducingDataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
873 while (it.hasNext()) {
874 final CommitEntry e = it.next();
875 if (cohort.equals(e.cohort)) {
876 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
879 if (cohort.getCandidate() != null) {
880 rebaseTransactions(it, newTip);
885 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), dataTree);
889 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
893 @SuppressWarnings("checkstyle:IllegalCatch")
894 private void rebaseTransactions(Iterator<CommitEntry> iter, @Nonnull TipProducingDataTreeTip newTip) {
895 tip = Preconditions.checkNotNull(newTip);
896 while (iter.hasNext()) {
897 final SimpleShardDataTreeCohort cohort = iter.next().cohort;
898 if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
899 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
902 tip.validate(cohort.getDataTreeModification());
903 } catch (DataValidationFailedException | RuntimeException e) {
904 LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
905 cohort.reportFailure(e);
907 } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
908 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
911 tip.validate(cohort.getDataTreeModification());
912 DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
913 cohort.userPreCommit(candidate);
915 cohort.setNewCandidate(candidate);
917 } catch (ExecutionException | TimeoutException | RuntimeException | DataValidationFailedException e) {
918 LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
919 cohort.reportFailure(e);
925 void setRunOnPendingTransactionsComplete(final Runnable operation) {
926 runOnPendingTransactionsComplete = operation;
927 maybeRunOperationOnPendingTransactionsComplete();
930 private void maybeRunOperationOnPendingTransactionsComplete() {
931 if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
932 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
933 runOnPendingTransactionsComplete);
935 runOnPendingTransactionsComplete.run();
936 runOnPendingTransactionsComplete = null;