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