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