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 ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
140 final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext) {
141 this(shard, schemaContext, InMemoryDataTreeFactory.getInstance().create(treeType),
142 treeChangeListenerPublisher, dataChangeListenerPublisher, logContext);
146 public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType) {
147 this(shard, schemaContext, treeType, new DefaultShardDataTreeChangeListenerPublisher(),
148 new DefaultShardDataChangeListenerPublisher(), "");
151 final String logContext() {
155 final Ticker ticker() {
156 return shard.ticker();
159 public TipProducingDataTree getDataTree() {
163 SchemaContext getSchemaContext() {
164 return schemaContext;
167 void updateSchemaContext(final SchemaContext newSchemaContext) {
168 dataTree.setSchemaContext(newSchemaContext);
169 this.schemaContext = Preconditions.checkNotNull(newSchemaContext);
173 * Take a snapshot of current state for later recovery.
175 * @return A state snapshot
177 @Nonnull ShardDataTreeSnapshot takeStateSnapshot() {
178 final NormalizedNode<?, ?> rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY).get();
179 final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
180 ImmutableMap.builder();
182 for (ShardDataTreeMetadata<?> m : metadata) {
183 final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
185 metaBuilder.put(meta.getType(), meta);
189 return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
192 private void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot,
193 final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
194 final Stopwatch elapsed = Stopwatch.createStarted();
196 if (!pendingTransactions.isEmpty()) {
197 LOG.warn("{}: applying state snapshot with pending transactions", logContext);
200 final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
201 if (snapshot instanceof MetadataShardDataTreeSnapshot) {
202 snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
204 snapshotMeta = ImmutableMap.of();
207 for (ShardDataTreeMetadata<?> m : metadata) {
208 final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
216 final DataTreeModification mod = wrapper.apply(dataTree.takeSnapshot().newModification());
217 // delete everything first
218 mod.delete(YangInstanceIdentifier.EMPTY);
220 final java.util.Optional<NormalizedNode<?, ?>> maybeNode = snapshot.getRootNode();
221 if (maybeNode.isPresent()) {
222 // Add everything from the remote node back
223 mod.write(YangInstanceIdentifier.EMPTY, maybeNode.get());
227 final DataTreeModification unwrapped = unwrap(mod);
228 dataTree.validate(unwrapped);
229 DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
230 dataTree.commit(candidate);
231 notifyListeners(candidate);
233 LOG.debug("{}: state snapshot applied in %s", logContext, elapsed);
237 * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
238 * does not perform any pruning.
240 * @param snapshot Snapshot that needs to be applied
241 * @throws DataValidationFailedException when the snapshot fails to apply
243 void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
244 applySnapshot(snapshot, UnaryOperator.identity());
247 private PruningDataTreeModification wrapWithPruning(final DataTreeModification delegate) {
248 return new PruningDataTreeModification(delegate, dataTree, schemaContext);
251 private static DataTreeModification unwrap(final DataTreeModification modification) {
252 if (modification instanceof PruningDataTreeModification) {
253 return ((PruningDataTreeModification)modification).delegate();
259 * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
260 * pruning in an attempt to adjust the state to our current SchemaContext.
262 * @param snapshot Snapshot that needs to be applied
263 * @throws DataValidationFailedException when the snapshot fails to apply
265 void applyRecoverySnapshot(final @Nonnull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
266 applySnapshot(snapshot, this::wrapWithPruning);
269 @SuppressWarnings("checkstyle:IllegalCatch")
270 private void applyRecoveryCandidate(final DataTreeCandidate candidate) throws DataValidationFailedException {
271 final PruningDataTreeModification mod = wrapWithPruning(dataTree.takeSnapshot().newModification());
272 DataTreeCandidates.applyToModification(mod, candidate);
275 final DataTreeModification unwrapped = mod.delegate();
276 LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
279 dataTree.validate(unwrapped);
280 dataTree.commit(dataTree.prepare(unwrapped));
281 } catch (Exception e) {
282 File file = new File(System.getProperty("karaf.data", "."),
283 "failed-recovery-payload-" + logContext + ".out");
284 DataTreeModificationOutput.toFile(file, unwrapped);
285 throw new IllegalStateException(String.format(
286 "%s: Failed to apply recovery payload. Modification data was written to file %s",
287 logContext, file), e);
292 * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
293 * pruning in an attempt to adjust the state to our current SchemaContext.
295 * @param payload Payload
296 * @throws IOException when the snapshot fails to deserialize
297 * @throws DataValidationFailedException when the snapshot fails to apply
299 void applyRecoveryPayload(final @Nonnull Payload payload) throws IOException, DataValidationFailedException {
300 if (payload instanceof CommitTransactionPayload) {
301 final Entry<TransactionIdentifier, DataTreeCandidate> e =
302 ((CommitTransactionPayload) payload).getCandidate();
303 applyRecoveryCandidate(e.getValue());
304 allMetadataCommittedTransaction(e.getKey());
305 } else if (payload instanceof DataTreeCandidatePayload) {
306 applyRecoveryCandidate(((DataTreeCandidatePayload) payload).getCandidate());
308 LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
312 private void applyReplicatedCandidate(final Identifier identifier, final DataTreeCandidate foreign)
313 throws DataValidationFailedException {
314 LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
316 final DataTreeModification mod = dataTree.takeSnapshot().newModification();
317 DataTreeCandidates.applyToModification(mod, foreign);
320 LOG.trace("{}: Applying foreign modification {}", logContext, mod);
321 dataTree.validate(mod);
322 final DataTreeCandidate candidate = dataTree.prepare(mod);
323 dataTree.commit(candidate);
325 notifyListeners(candidate);
329 * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
330 * SchemaContexts match and does not perform any pruning.
332 * @param identifier Payload identifier as returned from RaftActor
333 * @param payload Payload
334 * @throws IOException when the snapshot fails to deserialize
335 * @throws DataValidationFailedException when the snapshot fails to apply
337 void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
338 DataValidationFailedException {
340 * 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
341 * if we are the leader and it has originated with us.
343 * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
344 * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
345 * acting in that capacity anymore.
347 * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
348 * pre-Boron state -- which limits the number of options here.
350 if (payload instanceof CommitTransactionPayload) {
351 if (identifier == null) {
352 final Entry<TransactionIdentifier, DataTreeCandidate> e =
353 ((CommitTransactionPayload) payload).getCandidate();
354 applyReplicatedCandidate(e.getKey(), e.getValue());
355 allMetadataCommittedTransaction(e.getKey());
357 Verify.verify(identifier instanceof TransactionIdentifier);
358 payloadReplicationComplete((TransactionIdentifier) identifier);
361 LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
365 private void payloadReplicationComplete(final TransactionIdentifier txId) {
366 final CommitEntry current = pendingTransactions.peek();
367 if (current == null) {
368 LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
372 if (!current.cohort.getIdentifier().equals(txId)) {
373 LOG.warn("{}: Head of queue is {}, ignoring consensus on transaction {}", logContext,
374 current.cohort.getIdentifier(), txId);
378 finishCommit(current.cohort);
381 private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
382 for (ShardDataTreeMetadata<?> m : metadata) {
383 m.onTransactionCommitted(txId);
387 ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier localHistoryIdentifier) {
388 ShardDataTreeTransactionChain chain = transactionChains.get(localHistoryIdentifier);
390 chain = new ShardDataTreeTransactionChain(localHistoryIdentifier, this);
391 transactionChains.put(localHistoryIdentifier, chain);
397 ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
398 if (txId.getHistoryId().getHistoryId() == 0) {
399 return new ReadOnlyShardDataTreeTransaction(txId, dataTree.takeSnapshot());
402 return ensureTransactionChain(txId.getHistoryId()).newReadOnlyTransaction(txId);
405 ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
406 if (txId.getHistoryId().getHistoryId() == 0) {
407 return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
411 return ensureTransactionChain(txId.getHistoryId()).newReadWriteTransaction(txId);
415 public void notifyListeners(final DataTreeCandidate candidate) {
416 treeChangeListenerPublisher.publishChanges(candidate, logContext);
417 dataChangeListenerPublisher.publishChanges(candidate, logContext);
420 void notifyOfInitialData(final DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
421 NormalizedNode<?, ?>>> listenerReg, final Optional<DataTreeCandidate> currentState) {
422 if (currentState.isPresent()) {
423 ShardDataChangeListenerPublisher localPublisher = dataChangeListenerPublisher.newInstance();
424 localPublisher.registerDataChangeListener(listenerReg.getPath(), listenerReg.getInstance(),
425 listenerReg.getScope());
426 localPublisher.publishChanges(currentState.get(), logContext);
430 void notifyOfInitialData(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
431 final Optional<DataTreeCandidate> currentState) {
432 if (currentState.isPresent()) {
433 ShardDataTreeChangeListenerPublisher localPublisher = treeChangeListenerPublisher.newInstance();
434 localPublisher.registerTreeChangeListener(path, listener);
435 localPublisher.publishChanges(currentState.get(), logContext);
439 void closeAllTransactionChains() {
440 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
444 transactionChains.clear();
447 void closeTransactionChain(final LocalHistoryIdentifier transactionChainId) {
448 final ShardDataTreeTransactionChain chain = transactionChains.remove(transactionChainId);
452 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, transactionChainId);
456 Entry<DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>,
457 Optional<DataTreeCandidate>> registerChangeListener(final YangInstanceIdentifier path,
458 final AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener,
459 final DataChangeScope scope) {
460 DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> reg =
461 dataChangeListenerPublisher.registerDataChangeListener(path, listener, scope);
463 return new SimpleEntry<>(reg, readCurrentData());
466 private Optional<DataTreeCandidate> readCurrentData() {
467 final Optional<NormalizedNode<?, ?>> currentState =
468 dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY);
469 return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
470 YangInstanceIdentifier.EMPTY, currentState.get())) : Optional.<DataTreeCandidate>absent();
473 public Entry<ListenerRegistration<DOMDataTreeChangeListener>, Optional<DataTreeCandidate>>
474 registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener) {
475 final ListenerRegistration<DOMDataTreeChangeListener> reg =
476 treeChangeListenerPublisher.registerTreeChangeListener(path, listener);
478 return new SimpleEntry<>(reg, readCurrentData());
482 return pendingTransactions.size();
486 void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction) {
491 ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction) {
492 final DataTreeModification snapshot = transaction.getSnapshot();
495 return createReadyCohort(transaction.getIdentifier(), snapshot);
498 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
499 return dataTree.takeSnapshot().readNode(path);
502 DataTreeSnapshot takeSnapshot() {
503 return dataTree.takeSnapshot();
507 public DataTreeModification newModification() {
508 return dataTree.takeSnapshot().newModification();
512 * Commits a modification.
514 * @deprecated This method violates DataTree containment and will be removed.
518 public DataTreeCandidate commit(final DataTreeModification modification) throws DataValidationFailedException {
519 // Direct modification commit is a utility, which cannot be used while we have transactions in-flight
520 Preconditions.checkState(tip == dataTree, "Cannot modify data tree while transacgitons are pending");
522 modification.ready();
523 dataTree.validate(modification);
524 DataTreeCandidate candidate = dataTree.prepare(modification);
525 dataTree.commit(candidate);
529 public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
530 Collection<ShardDataTreeCohort> ret = new ArrayList<>(pendingTransactions.size());
531 for (CommitEntry entry: pendingTransactions) {
532 ret.add(entry.cohort);
535 pendingTransactions.clear();
540 @SuppressWarnings("checkstyle:IllegalCatch")
541 private void processNextTransaction() {
542 while (!pendingTransactions.isEmpty()) {
543 final CommitEntry entry = pendingTransactions.peek();
544 final SimpleShardDataTreeCohort cohort = entry.cohort;
545 final DataTreeModification modification = cohort.getDataTreeModification();
547 if (cohort.getState() != State.CAN_COMMIT_PENDING) {
551 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
554 tip.validate(modification);
555 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
556 cohort.successfulCanCommit();
557 entry.lastAccess = shard.ticker().read();
559 } catch (ConflictingModificationAppliedException e) {
560 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
562 cause = new OptimisticLockFailedException("Optimistic lock failed.", e);
563 } catch (DataValidationFailedException e) {
564 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
567 // For debugging purposes, allow dumping of the modification. Coupled with the above
568 // precondition log, it should allow us to understand what went on.
569 LOG.debug("{}: Store Tx {}: modifications: {} tree: {}", cohort.getIdentifier(), modification,
571 cause = new TransactionCommitFailedException("Data did not pass validation.", e);
572 } catch (Exception e) {
573 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
577 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
578 pendingTransactions.poll().cohort.failedCanCommit(cause);
581 maybeRunOperationOnPendingTransactionsComplete();
584 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
585 final SimpleShardDataTreeCohort current = pendingTransactions.peek().cohort;
586 if (!cohort.equals(current)) {
587 LOG.debug("{}: Transaction {} scheduled for canCommit step", logContext, cohort.getIdentifier());
591 processNextTransaction();
594 private void failPreCommit(final Exception cause) {
595 shard.getShardMBean().incrementFailedTransactionsCount();
596 pendingTransactions.poll().cohort.failedPreCommit(cause);
597 processNextTransaction();
600 @SuppressWarnings("checkstyle:IllegalCatch")
601 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
602 final CommitEntry entry = pendingTransactions.peek();
603 Preconditions.checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
605 final SimpleShardDataTreeCohort current = entry.cohort;
606 Verify.verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
607 final DataTreeCandidateTip candidate;
609 candidate = tip.prepare(cohort.getDataTreeModification());
610 } catch (Exception e) {
616 cohort.userPreCommit(candidate);
617 } catch (ExecutionException | TimeoutException e) {
622 // Set the tip of the data tree.
623 tip = Verify.verifyNotNull(candidate);
625 entry.lastAccess = shard.ticker().read();
626 cohort.successfulPreCommit(candidate);
629 private void failCommit(final Exception cause) {
630 shard.getShardMBean().incrementFailedTransactionsCount();
631 pendingTransactions.poll().cohort.failedCommit(cause);
632 processNextTransaction();
635 @SuppressWarnings("checkstyle:IllegalCatch")
636 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
637 final TransactionIdentifier txId = cohort.getIdentifier();
638 final DataTreeCandidate candidate = cohort.getCandidate();
640 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
643 dataTree.commit(candidate);
644 } catch (Exception e) {
645 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
650 // All pending candidates have been committed, reset the tip to the data tree
651 if (tip == candidate) {
655 shard.getShardMBean().incrementCommittedTransactionCount();
656 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
658 // FIXME: propagate journal index
659 pendingTransactions.poll().cohort.successfulCommit(UnsignedLong.ZERO);
661 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
662 notifyListeners(candidate);
664 processNextTransaction();
667 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
668 final CommitEntry entry = pendingTransactions.peek();
669 Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
671 final SimpleShardDataTreeCohort current = entry.cohort;
672 Verify.verify(cohort.equals(current), "Attempted to commit %s while %s is pending", cohort, current);
674 if (shard.canSkipPayload() || candidate.getRootNode().getModificationType() == ModificationType.UNMODIFIED) {
675 LOG.debug("{}: No replication required, proceeding to finish commit", logContext);
676 finishCommit(cohort);
680 final TransactionIdentifier txId = cohort.getIdentifier();
681 final Payload payload;
683 payload = CommitTransactionPayload.create(txId, candidate);
684 } catch (IOException e) {
685 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
686 pendingTransactions.poll().cohort.failedCommit(e);
690 // Once completed, we will continue via payloadReplicationComplete
691 entry.lastAccess = shard.ticker().read();
692 shard.persistPayload(txId, payload);
693 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
696 void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
697 cohortRegistry.process(sender, message);
701 ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId,
702 final DataTreeModification modification) {
703 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, modification, txId,
704 cohortRegistry.createCohort(schemaContext, txId, COMMIT_STEP_TIMEOUT));
705 pendingTransactions.add(new CommitEntry(cohort, shard.ticker().read()));
709 @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
710 void checkForExpiredTransactions(final long transactionCommitTimeoutMillis) {
711 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
712 final long now = shard.ticker().read();
713 final CommitEntry currentTx = pendingTransactions.peek();
714 if (currentTx != null && currentTx.lastAccess + timeout < now) {
715 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
716 currentTx.cohort.getIdentifier(), transactionCommitTimeoutMillis, currentTx.cohort.getState());
717 boolean processNext = true;
718 switch (currentTx.cohort.getState()) {
719 case CAN_COMMIT_PENDING:
720 pendingTransactions.remove().cohort.failedCanCommit(new TimeoutException());
722 case CAN_COMMIT_COMPLETE:
723 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
724 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
725 // in PRE_COMMIT_COMPLETE is changed.
726 pendingTransactions.remove().cohort.reportFailure(new TimeoutException());
728 case PRE_COMMIT_PENDING:
729 pendingTransactions.remove().cohort.failedPreCommit(new TimeoutException());
731 case PRE_COMMIT_COMPLETE:
732 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
733 // are ready we should commit the transaction, not abort it. Our current software stack does
734 // not allow us to do that consistently, because we persist at the time of commit, hence
735 // we can end up in a state where we have pre-committed a transaction, then a leader failover
736 // occurred ... the new leader does not see the pre-committed transaction and does not have
737 // a running timer. To fix this we really need two persistence events.
739 // The first one, done at pre-commit time will hold the transaction payload. When consensus
740 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
741 // apply the state in this event.
743 // The second one, done at commit (or abort) time holds only the transaction identifier and
744 // signals to followers that the state should (or should not) be applied.
746 // In order to make the pre-commit timer working across failovers, though, we need
747 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
748 // restart the timer.
749 pendingTransactions.remove().cohort.reportFailure(new TimeoutException());
752 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
753 currentTx.cohort.getIdentifier());
754 currentTx.lastAccess = now;
762 pendingTransactions.remove();
766 processNextTransaction();
771 boolean startAbort(final SimpleShardDataTreeCohort cohort) {
772 final Iterator<CommitEntry> it = pendingTransactions.iterator();
774 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
778 // First entry is special, as it may already be committing
779 final CommitEntry first = it.next();
780 if (cohort.equals(first.cohort)) {
781 if (cohort.getState() != State.COMMIT_PENDING) {
782 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
783 cohort.getIdentifier());
786 rebasePreCommittedTransactions(it, dataTree);
787 processNextTransaction();
791 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
795 TipProducingDataTreeTip newTip = dataTree;
796 while (it.hasNext()) {
797 final CommitEntry e = it.next();
798 if (cohort.equals(e.cohort)) {
799 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
801 rebasePreCommittedTransactions(it, newTip);
804 newTip = cohort.getCandidate();
808 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
812 @SuppressWarnings("checkstyle:IllegalCatch")
813 private void rebasePreCommittedTransactions(Iterator<CommitEntry> iter, TipProducingDataTreeTip newTip) {
815 while (iter.hasNext()) {
816 final SimpleShardDataTreeCohort cohort = iter.next().cohort;
817 if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
818 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
821 tip.validate(cohort.getDataTreeModification());
822 } catch (DataValidationFailedException | RuntimeException e) {
823 LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
824 cohort.reportFailure(e);
826 } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
827 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
830 tip.validate(cohort.getDataTreeModification());
831 DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
832 cohort.userPreCommit(candidate);
834 cohort.setNewCandidate(candidate);
836 } catch (ExecutionException | TimeoutException | RuntimeException | DataValidationFailedException e) {
837 LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
838 cohort.reportFailure(e);
844 void setRunOnPendingTransactionsComplete(final Runnable operation) {
845 runOnPendingTransactionsComplete = operation;
846 maybeRunOperationOnPendingTransactionsComplete();
849 private void maybeRunOperationOnPendingTransactionsComplete() {
850 if (runOnPendingTransactionsComplete != null && pendingTransactions.isEmpty()) {
851 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
852 runOnPendingTransactionsComplete);
854 runOnPendingTransactionsComplete.run();
855 runOnPendingTransactionsComplete = null;