5a7ce80ffd14cf61e4086bd3f3a7e7895f91f60e
[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.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Stopwatch;
16 import com.google.common.base.Verify;
17 import com.google.common.collect.ImmutableList;
18 import com.google.common.collect.ImmutableMap;
19 import com.google.common.collect.ImmutableMap.Builder;
20 import com.google.common.primitives.UnsignedLong;
21 import java.io.File;
22 import java.io.IOException;
23 import java.util.AbstractMap.SimpleEntry;
24 import java.util.ArrayDeque;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.HashMap;
28 import java.util.Iterator;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.Queue;
32 import java.util.concurrent.ExecutionException;
33 import java.util.concurrent.TimeUnit;
34 import java.util.concurrent.TimeoutException;
35 import java.util.function.UnaryOperator;
36 import javax.annotation.Nonnull;
37 import javax.annotation.concurrent.NotThreadSafe;
38 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
39 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
40 import org.opendaylight.controller.cluster.datastore.DataTreeCohortActorRegistry.CohortRegistryCommand;
41 import org.opendaylight.controller.cluster.datastore.ShardDataTreeCohort.State;
42 import org.opendaylight.controller.cluster.datastore.persisted.CommitTransactionPayload;
43 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
44 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
45 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshotMetadata;
46 import org.opendaylight.controller.cluster.datastore.utils.DataTreeModificationOutput;
47 import org.opendaylight.controller.cluster.datastore.utils.PruningDataTreeModification;
48 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
49 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
50 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
51 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
52 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
53 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
54 import org.opendaylight.controller.md.sal.dom.store.impl.DataChangeListenerRegistration;
55 import org.opendaylight.yangtools.concepts.Identifier;
56 import org.opendaylight.yangtools.concepts.ListenerRegistration;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
58 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
60 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
61 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
62 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
63 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
64 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
65 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
66 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
67 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
68 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
69 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
70 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
73 import scala.concurrent.duration.Duration;
74
75 /**
76  * Internal shard state, similar to a DOMStore, but optimized for use in the actor system,
77  * e.g. it does not expose public interfaces and assumes it is only ever called from a
78  * single thread.
79  * <p/>
80  * This class is not part of the API contract and is subject to change at any time.
81  */
82 @NotThreadSafe
83 public class ShardDataTree extends ShardDataTreeTransactionParent {
84     private static final class CommitEntry {
85         final SimpleShardDataTreeCohort cohort;
86         long lastAccess;
87
88         CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
89             this.cohort = Preconditions.checkNotNull(cohort);
90             lastAccess = now;
91         }
92     }
93
94     private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(Duration.create(5, TimeUnit.SECONDS));
95     private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
96
97     private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
98     private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
99     private final Queue<CommitEntry> pendingTransactions = new ArrayDeque<>();
100     private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
101     private final ShardDataChangeListenerPublisher dataChangeListenerPublisher;
102     private final Collection<ShardDataTreeMetadata<?>> metadata;
103     private final TipProducingDataTree dataTree;
104     private final String logContext;
105     private final Shard shard;
106     private Runnable runOnPendingTransactionsComplete;
107
108     private SchemaContext schemaContext;
109
110     public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TipProducingDataTree dataTree,
111             final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
112             final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext,
113             final ShardDataTreeMetadata<?>... metadata) {
114         this.dataTree = Preconditions.checkNotNull(dataTree);
115         updateSchemaContext(schemaContext);
116
117         this.shard = Preconditions.checkNotNull(shard);
118         this.treeChangeListenerPublisher = Preconditions.checkNotNull(treeChangeListenerPublisher);
119         this.dataChangeListenerPublisher = Preconditions.checkNotNull(dataChangeListenerPublisher);
120         this.logContext = Preconditions.checkNotNull(logContext);
121         this.metadata = ImmutableList.copyOf(metadata);
122     }
123
124     public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType,
125             final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
126             final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext) {
127         this(shard, schemaContext, InMemoryDataTreeFactory.getInstance().create(treeType),
128                 treeChangeListenerPublisher, dataChangeListenerPublisher, logContext);
129     }
130
131     @VisibleForTesting
132     public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType) {
133         this(shard, schemaContext, treeType, new DefaultShardDataTreeChangeListenerPublisher(),
134                 new DefaultShardDataChangeListenerPublisher(), "");
135     }
136
137     String logContext() {
138         return logContext;
139     }
140
141     public TipProducingDataTree getDataTree() {
142         return dataTree;
143     }
144
145     SchemaContext getSchemaContext() {
146         return schemaContext;
147     }
148
149     void updateSchemaContext(final SchemaContext newSchemaContext) {
150         dataTree.setSchemaContext(newSchemaContext);
151         this.schemaContext = Preconditions.checkNotNull(newSchemaContext);
152     }
153
154     /**
155      * Take a snapshot of current state for later recovery.
156      *
157      * @return A state snapshot
158      */
159     @Nonnull ShardDataTreeSnapshot takeStateSnapshot() {
160         final NormalizedNode<?, ?> rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY).get();
161         final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
162                 ImmutableMap.builder();
163
164         for (ShardDataTreeMetadata<?> m : metadata) {
165             final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
166             if (meta != null) {
167                 metaBuilder.put(meta.getType(), meta);
168             }
169         }
170
171         return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
172     }
173
174     private void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot,
175             final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
176         final Stopwatch elapsed = Stopwatch.createStarted();
177
178         if (!pendingTransactions.isEmpty()) {
179             LOG.warn("{}: applying state snapshot with pending transactions", logContext);
180         }
181
182         final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
183         if (snapshot instanceof MetadataShardDataTreeSnapshot) {
184             snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
185         } else {
186             snapshotMeta = ImmutableMap.of();
187         }
188
189         for (ShardDataTreeMetadata<?> m : metadata) {
190             final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
191             if (s != null) {
192                 m.applySnapshot(s);
193             } else {
194                 m.reset();
195             }
196         }
197
198         final DataTreeModification mod = wrapper.apply(dataTree.takeSnapshot().newModification());
199         // delete everything first
200         mod.delete(YangInstanceIdentifier.EMPTY);
201
202         final java.util.Optional<NormalizedNode<?, ?>> maybeNode = snapshot.getRootNode();
203         if (maybeNode.isPresent()) {
204             // Add everything from the remote node back
205             mod.write(YangInstanceIdentifier.EMPTY, maybeNode.get());
206         }
207         mod.ready();
208
209         final DataTreeModification unwrapped = unwrap(mod);
210         dataTree.validate(unwrapped);
211         DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
212         dataTree.commit(candidate);
213         notifyListeners(candidate);
214
215         LOG.debug("{}: state snapshot applied in %s", logContext, elapsed);
216     }
217
218     /**
219      * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
220      * does not perform any pruning.
221      *
222      * @param snapshot Snapshot that needs to be applied
223      * @throws DataValidationFailedException when the snapshot fails to apply
224      */
225     void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
226         applySnapshot(snapshot, UnaryOperator.identity());
227     }
228
229     private PruningDataTreeModification wrapWithPruning(final DataTreeModification delegate) {
230         return new PruningDataTreeModification(delegate, dataTree, schemaContext);
231     }
232
233     private static DataTreeModification unwrap(final DataTreeModification modification) {
234         if (modification instanceof PruningDataTreeModification) {
235             return ((PruningDataTreeModification)modification).delegate();
236         }
237         return modification;
238     }
239
240     /**
241      * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
242      * pruning in an attempt to adjust the state to our current SchemaContext.
243      *
244      * @param snapshot Snapshot that needs to be applied
245      * @throws DataValidationFailedException when the snapshot fails to apply
246      */
247     void applyRecoverySnapshot(final @Nonnull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
248         applySnapshot(snapshot, this::wrapWithPruning);
249     }
250
251     @SuppressWarnings("checkstyle:IllegalCatch")
252     private void applyRecoveryCandidate(final DataTreeCandidate candidate) throws DataValidationFailedException {
253         final PruningDataTreeModification mod = wrapWithPruning(dataTree.takeSnapshot().newModification());
254         DataTreeCandidates.applyToModification(mod, candidate);
255         mod.ready();
256
257         final DataTreeModification unwrapped = mod.delegate();
258         LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
259
260         try {
261             dataTree.validate(unwrapped);
262             dataTree.commit(dataTree.prepare(unwrapped));
263         } catch (Exception e) {
264             File file = new File(System.getProperty("karaf.data", "."),
265                     "failed-recovery-payload-" + logContext + ".out");
266             DataTreeModificationOutput.toFile(file, unwrapped);
267             throw new IllegalStateException(String.format(
268                     "%s: Failed to apply recovery payload. Modification data was written to file %s",
269                     logContext, file), e);
270         }
271     }
272
273     /**
274      * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
275      * pruning in an attempt to adjust the state to our current SchemaContext.
276      *
277      * @param payload Payload
278      * @throws IOException when the snapshot fails to deserialize
279      * @throws DataValidationFailedException when the snapshot fails to apply
280      */
281     void applyRecoveryPayload(final @Nonnull Payload payload) throws IOException, DataValidationFailedException {
282         if (payload instanceof CommitTransactionPayload) {
283             final Entry<TransactionIdentifier, DataTreeCandidate> e =
284                     ((CommitTransactionPayload) payload).getCandidate();
285             applyRecoveryCandidate(e.getValue());
286             allMetadataCommittedTransaction(e.getKey());
287         } else if (payload instanceof DataTreeCandidatePayload) {
288             applyRecoveryCandidate(((DataTreeCandidatePayload) payload).getCandidate());
289         } else {
290             LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
291         }
292     }
293
294     private void applyReplicatedCandidate(final Identifier identifier, final DataTreeCandidate foreign)
295             throws DataValidationFailedException {
296         LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
297
298         final DataTreeModification mod = dataTree.takeSnapshot().newModification();
299         DataTreeCandidates.applyToModification(mod, foreign);
300         mod.ready();
301
302         LOG.trace("{}: Applying foreign modification {}", logContext, mod);
303         dataTree.validate(mod);
304         final DataTreeCandidate candidate = dataTree.prepare(mod);
305         dataTree.commit(candidate);
306
307         notifyListeners(candidate);
308     }
309
310     /**
311      * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
312      * SchemaContexts match and does not perform any pruning.
313      *
314      * @param identifier Payload identifier as returned from RaftActor
315      * @param payload Payload
316      * @throws IOException when the snapshot fails to deserialize
317      * @throws DataValidationFailedException when the snapshot fails to apply
318      */
319     void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
320             DataValidationFailedException {
321         /*
322          * 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
323          * if we are the leader and it has originated with us.
324          *
325          * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
326          * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
327          * acting in that capacity anymore.
328          *
329          * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
330          * pre-Boron state -- which limits the number of options here.
331          */
332         if (payload instanceof CommitTransactionPayload) {
333             if (identifier == null) {
334                 final Entry<TransactionIdentifier, DataTreeCandidate> e =
335                         ((CommitTransactionPayload) payload).getCandidate();
336                 applyReplicatedCandidate(e.getKey(), e.getValue());
337                 allMetadataCommittedTransaction(e.getKey());
338             } else {
339                 Verify.verify(identifier instanceof TransactionIdentifier);
340                 payloadReplicationComplete((TransactionIdentifier) identifier);
341             }
342         } else {
343             LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
344         }
345     }
346
347     private void payloadReplicationComplete(final TransactionIdentifier txId) {
348         final CommitEntry current = pendingTransactions.peek();
349         if (current == null) {
350             LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
351             return;
352         }
353
354         if (!current.cohort.getIdentifier().equals(txId)) {
355             LOG.warn("{}: Head of queue is {}, ignoring consensus on transaction {}", logContext,
356                 current.cohort.getIdentifier(), txId);
357             return;
358         }
359
360         finishCommit(current.cohort);
361     }
362
363     private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
364         for (ShardDataTreeMetadata<?> m : metadata) {
365             m.onTransactionCommitted(txId);
366         }
367     }
368
369     private ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier localHistoryIdentifier) {
370         ShardDataTreeTransactionChain chain = transactionChains.get(localHistoryIdentifier);
371         if (chain == null) {
372             chain = new ShardDataTreeTransactionChain(localHistoryIdentifier, this);
373             transactionChains.put(localHistoryIdentifier, chain);
374         }
375
376         return chain;
377     }
378
379     ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
380         if (txId.getHistoryId().getHistoryId() == 0) {
381             return new ReadOnlyShardDataTreeTransaction(txId, dataTree.takeSnapshot());
382         }
383
384         return ensureTransactionChain(txId.getHistoryId()).newReadOnlyTransaction(txId);
385     }
386
387     ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
388         if (txId.getHistoryId().getHistoryId() == 0) {
389             return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
390                     .newModification());
391         }
392
393         return ensureTransactionChain(txId.getHistoryId()).newReadWriteTransaction(txId);
394     }
395
396     @VisibleForTesting
397     public void notifyListeners(final DataTreeCandidate candidate) {
398         treeChangeListenerPublisher.publishChanges(candidate, logContext);
399         dataChangeListenerPublisher.publishChanges(candidate, logContext);
400     }
401
402     void notifyOfInitialData(final DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
403             NormalizedNode<?, ?>>> listenerReg, final Optional<DataTreeCandidate> currentState) {
404         if (currentState.isPresent()) {
405             ShardDataChangeListenerPublisher localPublisher = dataChangeListenerPublisher.newInstance();
406             localPublisher.registerDataChangeListener(listenerReg.getPath(), listenerReg.getInstance(),
407                     listenerReg.getScope());
408             localPublisher.publishChanges(currentState.get(), logContext);
409         }
410     }
411
412     void notifyOfInitialData(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
413             final Optional<DataTreeCandidate> currentState) {
414         if (currentState.isPresent()) {
415             ShardDataTreeChangeListenerPublisher localPublisher = treeChangeListenerPublisher.newInstance();
416             localPublisher.registerTreeChangeListener(path, listener);
417             localPublisher.publishChanges(currentState.get(), logContext);
418         }
419     }
420
421     void closeAllTransactionChains() {
422         for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
423             chain.close();
424         }
425
426         transactionChains.clear();
427     }
428
429     void closeTransactionChain(final LocalHistoryIdentifier transactionChainId) {
430         final ShardDataTreeTransactionChain chain = transactionChains.remove(transactionChainId);
431         if (chain != null) {
432             chain.close();
433         } else {
434             LOG.debug("{}: Closing non-existent transaction chain {}", logContext, transactionChainId);
435         }
436     }
437
438     Entry<DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>,
439             Optional<DataTreeCandidate>> registerChangeListener(final YangInstanceIdentifier path,
440                     final AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener,
441                     final DataChangeScope scope) {
442         DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> reg =
443                 dataChangeListenerPublisher.registerDataChangeListener(path, listener, scope);
444
445         return new SimpleEntry<>(reg, readCurrentData());
446     }
447
448     private Optional<DataTreeCandidate> readCurrentData() {
449         final Optional<NormalizedNode<?, ?>> currentState =
450                 dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY);
451         return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
452             YangInstanceIdentifier.EMPTY, currentState.get())) : Optional.<DataTreeCandidate>absent();
453     }
454
455     public Entry<ListenerRegistration<DOMDataTreeChangeListener>, Optional<DataTreeCandidate>>
456             registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener) {
457         final ListenerRegistration<DOMDataTreeChangeListener> reg =
458                 treeChangeListenerPublisher.registerTreeChangeListener(path, listener);
459
460         return new SimpleEntry<>(reg, readCurrentData());
461     }
462
463     int getQueueSize() {
464         return pendingTransactions.size();
465     }
466
467     @Override
468     void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction) {
469         // Intentional no-op
470     }
471
472     @Override
473     ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction) {
474         final DataTreeModification snapshot = transaction.getSnapshot();
475         snapshot.ready();
476
477         return createReadyCohort(transaction.getId(), snapshot);
478     }
479
480     public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
481         return dataTree.takeSnapshot().readNode(path);
482     }
483
484     DataTreeSnapshot takeSnapshot() {
485         return dataTree.takeSnapshot();
486     }
487
488     @VisibleForTesting
489     public DataTreeModification newModification() {
490         return dataTree.takeSnapshot().newModification();
491     }
492
493     /**
494      * Commits a modification.
495      *
496      * @deprecated This method violates DataTree containment and will be removed.
497      */
498     @VisibleForTesting
499     @Deprecated
500     public DataTreeCandidate commit(final DataTreeModification modification) throws DataValidationFailedException {
501         modification.ready();
502         dataTree.validate(modification);
503         DataTreeCandidate candidate = dataTree.prepare(modification);
504         dataTree.commit(candidate);
505         return candidate;
506     }
507
508     public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
509         Collection<ShardDataTreeCohort> ret = new ArrayList<>(pendingTransactions.size());
510         for (CommitEntry entry: pendingTransactions) {
511             ret.add(entry.cohort);
512         }
513
514         pendingTransactions.clear();
515         return ret;
516     }
517
518     @SuppressWarnings("checkstyle:IllegalCatch")
519     private void processNextTransaction() {
520         while (!pendingTransactions.isEmpty()) {
521             final CommitEntry entry = pendingTransactions.peek();
522             final SimpleShardDataTreeCohort cohort = entry.cohort;
523             final DataTreeModification modification = cohort.getDataTreeModification();
524
525             if (cohort.getState() != State.CAN_COMMIT_PENDING) {
526                 break;
527             }
528
529             LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
530             Exception cause;
531             try {
532                 dataTree.validate(modification);
533                 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
534                 cohort.successfulCanCommit();
535                 entry.lastAccess = shard.ticker().read();
536                 return;
537             } catch (ConflictingModificationAppliedException e) {
538                 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
539                     e.getPath());
540                 cause = new OptimisticLockFailedException("Optimistic lock failed.", e);
541             } catch (DataValidationFailedException e) {
542                 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
543                     e.getPath(), e);
544
545                 // For debugging purposes, allow dumping of the modification. Coupled with the above
546                 // precondition log, it should allow us to understand what went on.
547                 LOG.debug("{}: Store Tx {}: modifications: {} tree: {}", cohort.getIdentifier(), modification,
548                         dataTree);
549                 cause = new TransactionCommitFailedException("Data did not pass validation.", e);
550             } catch (Exception e) {
551                 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
552                 cause = e;
553             }
554
555             // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
556             pendingTransactions.poll().cohort.failedCanCommit(cause);
557         }
558
559         maybeRunOperationOnPendingTransactionsComplete();
560     }
561
562     void startCanCommit(final SimpleShardDataTreeCohort cohort) {
563         final SimpleShardDataTreeCohort current = pendingTransactions.peek().cohort;
564         if (!cohort.equals(current)) {
565             LOG.debug("{}: Transaction {} scheduled for canCommit step", logContext, cohort.getIdentifier());
566             return;
567         }
568
569         processNextTransaction();
570     }
571
572     private void failPreCommit(final Exception cause) {
573         shard.getShardMBean().incrementFailedTransactionsCount();
574         pendingTransactions.poll().cohort.failedPreCommit(cause);
575         processNextTransaction();
576     }
577
578     @SuppressWarnings("checkstyle:IllegalCatch")
579     void startPreCommit(final SimpleShardDataTreeCohort cohort) {
580         final CommitEntry entry = pendingTransactions.peek();
581         Preconditions.checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
582
583         final SimpleShardDataTreeCohort current = entry.cohort;
584         Verify.verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
585         final DataTreeCandidateTip candidate;
586         try {
587             candidate = dataTree.prepare(cohort.getDataTreeModification());
588         } catch (Exception e) {
589             failPreCommit(e);
590             return;
591         }
592
593         try {
594             cohort.userPreCommit(candidate);
595         } catch (ExecutionException | TimeoutException e) {
596             failPreCommit(e);
597             return;
598         }
599
600         entry.lastAccess = shard.ticker().read();
601         cohort.successfulPreCommit(candidate);
602     }
603
604     private void failCommit(final Exception cause) {
605         shard.getShardMBean().incrementFailedTransactionsCount();
606         pendingTransactions.poll().cohort.failedCommit(cause);
607         processNextTransaction();
608     }
609
610     @SuppressWarnings("checkstyle:IllegalCatch")
611     private void finishCommit(final SimpleShardDataTreeCohort cohort) {
612         final TransactionIdentifier txId = cohort.getIdentifier();
613         final DataTreeCandidate candidate = cohort.getCandidate();
614
615         LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
616
617         try {
618             dataTree.commit(candidate);
619         } catch (Exception e) {
620             LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
621             failCommit(e);
622             return;
623         }
624
625         shard.getShardMBean().incrementCommittedTransactionCount();
626         shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
627
628         // FIXME: propagate journal index
629         pendingTransactions.poll().cohort.successfulCommit(UnsignedLong.ZERO);
630
631         LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
632         notifyListeners(candidate);
633
634         processNextTransaction();
635     }
636
637     void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
638         final CommitEntry entry = pendingTransactions.peek();
639         Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
640
641         final SimpleShardDataTreeCohort current = entry.cohort;
642         Verify.verify(cohort.equals(current), "Attempted to commit %s while %s is pending", cohort, current);
643
644         if (shard.canSkipPayload() || candidate.getRootNode().getModificationType() == ModificationType.UNMODIFIED) {
645             LOG.debug("{}: No replication required, proceeding to finish commit", logContext);
646             finishCommit(cohort);
647             return;
648         }
649
650         final TransactionIdentifier txId = cohort.getIdentifier();
651         final Payload payload;
652         try {
653             payload = CommitTransactionPayload.create(txId, candidate);
654         } catch (IOException e) {
655             LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
656             pendingTransactions.poll().cohort.failedCommit(e);
657             return;
658         }
659
660         // Once completed, we will continue via payloadReplicationComplete
661         entry.lastAccess = shard.ticker().read();
662         shard.persistPayload(txId, payload);
663         LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
664     }
665
666     void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
667         cohortRegistry.process(sender, message);
668     }
669
670     ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId,
671             final DataTreeModification modification) {
672         SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, modification, txId,
673                 cohortRegistry.createCohort(schemaContext, txId, COMMIT_STEP_TIMEOUT));
674         pendingTransactions.add(new CommitEntry(cohort, shard.ticker().read()));
675         return cohort;
676     }
677
678     void checkForExpiredTransactions(final long transactionCommitTimeoutMillis) {
679         final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
680         final long now = shard.ticker().read();
681         final CommitEntry currentTx = pendingTransactions.peek();
682         if (currentTx != null && currentTx.lastAccess + timeout < now) {
683             LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
684                     currentTx.cohort.getIdentifier(), transactionCommitTimeoutMillis, currentTx.cohort.getState());
685             boolean processNext = true;
686             switch (currentTx.cohort.getState()) {
687                 case CAN_COMMIT_PENDING:
688                     pendingTransactions.poll().cohort.failedCanCommit(new TimeoutException());
689                     break;
690                 case CAN_COMMIT_COMPLETE:
691                     pendingTransactions.poll().cohort.reportFailure(new TimeoutException());
692                     break;
693                 case PRE_COMMIT_PENDING:
694                     pendingTransactions.poll().cohort.failedPreCommit(new TimeoutException());
695                     break;
696                 case PRE_COMMIT_COMPLETE:
697                     // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
698                     //        are ready we should commit the transaction, not abort it. Our current software stack does
699                     //        not allow us to do that consistently, because we persist at the time of commit, hence
700                     //        we can end up in a state where we have pre-committed a transaction, then a leader failover
701                     //        occurred ... the new leader does not see the pre-committed transaction and does not have
702                     //        a running timer. To fix this we really need two persistence events.
703                     //
704                     //        The first one, done at pre-commit time will hold the transaction payload. When consensus
705                     //        is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
706                     //        apply the state in this event.
707                     //
708                     //        The second one, done at commit (or abort) time holds only the transaction identifier and
709                     //        signals to followers that the state should (or should not) be applied.
710                     //
711                     //        In order to make the pre-commit timer working across failovers, though, we need
712                     //        a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
713                     //        restart the timer.
714                     pendingTransactions.poll().cohort.reportFailure(new TimeoutException());
715                     break;
716                 case COMMIT_PENDING:
717                     LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
718                         currentTx.cohort.getIdentifier());
719                     currentTx.lastAccess = now;
720                     processNext = false;
721                     return;
722                 case ABORTED:
723                 case COMMITTED:
724                 case FAILED:
725                 case READY:
726                 default:
727                     pendingTransactions.poll();
728             }
729
730             if (processNext) {
731                 processNextTransaction();
732             }
733         }
734     }
735
736     void startAbort(final SimpleShardDataTreeCohort cohort) {
737         final Iterator<CommitEntry> it = pendingTransactions.iterator();
738         if (!it.hasNext()) {
739             LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
740             return;
741         }
742
743         // First entry is special, as it may already be committing
744         final CommitEntry first = it.next();
745         if (cohort.equals(first.cohort)) {
746             if (cohort.getState() != State.COMMIT_PENDING) {
747                 LOG.debug("{}: aborted head of queue {} in state {}", logContext, cohort.getIdentifier(),
748                     cohort.getIdentifier());
749                 pendingTransactions.poll();
750                 processNextTransaction();
751             } else {
752                 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
753             }
754
755             return;
756         }
757
758         while (it.hasNext()) {
759             final CommitEntry e = it.next();
760             if (cohort.equals(e.cohort)) {
761                 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
762                 it.remove();
763                 return;
764             }
765         }
766
767         LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
768     }
769
770     void setRunOnPendingTransactionsComplete(final Runnable operation) {
771         runOnPendingTransactionsComplete = operation;
772         maybeRunOperationOnPendingTransactionsComplete();
773     }
774
775     private void maybeRunOperationOnPendingTransactionsComplete() {
776         if (runOnPendingTransactionsComplete != null && pendingTransactions.isEmpty()) {
777             LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
778                     runOnPendingTransactionsComplete);
779
780             runOnPendingTransactionsComplete.run();
781             runOnPendingTransactionsComplete = null;
782         }
783     }
784 }