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.Verify;
17 import com.google.common.collect.ImmutableList;
18 import com.google.common.collect.ImmutableMap;
19 import com.google.common.collect.ImmutableMap.Builder;
20 import com.google.common.primitives.UnsignedLong;
22 import java.io.IOException;
23 import java.util.AbstractMap.SimpleEntry;
24 import java.util.ArrayDeque;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.HashMap;
28 import java.util.Iterator;
30 import java.util.Map.Entry;
31 import java.util.Queue;
32 import java.util.concurrent.ExecutionException;
33 import java.util.concurrent.TimeUnit;
34 import java.util.concurrent.TimeoutException;
35 import java.util.function.UnaryOperator;
36 import javax.annotation.Nonnull;
37 import javax.annotation.concurrent.NotThreadSafe;
38 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
39 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
40 import org.opendaylight.controller.cluster.datastore.DataTreeCohortActorRegistry.CohortRegistryCommand;
41 import org.opendaylight.controller.cluster.datastore.ShardDataTreeCohort.State;
42 import org.opendaylight.controller.cluster.datastore.persisted.CommitTransactionPayload;
43 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
44 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
45 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshotMetadata;
46 import org.opendaylight.controller.cluster.datastore.utils.DataTreeModificationOutput;
47 import org.opendaylight.controller.cluster.datastore.utils.PruningDataTreeModification;
48 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
49 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
50 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
51 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
52 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
53 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
54 import org.opendaylight.controller.md.sal.dom.store.impl.DataChangeListenerRegistration;
55 import org.opendaylight.yangtools.concepts.Identifier;
56 import org.opendaylight.yangtools.concepts.ListenerRegistration;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
58 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
60 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
61 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
62 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
63 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
64 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
65 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
66 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
67 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
68 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
69 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
70 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
73 import scala.concurrent.duration.Duration;
76 * Internal shard state, similar to a DOMStore, but optimized for use in the actor system,
77 * e.g. it does not expose public interfaces and assumes it is only ever called from a
80 * This class is not part of the API contract and is subject to change at any time.
83 public class ShardDataTree extends ShardDataTreeTransactionParent {
84 private static final class CommitEntry {
85 final SimpleShardDataTreeCohort cohort;
88 CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
89 this.cohort = Preconditions.checkNotNull(cohort);
94 private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(Duration.create(5, TimeUnit.SECONDS));
95 private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
97 private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
98 private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
99 private final Queue<CommitEntry> pendingTransactions = new ArrayDeque<>();
100 private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
101 private final ShardDataChangeListenerPublisher dataChangeListenerPublisher;
102 private final Collection<ShardDataTreeMetadata<?>> metadata;
103 private final TipProducingDataTree dataTree;
104 private final String logContext;
105 private final Shard shard;
106 private Runnable runOnPendingTransactionsComplete;
108 private SchemaContext schemaContext;
110 public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TipProducingDataTree dataTree,
111 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
112 final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext,
113 final ShardDataTreeMetadata<?>... metadata) {
114 this.dataTree = Preconditions.checkNotNull(dataTree);
115 updateSchemaContext(schemaContext);
117 this.shard = Preconditions.checkNotNull(shard);
118 this.treeChangeListenerPublisher = Preconditions.checkNotNull(treeChangeListenerPublisher);
119 this.dataChangeListenerPublisher = Preconditions.checkNotNull(dataChangeListenerPublisher);
120 this.logContext = Preconditions.checkNotNull(logContext);
121 this.metadata = ImmutableList.copyOf(metadata);
124 public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType,
125 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
126 final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext) {
127 this(shard, schemaContext, InMemoryDataTreeFactory.getInstance().create(treeType),
128 treeChangeListenerPublisher, dataChangeListenerPublisher, logContext);
132 public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType) {
133 this(shard, schemaContext, treeType, new DefaultShardDataTreeChangeListenerPublisher(),
134 new DefaultShardDataChangeListenerPublisher(), "");
137 String logContext() {
141 public TipProducingDataTree getDataTree() {
145 SchemaContext getSchemaContext() {
146 return schemaContext;
149 void updateSchemaContext(final SchemaContext schemaContext) {
150 dataTree.setSchemaContext(schemaContext);
151 this.schemaContext = Preconditions.checkNotNull(schemaContext);
155 * Take a snapshot of current state for later recovery.
157 * @return A state snapshot
159 @Nonnull ShardDataTreeSnapshot takeStateSnapshot() {
160 final NormalizedNode<?, ?> rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY).get();
161 final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
162 ImmutableMap.builder();
164 for (ShardDataTreeMetadata<?> m : metadata) {
165 final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
167 metaBuilder.put(meta.getType(), meta);
171 return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
174 private void applySnapshot(final @Nonnull ShardDataTreeSnapshot snapshot,
175 final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
176 final Stopwatch elapsed = Stopwatch.createStarted();
178 if (!pendingTransactions.isEmpty()) {
179 LOG.warn("{}: applying state snapshot with pending transactions", logContext);
182 final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
183 if (snapshot instanceof MetadataShardDataTreeSnapshot) {
184 snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
186 snapshotMeta = ImmutableMap.of();
189 for (ShardDataTreeMetadata<?> m : metadata) {
190 final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
198 final DataTreeModification mod = wrapper.apply(dataTree.takeSnapshot().newModification());
199 // delete everything first
200 mod.delete(YangInstanceIdentifier.EMPTY);
202 final java.util.Optional<NormalizedNode<?, ?>> maybeNode = snapshot.getRootNode();
203 if (maybeNode.isPresent()) {
204 // Add everything from the remote node back
205 mod.write(YangInstanceIdentifier.EMPTY, maybeNode.get());
209 final DataTreeModification unwrapped = unwrap(mod);
210 dataTree.validate(unwrapped);
211 dataTree.commit(dataTree.prepare(unwrapped));
212 LOG.debug("{}: state snapshot applied in %s", logContext, elapsed);
215 private PruningDataTreeModification wrapWithPruning(final DataTreeModification delegate) {
216 return new PruningDataTreeModification(delegate, dataTree, schemaContext);
219 private static DataTreeModification unwrap(final DataTreeModification modification) {
220 if (modification instanceof PruningDataTreeModification) {
221 return ((PruningDataTreeModification)modification).delegate();
227 * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
228 * pruning in an attempt to adjust the state to our current SchemaContext.
230 * @param snapshot Snapshot that needs to be applied
231 * @throws DataValidationFailedException when the snapshot fails to apply
233 void applyRecoverySnapshot(final @Nonnull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
234 applySnapshot(snapshot, this::wrapWithPruning);
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(final @Nonnull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
246 applySnapshot(snapshot, UnaryOperator.identity());
249 private void applyRecoveryCandidate(final DataTreeCandidate candidate) throws DataValidationFailedException {
250 final PruningDataTreeModification mod = wrapWithPruning(dataTree.takeSnapshot().newModification());
251 DataTreeCandidates.applyToModification(mod, candidate);
254 final DataTreeModification unwrapped = mod.delegate();
255 LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
258 dataTree.validate(unwrapped);
259 dataTree.commit(dataTree.prepare(unwrapped));
260 } catch (Exception e) {
261 File file = new File(System.getProperty("karaf.data", "."),
262 "failed-recovery-payload-" + logContext + ".out");
263 DataTreeModificationOutput.toFile(file, unwrapped);
264 throw new IllegalStateException(String.format(
265 "%s: Failed to apply recovery payload. Modification data was written to file %s",
266 logContext, file), e);
271 * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
272 * pruning in an attempt to adjust the state to our current SchemaContext.
274 * @param payload Payload
275 * @throws IOException when the snapshot fails to deserialize
276 * @throws DataValidationFailedException when the snapshot fails to apply
278 void applyRecoveryPayload(final @Nonnull Payload payload) throws IOException, DataValidationFailedException {
279 if (payload instanceof CommitTransactionPayload) {
280 final Entry<TransactionIdentifier, DataTreeCandidate> e = ((CommitTransactionPayload) payload).getCandidate();
281 applyRecoveryCandidate(e.getValue());
282 allMetadataCommittedTransaction(e.getKey());
283 } else if (payload instanceof DataTreeCandidatePayload) {
284 applyRecoveryCandidate(((DataTreeCandidatePayload) payload).getCandidate());
286 LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
290 private void applyReplicatedCandidate(final Identifier identifier, final DataTreeCandidate foreign)
291 throws DataValidationFailedException {
292 LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
294 final DataTreeModification mod = dataTree.takeSnapshot().newModification();
295 DataTreeCandidates.applyToModification(mod, foreign);
298 LOG.trace("{}: Applying foreign modification {}", logContext, mod);
299 dataTree.validate(mod);
300 final DataTreeCandidate candidate = dataTree.prepare(mod);
301 dataTree.commit(candidate);
303 notifyListeners(candidate);
307 * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
308 * SchemaContexts match and does not perform any pruning.
310 * @param identifier Payload identifier as returned from RaftActor
311 * @param payload Payload
312 * @throws IOException when the snapshot fails to deserialize
313 * @throws DataValidationFailedException when the snapshot fails to apply
315 void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
316 DataValidationFailedException {
318 * 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
319 * if we are the leader and it has originated with us.
321 * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
322 * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
323 * acting in that capacity anymore.
325 * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
326 * pre-Boron state -- which limits the number of options here.
328 if (payload instanceof CommitTransactionPayload) {
329 if (identifier == null) {
330 final Entry<TransactionIdentifier, DataTreeCandidate> e = ((CommitTransactionPayload) payload).getCandidate();
331 applyReplicatedCandidate(e.getKey(), e.getValue());
332 allMetadataCommittedTransaction(e.getKey());
334 Verify.verify(identifier instanceof TransactionIdentifier);
335 payloadReplicationComplete((TransactionIdentifier) identifier);
338 LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
342 private void payloadReplicationComplete(final TransactionIdentifier txId) {
343 final CommitEntry current = pendingTransactions.peek();
344 if (current == null) {
345 LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
349 if (!current.cohort.getIdentifier().equals(txId)) {
350 LOG.warn("{}: Head of queue is {}, ignoring consensus on transaction {}", logContext,
351 current.cohort.getIdentifier(), txId);
355 finishCommit(current.cohort);
358 private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
359 for (ShardDataTreeMetadata<?> m : metadata) {
360 m.onTransactionCommitted(txId);
364 private ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier localHistoryIdentifier) {
365 ShardDataTreeTransactionChain chain = transactionChains.get(localHistoryIdentifier);
367 chain = new ShardDataTreeTransactionChain(localHistoryIdentifier, this);
368 transactionChains.put(localHistoryIdentifier, chain);
374 ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
375 if (txId.getHistoryId().getHistoryId() == 0) {
376 return new ReadOnlyShardDataTreeTransaction(txId, dataTree.takeSnapshot());
379 return ensureTransactionChain(txId.getHistoryId()).newReadOnlyTransaction(txId);
382 ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
383 if (txId.getHistoryId().getHistoryId() == 0) {
384 return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
388 return ensureTransactionChain(txId.getHistoryId()).newReadWriteTransaction(txId);
392 public void notifyListeners(final DataTreeCandidate candidate) {
393 treeChangeListenerPublisher.publishChanges(candidate, logContext);
394 dataChangeListenerPublisher.publishChanges(candidate, logContext);
397 void notifyOfInitialData(final DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
398 NormalizedNode<?, ?>>> listenerReg, final Optional<DataTreeCandidate> currentState) {
399 if (currentState.isPresent()) {
400 ShardDataChangeListenerPublisher localPublisher = dataChangeListenerPublisher.newInstance();
401 localPublisher.registerDataChangeListener(listenerReg.getPath(), listenerReg.getInstance(),
402 listenerReg.getScope());
403 localPublisher.publishChanges(currentState.get(), logContext);
407 void notifyOfInitialData(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
408 final Optional<DataTreeCandidate> currentState) {
409 if (currentState.isPresent()) {
410 ShardDataTreeChangeListenerPublisher localPublisher = treeChangeListenerPublisher.newInstance();
411 localPublisher.registerTreeChangeListener(path, listener);
412 localPublisher.publishChanges(currentState.get(), logContext);
416 void closeAllTransactionChains() {
417 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
421 transactionChains.clear();
424 void closeTransactionChain(final LocalHistoryIdentifier transactionChainId) {
425 final ShardDataTreeTransactionChain chain = transactionChains.remove(transactionChainId);
429 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, transactionChainId);
433 Entry<DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>,
434 Optional<DataTreeCandidate>> registerChangeListener(final YangInstanceIdentifier path,
435 final AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener,
436 final DataChangeScope scope) {
437 final DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> reg =
438 dataChangeListenerPublisher.registerDataChangeListener(path, listener, scope);
440 return new SimpleEntry<>(reg, readCurrentData());
443 private Optional<DataTreeCandidate> readCurrentData() {
444 final Optional<NormalizedNode<?, ?>> currentState = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY);
445 return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
446 YangInstanceIdentifier.EMPTY, currentState.get())) : Optional.<DataTreeCandidate>absent();
449 public Entry<ListenerRegistration<DOMDataTreeChangeListener>, Optional<DataTreeCandidate>> registerTreeChangeListener(
450 final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener) {
451 final ListenerRegistration<DOMDataTreeChangeListener> reg = treeChangeListenerPublisher.registerTreeChangeListener(
454 return new SimpleEntry<>(reg, readCurrentData());
458 return pendingTransactions.size();
462 void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction) {
467 ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction) {
468 final DataTreeModification snapshot = transaction.getSnapshot();
471 return createReadyCohort(transaction.getId(), snapshot);
474 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
475 return dataTree.takeSnapshot().readNode(path);
478 DataTreeSnapshot takeSnapshot() {
479 return dataTree.takeSnapshot();
483 public DataTreeModification newModification() {
484 return dataTree.takeSnapshot().newModification();
488 * @deprecated This method violates DataTree containment and will be removed.
492 public DataTreeCandidate commit(final DataTreeModification modification) throws DataValidationFailedException {
493 modification.ready();
494 dataTree.validate(modification);
495 DataTreeCandidate candidate = dataTree.prepare(modification);
496 dataTree.commit(candidate);
500 public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
501 Collection<ShardDataTreeCohort> ret = new ArrayList<>(pendingTransactions.size());
502 for(CommitEntry entry: pendingTransactions) {
503 ret.add(entry.cohort);
506 pendingTransactions.clear();
510 private void processNextTransaction() {
511 while (!pendingTransactions.isEmpty()) {
512 final CommitEntry entry = pendingTransactions.peek();
513 final SimpleShardDataTreeCohort cohort = entry.cohort;
514 final DataTreeModification modification = cohort.getDataTreeModification();
516 if(cohort.getState() != State.CAN_COMMIT_PENDING) {
520 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
523 dataTree.validate(modification);
524 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
525 cohort.successfulCanCommit();
526 entry.lastAccess = shard.ticker().read();
528 } catch (ConflictingModificationAppliedException e) {
529 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
531 cause = new OptimisticLockFailedException("Optimistic lock failed.", e);
532 } catch (DataValidationFailedException e) {
533 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
536 // For debugging purposes, allow dumping of the modification. Coupled with the above
537 // precondition log, it should allow us to understand what went on.
538 LOG.debug("{}: Store Tx {}: modifications: {} tree: {}", cohort.getIdentifier(), modification, dataTree);
539 cause = new TransactionCommitFailedException("Data did not pass validation.", e);
540 } catch (Exception e) {
541 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
545 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
546 pendingTransactions.poll().cohort.failedCanCommit(cause);
549 maybeRunOperationOnPendingTransactionsComplete();
552 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
553 final SimpleShardDataTreeCohort current = pendingTransactions.peek().cohort;
554 if (!cohort.equals(current)) {
555 LOG.debug("{}: Transaction {} scheduled for canCommit step", logContext, cohort.getIdentifier());
559 processNextTransaction();
562 private void failPreCommit(final Exception cause) {
563 shard.getShardMBean().incrementFailedTransactionsCount();
564 pendingTransactions.poll().cohort.failedPreCommit(cause);
565 processNextTransaction();
568 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
569 final CommitEntry entry = pendingTransactions.peek();
570 Preconditions.checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
572 final SimpleShardDataTreeCohort current = entry.cohort;
573 Verify.verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
574 final DataTreeCandidateTip candidate;
576 candidate = dataTree.prepare(cohort.getDataTreeModification());
577 } catch (Exception e) {
583 cohort.userPreCommit(candidate);
584 } catch (ExecutionException | TimeoutException e) {
589 entry.lastAccess = shard.ticker().read();
590 cohort.successfulPreCommit(candidate);
593 private void failCommit(final Exception cause) {
594 shard.getShardMBean().incrementFailedTransactionsCount();
595 pendingTransactions.poll().cohort.failedCommit(cause);
596 processNextTransaction();
599 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
600 final TransactionIdentifier txId = cohort.getIdentifier();
601 final DataTreeCandidate candidate = cohort.getCandidate();
603 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
606 dataTree.commit(candidate);
607 } catch (Exception e) {
608 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
613 shard.getShardMBean().incrementCommittedTransactionCount();
614 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
616 // FIXME: propagate journal index
617 pendingTransactions.poll().cohort.successfulCommit(UnsignedLong.ZERO);
619 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
620 notifyListeners(candidate);
622 processNextTransaction();
625 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
626 final CommitEntry entry = pendingTransactions.peek();
627 Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
629 final SimpleShardDataTreeCohort current = entry.cohort;
630 Verify.verify(cohort.equals(current), "Attempted to commit %s while %s is pending", cohort, current);
632 if (shard.canSkipPayload() || candidate.getRootNode().getModificationType() == ModificationType.UNMODIFIED) {
633 LOG.debug("{}: No replication required, proceeding to finish commit", logContext);
634 finishCommit(cohort);
638 final TransactionIdentifier txId = cohort.getIdentifier();
639 final Payload payload;
641 payload = CommitTransactionPayload.create(txId, candidate);
642 } catch (IOException e) {
643 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
644 pendingTransactions.poll().cohort.failedCommit(e);
648 // Once completed, we will continue via payloadReplicationComplete
649 entry.lastAccess = shard.ticker().read();
650 shard.persistPayload(txId, payload);
651 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
654 void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
655 cohortRegistry.process(sender, message);
658 ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId,
659 final DataTreeModification modification) {
660 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, modification, txId,
661 cohortRegistry.createCohort(schemaContext, txId, COMMIT_STEP_TIMEOUT));
662 pendingTransactions.add(new CommitEntry(cohort, shard.ticker().read()));
666 void checkForExpiredTransactions(final long transactionCommitTimeoutMillis) {
667 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
668 final long now = shard.ticker().read();
669 final CommitEntry currentTx = pendingTransactions.peek();
670 if (currentTx != null && currentTx.lastAccess + timeout < now) {
671 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
672 currentTx.cohort.getIdentifier(), transactionCommitTimeoutMillis, currentTx.cohort.getState());
673 boolean processNext = true;
674 switch (currentTx.cohort.getState()) {
675 case CAN_COMMIT_PENDING:
676 pendingTransactions.poll().cohort.failedCanCommit(new TimeoutException());
678 case CAN_COMMIT_COMPLETE:
679 pendingTransactions.poll().cohort.reportFailure(new TimeoutException());
681 case PRE_COMMIT_PENDING:
682 pendingTransactions.poll().cohort.failedPreCommit(new TimeoutException());
684 case PRE_COMMIT_COMPLETE:
685 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
686 // are ready we should commit the transaction, not abort it. Our current software stack does
687 // not allow us to do that consistently, because we persist at the time of commit, hence
688 // we can end up in a state where we have pre-committed a transaction, then a leader failover
689 // occurred ... the new leader does not see the pre-committed transaction and does not have
690 // a running timer. To fix this we really need two persistence events.
692 // The first one, done at pre-commit time will hold the transaction payload. When consensus
693 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
694 // apply the state in this event.
696 // The second one, done at commit (or abort) time holds only the transaction identifier and
697 // signals to followers that the state should (or should not) be applied.
699 // In order to make the pre-commit timer working across failovers, though, we need
700 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
701 // restart the timer.
702 pendingTransactions.poll().cohort.reportFailure(new TimeoutException());
705 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
706 currentTx.cohort.getIdentifier());
707 currentTx.lastAccess = now;
715 pendingTransactions.poll();
719 processNextTransaction();
724 void startAbort(final SimpleShardDataTreeCohort cohort) {
725 final Iterator<CommitEntry> it = pendingTransactions.iterator();
727 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
731 // First entry is special, as it may already be committing
732 final CommitEntry first = it.next();
733 if (cohort.equals(first.cohort)) {
734 if (cohort.getState() != State.COMMIT_PENDING) {
735 LOG.debug("{}: aborted head of queue {} in state {}", logContext, cohort.getIdentifier(),
736 cohort.getIdentifier());
737 pendingTransactions.poll();
738 processNextTransaction();
740 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
746 while (it.hasNext()) {
747 final CommitEntry e = it.next();
748 if (cohort.equals(e.cohort)) {
749 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
755 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
758 void setRunOnPendingTransactionsComplete(final Runnable operation) {
759 runOnPendingTransactionsComplete = operation;
760 maybeRunOperationOnPendingTransactionsComplete();
763 private void maybeRunOperationOnPendingTransactionsComplete() {
764 if (runOnPendingTransactionsComplete != null && pendingTransactions.isEmpty()) {
765 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
766 runOnPendingTransactionsComplete);
768 runOnPendingTransactionsComplete.run();
769 runOnPendingTransactionsComplete = null;