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 akka.actor.ActorRef;
11 import akka.actor.Status;
12 import akka.serialization.Serialization;
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Stopwatch;
16 import java.util.HashMap;
17 import java.util.Iterator;
18 import java.util.LinkedList;
20 import java.util.Queue;
21 import java.util.concurrent.ExecutionException;
22 import java.util.concurrent.TimeUnit;
23 import org.opendaylight.controller.cluster.datastore.compat.BackwardsCompatibleThreePhaseCommitCohort;
24 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
25 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
26 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
27 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply;
28 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
29 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
30 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
31 import org.opendaylight.controller.cluster.datastore.modification.Modification;
32 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
33 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
34 import org.slf4j.Logger;
37 * Coordinates commits for a shard ensuring only one concurrent 3-phase commit.
39 * @author Thomas Pantelis
41 class ShardCommitCoordinator {
43 // Interface hook for unit tests to replace or decorate the DOMStoreThreePhaseCommitCohorts.
44 public interface CohortDecorator {
45 ShardDataTreeCohort decorate(String transactionID, ShardDataTreeCohort actual);
48 private final Map<String, CohortEntry> cohortCache = new HashMap<>();
50 private CohortEntry currentCohortEntry;
52 private final ShardDataTree dataTree;
54 // We use a LinkedList here to avoid synchronization overhead with concurrent queue impls
55 // since this should only be accessed on the shard's dispatcher.
56 private final Queue<CohortEntry> queuedCohortEntries = new LinkedList<>();
58 private int queueCapacity;
60 private final Logger log;
62 private final String name;
64 private final long cacheExpiryTimeoutInMillis;
66 // This is a hook for unit tests to replace or decorate the DOMStoreThreePhaseCommitCohorts.
67 private CohortDecorator cohortDecorator;
69 private ReadyTransactionReply readyTransactionReply;
71 ShardCommitCoordinator(ShardDataTree dataTree,
72 long cacheExpiryTimeoutInMillis, int queueCapacity, Logger log, String name) {
74 this.queueCapacity = queueCapacity;
77 this.dataTree = Preconditions.checkNotNull(dataTree);
78 this.cacheExpiryTimeoutInMillis = cacheExpiryTimeoutInMillis;
82 return queuedCohortEntries.size();
85 void setQueueCapacity(int queueCapacity) {
86 this.queueCapacity = queueCapacity;
89 private ReadyTransactionReply readyTransactionReply(Shard shard) {
90 if(readyTransactionReply == null) {
91 readyTransactionReply = new ReadyTransactionReply(Serialization.serializedActorPath(shard.self()));
94 return readyTransactionReply;
97 private boolean queueCohortEntry(CohortEntry cohortEntry, ActorRef sender, Shard shard) {
98 if(queuedCohortEntries.size() < queueCapacity) {
99 queuedCohortEntries.offer(cohortEntry);
101 log.debug("{}: Enqueued transaction {}, queue size {}", name, cohortEntry.getTransactionID(),
102 queuedCohortEntries.size());
106 cohortCache.remove(cohortEntry.getTransactionID());
108 RuntimeException ex = new RuntimeException(
109 String.format("%s: Could not enqueue transaction %s - the maximum commit queue"+
110 " capacity %d has been reached.",
111 name, cohortEntry.getTransactionID(), queueCapacity));
112 log.error(ex.getMessage());
113 sender.tell(new Status.Failure(ex), shard.self());
119 * This method is called to ready a transaction that was prepared by ShardTransaction actor. It caches
120 * the prepared cohort entry for the given transactions ID in preparation for the subsequent 3-phase commit.
122 * @param ready the ForwardedReadyTransaction message to process
123 * @param sender the sender of the message
124 * @param shard the transaction's shard actor
126 void handleForwardedReadyTransaction(ForwardedReadyTransaction ready, ActorRef sender, Shard shard) {
127 log.debug("{}: Readying transaction {}, client version {}", name,
128 ready.getTransactionID(), ready.getTxnClientVersion());
130 CohortEntry cohortEntry = new CohortEntry(ready.getTransactionID(), ready.getCohort());
131 cohortCache.put(ready.getTransactionID(), cohortEntry);
133 if(!queueCohortEntry(cohortEntry, sender, shard)) {
137 if(ready.getTxnClientVersion() < DataStoreVersions.LITHIUM_VERSION) {
138 // Return our actor path as we'll handle the three phase commit except if the Tx client
139 // version < Helium-1 version which means the Tx was initiated by a base Helium version node.
140 // In that case, the subsequent 3-phase commit messages won't contain the transactionId so to
141 // maintain backwards compatibility, we create a separate cohort actor to provide the compatible behavior.
142 ActorRef replyActorPath = shard.self();
143 if(ready.getTxnClientVersion() < DataStoreVersions.HELIUM_1_VERSION) {
144 log.debug("{}: Creating BackwardsCompatibleThreePhaseCommitCohort", name);
145 replyActorPath = shard.getContext().actorOf(BackwardsCompatibleThreePhaseCommitCohort.props(
146 ready.getTransactionID()));
149 ReadyTransactionReply readyTransactionReply =
150 new ReadyTransactionReply(Serialization.serializedActorPath(replyActorPath),
151 ready.getTxnClientVersion());
152 sender.tell(ready.isReturnSerialized() ? readyTransactionReply.toSerializable() :
153 readyTransactionReply, shard.self());
155 if(ready.isDoImmediateCommit()) {
156 cohortEntry.setDoImmediateCommit(true);
157 cohortEntry.setReplySender(sender);
158 cohortEntry.setShard(shard);
159 handleCanCommit(cohortEntry);
161 // The caller does not want immediate commit - the 3-phase commit will be coordinated by the
162 // front-end so send back a ReadyTransactionReply with our actor path.
163 sender.tell(readyTransactionReply(shard), shard.self());
169 * This method handles a BatchedModifications message for a transaction being prepared directly on the
170 * Shard actor instead of via a ShardTransaction actor. If there's no currently cached
171 * DOMStoreWriteTransaction, one is created. The batched modifications are applied to the write Tx. If
172 * the BatchedModifications is ready to commit then a DOMStoreThreePhaseCommitCohort is created.
174 * @param batched the BatchedModifications message to process
175 * @param sender the sender of the message
176 * @param shard the transaction's shard actor
178 void handleBatchedModifications(BatchedModifications batched, ActorRef sender, Shard shard) {
179 CohortEntry cohortEntry = cohortCache.get(batched.getTransactionID());
180 if(cohortEntry == null) {
181 cohortEntry = new CohortEntry(batched.getTransactionID(),
182 dataTree.newReadWriteTransaction(batched.getTransactionID(),
183 batched.getTransactionChainID()));
184 cohortCache.put(batched.getTransactionID(), cohortEntry);
187 if(log.isDebugEnabled()) {
188 log.debug("{}: Applying {} batched modifications for Tx {}", name,
189 batched.getModifications().size(), batched.getTransactionID());
192 cohortEntry.applyModifications(batched.getModifications());
194 if(batched.isReady()) {
195 if(cohortEntry.getLastBatchedModificationsException() != null) {
196 cohortCache.remove(cohortEntry.getTransactionID());
197 throw cohortEntry.getLastBatchedModificationsException();
200 if(cohortEntry.getTotalBatchedModificationsReceived() != batched.getTotalMessagesSent()) {
201 cohortCache.remove(cohortEntry.getTransactionID());
202 throw new IllegalStateException(String.format(
203 "The total number of batched messages received %d does not match the number sent %d",
204 cohortEntry.getTotalBatchedModificationsReceived(), batched.getTotalMessagesSent()));
207 if(!queueCohortEntry(cohortEntry, sender, shard)) {
211 if(log.isDebugEnabled()) {
212 log.debug("{}: Readying Tx {}, client version {}", name,
213 batched.getTransactionID(), batched.getVersion());
216 cohortEntry.ready(cohortDecorator, batched.isDoCommitOnReady());
218 if(batched.isDoCommitOnReady()) {
219 cohortEntry.setReplySender(sender);
220 cohortEntry.setShard(shard);
221 handleCanCommit(cohortEntry);
223 sender.tell(readyTransactionReply(shard), shard.self());
226 sender.tell(new BatchedModificationsReply(batched.getModifications().size()), shard.self());
231 * This method handles {@link ReadyLocalTransaction} message. All transaction modifications have
232 * been prepared beforehand by the sender and we just need to drive them through into the dataTree.
234 * @param message the ReadyLocalTransaction message to process
235 * @param sender the sender of the message
236 * @param shard the transaction's shard actor
238 void handleReadyLocalTransaction(ReadyLocalTransaction message, ActorRef sender, Shard shard) {
239 final ShardDataTreeCohort cohort = new SimpleShardDataTreeCohort(dataTree, message.getModification(),
240 message.getTransactionID());
241 final CohortEntry cohortEntry = new CohortEntry(message.getTransactionID(), cohort);
242 cohortCache.put(message.getTransactionID(), cohortEntry);
243 cohortEntry.setDoImmediateCommit(message.isDoCommitOnReady());
245 if(!queueCohortEntry(cohortEntry, sender, shard)) {
249 log.debug("{}: Applying local modifications for Tx {}", name, message.getTransactionID());
251 if (message.isDoCommitOnReady()) {
252 cohortEntry.setReplySender(sender);
253 cohortEntry.setShard(shard);
254 handleCanCommit(cohortEntry);
256 sender.tell(readyTransactionReply(shard), shard.self());
260 private void handleCanCommit(CohortEntry cohortEntry) {
261 String transactionID = cohortEntry.getTransactionID();
263 cohortEntry.updateLastAccessTime();
265 if(currentCohortEntry != null) {
266 // There's already a Tx commit in progress so we can't process this entry yet - but it's in the
267 // queue and will get processed after all prior entries complete.
269 if(log.isDebugEnabled()) {
270 log.debug("{}: Commit for Tx {} already in progress - skipping canCommit for {} for now",
271 name, currentCohortEntry.getTransactionID(), transactionID);
277 // No Tx commit currently in progress - check if this entry is the next one in the queue, If so make
278 // it the current entry and proceed with canCommit.
279 // Purposely checking reference equality here.
280 if(queuedCohortEntries.peek() == cohortEntry) {
281 currentCohortEntry = queuedCohortEntries.poll();
282 doCanCommit(currentCohortEntry);
284 if(log.isDebugEnabled()) {
285 log.debug("{}: Tx {} is the next pending canCommit - skipping {} for now",
286 name, queuedCohortEntries.peek().getTransactionID(), transactionID);
292 * This method handles the canCommit phase for a transaction.
294 * @param transactionID the ID of the transaction to canCommit
295 * @param sender the actor to which to send the response
296 * @param shard the transaction's shard actor
298 void handleCanCommit(String transactionID, final ActorRef sender, final Shard shard) {
299 // Lookup the cohort entry that was cached previously (or should have been) by
300 // transactionReady (via the ForwardedReadyTransaction message).
301 final CohortEntry cohortEntry = cohortCache.get(transactionID);
302 if(cohortEntry == null) {
303 // Either canCommit was invoked before ready(shouldn't happen) or a long time passed
304 // between canCommit and ready and the entry was expired from the cache.
305 IllegalStateException ex = new IllegalStateException(
306 String.format("%s: No cohort entry found for transaction %s", name, transactionID));
307 log.error(ex.getMessage());
308 sender.tell(new Status.Failure(ex), shard.self());
312 cohortEntry.setReplySender(sender);
313 cohortEntry.setShard(shard);
315 handleCanCommit(cohortEntry);
318 private void doCanCommit(final CohortEntry cohortEntry) {
319 boolean canCommit = false;
321 canCommit = cohortEntry.canCommit();
323 log.debug("{}: canCommit for {}: {}", name, cohortEntry.getTransactionID(), canCommit);
325 if(cohortEntry.isDoImmediateCommit()) {
327 doCommit(cohortEntry);
329 cohortEntry.getReplySender().tell(new Status.Failure(new TransactionCommitFailedException(
330 "Can Commit failed, no detailed cause available.")), cohortEntry.getShard().self());
333 cohortEntry.getReplySender().tell(
334 canCommit ? CanCommitTransactionReply.YES.toSerializable() :
335 CanCommitTransactionReply.NO.toSerializable(), cohortEntry.getShard().self());
337 } catch (Exception e) {
338 log.debug("{}: An exception occurred during canCommit", name, e);
340 Throwable failure = e;
341 if(e instanceof ExecutionException) {
342 failure = e.getCause();
345 cohortEntry.getReplySender().tell(new Status.Failure(failure), cohortEntry.getShard().self());
348 // Remove the entry from the cache now.
349 currentTransactionComplete(cohortEntry.getTransactionID(), true);
354 private boolean doCommit(CohortEntry cohortEntry) {
355 log.debug("{}: Committing transaction {}", name, cohortEntry.getTransactionID());
357 boolean success = false;
359 // We perform the preCommit phase here atomically with the commit phase. This is an
360 // optimization to eliminate the overhead of an extra preCommit message. We lose front-end
361 // coordination of preCommit across shards in case of failure but preCommit should not
362 // normally fail since we ensure only one concurrent 3-phase commit.
365 cohortEntry.preCommit();
367 cohortEntry.getShard().continueCommit(cohortEntry);
369 cohortEntry.updateLastAccessTime();
372 } catch (Exception e) {
373 log.error("{} An exception occurred while preCommitting transaction {}",
374 name, cohortEntry.getTransactionID(), e);
375 cohortEntry.getReplySender().tell(new akka.actor.Status.Failure(e), cohortEntry.getShard().self());
377 currentTransactionComplete(cohortEntry.getTransactionID(), true);
384 * This method handles the preCommit and commit phases for a transaction.
386 * @param transactionID the ID of the transaction to commit
387 * @param sender the actor to which to send the response
388 * @param shard the transaction's shard actor
389 * @return true if the transaction was successfully prepared, false otherwise.
391 boolean handleCommit(final String transactionID, final ActorRef sender, final Shard shard) {
392 // Get the current in-progress cohort entry in the commitCoordinator if it corresponds to
394 final CohortEntry cohortEntry = getCohortEntryIfCurrent(transactionID);
395 if(cohortEntry == null) {
396 // We're not the current Tx - the Tx was likely expired b/c it took too long in
397 // between the canCommit and commit messages.
398 IllegalStateException ex = new IllegalStateException(
399 String.format("%s: Cannot commit transaction %s - it is not the current transaction",
400 name, transactionID));
401 log.error(ex.getMessage());
402 sender.tell(new akka.actor.Status.Failure(ex), shard.self());
406 cohortEntry.setReplySender(sender);
407 return doCommit(cohortEntry);
410 void handleAbort(final String transactionID, final ActorRef sender, final Shard shard) {
411 CohortEntry cohortEntry = getCohortEntryIfCurrent(transactionID);
412 if(cohortEntry != null) {
413 // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
414 // aborted during replication in which case we may still commit locally if replication
416 currentTransactionComplete(transactionID, false);
418 cohortEntry = getAndRemoveCohortEntry(transactionID);
421 if(cohortEntry == null) {
425 log.debug("{}: Aborting transaction {}", name, transactionID);
427 final ActorRef self = shard.getSelf();
431 shard.getShardMBean().incrementAbortTransactionsCount();
434 sender.tell(new AbortTransactionReply().toSerializable(), self);
436 } catch (Exception e) {
437 log.error("{}: An exception happened during abort", name, e);
440 sender.tell(new akka.actor.Status.Failure(e), self);
446 * Returns the cohort entry for the Tx commit currently in progress if the given transaction ID
447 * matches the current entry.
449 * @param transactionID the ID of the transaction
450 * @return the current CohortEntry or null if the given transaction ID does not match the
453 public CohortEntry getCohortEntryIfCurrent(String transactionID) {
454 if(isCurrentTransaction(transactionID)) {
455 return currentCohortEntry;
461 public CohortEntry getCurrentCohortEntry() {
462 return currentCohortEntry;
465 public CohortEntry getAndRemoveCohortEntry(String transactionID) {
466 return cohortCache.remove(transactionID);
469 public boolean isCurrentTransaction(String transactionID) {
470 return currentCohortEntry != null &&
471 currentCohortEntry.getTransactionID().equals(transactionID);
475 * This method is called when a transaction is complete, successful or not. If the given
476 * given transaction ID matches the current in-progress transaction, the next cohort entry,
477 * if any, is dequeued and processed.
479 * @param transactionID the ID of the completed transaction
480 * @param removeCohortEntry if true the CohortEntry for the transaction is also removed from
483 public void currentTransactionComplete(String transactionID, boolean removeCohortEntry) {
484 if(removeCohortEntry) {
485 cohortCache.remove(transactionID);
488 if(isCurrentTransaction(transactionID)) {
489 currentCohortEntry = null;
491 log.debug("{}: currentTransactionComplete: {}", name, transactionID);
493 maybeProcessNextCohortEntry();
497 private void maybeProcessNextCohortEntry() {
498 // Check if there's a next cohort entry waiting in the queue and if it is ready to commit. Also
499 // clean out expired entries.
500 Iterator<CohortEntry> iter = queuedCohortEntries.iterator();
501 while(iter.hasNext()) {
502 CohortEntry next = iter.next();
503 if(next.isReadyToCommit()) {
504 if(currentCohortEntry == null) {
505 if(log.isDebugEnabled()) {
506 log.debug("{}: Next entry to canCommit {}", name, next);
510 currentCohortEntry = next;
511 currentCohortEntry.updateLastAccessTime();
512 doCanCommit(currentCohortEntry);
516 } else if(next.isExpired(cacheExpiryTimeoutInMillis)) {
517 log.warn("{}: canCommit for transaction {} was not received within {} ms - entry removed from cache",
518 name, next.getTransactionID(), cacheExpiryTimeoutInMillis);
519 } else if(!next.isAborted()) {
524 cohortCache.remove(next.getTransactionID());
528 void cleanupExpiredCohortEntries() {
529 maybeProcessNextCohortEntry();
533 void setCohortDecorator(CohortDecorator cohortDecorator) {
534 this.cohortDecorator = cohortDecorator;
537 static class CohortEntry {
538 private final String transactionID;
539 private ShardDataTreeCohort cohort;
540 private final ReadWriteShardDataTreeTransaction transaction;
541 private RuntimeException lastBatchedModificationsException;
542 private ActorRef replySender;
544 private boolean doImmediateCommit;
545 private final Stopwatch lastAccessTimer = Stopwatch.createStarted();
546 private int totalBatchedModificationsReceived;
547 private boolean aborted;
549 CohortEntry(String transactionID, ReadWriteShardDataTreeTransaction transaction) {
550 this.transaction = Preconditions.checkNotNull(transaction);
551 this.transactionID = transactionID;
554 CohortEntry(String transactionID, ShardDataTreeCohort cohort) {
555 this.transactionID = transactionID;
556 this.cohort = cohort;
557 this.transaction = null;
560 void updateLastAccessTime() {
561 lastAccessTimer.reset();
562 lastAccessTimer.start();
565 String getTransactionID() {
566 return transactionID;
569 DataTreeCandidate getCandidate() {
570 return cohort.getCandidate();
573 int getTotalBatchedModificationsReceived() {
574 return totalBatchedModificationsReceived;
577 RuntimeException getLastBatchedModificationsException() {
578 return lastBatchedModificationsException;
581 void applyModifications(Iterable<Modification> modifications) {
582 totalBatchedModificationsReceived++;
583 if(lastBatchedModificationsException == null) {
584 for (Modification modification : modifications) {
586 modification.apply(transaction.getSnapshot());
587 } catch (RuntimeException e) {
588 lastBatchedModificationsException = e;
595 boolean canCommit() throws InterruptedException, ExecutionException {
596 // We block on the future here (and also preCommit(), commit(), abort()) so we don't have to worry
597 // about possibly accessing our state on a different thread outside of our dispatcher.
598 // TODO: the ShardDataTreeCohort returns immediate Futures anyway which begs the question - why
599 // bother even returning Futures from ShardDataTreeCohort if we have to treat them synchronously
600 // anyway?. The Futures are really a remnant from when we were using the InMemoryDataBroker.
601 return cohort.canCommit().get();
604 void preCommit() throws InterruptedException, ExecutionException {
605 cohort.preCommit().get();
608 void commit() throws InterruptedException, ExecutionException {
609 cohort.commit().get();
612 void abort() throws InterruptedException, ExecutionException {
614 cohort.abort().get();
617 void ready(CohortDecorator cohortDecorator, boolean doImmediateCommit) {
618 Preconditions.checkState(cohort == null, "cohort was already set");
620 setDoImmediateCommit(doImmediateCommit);
622 cohort = transaction.ready();
624 if(cohortDecorator != null) {
625 // Call the hook for unit tests.
626 cohort = cohortDecorator.decorate(transactionID, cohort);
630 boolean isReadyToCommit() {
631 return replySender != null;
634 boolean isExpired(long expireTimeInMillis) {
635 return lastAccessTimer.elapsed(TimeUnit.MILLISECONDS) >= expireTimeInMillis;
638 boolean isDoImmediateCommit() {
639 return doImmediateCommit;
642 void setDoImmediateCommit(boolean doImmediateCommit) {
643 this.doImmediateCommit = doImmediateCommit;
646 ActorRef getReplySender() {
650 void setReplySender(ActorRef replySender) {
651 this.replySender = replySender;
658 void setShard(Shard shard) {
663 boolean isAborted() {
668 public String toString() {
669 StringBuilder builder = new StringBuilder();
670 builder.append("CohortEntry [transactionID=").append(transactionID).append(", doImmediateCommit=")
671 .append(doImmediateCommit).append("]");
672 return builder.toString();