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