2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.datastore;
10 import akka.actor.ActorRef;
11 import akka.util.Timeout;
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.MoreObjects;
14 import com.google.common.base.Optional;
15 import com.google.common.base.Preconditions;
16 import com.google.common.base.Stopwatch;
17 import com.google.common.base.Ticker;
18 import com.google.common.base.Verify;
19 import com.google.common.collect.ImmutableList;
20 import com.google.common.collect.ImmutableMap;
21 import com.google.common.collect.ImmutableMap.Builder;
22 import com.google.common.collect.Iterables;
23 import com.google.common.primitives.UnsignedLong;
24 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
26 import java.io.IOException;
27 import java.util.AbstractMap.SimpleEntry;
28 import java.util.ArrayDeque;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.HashMap;
32 import java.util.Iterator;
34 import java.util.Map.Entry;
35 import java.util.Queue;
36 import java.util.concurrent.ExecutionException;
37 import java.util.concurrent.TimeUnit;
38 import java.util.concurrent.TimeoutException;
39 import java.util.function.Consumer;
40 import java.util.function.UnaryOperator;
41 import javax.annotation.Nonnull;
42 import javax.annotation.Nullable;
43 import javax.annotation.concurrent.NotThreadSafe;
44 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
45 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
46 import org.opendaylight.controller.cluster.datastore.DataTreeCohortActorRegistry.CohortRegistryCommand;
47 import org.opendaylight.controller.cluster.datastore.ShardDataTreeCohort.State;
48 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
49 import org.opendaylight.controller.cluster.datastore.persisted.AbortTransactionPayload;
50 import org.opendaylight.controller.cluster.datastore.persisted.AbstractIdentifiablePayload;
51 import org.opendaylight.controller.cluster.datastore.persisted.CloseLocalHistoryPayload;
52 import org.opendaylight.controller.cluster.datastore.persisted.CommitTransactionPayload;
53 import org.opendaylight.controller.cluster.datastore.persisted.CreateLocalHistoryPayload;
54 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
55 import org.opendaylight.controller.cluster.datastore.persisted.PurgeLocalHistoryPayload;
56 import org.opendaylight.controller.cluster.datastore.persisted.PurgeTransactionPayload;
57 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
58 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshotMetadata;
59 import org.opendaylight.controller.cluster.datastore.utils.DataTreeModificationOutput;
60 import org.opendaylight.controller.cluster.datastore.utils.PruningDataTreeModification;
61 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
62 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
63 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
64 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
65 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
66 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
67 import org.opendaylight.controller.md.sal.dom.store.impl.DataChangeListenerRegistration;
68 import org.opendaylight.yangtools.concepts.Identifier;
69 import org.opendaylight.yangtools.concepts.ListenerRegistration;
70 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
71 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
73 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
74 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
75 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
76 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
77 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
78 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeTip;
79 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
80 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
81 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTreeTip;
82 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
83 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
84 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
85 import org.slf4j.Logger;
86 import org.slf4j.LoggerFactory;
87 import scala.concurrent.duration.Duration;
90 * Internal shard state, similar to a DOMStore, but optimized for use in the actor system,
91 * e.g. it does not expose public interfaces and assumes it is only ever called from a
95 * This class is not part of the API contract and is subject to change at any time.
98 public class ShardDataTree extends ShardDataTreeTransactionParent {
99 private static final class CommitEntry {
100 final SimpleShardDataTreeCohort cohort;
103 CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
104 this.cohort = Preconditions.checkNotNull(cohort);
109 private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(Duration.create(5, TimeUnit.SECONDS));
110 private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
112 private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
114 private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
115 private final Queue<CommitEntry> pendingTransactions = new ArrayDeque<>();
116 private final Queue<CommitEntry> pendingCommits = new ArrayDeque<>();
117 private final Queue<CommitEntry> pendingFinishCommits = new ArrayDeque<>();
120 * Callbacks that need to be invoked once a payload is replicated.
122 private final Map<Payload, Runnable> replicationCallbacks = new HashMap<>();
124 private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
125 private final ShardDataChangeListenerPublisher dataChangeListenerPublisher;
126 private final Collection<ShardDataTreeMetadata<?>> metadata;
127 private final TipProducingDataTree dataTree;
128 private final String logContext;
129 private final Shard shard;
130 private Runnable runOnPendingTransactionsComplete;
133 * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
134 * {@link TipProducingDataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
135 * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
136 * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
138 private TipProducingDataTreeTip tip;
140 private SchemaContext schemaContext;
142 ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TipProducingDataTree dataTree,
143 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
144 final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext,
145 final ShardDataTreeMetadata<?>... metadata) {
146 this.dataTree = Preconditions.checkNotNull(dataTree);
147 updateSchemaContext(schemaContext);
149 this.shard = Preconditions.checkNotNull(shard);
150 this.treeChangeListenerPublisher = Preconditions.checkNotNull(treeChangeListenerPublisher);
151 this.dataChangeListenerPublisher = Preconditions.checkNotNull(dataChangeListenerPublisher);
152 this.logContext = Preconditions.checkNotNull(logContext);
153 this.metadata = ImmutableList.copyOf(metadata);
157 ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType,
158 final YangInstanceIdentifier root,
159 final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
160 final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext,
161 final ShardDataTreeMetadata<?>... metadata) {
162 this(shard, schemaContext, InMemoryDataTreeFactory.getInstance().create(treeType, root),
163 treeChangeListenerPublisher, dataChangeListenerPublisher, logContext, metadata);
167 public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType) {
168 this(shard, schemaContext, treeType, YangInstanceIdentifier.EMPTY,
169 new DefaultShardDataTreeChangeListenerPublisher(), new DefaultShardDataChangeListenerPublisher(), "");
172 final String logContext() {
176 final Ticker ticker() {
177 return shard.ticker();
180 public TipProducingDataTree getDataTree() {
184 SchemaContext getSchemaContext() {
185 return schemaContext;
188 void updateSchemaContext(final SchemaContext newSchemaContext) {
189 dataTree.setSchemaContext(newSchemaContext);
190 this.schemaContext = Preconditions.checkNotNull(newSchemaContext);
194 * Take a snapshot of current state for later recovery.
196 * @return A state snapshot
198 @Nonnull ShardDataTreeSnapshot takeStateSnapshot() {
199 final NormalizedNode<?, ?> rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY).get();
200 final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
201 ImmutableMap.builder();
203 for (ShardDataTreeMetadata<?> m : metadata) {
204 final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
206 metaBuilder.put(meta.getType(), meta);
210 return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
213 private boolean anyPendingTransactions() {
214 return !pendingTransactions.isEmpty() || !pendingCommits.isEmpty() || !pendingFinishCommits.isEmpty();
217 private void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot,
218 final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
219 final Stopwatch elapsed = Stopwatch.createStarted();
221 if (anyPendingTransactions()) {
222 LOG.warn("{}: applying state snapshot with pending transactions", logContext);
225 final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
226 if (snapshot instanceof MetadataShardDataTreeSnapshot) {
227 snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
229 snapshotMeta = ImmutableMap.of();
232 for (ShardDataTreeMetadata<?> m : metadata) {
233 final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
241 final DataTreeModification mod = wrapper.apply(dataTree.takeSnapshot().newModification());
242 // delete everything first
243 mod.delete(YangInstanceIdentifier.EMPTY);
245 final java.util.Optional<NormalizedNode<?, ?>> maybeNode = snapshot.getRootNode();
246 if (maybeNode.isPresent()) {
247 // Add everything from the remote node back
248 mod.write(YangInstanceIdentifier.EMPTY, maybeNode.get());
252 final DataTreeModification unwrapped = unwrap(mod);
253 dataTree.validate(unwrapped);
254 DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
255 dataTree.commit(candidate);
256 notifyListeners(candidate);
258 LOG.debug("{}: state snapshot applied in %s", logContext, elapsed);
262 * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
263 * does not perform any pruning.
265 * @param snapshot Snapshot that needs to be applied
266 * @throws DataValidationFailedException when the snapshot fails to apply
268 void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
269 applySnapshot(snapshot, UnaryOperator.identity());
272 private PruningDataTreeModification wrapWithPruning(final DataTreeModification delegate) {
273 return new PruningDataTreeModification(delegate, dataTree, schemaContext);
276 private static DataTreeModification unwrap(final DataTreeModification modification) {
277 if (modification instanceof PruningDataTreeModification) {
278 return ((PruningDataTreeModification)modification).delegate();
284 * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
285 * pruning in an attempt to adjust the state to our current SchemaContext.
287 * @param snapshot Snapshot that needs to be applied
288 * @throws DataValidationFailedException when the snapshot fails to apply
290 void applyRecoverySnapshot(final @Nonnull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
291 applySnapshot(snapshot, this::wrapWithPruning);
294 @SuppressWarnings("checkstyle:IllegalCatch")
295 private void applyRecoveryCandidate(final DataTreeCandidate candidate) throws DataValidationFailedException {
296 final PruningDataTreeModification mod = wrapWithPruning(dataTree.takeSnapshot().newModification());
297 DataTreeCandidates.applyToModification(mod, candidate);
300 final DataTreeModification unwrapped = mod.delegate();
301 LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
304 dataTree.validate(unwrapped);
305 dataTree.commit(dataTree.prepare(unwrapped));
306 } catch (Exception e) {
307 File file = new File(System.getProperty("karaf.data", "."),
308 "failed-recovery-payload-" + logContext + ".out");
309 DataTreeModificationOutput.toFile(file, unwrapped);
310 throw new IllegalStateException(String.format(
311 "%s: Failed to apply recovery payload. Modification data was written to file %s",
312 logContext, file), e);
317 * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
318 * pruning in an attempt to adjust the state to our current SchemaContext.
320 * @param payload Payload
321 * @throws IOException when the snapshot fails to deserialize
322 * @throws DataValidationFailedException when the snapshot fails to apply
324 void applyRecoveryPayload(final @Nonnull Payload payload) throws IOException, DataValidationFailedException {
325 if (payload instanceof CommitTransactionPayload) {
326 final Entry<TransactionIdentifier, DataTreeCandidate> e =
327 ((CommitTransactionPayload) payload).getCandidate();
328 applyRecoveryCandidate(e.getValue());
329 allMetadataCommittedTransaction(e.getKey());
330 } else if (payload instanceof AbortTransactionPayload) {
331 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
332 } else if (payload instanceof PurgeTransactionPayload) {
333 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
334 } else if (payload instanceof CreateLocalHistoryPayload) {
335 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
336 } else if (payload instanceof CloseLocalHistoryPayload) {
337 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
338 } else if (payload instanceof PurgeLocalHistoryPayload) {
339 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
340 } else if (payload instanceof DataTreeCandidatePayload) {
341 applyRecoveryCandidate(((DataTreeCandidatePayload) payload).getCandidate());
343 LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
347 private void applyReplicatedCandidate(final Identifier identifier, final DataTreeCandidate foreign)
348 throws DataValidationFailedException {
349 LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
351 final DataTreeModification mod = dataTree.takeSnapshot().newModification();
352 DataTreeCandidates.applyToModification(mod, foreign);
355 LOG.trace("{}: Applying foreign modification {}", logContext, mod);
356 dataTree.validate(mod);
357 final DataTreeCandidate candidate = dataTree.prepare(mod);
358 dataTree.commit(candidate);
360 notifyListeners(candidate);
364 * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
365 * SchemaContexts match and does not perform any pruning.
367 * @param identifier Payload identifier as returned from RaftActor
368 * @param payload Payload
369 * @throws IOException when the snapshot fails to deserialize
370 * @throws DataValidationFailedException when the snapshot fails to apply
372 void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
373 DataValidationFailedException {
375 * 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
376 * if we are the leader and it has originated with us.
378 * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
379 * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
380 * acting in that capacity anymore.
382 * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
383 * pre-Boron state -- which limits the number of options here.
385 if (payload instanceof CommitTransactionPayload) {
386 if (identifier == null) {
387 final Entry<TransactionIdentifier, DataTreeCandidate> e =
388 ((CommitTransactionPayload) payload).getCandidate();
389 applyReplicatedCandidate(e.getKey(), e.getValue());
390 allMetadataCommittedTransaction(e.getKey());
392 Verify.verify(identifier instanceof TransactionIdentifier);
393 payloadReplicationComplete((TransactionIdentifier) identifier);
395 } else if (payload instanceof AbortTransactionPayload) {
396 if (identifier != null) {
397 payloadReplicationComplete((AbortTransactionPayload) payload);
399 allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
401 } else if (payload instanceof PurgeTransactionPayload) {
402 if (identifier != null) {
403 payloadReplicationComplete((PurgeTransactionPayload) payload);
405 allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
407 } else if (payload instanceof CloseLocalHistoryPayload) {
408 if (identifier != null) {
409 payloadReplicationComplete((CloseLocalHistoryPayload) payload);
411 allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
413 } else if (payload instanceof CreateLocalHistoryPayload) {
414 if (identifier != null) {
415 payloadReplicationComplete((CreateLocalHistoryPayload)payload);
417 allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
419 } else if (payload instanceof PurgeLocalHistoryPayload) {
420 if (identifier != null) {
421 payloadReplicationComplete((PurgeLocalHistoryPayload)payload);
423 allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
426 LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
430 private void replicatePayload(final Identifier id, final Payload payload, @Nullable final Runnable callback) {
431 if (callback != null) {
432 replicationCallbacks.put(payload, callback);
434 shard.persistPayload(id, payload, true);
437 private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
438 final Runnable callback = replicationCallbacks.remove(payload);
439 if (callback != null) {
440 LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
443 LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
447 private void payloadReplicationComplete(final TransactionIdentifier txId) {
448 final CommitEntry current = pendingFinishCommits.peek();
449 if (current == null) {
450 LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
454 if (!current.cohort.getIdentifier().equals(txId)) {
455 LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
456 current.cohort.getIdentifier(), txId);
460 finishCommit(current.cohort);
463 private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
464 for (ShardDataTreeMetadata<?> m : metadata) {
465 m.onTransactionAborted(txId);
469 private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
470 for (ShardDataTreeMetadata<?> m : metadata) {
471 m.onTransactionCommitted(txId);
475 private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
476 for (ShardDataTreeMetadata<?> m : metadata) {
477 m.onTransactionPurged(txId);
481 private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
482 for (ShardDataTreeMetadata<?> m : metadata) {
483 m.onHistoryCreated(historyId);
487 private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
488 for (ShardDataTreeMetadata<?> m : metadata) {
489 m.onHistoryClosed(historyId);
493 private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
494 for (ShardDataTreeMetadata<?> m : metadata) {
495 m.onHistoryPurged(historyId);
500 * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
501 * this method is used for re-establishing state when we are taking over
503 * @param historyId Local history identifier
504 * @param closed True if the chain should be created in closed state (i.e. pending purge)
505 * @return Transaction chain handle
507 ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
508 final boolean closed) {
509 final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
510 final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
511 Preconditions.checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId,
516 ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId) {
517 ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
519 chain = new ShardDataTreeTransactionChain(historyId, this);
520 transactionChains.put(historyId, chain);
521 shard.persistPayload(historyId, CreateLocalHistoryPayload.create(historyId), true);
527 ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
528 if (txId.getHistoryId().getHistoryId() == 0) {
529 return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
532 return ensureTransactionChain(txId.getHistoryId()).newReadOnlyTransaction(txId);
535 ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
536 if (txId.getHistoryId().getHistoryId() == 0) {
537 return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
541 return ensureTransactionChain(txId.getHistoryId()).newReadWriteTransaction(txId);
545 public void notifyListeners(final DataTreeCandidate candidate) {
546 treeChangeListenerPublisher.publishChanges(candidate, logContext);
547 dataChangeListenerPublisher.publishChanges(candidate, logContext);
550 void notifyOfInitialData(final DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
551 NormalizedNode<?, ?>>> listenerReg, final Optional<DataTreeCandidate> currentState) {
552 if (currentState.isPresent()) {
553 ShardDataChangeListenerPublisher localPublisher = dataChangeListenerPublisher.newInstance();
554 localPublisher.registerDataChangeListener(listenerReg.getPath(), listenerReg.getInstance(),
555 listenerReg.getScope());
556 localPublisher.publishChanges(currentState.get(), logContext);
560 void notifyOfInitialData(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
561 final Optional<DataTreeCandidate> currentState) {
562 if (currentState.isPresent()) {
563 ShardDataTreeChangeListenerPublisher localPublisher = treeChangeListenerPublisher.newInstance();
564 localPublisher.registerTreeChangeListener(path, listener);
565 localPublisher.publishChanges(currentState.get(), logContext);
570 * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
571 * replication callbacks.
573 void purgeLeaderState() {
574 for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
578 transactionChains.clear();
579 replicationCallbacks.clear();
583 * Close a single transaction chain.
585 * @param id History identifier
586 * @param callback Callback to invoke upon completion, may be null
588 void closeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
589 final ShardDataTreeTransactionChain chain = transactionChains.get(id);
591 LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
592 if (callback != null) {
599 replicatePayload(id, CloseLocalHistoryPayload.create(id), callback);
603 * Purge a single transaction chain.
605 * @param id History identifier
606 * @param callback Callback to invoke upon completion, may be null
608 void purgeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
609 final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
611 LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
612 if (callback != null) {
618 replicatePayload(id, PurgeLocalHistoryPayload.create(id), callback);
621 Entry<DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>,
622 Optional<DataTreeCandidate>> registerChangeListener(final YangInstanceIdentifier path,
623 final AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener,
624 final DataChangeScope scope) {
625 DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> reg =
626 dataChangeListenerPublisher.registerDataChangeListener(path, listener, scope);
628 return new SimpleEntry<>(reg, readCurrentData());
631 private Optional<DataTreeCandidate> readCurrentData() {
632 final Optional<NormalizedNode<?, ?>> currentState =
633 dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY);
634 return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
635 YangInstanceIdentifier.EMPTY, currentState.get())) : Optional.<DataTreeCandidate>absent();
638 public Entry<ListenerRegistration<DOMDataTreeChangeListener>, Optional<DataTreeCandidate>>
639 registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener) {
640 final ListenerRegistration<DOMDataTreeChangeListener> reg =
641 treeChangeListenerPublisher.registerTreeChangeListener(path, listener);
643 return new SimpleEntry<>(reg, readCurrentData());
647 return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
651 void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
652 final TransactionIdentifier id = transaction.getIdentifier();
653 LOG.debug("{}: aborting transaction {}", logContext, id);
654 replicatePayload(id, AbortTransactionPayload.create(id), callback);
658 void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
659 // No-op for free-standing transactions
664 ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction) {
665 final DataTreeModification snapshot = transaction.getSnapshot();
668 return createReadyCohort(transaction.getIdentifier(), snapshot);
671 void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
672 LOG.debug("{}: purging transaction {}", logContext, id);
673 replicatePayload(id, PurgeTransactionPayload.create(id), callback);
676 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
677 return dataTree.takeSnapshot().readNode(path);
680 DataTreeSnapshot takeSnapshot() {
681 return dataTree.takeSnapshot();
685 public DataTreeModification newModification() {
686 return dataTree.takeSnapshot().newModification();
690 * Commits a modification.
692 * @deprecated This method violates DataTree containment and will be removed.
696 public DataTreeCandidate commit(final DataTreeModification modification) throws DataValidationFailedException {
697 // Direct modification commit is a utility, which cannot be used while we have transactions in-flight
698 Preconditions.checkState(tip == dataTree, "Cannot modify data tree while transacgitons are pending");
700 modification.ready();
701 dataTree.validate(modification);
702 DataTreeCandidate candidate = dataTree.prepare(modification);
703 dataTree.commit(candidate);
707 public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
708 Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
710 for (CommitEntry entry: pendingFinishCommits) {
711 ret.add(entry.cohort);
714 for (CommitEntry entry: pendingCommits) {
715 ret.add(entry.cohort);
718 for (CommitEntry entry: pendingTransactions) {
719 ret.add(entry.cohort);
722 pendingFinishCommits.clear();
723 pendingCommits.clear();
724 pendingTransactions.clear();
729 @SuppressWarnings("checkstyle:IllegalCatch")
730 private void processNextPendingTransaction() {
731 processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
732 final SimpleShardDataTreeCohort cohort = entry.cohort;
733 final DataTreeModification modification = cohort.getDataTreeModification();
735 LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
738 cohort.throwCanCommitFailure();
740 tip.validate(modification);
741 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
742 cohort.successfulCanCommit();
743 entry.lastAccess = ticker().read();
745 } catch (ConflictingModificationAppliedException e) {
746 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
748 cause = new OptimisticLockFailedException("Optimistic lock failed.", e);
749 } catch (DataValidationFailedException e) {
750 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
753 // For debugging purposes, allow dumping of the modification. Coupled with the above
754 // precondition log, it should allow us to understand what went on.
755 LOG.debug("{}: Store Tx {}: modifications: {} tree: {}", cohort.getIdentifier(), modification,
757 cause = new TransactionCommitFailedException("Data did not pass validation.", e);
758 } catch (Exception e) {
759 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
763 // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
764 pendingTransactions.poll().cohort.failedCanCommit(cause);
768 private void processNextPending() {
769 processNextPendingCommit();
770 processNextPendingTransaction();
773 private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
774 final Consumer<CommitEntry> processor) {
775 while (!queue.isEmpty()) {
776 final CommitEntry entry = queue.peek();
777 final SimpleShardDataTreeCohort cohort = entry.cohort;
779 if (cohort.isFailed()) {
780 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
785 if (cohort.getState() == allowedState) {
786 processor.accept(entry);
792 maybeRunOperationOnPendingTransactionsComplete();
795 private void processNextPendingCommit() {
796 processNextPending(pendingCommits, State.COMMIT_PENDING,
797 entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
800 private boolean peekNextPendingCommit() {
801 final CommitEntry first = pendingCommits.peek();
802 return first != null && first.cohort.getState() == State.COMMIT_PENDING;
805 void startCanCommit(final SimpleShardDataTreeCohort cohort) {
806 final SimpleShardDataTreeCohort current = pendingTransactions.peek().cohort;
807 if (!cohort.equals(current)) {
808 LOG.debug("{}: Transaction {} scheduled for canCommit step", logContext, cohort.getIdentifier());
812 processNextPendingTransaction();
815 private void failPreCommit(final Exception cause) {
816 shard.getShardMBean().incrementFailedTransactionsCount();
817 pendingTransactions.poll().cohort.failedPreCommit(cause);
818 processNextPendingTransaction();
821 @SuppressWarnings("checkstyle:IllegalCatch")
822 void startPreCommit(final SimpleShardDataTreeCohort cohort) {
823 final CommitEntry entry = pendingTransactions.peek();
824 Preconditions.checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
826 final SimpleShardDataTreeCohort current = entry.cohort;
827 Verify.verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
829 LOG.debug("{}: Preparing transaction {}", logContext, current.getIdentifier());
831 final DataTreeCandidateTip candidate;
833 candidate = tip.prepare(cohort.getDataTreeModification());
834 cohort.userPreCommit(candidate);
835 } catch (ExecutionException | TimeoutException | RuntimeException e) {
840 // Set the tip of the data tree.
841 tip = Verify.verifyNotNull(candidate);
843 entry.lastAccess = ticker().read();
845 pendingTransactions.remove();
846 pendingCommits.add(entry);
848 LOG.debug("{}: Transaction {} prepared", logContext, current.getIdentifier());
850 cohort.successfulPreCommit(candidate);
852 processNextPendingTransaction();
855 private void failCommit(final Exception cause) {
856 shard.getShardMBean().incrementFailedTransactionsCount();
857 pendingFinishCommits.poll().cohort.failedCommit(cause);
858 processNextPending();
861 @SuppressWarnings("checkstyle:IllegalCatch")
862 private void finishCommit(final SimpleShardDataTreeCohort cohort) {
863 final TransactionIdentifier txId = cohort.getIdentifier();
864 final DataTreeCandidate candidate = cohort.getCandidate();
866 LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
868 if (tip == candidate) {
869 // All pending candidates have been committed, reset the tip to the data tree.
874 dataTree.commit(candidate);
875 } catch (Exception e) {
876 LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
881 shard.getShardMBean().incrementCommittedTransactionCount();
882 shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
884 // FIXME: propagate journal index
885 pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO);
887 LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
888 notifyListeners(candidate);
890 processNextPending();
893 void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
894 final CommitEntry entry = pendingCommits.peek();
895 Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
897 final SimpleShardDataTreeCohort current = entry.cohort;
898 if (!cohort.equals(current)) {
899 LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
903 LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
905 final TransactionIdentifier txId = cohort.getIdentifier();
906 final Payload payload;
908 payload = CommitTransactionPayload.create(txId, candidate);
909 } catch (IOException e) {
910 LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
911 pendingCommits.poll().cohort.failedCommit(e);
912 processNextPending();
916 // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
917 // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
918 // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
919 // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
920 // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
921 // pendingCommits queue.
922 processNextPendingTransaction();
924 // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
925 // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
926 // in order to properly determine the batchHint flag for the call to persistPayload.
927 pendingCommits.remove();
928 pendingFinishCommits.add(entry);
930 // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
931 // this transaction for replication.
932 boolean replicationBatchHint = peekNextPendingCommit();
934 // Once completed, we will continue via payloadReplicationComplete
935 shard.persistPayload(txId, payload, replicationBatchHint);
937 entry.lastAccess = shard.ticker().read();
939 LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
941 // Process the next transaction pending commit, if any. If there is one it will be batched with this
942 // transaction for replication.
943 processNextPendingCommit();
946 Collection<ActorRef> getCohortActors() {
947 return cohortRegistry.getCohortActors();
950 void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
951 cohortRegistry.process(sender, message);
956 ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
957 final Exception failure) {
958 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort.DeadOnArrival(this, mod, txId, failure);
959 pendingTransactions.add(new CommitEntry(cohort, ticker().read()));
964 ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod) {
965 SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort.Normal(this, mod, txId,
966 cohortRegistry.createCohort(schemaContext, txId, COMMIT_STEP_TIMEOUT));
967 pendingTransactions.add(new CommitEntry(cohort, ticker().read()));
971 @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
972 void checkForExpiredTransactions(final long transactionCommitTimeoutMillis) {
973 final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
974 final long now = ticker().read();
976 final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
977 !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
978 final CommitEntry currentTx = currentQueue.peek();
979 if (currentTx != null && currentTx.lastAccess + timeout < now) {
980 LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
981 currentTx.cohort.getIdentifier(), transactionCommitTimeoutMillis, currentTx.cohort.getState());
982 boolean processNext = true;
983 switch (currentTx.cohort.getState()) {
984 case CAN_COMMIT_PENDING:
985 currentQueue.remove().cohort.failedCanCommit(new TimeoutException());
987 case CAN_COMMIT_COMPLETE:
988 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
989 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
990 // in PRE_COMMIT_COMPLETE is changed.
991 currentQueue.remove().cohort.reportFailure(new TimeoutException());
993 case PRE_COMMIT_PENDING:
994 currentQueue.remove().cohort.failedPreCommit(new TimeoutException());
996 case PRE_COMMIT_COMPLETE:
997 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
998 // are ready we should commit the transaction, not abort it. Our current software stack does
999 // not allow us to do that consistently, because we persist at the time of commit, hence
1000 // we can end up in a state where we have pre-committed a transaction, then a leader failover
1001 // occurred ... the new leader does not see the pre-committed transaction and does not have
1002 // a running timer. To fix this we really need two persistence events.
1004 // The first one, done at pre-commit time will hold the transaction payload. When consensus
1005 // is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1006 // apply the state in this event.
1008 // The second one, done at commit (or abort) time holds only the transaction identifier and
1009 // signals to followers that the state should (or should not) be applied.
1011 // In order to make the pre-commit timer working across failovers, though, we need
1012 // a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1013 // restart the timer.
1014 currentQueue.remove().cohort.reportFailure(new TimeoutException());
1016 case COMMIT_PENDING:
1017 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1018 currentTx.cohort.getIdentifier());
1019 currentTx.lastAccess = now;
1020 processNext = false;
1027 currentQueue.remove();
1031 processNextPending();
1036 boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1037 final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1038 pendingTransactions).iterator();
1039 if (!it.hasNext()) {
1040 LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1044 // First entry is special, as it may already be committing
1045 final CommitEntry first = it.next();
1046 if (cohort.equals(first.cohort)) {
1047 if (cohort.getState() != State.COMMIT_PENDING) {
1048 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1049 cohort.getIdentifier());
1052 if (cohort.getCandidate() != null) {
1053 rebaseTransactions(it, dataTree);
1056 processNextPending();
1060 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1064 TipProducingDataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
1065 while (it.hasNext()) {
1066 final CommitEntry e = it.next();
1067 if (cohort.equals(e.cohort)) {
1068 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1071 if (cohort.getCandidate() != null) {
1072 rebaseTransactions(it, newTip);
1077 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), newTip);
1081 LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1085 @SuppressWarnings("checkstyle:IllegalCatch")
1086 private void rebaseTransactions(final Iterator<CommitEntry> iter, @Nonnull final TipProducingDataTreeTip newTip) {
1087 tip = Preconditions.checkNotNull(newTip);
1088 while (iter.hasNext()) {
1089 final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1090 if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1091 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1094 tip.validate(cohort.getDataTreeModification());
1095 } catch (DataValidationFailedException | RuntimeException e) {
1096 LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1097 cohort.reportFailure(e);
1099 } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1100 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1103 tip.validate(cohort.getDataTreeModification());
1104 DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1105 cohort.userPreCommit(candidate);
1107 cohort.setNewCandidate(candidate);
1109 } catch (ExecutionException | TimeoutException | RuntimeException | DataValidationFailedException e) {
1110 LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1111 cohort.reportFailure(e);
1117 void setRunOnPendingTransactionsComplete(final Runnable operation) {
1118 runOnPendingTransactionsComplete = operation;
1119 maybeRunOperationOnPendingTransactionsComplete();
1122 private void maybeRunOperationOnPendingTransactionsComplete() {
1123 if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1124 LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1125 runOnPendingTransactionsComplete);
1127 runOnPendingTransactionsComplete.run();
1128 runOnPendingTransactionsComplete = null;
1132 ShardStats getStats() {
1133 return shard.getShardMBean();