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.cache.Cache;
16 import com.google.common.cache.CacheBuilder;
17 import com.google.common.cache.RemovalCause;
18 import com.google.common.cache.RemovalListener;
19 import com.google.common.cache.RemovalNotification;
20 import java.util.LinkedList;
21 import java.util.Queue;
22 import java.util.concurrent.ExecutionException;
23 import java.util.concurrent.TimeUnit;
24 import org.opendaylight.controller.cluster.datastore.compat.BackwardsCompatibleThreePhaseCommitCohort;
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.ReadyTransactionReply;
30 import org.opendaylight.controller.cluster.datastore.modification.Modification;
31 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
32 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
33 import org.slf4j.Logger;
36 * Coordinates commits for a shard ensuring only one concurrent 3-phase commit.
38 * @author Thomas Pantelis
40 public class ShardCommitCoordinator {
42 // Interface hook for unit tests to replace or decorate the DOMStoreThreePhaseCommitCohorts.
43 public interface CohortDecorator {
44 ShardDataTreeCohort decorate(String transactionID, ShardDataTreeCohort actual);
47 private final Cache<String, CohortEntry> cohortCache;
49 private CohortEntry currentCohortEntry;
51 private final ShardDataTree dataTree;
53 private final Queue<CohortEntry> queuedCohortEntries;
55 private int queueCapacity;
57 private final Logger log;
59 private final String name;
61 private final RemovalListener<String, CohortEntry> cacheRemovalListener =
62 new RemovalListener<String, CohortEntry>() {
64 public void onRemoval(RemovalNotification<String, CohortEntry> notification) {
65 if(notification.getCause() == RemovalCause.EXPIRED) {
66 log.warn("{}: Transaction {} was timed out of the cache", name, notification.getKey());
71 // This is a hook for unit tests to replace or decorate the DOMStoreThreePhaseCommitCohorts.
72 private CohortDecorator cohortDecorator;
74 private ReadyTransactionReply readyTransactionReply;
76 public ShardCommitCoordinator(ShardDataTree dataTree,
77 long cacheExpiryTimeoutInSec, int queueCapacity, ActorRef shardActor, Logger log, String name) {
79 this.queueCapacity = queueCapacity;
82 this.dataTree = Preconditions.checkNotNull(dataTree);
84 cohortCache = CacheBuilder.newBuilder().expireAfterAccess(cacheExpiryTimeoutInSec, TimeUnit.SECONDS).
85 removalListener(cacheRemovalListener).build();
87 // We use a LinkedList here to avoid synchronization overhead with concurrent queue impls
88 // since this should only be accessed on the shard's dispatcher.
89 queuedCohortEntries = new LinkedList<>();
92 public void setQueueCapacity(int queueCapacity) {
93 this.queueCapacity = queueCapacity;
96 private ReadyTransactionReply readyTransactionReply(Shard shard) {
97 if(readyTransactionReply == null) {
98 readyTransactionReply = new ReadyTransactionReply(Serialization.serializedActorPath(shard.self()));
101 return readyTransactionReply;
105 * This method is called to ready a transaction that was prepared by ShardTransaction actor. It caches
106 * the prepared cohort entry for the given transactions ID in preparation for the subsequent 3-phase commit.
108 public void handleForwardedReadyTransaction(ForwardedReadyTransaction ready, ActorRef sender, Shard shard) {
109 log.debug("{}: Readying transaction {}, client version {}", name,
110 ready.getTransactionID(), ready.getTxnClientVersion());
112 CohortEntry cohortEntry = new CohortEntry(ready.getTransactionID(), ready.getCohort(),
113 (MutableCompositeModification) ready.getModification());
114 cohortCache.put(ready.getTransactionID(), cohortEntry);
116 if(ready.getTxnClientVersion() < DataStoreVersions.LITHIUM_VERSION) {
117 // Return our actor path as we'll handle the three phase commit except if the Tx client
118 // version < Helium-1 version which means the Tx was initiated by a base Helium version node.
119 // In that case, the subsequent 3-phase commit messages won't contain the transactionId so to
120 // maintain backwards compatibility, we create a separate cohort actor to provide the compatible behavior.
121 ActorRef replyActorPath = shard.self();
122 if(ready.getTxnClientVersion() < DataStoreVersions.HELIUM_1_VERSION) {
123 log.debug("{}: Creating BackwardsCompatibleThreePhaseCommitCohort", name);
124 replyActorPath = shard.getContext().actorOf(BackwardsCompatibleThreePhaseCommitCohort.props(
125 ready.getTransactionID()));
128 ReadyTransactionReply readyTransactionReply =
129 new ReadyTransactionReply(Serialization.serializedActorPath(replyActorPath),
130 ready.getTxnClientVersion());
131 sender.tell(ready.isReturnSerialized() ? readyTransactionReply.toSerializable() :
132 readyTransactionReply, shard.self());
134 if(ready.isDoImmediateCommit()) {
135 cohortEntry.setDoImmediateCommit(true);
136 cohortEntry.setReplySender(sender);
137 cohortEntry.setShard(shard);
138 handleCanCommit(cohortEntry);
140 // The caller does not want immediate commit - the 3-phase commit will be coordinated by the
141 // front-end so send back a ReadyTransactionReply with our actor path.
142 sender.tell(readyTransactionReply(shard), shard.self());
148 * This method handles a BatchedModifications message for a transaction being prepared directly on the
149 * Shard actor instead of via a ShardTransaction actor. If there's no currently cached
150 * DOMStoreWriteTransaction, one is created. The batched modifications are applied to the write Tx. If
151 * the BatchedModifications is ready to commit then a DOMStoreThreePhaseCommitCohort is created.
153 * @param batched the BatchedModifications
154 * @param shardActor the transaction's shard actor
156 * @throws ExecutionException if an error occurs loading the cache
158 boolean handleBatchedModifications(BatchedModifications batched, ActorRef sender, Shard shard)
159 throws ExecutionException {
160 CohortEntry cohortEntry = cohortCache.getIfPresent(batched.getTransactionID());
161 if(cohortEntry == null) {
162 cohortEntry = new CohortEntry(batched.getTransactionID(),
163 dataTree.newReadWriteTransaction(batched.getTransactionID(),
164 batched.getTransactionChainID()));
165 cohortCache.put(batched.getTransactionID(), cohortEntry);
168 if(log.isDebugEnabled()) {
169 log.debug("{}: Applying {} batched modifications for Tx {}", name,
170 batched.getModifications().size(), batched.getTransactionID());
173 cohortEntry.applyModifications(batched.getModifications());
175 if(batched.isReady()) {
176 if(log.isDebugEnabled()) {
177 log.debug("{}: Readying Tx {}, client version {}", name,
178 batched.getTransactionID(), batched.getVersion());
181 cohortEntry.ready(cohortDecorator, batched.isDoCommitOnReady());
183 if(batched.isDoCommitOnReady()) {
184 cohortEntry.setReplySender(sender);
185 cohortEntry.setShard(shard);
186 handleCanCommit(cohortEntry);
188 sender.tell(readyTransactionReply(shard), shard.self());
191 sender.tell(new BatchedModificationsReply(batched.getModifications().size()), shard.self());
194 return batched.isReady();
197 private void handleCanCommit(CohortEntry cohortEntry) {
198 String transactionID = cohortEntry.getTransactionID();
200 if(log.isDebugEnabled()) {
201 log.debug("{}: Processing canCommit for transaction {} for shard {}",
202 name, transactionID, cohortEntry.getShard().self().path());
205 if(currentCohortEntry != null) {
206 // There's already a Tx commit in progress - attempt to queue this entry to be
207 // committed after the current Tx completes.
208 log.debug("{}: Transaction {} is already in progress - queueing transaction {}",
209 name, currentCohortEntry.getTransactionID(), transactionID);
211 if(queuedCohortEntries.size() < queueCapacity) {
212 queuedCohortEntries.offer(cohortEntry);
214 removeCohortEntry(transactionID);
216 RuntimeException ex = new RuntimeException(
217 String.format("%s: Could not enqueue transaction %s - the maximum commit queue"+
218 " capacity %d has been reached.",
219 name, transactionID, queueCapacity));
220 log.error(ex.getMessage());
221 cohortEntry.getReplySender().tell(new Status.Failure(ex), cohortEntry.getShard().self());
224 // No Tx commit currently in progress - make this the current entry and proceed with
226 cohortEntry.updateLastAccessTime();
227 currentCohortEntry = cohortEntry;
229 doCanCommit(cohortEntry);
234 * This method handles the canCommit phase for a transaction.
236 * @param canCommit the CanCommitTransaction message
237 * @param sender the actor that sent the message
238 * @param shard the transaction's shard actor
240 public void handleCanCommit(String transactionID, final ActorRef sender, final Shard shard) {
241 // Lookup the cohort entry that was cached previously (or should have been) by
242 // transactionReady (via the ForwardedReadyTransaction message).
243 final CohortEntry cohortEntry = cohortCache.getIfPresent(transactionID);
244 if(cohortEntry == null) {
245 // Either canCommit was invoked before ready(shouldn't happen) or a long time passed
246 // between canCommit and ready and the entry was expired from the cache.
247 IllegalStateException ex = new IllegalStateException(
248 String.format("%s: No cohort entry found for transaction %s", name, transactionID));
249 log.error(ex.getMessage());
250 sender.tell(new Status.Failure(ex), shard.self());
254 cohortEntry.setReplySender(sender);
255 cohortEntry.setShard(shard);
257 handleCanCommit(cohortEntry);
260 private void doCanCommit(final CohortEntry cohortEntry) {
262 boolean canCommit = false;
264 // We block on the future here so we don't have to worry about possibly accessing our
265 // state on a different thread outside of our dispatcher. Also, the data store
266 // currently uses a same thread executor anyway.
267 canCommit = cohortEntry.getCohort().canCommit().get();
269 if(cohortEntry.isDoImmediateCommit()) {
271 doCommit(cohortEntry);
273 cohortEntry.getReplySender().tell(new Status.Failure(new TransactionCommitFailedException(
274 "Can Commit failed, no detailed cause available.")), cohortEntry.getShard().self());
277 cohortEntry.getReplySender().tell(
278 canCommit ? CanCommitTransactionReply.YES.toSerializable() :
279 CanCommitTransactionReply.NO.toSerializable(), cohortEntry.getShard().self());
281 } catch (Exception e) {
282 log.debug("{}: An exception occurred during canCommit: {}", name, e);
284 Throwable failure = e;
285 if(e instanceof ExecutionException) {
286 failure = e.getCause();
289 cohortEntry.getReplySender().tell(new Status.Failure(failure), cohortEntry.getShard().self());
292 // Remove the entry from the cache now.
293 currentTransactionComplete(cohortEntry.getTransactionID(), true);
298 private boolean doCommit(CohortEntry cohortEntry) {
299 log.debug("{}: Committing transaction {}", name, cohortEntry.getTransactionID());
301 boolean success = false;
303 // We perform the preCommit phase here atomically with the commit phase. This is an
304 // optimization to eliminate the overhead of an extra preCommit message. We lose front-end
305 // coordination of preCommit across shards in case of failure but preCommit should not
306 // normally fail since we ensure only one concurrent 3-phase commit.
309 // We block on the future here so we don't have to worry about possibly accessing our
310 // state on a different thread outside of our dispatcher. Also, the data store
311 // currently uses a same thread executor anyway.
312 cohortEntry.getCohort().preCommit().get();
314 cohortEntry.getShard().continueCommit(cohortEntry);
316 cohortEntry.updateLastAccessTime();
319 } catch (Exception e) {
320 log.error("{} An exception occurred while preCommitting transaction {}",
321 name, cohortEntry.getTransactionID(), e);
322 cohortEntry.getReplySender().tell(new akka.actor.Status.Failure(e), cohortEntry.getShard().self());
324 currentTransactionComplete(cohortEntry.getTransactionID(), true);
330 boolean handleCommit(final String transactionID, final ActorRef sender, final Shard shard) {
331 // Get the current in-progress cohort entry in the commitCoordinator if it corresponds to
333 final CohortEntry cohortEntry = getCohortEntryIfCurrent(transactionID);
334 if(cohortEntry == null) {
335 // We're not the current Tx - the Tx was likely expired b/c it took too long in
336 // between the canCommit and commit messages.
337 IllegalStateException ex = new IllegalStateException(
338 String.format("%s: Cannot commit transaction %s - it is not the current transaction",
339 name, transactionID));
340 log.error(ex.getMessage());
341 sender.tell(new akka.actor.Status.Failure(ex), shard.self());
345 return doCommit(cohortEntry);
349 * Returns the cohort entry for the Tx commit currently in progress if the given transaction ID
350 * matches the current entry.
352 * @param transactionID the ID of the transaction
353 * @return the current CohortEntry or null if the given transaction ID does not match the
356 public CohortEntry getCohortEntryIfCurrent(String transactionID) {
357 if(isCurrentTransaction(transactionID)) {
358 return currentCohortEntry;
364 public CohortEntry getCurrentCohortEntry() {
365 return currentCohortEntry;
368 public CohortEntry getAndRemoveCohortEntry(String transactionID) {
369 CohortEntry cohortEntry = cohortCache.getIfPresent(transactionID);
370 cohortCache.invalidate(transactionID);
374 public void removeCohortEntry(String transactionID) {
375 cohortCache.invalidate(transactionID);
378 public boolean isCurrentTransaction(String transactionID) {
379 return currentCohortEntry != null &&
380 currentCohortEntry.getTransactionID().equals(transactionID);
384 * This method is called when a transaction is complete, successful or not. If the given
385 * given transaction ID matches the current in-progress transaction, the next cohort entry,
386 * if any, is dequeued and processed.
388 * @param transactionID the ID of the completed transaction
389 * @param removeCohortEntry if true the CohortEntry for the transaction is also removed from
392 public void currentTransactionComplete(String transactionID, boolean removeCohortEntry) {
393 if(removeCohortEntry) {
394 removeCohortEntry(transactionID);
397 if(isCurrentTransaction(transactionID)) {
398 // Dequeue the next cohort entry waiting in the queue.
399 currentCohortEntry = queuedCohortEntries.poll();
400 if(currentCohortEntry != null) {
401 currentCohortEntry.updateLastAccessTime();
402 doCanCommit(currentCohortEntry);
408 void setCohortDecorator(CohortDecorator cohortDecorator) {
409 this.cohortDecorator = cohortDecorator;
413 static class CohortEntry {
414 private final String transactionID;
415 private ShardDataTreeCohort cohort;
416 private final ReadWriteShardDataTreeTransaction transaction;
417 private ActorRef replySender;
419 private long lastAccessTime;
420 private boolean doImmediateCommit;
422 CohortEntry(String transactionID, ReadWriteShardDataTreeTransaction transaction) {
423 this.transaction = Preconditions.checkNotNull(transaction);
424 this.transactionID = transactionID;
427 CohortEntry(String transactionID, ShardDataTreeCohort cohort,
428 MutableCompositeModification compositeModification) {
429 this.transactionID = transactionID;
430 this.cohort = cohort;
431 this.transaction = null;
434 void updateLastAccessTime() {
435 lastAccessTime = System.currentTimeMillis();
438 long getLastAccessTime() {
439 return lastAccessTime;
442 String getTransactionID() {
443 return transactionID;
446 ShardDataTreeCohort getCohort() {
450 void applyModifications(Iterable<Modification> modifications) {
451 for (Modification modification : modifications) {
452 modification.apply(transaction.getSnapshot());
456 void ready(CohortDecorator cohortDecorator, boolean doImmediateCommit) {
457 Preconditions.checkState(cohort == null, "cohort was already set");
459 setDoImmediateCommit(doImmediateCommit);
461 cohort = transaction.ready();
463 if(cohortDecorator != null) {
464 // Call the hook for unit tests.
465 cohort = cohortDecorator.decorate(transactionID, cohort);
469 boolean isDoImmediateCommit() {
470 return doImmediateCommit;
473 void setDoImmediateCommit(boolean doImmediateCommit) {
474 this.doImmediateCommit = doImmediateCommit;
477 ActorRef getReplySender() {
481 void setReplySender(ActorRef replySender) {
482 this.replySender = replySender;
489 void setShard(Shard shard) {