7e8a2a00ebe3fb701cb66f0991ba1a0fee9e2cf0
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / RemoteTransactionContext.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.OnComplete;
13 import com.google.common.base.Optional;
14 import com.google.common.util.concurrent.SettableFuture;
15 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
16 import org.opendaylight.controller.cluster.datastore.messages.CloseTransaction;
17 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
18 import org.opendaylight.controller.cluster.datastore.messages.DataExistsReply;
19 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
20 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
21 import org.opendaylight.controller.cluster.datastore.messages.SerializableMessage;
22 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
23 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
24 import org.opendaylight.controller.cluster.datastore.modification.Modification;
25 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
26 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
27 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32 import scala.concurrent.Future;
33
34 /**
35  * Redirects front-end transaction operations to a shard for processing. Instances of this class are used
36  * when the destination shard is remote to the caller.
37  *
38  * @author Thomas Pantelis
39  */
40 public class RemoteTransactionContext extends AbstractTransactionContext {
41     private static final Logger LOG = LoggerFactory.getLogger(RemoteTransactionContext.class);
42
43     private final ActorContext actorContext;
44     private final ActorSelection actor;
45     private final boolean isTxActorLocal;
46     private final short remoteTransactionVersion;
47
48     private BatchedModifications batchedModifications;
49     private int totalBatchedModificationsSent;
50
51     protected RemoteTransactionContext(ActorSelection actor,
52             ActorContext actorContext, boolean isTxActorLocal,
53             short remoteTransactionVersion, OperationLimiter limiter) {
54         super(limiter);
55         this.actor = actor;
56         this.actorContext = actorContext;
57         this.isTxActorLocal = isTxActorLocal;
58         this.remoteTransactionVersion = remoteTransactionVersion;
59     }
60
61     private Future<Object> completeOperation(Future<Object> operationFuture){
62         operationFuture.onComplete(getLimiter(), actorContext.getClientDispatcher());
63         return operationFuture;
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         TransactionContextCleanup.untrack(this);
86
87         actorContext.sendOperationAsync(getActor(), CloseTransaction.INSTANCE.toSerializable());
88     }
89
90     @Override
91     public boolean supportsDirectCommit() {
92         return true;
93     }
94
95     @Override
96     public Future<Object> directCommit() {
97         LOG.debug("Tx {} directCommit called", getIdentifier());
98
99         // Send the remaining batched modifications, if any, with the ready flag set.
100
101         return sendBatchedModifications(true, true);
102     }
103
104     @Override
105     public Future<ActorSelection> readyTransaction() {
106         logModificationCount();
107
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 TransactionReadyReplyMapper.transform(readyReplyFuture, actorContext, getIdentifier());
122     }
123
124     private BatchedModifications newBatchedModifications() {
125         return new BatchedModifications(getIdentifier().toString(), remoteTransactionVersion, getIdentifier().getChainId());
126     }
127
128     private void batchModification(Modification modification) {
129         incrementModificationCount();
130         if(batchedModifications == null) {
131             batchedModifications = newBatchedModifications();
132         }
133
134         batchedModifications.addModification(modification);
135
136         if(batchedModifications.getModifications().size() >=
137                 actorContext.getDatastoreContext().getShardBatchedModificationCount()) {
138             sendBatchedModifications();
139         }
140     }
141
142     protected Future<Object> sendBatchedModifications() {
143         return sendBatchedModifications(false, false);
144     }
145
146     protected Future<Object> sendBatchedModifications(boolean ready, boolean doCommitOnReady) {
147         Future<Object> sent = null;
148         if(ready || (batchedModifications != null && !batchedModifications.getModifications().isEmpty())) {
149             if(batchedModifications == null) {
150                 batchedModifications = newBatchedModifications();
151             }
152
153             if(LOG.isDebugEnabled()) {
154                 LOG.debug("Tx {} sending {} batched modifications, ready: {}", getIdentifier(),
155                         batchedModifications.getModifications().size(), ready);
156             }
157
158             batchedModifications.setReady(ready);
159             batchedModifications.setDoCommitOnReady(doCommitOnReady);
160             batchedModifications.setTotalMessagesSent(++totalBatchedModificationsSent);
161             sent = executeOperationAsync(batchedModifications);
162
163             if(ready) {
164                 batchedModifications = null;
165             } else {
166                 batchedModifications = newBatchedModifications();
167             }
168         }
169
170         return sent;
171     }
172
173     @Override
174     public void deleteData(YangInstanceIdentifier path) {
175         LOG.debug("Tx {} deleteData called path = {}", getIdentifier(), path);
176
177         acquireOperation();
178         batchModification(new DeleteModification(path));
179     }
180
181     @Override
182     public void mergeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
183         LOG.debug("Tx {} mergeData called path = {}", getIdentifier(), path);
184
185         acquireOperation();
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         acquireOperation();
194         batchModification(new WriteModification(path, data));
195     }
196
197     @Override
198     public void readData(final YangInstanceIdentifier path,
199             final SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture ) {
200
201         LOG.debug("Tx {} readData called path = {}", getIdentifier(), path);
202
203         // Send any batched modifications. This is necessary to honor the read uncommitted semantics of the
204         // public API contract.
205
206         acquireOperation();
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         acquireOperation();
250         sendBatchedModifications();
251
252         OnComplete<Object> onComplete = new OnComplete<Object>() {
253             @Override
254             public void onComplete(Throwable failure, Object response) throws Throwable {
255                 if(failure != null) {
256                     LOG.debug("Tx {} dataExists operation failed: {}", getIdentifier(), failure);
257                     returnFuture.setException(new ReadFailedException(
258                             "Error checking data exists for path " + path, failure));
259                 } else {
260                     LOG.debug("Tx {} dataExists operation succeeded", getIdentifier(), failure);
261
262                     if (response instanceof DataExistsReply) {
263                         returnFuture.set(Boolean.valueOf(((DataExistsReply) response).exists()));
264
265                     } else if (response.getClass().equals(DataExistsReply.SERIALIZABLE_CLASS)) {
266                         returnFuture.set(Boolean.valueOf(DataExistsReply.fromSerializable(response).exists()));
267
268                     } else {
269                         returnFuture.setException(new ReadFailedException(
270                                 "Invalid response checking exists for path " + path));
271                     }
272                 }
273             }
274         };
275
276         Future<Object> future = executeOperationAsync(new DataExists(path));
277
278         future.onComplete(onComplete, actorContext.getClientDispatcher());
279     }
280 }