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