Improve LocalProxyTransaction.doExists()
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / ShardCommitCoordinator.java
1 /*
2  * Copyright (c) 2014 Brocade Communications 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 static java.util.Objects.requireNonNull;
11
12 import akka.actor.ActorRef;
13 import akka.actor.Status.Failure;
14 import akka.serialization.Serialization;
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.primitives.UnsignedLong;
17 import com.google.common.util.concurrent.FutureCallback;
18 import java.util.ArrayDeque;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.Deque;
23 import java.util.HashMap;
24 import java.util.LinkedList;
25 import java.util.Map;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
28 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
29 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
30 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
31 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
32 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply;
33 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
34 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
35 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
36 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
37 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
38 import org.opendaylight.controller.cluster.datastore.messages.VersionedExternalizableMessage;
39 import org.opendaylight.controller.cluster.datastore.utils.AbstractBatchedModificationsCursor;
40 import org.opendaylight.yangtools.concepts.Identifier;
41 import org.opendaylight.yangtools.yang.common.Empty;
42 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
43 import org.slf4j.Logger;
44
45 /**
46  * Coordinates commits for a shard ensuring only one concurrent 3-phase commit.
47  *
48  * @author Thomas Pantelis
49  */
50 final class ShardCommitCoordinator {
51
52     // Interface hook for unit tests to replace or decorate the ShardDataTreeCohorts.
53     @VisibleForTesting
54     public interface CohortDecorator {
55         ShardDataTreeCohort decorate(Identifier transactionID, ShardDataTreeCohort actual);
56     }
57
58     private final Map<Identifier, CohortEntry> cohortCache = new HashMap<>();
59
60     private final ShardDataTree dataTree;
61
62     private final Logger log;
63
64     private final String name;
65
66     // This is a hook for unit tests to replace or decorate the ShardDataTreeCohorts.
67     @VisibleForTesting
68     private CohortDecorator cohortDecorator;
69
70     private ReadyTransactionReply readyTransactionReply;
71
72     ShardCommitCoordinator(final ShardDataTree dataTree, final Logger log, final String name) {
73         this.log = log;
74         this.name = name;
75         this.dataTree = requireNonNull(dataTree);
76     }
77
78     int getCohortCacheSize() {
79         return cohortCache.size();
80     }
81
82     private String persistenceId() {
83         return dataTree.logContext();
84     }
85
86     private ReadyTransactionReply readyTransactionReply(final ActorRef cohort) {
87         if (readyTransactionReply == null) {
88             readyTransactionReply = new ReadyTransactionReply(Serialization.serializedActorPath(cohort));
89         }
90
91         return readyTransactionReply;
92     }
93
94     /**
95      * This method is called to ready a transaction that was prepared by ShardTransaction actor. It caches
96      * the prepared cohort entry for the given transactions ID in preparation for the subsequent 3-phase commit.
97      *
98      * @param ready the ForwardedReadyTransaction message to process
99      * @param sender the sender of the message
100      * @param shard the transaction's shard actor
101      */
102     void handleForwardedReadyTransaction(final ForwardedReadyTransaction ready, final ActorRef sender,
103             final Shard shard) {
104         log.debug("{}: Readying transaction {}, client version {}", name,
105                 ready.getTransactionId(), ready.getTxnClientVersion());
106
107         final ShardDataTreeCohort cohort = ready.getTransaction().ready(ready.getParticipatingShardNames());
108         final CohortEntry cohortEntry = CohortEntry.createReady(cohort, ready.getTxnClientVersion());
109         cohortCache.put(cohortEntry.getTransactionId(), cohortEntry);
110
111         if (ready.isDoImmediateCommit()) {
112             cohortEntry.setDoImmediateCommit(true);
113             cohortEntry.setReplySender(sender);
114             cohortEntry.setShard(shard);
115             handleCanCommit(cohortEntry);
116         } else {
117             // The caller does not want immediate commit - the 3-phase commit will be coordinated by the
118             // front-end so send back a ReadyTransactionReply with our actor path.
119             sender.tell(readyTransactionReply(shard.self()), shard.self());
120         }
121     }
122
123     /**
124      * This method handles a BatchedModifications message for a transaction being prepared directly on the
125      * Shard actor instead of via a ShardTransaction actor. If there's no currently cached
126      * DOMStoreWriteTransaction, one is created. The batched modifications are applied to the write Tx. If
127      * the BatchedModifications is ready to commit then a DOMStoreThreePhaseCommitCohort is created.
128      *
129      * @param batched the BatchedModifications message to process
130      * @param sender the sender of the message
131      */
132     void handleBatchedModifications(final BatchedModifications batched, final ActorRef sender, final Shard shard) {
133         CohortEntry cohortEntry = cohortCache.get(batched.getTransactionId());
134         if (cohortEntry == null || cohortEntry.isSealed()) {
135             cohortEntry = CohortEntry.createOpen(dataTree.newReadWriteTransaction(batched.getTransactionId()),
136                 batched.getVersion());
137             cohortCache.put(cohortEntry.getTransactionId(), cohortEntry);
138         }
139
140         if (log.isDebugEnabled()) {
141             log.debug("{}: Applying {} batched modifications for Tx {}", name,
142                     batched.getModifications().size(), batched.getTransactionId());
143         }
144
145         cohortEntry.applyModifications(batched.getModifications());
146
147         if (batched.isReady()) {
148             if (cohortEntry.getLastBatchedModificationsException() != null) {
149                 cohortCache.remove(cohortEntry.getTransactionId());
150                 throw cohortEntry.getLastBatchedModificationsException();
151             }
152
153             if (cohortEntry.getTotalBatchedModificationsReceived() != batched.getTotalMessagesSent()) {
154                 cohortCache.remove(cohortEntry.getTransactionId());
155                 throw new IllegalStateException(String.format(
156                         "The total number of batched messages received %d does not match the number sent %d",
157                         cohortEntry.getTotalBatchedModificationsReceived(), batched.getTotalMessagesSent()));
158             }
159
160             if (log.isDebugEnabled()) {
161                 log.debug("{}: Readying Tx {} of {} operations, client version {}", name,
162                         batched.getTransactionId(), cohortEntry.getTotalOperationsProcessed(), batched.getVersion());
163             }
164
165             cohortEntry.setDoImmediateCommit(batched.isDoCommitOnReady());
166             cohortEntry.ready(batched.getParticipatingShardNames(), cohortDecorator);
167
168             if (batched.isDoCommitOnReady()) {
169                 cohortEntry.setReplySender(sender);
170                 cohortEntry.setShard(shard);
171                 handleCanCommit(cohortEntry);
172             } else {
173                 sender.tell(readyTransactionReply(shard.self()), shard.self());
174             }
175         } else {
176             sender.tell(new BatchedModificationsReply(batched.getModifications().size()), shard.self());
177         }
178     }
179
180     /**
181      * This method handles {@link ReadyLocalTransaction} message. All transaction modifications have
182      * been prepared beforehand by the sender and we just need to drive them through into the
183      * dataTree.
184      *
185      * @param message the ReadyLocalTransaction message to process
186      * @param sender the sender of the message
187      * @param shard the transaction's shard actor
188      */
189     void handleReadyLocalTransaction(final ReadyLocalTransaction message, final ActorRef sender, final Shard shard) {
190         final TransactionIdentifier txId = message.getTransactionId();
191         final ShardDataTreeCohort cohort = dataTree.newReadyCohort(txId, message.getModification(),
192                 message.getParticipatingShardNames());
193         final CohortEntry cohortEntry = CohortEntry.createReady(cohort, DataStoreVersions.CURRENT_VERSION);
194         cohortCache.put(cohortEntry.getTransactionId(), cohortEntry);
195         cohortEntry.setDoImmediateCommit(message.isDoCommitOnReady());
196
197         log.debug("{}: Applying local modifications for Tx {}", name, txId);
198
199         if (message.isDoCommitOnReady()) {
200             cohortEntry.setReplySender(sender);
201             cohortEntry.setShard(shard);
202             handleCanCommit(cohortEntry);
203         } else {
204             sender.tell(readyTransactionReply(shard.self()), shard.self());
205         }
206     }
207
208     Collection<BatchedModifications> createForwardedBatchedModifications(final BatchedModifications from,
209             final int maxModificationsPerBatch) {
210         CohortEntry cohortEntry = cohortCache.remove(from.getTransactionId());
211         if (cohortEntry == null || cohortEntry.getTransaction() == null) {
212             return Collections.singletonList(from);
213         }
214
215         cohortEntry.applyModifications(from.getModifications());
216
217         final LinkedList<BatchedModifications> newModifications = new LinkedList<>();
218         cohortEntry.getTransaction().getSnapshot().applyToCursor(new AbstractBatchedModificationsCursor() {
219             @Override
220             protected BatchedModifications getModifications() {
221                 if (newModifications.isEmpty()
222                         || newModifications.getLast().getModifications().size() >= maxModificationsPerBatch) {
223                     newModifications.add(new BatchedModifications(from.getTransactionId(), from.getVersion()));
224                 }
225
226                 return newModifications.getLast();
227             }
228         });
229
230         BatchedModifications last = newModifications.getLast();
231         last.setDoCommitOnReady(from.isDoCommitOnReady());
232         if (from.isReady()) {
233             last.setReady(from.getParticipatingShardNames());
234         }
235         last.setTotalMessagesSent(newModifications.size());
236         return newModifications;
237     }
238
239     private void handleCanCommit(final CohortEntry cohortEntry) {
240         cohortEntry.canCommit(new FutureCallback<>() {
241             @Override
242             public void onSuccess(final Empty result) {
243                 log.debug("{}: canCommit for {}: success", name, cohortEntry.getTransactionId());
244
245                 if (cohortEntry.isDoImmediateCommit()) {
246                     doCommit(cohortEntry);
247                 } else {
248                     cohortEntry.getReplySender().tell(
249                         CanCommitTransactionReply.yes(cohortEntry.getClientVersion()).toSerializable(),
250                         cohortEntry.getShard().self());
251                 }
252             }
253
254             @Override
255             public void onFailure(final Throwable failure) {
256                 log.debug("{}: An exception occurred during canCommit for {}", name, cohortEntry.getTransactionId(),
257                     failure);
258
259                 cohortCache.remove(cohortEntry.getTransactionId());
260                 cohortEntry.getReplySender().tell(new Failure(failure), cohortEntry.getShard().self());
261             }
262         });
263     }
264
265     /**
266      * This method handles the canCommit phase for a transaction.
267      *
268      * @param transactionID the ID of the transaction to canCommit
269      * @param sender the actor to which to send the response
270      * @param shard the transaction's shard actor
271      */
272     void handleCanCommit(final Identifier transactionID, final ActorRef sender, final Shard shard) {
273         // Lookup the cohort entry that was cached previously (or should have been) by
274         // transactionReady (via the ForwardedReadyTransaction message).
275         final CohortEntry cohortEntry = cohortCache.get(transactionID);
276         if (cohortEntry == null) {
277             // Either canCommit was invoked before ready (shouldn't happen) or a long time passed
278             // between canCommit and ready and the entry was expired from the cache or it was aborted.
279             IllegalStateException ex = new IllegalStateException(
280                     String.format("%s: Cannot canCommit transaction %s - no cohort entry found", name, transactionID));
281             log.error("{}: Inconsistency during transaction {} canCommit", name, transactionID, ex);
282             sender.tell(new Failure(ex), shard.self());
283             return;
284         }
285
286         cohortEntry.setReplySender(sender);
287         cohortEntry.setShard(shard);
288
289         handleCanCommit(cohortEntry);
290     }
291
292     void doCommit(final CohortEntry cohortEntry) {
293         log.debug("{}: Committing transaction {}", name, cohortEntry.getTransactionId());
294
295         // We perform the preCommit phase here atomically with the commit phase. This is an
296         // optimization to eliminate the overhead of an extra preCommit message. We lose front-end
297         // coordination of preCommit across shards in case of failure but preCommit should not
298         // normally fail since we ensure only one concurrent 3-phase commit.
299         cohortEntry.preCommit(new FutureCallback<DataTreeCandidate>() {
300             @Override
301             public void onSuccess(final DataTreeCandidate candidate) {
302                 finishCommit(cohortEntry.getReplySender(), cohortEntry);
303             }
304
305             @Override
306             public void onFailure(final Throwable failure) {
307                 log.error("{} An exception occurred while preCommitting transaction {}", name,
308                         cohortEntry.getTransactionId(), failure);
309
310                 cohortCache.remove(cohortEntry.getTransactionId());
311                 cohortEntry.getReplySender().tell(new Failure(failure), cohortEntry.getShard().self());
312             }
313         });
314     }
315
316     void finishCommit(final @NonNull ActorRef sender, final @NonNull CohortEntry cohortEntry) {
317         log.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionId());
318
319         cohortEntry.commit(new FutureCallback<UnsignedLong>() {
320             @Override
321             public void onSuccess(final UnsignedLong result) {
322                 final TransactionIdentifier txId = cohortEntry.getTransactionId();
323                 log.debug("{}: Transaction {} committed as {}, sending response to {}", persistenceId(), txId, result,
324                     sender);
325
326                 cohortCache.remove(cohortEntry.getTransactionId());
327                 sender.tell(CommitTransactionReply.instance(cohortEntry.getClientVersion()).toSerializable(),
328                     cohortEntry.getShard().self());
329             }
330
331             @Override
332             public void onFailure(final Throwable failure) {
333                 final TransactionIdentifier txId = cohortEntry.getTransactionId();
334                 log.error("{}, An exception occurred while committing transaction {}", persistenceId(), txId, failure);
335
336                 cohortCache.remove(cohortEntry.getTransactionId());
337                 sender.tell(new Failure(failure), cohortEntry.getShard().self());
338             }
339         });
340     }
341
342     /**
343      * This method handles the preCommit and commit phases for a transaction.
344      *
345      * @param transactionID the ID of the transaction to commit
346      * @param sender the actor to which to send the response
347      * @param shard the transaction's shard actor
348      */
349     void handleCommit(final Identifier transactionID, final ActorRef sender, final Shard shard) {
350         final CohortEntry cohortEntry = cohortCache.get(transactionID);
351         if (cohortEntry == null) {
352             // Either a long time passed between canCommit and commit and the entry was expired from the cache
353             // or it was aborted.
354             IllegalStateException ex = new IllegalStateException(
355                     String.format("%s: Cannot commit transaction %s - no cohort entry found", name, transactionID));
356             log.error("{}: Inconsistency during transaction {} commit", name, transactionID, ex);
357             sender.tell(new Failure(ex), shard.self());
358             return;
359         }
360
361         cohortEntry.setReplySender(sender);
362         doCommit(cohortEntry);
363     }
364
365     @SuppressWarnings("checkstyle:IllegalCatch")
366     void handleAbort(final Identifier transactionID, final ActorRef sender, final Shard shard) {
367         CohortEntry cohortEntry = cohortCache.remove(transactionID);
368         if (cohortEntry == null) {
369             return;
370         }
371
372         log.debug("{}: Aborting transaction {}", name, transactionID);
373
374         final ActorRef self = shard.getSelf();
375         cohortEntry.abort(new FutureCallback<>() {
376             @Override
377             public void onSuccess(final Empty result) {
378                 if (sender != null) {
379                     sender.tell(AbortTransactionReply.instance(cohortEntry.getClientVersion()).toSerializable(), self);
380                 }
381             }
382
383             @Override
384             public void onFailure(final Throwable failure) {
385                 log.error("{}: An exception happened during abort", name, failure);
386
387                 if (sender != null) {
388                     sender.tell(new Failure(failure), self);
389                 }
390             }
391         });
392
393         shard.getShardMBean().incrementAbortTransactionsCount();
394     }
395
396     void checkForExpiredTransactions(final long timeout, final Shard shard) {
397         cohortCache.values().removeIf(CohortEntry::isFailed);
398     }
399
400     void abortPendingTransactions(final String reason, final Shard shard) {
401         final Failure failure = new Failure(new RuntimeException(reason));
402         Collection<ShardDataTreeCohort> pending = dataTree.getAndClearPendingTransactions();
403
404         log.debug("{}: Aborting {} pending queued transactions", name, pending.size());
405
406         for (ShardDataTreeCohort cohort : pending) {
407             CohortEntry cohortEntry = cohortCache.remove(cohort.getIdentifier());
408             if (cohortEntry == null) {
409                 continue;
410             }
411
412             if (cohortEntry.getReplySender() != null) {
413                 cohortEntry.getReplySender().tell(failure, shard.self());
414             }
415         }
416
417         cohortCache.clear();
418     }
419
420     Collection<?> convertPendingTransactionsToMessages(final int maxModificationsPerBatch) {
421         final Collection<VersionedExternalizableMessage> messages = new ArrayList<>();
422         for (ShardDataTreeCohort cohort : dataTree.getAndClearPendingTransactions()) {
423             CohortEntry cohortEntry = cohortCache.remove(cohort.getIdentifier());
424             if (cohortEntry == null) {
425                 continue;
426             }
427
428             final Deque<BatchedModifications> newMessages = new ArrayDeque<>();
429             cohortEntry.getDataTreeModification().applyToCursor(new AbstractBatchedModificationsCursor() {
430                 @Override
431                 protected BatchedModifications getModifications() {
432                     final BatchedModifications lastBatch = newMessages.peekLast();
433
434                     if (lastBatch != null && lastBatch.getModifications().size() >= maxModificationsPerBatch) {
435                         return lastBatch;
436                     }
437
438                     // Allocate a new message
439                     final BatchedModifications ret = new BatchedModifications(cohortEntry.getTransactionId(),
440                         cohortEntry.getClientVersion());
441                     newMessages.add(ret);
442                     return ret;
443                 }
444             });
445
446             final BatchedModifications last = newMessages.peekLast();
447             if (last != null) {
448                 final boolean immediate = cohortEntry.isDoImmediateCommit();
449                 last.setDoCommitOnReady(immediate);
450                 last.setReady(cohortEntry.getParticipatingShardNames());
451                 last.setTotalMessagesSent(newMessages.size());
452
453                 messages.addAll(newMessages);
454
455                 if (!immediate) {
456                     switch (cohort.getState()) {
457                         case CAN_COMMIT_COMPLETE:
458                         case CAN_COMMIT_PENDING:
459                             messages.add(new CanCommitTransaction(cohortEntry.getTransactionId(),
460                                 cohortEntry.getClientVersion()));
461                             break;
462                         case PRE_COMMIT_COMPLETE:
463                         case PRE_COMMIT_PENDING:
464                             messages.add(new CommitTransaction(cohortEntry.getTransactionId(),
465                                 cohortEntry.getClientVersion()));
466                             break;
467                         default:
468                             break;
469                     }
470                 }
471             }
472         }
473
474         return messages;
475     }
476
477     @VisibleForTesting
478     void setCohortDecorator(final CohortDecorator cohortDecorator) {
479         this.cohortDecorator = cohortDecorator;
480     }
481 }