Merge "Add missing copyright text"
[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 boolean supportsDirectCommit() {
94         return true;
95     }
96
97     @Override
98     public Future<Object> directCommit() {
99         LOG.debug("Tx {} directCommit called", getIdentifier());
100
101         // Send the remaining batched modifications, if any, with the ready flag set.
102
103         return sendBatchedModifications(true, true);
104     }
105
106     @Override
107     public Future<ActorSelection> readyTransaction() {
108         LOG.debug("Tx {} readyTransaction called", getIdentifier());
109
110         // Send the remaining batched modifications, if any, with the ready flag set.
111
112         Future<Object> lastModificationsFuture = sendBatchedModifications(true, false);
113
114         return transformReadyReply(lastModificationsFuture);
115     }
116
117     protected Future<ActorSelection> transformReadyReply(final Future<Object> readyReplyFuture) {
118         // Transform the last reply Future into a Future that returns the cohort actor path from
119         // the last reply message. That's the end result of the ready operation.
120
121         return readyReplyFuture.transform(new Mapper<Object, ActorSelection>() {
122             @Override
123             public ActorSelection checkedApply(Object serializedReadyReply) {
124                 LOG.debug("Tx {} readyTransaction", getIdentifier());
125
126                 // At this point the ready operation succeeded and we need to extract the cohort
127                 // actor path from the reply.
128                 if(ReadyTransactionReply.isSerializedType(serializedReadyReply)) {
129                     ReadyTransactionReply readyTxReply = ReadyTransactionReply.fromSerializable(serializedReadyReply);
130                     return actorContext.actorSelection(extractCohortPathFrom(readyTxReply));
131                 }
132
133                 // Throwing an exception here will fail the Future.
134                 throw new IllegalArgumentException(String.format("%s: Invalid reply type %s",
135                         getIdentifier(), serializedReadyReply.getClass()));
136             }
137         }, TransactionProxy.SAME_FAILURE_TRANSFORMER, actorContext.getClientDispatcher());
138     }
139
140     protected String extractCohortPathFrom(ReadyTransactionReply readyTxReply) {
141         return readyTxReply.getCohortPath();
142     }
143
144     private BatchedModifications newBatchedModifications() {
145         return new BatchedModifications(getIdentifier().toString(), remoteTransactionVersion, transactionChainId);
146     }
147
148     private void batchModification(Modification modification) {
149         if(batchedModifications == null) {
150             batchedModifications = newBatchedModifications();
151         }
152
153         batchedModifications.addModification(modification);
154
155         if(batchedModifications.getModifications().size() >=
156                 actorContext.getDatastoreContext().getShardBatchedModificationCount()) {
157             sendBatchedModifications();
158         }
159     }
160
161     protected Future<Object> sendBatchedModifications() {
162         return sendBatchedModifications(false, false);
163     }
164
165     protected Future<Object> sendBatchedModifications(boolean ready, boolean doCommitOnReady) {
166         Future<Object> sent = null;
167         if(ready || (batchedModifications != null && !batchedModifications.getModifications().isEmpty())) {
168             if(batchedModifications == null) {
169                 batchedModifications = newBatchedModifications();
170             }
171
172             if(LOG.isDebugEnabled()) {
173                 LOG.debug("Tx {} sending {} batched modifications, ready: {}", getIdentifier(),
174                         batchedModifications.getModifications().size(), ready);
175             }
176
177             batchedModifications.setReady(ready);
178             batchedModifications.setDoCommitOnReady(doCommitOnReady);
179             batchedModifications.setTotalMessagesSent(++totalBatchedModificationsSent);
180             sent = executeOperationAsync(batchedModifications);
181
182             if(ready) {
183                 batchedModifications = null;
184             } else {
185                 batchedModifications = newBatchedModifications();
186             }
187         }
188
189         return sent;
190     }
191
192     @Override
193     public void deleteData(YangInstanceIdentifier path) {
194         LOG.debug("Tx {} deleteData called path = {}", getIdentifier(), path);
195
196         batchModification(new DeleteModification(path));
197     }
198
199     @Override
200     public void mergeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
201         LOG.debug("Tx {} mergeData called path = {}", getIdentifier(), path);
202
203         batchModification(new MergeModification(path, data));
204     }
205
206     @Override
207     public void writeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
208         LOG.debug("Tx {} writeData called path = {}", getIdentifier(), path);
209
210         batchModification(new WriteModification(path, data));
211     }
212
213     @Override
214     public void readData(final YangInstanceIdentifier path,
215             final SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture ) {
216
217         LOG.debug("Tx {} readData called path = {}", getIdentifier(), path);
218
219         // Send any batched modifications. This is necessary to honor the read uncommitted semantics of the
220         // public API contract.
221
222         sendBatchedModifications();
223
224         OnComplete<Object> onComplete = new OnComplete<Object>() {
225             @Override
226             public void onComplete(Throwable failure, Object readResponse) throws Throwable {
227                 if(failure != null) {
228                     LOG.debug("Tx {} read operation failed: {}", getIdentifier(), failure);
229                     returnFuture.setException(new ReadFailedException(
230                             "Error reading data for path " + path, failure));
231
232                 } else {
233                     LOG.debug("Tx {} read operation succeeded", getIdentifier(), failure);
234
235                     if (readResponse instanceof ReadDataReply) {
236                         ReadDataReply reply = (ReadDataReply) readResponse;
237                         returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
238
239                     } else if (ReadDataReply.isSerializedType(readResponse)) {
240                         ReadDataReply reply = ReadDataReply.fromSerializable(readResponse);
241                         returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
242
243                     } else {
244                         returnFuture.setException(new ReadFailedException(
245                             "Invalid response reading data for path " + path));
246                     }
247                 }
248             }
249         };
250
251         Future<Object> readFuture = executeOperationAsync(new ReadData(path));
252
253         readFuture.onComplete(onComplete, actorContext.getClientDispatcher());
254     }
255
256     @Override
257     public void dataExists(final YangInstanceIdentifier path, final SettableFuture<Boolean> returnFuture) {
258
259         LOG.debug("Tx {} dataExists called path = {}", getIdentifier(), path);
260
261         // Send any batched modifications. This is necessary to honor the read uncommitted semantics of the
262         // public API contract.
263
264         sendBatchedModifications();
265
266         OnComplete<Object> onComplete = new OnComplete<Object>() {
267             @Override
268             public void onComplete(Throwable failure, Object response) throws Throwable {
269                 if(failure != null) {
270                     LOG.debug("Tx {} dataExists operation failed: {}", getIdentifier(), failure);
271                     returnFuture.setException(new ReadFailedException(
272                             "Error checking data exists for path " + path, failure));
273                 } else {
274                     LOG.debug("Tx {} dataExists operation succeeded", getIdentifier(), failure);
275
276                     if (response instanceof DataExistsReply) {
277                         returnFuture.set(Boolean.valueOf(((DataExistsReply) response).exists()));
278
279                     } else if (response.getClass().equals(DataExistsReply.SERIALIZABLE_CLASS)) {
280                         returnFuture.set(Boolean.valueOf(DataExistsReply.fromSerializable(response).exists()));
281
282                     } else {
283                         returnFuture.setException(new ReadFailedException(
284                                 "Invalid response checking exists for path " + path));
285                     }
286                 }
287             }
288         };
289
290         Future<Object> future = executeOperationAsync(new DataExists(path));
291
292         future.onComplete(onComplete, actorContext.getClientDispatcher());
293     }
294 }