Specify initial serialization buffer capacity for Payloads
[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.FiniteDuration;
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(FiniteDuration.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) {
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 {
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 TransactionIdentifier 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         allMetadataCommittedTransaction(identifier);
382         notifyListeners(candidate);
383     }
384
385     /**
386      * Apply a payload coming from the leader, which could actually be us. This method assumes the leader and follower
387      * SchemaContexts match and does not perform any pruning.
388      *
389      * @param identifier Payload identifier as returned from RaftActor
390      * @param payload Payload
391      * @throws IOException when the snapshot fails to deserialize
392      * @throws DataValidationFailedException when the snapshot fails to apply
393      */
394     void applyReplicatedPayload(final Identifier identifier, final Payload payload) throws IOException,
395             DataValidationFailedException {
396         /*
397          * 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
398          * if we are the leader and it has originated with us.
399          *
400          * The identifier will only ever be non-null when we were the leader which achieved consensus. Unfortunately,
401          * though, this may not be the case anymore, as we are being called some time afterwards and we may not be
402          * acting in that capacity anymore.
403          *
404          * In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
405          * pre-Boron state -- which limits the number of options here.
406          */
407         if (payload instanceof CommitTransactionPayload) {
408             if (identifier == null) {
409                 final Entry<TransactionIdentifier, DataTreeCandidate> e =
410                         ((CommitTransactionPayload) payload).getCandidate();
411                 applyReplicatedCandidate(e.getKey(), e.getValue());
412             } else {
413                 Verify.verify(identifier instanceof TransactionIdentifier);
414                 payloadReplicationComplete((TransactionIdentifier) identifier);
415             }
416         } else if (payload instanceof AbortTransactionPayload) {
417             if (identifier != null) {
418                 payloadReplicationComplete((AbortTransactionPayload) payload);
419             }
420             allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
421         } else if (payload instanceof PurgeTransactionPayload) {
422             if (identifier != null) {
423                 payloadReplicationComplete((PurgeTransactionPayload) payload);
424             }
425             allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
426         } else if (payload instanceof CloseLocalHistoryPayload) {
427             if (identifier != null) {
428                 payloadReplicationComplete((CloseLocalHistoryPayload) payload);
429             }
430             allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
431         } else if (payload instanceof CreateLocalHistoryPayload) {
432             if (identifier != null) {
433                 payloadReplicationComplete((CreateLocalHistoryPayload)payload);
434             }
435             allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
436         } else if (payload instanceof PurgeLocalHistoryPayload) {
437             if (identifier != null) {
438                 payloadReplicationComplete((PurgeLocalHistoryPayload)payload);
439             }
440             allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
441         } else {
442             LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
443         }
444     }
445
446     private void replicatePayload(final Identifier id, final Payload payload, @Nullable final Runnable callback) {
447         if (callback != null) {
448             replicationCallbacks.put(payload, callback);
449         }
450         shard.persistPayload(id, payload, true);
451     }
452
453     private void payloadReplicationComplete(final AbstractIdentifiablePayload<?> payload) {
454         final Runnable callback = replicationCallbacks.remove(payload);
455         if (callback != null) {
456             LOG.debug("{}: replication of {} completed, invoking {}", logContext, payload.getIdentifier(), callback);
457             callback.run();
458         } else {
459             LOG.debug("{}: replication of {} has no callback", logContext, payload.getIdentifier());
460         }
461     }
462
463     private void payloadReplicationComplete(final TransactionIdentifier txId) {
464         final CommitEntry current = pendingFinishCommits.peek();
465         if (current == null) {
466             LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
467             allMetadataCommittedTransaction(txId);
468             return;
469         }
470
471         if (!current.cohort.getIdentifier().equals(txId)) {
472             LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
473                 current.cohort.getIdentifier(), txId);
474             allMetadataCommittedTransaction(txId);
475             return;
476         }
477
478         finishCommit(current.cohort);
479     }
480
481     private void allMetadataAbortedTransaction(final TransactionIdentifier txId) {
482         for (ShardDataTreeMetadata<?> m : metadata) {
483             m.onTransactionAborted(txId);
484         }
485     }
486
487     private void allMetadataCommittedTransaction(final TransactionIdentifier txId) {
488         for (ShardDataTreeMetadata<?> m : metadata) {
489             m.onTransactionCommitted(txId);
490         }
491     }
492
493     private void allMetadataPurgedTransaction(final TransactionIdentifier txId) {
494         for (ShardDataTreeMetadata<?> m : metadata) {
495             m.onTransactionPurged(txId);
496         }
497     }
498
499     private void allMetadataCreatedLocalHistory(final LocalHistoryIdentifier historyId) {
500         for (ShardDataTreeMetadata<?> m : metadata) {
501             m.onHistoryCreated(historyId);
502         }
503     }
504
505     private void allMetadataClosedLocalHistory(final LocalHistoryIdentifier historyId) {
506         for (ShardDataTreeMetadata<?> m : metadata) {
507             m.onHistoryClosed(historyId);
508         }
509     }
510
511     private void allMetadataPurgedLocalHistory(final LocalHistoryIdentifier historyId) {
512         for (ShardDataTreeMetadata<?> m : metadata) {
513             m.onHistoryPurged(historyId);
514         }
515     }
516
517     /**
518      * Create a transaction chain for specified history. Unlike {@link #ensureTransactionChain(LocalHistoryIdentifier)},
519      * this method is used for re-establishing state when we are taking over
520      *
521      * @param historyId Local history identifier
522      * @param closed True if the chain should be created in closed state (i.e. pending purge)
523      * @return Transaction chain handle
524      */
525     ShardDataTreeTransactionChain recreateTransactionChain(final LocalHistoryIdentifier historyId,
526             final boolean closed) {
527         final ShardDataTreeTransactionChain ret = new ShardDataTreeTransactionChain(historyId, this);
528         final ShardDataTreeTransactionChain existing = transactionChains.putIfAbsent(historyId, ret);
529         Preconditions.checkState(existing == null, "Attempted to recreate chain %s, but %s already exists", historyId,
530                 existing);
531         return ret;
532     }
533
534     ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier historyId,
535             @Nullable final Runnable callback) {
536         ShardDataTreeTransactionChain chain = transactionChains.get(historyId);
537         if (chain == null) {
538             chain = new ShardDataTreeTransactionChain(historyId, this);
539             transactionChains.put(historyId, chain);
540             replicatePayload(historyId, CreateLocalHistoryPayload.create(
541                     historyId, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), 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(
602                 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
603     }
604
605     /**
606      * Purge a single transaction chain.
607      *
608      * @param id History identifier
609      * @param callback Callback to invoke upon completion, may be null
610      */
611     void purgeTransactionChain(final LocalHistoryIdentifier id, @Nullable final Runnable callback) {
612         final ShardDataTreeTransactionChain chain = transactionChains.remove(id);
613         if (chain == null) {
614             LOG.debug("{}: Purging non-existent transaction chain {}", logContext, id);
615             if (callback != null) {
616                 callback.run();
617             }
618             return;
619         }
620
621         replicatePayload(id, PurgeLocalHistoryPayload.create(
622                 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
623     }
624
625     Optional<DataTreeCandidate> readCurrentData() {
626         final java.util.Optional<NormalizedNode<?, ?>> currentState =
627                 dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY);
628         return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
629             YangInstanceIdentifier.EMPTY, currentState.get())) : Optional.<DataTreeCandidate>absent();
630     }
631
632     public void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
633             final Optional<DataTreeCandidate> initialState,
634             final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
635         treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
636     }
637
638     int getQueueSize() {
639         return pendingTransactions.size() + pendingCommits.size() + pendingFinishCommits.size();
640     }
641
642     @Override
643     void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction, final Runnable callback) {
644         final TransactionIdentifier id = transaction.getIdentifier();
645         LOG.debug("{}: aborting transaction {}", logContext, id);
646         replicatePayload(id, AbortTransactionPayload.create(
647                 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
648     }
649
650     @Override
651     void abortFromTransactionActor(final AbstractShardDataTreeTransaction<?> transaction) {
652         // No-op for free-standing transactions
653
654     }
655
656     @Override
657     ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction,
658             final java.util.Optional<SortedSet<String>> participatingShardNames) {
659         final DataTreeModification snapshot = transaction.getSnapshot();
660         snapshot.ready();
661
662         return createReadyCohort(transaction.getIdentifier(), snapshot, participatingShardNames);
663     }
664
665     void purgeTransaction(final TransactionIdentifier id, final Runnable callback) {
666         LOG.debug("{}: purging transaction {}", logContext, id);
667         replicatePayload(id, PurgeTransactionPayload.create(
668                 id, shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity()), callback);
669     }
670
671     public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
672         return Optional.fromJavaUtil(dataTree.takeSnapshot().readNode(path));
673     }
674
675     DataTreeSnapshot takeSnapshot() {
676         return dataTree.takeSnapshot();
677     }
678
679     @VisibleForTesting
680     public DataTreeModification newModification() {
681         return dataTree.takeSnapshot().newModification();
682     }
683
684     public Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
685         Collection<ShardDataTreeCohort> ret = new ArrayList<>(getQueueSize());
686
687         for (CommitEntry entry: pendingFinishCommits) {
688             ret.add(entry.cohort);
689         }
690
691         for (CommitEntry entry: pendingCommits) {
692             ret.add(entry.cohort);
693         }
694
695         for (CommitEntry entry: pendingTransactions) {
696             ret.add(entry.cohort);
697         }
698
699         pendingFinishCommits.clear();
700         pendingCommits.clear();
701         pendingTransactions.clear();
702         tip = dataTree;
703         return ret;
704     }
705
706     /**
707      * Called some time after {@link #processNextPendingTransaction()} decides to stop processing.
708      */
709     void resumeNextPendingTransaction() {
710         LOG.debug("{}: attempting to resume transaction processing", logContext);
711         processNextPending();
712     }
713
714     @SuppressWarnings("checkstyle:IllegalCatch")
715     private void processNextPendingTransaction() {
716         ++currentTransactionBatch;
717         if (currentTransactionBatch > MAX_TRANSACTION_BATCH) {
718             LOG.debug("{}: Already processed {}, scheduling continuation", logContext, currentTransactionBatch);
719             shard.scheduleNextPendingTransaction();
720             return;
721         }
722
723         processNextPending(pendingTransactions, State.CAN_COMMIT_PENDING, entry -> {
724             final SimpleShardDataTreeCohort cohort = entry.cohort;
725             final DataTreeModification modification = cohort.getDataTreeModification();
726
727             LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
728             Exception cause;
729             try {
730                 tip.validate(modification);
731                 LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
732                 cohort.successfulCanCommit();
733                 entry.lastAccess = readTime();
734                 return;
735             } catch (ConflictingModificationAppliedException e) {
736                 LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
737                     e.getPath());
738                 cause = new OptimisticLockFailedException("Optimistic lock failed for path " + e.getPath(), e);
739             } catch (DataValidationFailedException e) {
740                 LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
741                     e.getPath(), e);
742
743                 // For debugging purposes, allow dumping of the modification. Coupled with the above
744                 // precondition log, it should allow us to understand what went on.
745                 LOG.debug("{}: Store Tx {}: modifications: {} tree: {}", logContext, cohort.getIdentifier(),
746                     modification, dataTree);
747                 cause = new TransactionCommitFailedException("Data did not pass validation for path " + e.getPath(), e);
748             } catch (Exception e) {
749                 LOG.warn("{}: Unexpected failure in validation phase", logContext, e);
750                 cause = e;
751             }
752
753             // Failure path: propagate the failure, remove the transaction from the queue and loop to the next one
754             pendingTransactions.poll().cohort.failedCanCommit(cause);
755         });
756     }
757
758     private void processNextPending() {
759         processNextPendingCommit();
760         processNextPendingTransaction();
761     }
762
763     private void processNextPending(final Queue<CommitEntry> queue, final State allowedState,
764             final Consumer<CommitEntry> processor) {
765         while (!queue.isEmpty()) {
766             final CommitEntry entry = queue.peek();
767             final SimpleShardDataTreeCohort cohort = entry.cohort;
768
769             if (cohort.isFailed()) {
770                 LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
771                 queue.remove();
772                 continue;
773             }
774
775             if (cohort.getState() == allowedState) {
776                 processor.accept(entry);
777             }
778
779             break;
780         }
781
782         maybeRunOperationOnPendingTransactionsComplete();
783     }
784
785     private void processNextPendingCommit() {
786         processNextPending(pendingCommits, State.COMMIT_PENDING,
787             entry -> startCommit(entry.cohort, entry.cohort.getCandidate()));
788     }
789
790     private boolean peekNextPendingCommit() {
791         final CommitEntry first = pendingCommits.peek();
792         return first != null && first.cohort.getState() == State.COMMIT_PENDING;
793     }
794
795     void startCanCommit(final SimpleShardDataTreeCohort cohort) {
796         final CommitEntry head = pendingTransactions.peek();
797         if (head == null) {
798             LOG.warn("{}: No transactions enqueued while attempting to start canCommit on {}", logContext, cohort);
799             return;
800         }
801         if (!cohort.equals(head.cohort)) {
802             // The tx isn't at the head of the queue so we can't start canCommit at this point. Here we check if this
803             // tx should be moved ahead of other tx's in the READY state in the pendingTransactions queue. If this tx
804             // has other participating shards, it could deadlock with other tx's accessing the same shards
805             // depending on the order the tx's are readied on each shard
806             // (see https://jira.opendaylight.org/browse/CONTROLLER-1836). Therefore, if the preceding participating
807             // shard names for a preceding pending tx, call it A, in the queue matches that of this tx, then this tx
808             // is allowed to be moved ahead of tx A in the queue so it is processed first to avoid potential deadlock
809             // if tx A is behind this tx in the pendingTransactions queue for a preceding shard. In other words, since
810             // canCommmit for this tx was requested before tx A, honor that request. If this tx is moved to the head of
811             // the queue as a result, then proceed with canCommit.
812
813             Collection<String> precedingShardNames = extractPrecedingShardNames(cohort.getParticipatingShardNames());
814             if (precedingShardNames.isEmpty()) {
815                 LOG.debug("{}: Tx {} is scheduled for canCommit step", logContext, cohort.getIdentifier());
816                 return;
817             }
818
819             LOG.debug("{}: Evaluating tx {} for canCommit -  preceding participating shard names {}",
820                     logContext, cohort.getIdentifier(), precedingShardNames);
821             final Iterator<CommitEntry> iter = pendingTransactions.iterator();
822             int index = -1;
823             int moveToIndex = -1;
824             while (iter.hasNext()) {
825                 final CommitEntry entry = iter.next();
826                 ++index;
827
828                 if (cohort.equals(entry.cohort)) {
829                     if (moveToIndex < 0) {
830                         LOG.debug("{}: Not moving tx {} - cannot proceed with canCommit",
831                                 logContext, cohort.getIdentifier());
832                         return;
833                     }
834
835                     LOG.debug("{}: Moving {} to index {} in the pendingTransactions queue",
836                             logContext, cohort.getIdentifier(), moveToIndex);
837                     iter.remove();
838                     insertEntry(pendingTransactions, entry, moveToIndex);
839
840                     if (!cohort.equals(pendingTransactions.peek().cohort)) {
841                         LOG.debug("{}: Tx {} is not at the head of the queue - cannot proceed with canCommit",
842                                 logContext, cohort.getIdentifier());
843                         return;
844                     }
845
846                     LOG.debug("{}: Tx {} is now at the head of the queue - proceeding with canCommit",
847                             logContext, cohort.getIdentifier());
848                     break;
849                 }
850
851                 if (entry.cohort.getState() != State.READY) {
852                     LOG.debug("{}: Skipping pending transaction {} in state {}",
853                             logContext, entry.cohort.getIdentifier(), entry.cohort.getState());
854                     continue;
855                 }
856
857                 final Collection<String> pendingPrecedingShardNames = extractPrecedingShardNames(
858                         entry.cohort.getParticipatingShardNames());
859
860                 if (precedingShardNames.equals(pendingPrecedingShardNames)) {
861                     if (moveToIndex < 0) {
862                         LOG.debug("{}: Preceding shard names {} for pending tx {} match - saving moveToIndex {}",
863                                 logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), index);
864                         moveToIndex = index;
865                     } else {
866                         LOG.debug(
867                             "{}: Preceding shard names {} for pending tx {} match but moveToIndex already set to {}",
868                             logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), moveToIndex);
869                     }
870                 } else {
871                     LOG.debug("{}: Preceding shard names {} for pending tx {} differ - skipping",
872                         logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier());
873                 }
874             }
875         }
876
877         processNextPendingTransaction();
878     }
879
880     private static void insertEntry(final Deque<CommitEntry> queue, final CommitEntry entry, final int atIndex) {
881         if (atIndex == 0) {
882             queue.addFirst(entry);
883             return;
884         }
885
886         LOG.trace("Inserting into Deque at index {}", atIndex);
887
888         Deque<CommitEntry> tempStack = new ArrayDeque<>(atIndex);
889         for (int i = 0; i < atIndex; i++) {
890             tempStack.push(queue.poll());
891         }
892
893         queue.addFirst(entry);
894
895         tempStack.forEach(queue::addFirst);
896     }
897
898     private Collection<String> extractPrecedingShardNames(
899             final java.util.Optional<SortedSet<String>> participatingShardNames) {
900         return participatingShardNames.map((Function<SortedSet<String>, Collection<String>>)
901             set -> set.headSet(shard.getShardName())).orElse(Collections.<String>emptyList());
902     }
903
904     private void failPreCommit(final Throwable cause) {
905         shard.getShardMBean().incrementFailedTransactionsCount();
906         pendingTransactions.poll().cohort.failedPreCommit(cause);
907         processNextPendingTransaction();
908     }
909
910     @SuppressWarnings("checkstyle:IllegalCatch")
911     void startPreCommit(final SimpleShardDataTreeCohort cohort) {
912         final CommitEntry entry = pendingTransactions.peek();
913         Preconditions.checkState(entry != null, "Attempted to pre-commit of %s when no transactions pending", cohort);
914
915         final SimpleShardDataTreeCohort current = entry.cohort;
916         Verify.verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
917
918         LOG.debug("{}: Preparing transaction {}", logContext, current.getIdentifier());
919
920         final DataTreeCandidateTip candidate;
921         try {
922             candidate = tip.prepare(cohort.getDataTreeModification());
923         } catch (RuntimeException e) {
924             failPreCommit(e);
925             return;
926         }
927
928         cohort.userPreCommit(candidate, new FutureCallback<Void>() {
929             @Override
930             public void onSuccess(final Void noop) {
931                 // Set the tip of the data tree.
932                 tip = Verify.verifyNotNull(candidate);
933
934                 entry.lastAccess = readTime();
935
936                 pendingTransactions.remove();
937                 pendingCommits.add(entry);
938
939                 LOG.debug("{}: Transaction {} prepared", logContext, current.getIdentifier());
940
941                 cohort.successfulPreCommit(candidate);
942
943                 processNextPendingTransaction();
944             }
945
946             @Override
947             public void onFailure(final Throwable failure) {
948                 failPreCommit(failure);
949             }
950         });
951     }
952
953     private void failCommit(final Exception cause) {
954         shard.getShardMBean().incrementFailedTransactionsCount();
955         pendingFinishCommits.poll().cohort.failedCommit(cause);
956         processNextPending();
957     }
958
959     @SuppressWarnings("checkstyle:IllegalCatch")
960     private void finishCommit(final SimpleShardDataTreeCohort cohort) {
961         final TransactionIdentifier txId = cohort.getIdentifier();
962         final DataTreeCandidate candidate = cohort.getCandidate();
963
964         LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
965
966         if (tip == candidate) {
967             // All pending candidates have been committed, reset the tip to the data tree.
968             tip = dataTree;
969         }
970
971         try {
972             dataTree.commit(candidate);
973         } catch (Exception e) {
974             LOG.error("{}: Failed to commit transaction {}", logContext, txId, e);
975             failCommit(e);
976             return;
977         }
978
979         allMetadataCommittedTransaction(txId);
980         shard.getShardMBean().incrementCommittedTransactionCount();
981         shard.getShardMBean().setLastCommittedTransactionTime(System.currentTimeMillis());
982
983         // FIXME: propagate journal index
984         pendingFinishCommits.poll().cohort.successfulCommit(UnsignedLong.ZERO, () -> {
985             LOG.trace("{}: Transaction {} committed, proceeding to notify", logContext, txId);
986             notifyListeners(candidate);
987
988             processNextPending();
989         });
990     }
991
992     void startCommit(final SimpleShardDataTreeCohort cohort, final DataTreeCandidate candidate) {
993         final CommitEntry entry = pendingCommits.peek();
994         Preconditions.checkState(entry != null, "Attempted to start commit of %s when no transactions pending", cohort);
995
996         final SimpleShardDataTreeCohort current = entry.cohort;
997         if (!cohort.equals(current)) {
998             LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
999             return;
1000         }
1001
1002         LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
1003
1004         final TransactionIdentifier txId = cohort.getIdentifier();
1005         final Payload payload;
1006         try {
1007             payload = CommitTransactionPayload.create(txId, candidate,
1008                     shard.getDatastoreContext().getInitialPayloadSerializedBufferCapacity());
1009         } catch (IOException e) {
1010             LOG.error("{}: Failed to encode transaction {} candidate {}", logContext, txId, candidate, e);
1011             pendingCommits.poll().cohort.failedCommit(e);
1012             processNextPending();
1013             return;
1014         }
1015
1016         // We process next transactions pending canCommit before we call persistPayload to possibly progress subsequent
1017         // transactions to the COMMIT_PENDING state so the payloads can be batched for replication. This is done for
1018         // single-shard transactions that immediately transition from canCommit to preCommit to commit. Note that
1019         // if the next pending transaction is progressed to COMMIT_PENDING and this method (startCommit) is called,
1020         // the next transaction will not attempt to replicate b/c the current transaction is still at the head of the
1021         // pendingCommits queue.
1022         processNextPendingTransaction();
1023
1024         // After processing next pending transactions, we can now remove the current transaction from pendingCommits.
1025         // Note this must be done before the call to peekNextPendingCommit below so we check the next transaction
1026         // in order to properly determine the batchHint flag for the call to persistPayload.
1027         pendingCommits.remove();
1028         pendingFinishCommits.add(entry);
1029
1030         // See if the next transaction is pending commit (ie in the COMMIT_PENDING state) so it can be batched with
1031         // this transaction for replication.
1032         boolean replicationBatchHint = peekNextPendingCommit();
1033
1034         // Once completed, we will continue via payloadReplicationComplete
1035         shard.persistPayload(txId, payload, replicationBatchHint);
1036
1037         entry.lastAccess = shard.ticker().read();
1038
1039         LOG.debug("{}: Transaction {} submitted to persistence", logContext, txId);
1040
1041         // Process the next transaction pending commit, if any. If there is one it will be batched with this
1042         // transaction for replication.
1043         processNextPendingCommit();
1044     }
1045
1046     Collection<ActorRef> getCohortActors() {
1047         return cohortRegistry.getCohortActors();
1048     }
1049
1050     void processCohortRegistryCommand(final ActorRef sender, final CohortRegistryCommand message) {
1051         cohortRegistry.process(sender, message);
1052     }
1053
1054     @Override
1055     ShardDataTreeCohort createFailedCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1056             final Exception failure) {
1057         final SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId, failure);
1058         pendingTransactions.add(new CommitEntry(cohort, readTime()));
1059         return cohort;
1060     }
1061
1062     @Override
1063     ShardDataTreeCohort createReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1064             final java.util.Optional<SortedSet<String>> participatingShardNames) {
1065         SimpleShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(this, mod, txId,
1066                 cohortRegistry.createCohort(schemaContext, txId, shard::executeInSelf,
1067                         COMMIT_STEP_TIMEOUT), participatingShardNames);
1068         pendingTransactions.add(new CommitEntry(cohort, readTime()));
1069         return cohort;
1070     }
1071
1072     // Exposed for ShardCommitCoordinator so it does not have deal with local histories (it does not care), this mimics
1073     // the newReadWriteTransaction()
1074     ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
1075             final java.util.Optional<SortedSet<String>> participatingShardNames) {
1076         if (txId.getHistoryId().getHistoryId() == 0) {
1077             return createReadyCohort(txId, mod, participatingShardNames);
1078         }
1079
1080         return ensureTransactionChain(txId.getHistoryId(), null).createReadyCohort(txId, mod, participatingShardNames);
1081     }
1082
1083     @SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
1084     void checkForExpiredTransactions(final long transactionCommitTimeoutMillis,
1085             final Function<SimpleShardDataTreeCohort, Optional<Long>> accessTimeUpdater) {
1086         final long timeout = TimeUnit.MILLISECONDS.toNanos(transactionCommitTimeoutMillis);
1087         final long now = readTime();
1088
1089         final Queue<CommitEntry> currentQueue = !pendingFinishCommits.isEmpty() ? pendingFinishCommits :
1090             !pendingCommits.isEmpty() ? pendingCommits : pendingTransactions;
1091         final CommitEntry currentTx = currentQueue.peek();
1092         if (currentTx == null) {
1093             // Empty queue, no-op
1094             return;
1095         }
1096
1097         long delta = now - currentTx.lastAccess;
1098         if (delta < timeout) {
1099             // Not expired yet, bail
1100             return;
1101         }
1102
1103         final Optional<Long> updateOpt = accessTimeUpdater.apply(currentTx.cohort);
1104         if (updateOpt.isPresent()) {
1105             final long newAccess =  updateOpt.get().longValue();
1106             final long newDelta = now - newAccess;
1107             if (newDelta < delta) {
1108                 LOG.debug("{}: Updated current transaction {} access time", logContext,
1109                     currentTx.cohort.getIdentifier());
1110                 currentTx.lastAccess = newAccess;
1111                 delta = newDelta;
1112             }
1113
1114             if (delta < timeout) {
1115                 // Not expired yet, bail
1116                 return;
1117             }
1118         }
1119
1120         final long deltaMillis = TimeUnit.NANOSECONDS.toMillis(delta);
1121         final State state = currentTx.cohort.getState();
1122
1123         LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
1124             currentTx.cohort.getIdentifier(), deltaMillis, state);
1125         boolean processNext = true;
1126         final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
1127                 + deltaMillis + "ms");
1128
1129         switch (state) {
1130             case CAN_COMMIT_PENDING:
1131                 currentQueue.remove().cohort.failedCanCommit(cohortFailure);
1132                 break;
1133             case CAN_COMMIT_COMPLETE:
1134                 // The suppression of the FindBugs "DB_DUPLICATE_SWITCH_CLAUSES" warning pertains to this clause
1135                 // whose code is duplicated with PRE_COMMIT_COMPLETE. The clauses aren't combined in case the code
1136                 // in PRE_COMMIT_COMPLETE is changed.
1137                 currentQueue.remove().cohort.reportFailure(cohortFailure);
1138                 break;
1139             case PRE_COMMIT_PENDING:
1140                 currentQueue.remove().cohort.failedPreCommit(cohortFailure);
1141                 break;
1142             case PRE_COMMIT_COMPLETE:
1143                 // FIXME: this is a legacy behavior problem. Three-phase commit protocol specifies that after we
1144                 //        are ready we should commit the transaction, not abort it. Our current software stack does
1145                 //        not allow us to do that consistently, because we persist at the time of commit, hence
1146                 //        we can end up in a state where we have pre-committed a transaction, then a leader failover
1147                 //        occurred ... the new leader does not see the pre-committed transaction and does not have
1148                 //        a running timer. To fix this we really need two persistence events.
1149                 //
1150                 //        The first one, done at pre-commit time will hold the transaction payload. When consensus
1151                 //        is reached, we exit the pre-commit phase and start the pre-commit timer. Followers do not
1152                 //        apply the state in this event.
1153                 //
1154                 //        The second one, done at commit (or abort) time holds only the transaction identifier and
1155                 //        signals to followers that the state should (or should not) be applied.
1156                 //
1157                 //        In order to make the pre-commit timer working across failovers, though, we need
1158                 //        a per-shard cluster-wide monotonic time, so a follower becoming the leader can accurately
1159                 //        restart the timer.
1160                 currentQueue.remove().cohort.reportFailure(cohortFailure);
1161                 break;
1162             case COMMIT_PENDING:
1163                 LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
1164                     currentTx.cohort.getIdentifier());
1165                 currentTx.lastAccess = now;
1166                 processNext = false;
1167                 return;
1168             case READY:
1169                 currentQueue.remove().cohort.reportFailure(cohortFailure);
1170                 break;
1171             case ABORTED:
1172             case COMMITTED:
1173             case FAILED:
1174             default:
1175                 currentQueue.remove();
1176         }
1177
1178         if (processNext) {
1179             processNextPending();
1180         }
1181     }
1182
1183     boolean startAbort(final SimpleShardDataTreeCohort cohort) {
1184         final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
1185                 pendingTransactions).iterator();
1186         if (!it.hasNext()) {
1187             LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
1188             return true;
1189         }
1190
1191         // First entry is special, as it may already be committing
1192         final CommitEntry first = it.next();
1193         if (cohort.equals(first.cohort)) {
1194             if (cohort.getState() != State.COMMIT_PENDING) {
1195                 LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
1196                     cohort.getIdentifier());
1197
1198                 it.remove();
1199                 if (cohort.getCandidate() != null) {
1200                     rebaseTransactions(it, dataTree);
1201                 }
1202
1203                 processNextPending();
1204                 return true;
1205             }
1206
1207             LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
1208             return false;
1209         }
1210
1211         DataTreeTip newTip = MoreObjects.firstNonNull(first.cohort.getCandidate(), dataTree);
1212         while (it.hasNext()) {
1213             final CommitEntry e = it.next();
1214             if (cohort.equals(e.cohort)) {
1215                 LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
1216
1217                 it.remove();
1218                 if (cohort.getCandidate() != null) {
1219                     rebaseTransactions(it, newTip);
1220                 }
1221
1222                 return true;
1223             } else {
1224                 newTip = MoreObjects.firstNonNull(e.cohort.getCandidate(), newTip);
1225             }
1226         }
1227
1228         LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
1229         return true;
1230     }
1231
1232     @SuppressWarnings("checkstyle:IllegalCatch")
1233     private void rebaseTransactions(final Iterator<CommitEntry> iter, @Nonnull final DataTreeTip newTip) {
1234         tip = Preconditions.checkNotNull(newTip);
1235         while (iter.hasNext()) {
1236             final SimpleShardDataTreeCohort cohort = iter.next().cohort;
1237             if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
1238                 LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
1239
1240                 try {
1241                     tip.validate(cohort.getDataTreeModification());
1242                 } catch (DataValidationFailedException | RuntimeException e) {
1243                     LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
1244                     cohort.reportFailure(e);
1245                 }
1246             } else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
1247                 LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
1248
1249                 try {
1250                     tip.validate(cohort.getDataTreeModification());
1251                     DataTreeCandidateTip candidate = tip.prepare(cohort.getDataTreeModification());
1252
1253                     cohort.setNewCandidate(candidate);
1254                     tip = candidate;
1255                 } catch (RuntimeException | DataValidationFailedException e) {
1256                     LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
1257                     cohort.reportFailure(e);
1258                 }
1259             }
1260         }
1261     }
1262
1263     void setRunOnPendingTransactionsComplete(final Runnable operation) {
1264         runOnPendingTransactionsComplete = operation;
1265         maybeRunOperationOnPendingTransactionsComplete();
1266     }
1267
1268     private void maybeRunOperationOnPendingTransactionsComplete() {
1269         if (runOnPendingTransactionsComplete != null && !anyPendingTransactions()) {
1270             LOG.debug("{}: Pending transactions complete - running operation {}", logContext,
1271                     runOnPendingTransactionsComplete);
1272
1273             runOnPendingTransactionsComplete.run();
1274             runOnPendingTransactionsComplete = null;
1275         }
1276     }
1277
1278     ShardStats getStats() {
1279         return shard.getShardMBean();
1280     }
1281
1282     Iterator<SimpleShardDataTreeCohort> cohortIterator() {
1283         return Iterables.transform(Iterables.concat(pendingFinishCommits, pendingCommits, pendingTransactions),
1284             e -> e.cohort).iterator();
1285     }
1286
1287     void removeTransactionChain(final LocalHistoryIdentifier id) {
1288         if (transactionChains.remove(id) != null) {
1289             LOG.debug("{}: Removed transaction chain {}", logContext, id);
1290         }
1291     }
1292 }