Merge changes I114cbac1,I45c2e7cd
[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.opendaylight.yangtools.yang.model.api.SchemaContext;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import scala.concurrent.Future;
37
38 public class TransactionContextImpl extends AbstractTransactionContext {
39     private static final Logger LOG = LoggerFactory.getLogger(TransactionContextImpl.class);
40
41     private final String transactionChainId;
42     private final ActorContext actorContext;
43     private final ActorSelection actor;
44     private final boolean isTxActorLocal;
45     private final short remoteTransactionVersion;
46
47     private final OperationCompleter operationCompleter;
48     private BatchedModifications batchedModifications;
49     private int totalBatchedModificationsSent;
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, with the ready flag set.
97
98         Future<Object> lastModificationsFuture = sendBatchedModifications(true);
99
100         return transformReadyReply(lastModificationsFuture);
101     }
102
103     protected Future<ActorSelection> transformReadyReply(final Future<Object> readyReplyFuture) {
104         // Transform the last reply Future into a Future that returns the cohort actor path from
105         // the last reply message. That's the end result of the ready operation.
106
107         return readyReplyFuture.transform(new Mapper<Object, ActorSelection>() {
108             @Override
109             public ActorSelection checkedApply(Object serializedReadyReply) {
110                 LOG.debug("Tx {} readyTransaction", getIdentifier());
111
112                 // At this point the ready operation succeeded and we need to extract the cohort
113                 // actor path from the reply.
114                 if(ReadyTransactionReply.isSerializedType(serializedReadyReply)) {
115                     ReadyTransactionReply readyTxReply = ReadyTransactionReply.fromSerializable(serializedReadyReply);
116                     return actorContext.actorSelection(extractCohortPathFrom(readyTxReply));
117                 }
118
119                 // Throwing an exception here will fail the Future.
120                 throw new IllegalArgumentException(String.format("%s: Invalid reply type %s",
121                         getIdentifier(), serializedReadyReply.getClass()));
122             }
123         }, TransactionProxy.SAME_FAILURE_TRANSFORMER, actorContext.getClientDispatcher());
124     }
125
126     protected String extractCohortPathFrom(ReadyTransactionReply readyTxReply) {
127         return readyTxReply.getCohortPath();
128     }
129
130     private BatchedModifications newBatchedModifications() {
131         return new BatchedModifications(getIdentifier().toString(), remoteTransactionVersion, transactionChainId);
132     }
133
134     private void batchModification(Modification modification) {
135         if(batchedModifications == null) {
136             batchedModifications = newBatchedModifications();
137         }
138
139         batchedModifications.addModification(modification);
140
141         if(batchedModifications.getModifications().size() >=
142                 actorContext.getDatastoreContext().getShardBatchedModificationCount()) {
143             sendBatchedModifications();
144         }
145     }
146
147     protected Future<Object> sendBatchedModifications() {
148         return sendBatchedModifications(false);
149     }
150
151     protected Future<Object> sendBatchedModifications(boolean ready) {
152         Future<Object> sent = null;
153         if(ready || (batchedModifications != null && !batchedModifications.getModifications().isEmpty())) {
154             if(batchedModifications == null) {
155                 batchedModifications = newBatchedModifications();
156             }
157
158             if(LOG.isDebugEnabled()) {
159                 LOG.debug("Tx {} sending {} batched modifications, ready: {}", getIdentifier(),
160                         batchedModifications.getModifications().size(), ready);
161             }
162
163             batchedModifications.setReady(ready);
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 }