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