2 * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.cluster.datastore;
10 import static java.util.Objects.requireNonNull;
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;
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;
46 * Coordinates commits for a shard ensuring only one concurrent 3-phase commit.
48 * @author Thomas Pantelis
50 @Deprecated(since = "9.0.0", forRemoval = true)
51 final class ShardCommitCoordinator {
53 // Interface hook for unit tests to replace or decorate the ShardDataTreeCohorts.
55 public interface CohortDecorator {
56 ShardDataTreeCohort decorate(Identifier transactionID, ShardDataTreeCohort actual);
59 private final Map<Identifier, CohortEntry> cohortCache = new HashMap<>();
61 private final ShardDataTree dataTree;
63 private final Logger log;
65 private final String name;
67 // This is a hook for unit tests to replace or decorate the ShardDataTreeCohorts.
69 private CohortDecorator cohortDecorator;
71 private ReadyTransactionReply readyTransactionReply;
73 ShardCommitCoordinator(final ShardDataTree dataTree, final Logger log, final String name) {
76 this.dataTree = requireNonNull(dataTree);
79 int getCohortCacheSize() {
80 return cohortCache.size();
83 private String persistenceId() {
84 return dataTree.logContext();
87 private ReadyTransactionReply readyTransactionReply(final ActorRef cohort) {
88 if (readyTransactionReply == null) {
89 readyTransactionReply = new ReadyTransactionReply(Serialization.serializedActorPath(cohort));
92 return readyTransactionReply;
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.
99 * @param ready the ForwardedReadyTransaction message to process
100 * @param sender the sender of the message
101 * @param shard the transaction's shard actor
103 void handleForwardedReadyTransaction(final ForwardedReadyTransaction ready, final ActorRef sender,
105 log.debug("{}: Readying transaction {}, client version {}", name,
106 ready.getTransactionId(), ready.getTxnClientVersion());
108 final ShardDataTreeCohort cohort = ready.getTransaction().ready(ready.getParticipatingShardNames());
109 final CohortEntry cohortEntry = CohortEntry.createReady(cohort, ready.getTxnClientVersion());
110 cohortCache.put(cohortEntry.getTransactionId(), cohortEntry);
112 if (ready.isDoImmediateCommit()) {
113 cohortEntry.setDoImmediateCommit(true);
114 cohortEntry.setReplySender(sender);
115 cohortEntry.setShard(shard);
116 handleCanCommit(cohortEntry);
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());
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.
130 * @param batched the BatchedModifications message to process
131 * @param sender the sender of the message
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);
142 if (log.isDebugEnabled()) {
143 log.debug("{}: Applying {} batched modifications for Tx {}", name,
144 batched.getModifications().size(), batched.getTransactionId());
147 cohortEntry.applyModifications(batched.getModifications());
149 if (batched.isReady()) {
150 if (cohortEntry.getLastBatchedModificationsException() != null) {
151 cohortCache.remove(cohortEntry.getTransactionId());
152 throw cohortEntry.getLastBatchedModificationsException();
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()));
162 if (log.isDebugEnabled()) {
163 log.debug("{}: Readying Tx {} of {} operations, client version {}", name,
164 batched.getTransactionId(), cohortEntry.getTotalOperationsProcessed(), batched.getVersion());
167 cohortEntry.setDoImmediateCommit(batched.isDoCommitOnReady());
168 cohortEntry.ready(batched.getParticipatingShardNames(), cohortDecorator);
170 if (batched.isDoCommitOnReady()) {
171 cohortEntry.setReplySender(sender);
172 cohortEntry.setShard(shard);
173 handleCanCommit(cohortEntry);
175 sender.tell(readyTransactionReply(shard.self()), shard.self());
178 sender.tell(new BatchedModificationsReply(batched.getModifications().size()), shard.self());
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
187 * @param message the ReadyLocalTransaction message to process
188 * @param sender the sender of the message
189 * @param shard the transaction's shard actor
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());
199 log.debug("{}: Applying local modifications for Tx {}", name, txId);
201 if (message.isDoCommitOnReady()) {
202 cohortEntry.setReplySender(sender);
203 cohortEntry.setShard(shard);
204 handleCanCommit(cohortEntry);
206 sender.tell(readyTransactionReply(shard.self()), shard.self());
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);
218 cohortEntry.applyModifications(from.getModifications());
220 final LinkedList<BatchedModifications> newModifications = new LinkedList<>();
221 cohortEntry.getTransaction().getSnapshot().applyToCursor(new AbstractBatchedModificationsCursor() {
223 protected BatchedModifications getModifications() {
224 if (newModifications.isEmpty()
225 || newModifications.getLast().getModifications().size() >= maxModificationsPerBatch) {
226 newModifications.add(new BatchedModifications(from.getTransactionId(), from.getVersion()));
229 return newModifications.getLast();
233 BatchedModifications last = newModifications.getLast();
234 last.setDoCommitOnReady(from.isDoCommitOnReady());
235 if (from.isReady()) {
236 last.setReady(from.getParticipatingShardNames());
238 last.setTotalMessagesSent(newModifications.size());
239 return newModifications;
242 private void handleCanCommit(final CohortEntry cohortEntry) {
243 cohortEntry.canCommit(new FutureCallback<>() {
245 public void onSuccess(final Empty result) {
246 log.debug("{}: canCommit for {}: success", name, cohortEntry.getTransactionId());
248 if (cohortEntry.isDoImmediateCommit()) {
249 doCommit(cohortEntry);
251 cohortEntry.getReplySender().tell(
252 CanCommitTransactionReply.yes(cohortEntry.getClientVersion()).toSerializable(),
253 cohortEntry.getShard().self());
258 public void onFailure(final Throwable failure) {
259 log.debug("{}: An exception occurred during canCommit for {}", name, cohortEntry.getTransactionId(),
262 cohortCache.remove(cohortEntry.getTransactionId());
263 cohortEntry.getReplySender().tell(new Failure(failure), cohortEntry.getShard().self());
269 * This method handles the canCommit phase for a transaction.
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
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());
289 cohortEntry.setReplySender(sender);
290 cohortEntry.setShard(shard);
292 handleCanCommit(cohortEntry);
295 void doCommit(final CohortEntry cohortEntry) {
296 log.debug("{}: Committing transaction {}", name, cohortEntry.getTransactionId());
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>() {
304 public void onSuccess(final DataTreeCandidate candidate) {
305 finishCommit(cohortEntry.getReplySender(), cohortEntry);
309 public void onFailure(final Throwable failure) {
310 log.error("{} An exception occurred while preCommitting transaction {}", name,
311 cohortEntry.getTransactionId(), failure);
313 cohortCache.remove(cohortEntry.getTransactionId());
314 cohortEntry.getReplySender().tell(new Failure(failure), cohortEntry.getShard().self());
319 void finishCommit(final @NonNull ActorRef sender, final @NonNull CohortEntry cohortEntry) {
320 log.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionId());
322 cohortEntry.commit(new FutureCallback<UnsignedLong>() {
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,
329 cohortCache.remove(cohortEntry.getTransactionId());
330 sender.tell(CommitTransactionReply.instance(cohortEntry.getClientVersion()).toSerializable(),
331 cohortEntry.getShard().self());
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);
339 cohortCache.remove(cohortEntry.getTransactionId());
340 sender.tell(new Failure(failure), cohortEntry.getShard().self());
346 * This method handles the preCommit and commit phases for a transaction.
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
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());
364 cohortEntry.setReplySender(sender);
365 doCommit(cohortEntry);
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) {
375 log.debug("{}: Aborting transaction {}", name, transactionID);
377 final ActorRef self = shard.getSelf();
378 cohortEntry.abort(new FutureCallback<>() {
380 public void onSuccess(final Empty result) {
381 if (sender != null) {
382 sender.tell(AbortTransactionReply.instance(cohortEntry.getClientVersion()).toSerializable(), self);
387 public void onFailure(final Throwable failure) {
388 log.error("{}: An exception happened during abort", name, failure);
390 if (sender != null) {
391 sender.tell(new Failure(failure), self);
396 shard.getShardMBean().incrementAbortTransactionsCount();
399 void checkForExpiredTransactions(final long timeout, final Shard shard) {
400 cohortCache.values().removeIf(CohortEntry::isFailed);
403 void abortPendingTransactions(final String reason, final Shard shard) {
404 final var failure = new Failure(new RuntimeException(reason));
405 final var pending = dataTree.getAndClearPendingTransactions();
407 log.debug("{}: Aborting {} pending queued transactions", name, pending.size());
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());
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) {
430 final var newMessages = new ArrayDeque<BatchedModifications>();
431 cohortEntry.getDataTreeModification().applyToCursor(new AbstractBatchedModificationsCursor() {
433 protected BatchedModifications getModifications() {
434 final var lastBatch = newMessages.peekLast();
435 if (lastBatch != null && lastBatch.getModifications().size() >= maxModificationsPerBatch) {
439 // Allocate a new message
440 final var ret = new BatchedModifications(cohortEntry.getTransactionId(),
441 cohortEntry.getClientVersion());
442 newMessages.add(ret);
447 final var last = newMessages.peekLast();
449 final boolean immediate = cohortEntry.isDoImmediateCommit();
450 last.setDoCommitOnReady(immediate);
451 last.setReady(cohortEntry.getParticipatingShardNames());
452 last.setTotalMessagesSent(newMessages.size());
454 messages.addAll(newMessages);
457 switch (cohort.getState()) {
458 case CAN_COMMIT_COMPLETE:
459 case CAN_COMMIT_PENDING:
460 messages.add(new CanCommitTransaction(cohortEntry.getTransactionId(),
461 cohortEntry.getClientVersion()));
463 case PRE_COMMIT_COMPLETE:
464 case PRE_COMMIT_PENDING:
465 messages.add(new CommitTransaction(cohortEntry.getTransactionId(),
466 cohortEntry.getClientVersion()));
479 void setCohortDecorator(final CohortDecorator cohortDecorator) {
480 this.cohortDecorator = cohortDecorator;