Convert OperationCompleter to OperationLimiter
[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 com.google.common.base.Optional;
14 import com.google.common.util.concurrent.SettableFuture;
15 import org.opendaylight.controller.cluster.datastore.identifiers.TransactionIdentifier;
16 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
17 import org.opendaylight.controller.cluster.datastore.messages.CloseTransaction;
18 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
19 import org.opendaylight.controller.cluster.datastore.messages.DataExistsReply;
20 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
21 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
22 import org.opendaylight.controller.cluster.datastore.messages.SerializableMessage;
23 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
24 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
25 import org.opendaylight.controller.cluster.datastore.modification.Modification;
26 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
27 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
28 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33 import scala.concurrent.Future;
34
35 /**
36  * Redirects front-end transaction operations to a shard for processing. Instances of this class are used
37  * when the destination shard is remote to the caller.
38  *
39  * @author Thomas Pantelis
40  */
41 public class RemoteTransactionContext extends AbstractTransactionContext {
42     private static final Logger LOG = LoggerFactory.getLogger(RemoteTransactionContext.class);
43
44     private final ActorContext actorContext;
45     private final ActorSelection actor;
46     private final boolean isTxActorLocal;
47     private final short remoteTransactionVersion;
48
49     private final OperationLimiter operationCompleter;
50     private BatchedModifications batchedModifications;
51     private int totalBatchedModificationsSent;
52
53     protected RemoteTransactionContext(ActorSelection actor, TransactionIdentifier identifier,
54             ActorContext actorContext, boolean isTxActorLocal,
55             short remoteTransactionVersion, OperationLimiter limiter) {
56         super(identifier);
57         this.actor = actor;
58         this.actorContext = actorContext;
59         this.isTxActorLocal = isTxActorLocal;
60         this.remoteTransactionVersion = remoteTransactionVersion;
61         this.operationCompleter = limiter;
62     }
63
64     private Future<Object> completeOperation(Future<Object> operationFuture){
65         operationFuture.onComplete(this.operationCompleter, actorContext.getClientDispatcher());
66         return operationFuture;
67     }
68
69
70     private ActorSelection getActor() {
71         return actor;
72     }
73
74     protected ActorContext getActorContext() {
75         return actorContext;
76     }
77
78     protected short getRemoteTransactionVersion() {
79         return remoteTransactionVersion;
80     }
81
82     protected Future<Object> executeOperationAsync(SerializableMessage msg) {
83         return completeOperation(actorContext.executeOperationAsync(getActor(), isTxActorLocal ? msg : msg.toSerializable()));
84     }
85
86     @Override
87     public void closeTransaction() {
88         LOG.debug("Tx {} closeTransaction called", getIdentifier());
89         TransactionContextCleanup.untrack(this);
90
91         actorContext.sendOperationAsync(getActor(), CloseTransaction.INSTANCE.toSerializable());
92     }
93
94     @Override
95     public boolean supportsDirectCommit() {
96         return true;
97     }
98
99     @Override
100     public Future<Object> directCommit() {
101         LOG.debug("Tx {} directCommit called", getIdentifier());
102
103         // Send the remaining batched modifications, if any, with the ready flag set.
104
105         return sendBatchedModifications(true, true);
106     }
107
108     @Override
109     public Future<ActorSelection> readyTransaction() {
110         logModificationCount();
111
112         LOG.debug("Tx {} readyTransaction called", getIdentifier());
113
114         // Send the remaining batched modifications, if any, with the ready flag set.
115
116         Future<Object> lastModificationsFuture = sendBatchedModifications(true, false);
117
118         return transformReadyReply(lastModificationsFuture);
119     }
120
121     protected Future<ActorSelection> transformReadyReply(final Future<Object> readyReplyFuture) {
122         // Transform the last reply Future into a Future that returns the cohort actor path from
123         // the last reply message. That's the end result of the ready operation.
124
125         return TransactionReadyReplyMapper.transform(readyReplyFuture, actorContext, getIdentifier());
126     }
127
128     private BatchedModifications newBatchedModifications() {
129         return new BatchedModifications(getIdentifier().toString(), remoteTransactionVersion, getIdentifier().getChainId());
130     }
131
132     private void batchModification(Modification modification) {
133         incrementModificationCount();
134         if(batchedModifications == null) {
135             batchedModifications = newBatchedModifications();
136         }
137
138         batchedModifications.addModification(modification);
139
140         if(batchedModifications.getModifications().size() >=
141                 actorContext.getDatastoreContext().getShardBatchedModificationCount()) {
142             sendBatchedModifications();
143         }
144     }
145
146     protected Future<Object> sendBatchedModifications() {
147         return sendBatchedModifications(false, false);
148     }
149
150     protected Future<Object> sendBatchedModifications(boolean ready, boolean doCommitOnReady) {
151         Future<Object> sent = null;
152         if(ready || (batchedModifications != null && !batchedModifications.getModifications().isEmpty())) {
153             if(batchedModifications == null) {
154                 batchedModifications = newBatchedModifications();
155             }
156
157             if(LOG.isDebugEnabled()) {
158                 LOG.debug("Tx {} sending {} batched modifications, ready: {}", getIdentifier(),
159                         batchedModifications.getModifications().size(), ready);
160             }
161
162             batchedModifications.setReady(ready);
163             batchedModifications.setDoCommitOnReady(doCommitOnReady);
164             batchedModifications.setTotalMessagesSent(++totalBatchedModificationsSent);
165             sent = executeOperationAsync(batchedModifications);
166
167             if(ready) {
168                 batchedModifications = null;
169             } else {
170                 batchedModifications = newBatchedModifications();
171             }
172         }
173
174         return sent;
175     }
176
177     @Override
178     public void deleteData(YangInstanceIdentifier path) {
179         LOG.debug("Tx {} deleteData called path = {}", getIdentifier(), path);
180
181         batchModification(new DeleteModification(path));
182     }
183
184     @Override
185     public void mergeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
186         LOG.debug("Tx {} mergeData called path = {}", getIdentifier(), path);
187
188         batchModification(new MergeModification(path, data));
189     }
190
191     @Override
192     public void writeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
193         LOG.debug("Tx {} writeData called path = {}", getIdentifier(), path);
194
195         batchModification(new WriteModification(path, data));
196     }
197
198     @Override
199     public void readData(final YangInstanceIdentifier path,
200             final SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture ) {
201
202         LOG.debug("Tx {} readData called path = {}", getIdentifier(), path);
203
204         // Send any batched modifications. This is necessary to honor the read uncommitted semantics of the
205         // public API contract.
206
207         sendBatchedModifications();
208
209         OnComplete<Object> onComplete = new OnComplete<Object>() {
210             @Override
211             public void onComplete(Throwable failure, Object readResponse) throws Throwable {
212                 if(failure != null) {
213                     LOG.debug("Tx {} read operation failed: {}", getIdentifier(), failure);
214                     returnFuture.setException(new ReadFailedException(
215                             "Error reading data for path " + path, failure));
216
217                 } else {
218                     LOG.debug("Tx {} read operation succeeded", getIdentifier(), failure);
219
220                     if (readResponse instanceof ReadDataReply) {
221                         ReadDataReply reply = (ReadDataReply) readResponse;
222                         returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
223
224                     } else if (ReadDataReply.isSerializedType(readResponse)) {
225                         ReadDataReply reply = ReadDataReply.fromSerializable(readResponse);
226                         returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
227
228                     } else {
229                         returnFuture.setException(new ReadFailedException(
230                             "Invalid response reading data for path " + path));
231                     }
232                 }
233             }
234         };
235
236         Future<Object> readFuture = executeOperationAsync(new ReadData(path));
237
238         readFuture.onComplete(onComplete, actorContext.getClientDispatcher());
239     }
240
241     @Override
242     public void dataExists(final YangInstanceIdentifier path, final SettableFuture<Boolean> returnFuture) {
243
244         LOG.debug("Tx {} dataExists called path = {}", getIdentifier(), path);
245
246         // Send any batched modifications. This is necessary to honor the read uncommitted semantics of the
247         // public API contract.
248
249         sendBatchedModifications();
250
251         OnComplete<Object> onComplete = new OnComplete<Object>() {
252             @Override
253             public void onComplete(Throwable failure, Object response) throws Throwable {
254                 if(failure != null) {
255                     LOG.debug("Tx {} dataExists operation failed: {}", getIdentifier(), failure);
256                     returnFuture.setException(new ReadFailedException(
257                             "Error checking data exists for path " + path, failure));
258                 } else {
259                     LOG.debug("Tx {} dataExists operation succeeded", getIdentifier(), failure);
260
261                     if (response instanceof DataExistsReply) {
262                         returnFuture.set(Boolean.valueOf(((DataExistsReply) response).exists()));
263
264                     } else if (response.getClass().equals(DataExistsReply.SERIALIZABLE_CLASS)) {
265                         returnFuture.set(Boolean.valueOf(DataExistsReply.fromSerializable(response).exists()));
266
267                     } else {
268                         returnFuture.setException(new ReadFailedException(
269                                 "Invalid response checking exists for path " + path));
270                     }
271                 }
272             }
273         };
274
275         Future<Object> future = executeOperationAsync(new DataExists(path));
276
277         future.onComplete(onComplete, actorContext.getClientDispatcher());
278     }
279 }