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

©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.