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