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

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.