CDS: use internal DataTree instance
[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;
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;
35
36 /**
37  * Coordinates commits for a shard ensuring only one concurrent 3-phase commit.
38  *
39  * @author Thomas Pantelis
40  */
41 public class ShardCommitCoordinator {
42
43     // Interface hook for unit tests to replace or decorate the DOMStoreThreePhaseCommitCohorts.
44     public interface CohortDecorator {
45         DOMStoreThreePhaseCommitCohort decorate(String transactionID, DOMStoreThreePhaseCommitCohort actual);
46     }
47
48     private final Cache<String, CohortEntry> cohortCache;
49
50     private CohortEntry currentCohortEntry;
51
52     private final ShardDataTree dataTree;
53
54     private final Queue<CohortEntry> queuedCohortEntries;
55
56     private int queueCapacity;
57
58     private final Logger log;
59
60     private final String name;
61
62     private final RemovalListener<String, CohortEntry> cacheRemovalListener =
63             new RemovalListener<String, CohortEntry>() {
64                 @Override
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());
68                     }
69                 }
70             };
71
72     // This is a hook for unit tests to replace or decorate the DOMStoreThreePhaseCommitCohorts.
73     private CohortDecorator cohortDecorator;
74
75     private ReadyTransactionReply readyTransactionReply;
76
77     public ShardCommitCoordinator(ShardDataTree dataTree,
78             long cacheExpiryTimeoutInSec, int queueCapacity, ActorRef shardActor, Logger log, String name) {
79
80         this.queueCapacity = queueCapacity;
81         this.log = log;
82         this.name = name;
83         this.dataTree = Preconditions.checkNotNull(dataTree);
84
85         cohortCache = CacheBuilder.newBuilder().expireAfterAccess(cacheExpiryTimeoutInSec, TimeUnit.SECONDS).
86                 removalListener(cacheRemovalListener).build();
87
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<>();
91     }
92
93     public void setQueueCapacity(int queueCapacity) {
94         this.queueCapacity = queueCapacity;
95     }
96
97     private ReadyTransactionReply readyTransactionReply(Shard shard) {
98         if(readyTransactionReply == null) {
99             readyTransactionReply = new ReadyTransactionReply(Serialization.serializedActorPath(shard.self()));
100         }
101
102         return readyTransactionReply;
103     }
104
105     /**
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.
108      */
109     public void handleForwardedReadyTransaction(ForwardedReadyTransaction ready, ActorRef sender, Shard shard) {
110         log.debug("{}: Readying transaction {}, client version {}", name,
111                 ready.getTransactionID(), ready.getTxnClientVersion());
112
113         CohortEntry cohortEntry = new CohortEntry(ready.getTransactionID(), ready.getCohort(),
114                 (MutableCompositeModification) ready.getModification());
115         cohortCache.put(ready.getTransactionID(), cohortEntry);
116
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()));
127             }
128
129             ReadyTransactionReply readyTransactionReply =
130                     new ReadyTransactionReply(Serialization.serializedActorPath(replyActorPath),
131                             ready.getTxnClientVersion());
132             sender.tell(ready.isReturnSerialized() ? readyTransactionReply.toSerializable() :
133                 readyTransactionReply, shard.self());
134         } else {
135             if(ready.isDoImmediateCommit()) {
136                 cohortEntry.setDoImmediateCommit(true);
137                 cohortEntry.setReplySender(sender);
138                 cohortEntry.setShard(shard);
139                 handleCanCommit(cohortEntry);
140             } else {
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());
144             }
145         }
146     }
147
148     /**
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.
153      *
154      * @param batched the BatchedModifications
155      * @param shardActor the transaction's shard actor
156      *
157      * @throws ExecutionException if an error occurs loading the cache
158      */
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);
167         }
168
169         if(log.isDebugEnabled()) {
170             log.debug("{}: Applying {} batched modifications for Tx {}", name,
171                     batched.getModifications().size(), batched.getTransactionID());
172         }
173
174         cohortEntry.applyModifications(batched.getModifications());
175
176         if(batched.isReady()) {
177             if(log.isDebugEnabled()) {
178                 log.debug("{}: Readying Tx {}, client version {}", name,
179                         batched.getTransactionID(), batched.getVersion());
180             }
181
182             cohortEntry.ready(cohortDecorator, batched.isDoCommitOnReady());
183
184             if(batched.isDoCommitOnReady()) {
185                 cohortEntry.setReplySender(sender);
186                 cohortEntry.setShard(shard);
187                 handleCanCommit(cohortEntry);
188             } else {
189                 sender.tell(readyTransactionReply(shard), shard.self());
190             }
191         } else {
192             sender.tell(new BatchedModificationsReply(batched.getModifications().size()), shard.self());
193         }
194
195         return batched.isReady();
196     }
197
198     private void handleCanCommit(CohortEntry cohortEntry) {
199         String transactionID = cohortEntry.getTransactionID();
200
201         if(log.isDebugEnabled()) {
202             log.debug("{}: Processing canCommit for transaction {} for shard {}",
203                     name, transactionID, cohortEntry.getShard().self().path());
204         }
205
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);
211
212             if(queuedCohortEntries.size() < queueCapacity) {
213                 queuedCohortEntries.offer(cohortEntry);
214             } else {
215                 removeCohortEntry(transactionID);
216
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());
223             }
224         } else {
225             // No Tx commit currently in progress - make this the current entry and proceed with
226             // canCommit.
227             cohortEntry.updateLastAccessTime();
228             currentCohortEntry = cohortEntry;
229
230             doCanCommit(cohortEntry);
231         }
232     }
233
234     /**
235      * This method handles the canCommit phase for a transaction.
236      *
237      * @param canCommit the CanCommitTransaction message
238      * @param sender the actor that sent the message
239      * @param shard the transaction's shard actor
240      */
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());
252             return;
253         }
254
255         cohortEntry.setReplySender(sender);
256         cohortEntry.setShard(shard);
257
258         handleCanCommit(cohortEntry);
259     }
260
261     private void doCanCommit(final CohortEntry cohortEntry) {
262
263         boolean canCommit = false;
264         try {
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();
269
270             if(cohortEntry.isDoImmediateCommit()) {
271                 if(canCommit) {
272                     doCommit(cohortEntry);
273                 } else {
274                     cohortEntry.getReplySender().tell(new Status.Failure(new TransactionCommitFailedException(
275                                 "Can Commit failed, no detailed cause available.")), cohortEntry.getShard().self());
276                 }
277             } else {
278                 cohortEntry.getReplySender().tell(
279                         canCommit ? CanCommitTransactionReply.YES.toSerializable() :
280                             CanCommitTransactionReply.NO.toSerializable(), cohortEntry.getShard().self());
281             }
282         } catch (Exception e) {
283             log.debug("{}: An exception occurred during canCommit: {}", name, e);
284
285             Throwable failure = e;
286             if(e instanceof ExecutionException) {
287                 failure = e.getCause();
288             }
289
290             cohortEntry.getReplySender().tell(new Status.Failure(failure), cohortEntry.getShard().self());
291         } finally {
292             if(!canCommit) {
293                 // Remove the entry from the cache now.
294                 currentTransactionComplete(cohortEntry.getTransactionID(), true);
295             }
296         }
297     }
298
299     private boolean doCommit(CohortEntry cohortEntry) {
300         log.debug("{}: Committing transaction {}", name, cohortEntry.getTransactionID());
301
302         boolean success = false;
303
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.
308
309         try {
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();
314
315             cohortEntry.getShard().continueCommit(cohortEntry);
316
317             cohortEntry.updateLastAccessTime();
318
319             success = true;
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());
324
325             currentTransactionComplete(cohortEntry.getTransactionID(), true);
326         }
327
328         return success;
329     }
330
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
333         // this transaction.
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());
343             return false;
344         }
345
346         return doCommit(cohortEntry);
347     }
348
349     /**
350      * Returns the cohort entry for the Tx commit currently in progress if the given transaction ID
351      * matches the current entry.
352      *
353      * @param transactionID the ID of the transaction
354      * @return the current CohortEntry or null if the given transaction ID does not match the
355      *         current entry.
356      */
357     public CohortEntry getCohortEntryIfCurrent(String transactionID) {
358         if(isCurrentTransaction(transactionID)) {
359             return currentCohortEntry;
360         }
361
362         return null;
363     }
364
365     public CohortEntry getCurrentCohortEntry() {
366         return currentCohortEntry;
367     }
368
369     public CohortEntry getAndRemoveCohortEntry(String transactionID) {
370         CohortEntry cohortEntry = cohortCache.getIfPresent(transactionID);
371         cohortCache.invalidate(transactionID);
372         return cohortEntry;
373     }
374
375     public void removeCohortEntry(String transactionID) {
376         cohortCache.invalidate(transactionID);
377     }
378
379     public boolean isCurrentTransaction(String transactionID) {
380         return currentCohortEntry != null &&
381                 currentCohortEntry.getTransactionID().equals(transactionID);
382     }
383
384     /**
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.
388      *
389      * @param transactionID the ID of the completed transaction
390      * @param removeCohortEntry if true the CohortEntry for the transaction is also removed from
391      *        the cache.
392      */
393     public void currentTransactionComplete(String transactionID, boolean removeCohortEntry) {
394         if(removeCohortEntry) {
395             removeCohortEntry(transactionID);
396         }
397
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);
404             }
405         }
406     }
407
408     @VisibleForTesting
409     void setCohortDecorator(CohortDecorator cohortDecorator) {
410         this.cohortDecorator = cohortDecorator;
411     }
412
413
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;
420         private Shard shard;
421         private long lastAccessTime;
422         private boolean doImmediateCommit;
423
424         CohortEntry(String transactionID, ReadWriteShardDataTreeTransaction transaction) {
425             this.compositeModification = new MutableCompositeModification();
426             this.transaction = Preconditions.checkNotNull(transaction);
427             this.transactionID = transactionID;
428         }
429
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;
436         }
437
438         void updateLastAccessTime() {
439             lastAccessTime = System.currentTimeMillis();
440         }
441
442         long getLastAccessTime() {
443             return lastAccessTime;
444         }
445
446         String getTransactionID() {
447             return transactionID;
448         }
449
450         DOMStoreThreePhaseCommitCohort getCohort() {
451             return cohort;
452         }
453
454         MutableCompositeModification getModification() {
455             return compositeModification;
456         }
457
458         void applyModifications(Iterable<Modification> modifications) {
459             for(Modification modification: modifications) {
460                 compositeModification.addModification(modification);
461                 modification.apply(transaction.getSnapshot());
462             }
463         }
464
465         void ready(CohortDecorator cohortDecorator, boolean doImmediateCommit) {
466             Preconditions.checkState(cohort == null, "cohort was already set");
467
468             setDoImmediateCommit(doImmediateCommit);
469
470             cohort = transaction.ready();
471
472             if(cohortDecorator != null) {
473                 // Call the hook for unit tests.
474                 cohort = cohortDecorator.decorate(transactionID, cohort);
475             }
476         }
477
478         boolean isDoImmediateCommit() {
479             return doImmediateCommit;
480         }
481
482         void setDoImmediateCommit(boolean doImmediateCommit) {
483             this.doImmediateCommit = doImmediateCommit;
484         }
485
486         ActorRef getReplySender() {
487             return replySender;
488         }
489
490         void setReplySender(ActorRef replySender) {
491             this.replySender = replySender;
492         }
493
494         Shard getShard() {
495             return shard;
496         }
497
498         void setShard(Shard shard) {
499             this.shard = shard;
500         }
501
502         boolean hasModifications(){
503             return compositeModification.getModifications().size() > 0;
504         }
505     }
506 }