2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.datastore;
10 import akka.actor.ActorRef;
11 import akka.util.Timeout;
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.MoreObjects;
14 import com.google.common.base.Optional;
15 import com.google.common.base.Preconditions;
16 import com.google.common.base.Stopwatch;
17 import com.google.common.base.Ticker;
18 import com.google.common.base.Verify;
19 import com.google.common.collect.ImmutableList;
20 import com.google.common.collect.ImmutableMap;
21 import com.google.common.collect.ImmutableMap.Builder;
22 import com.google.common.collect.Iterables;
23 import com.google.common.primitives.UnsignedLong;
24 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
26 import java.io.IOException;
27 import java.util.ArrayDeque;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.HashMap;
31 import java.util.Iterator;
33 import java.util.Map.Entry;
34 import java.util.Queue;
35 import java.util.concurrent.ExecutionException;
36 import java.util.concurrent.TimeUnit;
37 import java.util.concurrent.TimeoutException;
38 import java.util.function.Consumer;
39 import java.util.function.UnaryOperator;
40 import javax.annotation.Nonnull;
41 import javax.annotation.Nullable;
42 import javax.annotation.concurrent.NotThreadSafe;
43 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
44 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
45 import org.opendaylight.controller.cluster.datastore.DataTreeCohortActorRegistry.CohortRegistryCommand;
46 import org.opendaylight.controller.cluster.datastore.ShardDataTreeCohort.State;
47 import org.opendaylight.controller.cluster.datastore.persisted.AbortTransactionPayload;
48 import org.opendaylight.controller.cluster.datastore.persisted.AbstractIdentifiablePayload;
49 import org.opendaylight.controller.cluster.datastore.persisted.CloseLocalHistoryPayload;
50 import org.opendaylight.controller.cluster.datastore.persisted.CommitTransactionPayload;
51 import org.opendaylight.controller.cluster.datastore.persisted.CreateLocalHistoryPayload;
52 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
53 import org.opendaylight.controller.cluster.datastore.persisted.PurgeLocalHistoryPayload;
54 import org.opendaylight.controller.cluster.datastore.persisted.PurgeTransactionPayload;
55 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
56 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshotMetadata;
57 import org.opendaylight.controller.cluster.datastore.utils.DataTreeModificationOutput;
58 import org.opendaylight.controller.cluster.datastore.utils.PruningDataTreeModification;
59 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
60 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
61 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
62 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
63 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
64 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
65 import org.opendaylight.yangtools.concepts.Identifier;
66 import org.opendaylight.yangtools.concepts.ListenerRegistration;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
68 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
70 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
71 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
72 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
73 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
74 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
75 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeTip;
76 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
77 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
78 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTreeTip;
79 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
80 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
81 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
84 import scala.concurrent.duration.Duration;
87 * Internal shard state, similar to a DOMStore, but optimized for use in the actor system,
88 * e.g. it does not expose public interfaces and assumes it is only ever called from a
92 * This class is not part of the API contract and is subject to change at any time.
95 public class ShardDataTree extends ShardDataTreeTransactionParent {
96 private static final class CommitEntry {
97 final SimpleShardDataTreeCohort cohort;
100 CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
101 this.cohort = Preconditions.checkNotNull(cohort);
106 private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(Duration.create(5, TimeUnit.SECONDS));
107 private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
109 private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
111 private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
112 private final Queue<CommitEntry> pendingTransactions = new ArrayDeque<>();
113 private final Queue<CommitEntry> pendingCommits = new ArrayDeque<>();
114 private final Queue<CommitEntry> pendingFinishCommits = new ArrayDeque<>();
117 * Callbacks that need to be invoked once a payload is replicated.
119 private final Map<Payload, Runnable> replicationCallbacks = new HashMap<>();
121 private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
122 private final ShardDataChangeListenerPublisher dataChangeListenerPublisher;
123 private final Collection<ShardDataTreeMetadata<?>> metadata;
124 private final TipProducingDataTree dataTree;
125 private final String logContext;
126 private final Shard shard;
127 private Runnable runOnPendingTransactionsComplete;
130 * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
131 * {@link TipProducingDataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
132 * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
133 * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
135 private TipProducingDataTreeTip tip;
137 private SchemaContext schemaContext;
139 ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TipProducingDataTree dataTree,
140 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
141 final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext,
142 final ShardDataTreeMetadata<?>... metadata) {
143 this.dataTree = Preconditions.checkNotNull(dataTree);
144 updateSchemaContext(schemaContext);
146 this.shard = Preconditions.checkNotNull(shard);
147 this.treeChangeListenerPublisher = Preconditions.checkNotNull(treeChangeListenerPublisher);
148 this.dataChangeListenerPublisher = Preconditions.checkNotNull(dataChangeListenerPublisher);
149 this.logContext = Preconditions.checkNotNull(logContext);
150 this.metadata = ImmutableList.copyOf(metadata);
154 ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType,
155 final YangInstanceIdentifier root,
156 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
157 final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext,
158 final ShardDataTreeMetadata<?>... metadata) {
159 this(shard, schemaContext, InMemoryDataTreeFactory.getInstance().create(treeType, root),
160 treeChangeListenerPublisher, dataChangeListenerPublisher, logContext, metadata);
164 public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType) {
165 this(shard, schemaContext, treeType, YangInstanceIdentifier.EMPTY,
166 new DefaultShardDataTreeChangeListenerPublisher(), new DefaultShardDataChangeListenerPublisher(), "");
169 final String logContext() {
173 final Ticker ticker() {
174 return shard.ticker();
177 public TipProducingDataTree getDataTree() {
181 SchemaContext getSchemaContext() {
182 return schemaContext;
185 void updateSchemaContext(final SchemaContext newSchemaContext) {
186 dataTree.setSchemaContext(newSchemaContext);
187 this.schemaContext = Preconditions.checkNotNull(newSchemaContext);
191 * Take a snapshot of current state for later recovery.
193 * @return A state snapshot
195 @Nonnull ShardDataTreeSnapshot takeStateSnapshot() {
196 final NormalizedNode<?, ?> rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY).get();
197 final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
198 ImmutableMap.builder();
200 for (ShardDataTreeMetadata<?> m : metadata) {
201 final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
203 metaBuilder.put(meta.getType(), meta);
207 return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
210 private boolean anyPendingTransactions() {
211 return !pendingTransactions.isEmpty() || !pendingCommits.isEmpty() || !pendingFinishCommits.isEmpty();
214 private void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot,
215 final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
216 final Stopwatch elapsed = Stopwatch.createStarted();
218 if (anyPendingTransactions()) {
219 LOG.warn("{}: applying state snapshot with pending transactions", logContext);
222 final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
223 if (snapshot instanceof MetadataShardDataTreeSnapshot) {
224 snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
226 snapshotMeta = ImmutableMap.of();
229 for (ShardDataTreeMetadata<?> m : metadata) {
230 final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
238 final DataTreeModification mod = wrapper.apply(dataTree.takeSnapshot().newModification());
239 // delete everything first
240 mod.delete(YangInstanceIdentifier.EMPTY);
242 final java.util.Optional<NormalizedNode<?, ?>> maybeNode = snapshot.getRootNode();
243 if (maybeNode.isPresent()) {
244 // Add everything from the remote node back
245 mod.write(YangInstanceIdentifier.EMPTY, maybeNode.get());
249 final DataTreeModification unwrapped = unwrap(mod);
250 dataTree.validate(unwrapped);
251 DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
252 dataTree.commit(candidate);
253 notifyListeners(candidate);
255 LOG.debug("{}: state snapshot applied in %s", logContext, elapsed);
259 * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
260 * does not perform any pruning.
262 * @param snapshot Snapshot that needs to be applied
263 * @throws DataValidationFailedException when the snapshot fails to apply
265 void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
266 applySnapshot(snapshot, UnaryOperator.identity());
269 private PruningDataTreeModification wrapWithPruning(final DataTreeModification delegate) {
270 return new PruningDataTreeModification(delegate, dataTree, schemaContext);
273 private static DataTreeModification unwrap(final DataTreeModification modification) {
274 if (modification instanceof PruningDataTreeModification) {
275 return ((PruningDataTreeModification)modification).delegate();
281 * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
282 * pruning in an attempt to adjust the state to our current SchemaContext.
284 * @param snapshot Snapshot that needs to be applied
285 * @throws DataValidationFailedException when the snapshot fails to apply
287 void applyRecoverySnapshot(final @Nonnull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
288 applySnapshot(snapshot, this::wrapWithPruning);
291 @SuppressWarnings("checkstyle:IllegalCatch")
292 private void applyRecoveryCandidate(final DataTreeCandidate candidate) throws DataValidationFailedException {
293 final PruningDataTreeModification mod = wrapWithPruning(dataTree.takeSnapshot().newModification());
294 DataTreeCandidates.applyToModification(mod, candidate);
297 final DataTreeModification unwrapped = mod.delegate();
298 LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
301 dataTree.validate(unwrapped);
302 dataTree.commit(dataTree.prepare(unwrapped));
303 } catch (Exception e) {
304 File file = new File(System.getProperty("karaf.data", "."),
305 "failed-recovery-payload-" + logContext + ".out");
306 DataTreeModificationOutput.toFile(file, unwrapped);
307 throw new IllegalStateException(String.format(
308 "%s: Failed to apply recovery payload. Modification data was written to file %s",
309 logContext, file), e);
314 * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
315 * pruning in an attempt to adjust the state to our current SchemaContext.
317 * @param payload Payload
318 * @throws IOException when the snapshot fails to deserialize
319 * @throws DataValidationFailedException when the snapshot fails to apply
321 void applyRecoveryPayload(final @Nonnull Payload payload) throws IOException, DataValidationFailedException {
322 if (payload instanceof CommitTransactionPayload) {
323 final Entry<TransactionIdentifier, DataTreeCandidate> e =
324 ((CommitTransactionPayload) payload).getCandidate();
325 applyRecoveryCandidate(e.getValue());
326 allMetadataCommittedTransaction(e.getKey());
327 } else if (payload instanceof AbortTransactionPayload) {
328 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
329 } else if (payload instanceof PurgeTransactionPayload) {
330 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
331 } else if (payload instanceof CreateLocalHistoryPayload) {
332 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
333 } else if (payload instanceof CloseLocalHistoryPayload) {
334 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
335 } else if (payload instanceof PurgeLocalHistoryPayload) {
336 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
338 LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
342 private void applyReplicatedCandidate(final Identifier identifier, final DataTreeCandidate foreign)
343 throws DataValidationFailedException {
344 LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
346 final DataTreeModification mod = dataTree.takeSnapshot().newModification();
347 DataTreeCandidates.applyToModification(mod, foreign);
350 LOG.trace("{}: Applying foreign modification {}", logContext, mod);
351 dataTree.validate(mod);
352 final DataTreeCandidate candidate = dataTree.prepare(mod);
353 dataTree.commit(candidate);
355 notifyListeners(candidate);
359 * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
360 * SchemaContexts match and does not perform any pruning.
362 * @param identifier Payload identifier as returned from RaftActor
363 * @param payload Payload
364 * @throws IOException when the snapshot fails to deserialize
365 * @throws DataValidationFailedException when the snapshot fails to apply
367 void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
368 DataValidationFailedException {
370 * 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
371 * if we are the leader and it has originated with us.
373 * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
374 * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
375 * acting in that capacity anymore.
377 * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
378 * pre-Boron state -- which limits the number of options here.
380 if (payload instanceof CommitTransactionPayload) {
381 if (identifier == null) {
382 final Entry<TransactionIdentifier, DataTreeCandidate> e =
383 ((CommitTransactionPayload) payload).getCandidate();
384 applyReplicatedCandidate(e.getKey(), e.getValue());
385 allMetadataCommittedTransaction(e.getKey());
387 Verify.verify(identifier instanceof TransactionIdentifier);
388 payloadReplicationComplete((TransactionIdentifier) identifier);
390 } else if (payload instanceof AbortTransactionPayload) {
391 if (identifier != null) {
392 payloadReplicationComplete((AbortTransactionPayload) payload);
394 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
396 } else if (payload instanceof PurgeTransactionPayload) {
397 if (identifier != null) {
398 payloadReplicationComplete((PurgeTransactionPayload) payload);
400 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
402 } else if (payload instanceof CloseLocalHistoryPayload) {
403 if (identifier != null) {
404 payloadReplicationComplete((CloseLocalHistoryPayload) payload);
406 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
408 } else if (payload instanceof CreateLocalHistoryPayload) {
409 if (identifier != null) {
410 payloadReplicationComplete((CreateLocalHistoryPayload)payload);
412 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
414 } else if (payload instanceof PurgeLocalHistoryPayload) {
415 if (identifier != null) {
416 payloadReplicationComplete((PurgeLocalHistoryPayload)payload);
418 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
421 LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
425 private void replicatePayload(final Identifier id, final Payload payload, @Nullable final Runnable callback) {
426 if (callback != null) {
427 replicationCallbacks.put(payload, callback);
429 shard.persistPayload(id, payload, true);
432 private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
433 final Runnable callback = replicationCallbacks.remove(payload);
434 if (callback != null) {
435 LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
438 LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
442 private void payloadReplicationComplete(final TransactionIdentifier txId) {
443 final CommitEntry current = pendingFinishCommits.peek();
444 if (current == null) {
445 LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
449 if (!current.cohort.getIdentifier().equals(txId)) {
450 LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
451 current.cohort.getIdentifier(), txId);
455 finishCommit(current.cohort);
458 private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
459 for (ShardDataTreeMetadata<?> m : metadata) {
460 m.onTransactionAborted(txId);
464 private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
465 for (ShardDataTreeMetadata<?> m : metadata) {
466 m.onTransactionCommitted(txId);
470 private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
471 for (ShardDataTreeMetadata<?> m : metadata) {
472 m.onTransactionPurged(txId);
476 private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
477 for (ShardDataTreeMetadata<?> m : metadata) {
478 m.onHistoryCreated(historyId);
482 private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
483 for (ShardDataTreeMetadata<?> m : metadata) {
484 m.onHistoryClosed(historyId);
488 private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
489 for (ShardDataTreeMetadata<?> m : metadata) {
490 m.onHistoryPurged(historyId);
495 * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
496 * this method is used for re-establishing state when we are taking over
498 * @param historyId Local history identifier
499 * @param closed True if the chain should be created in closed state (i.e. pending purge)
500 * @return Transaction chain handle
502 ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
503 final boolean closed) {
504 final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
505 final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
506 Preconditions.checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId,
511 ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId) {
512 ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
514 chain = new ShardDataTreeTransactionChain(historyId, this);
515 transactionChains.put(historyId, chain);
516 shard.persistPayload(historyId, CreateLocalHistoryPayload.create(historyId), true);
522 ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
523 if (txId.getHistoryId().getHistoryId() == 0) {
524 return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
527 return ensureTransactionChain(txId.getHistoryId()).newReadOnlyTransaction(txId);
530 ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
531 if (txId.getHistoryId().getHistoryId() == 0) {
532 return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
536 return ensureTransactionChain(txId.getHistoryId()).newReadWriteTransaction(txId);
540 public void notifyListeners(final DataTreeCandidate candidate) {
541 treeChangeListenerPublisher.publishChanges(candidate, logContext);
542 dataChangeListenerPublisher.publishChanges(candidate, logContext);
546 * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
547 * replication callbacks.
549 void purgeLeaderState() {
550 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
554 transactionChains.clear();
555 replicationCallbacks.clear();
559 * Close a single transaction chain.
561 * @param id History identifier
562 * @param callback Callback to invoke upon completion, may be null
564 void closeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
565 final ShardDataTreeTransactionChain chain = transactionChains.get(id);
567 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
568 if (callback != null) {
575 replicatePayload(id, CloseLocalHistoryPayload.create(id), callback);
579 * Purge a single transaction chain.
581 * @param id History identifier
582 * @param callback Callback to invoke upon completion, may be null
584 void purgeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
585 final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
587 LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
588 if (callback != null) {
594 replicatePayload(id, PurgeLocalHistoryPayload.create(id), callback);
597 void registerDataChangeListener(final YangInstanceIdentifier path,
598 final AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener,
599 final DataChangeScope scope, final Optional<DataTreeCandidate> initialState,
600 final Consumer<ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>>
602 dataChangeListenerPublisher.registerDataChangeListener(path, listener, scope, initialState, onRegistration);
605 Optional<DataTreeCandidate> readCurrentData() {
606 final Optional<NormalizedNode<?, ?>> currentState =
607 dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY);
608 return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
609 YangInstanceIdentifier.EMPTY, currentState.get())) : Optional.<DataTreeCandidate>absent();
612 public void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
613 final Optional<DataTreeCandidate> initialState,
614 final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
615 treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
619 return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
623 void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
624 final TransactionIdentifier id = transaction.getIdentifier();
625 LOG.debug("{}: aborting transaction {}", logContext, id);
626 replicatePayload(id, AbortTransactionPayload.create(id), callback);
630 void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
631 // No-op for free-standing transactions
636 ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction) {
637 final DataTreeModification snapshot = transaction.getSnapshot();
640 return createReadyCohort(transaction.getIdentifier(), snapshot);
643 void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
644 LOG.debug("{}: purging transaction {}", logContext, id);
645 replicatePayload(id, PurgeTransactionPayload.create(id), callback);
648 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
649 return dataTree.takeSnapshot().readNode(path);
652 DataTreeSnapshot takeSnapshot() {
653 return dataTree.takeSnapshot();
657 public DataTreeModification newModification() {
658 return dataTree.takeSnapshot().newModification();
662 * Commits a modification.
664 * @deprecated This method violates DataTree containment and will be removed.
668 public DataTreeCandidate commit(final DataTreeModification modification) throws DataValidationFailedException {
669 // Direct modification commit is a utility, which cannot be used while we have transactions in-flight
670 Preconditions.checkState(tip == dataTree, "Cannot modify data tree while transacgitons are pending");
672 modification.ready();
673 dataTree.validate(modification);
674 DataTreeCandidate candidate = dataTree.prepare(modification);
675 dataTree.commit(candidate);
679 public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
680 Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
682 for (CommitEntry entry: pendingFinishCommits) {
683 ret.add(entry.cohort);
686 for (CommitEntry entry: pendingCommits) {
687 ret.add(entry.cohort);
690 for (CommitEntry entry: pendingTransactions) {
691 ret.add(entry.cohort);
694 pendingFinishCommits.clear();
695 pendingCommits.clear();
696 pendingTransactions.clear();
701 @SuppressWarnings("checkstyle:IllegalCatch")
702 private void processNextPendingTransaction() {
703 processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
704 final SimpleShardDataTreeCohort cohort = entry.cohort;
705 final DataTreeModification modification = cohort.getDataTreeModification();
707 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
710 cohort.throwCanCommitFailure();
712 tip.validate(modification);
713 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
714 cohort.successfulCanCommit();
715 entry.lastAccess = ticker().read();
717 } catch (ConflictingModificationAppliedException e) {
718 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
720 cause = new OptimisticLockFailedException("Optimistic lock failed.", e);
721 } catch (DataValidationFailedException e) {
722 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
725 // For debugging purposes, allow dumping of the modification. Coupled with the above
726 // precondition log, it should allow us to understand what went on.
727 LOG.debug("{}: Store Tx {}: modifications: {} tree: {}", cohort.getIdentifier(), modification,
729 cause = new TransactionCommitFailedException("Data did not pass validation.", e);
730 } catch (Exception e) {
731 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
735 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
736 pendingTransactions.poll().cohort.failedCanCommit(cause);
740 private void processNextPending() {
741 processNextPendingCommit();
742 processNextPendingTransaction();
745 private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
746 final Consumer<CommitEntry> processor) {
747 while (!queue.isEmpty()) {
748 final CommitEntry entry = queue.peek();
749 final SimpleShardDataTreeCohort cohort = entry.cohort;
751 if (cohort.isFailed()) {
752 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
757 if (cohort.getState() == allowedState) {
758 processor.accept(entry);
764 maybeRunOperationOnPendingTransactionsComplete();
767 private void processNextPendingCommit() {
768 processNextPending(pendingCommits, State.COMMIT_PENDING,
769 entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
772 private boolean peekNextPendingCommit() {
773 final CommitEntry first = pendingCommits.peek();
774 return first != null && first.cohort.getState() == State.COMMIT_PENDING;
777 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
778 final SimpleShardDataTreeCohort current = pendingTransactions.peek().cohort;
779 if (!cohort.equals(current)) {
780 LOG.debug("{}: Transaction {} scheduled for canCommit step", logContext, cohort.getIdentifier());
784 processNextPendingTransaction();
787 private void failPreCommit(final Exception cause) {
788 shard.getShardMBean().incrementFailedTransactionsCount();
789 pendingTransactions.poll().cohort.failedPreCommit(cause);
790 processNextPendingTransaction();
793 @SuppressWarnings("checkstyle:IllegalCatch")
794 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
795 final CommitEntry entry = pendingTransactions.peek();
796 Preconditions.checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
798 final SimpleShardDataTreeCohort current = entry.cohort;
799 Verify.verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
801 LOG.debug("{}: Preparing transaction {}", logContext, current.getIdentifier());
803 final DataTreeCandidateTip candidate;
805 candidate = tip.prepare(cohort.getDataTreeModification());
806 cohort.userPreCommit(candidate);
807 } catch (ExecutionException | TimeoutException | RuntimeException e) {
812 // Set the tip of the data tree.
813 tip = Verify.verifyNotNull(candidate);
815 entry.lastAccess = ticker().read();
817 pendingTransactions.remove();
818 pendingCommits.add(entry);
820 LOG.debug("{}: Transaction {} prepared", logContext, current.getIdentifier());
822 cohort.successfulPreCommit(candidate);
824 processNextPendingTransaction();
827 private void failCommit(final Exception cause) {
828 shard.getShardMBean().incrementFailedTransactionsCount();
829 pendingFinishCommits.poll().cohort.failedCommit(cause);
830 processNextPending();
833 @SuppressWarnings("checkstyle:IllegalCatch")
834 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
835 final TransactionIdentifier txId = cohort.getIdentifier();
836 final DataTreeCandidate candidate = cohort.getCandidate();
838 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
840 if (tip == candidate) {
841 // All pending candidates have been committed, reset the tip to the data tree.
846 dataTree.commit(candidate);
847 } catch (Exception e) {
848 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
853 shard.getShardMBean().incrementCommittedTransactionCount();
854 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
856 // FIXME: propagate journal index
857 pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO);
859 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
860 notifyListeners(candidate);
862 processNextPending();
865 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
866 final CommitEntry entry = pendingCommits.peek();
867 Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
869 final SimpleShardDataTreeCohort current = entry.cohort;
870 if (!cohort.equals(current)) {
871 LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
875 LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
877 final TransactionIdentifier txId = cohort.getIdentifier();
878 final Payload payload;
880 payload = CommitTransactionPayload.create(txId, candidate);
881 } catch (IOException e) {
882 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
883 pendingCommits.poll().cohort.failedCommit(e);
884 processNextPending();
888 // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
889 // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
890 // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
891 // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
892 // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
893 // pendingCommits queue.
894 processNextPendingTransaction();
896 // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
897 // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
898 // in order to properly determine the batchHint flag for the call to persistPayload.
899 pendingCommits.remove();
900 pendingFinishCommits.add(entry);
902 // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
903 // this transaction for replication.
904 boolean replicationBatchHint = peekNextPendingCommit();
906 // Once completed, we will continue via payloadReplicationComplete
907 shard.persistPayload(txId, payload, replicationBatchHint);
909 entry.lastAccess = shard.ticker().read();
911 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
913 // Process the next transaction pending commit, if any. If there is one it will be batched with this
914 // transaction for replication.
915 processNextPendingCommit();
918 Collection<ActorRef> getCohortActors() {
919 return cohortRegistry.getCohortActors();
922 void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
923 cohortRegistry.process(sender, message);
927 ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
928 final Exception failure) {
929 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort.DeadOnArrival(this, mod, txId, failure);
930 pendingTransactions.add(new CommitEntry(cohort, ticker().read()));
935 ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId,
936 final DataTreeModification mod) {
937 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort.Normal(this, mod, txId,
938 cohortRegistry.createCohort(schemaContext, txId, COMMIT_STEP_TIMEOUT));
939 pendingTransactions.add(new CommitEntry(cohort, ticker().read()));
943 // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
944 // the newReadWriteTransaction()
945 ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod) {
946 if (txId.getHistoryId().getHistoryId() == 0) {
947 return createReadyCohort(txId, mod);
950 return ensureTransactionChain(txId.getHistoryId()).createReadyCohort(txId, mod);
953 @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
954 void checkForExpiredTransactions(final long transactionCommitTimeoutMillis) {
955 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
956 final long now = ticker().read();
958 final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
959 !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
960 final CommitEntry currentTx = currentQueue.peek();
961 if (currentTx != null && currentTx.lastAccess + timeout < now) {
962 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
963 currentTx.cohort.getIdentifier(), transactionCommitTimeoutMillis, currentTx.cohort.getState());
964 boolean processNext = true;
965 switch (currentTx.cohort.getState()) {
966 case CAN_COMMIT_PENDING:
967 currentQueue.remove().cohort.failedCanCommit(new TimeoutException());
969 case CAN_COMMIT_COMPLETE:
970 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
971 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
972 // in PRE_COMMIT_COMPLETE is changed.
973 currentQueue.remove().cohort.reportFailure(new TimeoutException());
975 case PRE_COMMIT_PENDING:
976 currentQueue.remove().cohort.failedPreCommit(new TimeoutException());
978 case PRE_COMMIT_COMPLETE:
979 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
980 // are ready we should commit the transaction, not abort it. Our current software stack does
981 // not allow us to do that consistently, because we persist at the time of commit, hence
982 // we can end up in a state where we have pre-committed a transaction, then a leader failover
983 // occurred ... the new leader does not see the pre-committed transaction and does not have
984 // a running timer. To fix this we really need two persistence events.
986 // The first one, done at pre-commit time will hold the transaction payload. When consensus
987 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
988 // apply the state in this event.
990 // The second one, done at commit (or abort) time holds only the transaction identifier and
991 // signals to followers that the state should (or should not) be applied.
993 // In order to make the pre-commit timer working across failovers, though, we need
994 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
995 // restart the timer.
996 currentQueue.remove().cohort.reportFailure(new TimeoutException());
999 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1000 currentTx.cohort.getIdentifier());
1001 currentTx.lastAccess = now;
1002 processNext = false;
1009 currentQueue.remove();
1013 processNextPending();
1018 boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1019 final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1020 pendingTransactions).iterator();
1021 if (!it.hasNext()) {
1022 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1026 // First entry is special, as it may already be committing
1027 final CommitEntry first = it.next();
1028 if (cohort.equals(first.cohort)) {
1029 if (cohort.getState() != State.COMMIT_PENDING) {
1030 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1031 cohort.getIdentifier());
1034 if (cohort.getCandidate() != null) {
1035 rebaseTransactions(it, dataTree);
1038 processNextPending();
1042 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1046 TipProducingDataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
1047 while (it.hasNext()) {
1048 final CommitEntry e = it.next();
1049 if (cohort.equals(e.cohort)) {
1050 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1053 if (cohort.getCandidate() != null) {
1054 rebaseTransactions(it, newTip);
1059 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), newTip);
1063 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1067 @SuppressWarnings("checkstyle:IllegalCatch")
1068 private void rebaseTransactions(final Iterator<CommitEntry> iter, @Nonnull final TipProducingDataTreeTip newTip) {
1069 tip = Preconditions.checkNotNull(newTip);
1070 while (iter.hasNext()) {
1071 final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1072 if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1073 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1076 tip.validate(cohort.getDataTreeModification());
1077 } catch (DataValidationFailedException | RuntimeException e) {
1078 LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1079 cohort.reportFailure(e);
1081 } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1082 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1085 tip.validate(cohort.getDataTreeModification());
1086 DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1087 cohort.userPreCommit(candidate);
1089 cohort.setNewCandidate(candidate);
1091 } catch (ExecutionException | TimeoutException | RuntimeException | DataValidationFailedException e) {
1092 LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1093 cohort.reportFailure(e);
1099 void setRunOnPendingTransactionsComplete(final Runnable operation) {
1100 runOnPendingTransactionsComplete = operation;
1101 maybeRunOperationOnPendingTransactionsComplete();
1104 private void maybeRunOperationOnPendingTransactionsComplete() {
1105 if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1106 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1107 runOnPendingTransactionsComplete);
1109 runOnPendingTransactionsComplete.run();
1110 runOnPendingTransactionsComplete = null;