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

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.