Fix warnings/javadocs in sal-distributed-datastore
[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         try {
372             cohortEntry.abort();
373
374             shard.getShardMBean().incrementAbortTransactionsCount();
375
376             if (sender != null) {
377                 sender.tell(AbortTransactionReply.instance(cohortEntry.getClientVersion()).toSerializable(), self);
378             }
379         } catch (Exception e) {
380             log.error("{}: An exception happened during abort", name, e);
381
382             if (sender != null) {
383                 sender.tell(new Failure(e), self);
384             }
385         }
386     }
387
388     void checkForExpiredTransactions(final long timeout, final Shard shard) {
389         Iterator<CohortEntry> iter = cohortCache.values().iterator();
390         while (iter.hasNext()) {
391             CohortEntry cohortEntry = iter.next();
392             if (cohortEntry.isFailed()) {
393                 iter.remove();
394             }
395         }
396     }
397
398     void abortPendingTransactions(final String reason, final Shard shard) {
399         final Failure failure = new Failure(new RuntimeException(reason));
400         Collection<ShardDataTreeCohort> pending = dataTree.getAndClearPendingTransactions();
401
402         log.debug("{}: Aborting {} pending queued transactions", name, pending.size());
403
404         for (ShardDataTreeCohort cohort : pending) {
405             CohortEntry cohortEntry = cohortCache.remove(cohort.getIdentifier());
406             if (cohortEntry == null) {
407                 continue;
408             }
409
410             if (cohortEntry.getReplySender() != null) {
411                 cohortEntry.getReplySender().tell(failure, shard.self());
412             }
413         }
414
415         cohortCache.clear();
416     }
417
418     Collection<?> convertPendingTransactionsToMessages(final int maxModificationsPerBatch) {
419         final Collection<VersionedExternalizableMessage> messages = new ArrayList<>();
420         for (ShardDataTreeCohort cohort : dataTree.getAndClearPendingTransactions()) {
421             CohortEntry cohortEntry = cohortCache.remove(cohort.getIdentifier());
422             if (cohortEntry == null) {
423                 continue;
424             }
425
426             final Deque<BatchedModifications> newMessages = new ArrayDeque<>();
427             cohortEntry.getDataTreeModification().applyToCursor(new AbstractBatchedModificationsCursor() {
428                 @Override
429                 protected BatchedModifications getModifications() {
430                     final BatchedModifications lastBatch = newMessages.peekLast();
431
432                     if (lastBatch != null && lastBatch.getModifications().size() >= maxModificationsPerBatch) {
433                         return lastBatch;
434                     }
435
436                     // Allocate a new message
437                     final BatchedModifications ret = new BatchedModifications(cohortEntry.getTransactionID(),
438                         cohortEntry.getClientVersion());
439                     newMessages.add(ret);
440                     return ret;
441                 }
442             });
443
444             final BatchedModifications last = newMessages.peekLast();
445             if (last != null) {
446                 final boolean immediate = cohortEntry.isDoImmediateCommit();
447                 last.setDoCommitOnReady(immediate);
448                 last.setReady(true);
449                 last.setTotalMessagesSent(newMessages.size());
450
451                 messages.addAll(newMessages);
452
453                 if (!immediate) {
454                     switch (cohort.getState()) {
455                         case CAN_COMMIT_COMPLETE:
456                         case CAN_COMMIT_PENDING:
457                             messages.add(new CanCommitTransaction(cohortEntry.getTransactionID(),
458                                 cohortEntry.getClientVersion()));
459                             break;
460                         case PRE_COMMIT_COMPLETE:
461                         case PRE_COMMIT_PENDING:
462                             messages.add(new CommitTransaction(cohortEntry.getTransactionID(),
463                                 cohortEntry.getClientVersion()));
464                             break;
465                         default:
466                             break;
467                     }
468                 }
469             }
470         }
471
472         return messages;
473     }
474
475     @VisibleForTesting
476     void setCohortDecorator(final CohortDecorator cohortDecorator) {
477         this.cohortDecorator = cohortDecorator;
478     }
479 }

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