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.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Stopwatch;
16 import com.google.common.base.Ticker;
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.primitives.UnsignedLong;
22 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
24 import java.io.IOException;
25 import java.util.AbstractMap.SimpleEntry;
26 import java.util.ArrayDeque;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.HashMap;
30 import java.util.Iterator;
32 import java.util.Map.Entry;
33 import java.util.Queue;
34 import java.util.concurrent.ExecutionException;
35 import java.util.concurrent.TimeUnit;
36 import java.util.concurrent.TimeoutException;
37 import java.util.function.UnaryOperator;
38 import javax.annotation.Nonnull;
39 import javax.annotation.concurrent.NotThreadSafe;
40 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
41 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
42 import org.opendaylight.controller.cluster.datastore.DataTreeCohortActorRegistry.CohortRegistryCommand;
43 import org.opendaylight.controller.cluster.datastore.ShardDataTreeCohort.State;
44 import org.opendaylight.controller.cluster.datastore.persisted.CommitTransactionPayload;
45 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
46 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
47 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshotMetadata;
48 import org.opendaylight.controller.cluster.datastore.utils.DataTreeModificationOutput;
49 import org.opendaylight.controller.cluster.datastore.utils.PruningDataTreeModification;
50 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
51 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
52 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
53 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
54 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
55 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
56 import org.opendaylight.controller.md.sal.dom.store.impl.DataChangeListenerRegistration;
57 import org.opendaylight.yangtools.concepts.Identifier;
58 import org.opendaylight.yangtools.concepts.ListenerRegistration;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
60 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
62 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
63 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
64 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
65 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
66 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
67 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeTip;
68 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
69 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
70 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
71 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTreeTip;
72 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
73 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
74 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
77 import scala.concurrent.duration.Duration;
80 * Internal shard state, similar to a DOMStore, but optimized for use in the actor system,
81 * e.g. it does not expose public interfaces and assumes it is only ever called from a
85 * This class is not part of the API contract and is subject to change at any time.
88 public class ShardDataTree extends ShardDataTreeTransactionParent {
89 private static final class CommitEntry {
90 final SimpleShardDataTreeCohort cohort;
93 CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
94 this.cohort = Preconditions.checkNotNull(cohort);
99 private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(Duration.create(5, TimeUnit.SECONDS));
100 private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
102 private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
103 private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
104 private final Queue<CommitEntry> pendingTransactions = new ArrayDeque<>();
105 private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
106 private final ShardDataChangeListenerPublisher dataChangeListenerPublisher;
107 private final Collection<ShardDataTreeMetadata<?>> metadata;
108 private final TipProducingDataTree dataTree;
109 private final String logContext;
110 private final Shard shard;
111 private Runnable runOnPendingTransactionsComplete;
114 * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
115 * {@link TipProducingDataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
116 * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
117 * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
119 private TipProducingDataTreeTip tip;
121 private SchemaContext schemaContext;
123 public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TipProducingDataTree dataTree,
124 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
125 final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext,
126 final ShardDataTreeMetadata<?>... metadata) {
127 this.dataTree = Preconditions.checkNotNull(dataTree);
128 updateSchemaContext(schemaContext);
130 this.shard = Preconditions.checkNotNull(shard);
131 this.treeChangeListenerPublisher = Preconditions.checkNotNull(treeChangeListenerPublisher);
132 this.dataChangeListenerPublisher = Preconditions.checkNotNull(dataChangeListenerPublisher);
133 this.logContext = Preconditions.checkNotNull(logContext);
134 this.metadata = ImmutableList.copyOf(metadata);
138 public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType,
139 final YangInstanceIdentifier root,
140 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
141 final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext) {
142 this(shard, schemaContext, InMemoryDataTreeFactory.getInstance().create(treeType, root),
143 treeChangeListenerPublisher, dataChangeListenerPublisher, logContext);
147 public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType) {
148 this(shard, schemaContext, treeType, YangInstanceIdentifier.EMPTY,
149 new DefaultShardDataTreeChangeListenerPublisher(),
150 new DefaultShardDataChangeListenerPublisher(), "");
153 final String logContext() {
157 final Ticker ticker() {
158 return shard.ticker();
161 public TipProducingDataTree getDataTree() {
165 SchemaContext getSchemaContext() {
166 return schemaContext;
169 void updateSchemaContext(final SchemaContext newSchemaContext) {
170 dataTree.setSchemaContext(newSchemaContext);
171 this.schemaContext = Preconditions.checkNotNull(newSchemaContext);
175 * Take a snapshot of current state for later recovery.
177 * @return A state snapshot
179 @Nonnull ShardDataTreeSnapshot takeStateSnapshot() {
180 final NormalizedNode<?, ?> rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY).get();
181 final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
182 ImmutableMap.builder();
184 for (ShardDataTreeMetadata<?> m : metadata) {
185 final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
187 metaBuilder.put(meta.getType(), meta);
191 return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
194 private void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot,
195 final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
196 final Stopwatch elapsed = Stopwatch.createStarted();
198 if (!pendingTransactions.isEmpty()) {
199 LOG.warn("{}: applying state snapshot with pending transactions", logContext);
202 final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
203 if (snapshot instanceof MetadataShardDataTreeSnapshot) {
204 snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
206 snapshotMeta = ImmutableMap.of();
209 for (ShardDataTreeMetadata<?> m : metadata) {
210 final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
218 final DataTreeModification mod = wrapper.apply(dataTree.takeSnapshot().newModification());
219 // delete everything first
220 mod.delete(YangInstanceIdentifier.EMPTY);
222 final java.util.Optional<NormalizedNode<?, ?>> maybeNode = snapshot.getRootNode();
223 if (maybeNode.isPresent()) {
224 // Add everything from the remote node back
225 mod.write(YangInstanceIdentifier.EMPTY, maybeNode.get());
229 final DataTreeModification unwrapped = unwrap(mod);
230 dataTree.validate(unwrapped);
231 DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
232 dataTree.commit(candidate);
233 notifyListeners(candidate);
235 LOG.debug("{}: state snapshot applied in %s", logContext, elapsed);
239 * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
240 * does not perform any pruning.
242 * @param snapshot Snapshot that needs to be applied
243 * @throws DataValidationFailedException when the snapshot fails to apply
245 void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
246 applySnapshot(snapshot, UnaryOperator.identity());
249 private PruningDataTreeModification wrapWithPruning(final DataTreeModification delegate) {
250 return new PruningDataTreeModification(delegate, dataTree, schemaContext);
253 private static DataTreeModification unwrap(final DataTreeModification modification) {
254 if (modification instanceof PruningDataTreeModification) {
255 return ((PruningDataTreeModification)modification).delegate();
261 * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
262 * pruning in an attempt to adjust the state to our current SchemaContext.
264 * @param snapshot Snapshot that needs to be applied
265 * @throws DataValidationFailedException when the snapshot fails to apply
267 void applyRecoverySnapshot(final @Nonnull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
268 applySnapshot(snapshot, this::wrapWithPruning);
271 @SuppressWarnings("checkstyle:IllegalCatch")
272 private void applyRecoveryCandidate(final DataTreeCandidate candidate) throws DataValidationFailedException {
273 final PruningDataTreeModification mod = wrapWithPruning(dataTree.takeSnapshot().newModification());
274 DataTreeCandidates.applyToModification(mod, candidate);
277 final DataTreeModification unwrapped = mod.delegate();
278 LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
281 dataTree.validate(unwrapped);
282 dataTree.commit(dataTree.prepare(unwrapped));
283 } catch (Exception e) {
284 File file = new File(System.getProperty("karaf.data", "."),
285 "failed-recovery-payload-" + logContext + ".out");
286 DataTreeModificationOutput.toFile(file, unwrapped);
287 throw new IllegalStateException(String.format(
288 "%s: Failed to apply recovery payload. Modification data was written to file %s",
289 logContext, file), e);
294 * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
295 * pruning in an attempt to adjust the state to our current SchemaContext.
297 * @param payload Payload
298 * @throws IOException when the snapshot fails to deserialize
299 * @throws DataValidationFailedException when the snapshot fails to apply
301 void applyRecoveryPayload(final @Nonnull Payload payload) throws IOException, DataValidationFailedException {
302 if (payload instanceof CommitTransactionPayload) {
303 final Entry<TransactionIdentifier, DataTreeCandidate> e =
304 ((CommitTransactionPayload) payload).getCandidate();
305 applyRecoveryCandidate(e.getValue());
306 allMetadataCommittedTransaction(e.getKey());
307 } else if (payload instanceof DataTreeCandidatePayload) {
308 applyRecoveryCandidate(((DataTreeCandidatePayload) payload).getCandidate());
310 LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
314 private void applyReplicatedCandidate(final Identifier identifier, final DataTreeCandidate foreign)
315 throws DataValidationFailedException {
316 LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
318 final DataTreeModification mod = dataTree.takeSnapshot().newModification();
319 DataTreeCandidates.applyToModification(mod, foreign);
322 LOG.trace("{}: Applying foreign modification {}", logContext, mod);
323 dataTree.validate(mod);
324 final DataTreeCandidate candidate = dataTree.prepare(mod);
325 dataTree.commit(candidate);
327 notifyListeners(candidate);
331 * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
332 * SchemaContexts match and does not perform any pruning.
334 * @param identifier Payload identifier as returned from RaftActor
335 * @param payload Payload
336 * @throws IOException when the snapshot fails to deserialize
337 * @throws DataValidationFailedException when the snapshot fails to apply
339 void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
340 DataValidationFailedException {
342 * 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
343 * if we are the leader and it has originated with us.
345 * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
346 * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
347 * acting in that capacity anymore.
349 * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
350 * pre-Boron state -- which limits the number of options here.
352 if (payload instanceof CommitTransactionPayload) {
353 if (identifier == null) {
354 final Entry<TransactionIdentifier, DataTreeCandidate> e =
355 ((CommitTransactionPayload) payload).getCandidate();
356 applyReplicatedCandidate(e.getKey(), e.getValue());
357 allMetadataCommittedTransaction(e.getKey());
359 Verify.verify(identifier instanceof TransactionIdentifier);
360 payloadReplicationComplete((TransactionIdentifier) identifier);
363 LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
367 private void payloadReplicationComplete(final TransactionIdentifier txId) {
368 final CommitEntry current = pendingTransactions.peek();
369 if (current == null) {
370 LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
374 if (!current.cohort.getIdentifier().equals(txId)) {
375 LOG.warn("{}: Head of queue is {}, ignoring consensus on transaction {}", logContext,
376 current.cohort.getIdentifier(), txId);
380 finishCommit(current.cohort);
383 private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
384 for (ShardDataTreeMetadata<?> m : metadata) {
385 m.onTransactionCommitted(txId);
389 ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier localHistoryIdentifier) {
390 ShardDataTreeTransactionChain chain = transactionChains.get(localHistoryIdentifier);
392 chain = new ShardDataTreeTransactionChain(localHistoryIdentifier, this);
393 transactionChains.put(localHistoryIdentifier, chain);
399 ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
400 if (txId.getHistoryId().getHistoryId() == 0) {
401 return new ReadOnlyShardDataTreeTransaction(txId, dataTree.takeSnapshot());
404 return ensureTransactionChain(txId.getHistoryId()).newReadOnlyTransaction(txId);
407 ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
408 if (txId.getHistoryId().getHistoryId() == 0) {
409 return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
413 return ensureTransactionChain(txId.getHistoryId()).newReadWriteTransaction(txId);
417 public void notifyListeners(final DataTreeCandidate candidate) {
418 treeChangeListenerPublisher.publishChanges(candidate, logContext);
419 dataChangeListenerPublisher.publishChanges(candidate, logContext);
422 void notifyOfInitialData(final DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
423 NormalizedNode<?, ?>>> listenerReg, final Optional<DataTreeCandidate> currentState) {
424 if (currentState.isPresent()) {
425 ShardDataChangeListenerPublisher localPublisher = dataChangeListenerPublisher.newInstance();
426 localPublisher.registerDataChangeListener(listenerReg.getPath(), listenerReg.getInstance(),
427 listenerReg.getScope());
428 localPublisher.publishChanges(currentState.get(), logContext);
432 void notifyOfInitialData(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
433 final Optional<DataTreeCandidate> currentState) {
434 if (currentState.isPresent()) {
435 ShardDataTreeChangeListenerPublisher localPublisher = treeChangeListenerPublisher.newInstance();
436 localPublisher.registerTreeChangeListener(path, listener);
437 localPublisher.publishChanges(currentState.get(), logContext);
441 void closeAllTransactionChains() {
442 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
446 transactionChains.clear();
449 void closeTransactionChain(final LocalHistoryIdentifier transactionChainId) {
450 final ShardDataTreeTransactionChain chain = transactionChains.remove(transactionChainId);
454 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, transactionChainId);
458 Entry<DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>,
459 Optional<DataTreeCandidate>> registerChangeListener(final YangInstanceIdentifier path,
460 final AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener,
461 final DataChangeScope scope) {
462 DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> reg =
463 dataChangeListenerPublisher.registerDataChangeListener(path, listener, scope);
465 return new SimpleEntry<>(reg, readCurrentData());
468 private Optional<DataTreeCandidate> readCurrentData() {
469 final Optional<NormalizedNode<?, ?>> currentState =
470 dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY);
471 return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
472 YangInstanceIdentifier.EMPTY, currentState.get())) : Optional.<DataTreeCandidate>absent();
475 public Entry<ListenerRegistration<DOMDataTreeChangeListener>, Optional<DataTreeCandidate>>
476 registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener) {
477 final ListenerRegistration<DOMDataTreeChangeListener> reg =
478 treeChangeListenerPublisher.registerTreeChangeListener(path, listener);
480 return new SimpleEntry<>(reg, readCurrentData());
484 return pendingTransactions.size();
488 void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction) {
493 ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction) {
494 final DataTreeModification snapshot = transaction.getSnapshot();
497 return createReadyCohort(transaction.getIdentifier(), snapshot);
500 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
501 return dataTree.takeSnapshot().readNode(path);
504 DataTreeSnapshot takeSnapshot() {
505 return dataTree.takeSnapshot();
509 public DataTreeModification newModification() {
510 return dataTree.takeSnapshot().newModification();
514 * Commits a modification.
516 * @deprecated This method violates DataTree containment and will be removed.
520 public DataTreeCandidate commit(final DataTreeModification modification) throws DataValidationFailedException {
521 // Direct modification commit is a utility, which cannot be used while we have transactions in-flight
522 Preconditions.checkState(tip == dataTree, "Cannot modify data tree while transacgitons are pending");
524 modification.ready();
525 dataTree.validate(modification);
526 DataTreeCandidate candidate = dataTree.prepare(modification);
527 dataTree.commit(candidate);
531 public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
532 Collection<ShardDataTreeCohort> ret = new ArrayList<>(pendingTransactions.size());
533 for (CommitEntry entry: pendingTransactions) {
534 ret.add(entry.cohort);
537 pendingTransactions.clear();
542 @SuppressWarnings("checkstyle:IllegalCatch")
543 private void processNextTransaction() {
544 while (!pendingTransactions.isEmpty()) {
545 final CommitEntry entry = pendingTransactions.peek();
546 final SimpleShardDataTreeCohort cohort = entry.cohort;
547 final DataTreeModification modification = cohort.getDataTreeModification();
549 if (cohort.getState() != State.CAN_COMMIT_PENDING) {
553 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
556 tip.validate(modification);
557 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
558 cohort.successfulCanCommit();
559 entry.lastAccess = shard.ticker().read();
561 } catch (ConflictingModificationAppliedException e) {
562 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
564 cause = new OptimisticLockFailedException("Optimistic lock failed.", e);
565 } catch (DataValidationFailedException e) {
566 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
569 // For debugging purposes, allow dumping of the modification. Coupled with the above
570 // precondition log, it should allow us to understand what went on.
571 LOG.debug("{}: Store Tx {}: modifications: {} tree: {}", cohort.getIdentifier(), modification,
573 cause = new TransactionCommitFailedException("Data did not pass validation.", e);
574 } catch (Exception e) {
575 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
579 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
580 pendingTransactions.poll().cohort.failedCanCommit(cause);
583 maybeRunOperationOnPendingTransactionsComplete();
586 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
587 final SimpleShardDataTreeCohort current = pendingTransactions.peek().cohort;
588 if (!cohort.equals(current)) {
589 LOG.debug("{}: Transaction {} scheduled for canCommit step", logContext, cohort.getIdentifier());
593 processNextTransaction();
596 private void failPreCommit(final Exception cause) {
597 shard.getShardMBean().incrementFailedTransactionsCount();
598 pendingTransactions.poll().cohort.failedPreCommit(cause);
599 processNextTransaction();
602 @SuppressWarnings("checkstyle:IllegalCatch")
603 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
604 final CommitEntry entry = pendingTransactions.peek();
605 Preconditions.checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
607 final SimpleShardDataTreeCohort current = entry.cohort;
608 Verify.verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
609 final DataTreeCandidateTip candidate;
611 candidate = tip.prepare(cohort.getDataTreeModification());
612 } catch (Exception e) {
618 cohort.userPreCommit(candidate);
619 } catch (ExecutionException | TimeoutException e) {
624 // Set the tip of the data tree.
625 tip = Verify.verifyNotNull(candidate);
627 entry.lastAccess = shard.ticker().read();
628 cohort.successfulPreCommit(candidate);
631 private void failCommit(final Exception cause) {
632 shard.getShardMBean().incrementFailedTransactionsCount();
633 pendingTransactions.poll().cohort.failedCommit(cause);
634 processNextTransaction();
637 @SuppressWarnings("checkstyle:IllegalCatch")
638 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
639 final TransactionIdentifier txId = cohort.getIdentifier();
640 final DataTreeCandidate candidate = cohort.getCandidate();
642 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
645 dataTree.commit(candidate);
646 } catch (Exception e) {
647 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
652 // All pending candidates have been committed, reset the tip to the data tree
653 if (tip == candidate) {
657 shard.getShardMBean().incrementCommittedTransactionCount();
658 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
660 // FIXME: propagate journal index
661 pendingTransactions.poll().cohort.successfulCommit(UnsignedLong.ZERO);
663 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
664 notifyListeners(candidate);
666 processNextTransaction();
669 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
670 final CommitEntry entry = pendingTransactions.peek();
671 Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
673 final SimpleShardDataTreeCohort current = entry.cohort;
674 Verify.verify(cohort.equals(current), "Attempted to commit %s while %s is pending", cohort, current);
676 if (shard.canSkipPayload() || candidate.getRootNode().getModificationType() == ModificationType.UNMODIFIED) {
677 LOG.debug("{}: No replication required, proceeding to finish commit", logContext);
678 finishCommit(cohort);
682 final TransactionIdentifier txId = cohort.getIdentifier();
683 final Payload payload;
685 payload = CommitTransactionPayload.create(txId, candidate);
686 } catch (IOException e) {
687 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
688 pendingTransactions.poll().cohort.failedCommit(e);
692 // Once completed, we will continue via payloadReplicationComplete
693 entry.lastAccess = shard.ticker().read();
694 shard.persistPayload(txId, payload);
695 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
698 void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
699 cohortRegistry.process(sender, message);
703 ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId,
704 final DataTreeModification modification) {
705 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, modification, txId,
706 cohortRegistry.createCohort(schemaContext, txId, COMMIT_STEP_TIMEOUT));
707 pendingTransactions.add(new CommitEntry(cohort, shard.ticker().read()));
711 @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
712 void checkForExpiredTransactions(final long transactionCommitTimeoutMillis) {
713 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
714 final long now = shard.ticker().read();
715 final CommitEntry currentTx = pendingTransactions.peek();
716 if (currentTx != null && currentTx.lastAccess + timeout < now) {
717 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
718 currentTx.cohort.getIdentifier(), transactionCommitTimeoutMillis, currentTx.cohort.getState());
719 boolean processNext = true;
720 switch (currentTx.cohort.getState()) {
721 case CAN_COMMIT_PENDING:
722 pendingTransactions.remove().cohort.failedCanCommit(new TimeoutException());
724 case CAN_COMMIT_COMPLETE:
725 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
726 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
727 // in PRE_COMMIT_COMPLETE is changed.
728 pendingTransactions.remove().cohort.reportFailure(new TimeoutException());
730 case PRE_COMMIT_PENDING:
731 pendingTransactions.remove().cohort.failedPreCommit(new TimeoutException());
733 case PRE_COMMIT_COMPLETE:
734 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
735 // are ready we should commit the transaction, not abort it. Our current software stack does
736 // not allow us to do that consistently, because we persist at the time of commit, hence
737 // we can end up in a state where we have pre-committed a transaction, then a leader failover
738 // occurred ... the new leader does not see the pre-committed transaction and does not have
739 // a running timer. To fix this we really need two persistence events.
741 // The first one, done at pre-commit time will hold the transaction payload. When consensus
742 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
743 // apply the state in this event.
745 // The second one, done at commit (or abort) time holds only the transaction identifier and
746 // signals to followers that the state should (or should not) be applied.
748 // In order to make the pre-commit timer working across failovers, though, we need
749 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
750 // restart the timer.
751 pendingTransactions.remove().cohort.reportFailure(new TimeoutException());
754 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
755 currentTx.cohort.getIdentifier());
756 currentTx.lastAccess = now;
764 pendingTransactions.remove();
768 processNextTransaction();
773 boolean startAbort(final SimpleShardDataTreeCohort cohort) {
774 final Iterator<CommitEntry> it = pendingTransactions.iterator();
776 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
780 // First entry is special, as it may already be committing
781 final CommitEntry first = it.next();
782 if (cohort.equals(first.cohort)) {
783 if (cohort.getState() != State.COMMIT_PENDING) {
784 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
785 cohort.getIdentifier());
788 rebasePreCommittedTransactions(it, dataTree);
789 processNextTransaction();
793 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
797 TipProducingDataTreeTip newTip = dataTree;
798 while (it.hasNext()) {
799 final CommitEntry e = it.next();
800 if (cohort.equals(e.cohort)) {
801 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
803 rebasePreCommittedTransactions(it, newTip);
806 newTip = cohort.getCandidate();
810 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
814 @SuppressWarnings("checkstyle:IllegalCatch")
815 private void rebasePreCommittedTransactions(Iterator<CommitEntry> iter, TipProducingDataTreeTip newTip) {
817 while (iter.hasNext()) {
818 final SimpleShardDataTreeCohort cohort = iter.next().cohort;
819 if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
820 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
823 tip.validate(cohort.getDataTreeModification());
824 } catch (DataValidationFailedException | RuntimeException e) {
825 LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
826 cohort.reportFailure(e);
828 } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
829 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
832 tip.validate(cohort.getDataTreeModification());
833 DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
834 cohort.userPreCommit(candidate);
836 cohort.setNewCandidate(candidate);
838 } catch (ExecutionException | TimeoutException | RuntimeException | DataValidationFailedException e) {
839 LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
840 cohort.reportFailure(e);
846 void setRunOnPendingTransactionsComplete(final Runnable operation) {
847 runOnPendingTransactionsComplete = operation;
848 maybeRunOperationOnPendingTransactionsComplete();
851 private void maybeRunOperationOnPendingTransactionsComplete() {
852 if (runOnPendingTransactionsComplete != null && pendingTransactions.isEmpty()) {
853 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
854 runOnPendingTransactionsComplete);
856 runOnPendingTransactionsComplete.run();
857 runOnPendingTransactionsComplete = null;