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