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