5f1e67e988e60ccca5f434f2e04358cd484ba8b9
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / ShardDataTree.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.cluster.datastore;
9
10 import akka.actor.ActorRef;
11 import akka.util.Timeout;
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.MoreObjects;
14 import com.google.common.base.Optional;
15 import com.google.common.base.Preconditions;
16 import com.google.common.base.Stopwatch;
17 import com.google.common.base.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.collect.Iterables;
22 import com.google.common.primitives.UnsignedLong;
23 import com.google.common.util.concurrent.FutureCallback;
24 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
25 import java.io.File;
26 import java.io.IOException;
27 import java.util.ArrayDeque;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.Deque;
32 import java.util.HashMap;
33 import java.util.Iterator;
34 import java.util.Map;
35 import java.util.Map.Entry;
36 import java.util.Queue;
37 import java.util.SortedSet;
38 import java.util.concurrent.TimeUnit;
39 import java.util.concurrent.TimeoutException;
40 import java.util.function.Consumer;
41 import java.util.function.Function;
42 import java.util.function.UnaryOperator;
43 import javax.annotation.Nonnull;
44 import javax.annotation.Nullable;
45 import javax.annotation.concurrent.NotThreadSafe;
46 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
47 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
48 import org.opendaylight.controller.cluster.datastore.DataTreeCohortActorRegistry.CohortRegistryCommand;
49 import org.opendaylight.controller.cluster.datastore.ShardDataTreeCohort.State;
50 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
51 import org.opendaylight.controller.cluster.datastore.persisted.AbortTransactionPayload;
52 import org.opendaylight.controller.cluster.datastore.persisted.AbstractIdentifiablePayload;
53 import org.opendaylight.controller.cluster.datastore.persisted.CloseLocalHistoryPayload;
54 import org.opendaylight.controller.cluster.datastore.persisted.CommitTransactionPayload;
55 import org.opendaylight.controller.cluster.datastore.persisted.CreateLocalHistoryPayload;
56 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
57 import org.opendaylight.controller.cluster.datastore.persisted.PurgeLocalHistoryPayload;
58 import org.opendaylight.controller.cluster.datastore.persisted.PurgeTransactionPayload;
59 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
60 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshotMetadata;
61 import org.opendaylight.controller.cluster.datastore.utils.DataTreeModificationOutput;
62 import org.opendaylight.controller.cluster.datastore.utils.PruningDataTreeModification;
63 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
64 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
65 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
66 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
67 import org.opendaylight.yangtools.concepts.Identifier;
68 import org.opendaylight.yangtools.concepts.ListenerRegistration;
69 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
70 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
72 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
73 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
74 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
75 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
76 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
77 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
78 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
79 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeTip;
80 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
81 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
82 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
83 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
84 import org.slf4j.Logger;
85 import org.slf4j.LoggerFactory;
86 import scala.concurrent.duration.Duration;
87
88 /**
89  * Internal shard state, similar to a DOMStore, but optimized for use in the actor system,
90  * e.g. it does not expose public interfaces and assumes it is only ever called from a
91  * single thread.
92  *
93  * <p>
94  * This class is not part of the API contract and is subject to change at any time.
95  */
96 @NotThreadSafe
97 public class ShardDataTree extends ShardDataTreeTransactionParent {
98     private static final class CommitEntry {
99         final SimpleShardDataTreeCohort cohort;
100         long lastAccess;
101
102         CommitEntry(final SimpleShardDataTreeCohort cohort, final long now) {
103             this.cohort = Preconditions.checkNotNull(cohort);
104             lastAccess = now;
105         }
106
107         @Override
108         public String toString() {
109             return "CommitEntry [tx=" + cohort.getIdentifier() + ", state=" + cohort.getState() + "]";
110         }
111     }
112
113     private static final Timeout COMMIT_STEP_TIMEOUT = new Timeout(Duration.create(5, TimeUnit.SECONDS));
114     private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
115
116     /**
117      * Process this many transactions in a single batched run. If we exceed this limit, we need to schedule later
118      * execution to finish up the batch. This is necessary in case of a long list of transactions which progress
119      * immediately through their preCommit phase -- if that happens, their completion eats up stack frames and could
120      * result in StackOverflowError.
121      */
122     private static final int MAX_TRANSACTION_BATCH = 100;
123
124     private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
125     private final DataTreeCohortActorRegistry cohortRegistry = new DataTreeCohortActorRegistry();
126     private final Deque<CommitEntry> pendingTransactions = new ArrayDeque<>();
127     private final Queue<CommitEntry> pendingCommits = new ArrayDeque<>();
128     private final Queue<CommitEntry> pendingFinishCommits = new ArrayDeque<>();
129
130     /**
131      * Callbacks that need to be invoked once a payload is replicated.
132      */
133     private final Map<Payload, Runnable> replicationCallbacks = new HashMap<>();
134
135     private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
136     private final Collection<ShardDataTreeMetadata<?>> metadata;
137     private final DataTree dataTree;
138     private final String logContext;
139     private final Shard shard;
140     private Runnable runOnPendingTransactionsComplete;
141
142     /**
143      * Optimistic {@link DataTreeCandidate} preparation. Since our DataTree implementation is a
144      * {@link DataTree}, each {@link DataTreeCandidate} is also a {@link DataTreeTip}, e.g. another
145      * candidate can be prepared on top of it. They still need to be committed in sequence. Here we track the current
146      * tip of the data tree, which is the last DataTreeCandidate we have in flight, or the DataTree itself.
147      */
148     private DataTreeTip tip;
149
150     private SchemaContext schemaContext;
151
152     private int currentTransactionBatch;
153
154     ShardDataTree(final Shard shard, final SchemaContext schemaContext, final DataTree dataTree,
155             final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
156             final String logContext,
157             final ShardDataTreeMetadata<?>... metadata) {
158         this.dataTree = Preconditions.checkNotNull(dataTree);
159         updateSchemaContext(schemaContext);
160
161         this.shard = Preconditions.checkNotNull(shard);
162         this.treeChangeListenerPublisher = Preconditions.checkNotNull(treeChangeListenerPublisher);
163         this.logContext = Preconditions.checkNotNull(logContext);
164         this.metadata = ImmutableList.copyOf(metadata);
165         tip = dataTree;
166     }
167
168     ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType,
169             final YangInstanceIdentifier root,
170             final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
171             final String logContext,
172             final ShardDataTreeMetadata<?>... metadata) {
173         this(shard, schemaContext, createDataTree(treeType, root), treeChangeListenerPublisher, logContext, metadata);
174     }
175
176     private static DataTree createDataTree(final TreeType treeType, final YangInstanceIdentifier root) {
177         final DataTreeConfiguration baseConfig = DataTreeConfiguration.getDefault(treeType);
178         return new InMemoryDataTreeFactory().create(new DataTreeConfiguration.Builder(baseConfig.getTreeType())
179                 .setMandatoryNodesValidation(baseConfig.isMandatoryNodesValidationEnabled())
180                 .setUniqueIndexes(baseConfig.isUniqueIndexEnabled())
181                 .setRootPath(root)
182                 .build());
183     }
184
185     @VisibleForTesting
186     public ShardDataTree(final Shard shard, final SchemaContext schemaContext, final TreeType treeType) {
187         this(shard, schemaContext, treeType, YangInstanceIdentifier.EMPTY,
188                 new DefaultShardDataTreeChangeListenerPublisher(""), "");
189     }
190
191     final String logContext() {
192         return logContext;
193     }
194
195     final long readTime() {
196         return shard.ticker().read();
197     }
198
199     public DataTree getDataTree() {
200         return dataTree;
201     }
202
203     SchemaContext getSchemaContext() {
204         return schemaContext;
205     }
206
207     void updateSchemaContext(final SchemaContext newSchemaContext) {
208         dataTree.setSchemaContext(newSchemaContext);
209         this.schemaContext = Preconditions.checkNotNull(newSchemaContext);
210     }
211
212     void resetTransactionBatch() {
213         currentTransactionBatch = 0;
214     }
215
216     /**
217      * Take a snapshot of current state for later recovery.
218      *
219      * @return A state snapshot
220      */
221     @Nonnull ShardDataTreeSnapshot takeStateSnapshot() {
222         final NormalizedNode<?, ?> rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY).get();
223         final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
224                 ImmutableMap.builder();
225
226         for (ShardDataTreeMetadata<?> m : metadata) {
227             final ShardDataTreeSnapshotMetadata<?> meta = m.toSnapshot();
228             if (meta != null) {
229                 metaBuilder.put(meta.getType(), meta);
230             }
231         }
232
233         return new MetadataShardDataTreeSnapshot(rootNode, metaBuilder.build());
234     }
235
236     private boolean anyPendingTransactions() {
237         return !pendingTransactions.isEmpty() || !pendingCommits.isEmpty() || !pendingFinishCommits.isEmpty();
238     }
239
240     private void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot,
241             final UnaryOperator<DataTreeModification> wrapper) throws DataValidationFailedException {
242         final Stopwatch elapsed = Stopwatch.createStarted();
243
244         if (anyPendingTransactions()) {
245             LOG.warn("{}: applying state snapshot with pending transactions", logContext);
246         }
247
248         final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
249         if (snapshot instanceof MetadataShardDataTreeSnapshot) {
250             snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
251         } else {
252             snapshotMeta = ImmutableMap.of();
253         }
254
255         for (ShardDataTreeMetadata<?> m : metadata) {
256             final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
257             if (s != null) {
258                 m.applySnapshot(s);
259             } else {
260                 m.reset();
261             }
262         }
263
264         final DataTreeModification mod = wrapper.apply(dataTree.takeSnapshot().newModification());
265         // delete everything first
266         mod.delete(YangInstanceIdentifier.EMPTY);
267
268         final java.util.Optional<NormalizedNode<?, ?>> maybeNode = snapshot.getRootNode();
269         if (maybeNode.isPresent()) {
270             // Add everything from the remote node back
271             mod.write(YangInstanceIdentifier.EMPTY, maybeNode.get());
272         }
273         mod.ready();
274
275         final DataTreeModification unwrapped = unwrap(mod);
276         dataTree.validate(unwrapped);
277         DataTreeCandidateTip candidate = dataTree.prepare(unwrapped);
278         dataTree.commit(candidate);
279         notifyListeners(candidate);
280
281         LOG.debug("{}: state snapshot applied in {}", logContext, elapsed);
282     }
283
284     /**
285      * Apply a snapshot coming from the leader. This method assumes the leader and follower SchemaContexts match and
286      * does not perform any pruning.
287      *
288      * @param snapshot Snapshot that needs to be applied
289      * @throws DataValidationFailedException when the snapshot fails to apply
290      */
291     void applySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
292         applySnapshot(snapshot, UnaryOperator.identity());
293     }
294
295     private PruningDataTreeModification wrapWithPruning(final DataTreeModification delegate) {
296         return new PruningDataTreeModification(delegate, dataTree, schemaContext);
297     }
298
299     private static DataTreeModification unwrap(final DataTreeModification modification) {
300         if (modification instanceof PruningDataTreeModification) {
301             return ((PruningDataTreeModification)modification).delegate();
302         }
303         return modification;
304     }
305
306     /**
307      * Apply a snapshot coming from recovery. This method does not assume the SchemaContexts match and performs data
308      * pruning in an attempt to adjust the state to our current SchemaContext.
309      *
310      * @param snapshot Snapshot that needs to be applied
311      * @throws DataValidationFailedException when the snapshot fails to apply
312      */
313     void applyRecoverySnapshot(@Nonnull final ShardDataTreeSnapshot snapshot) throws DataValidationFailedException {
314         applySnapshot(snapshot, this::wrapWithPruning);
315     }
316
317     @SuppressWarnings("checkstyle:IllegalCatch")
318     private void applyRecoveryCandidate(final DataTreeCandidate candidate) throws DataValidationFailedException {
319         final PruningDataTreeModification mod = wrapWithPruning(dataTree.takeSnapshot().newModification());
320         DataTreeCandidates.applyToModification(mod, candidate);
321         mod.ready();
322
323         final DataTreeModification unwrapped = mod.delegate();
324         LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
325
326         try {
327             dataTree.validate(unwrapped);
328             dataTree.commit(dataTree.prepare(unwrapped));
329         } catch (Exception e) {
330             File file = new File(System.getProperty("karaf.data", "."),
331                     "failed-recovery-payload-" + logContext + ".out");
332             DataTreeModificationOutput.toFile(file, unwrapped);
333             throw new IllegalStateException(String.format(
334                     "%s: Failed to apply recovery payload. Modification data was written to file %s",
335                     logContext, file), e);
336         }
337     }
338
339     /**
340      * Apply a payload coming from recovery. This method does not assume the SchemaContexts match and performs data
341      * pruning in an attempt to adjust the state to our current SchemaContext.
342      *
343      * @param payload Payload
344      * @throws IOException when the snapshot fails to deserialize
345      * @throws DataValidationFailedException when the snapshot fails to apply
346      */
347     void applyRecoveryPayload(@Nonnull final Payload payload) throws IOException, DataValidationFailedException {
348         if (payload instanceof CommitTransactionPayload) {
349             final Entry<TransactionIdentifier, DataTreeCandidate> e =
350                     ((CommitTransactionPayload) payload).getCandidate();
351             applyRecoveryCandidate(e.getValue());
352             allMetadataCommittedTransaction(e.getKey());
353         } else if (payload instanceof AbortTransactionPayload) {
354             allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
355         } else if (payload instanceof PurgeTransactionPayload) {
356             allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
357         } else if (payload instanceof CreateLocalHistoryPayload) {
358             allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
359         } else if (payload instanceof CloseLocalHistoryPayload) {
360             allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
361         } else if (payload instanceof PurgeLocalHistoryPayload) {
362             allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
363         } else {
364             LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
365         }
366     }
367
368     private void applyReplicatedCandidate(final Identifier identifier, final DataTreeCandidate foreign)
369             throws DataValidationFailedException {
370         LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
371
372         final DataTreeModification mod = dataTree.takeSnapshot().newModification();
373         DataTreeCandidates.applyToModification(mod, foreign);
374         mod.ready();
375
376         LOG.trace("{}: Applying foreign modification {}", logContext, mod);
377         dataTree.validate(mod);
378         final DataTreeCandidate candidate = dataTree.prepare(mod);
379         dataTree.commit(candidate);
380
381         notifyListeners(candidate);
382     }
383
384     /**
385      * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
386      * SchemaContexts match and does not perform any pruning.
387      *
388      * @param identifier Payload identifier as returned from RaftActor
389      * @param payload Payload
390      * @throws IOException when the snapshot fails to deserialize
391      * @throws DataValidationFailedException when the snapshot fails to apply
392      */
393     void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
394             DataValidationFailedException {
395         /*
396          * 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
397          * if we are the leader and it has originated with us.
398          *
399          * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
400          * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
401          * acting in that capacity anymore.
402          *
403          * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
404          * pre-Boron state -- which limits the number of options here.
405          */
406         if (payload instanceof CommitTransactionPayload) {
407             final TransactionIdentifier txId;
408             if (identifier == null) {
409                 final Entry<TransactionIdentifier, DataTreeCandidate> e =
410                         ((CommitTransactionPayload) payload).getCandidate();
411                 txId = e.getKey();
412                 applyReplicatedCandidate(txId, e.getValue());
413             } else {
414                 Verify.verify(identifier instanceof TransactionIdentifier);
415                 txId = (TransactionIdentifier) identifier;
416                 payloadReplicationComplete(txId);
417             }
418             allMetadataCommittedTransaction(txId);
419         } else if (payload instanceof AbortTransactionPayload) {
420             if (identifier != null) {
421                 payloadReplicationComplete((AbortTransactionPayload) payload);
422             }
423             allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
424         } else if (payload instanceof PurgeTransactionPayload) {
425             if (identifier != null) {
426                 payloadReplicationComplete((PurgeTransactionPayload) payload);
427             }
428             allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
429         } else if (payload instanceof CloseLocalHistoryPayload) {
430             if (identifier != null) {
431                 payloadReplicationComplete((CloseLocalHistoryPayload) payload);
432             }
433             allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
434         } else if (payload instanceof CreateLocalHistoryPayload) {
435             if (identifier != null) {
436                 payloadReplicationComplete((CreateLocalHistoryPayload)payload);
437             }
438             allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
439         } else if (payload instanceof PurgeLocalHistoryPayload) {
440             if (identifier != null) {
441                 payloadReplicationComplete((PurgeLocalHistoryPayload)payload);
442             }
443             allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
444         } else {
445             LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
446         }
447     }
448
449     private void replicatePayload(final Identifier id, final Payload payload, @Nullable final Runnable callback) {
450         if (callback != null) {
451             replicationCallbacks.put(payload, callback);
452         }
453         shard.persistPayload(id, payload, true);
454     }
455
456     private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
457         final Runnable callback = replicationCallbacks.remove(payload);
458         if (callback != null) {
459             LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
460             callback.run();
461         } else {
462             LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
463         }
464     }
465
466     private void payloadReplicationComplete(final TransactionIdentifier txId) {
467         final CommitEntry current = pendingFinishCommits.peek();
468         if (current == null) {
469             LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
470             return;
471         }
472
473         if (!current.cohort.getIdentifier().equals(txId)) {
474             LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
475                 current.cohort.getIdentifier(), txId);
476             return;
477         }
478
479         finishCommit(current.cohort);
480     }
481
482     private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
483         for (ShardDataTreeMetadata<?> m : metadata) {
484             m.onTransactionAborted(txId);
485         }
486     }
487
488     private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
489         for (ShardDataTreeMetadata<?> m : metadata) {
490             m.onTransactionCommitted(txId);
491         }
492     }
493
494     private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
495         for (ShardDataTreeMetadata<?> m : metadata) {
496             m.onTransactionPurged(txId);
497         }
498     }
499
500     private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
501         for (ShardDataTreeMetadata<?> m : metadata) {
502             m.onHistoryCreated(historyId);
503         }
504     }
505
506     private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
507         for (ShardDataTreeMetadata<?> m : metadata) {
508             m.onHistoryClosed(historyId);
509         }
510     }
511
512     private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
513         for (ShardDataTreeMetadata<?> m : metadata) {
514             m.onHistoryPurged(historyId);
515         }
516     }
517
518     /**
519      * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
520      * this method is used for re-establishing state when we are taking over
521      *
522      * @param historyId Local history identifier
523      * @param closed True if the chain should be created in closed state (i.e. pending purge)
524      * @return Transaction chain handle
525      */
526     ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
527             final boolean closed) {
528         final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
529         final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
530         Preconditions.checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId,
531                 existing);
532         return ret;
533     }
534
535     ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId,
536             @Nullable final Runnable callback) {
537         ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
538         if (chain == null) {
539             chain = new ShardDataTreeTransactionChain(historyId, this);
540             transactionChains.put(historyId, chain);
541             replicatePayload(historyId, CreateLocalHistoryPayload.create(historyId), callback);
542         } else if (callback != null) {
543             callback.run();
544         }
545
546         return chain;
547     }
548
549     ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
550         if (txId.getHistoryId().getHistoryId() == 0) {
551             return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
552         }
553
554         return ensureTransactionChain(txId.getHistoryId(), null).newReadOnlyTransaction(txId);
555     }
556
557     ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
558         if (txId.getHistoryId().getHistoryId() == 0) {
559             return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
560                     .newModification());
561         }
562
563         return ensureTransactionChain(txId.getHistoryId(), null).newReadWriteTransaction(txId);
564     }
565
566     @VisibleForTesting
567     public void notifyListeners(final DataTreeCandidate candidate) {
568         treeChangeListenerPublisher.publishChanges(candidate);
569     }
570
571     /**
572      * Immediately purge all state relevant to leader. This includes all transaction chains and any scheduled
573      * replication callbacks.
574      */
575     void purgeLeaderState() {
576         for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
577             chain.close();
578         }
579
580         transactionChains.clear();
581         replicationCallbacks.clear();
582     }
583
584     /**
585      * Close a single transaction chain.
586      *
587      * @param id History identifier
588      * @param callback Callback to invoke upon completion, may be null
589      */
590     void closeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
591         final ShardDataTreeTransactionChain chain = transactionChains.get(id);
592         if (chain == null) {
593             LOG.debug("{}: Closing non-existent transaction chain {}", logContext, id);
594             if (callback != null) {
595                 callback.run();
596             }
597             return;
598         }
599
600         chain.close();
601         replicatePayload(id, CloseLocalHistoryPayload.create(id), callback);
602     }
603
604     /**
605      * Purge a single transaction chain.
606      *
607      * @param id History identifier
608      * @param callback Callback to invoke upon completion, may be null
609      */
610     void purgeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
611         final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
612         if (chain == null) {
613             LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
614             if (callback != null) {
615                 callback.run();
616             }
617             return;
618         }
619
620         replicatePayload(id, PurgeLocalHistoryPayload.create(id), callback);
621     }
622
623     Optional<DataTreeCandidate> readCurrentData() {
624         final java.util.Optional<NormalizedNode<?, ?>> currentState =
625                 dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY);
626         return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
627             YangInstanceIdentifier.EMPTY, currentState.get())) : Optional.<DataTreeCandidate>absent();
628     }
629
630     public void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
631             final Optional<DataTreeCandidate> initialState,
632             final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
633         treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
634     }
635
636     int getQueueSize() {
637         return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
638     }
639
640     @Override
641     void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
642         final TransactionIdentifier id = transaction.getIdentifier();
643         LOG.debug("{}: aborting transaction {}", logContext, id);
644         replicatePayload(id, AbortTransactionPayload.create(id), callback);
645     }
646
647     @Override
648     void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
649         // No-op for free-standing transactions
650
651     }
652
653     @Override
654     ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction,
655             final java.util.Optional<SortedSet<String>> participatingShardNames) {
656         final DataTreeModification snapshot = transaction.getSnapshot();
657         snapshot.ready();
658
659         return createReadyCohort(transaction.getIdentifier(), snapshot, participatingShardNames);
660     }
661
662     void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
663         LOG.debug("{}: purging transaction {}", logContext, id);
664         replicatePayload(id, PurgeTransactionPayload.create(id), callback);
665     }
666
667     public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
668         return Optional.fromJavaUtil(dataTree.takeSnapshot().readNode(path));
669     }
670
671     DataTreeSnapshot takeSnapshot() {
672         return dataTree.takeSnapshot();
673     }
674
675     @VisibleForTesting
676     public DataTreeModification newModification() {
677         return dataTree.takeSnapshot().newModification();
678     }
679
680     public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
681         Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
682
683         for (CommitEntry entry: pendingFinishCommits) {
684             ret.add(entry.cohort);
685         }
686
687         for (CommitEntry entry: pendingCommits) {
688             ret.add(entry.cohort);
689         }
690
691         for (CommitEntry entry: pendingTransactions) {
692             ret.add(entry.cohort);
693         }
694
695         pendingFinishCommits.clear();
696         pendingCommits.clear();
697         pendingTransactions.clear();
698         tip = dataTree;
699         return ret;
700     }
701
702     /**
703      * Called some time after {@link #processNextPendingTransaction()} decides to stop processing.
704      */
705     void resumeNextPendingTransaction() {
706         LOG.debug("{}: attempting to resume transaction processing", logContext);
707         processNextPending();
708     }
709
710     @SuppressWarnings("checkstyle:IllegalCatch")
711     private void processNextPendingTransaction() {
712         ++currentTransactionBatch;
713         if (currentTransactionBatch > MAX_TRANSACTION_BATCH) {
714             LOG.debug("{}: Already processed {}, scheduling continuation", logContext, currentTransactionBatch);
715             shard.scheduleNextPendingTransaction();
716             return;
717         }
718
719         processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
720             final SimpleShardDataTreeCohort cohort = entry.cohort;
721             final DataTreeModification modification = cohort.getDataTreeModification();
722
723             LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
724             Exception cause;
725             try {
726                 tip.validate(modification);
727                 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
728                 cohort.successfulCanCommit();
729                 entry.lastAccess = readTime();
730                 return;
731             } catch (ConflictingModificationAppliedException e) {
732                 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
733                     e.getPath());
734                 cause = new OptimisticLockFailedException("Optimistic lock failed for path " + e.getPath(), e);
735             } catch (DataValidationFailedException e) {
736                 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
737                     e.getPath(), e);
738
739                 // For debugging purposes, allow dumping of the modification. Coupled with the above
740                 // precondition log, it should allow us to understand what went on.
741                 LOG.debug("{}: Store Tx {}: modifications: {} tree: {}", cohort.getIdentifier(), modification,
742                         dataTree);
743                 cause = new TransactionCommitFailedException("Data did not pass validation for path " + e.getPath(), e);
744             } catch (Exception e) {
745                 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
746                 cause = e;
747             }
748
749             // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
750             pendingTransactions.poll().cohort.failedCanCommit(cause);
751         });
752     }
753
754     private void processNextPending() {
755         processNextPendingCommit();
756         processNextPendingTransaction();
757     }
758
759     private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
760             final Consumer<CommitEntry> processor) {
761         while (!queue.isEmpty()) {
762             final CommitEntry entry = queue.peek();
763             final SimpleShardDataTreeCohort cohort = entry.cohort;
764
765             if (cohort.isFailed()) {
766                 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
767                 queue.remove();
768                 continue;
769             }
770
771             if (cohort.getState() == allowedState) {
772                 processor.accept(entry);
773             }
774
775             break;
776         }
777
778         maybeRunOperationOnPendingTransactionsComplete();
779     }
780
781     private void processNextPendingCommit() {
782         processNextPending(pendingCommits, State.COMMIT_PENDING,
783             entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
784     }
785
786     private boolean peekNextPendingCommit() {
787         final CommitEntry first = pendingCommits.peek();
788         return first != null && first.cohort.getState() == State.COMMIT_PENDING;
789     }
790
791     void startCanCommit(final SimpleShardDataTreeCohort cohort) {
792         final CommitEntry head = pendingTransactions.peek();
793         if (head == null) {
794             LOG.warn("{}: No transactions enqueued while attempting to start canCommit on {}", logContext, cohort);
795             return;
796         }
797         if (!cohort.equals(head.cohort)) {
798             // The tx isn't at the head of the queue so we can't start canCommit at this point. Here we check if this
799             // tx should be moved ahead of other tx's in the READY state in the pendingTransactions queue. If this tx
800             // has other participating shards, it could deadlock with other tx's accessing the same shards
801             // depending on the order the tx's are readied on each shard
802             // (see https://jira.opendaylight.org/browse/CONTROLLER-1836). Therefore, if the preceding participating
803             // shard names for a preceding pending tx, call it A, in the queue matches that of this tx, then this tx
804             // is allowed to be moved ahead of tx A in the queue so it is processed first to avoid potential deadlock
805             // if tx A is behind this tx in the pendingTransactions queue for a preceding shard. In other words, since
806             // canCommmit for this tx was requested before tx A, honor that request. If this tx is moved to the head of
807             // the queue as a result, then proceed with canCommit.
808
809             Collection<String> precedingShardNames = extractPrecedingShardNames(cohort.getParticipatingShardNames());
810             if (precedingShardNames.isEmpty()) {
811                 LOG.debug("{}: Tx {} is scheduled for canCommit step", logContext, cohort.getIdentifier());
812                 return;
813             }
814
815             LOG.debug("{}: Evaluating tx {} for canCommit -  preceding participating shard names {}",
816                     logContext, cohort.getIdentifier(), precedingShardNames);
817             final Iterator<CommitEntry> iter = pendingTransactions.iterator();
818             int index = -1;
819             int moveToIndex = -1;
820             while (iter.hasNext()) {
821                 final CommitEntry entry = iter.next();
822                 ++index;
823
824                 if (cohort.equals(entry.cohort)) {
825                     if (moveToIndex < 0) {
826                         LOG.debug("{}: Not moving tx {} - cannot proceed with canCommit",
827                                 logContext, cohort.getIdentifier());
828                         return;
829                     }
830
831                     LOG.debug("{}: Moving {} to index {} in the pendingTransactions queue",
832                             logContext, cohort.getIdentifier(), moveToIndex);
833                     iter.remove();
834                     insertEntry(pendingTransactions, entry, moveToIndex);
835
836                     if (!cohort.equals(pendingTransactions.peek().cohort)) {
837                         LOG.debug("{}: Tx {} is not at the head of the queue - cannot proceed with canCommit",
838                                 logContext, cohort.getIdentifier());
839                         return;
840                     }
841
842                     LOG.debug("{}: Tx {} is now at the head of the queue - proceeding with canCommit",
843                             logContext, cohort.getIdentifier());
844                     break;
845                 }
846
847                 if (entry.cohort.getState() != State.READY) {
848                     LOG.debug("{}: Skipping pending transaction {} in state {}",
849                             logContext, entry.cohort.getIdentifier(), entry.cohort.getState());
850                     continue;
851                 }
852
853                 final Collection<String> pendingPrecedingShardNames = extractPrecedingShardNames(
854                         entry.cohort.getParticipatingShardNames());
855
856                 if (precedingShardNames.equals(pendingPrecedingShardNames)) {
857                     if (moveToIndex < 0) {
858                         LOG.debug("{}: Preceding shard names {} for pending tx {} match - saving moveToIndex {}",
859                                 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), index);
860                         moveToIndex = index;
861                     } else {
862                         LOG.debug(
863                             "{}: Preceding shard names {} for pending tx {} match but moveToIndex already set to {}",
864                             logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), moveToIndex);
865                     }
866                 } else {
867                     LOG.debug("{}: Preceding shard names {} for pending tx {} differ - skipping",
868                         logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier());
869                 }
870             }
871         }
872
873         processNextPendingTransaction();
874     }
875
876     private void insertEntry(Deque<CommitEntry> queue, CommitEntry entry, int atIndex) {
877         if (atIndex == 0) {
878             queue.addFirst(entry);
879             return;
880         }
881
882         LOG.trace("Inserting into Deque at index {}", atIndex);
883
884         Deque<CommitEntry> tempStack = new ArrayDeque<>(atIndex);
885         for (int i = 0; i < atIndex; i++) {
886             tempStack.push(queue.poll());
887         }
888
889         queue.addFirst(entry);
890
891         tempStack.forEach(queue::addFirst);
892     }
893
894     private Collection<String> extractPrecedingShardNames(
895             java.util.Optional<SortedSet<String>> participatingShardNames) {
896         return participatingShardNames.map((Function<SortedSet<String>, Collection<String>>)
897             set -> set.headSet(shard.getShardName())).orElse(Collections.<String>emptyList());
898     }
899
900     private void failPreCommit(final Throwable cause) {
901         shard.getShardMBean().incrementFailedTransactionsCount();
902         pendingTransactions.poll().cohort.failedPreCommit(cause);
903         processNextPendingTransaction();
904     }
905
906     @SuppressWarnings("checkstyle:IllegalCatch")
907     void startPreCommit(final SimpleShardDataTreeCohort cohort) {
908         final CommitEntry entry = pendingTransactions.peek();
909         Preconditions.checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
910
911         final SimpleShardDataTreeCohort current = entry.cohort;
912         Verify.verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
913
914         LOG.debug("{}: Preparing transaction {}", logContext, current.getIdentifier());
915
916         final DataTreeCandidateTip candidate;
917         try {
918             candidate = tip.prepare(cohort.getDataTreeModification());
919         } catch (RuntimeException e) {
920             failPreCommit(e);
921             return;
922         }
923
924         cohort.userPreCommit(candidate, new FutureCallback<Void>() {
925             @Override
926             public void onSuccess(final Void noop) {
927                 // Set the tip of the data tree.
928                 tip = Verify.verifyNotNull(candidate);
929
930                 entry.lastAccess = readTime();
931
932                 pendingTransactions.remove();
933                 pendingCommits.add(entry);
934
935                 LOG.debug("{}: Transaction {} prepared", logContext, current.getIdentifier());
936
937                 cohort.successfulPreCommit(candidate);
938
939                 processNextPendingTransaction();
940             }
941
942             @Override
943             public void onFailure(final Throwable failure) {
944                 failPreCommit(failure);
945             }
946         });
947     }
948
949     private void failCommit(final Exception cause) {
950         shard.getShardMBean().incrementFailedTransactionsCount();
951         pendingFinishCommits.poll().cohort.failedCommit(cause);
952         processNextPending();
953     }
954
955     @SuppressWarnings("checkstyle:IllegalCatch")
956     private void finishCommit(final SimpleShardDataTreeCohort cohort) {
957         final TransactionIdentifier txId = cohort.getIdentifier();
958         final DataTreeCandidate candidate = cohort.getCandidate();
959
960         LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
961
962         if (tip == candidate) {
963             // All pending candidates have been committed, reset the tip to the data tree.
964             tip = dataTree;
965         }
966
967         try {
968             dataTree.commit(candidate);
969         } catch (Exception e) {
970             LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
971             failCommit(e);
972             return;
973         }
974
975         shard.getShardMBean().incrementCommittedTransactionCount();
976         shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
977
978         // FIXME: propagate journal index
979         pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO, () -> {
980             LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
981             notifyListeners(candidate);
982
983             processNextPending();
984         });
985     }
986
987     void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
988         final CommitEntry entry = pendingCommits.peek();
989         Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
990
991         final SimpleShardDataTreeCohort current = entry.cohort;
992         if (!cohort.equals(current)) {
993             LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
994             return;
995         }
996
997         LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
998
999         final TransactionIdentifier txId = cohort.getIdentifier();
1000         final Payload payload;
1001         try {
1002             payload = CommitTransactionPayload.create(txId, candidate);
1003         } catch (IOException e) {
1004             LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
1005             pendingCommits.poll().cohort.failedCommit(e);
1006             processNextPending();
1007             return;
1008         }
1009
1010         // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
1011         // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
1012         // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
1013         // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
1014         // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
1015         // pendingCommits queue.
1016         processNextPendingTransaction();
1017
1018         // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
1019         // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
1020         // in order to properly determine the batchHint flag for the call to persistPayload.
1021         pendingCommits.remove();
1022         pendingFinishCommits.add(entry);
1023
1024         // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
1025         // this transaction for replication.
1026         boolean replicationBatchHint = peekNextPendingCommit();
1027
1028         // Once completed, we will continue via payloadReplicationComplete
1029         shard.persistPayload(txId, payload, replicationBatchHint);
1030
1031         entry.lastAccess = shard.ticker().read();
1032
1033         LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
1034
1035         // Process the next transaction pending commit, if any. If there is one it will be batched with this
1036         // transaction for replication.
1037         processNextPendingCommit();
1038     }
1039
1040     Collection<ActorRef> getCohortActors() {
1041         return cohortRegistry.getCohortActors();
1042     }
1043
1044     void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
1045         cohortRegistry.process(sender, message);
1046     }
1047
1048     @Override
1049     ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1050             final Exception failure) {
1051         final SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId, failure);
1052         pendingTransactions.add(new CommitEntry(cohort, readTime()));
1053         return cohort;
1054     }
1055
1056     @Override
1057     ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1058             final java.util.Optional<SortedSet<String>> participatingShardNames) {
1059         SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId,
1060                 cohortRegistry.createCohort(schemaContext, txId, runnable -> shard.executeInSelf(runnable),
1061                         COMMIT_STEP_TIMEOUT), participatingShardNames);
1062         pendingTransactions.add(new CommitEntry(cohort, readTime()));
1063         return cohort;
1064     }
1065
1066     // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
1067     // the newReadWriteTransaction()
1068     ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1069             final java.util.Optional<SortedSet<String>> participatingShardNames) {
1070         if (txId.getHistoryId().getHistoryId() == 0) {
1071             return createReadyCohort(txId, mod, participatingShardNames);
1072         }
1073
1074         return ensureTransactionChain(txId.getHistoryId(), null).createReadyCohort(txId, mod, participatingShardNames);
1075     }
1076
1077     @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
1078     void checkForExpiredTransactions(final long transactionCommitTimeoutMillis,
1079             final Function<SimpleShardDataTreeCohort, Optional<Long>> accessTimeUpdater) {
1080         final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
1081         final long now = readTime();
1082
1083         final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
1084             !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
1085         final CommitEntry currentTx = currentQueue.peek();
1086         if (currentTx == null) {
1087             // Empty queue, no-op
1088             return;
1089         }
1090
1091         long delta = now - currentTx.lastAccess;
1092         if (delta < timeout) {
1093             // Not expired yet, bail
1094             return;
1095         }
1096
1097         final Optional<Long> updateOpt = accessTimeUpdater.apply(currentTx.cohort);
1098         if (updateOpt.isPresent()) {
1099             final long newAccess =  updateOpt.get().longValue();
1100             final long newDelta = now - newAccess;
1101             if (newDelta < delta) {
1102                 LOG.debug("{}: Updated current transaction {} access time", logContext,
1103                     currentTx.cohort.getIdentifier());
1104                 currentTx.lastAccess = newAccess;
1105                 delta = newDelta;
1106             }
1107
1108             if (delta < timeout) {
1109                 // Not expired yet, bail
1110                 return;
1111             }
1112         }
1113
1114         final long deltaMillis = TimeUnit.NANOSECONDS.toMillis(delta);
1115         final State state = currentTx.cohort.getState();
1116
1117         LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
1118             currentTx.cohort.getIdentifier(), deltaMillis, state);
1119         boolean processNext = true;
1120         final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
1121                 + deltaMillis + "ms");
1122
1123         switch (state) {
1124             case CAN_COMMIT_PENDING:
1125                 currentQueue.remove().cohort.failedCanCommit(cohortFailure);
1126                 break;
1127             case CAN_COMMIT_COMPLETE:
1128                 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
1129                 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
1130                 // in PRE_COMMIT_COMPLETE is changed.
1131                 currentQueue.remove().cohort.reportFailure(cohortFailure);
1132                 break;
1133             case PRE_COMMIT_PENDING:
1134                 currentQueue.remove().cohort.failedPreCommit(cohortFailure);
1135                 break;
1136             case PRE_COMMIT_COMPLETE:
1137                 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
1138                 //        are ready we should commit the transaction, not abort it. Our current software stack does
1139                 //        not allow us to do that consistently, because we persist at the time of commit, hence
1140                 //        we can end up in a state where we have pre-committed a transaction, then a leader failover
1141                 //        occurred ... the new leader does not see the pre-committed transaction and does not have
1142                 //        a running timer. To fix this we really need two persistence events.
1143                 //
1144                 //        The first one, done at pre-commit time will hold the transaction payload. When consensus
1145                 //        is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1146                 //        apply the state in this event.
1147                 //
1148                 //        The second one, done at commit (or abort) time holds only the transaction identifier and
1149                 //        signals to followers that the state should (or should not) be applied.
1150                 //
1151                 //        In order to make the pre-commit timer working across failovers, though, we need
1152                 //        a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1153                 //        restart the timer.
1154                 currentQueue.remove().cohort.reportFailure(cohortFailure);
1155                 break;
1156             case COMMIT_PENDING:
1157                 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1158                     currentTx.cohort.getIdentifier());
1159                 currentTx.lastAccess = now;
1160                 processNext = false;
1161                 return;
1162             case READY:
1163                 currentQueue.remove().cohort.reportFailure(cohortFailure);
1164                 break;
1165             case ABORTED:
1166             case COMMITTED:
1167             case FAILED:
1168             default:
1169                 currentQueue.remove();
1170         }
1171
1172         if (processNext) {
1173             processNextPending();
1174         }
1175     }
1176
1177     boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1178         final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1179                 pendingTransactions).iterator();
1180         if (!it.hasNext()) {
1181             LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1182             return true;
1183         }
1184
1185         // First entry is special, as it may already be committing
1186         final CommitEntry first = it.next();
1187         if (cohort.equals(first.cohort)) {
1188             if (cohort.getState() != State.COMMIT_PENDING) {
1189                 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1190                     cohort.getIdentifier());
1191
1192                 it.remove();
1193                 if (cohort.getCandidate() != null) {
1194                     rebaseTransactions(it, dataTree);
1195                 }
1196
1197                 processNextPending();
1198                 return true;
1199             }
1200
1201             LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1202             return false;
1203         }
1204
1205         DataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
1206         while (it.hasNext()) {
1207             final CommitEntry e = it.next();
1208             if (cohort.equals(e.cohort)) {
1209                 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1210
1211                 it.remove();
1212                 if (cohort.getCandidate() != null) {
1213                     rebaseTransactions(it, newTip);
1214                 }
1215
1216                 return true;
1217             } else {
1218                 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), newTip);
1219             }
1220         }
1221
1222         LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1223         return true;
1224     }
1225
1226     @SuppressWarnings("checkstyle:IllegalCatch")
1227     private void rebaseTransactions(final Iterator<CommitEntry> iter, @Nonnull final DataTreeTip newTip) {
1228         tip = Preconditions.checkNotNull(newTip);
1229         while (iter.hasNext()) {
1230             final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1231             if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1232                 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1233
1234                 try {
1235                     tip.validate(cohort.getDataTreeModification());
1236                 } catch (DataValidationFailedException | RuntimeException e) {
1237                     LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1238                     cohort.reportFailure(e);
1239                 }
1240             } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1241                 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1242
1243                 try {
1244                     tip.validate(cohort.getDataTreeModification());
1245                     DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1246
1247                     cohort.setNewCandidate(candidate);
1248                     tip = candidate;
1249                 } catch (RuntimeException | DataValidationFailedException e) {
1250                     LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1251                     cohort.reportFailure(e);
1252                 }
1253             }
1254         }
1255     }
1256
1257     void setRunOnPendingTransactionsComplete(final Runnable operation) {
1258         runOnPendingTransactionsComplete = operation;
1259         maybeRunOperationOnPendingTransactionsComplete();
1260     }
1261
1262     private void maybeRunOperationOnPendingTransactionsComplete() {
1263         if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1264             LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1265                     runOnPendingTransactionsComplete);
1266
1267             runOnPendingTransactionsComplete.run();
1268             runOnPendingTransactionsComplete = null;
1269         }
1270     }
1271
1272     ShardStats getStats() {
1273         return shard.getShardMBean();
1274     }
1275
1276     Iterator<SimpleShardDataTreeCohort> cohortIterator() {
1277         return Iterables.transform(Iterables.concat(pendingFinishCommits, pendingCommits, pendingTransactions),
1278             e -> e.cohort).iterator();
1279     }
1280
1281     void removeTransactionChain(final LocalHistoryIdentifier id) {
1282         if (transactionChains.remove(id) != null) {
1283             LOG.debug("{}: Removed transaction chain {}", logContext, id);
1284         }
1285     }
1286 }