603fb20a6bd44a22f10ffe407806899ae4565fcb
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / RemoteTransactionContext.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  * Copyright (c) 2015 Brocade Communications Systems, Inc. and others.  All rights reserved.
4  *
5  * This program and the accompanying materials are made available under the
6  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7  * and is available at http://www.eclipse.org/legal/epl-v10.html
8  */
9 package org.opendaylight.controller.cluster.datastore;
10
11 import akka.actor.ActorSelection;
12 import akka.dispatch.OnComplete;
13 import akka.util.Timeout;
14 import com.google.common.base.Preconditions;
15 import com.google.common.util.concurrent.SettableFuture;
16 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
17 import org.opendaylight.controller.cluster.datastore.messages.AbstractRead;
18 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
19 import org.opendaylight.controller.cluster.datastore.messages.CloseTransaction;
20 import org.opendaylight.controller.cluster.datastore.messages.SerializableMessage;
21 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
22 import org.opendaylight.controller.cluster.datastore.modification.Modification;
23 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
24 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27 import scala.concurrent.Future;
28
29 /**
30  * Redirects front-end transaction operations to a shard for processing. Instances of this class are used
31  * when the destination shard is remote to the caller.
32  *
33  * @author Thomas Pantelis
34  */
35 public class RemoteTransactionContext extends AbstractTransactionContext {
36     private static final Logger LOG = LoggerFactory.getLogger(RemoteTransactionContext.class);
37
38     private final ActorContext actorContext;
39     private final ActorSelection actor;
40     private final OperationLimiter limiter;
41
42     private BatchedModifications batchedModifications;
43     private int totalBatchedModificationsSent;
44
45     protected RemoteTransactionContext(TransactionIdentifier identifier, ActorSelection actor,
46             ActorContext actorContext, short remoteTransactionVersion, OperationLimiter limiter) {
47         super(identifier, remoteTransactionVersion);
48         this.limiter = Preconditions.checkNotNull(limiter);
49         this.actor = actor;
50         this.actorContext = actorContext;
51     }
52
53     private Future<Object> completeOperation(Future<Object> operationFuture){
54         operationFuture.onComplete(limiter, actorContext.getClientDispatcher());
55         return operationFuture;
56     }
57
58     private ActorSelection getActor() {
59         return actor;
60     }
61
62     protected ActorContext getActorContext() {
63         return actorContext;
64     }
65
66     protected Future<Object> executeOperationAsync(SerializableMessage msg, Timeout timeout) {
67         return completeOperation(actorContext.executeOperationAsync(getActor(), msg.toSerializable(), timeout));
68     }
69
70     @Override
71     public void closeTransaction() {
72         LOG.debug("Tx {} closeTransaction called", getIdentifier());
73         TransactionContextCleanup.untrack(this);
74
75         actorContext.sendOperationAsync(getActor(), new CloseTransaction(getTransactionVersion()).toSerializable());
76     }
77
78     @Override
79     public Future<Object> directCommit() {
80         LOG.debug("Tx {} directCommit called", getIdentifier());
81
82         // Send the remaining batched modifications, if any, with the ready flag set.
83
84         return sendBatchedModifications(true, true);
85     }
86
87     @Override
88     public Future<ActorSelection> readyTransaction() {
89         logModificationCount();
90
91         LOG.debug("Tx {} readyTransaction called", getIdentifier());
92
93         // Send the remaining batched modifications, if any, with the ready flag set.
94
95         Future<Object> lastModificationsFuture = sendBatchedModifications(true, false);
96
97         return transformReadyReply(lastModificationsFuture);
98     }
99
100     protected Future<ActorSelection> transformReadyReply(final Future<Object> readyReplyFuture) {
101         // Transform the last reply Future into a Future that returns the cohort actor path from
102         // the last reply message. That's the end result of the ready operation.
103
104         return TransactionReadyReplyMapper.transform(readyReplyFuture, actorContext, getIdentifier());
105     }
106
107     private BatchedModifications newBatchedModifications() {
108         return new BatchedModifications(getIdentifier(), getTransactionVersion());
109     }
110
111     private void batchModification(Modification modification) {
112         incrementModificationCount();
113         if(batchedModifications == null) {
114             batchedModifications = newBatchedModifications();
115         }
116
117         batchedModifications.addModification(modification);
118
119         if(batchedModifications.getModifications().size() >=
120                 actorContext.getDatastoreContext().getShardBatchedModificationCount()) {
121             sendBatchedModifications();
122         }
123     }
124
125     protected Future<Object> sendBatchedModifications() {
126         return sendBatchedModifications(false, false);
127     }
128
129     protected Future<Object> sendBatchedModifications(boolean ready, boolean doCommitOnReady) {
130         Future<Object> sent = null;
131         if(ready || (batchedModifications != null && !batchedModifications.getModifications().isEmpty())) {
132             if(batchedModifications == null) {
133                 batchedModifications = newBatchedModifications();
134             }
135
136             if(LOG.isDebugEnabled()) {
137                 LOG.debug("Tx {} sending {} batched modifications, ready: {}", getIdentifier(),
138                         batchedModifications.getModifications().size(), ready);
139             }
140
141             batchedModifications.setReady(ready);
142             batchedModifications.setDoCommitOnReady(doCommitOnReady);
143             batchedModifications.setTotalMessagesSent(++totalBatchedModificationsSent);
144             sent = executeOperationAsync(batchedModifications, actorContext.getTransactionCommitOperationTimeout());
145
146             if(ready) {
147                 batchedModifications = null;
148             } else {
149                 batchedModifications = newBatchedModifications();
150             }
151         }
152
153         return sent;
154     }
155
156     @Override
157     public void executeModification(AbstractModification modification) {
158         if(LOG.isDebugEnabled()) {
159             LOG.debug("Tx {} executeModification {} called path = {}", getIdentifier(), modification.getClass()
160                     .getSimpleName(), modification.getPath());
161         }
162
163         acquireOperation();
164         batchModification(modification);
165     }
166
167     @Override
168     public <T> void executeRead(final AbstractRead<T> readCmd, final SettableFuture<T> returnFuture) {
169         if(LOG.isDebugEnabled()) {
170             LOG.debug("Tx {} executeRead {} called path = {}", getIdentifier(), readCmd.getClass().getSimpleName(),
171                     readCmd.getPath());
172         }
173
174         // Send any batched modifications. This is necessary to honor the read uncommitted semantics of the
175         // public API contract.
176
177         acquireOperation();
178         sendBatchedModifications();
179
180         OnComplete<Object> onComplete = new OnComplete<Object>() {
181             @Override
182             public void onComplete(Throwable failure, Object response) throws Throwable {
183                 if(failure != null) {
184                     if(LOG.isDebugEnabled()) {
185                         LOG.debug("Tx {} {} operation failed: {}", getIdentifier(), readCmd.getClass().getSimpleName(),
186                                 failure);
187                     }
188                     returnFuture.setException(new ReadFailedException("Error checking " + readCmd.getClass().getSimpleName()
189                             + " for path " + readCmd.getPath(), failure));
190                 } else {
191                     if(LOG.isDebugEnabled()) {
192                         LOG.debug("Tx {} {} operation succeeded", getIdentifier(), readCmd.getClass().getSimpleName());
193                     }
194                     readCmd.processResponse(response, returnFuture);
195                 }
196             }
197         };
198
199         Future<Object> future = executeOperationAsync(readCmd.asVersion(getTransactionVersion()),
200                 actorContext.getOperationTimeout());
201
202         future.onComplete(onComplete, actorContext.getClientDispatcher());
203     }
204
205     /**
206      * Acquire operation from the limiter if the hand-off has completed. If
207      * the hand-off is still ongoing, this method does nothing.
208      */
209     private final void acquireOperation() {
210         if (isOperationHandOffComplete()) {
211             limiter.acquire();
212         }
213     }
214
215     @Override
216     public boolean usesOperationLimiting() {
217         return true;
218     }
219 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.