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.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
34 import org.slf4j.Logger;
37 * Coordinates commits for a shard ensuring only one concurrent 3-phase commit.
39 * @author Thomas Pantelis
41 public class ShardCommitCoordinator {
43 // Interface hook for unit tests to replace or decorate the DOMStoreThreePhaseCommitCohorts.
44 public interface CohortDecorator {
45 DOMStoreThreePhaseCommitCohort decorate(String transactionID, DOMStoreThreePhaseCommitCohort actual);
48 private final Cache<String, CohortEntry> cohortCache;
50 private CohortEntry currentCohortEntry;
52 private final ShardDataTree dataTree;
54 private final Queue<CohortEntry> queuedCohortEntries;
56 private int queueCapacity;
58 private final Logger log;
60 private final String name;
62 private final RemovalListener<String, CohortEntry> cacheRemovalListener =
63 new RemovalListener<String, CohortEntry>() {
65 public void onRemoval(RemovalNotification<String, CohortEntry> notification) {
66 if(notification.getCause() == RemovalCause.EXPIRED) {
67 log.warn("{}: Transaction {} was timed out of the cache", name, notification.getKey());
72 // This is a hook for unit tests to replace or decorate the DOMStoreThreePhaseCommitCohorts.
73 private CohortDecorator cohortDecorator;
75 private ReadyTransactionReply readyTransactionReply;
77 public ShardCommitCoordinator(ShardDataTree dataTree,
78 long cacheExpiryTimeoutInSec, int queueCapacity, ActorRef shardActor, Logger log, String name) {
80 this.queueCapacity = queueCapacity;
83 this.dataTree = Preconditions.checkNotNull(dataTree);
85 cohortCache = CacheBuilder.newBuilder().expireAfterAccess(cacheExpiryTimeoutInSec, TimeUnit.SECONDS).
86 removalListener(cacheRemovalListener).build();
88 // We use a LinkedList here to avoid synchronization overhead with concurrent queue impls
89 // since this should only be accessed on the shard's dispatcher.
90 queuedCohortEntries = new LinkedList<>();
93 public void setQueueCapacity(int queueCapacity) {
94 this.queueCapacity = queueCapacity;
97 private ReadyTransactionReply readyTransactionReply(Shard shard) {
98 if(readyTransactionReply == null) {
99 readyTransactionReply = new ReadyTransactionReply(Serialization.serializedActorPath(shard.self()));
102 return readyTransactionReply;
106 * This method is called to ready a transaction that was prepared by ShardTransaction actor. It caches
107 * the prepared cohort entry for the given transactions ID in preparation for the subsequent 3-phase commit.
109 public void handleForwardedReadyTransaction(ForwardedReadyTransaction ready, ActorRef sender, Shard shard) {
110 log.debug("{}: Readying transaction {}, client version {}", name,
111 ready.getTransactionID(), ready.getTxnClientVersion());
113 CohortEntry cohortEntry = new CohortEntry(ready.getTransactionID(), ready.getCohort(),
114 (MutableCompositeModification) ready.getModification());
115 cohortCache.put(ready.getTransactionID(), cohortEntry);
117 if(ready.getTxnClientVersion() < DataStoreVersions.LITHIUM_VERSION) {
118 // Return our actor path as we'll handle the three phase commit except if the Tx client
119 // version < Helium-1 version which means the Tx was initiated by a base Helium version node.
120 // In that case, the subsequent 3-phase commit messages won't contain the transactionId so to
121 // maintain backwards compatibility, we create a separate cohort actor to provide the compatible behavior.
122 ActorRef replyActorPath = shard.self();
123 if(ready.getTxnClientVersion() < DataStoreVersions.HELIUM_1_VERSION) {
124 log.debug("{}: Creating BackwardsCompatibleThreePhaseCommitCohort", name);
125 replyActorPath = shard.getContext().actorOf(BackwardsCompatibleThreePhaseCommitCohort.props(
126 ready.getTransactionID()));
129 ReadyTransactionReply readyTransactionReply =
130 new ReadyTransactionReply(Serialization.serializedActorPath(replyActorPath),
131 ready.getTxnClientVersion());
132 sender.tell(ready.isReturnSerialized() ? readyTransactionReply.toSerializable() :
133 readyTransactionReply, shard.self());
135 if(ready.isDoImmediateCommit()) {
136 cohortEntry.setDoImmediateCommit(true);
137 cohortEntry.setReplySender(sender);
138 cohortEntry.setShard(shard);
139 handleCanCommit(cohortEntry);
141 // The caller does not want immediate commit - the 3-phase commit will be coordinated by the
142 // front-end so send back a ReadyTransactionReply with our actor path.
143 sender.tell(readyTransactionReply(shard), shard.self());
149 * This method handles a BatchedModifications message for a transaction being prepared directly on the
150 * Shard actor instead of via a ShardTransaction actor. If there's no currently cached
151 * DOMStoreWriteTransaction, one is created. The batched modifications are applied to the write Tx. If
152 * the BatchedModifications is ready to commit then a DOMStoreThreePhaseCommitCohort is created.
154 * @param batched the BatchedModifications
155 * @param shardActor the transaction's shard actor
157 * @throws ExecutionException if an error occurs loading the cache
159 boolean handleBatchedModifications(BatchedModifications batched, ActorRef sender, Shard shard)
160 throws ExecutionException {
161 CohortEntry cohortEntry = cohortCache.getIfPresent(batched.getTransactionID());
162 if(cohortEntry == null) {
163 cohortEntry = new CohortEntry(batched.getTransactionID(),
164 dataTree.newReadWriteTransaction(batched.getTransactionID(),
165 batched.getTransactionChainID()));
166 cohortCache.put(batched.getTransactionID(), cohortEntry);
169 if(log.isDebugEnabled()) {
170 log.debug("{}: Applying {} batched modifications for Tx {}", name,
171 batched.getModifications().size(), batched.getTransactionID());
174 cohortEntry.applyModifications(batched.getModifications());
176 if(batched.isReady()) {
177 if(log.isDebugEnabled()) {
178 log.debug("{}: Readying Tx {}, client version {}", name,
179 batched.getTransactionID(), batched.getVersion());
182 cohortEntry.ready(cohortDecorator, batched.isDoCommitOnReady());
184 if(batched.isDoCommitOnReady()) {
185 cohortEntry.setReplySender(sender);
186 cohortEntry.setShard(shard);
187 handleCanCommit(cohortEntry);
189 sender.tell(readyTransactionReply(shard), shard.self());
192 sender.tell(new BatchedModificationsReply(batched.getModifications().size()), shard.self());
195 return batched.isReady();
198 private void handleCanCommit(CohortEntry cohortEntry) {
199 String transactionID = cohortEntry.getTransactionID();
201 if(log.isDebugEnabled()) {
202 log.debug("{}: Processing canCommit for transaction {} for shard {}",
203 name, transactionID, cohortEntry.getShard().self().path());
206 if(currentCohortEntry != null) {
207 // There's already a Tx commit in progress - attempt to queue this entry to be
208 // committed after the current Tx completes.
209 log.debug("{}: Transaction {} is already in progress - queueing transaction {}",
210 name, currentCohortEntry.getTransactionID(), transactionID);
212 if(queuedCohortEntries.size() < queueCapacity) {
213 queuedCohortEntries.offer(cohortEntry);
215 removeCohortEntry(transactionID);
217 RuntimeException ex = new RuntimeException(
218 String.format("%s: Could not enqueue transaction %s - the maximum commit queue"+
219 " capacity %d has been reached.",
220 name, transactionID, queueCapacity));
221 log.error(ex.getMessage());
222 cohortEntry.getReplySender().tell(new Status.Failure(ex), cohortEntry.getShard().self());
225 // No Tx commit currently in progress - make this the current entry and proceed with
227 cohortEntry.updateLastAccessTime();
228 currentCohortEntry = cohortEntry;
230 doCanCommit(cohortEntry);
235 * This method handles the canCommit phase for a transaction.
237 * @param canCommit the CanCommitTransaction message
238 * @param sender the actor that sent the message
239 * @param shard the transaction's shard actor
241 public void handleCanCommit(String transactionID, final ActorRef sender, final Shard shard) {
242 // Lookup the cohort entry that was cached previously (or should have been) by
243 // transactionReady (via the ForwardedReadyTransaction message).
244 final CohortEntry cohortEntry = cohortCache.getIfPresent(transactionID);
245 if(cohortEntry == null) {
246 // Either canCommit was invoked before ready(shouldn't happen) or a long time passed
247 // between canCommit and ready and the entry was expired from the cache.
248 IllegalStateException ex = new IllegalStateException(
249 String.format("%s: No cohort entry found for transaction %s", name, transactionID));
250 log.error(ex.getMessage());
251 sender.tell(new Status.Failure(ex), shard.self());
255 cohortEntry.setReplySender(sender);
256 cohortEntry.setShard(shard);
258 handleCanCommit(cohortEntry);
261 private void doCanCommit(final CohortEntry cohortEntry) {
263 boolean canCommit = false;
265 // We block on the future here so we don't have to worry about possibly accessing our
266 // state on a different thread outside of our dispatcher. Also, the data store
267 // currently uses a same thread executor anyway.
268 canCommit = cohortEntry.getCohort().canCommit().get();
270 if(cohortEntry.isDoImmediateCommit()) {
272 doCommit(cohortEntry);
274 cohortEntry.getReplySender().tell(new Status.Failure(new TransactionCommitFailedException(
275 "Can Commit failed, no detailed cause available.")), cohortEntry.getShard().self());
278 cohortEntry.getReplySender().tell(
279 canCommit ? CanCommitTransactionReply.YES.toSerializable() :
280 CanCommitTransactionReply.NO.toSerializable(), cohortEntry.getShard().self());
282 } catch (Exception e) {
283 log.debug("{}: An exception occurred during canCommit: {}", name, e);
285 Throwable failure = e;
286 if(e instanceof ExecutionException) {
287 failure = e.getCause();
290 cohortEntry.getReplySender().tell(new Status.Failure(failure), cohortEntry.getShard().self());
293 // Remove the entry from the cache now.
294 currentTransactionComplete(cohortEntry.getTransactionID(), true);
299 private boolean doCommit(CohortEntry cohortEntry) {
300 log.debug("{}: Committing transaction {}", name, cohortEntry.getTransactionID());
302 boolean success = false;
304 // We perform the preCommit phase here atomically with the commit phase. This is an
305 // optimization to eliminate the overhead of an extra preCommit message. We lose front-end
306 // coordination of preCommit across shards in case of failure but preCommit should not
307 // normally fail since we ensure only one concurrent 3-phase commit.
310 // We block on the future here so we don't have to worry about possibly accessing our
311 // state on a different thread outside of our dispatcher. Also, the data store
312 // currently uses a same thread executor anyway.
313 cohortEntry.getCohort().preCommit().get();
315 cohortEntry.getShard().continueCommit(cohortEntry);
317 cohortEntry.updateLastAccessTime();
320 } catch (Exception e) {
321 log.error("{} An exception occurred while preCommitting transaction {}",
322 name, cohortEntry.getTransactionID(), e);
323 cohortEntry.getReplySender().tell(new akka.actor.Status.Failure(e), cohortEntry.getShard().self());
325 currentTransactionComplete(cohortEntry.getTransactionID(), true);
331 boolean handleCommit(final String transactionID, final ActorRef sender, final Shard shard) {
332 // Get the current in-progress cohort entry in the commitCoordinator if it corresponds to
334 final CohortEntry cohortEntry = getCohortEntryIfCurrent(transactionID);
335 if(cohortEntry == null) {
336 // We're not the current Tx - the Tx was likely expired b/c it took too long in
337 // between the canCommit and commit messages.
338 IllegalStateException ex = new IllegalStateException(
339 String.format("%s: Cannot commit transaction %s - it is not the current transaction",
340 name, transactionID));
341 log.error(ex.getMessage());
342 sender.tell(new akka.actor.Status.Failure(ex), shard.self());
346 return doCommit(cohortEntry);
350 * Returns the cohort entry for the Tx commit currently in progress if the given transaction ID
351 * matches the current entry.
353 * @param transactionID the ID of the transaction
354 * @return the current CohortEntry or null if the given transaction ID does not match the
357 public CohortEntry getCohortEntryIfCurrent(String transactionID) {
358 if(isCurrentTransaction(transactionID)) {
359 return currentCohortEntry;
365 public CohortEntry getCurrentCohortEntry() {
366 return currentCohortEntry;
369 public CohortEntry getAndRemoveCohortEntry(String transactionID) {
370 CohortEntry cohortEntry = cohortCache.getIfPresent(transactionID);
371 cohortCache.invalidate(transactionID);
375 public void removeCohortEntry(String transactionID) {
376 cohortCache.invalidate(transactionID);
379 public boolean isCurrentTransaction(String transactionID) {
380 return currentCohortEntry != null &&
381 currentCohortEntry.getTransactionID().equals(transactionID);
385 * This method is called when a transaction is complete, successful or not. If the given
386 * given transaction ID matches the current in-progress transaction, the next cohort entry,
387 * if any, is dequeued and processed.
389 * @param transactionID the ID of the completed transaction
390 * @param removeCohortEntry if true the CohortEntry for the transaction is also removed from
393 public void currentTransactionComplete(String transactionID, boolean removeCohortEntry) {
394 if(removeCohortEntry) {
395 removeCohortEntry(transactionID);
398 if(isCurrentTransaction(transactionID)) {
399 // Dequeue the next cohort entry waiting in the queue.
400 currentCohortEntry = queuedCohortEntries.poll();
401 if(currentCohortEntry != null) {
402 currentCohortEntry.updateLastAccessTime();
403 doCanCommit(currentCohortEntry);
409 void setCohortDecorator(CohortDecorator cohortDecorator) {
410 this.cohortDecorator = cohortDecorator;
414 static class CohortEntry {
415 private final String transactionID;
416 private DOMStoreThreePhaseCommitCohort cohort;
417 private final MutableCompositeModification compositeModification;
418 private final ReadWriteShardDataTreeTransaction transaction;
419 private ActorRef replySender;
421 private long lastAccessTime;
422 private boolean doImmediateCommit;
424 CohortEntry(String transactionID, ReadWriteShardDataTreeTransaction transaction) {
425 this.compositeModification = new MutableCompositeModification();
426 this.transaction = Preconditions.checkNotNull(transaction);
427 this.transactionID = transactionID;
430 CohortEntry(String transactionID, DOMStoreThreePhaseCommitCohort cohort,
431 MutableCompositeModification compositeModification) {
432 this.transactionID = transactionID;
433 this.cohort = cohort;
434 this.compositeModification = compositeModification;
435 this.transaction = null;
438 void updateLastAccessTime() {
439 lastAccessTime = System.currentTimeMillis();
442 long getLastAccessTime() {
443 return lastAccessTime;
446 String getTransactionID() {
447 return transactionID;
450 DOMStoreThreePhaseCommitCohort getCohort() {
454 MutableCompositeModification getModification() {
455 return compositeModification;
458 void applyModifications(Iterable<Modification> modifications) {
459 for(Modification modification: modifications) {
460 compositeModification.addModification(modification);
461 modification.apply(transaction.getSnapshot());
465 void ready(CohortDecorator cohortDecorator, boolean doImmediateCommit) {
466 Preconditions.checkState(cohort == null, "cohort was already set");
468 setDoImmediateCommit(doImmediateCommit);
470 cohort = transaction.ready();
472 if(cohortDecorator != null) {
473 // Call the hook for unit tests.
474 cohort = cohortDecorator.decorate(transactionID, cohort);
478 boolean isDoImmediateCommit() {
479 return doImmediateCommit;
482 void setDoImmediateCommit(boolean doImmediateCommit) {
483 this.doImmediateCommit = doImmediateCommit;
486 ActorRef getReplySender() {
490 void setReplySender(ActorRef replySender) {
491 this.replySender = replySender;
498 void setShard(Shard shard) {
502 boolean hasModifications(){
503 return compositeModification.getModifications().size() > 0;