72ca1aebd8e1723a2a0c86de0ed2a9e7d250d544
[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  *
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 schemaContext) {
150         dataTree.setSchemaContext(schemaContext);
151         this.schemaContext = Preconditions.checkNotNull(schemaContext);
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(final @Nonnull 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         dataTree.commit(dataTree.prepare(unwrapped));
212         LOG.debug("{}: state snapshot applied in %s", logContext, elapsed);
213     }
214
215     private PruningDataTreeModification wrapWithPruning(final DataTreeModification delegate) {
216         return new PruningDataTreeModification(delegate, dataTree, schemaContext);
217     }
218
219     private static DataTreeModification unwrap(final DataTreeModification modification) {
220         if (modification instanceof PruningDataTreeModification) {
221             return ((PruningDataTreeModification)modification).delegate();
222         }
223         return modification;
224     }
225
226     /**
227      * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
228      * pruning in an attempt to adjust the state to our current SchemaContext.
229      *
230      * @param snapshot Snapshot that needs to be applied
231      * @throws DataValidationFailedException when the snapshot fails to apply
232      */
233     void applyRecoverySnapshot(final @Nonnull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
234         applySnapshot(snapshot, this::wrapWithPruning);
235     }
236
237
238     /**
239      * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
240      * does not perform any pruning.
241      *
242      * @param snapshot Snapshot that needs to be applied
243      * @throws DataValidationFailedException when the snapshot fails to apply
244      */
245     void applySnapshot(final @Nonnull ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
246         applySnapshot(snapshot, UnaryOperator.identity());
247     }
248
249     private void applyRecoveryCandidate(final DataTreeCandidate candidate) throws DataValidationFailedException {
250         final PruningDataTreeModification mod = wrapWithPruning(dataTree.takeSnapshot().newModification());
251         DataTreeCandidates.applyToModification(mod, candidate);
252         mod.ready();
253
254         final DataTreeModification unwrapped = mod.delegate();
255         LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
256
257         try {
258             dataTree.validate(unwrapped);
259             dataTree.commit(dataTree.prepare(unwrapped));
260         } catch (Exception e) {
261             File file = new File(System.getProperty("karaf.data", "."),
262                     "failed-recovery-payload-" + logContext + ".out");
263             DataTreeModificationOutput.toFile(file, unwrapped);
264             throw new IllegalStateException(String.format(
265                     "%s: Failed to apply recovery payload. Modification data was written to file %s",
266                     logContext, file), e);
267         }
268     }
269
270     /**
271      * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
272      * pruning in an attempt to adjust the state to our current SchemaContext.
273      *
274      * @param payload Payload
275      * @throws IOException when the snapshot fails to deserialize
276      * @throws DataValidationFailedException when the snapshot fails to apply
277      */
278     void applyRecoveryPayload(final @Nonnull Payload payload) throws IOException, DataValidationFailedException {
279         if (payload instanceof CommitTransactionPayload) {
280             final Entry<TransactionIdentifier, DataTreeCandidate> e = ((CommitTransactionPayload) payload).getCandidate();
281             applyRecoveryCandidate(e.getValue());
282             allMetadataCommittedTransaction(e.getKey());
283         } else if (payload instanceof DataTreeCandidatePayload) {
284             applyRecoveryCandidate(((DataTreeCandidatePayload) payload).getCandidate());
285         } else {
286             LOG.warn("{}: ignoring unhandled payload {}", logContext, payload);
287         }
288     }
289
290     private void applyReplicatedCandidate(final Identifier identifier, final DataTreeCandidate foreign)
291             throws DataValidationFailedException {
292         LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
293
294         final DataTreeModification mod = dataTree.takeSnapshot().newModification();
295         DataTreeCandidates.applyToModification(mod, foreign);
296         mod.ready();
297
298         LOG.trace("{}: Applying foreign modification {}", logContext, mod);
299         dataTree.validate(mod);
300         final DataTreeCandidate candidate = dataTree.prepare(mod);
301         dataTree.commit(candidate);
302
303         notifyListeners(candidate);
304     }
305
306     /**
307      * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
308      * SchemaContexts match and does not perform any pruning.
309      *
310      * @param identifier Payload identifier as returned from RaftActor
311      * @param payload Payload
312      * @throws IOException when the snapshot fails to deserialize
313      * @throws DataValidationFailedException when the snapshot fails to apply
314      */
315     void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
316             DataValidationFailedException {
317         /*
318          * This is a bit more involved than it needs to be due to to the fact we do not want to be touching the payload
319          * if we are the leader and it has originated with us.
320          *
321          * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
322          * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
323          * acting in that capacity anymore.
324          *
325          * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
326          * pre-Boron state -- which limits the number of options here.
327          */
328         if (payload instanceof CommitTransactionPayload) {
329             if (identifier == null) {
330                 final Entry<TransactionIdentifier, DataTreeCandidate> e = ((CommitTransactionPayload) payload).getCandidate();
331                 applyReplicatedCandidate(e.getKey(), e.getValue());
332                 allMetadataCommittedTransaction(e.getKey());
333             } else {
334                 Verify.verify(identifier instanceof TransactionIdentifier);
335                 payloadReplicationComplete((TransactionIdentifier) identifier);
336             }
337         } else {
338             LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
339         }
340     }
341
342     private void payloadReplicationComplete(final TransactionIdentifier txId) {
343         final CommitEntry current = pendingTransactions.peek();
344         if (current == null) {
345             LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
346             return;
347         }
348
349         if (!current.cohort.getIdentifier().equals(txId)) {
350             LOG.warn("{}: Head of queue is {}, ignoring consensus on transaction {}", logContext,
351                 current.cohort.getIdentifier(), txId);
352             return;
353         }
354
355         finishCommit(current.cohort);
356     }
357
358     private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
359         for (ShardDataTreeMetadata<?> m : metadata) {
360             m.onTransactionCommitted(txId);
361         }
362     }
363
364     private ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier localHistoryIdentifier) {
365         ShardDataTreeTransactionChain chain = transactionChains.get(localHistoryIdentifier);
366         if (chain == null) {
367             chain = new ShardDataTreeTransactionChain(localHistoryIdentifier, this);
368             transactionChains.put(localHistoryIdentifier, chain);
369         }
370
371         return chain;
372     }
373
374     ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
375         if (txId.getHistoryId().getHistoryId() == 0) {
376             return new ReadOnlyShardDataTreeTransaction(txId, dataTree.takeSnapshot());
377         }
378
379         return ensureTransactionChain(txId.getHistoryId()).newReadOnlyTransaction(txId);
380     }
381
382     ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
383         if (txId.getHistoryId().getHistoryId() == 0) {
384             return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
385                     .newModification());
386         }
387
388         return ensureTransactionChain(txId.getHistoryId()).newReadWriteTransaction(txId);
389     }
390
391     public void notifyListeners(final DataTreeCandidate candidate) {
392         treeChangeListenerPublisher.publishChanges(candidate, logContext);
393         dataChangeListenerPublisher.publishChanges(candidate, logContext);
394     }
395
396     void notifyOfInitialData(final DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
397             NormalizedNode<?, ?>>> listenerReg, final Optional<DataTreeCandidate> currentState) {
398         if (currentState.isPresent()) {
399             ShardDataChangeListenerPublisher localPublisher = dataChangeListenerPublisher.newInstance();
400             localPublisher.registerDataChangeListener(listenerReg.getPath(), listenerReg.getInstance(),
401                     listenerReg.getScope());
402             localPublisher.publishChanges(currentState.get(), logContext);
403         }
404     }
405
406     void notifyOfInitialData(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
407             final Optional<DataTreeCandidate> currentState) {
408         if (currentState.isPresent()) {
409             ShardDataTreeChangeListenerPublisher localPublisher = treeChangeListenerPublisher.newInstance();
410             localPublisher.registerTreeChangeListener(path, listener);
411             localPublisher.publishChanges(currentState.get(), logContext);
412         }
413     }
414
415     void closeAllTransactionChains() {
416         for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
417             chain.close();
418         }
419
420         transactionChains.clear();
421     }
422
423     void closeTransactionChain(final LocalHistoryIdentifier transactionChainId) {
424         final ShardDataTreeTransactionChain chain = transactionChains.remove(transactionChainId);
425         if (chain != null) {
426             chain.close();
427         } else {
428             LOG.debug("{}: Closing non-existent transaction chain {}", logContext, transactionChainId);
429         }
430     }
431
432     Entry<DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>,
433             Optional<DataTreeCandidate>> registerChangeListener(final YangInstanceIdentifier path,
434                     final AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener,
435                     final DataChangeScope scope) {
436         final DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> reg =
437                 dataChangeListenerPublisher.registerDataChangeListener(path, listener, scope);
438
439         return new SimpleEntry<>(reg, readCurrentData());
440     }
441
442     private Optional<DataTreeCandidate> readCurrentData() {
443         final Optional<NormalizedNode<?, ?>> currentState = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY);
444         return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
445             YangInstanceIdentifier.EMPTY, currentState.get())) : Optional.<DataTreeCandidate>absent();
446     }
447
448     public Entry<ListenerRegistration<DOMDataTreeChangeListener>, Optional<DataTreeCandidate>> registerTreeChangeListener(
449             final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener) {
450         final ListenerRegistration<DOMDataTreeChangeListener> reg = treeChangeListenerPublisher.registerTreeChangeListener(
451                 path, listener);
452
453         return new SimpleEntry<>(reg, readCurrentData());
454     }
455
456     int getQueueSize() {
457         return pendingTransactions.size();
458     }
459
460     @Override
461     void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction) {
462         // Intentional no-op
463     }
464
465     @Override
466     ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction) {
467         final DataTreeModification snapshot = transaction.getSnapshot();
468         snapshot.ready();
469
470         return createReadyCohort(transaction.getId(), snapshot);
471     }
472
473     public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
474         return dataTree.takeSnapshot().readNode(path);
475     }
476
477     public DataTreeSnapshot takeSnapshot() {
478         return dataTree.takeSnapshot();
479     }
480
481     public DataTreeModification newModification() {
482         return dataTree.takeSnapshot().newModification();
483     }
484
485     /**
486      * @deprecated This method violates DataTree containment and will be removed.
487      */
488     @VisibleForTesting
489     @Deprecated
490     public DataTreeCandidate commit(final DataTreeModification modification) throws DataValidationFailedException {
491         modification.ready();
492         dataTree.validate(modification);
493         DataTreeCandidate candidate = dataTree.prepare(modification);
494         dataTree.commit(candidate);
495         return candidate;
496     }
497
498     public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
499         Collection<ShardDataTreeCohort> ret = new ArrayList<>(pendingTransactions.size());
500         for(CommitEntry entry: pendingTransactions) {
501             ret.add(entry.cohort);
502         }
503
504         pendingTransactions.clear();
505         return ret;
506     }
507
508     private void processNextTransaction() {
509         while (!pendingTransactions.isEmpty()) {
510             final CommitEntry entry = pendingTransactions.peek();
511             final SimpleShardDataTreeCohort cohort = entry.cohort;
512             final DataTreeModification modification = cohort.getDataTreeModification();
513
514             if(cohort.getState() != State.CAN_COMMIT_PENDING) {
515                 break;
516             }
517
518             LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
519             Exception cause;
520             try {
521                 dataTree.validate(modification);
522                 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
523                 cohort.successfulCanCommit();
524                 entry.lastAccess = shard.ticker().read();
525                 return;
526             } catch (ConflictingModificationAppliedException e) {
527                 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
528                     e.getPath());
529                 cause = new OptimisticLockFailedException("Optimistic lock failed.", e);
530             } catch (DataValidationFailedException e) {
531                 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
532                     e.getPath(), e);
533
534                 // For debugging purposes, allow dumping of the modification. Coupled with the above
535                 // precondition log, it should allow us to understand what went on.
536                 LOG.debug("{}: Store Tx {}: modifications: {} tree: {}", cohort.getIdentifier(), modification, dataTree);
537                 cause = new TransactionCommitFailedException("Data did not pass validation.", e);
538             } catch (Exception e) {
539                 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
540                 cause = e;
541             }
542
543             // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
544             pendingTransactions.poll().cohort.failedCanCommit(cause);
545         }
546
547         maybeRunOperationOnPendingTransactionsComplete();
548     }
549
550     void startCanCommit(final SimpleShardDataTreeCohort cohort) {
551         final SimpleShardDataTreeCohort current = pendingTransactions.peek().cohort;
552         if (!cohort.equals(current)) {
553             LOG.debug("{}: Transaction {} scheduled for canCommit step", logContext, cohort.getIdentifier());
554             return;
555         }
556
557         processNextTransaction();
558     }
559
560     private void failPreCommit(final Exception cause) {
561         shard.getShardMBean().incrementFailedTransactionsCount();
562         pendingTransactions.poll().cohort.failedPreCommit(cause);
563         processNextTransaction();
564     }
565
566     void startPreCommit(final SimpleShardDataTreeCohort cohort) {
567         final CommitEntry entry = pendingTransactions.peek();
568         Preconditions.checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
569
570         final SimpleShardDataTreeCohort current = entry.cohort;
571         Verify.verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
572         final DataTreeCandidateTip candidate;
573         try {
574             candidate = dataTree.prepare(cohort.getDataTreeModification());
575         } catch (Exception e) {
576             failPreCommit(e);
577             return;
578         }
579
580         try {
581             cohort.userPreCommit(candidate);
582         } catch (ExecutionException | TimeoutException e) {
583             failPreCommit(e);
584             return;
585         }
586
587         entry.lastAccess = shard.ticker().read();
588         cohort.successfulPreCommit(candidate);
589     }
590
591     private void failCommit(final Exception cause) {
592         shard.getShardMBean().incrementFailedTransactionsCount();
593         pendingTransactions.poll().cohort.failedCommit(cause);
594         processNextTransaction();
595     }
596
597     private void finishCommit(final SimpleShardDataTreeCohort cohort) {
598         final TransactionIdentifier txId = cohort.getIdentifier();
599         final DataTreeCandidate candidate = cohort.getCandidate();
600
601         LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
602
603         try {
604             dataTree.commit(candidate);
605         } catch (Exception e) {
606             LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
607             failCommit(e);
608             return;
609         }
610
611         shard.getShardMBean().incrementCommittedTransactionCount();
612         shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
613
614         // FIXME: propagate journal index
615         pendingTransactions.poll().cohort.successfulCommit(UnsignedLong.ZERO);
616
617         LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
618         notifyListeners(candidate);
619
620         processNextTransaction();
621     }
622
623     void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
624         final CommitEntry entry = pendingTransactions.peek();
625         Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
626
627         final SimpleShardDataTreeCohort current = entry.cohort;
628         Verify.verify(cohort.equals(current), "Attempted to commit %s while %s is pending", cohort, current);
629
630         if (shard.canSkipPayload() || candidate.getRootNode().getModificationType() == ModificationType.UNMODIFIED) {
631             LOG.debug("{}: No replication required, proceeding to finish commit", logContext);
632             finishCommit(cohort);
633             return;
634         }
635
636         final TransactionIdentifier txId = cohort.getIdentifier();
637         final Payload payload;
638         try {
639             payload = CommitTransactionPayload.create(txId, candidate);
640         } catch (IOException e) {
641             LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
642             pendingTransactions.poll().cohort.failedCommit(e);
643             return;
644         }
645
646         // Once completed, we will continue via payloadReplicationComplete
647         entry.lastAccess = shard.ticker().read();
648         shard.persistPayload(txId, payload);
649         LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
650     }
651
652     void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
653         cohortRegistry.process(sender, message);
654     }
655
656     ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId,
657             final DataTreeModification modification) {
658         SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, modification, txId,
659                 cohortRegistry.createCohort(schemaContext, txId, COMMIT_STEP_TIMEOUT));
660         pendingTransactions.add(new CommitEntry(cohort, shard.ticker().read()));
661         return cohort;
662     }
663
664     void checkForExpiredTransactions(final long transactionCommitTimeoutMillis) {
665         final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
666         final long now = shard.ticker().read();
667         final CommitEntry currentTx = pendingTransactions.peek();
668         if (currentTx != null && currentTx.lastAccess + timeout < now) {
669             LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
670                     currentTx.cohort.getIdentifier(), transactionCommitTimeoutMillis, currentTx.cohort.getState());
671             boolean processNext = true;
672             switch (currentTx.cohort.getState()) {
673                 case CAN_COMMIT_PENDING:
674                     pendingTransactions.poll().cohort.failedCanCommit(new TimeoutException());
675                     break;
676                 case CAN_COMMIT_COMPLETE:
677                     pendingTransactions.poll().cohort.reportFailure(new TimeoutException());
678                     break;
679                 case PRE_COMMIT_PENDING:
680                     pendingTransactions.poll().cohort.failedPreCommit(new TimeoutException());
681                     break;
682                 case PRE_COMMIT_COMPLETE:
683                     // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
684                     //        are ready we should commit the transaction, not abort it. Our current software stack does
685                     //        not allow us to do that consistently, because we persist at the time of commit, hence
686                     //        we can end up in a state where we have pre-committed a transaction, then a leader failover
687                     //        occurred ... the new leader does not see the pre-committed transaction and does not have
688                     //        a running timer. To fix this we really need two persistence events.
689                     //
690                     //        The first one, done at pre-commit time will hold the transaction payload. When consensus
691                     //        is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
692                     //        apply the state in this event.
693                     //
694                     //        The second one, done at commit (or abort) time holds only the transaction identifier and
695                     //        signals to followers that the state should (or should not) be applied.
696                     //
697                     //        In order to make the pre-commit timer working across failovers, though, we need
698                     //        a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
699                     //        restart the timer.
700                     pendingTransactions.poll().cohort.reportFailure(new TimeoutException());
701                     break;
702                 case COMMIT_PENDING:
703                     LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
704                         currentTx.cohort.getIdentifier());
705                     currentTx.lastAccess = now;
706                     processNext = false;
707                     return;
708                 case ABORTED:
709                 case COMMITTED:
710                 case FAILED:
711                 case READY:
712                 default:
713                     pendingTransactions.poll();
714             }
715
716             if (processNext) {
717                 processNextTransaction();
718             }
719         }
720     }
721
722     void startAbort(final SimpleShardDataTreeCohort cohort) {
723         final Iterator<CommitEntry> it = pendingTransactions.iterator();
724         if (!it.hasNext()) {
725             LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
726             return;
727         }
728
729         // First entry is special, as it may already be committing
730         final CommitEntry first = it.next();
731         if (cohort.equals(first.cohort)) {
732             if (cohort.getState() != State.COMMIT_PENDING) {
733                 LOG.debug("{}: aborted head of queue {} in state {}", logContext, cohort.getIdentifier(),
734                     cohort.getIdentifier());
735                 pendingTransactions.poll();
736                 processNextTransaction();
737             } else {
738                 LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
739             }
740
741             return;
742         }
743
744         while (it.hasNext()) {
745             final CommitEntry e = it.next();
746             if (cohort.equals(e.cohort)) {
747                 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
748                 it.remove();
749                 return;
750             }
751         }
752
753         LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
754     }
755
756     void setRunOnPendingTransactionsComplete(final Runnable operation) {
757         runOnPendingTransactionsComplete = operation;
758         maybeRunOperationOnPendingTransactionsComplete();
759     }
760
761     private void maybeRunOperationOnPendingTransactionsComplete() {
762       if (runOnPendingTransactionsComplete != null && pendingTransactions.isEmpty()) {
763           LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
764                   runOnPendingTransactionsComplete);
765
766           runOnPendingTransactionsComplete.run();
767           runOnPendingTransactionsComplete = null;
768       }
769   }
770 }