78b49a60ae5cef444b28633fd9b8fe397d117914
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / ShardDataTree.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.cluster.datastore;
9
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;
25 import java.io.File;
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;
33 import java.util.Map;
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.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.CommitTransactionPayload;
48 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
49 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
50 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshotMetadata;
51 import org.opendaylight.controller.cluster.datastore.utils.DataTreeModificationOutput;
52 import org.opendaylight.controller.cluster.datastore.utils.PruningDataTreeModification;
53 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
54 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
55 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
56 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
57 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
58 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
59 import org.opendaylight.controller.md.sal.dom.store.impl.DataChangeListenerRegistration;
60 import org.opendaylight.yangtools.concepts.Identifier;
61 import org.opendaylight.yangtools.concepts.ListenerRegistration;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
63 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
65 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
66 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
67 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
68 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
69 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
70 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeTip;
71 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
72 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
73 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
74 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTreeTip;
75 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
76 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
77 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
80 import scala.concurrent.duration.Duration;
81
82 /**
83  * Internal shard state, similar to a DOMStore, but optimized for use in the actor system,
84  * e.g. it does not expose public interfaces and assumes it is only ever called from a
85  * single thread.
86  *
87  * <p>
88  * This class is not part of the API contract and is subject to change at any time.
89  */
90 @NotThreadSafe
91 public class ShardDataTree extends ShardDataTreeTransactionParent {
92     private static final class CommitEntry {
93         final SimpleShardDataTreeCohort cohort;
94         long lastAccess;
95
96         CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
97             this.cohort = Preconditions.checkNotNull(cohort);
98             lastAccess = now;
99         }
100     }
101
102     private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(Duration.create(5, TimeUnit.SECONDS));
103     private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
104
105     private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
106     private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
107     private final Queue<CommitEntry> pendingTransactions = new ArrayDeque<>();
108     private final Queue<CommitEntry> pendingCommits = new ArrayDeque<>();
109     private final Queue<CommitEntry> pendingFinishCommits = new ArrayDeque<>();
110     private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
111     private final ShardDataChangeListenerPublisher dataChangeListenerPublisher;
112     private final Collection<ShardDataTreeMetadata<?>> metadata;
113     private final TipProducingDataTree dataTree;
114     private final String logContext;
115     private final Shard shard;
116     private Runnable runOnPendingTransactionsComplete;
117
118     /**
119      * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
120      * {@link TipProducingDataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
121      * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
122      * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
123      */
124     private TipProducingDataTreeTip tip;
125
126     private SchemaContext schemaContext;
127
128     public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TipProducingDataTree dataTree,
129             final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
130             final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext,
131             final ShardDataTreeMetadata<?>... metadata) {
132         this.dataTree = Preconditions.checkNotNull(dataTree);
133         updateSchemaContext(schemaContext);
134
135         this.shard = Preconditions.checkNotNull(shard);
136         this.treeChangeListenerPublisher = Preconditions.checkNotNull(treeChangeListenerPublisher);
137         this.dataChangeListenerPublisher = Preconditions.checkNotNull(dataChangeListenerPublisher);
138         this.logContext = Preconditions.checkNotNull(logContext);
139         this.metadata = ImmutableList.copyOf(metadata);
140         tip = dataTree;
141     }
142
143     public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType,
144             final YangInstanceIdentifier root,
145             final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
146             final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext) {
147         this(shard, schemaContext, InMemoryDataTreeFactory.getInstance().create(treeType, root),
148                 treeChangeListenerPublisher, dataChangeListenerPublisher, logContext);
149     }
150
151     @VisibleForTesting
152     public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType) {
153         this(shard, schemaContext, treeType, YangInstanceIdentifier.EMPTY,
154                 new DefaultShardDataTreeChangeListenerPublisher(),
155                 new DefaultShardDataChangeListenerPublisher(), "");
156     }
157
158     final String logContext() {
159         return logContext;
160     }
161
162     final Ticker ticker() {
163         return shard.ticker();
164     }
165
166     public TipProducingDataTree getDataTree() {
167         return dataTree;
168     }
169
170     SchemaContext getSchemaContext() {
171         return schemaContext;
172     }
173
174     void updateSchemaContext(final SchemaContext newSchemaContext) {
175         dataTree.setSchemaContext(newSchemaContext);
176         this.schemaContext = Preconditions.checkNotNull(newSchemaContext);
177     }
178
179     /**
180      * Take a snapshot of current state for later recovery.
181      *
182      * @return A state snapshot
183      */
184     @Nonnull ShardDataTreeSnapshot takeStateSnapshot() {
185         final NormalizedNode<?, ?> rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY).get();
186         final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
187                 ImmutableMap.builder();
188
189         for (ShardDataTreeMetadata<?> m : metadata) {
190             final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
191             if (meta != null) {
192                 metaBuilder.put(meta.getType(), meta);
193             }
194         }
195
196         return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
197     }
198
199     private boolean anyPendingTransactions() {
200         return !pendingTransactions.isEmpty() || !pendingCommits.isEmpty() || !pendingFinishCommits.isEmpty();
201     }
202
203     private void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot,
204             final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
205         final Stopwatch elapsed = Stopwatch.createStarted();
206
207         if (anyPendingTransactions()) {
208             LOG.warn("{}: applying state snapshot with pending transactions", logContext);
209         }
210
211         final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
212         if (snapshot instanceof MetadataShardDataTreeSnapshot) {
213             snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
214         } else {
215             snapshotMeta = ImmutableMap.of();
216         }
217
218         for (ShardDataTreeMetadata<?> m : metadata) {
219             final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
220             if (s != null) {
221                 m.applySnapshot(s);
222             } else {
223                 m.reset();
224             }
225         }
226
227         final DataTreeModification mod = wrapper.apply(dataTree.takeSnapshot().newModification());
228         // delete everything first
229         mod.delete(YangInstanceIdentifier.EMPTY);
230
231         final java.util.Optional<NormalizedNode<?, ?>> maybeNode = snapshot.getRootNode();
232         if (maybeNode.isPresent()) {
233             // Add everything from the remote node back
234             mod.write(YangInstanceIdentifier.EMPTY, maybeNode.get());
235         }
236         mod.ready();
237
238         final DataTreeModification unwrapped = unwrap(mod);
239         dataTree.validate(unwrapped);
240         DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
241         dataTree.commit(candidate);
242         notifyListeners(candidate);
243
244         LOG.debug("{}: state snapshot applied in %s", logContext, elapsed);
245     }
246
247     /**
248      * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
249      * does not perform any pruning.
250      *
251      * @param snapshot Snapshot that needs to be applied
252      * @throws DataValidationFailedException when the snapshot fails to apply
253      */
254     void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
255         applySnapshot(snapshot, UnaryOperator.identity());
256     }
257
258     private PruningDataTreeModification wrapWithPruning(final DataTreeModification delegate) {
259         return new PruningDataTreeModification(delegate, dataTree, schemaContext);
260     }
261
262     private static DataTreeModification unwrap(final DataTreeModification modification) {
263         if (modification instanceof PruningDataTreeModification) {
264             return ((PruningDataTreeModification)modification).delegate();
265         }
266         return modification;
267     }
268
269     /**
270      * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
271      * pruning in an attempt to adjust the state to our current SchemaContext.
272      *
273      * @param snapshot Snapshot that needs to be applied
274      * @throws DataValidationFailedException when the snapshot fails to apply
275      */
276     void applyRecoverySnapshot(final @Nonnull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
277         applySnapshot(snapshot, this::wrapWithPruning);
278     }
279
280     @SuppressWarnings("checkstyle:IllegalCatch")
281     private void applyRecoveryCandidate(final DataTreeCandidate candidate) throws DataValidationFailedException {
282         final PruningDataTreeModification mod = wrapWithPruning(dataTree.takeSnapshot().newModification());
283         DataTreeCandidates.applyToModification(mod, candidate);
284         mod.ready();
285
286         final DataTreeModification unwrapped = mod.delegate();
287         LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
288
289         try {
290             dataTree.validate(unwrapped);
291             dataTree.commit(dataTree.prepare(unwrapped));
292         } catch (Exception e) {
293             File file = new File(System.getProperty("karaf.data", "."),
294                     "failed-recovery-payload-" + logContext + ".out");
295             DataTreeModificationOutput.toFile(file, unwrapped);
296             throw new IllegalStateException(String.format(
297                     "%s: Failed to apply recovery payload. Modification data was written to file %s",
298                     logContext, file), e);
299         }
300     }
301
302     /**
303      * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
304      * pruning in an attempt to adjust the state to our current SchemaContext.
305      *
306      * @param payload Payload
307      * @throws IOException when the snapshot fails to deserialize
308      * @throws DataValidationFailedException when the snapshot fails to apply
309      */
310     void applyRecoveryPayload(final @Nonnull Payload payload) throws IOException, DataValidationFailedException {
311         if (payload instanceof CommitTransactionPayload) {
312             final Entry<TransactionIdentifier, DataTreeCandidate> e =
313                     ((CommitTransactionPayload) payload).getCandidate();
314             applyRecoveryCandidate(e.getValue());
315             allMetadataCommittedTransaction(e.getKey());
316         } else if (payload instanceof DataTreeCandidatePayload) {
317             applyRecoveryCandidate(((DataTreeCandidatePayload) payload).getCandidate());
318         } else {
319             LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
320         }
321     }
322
323     private void applyReplicatedCandidate(final Identifier identifier, final DataTreeCandidate foreign)
324             throws DataValidationFailedException {
325         LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
326
327         final DataTreeModification mod = dataTree.takeSnapshot().newModification();
328         DataTreeCandidates.applyToModification(mod, foreign);
329         mod.ready();
330
331         LOG.trace("{}: Applying foreign modification {}", logContext, mod);
332         dataTree.validate(mod);
333         final DataTreeCandidate candidate = dataTree.prepare(mod);
334         dataTree.commit(candidate);
335
336         notifyListeners(candidate);
337     }
338
339     /**
340      * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
341      * SchemaContexts match and does not perform any pruning.
342      *
343      * @param identifier Payload identifier as returned from RaftActor
344      * @param payload Payload
345      * @throws IOException when the snapshot fails to deserialize
346      * @throws DataValidationFailedException when the snapshot fails to apply
347      */
348     void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
349             DataValidationFailedException {
350         /*
351          * 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
352          * if we are the leader and it has originated with us.
353          *
354          * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
355          * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
356          * acting in that capacity anymore.
357          *
358          * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
359          * pre-Boron state -- which limits the number of options here.
360          */
361         if (payload instanceof CommitTransactionPayload) {
362             if (identifier == null) {
363                 final Entry<TransactionIdentifier, DataTreeCandidate> e =
364                         ((CommitTransactionPayload) payload).getCandidate();
365                 applyReplicatedCandidate(e.getKey(), e.getValue());
366                 allMetadataCommittedTransaction(e.getKey());
367             } else {
368                 Verify.verify(identifier instanceof TransactionIdentifier);
369                 payloadReplicationComplete((TransactionIdentifier) identifier);
370             }
371         } else {
372             LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
373         }
374     }
375
376     private void payloadReplicationComplete(final TransactionIdentifier txId) {
377         final CommitEntry current = pendingFinishCommits.peek();
378         if (current == null) {
379             LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
380             return;
381         }
382
383         if (!current.cohort.getIdentifier().equals(txId)) {
384             LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
385                 current.cohort.getIdentifier(), txId);
386             return;
387         }
388
389         finishCommit(current.cohort);
390     }
391
392     private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
393         for (ShardDataTreeMetadata<?> m : metadata) {
394             m.onTransactionCommitted(txId);
395         }
396     }
397
398     ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier localHistoryIdentifier) {
399         ShardDataTreeTransactionChain chain = transactionChains.get(localHistoryIdentifier);
400         if (chain == null) {
401             chain = new ShardDataTreeTransactionChain(localHistoryIdentifier, this);
402             transactionChains.put(localHistoryIdentifier, chain);
403         }
404
405         return chain;
406     }
407
408     ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
409         if (txId.getHistoryId().getHistoryId() == 0) {
410             return new ReadOnlyShardDataTreeTransaction(txId, dataTree.takeSnapshot());
411         }
412
413         return ensureTransactionChain(txId.getHistoryId()).newReadOnlyTransaction(txId);
414     }
415
416     ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
417         if (txId.getHistoryId().getHistoryId() == 0) {
418             return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
419                     .newModification());
420         }
421
422         return ensureTransactionChain(txId.getHistoryId()).newReadWriteTransaction(txId);
423     }
424
425     @VisibleForTesting
426     public void notifyListeners(final DataTreeCandidate candidate) {
427         treeChangeListenerPublisher.publishChanges(candidate, logContext);
428         dataChangeListenerPublisher.publishChanges(candidate, logContext);
429     }
430
431     void notifyOfInitialData(final DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
432             NormalizedNode<?, ?>>> listenerReg, final Optional<DataTreeCandidate> currentState) {
433         if (currentState.isPresent()) {
434             ShardDataChangeListenerPublisher localPublisher = dataChangeListenerPublisher.newInstance();
435             localPublisher.registerDataChangeListener(listenerReg.getPath(), listenerReg.getInstance(),
436                     listenerReg.getScope());
437             localPublisher.publishChanges(currentState.get(), logContext);
438         }
439     }
440
441     void notifyOfInitialData(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
442             final Optional<DataTreeCandidate> currentState) {
443         if (currentState.isPresent()) {
444             ShardDataTreeChangeListenerPublisher localPublisher = treeChangeListenerPublisher.newInstance();
445             localPublisher.registerTreeChangeListener(path, listener);
446             localPublisher.publishChanges(currentState.get(), logContext);
447         }
448     }
449
450     void closeAllTransactionChains() {
451         for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
452             chain.close();
453         }
454
455         transactionChains.clear();
456     }
457
458     void closeTransactionChain(final LocalHistoryIdentifier transactionChainId) {
459         final ShardDataTreeTransactionChain chain = transactionChains.remove(transactionChainId);
460         if (chain != null) {
461             chain.close();
462         } else {
463             LOG.debug("{}: Closing non-existent transaction chain {}", logContext, transactionChainId);
464         }
465     }
466
467     Entry<DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>,
468             Optional<DataTreeCandidate>> registerChangeListener(final YangInstanceIdentifier path,
469                     final AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener,
470                     final DataChangeScope scope) {
471         DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> reg =
472                 dataChangeListenerPublisher.registerDataChangeListener(path, listener, scope);
473
474         return new SimpleEntry<>(reg, readCurrentData());
475     }
476
477     private Optional<DataTreeCandidate> readCurrentData() {
478         final Optional<NormalizedNode<?, ?>> currentState =
479                 dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY);
480         return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
481             YangInstanceIdentifier.EMPTY, currentState.get())) : Optional.<DataTreeCandidate>absent();
482     }
483
484     public Entry<ListenerRegistration<DOMDataTreeChangeListener>, Optional<DataTreeCandidate>>
485             registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener) {
486         final ListenerRegistration<DOMDataTreeChangeListener> reg =
487                 treeChangeListenerPublisher.registerTreeChangeListener(path, listener);
488
489         return new SimpleEntry<>(reg, readCurrentData());
490     }
491
492     int getQueueSize() {
493         return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
494     }
495
496     @Override
497     void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction) {
498         // Intentional no-op
499     }
500
501     @Override
502     ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction) {
503         final DataTreeModification snapshot = transaction.getSnapshot();
504         snapshot.ready();
505
506         return createReadyCohort(transaction.getIdentifier(), snapshot);
507     }
508
509     public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
510         return dataTree.takeSnapshot().readNode(path);
511     }
512
513     DataTreeSnapshot takeSnapshot() {
514         return dataTree.takeSnapshot();
515     }
516
517     @VisibleForTesting
518     public DataTreeModification newModification() {
519         return dataTree.takeSnapshot().newModification();
520     }
521
522     /**
523      * Commits a modification.
524      *
525      * @deprecated This method violates DataTree containment and will be removed.
526      */
527     @VisibleForTesting
528     @Deprecated
529     public DataTreeCandidate commit(final DataTreeModification modification) throws DataValidationFailedException {
530         // Direct modification commit is a utility, which cannot be used while we have transactions in-flight
531         Preconditions.checkState(tip == dataTree, "Cannot modify data tree while transacgitons are pending");
532
533         modification.ready();
534         dataTree.validate(modification);
535         DataTreeCandidate candidate = dataTree.prepare(modification);
536         dataTree.commit(candidate);
537         return candidate;
538     }
539
540     public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
541         Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
542
543         for (CommitEntry entry: pendingFinishCommits) {
544             ret.add(entry.cohort);
545         }
546
547         for (CommitEntry entry: pendingCommits) {
548             ret.add(entry.cohort);
549         }
550
551         for (CommitEntry entry: pendingTransactions) {
552             ret.add(entry.cohort);
553         }
554
555         pendingFinishCommits.clear();
556         pendingCommits.clear();
557         pendingTransactions.clear();
558         tip = dataTree;
559         return ret;
560     }
561
562     @SuppressWarnings("checkstyle:IllegalCatch")
563     private void processNextPendingTransaction() {
564         processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
565             final SimpleShardDataTreeCohort cohort = entry.cohort;
566             final DataTreeModification modification = cohort.getDataTreeModification();
567
568             LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
569             Exception cause;
570             try {
571                 tip.validate(modification);
572                 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
573                 cohort.successfulCanCommit();
574                 entry.lastAccess = shard.ticker().read();
575                 return;
576             } catch (ConflictingModificationAppliedException e) {
577                 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
578                     e.getPath());
579                 cause = new OptimisticLockFailedException("Optimistic lock failed.", e);
580             } catch (DataValidationFailedException e) {
581                 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
582                     e.getPath(), e);
583
584                 // For debugging purposes, allow dumping of the modification. Coupled with the above
585                 // precondition log, it should allow us to understand what went on.
586                 LOG.debug("{}: Store Tx {}: modifications: {} tree: {}", cohort.getIdentifier(), modification,
587                         dataTree);
588                 cause = new TransactionCommitFailedException("Data did not pass validation.", e);
589             } catch (Exception e) {
590                 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
591                 cause = e;
592             }
593
594             // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
595             pendingTransactions.poll().cohort.failedCanCommit(cause);
596         });
597     }
598
599     private void processNextPending() {
600         processNextPendingFinishCommit();
601         processNextPendingCommit();
602         processNextPendingTransaction();
603     }
604
605     private void processNextPending(Queue<CommitEntry> queue, State allowedState, Consumer<CommitEntry> processor) {
606         while (!queue.isEmpty()) {
607             final CommitEntry entry = queue.peek();
608             final SimpleShardDataTreeCohort cohort = entry.cohort;
609
610             if (cohort.isFailed()) {
611                 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
612                 queue.remove();
613                 continue;
614             }
615
616             if (cohort.getState() == allowedState) {
617                 processor.accept(entry);
618             }
619
620             break;
621         }
622
623         maybeRunOperationOnPendingTransactionsComplete();
624     }
625
626     private void processNextPendingCommit() {
627         processNextPending(pendingCommits, State.COMMIT_PENDING,
628             entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
629     }
630
631     private void processNextPendingFinishCommit() {
632         processNextPending(pendingFinishCommits, State.FINISH_COMMIT_PENDING,
633             entry -> payloadReplicationComplete(entry.cohort.getIdentifier()));
634     }
635
636     private boolean peekNextPendingCommit() {
637         final CommitEntry first = pendingCommits.peek();
638         return first != null && first.cohort.getState() == State.COMMIT_PENDING;
639     }
640
641     void startCanCommit(final SimpleShardDataTreeCohort cohort) {
642         final SimpleShardDataTreeCohort current = pendingTransactions.peek().cohort;
643         if (!cohort.equals(current)) {
644             LOG.debug("{}: Transaction {} scheduled for canCommit step", logContext, cohort.getIdentifier());
645             return;
646         }
647
648         processNextPendingTransaction();
649     }
650
651     private void failPreCommit(final Exception cause) {
652         shard.getShardMBean().incrementFailedTransactionsCount();
653         pendingTransactions.poll().cohort.failedPreCommit(cause);
654         processNextPendingTransaction();
655     }
656
657     @SuppressWarnings("checkstyle:IllegalCatch")
658     void startPreCommit(final SimpleShardDataTreeCohort cohort) {
659         final CommitEntry entry = pendingTransactions.peek();
660         Preconditions.checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
661
662         final SimpleShardDataTreeCohort current = entry.cohort;
663         Verify.verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
664
665         LOG.debug("{}: Preparing transaction {}", logContext, current.getIdentifier());
666
667         final DataTreeCandidateTip candidate;
668         try {
669             candidate = tip.prepare(cohort.getDataTreeModification());
670             cohort.userPreCommit(candidate);
671         } catch (ExecutionException | TimeoutException | RuntimeException e) {
672             failPreCommit(e);
673             return;
674         }
675
676         // Set the tip of the data tree.
677         tip = Verify.verifyNotNull(candidate);
678
679         entry.lastAccess = shard.ticker().read();
680
681         pendingTransactions.remove();
682         pendingCommits.add(entry);
683
684         LOG.debug("{}: Transaction {} prepared", logContext, current.getIdentifier());
685
686         cohort.successfulPreCommit(candidate);
687
688         processNextPendingTransaction();
689     }
690
691     private void failCommit(final Exception cause) {
692         shard.getShardMBean().incrementFailedTransactionsCount();
693         pendingFinishCommits.poll().cohort.failedCommit(cause);
694         processNextPending();
695     }
696
697     @SuppressWarnings("checkstyle:IllegalCatch")
698     private void finishCommit(final SimpleShardDataTreeCohort cohort) {
699         final TransactionIdentifier txId = cohort.getIdentifier();
700         final DataTreeCandidate candidate = cohort.getCandidate();
701
702         LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
703
704         if (tip == candidate) {
705             // All pending candidates have been committed, reset the tip to the data tree.
706             tip = dataTree;
707         }
708
709         try {
710             dataTree.commit(candidate);
711         } catch (Exception e) {
712             LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
713             failCommit(e);
714             return;
715         }
716
717         shard.getShardMBean().incrementCommittedTransactionCount();
718         shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
719
720         // FIXME: propagate journal index
721         pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO);
722
723         LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
724         notifyListeners(candidate);
725
726         processNextPending();
727     }
728
729     void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
730         final CommitEntry entry = pendingCommits.peek();
731         Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
732
733         final SimpleShardDataTreeCohort current = entry.cohort;
734         if (!cohort.equals(current)) {
735             LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
736             return;
737         }
738
739         LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
740
741         final TransactionIdentifier txId = cohort.getIdentifier();
742         if (shard.canSkipPayload() || candidate.getRootNode().getModificationType() == ModificationType.UNMODIFIED) {
743             LOG.debug("{}: No replication required, proceeding to finish commit", logContext);
744             pendingCommits.remove();
745             pendingFinishCommits.add(entry);
746             cohort.finishCommitPending();
747             payloadReplicationComplete(txId);
748             return;
749         }
750
751         final Payload payload;
752         try {
753             payload = CommitTransactionPayload.create(txId, candidate);
754         } catch (IOException e) {
755             LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
756             pendingCommits.poll().cohort.failedCommit(e);
757             processNextPending();
758             return;
759         }
760
761         // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
762         // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
763         // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
764         // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
765         // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
766         // pendingCommits queue.
767         processNextPendingTransaction();
768
769         // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
770         // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
771         // in order to properly determine the batchHint flag for the call to persistPayload.
772         pendingCommits.remove();
773         pendingFinishCommits.add(entry);
774
775         // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
776         // this transaction for replication.
777         boolean replicationBatchHint = peekNextPendingCommit();
778
779         // Once completed, we will continue via payloadReplicationComplete
780         shard.persistPayload(txId, payload, replicationBatchHint);
781
782         entry.lastAccess = shard.ticker().read();
783
784         LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
785
786         // Process the next transaction pending commit, if any. If there is one it will be batched with this
787         // transaction for replication.
788         processNextPendingCommit();
789     }
790
791     void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
792         cohortRegistry.process(sender, message);
793     }
794
795     @Override
796     ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId,
797             final DataTreeModification modification) {
798         SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, modification, txId,
799                 cohortRegistry.createCohort(schemaContext, txId, COMMIT_STEP_TIMEOUT));
800         pendingTransactions.add(new CommitEntry(cohort, shard.ticker().read()));
801         return cohort;
802     }
803
804     @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
805     void checkForExpiredTransactions(final long transactionCommitTimeoutMillis) {
806         final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
807         final long now = shard.ticker().read();
808
809         final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
810             !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
811         final CommitEntry currentTx = currentQueue.peek();
812         if (currentTx != null && currentTx.lastAccess + timeout < now) {
813             LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
814                     currentTx.cohort.getIdentifier(), transactionCommitTimeoutMillis, currentTx.cohort.getState());
815             boolean processNext = true;
816             switch (currentTx.cohort.getState()) {
817                 case CAN_COMMIT_PENDING:
818                     currentQueue.remove().cohort.failedCanCommit(new TimeoutException());
819                     break;
820                 case CAN_COMMIT_COMPLETE:
821                     // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
822                     // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
823                     // in PRE_COMMIT_COMPLETE is changed.
824                     currentQueue.remove().cohort.reportFailure(new TimeoutException());
825                     break;
826                 case PRE_COMMIT_PENDING:
827                     currentQueue.remove().cohort.failedPreCommit(new TimeoutException());
828                     break;
829                 case PRE_COMMIT_COMPLETE:
830                     // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
831                     //        are ready we should commit the transaction, not abort it. Our current software stack does
832                     //        not allow us to do that consistently, because we persist at the time of commit, hence
833                     //        we can end up in a state where we have pre-committed a transaction, then a leader failover
834                     //        occurred ... the new leader does not see the pre-committed transaction and does not have
835                     //        a running timer. To fix this we really need two persistence events.
836                     //
837                     //        The first one, done at pre-commit time will hold the transaction payload. When consensus
838                     //        is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
839                     //        apply the state in this event.
840                     //
841                     //        The second one, done at commit (or abort) time holds only the transaction identifier and
842                     //        signals to followers that the state should (or should not) be applied.
843                     //
844                     //        In order to make the pre-commit timer working across failovers, though, we need
845                     //        a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
846                     //        restart the timer.
847                     currentQueue.remove().cohort.reportFailure(new TimeoutException());
848                     break;
849                 case COMMIT_PENDING:
850                     LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
851                         currentTx.cohort.getIdentifier());
852                     currentTx.lastAccess = now;
853                     processNext = false;
854                     return;
855                 case ABORTED:
856                 case COMMITTED:
857                 case FAILED:
858                 case READY:
859                 default:
860                     currentQueue.remove();
861             }
862
863             if (processNext) {
864                 processNextPending();
865             }
866         }
867     }
868
869     boolean startAbort(final SimpleShardDataTreeCohort cohort) {
870         final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
871                 pendingTransactions).iterator();
872         if (!it.hasNext()) {
873             LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
874             return true;
875         }
876
877         // First entry is special, as it may already be committing
878         final CommitEntry first = it.next();
879         if (cohort.equals(first.cohort)) {
880             if (cohort.getState() != State.COMMIT_PENDING) {
881                 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
882                     cohort.getIdentifier());
883
884                 it.remove();
885                 if (cohort.getCandidate() != null) {
886                     rebaseTransactions(it, dataTree);
887                 }
888
889                 processNextPending();
890                 return true;
891             }
892
893             LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
894             return false;
895         }
896
897         TipProducingDataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
898         while (it.hasNext()) {
899             final CommitEntry e = it.next();
900             if (cohort.equals(e.cohort)) {
901                 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
902
903                 it.remove();
904                 if (cohort.getCandidate() != null) {
905                     rebaseTransactions(it, newTip);
906                 }
907
908                 return true;
909             } else {
910                 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), newTip);
911             }
912         }
913
914         LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
915         return true;
916     }
917
918     @SuppressWarnings("checkstyle:IllegalCatch")
919     private void rebaseTransactions(Iterator<CommitEntry> iter, @Nonnull TipProducingDataTreeTip newTip) {
920         tip = Preconditions.checkNotNull(newTip);
921         while (iter.hasNext()) {
922             final SimpleShardDataTreeCohort cohort = iter.next().cohort;
923             if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
924                 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
925
926                 try {
927                     tip.validate(cohort.getDataTreeModification());
928                 } catch (DataValidationFailedException | RuntimeException e) {
929                     LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
930                     cohort.reportFailure(e);
931                 }
932             } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
933                 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
934
935                 try {
936                     tip.validate(cohort.getDataTreeModification());
937                     DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
938                     cohort.userPreCommit(candidate);
939
940                     cohort.setNewCandidate(candidate);
941                     tip = candidate;
942                 } catch (ExecutionException | TimeoutException | RuntimeException | DataValidationFailedException e) {
943                     LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
944                     cohort.reportFailure(e);
945                 }
946             }
947         }
948     }
949
950     void setRunOnPendingTransactionsComplete(final Runnable operation) {
951         runOnPendingTransactionsComplete = operation;
952         maybeRunOperationOnPendingTransactionsComplete();
953     }
954
955     private void maybeRunOperationOnPendingTransactionsComplete() {
956         if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
957             LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
958                     runOnPendingTransactionsComplete);
959
960             runOnPendingTransactionsComplete.run();
961             runOnPendingTransactionsComplete = null;
962         }
963     }
964 }