a2560bd369d353e46cfbc23aeaa780c1057f3b0c
[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.Preconditions;
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.AbstractRead;
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.SerializableMessage;
20 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
21 import org.opendaylight.controller.cluster.datastore.modification.Modification;
22 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
23 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26 import scala.concurrent.Future;
27
28 /**
29  * Redirects front-end transaction operations to a shard for processing. Instances of this class are used
30  * when the destination shard is remote to the caller.
31  *
32  * @author Thomas Pantelis
33  */
34 public class RemoteTransactionContext extends AbstractTransactionContext {
35     private static final Logger LOG = LoggerFactory.getLogger(RemoteTransactionContext.class);
36
37     private final ActorContext actorContext;
38     private final ActorSelection actor;
39     private final boolean isTxActorLocal;
40     private final short remoteTransactionVersion;
41     private final OperationLimiter limiter;
42
43     private BatchedModifications batchedModifications;
44     private int totalBatchedModificationsSent;
45
46     protected RemoteTransactionContext(TransactionIdentifier identifier, ActorSelection actor,
47             ActorContext actorContext, boolean isTxActorLocal,
48             short remoteTransactionVersion, OperationLimiter limiter) {
49         super(identifier);
50         this.limiter = Preconditions.checkNotNull(limiter);
51         this.actor = actor;
52         this.actorContext = actorContext;
53         this.isTxActorLocal = isTxActorLocal;
54         this.remoteTransactionVersion = remoteTransactionVersion;
55     }
56
57     private Future<Object> completeOperation(Future<Object> operationFuture){
58         operationFuture.onComplete(limiter, actorContext.getClientDispatcher());
59         return operationFuture;
60     }
61
62     private ActorSelection getActor() {
63         return actor;
64     }
65
66     protected ActorContext getActorContext() {
67         return actorContext;
68     }
69
70     protected short getRemoteTransactionVersion() {
71         return remoteTransactionVersion;
72     }
73
74     protected Future<Object> executeOperationAsync(SerializableMessage msg) {
75         return completeOperation(actorContext.executeOperationAsync(getActor(), isTxActorLocal ? msg : msg.toSerializable()));
76     }
77
78     @Override
79     public void closeTransaction() {
80         LOG.debug("Tx {} closeTransaction called", getIdentifier());
81         TransactionContextCleanup.untrack(this);
82
83         actorContext.sendOperationAsync(getActor(), new CloseTransaction(remoteTransactionVersion).toSerializable());
84     }
85
86     @Override
87     public boolean supportsDirectCommit() {
88         return true;
89     }
90
91     @Override
92     public Future<Object> directCommit() {
93         LOG.debug("Tx {} directCommit called", getIdentifier());
94
95         // Send the remaining batched modifications, if any, with the ready flag set.
96
97         return sendBatchedModifications(true, true);
98     }
99
100     @Override
101     public Future<ActorSelection> readyTransaction() {
102         logModificationCount();
103
104         LOG.debug("Tx {} readyTransaction called", getIdentifier());
105
106         // Send the remaining batched modifications, if any, with the ready flag set.
107
108         Future<Object> lastModificationsFuture = sendBatchedModifications(true, false);
109
110         return transformReadyReply(lastModificationsFuture);
111     }
112
113     protected Future<ActorSelection> transformReadyReply(final Future<Object> readyReplyFuture) {
114         // Transform the last reply Future into a Future that returns the cohort actor path from
115         // the last reply message. That's the end result of the ready operation.
116
117         return TransactionReadyReplyMapper.transform(readyReplyFuture, actorContext, getIdentifier());
118     }
119
120     private BatchedModifications newBatchedModifications() {
121         return new BatchedModifications(getIdentifier().toString(), remoteTransactionVersion, getIdentifier().getChainId());
122     }
123
124     private void batchModification(Modification modification) {
125         incrementModificationCount();
126         if(batchedModifications == null) {
127             batchedModifications = newBatchedModifications();
128         }
129
130         batchedModifications.addModification(modification);
131
132         if(batchedModifications.getModifications().size() >=
133                 actorContext.getDatastoreContext().getShardBatchedModificationCount()) {
134             sendBatchedModifications();
135         }
136     }
137
138     protected Future<Object> sendBatchedModifications() {
139         return sendBatchedModifications(false, false);
140     }
141
142     protected Future<Object> sendBatchedModifications(boolean ready, boolean doCommitOnReady) {
143         Future<Object> sent = null;
144         if(ready || (batchedModifications != null && !batchedModifications.getModifications().isEmpty())) {
145             if(batchedModifications == null) {
146                 batchedModifications = newBatchedModifications();
147             }
148
149             if(LOG.isDebugEnabled()) {
150                 LOG.debug("Tx {} sending {} batched modifications, ready: {}", getIdentifier(),
151                         batchedModifications.getModifications().size(), ready);
152             }
153
154             batchedModifications.setReady(ready);
155             batchedModifications.setDoCommitOnReady(doCommitOnReady);
156             batchedModifications.setTotalMessagesSent(++totalBatchedModificationsSent);
157             sent = executeOperationAsync(batchedModifications);
158
159             if(ready) {
160                 batchedModifications = null;
161             } else {
162                 batchedModifications = newBatchedModifications();
163             }
164         }
165
166         return sent;
167     }
168
169     @Override
170     public void executeModification(AbstractModification modification) {
171         if(LOG.isDebugEnabled()) {
172             LOG.debug("Tx {} executeModification {} called path = {}", getIdentifier(), modification.getClass()
173                     .getSimpleName(), modification.getPath());
174         }
175
176         acquireOperation();
177         batchModification(modification);
178     }
179
180     @Override
181     public <T> void executeRead(final AbstractRead<T> readCmd, final SettableFuture<T> returnFuture) {
182         if(LOG.isDebugEnabled()) {
183             LOG.debug("Tx {} executeRead {} called path = {}", getIdentifier(), readCmd.getClass().getSimpleName(),
184                     readCmd.getPath());
185         }
186
187         // Send any batched modifications. This is necessary to honor the read uncommitted semantics of the
188         // public API contract.
189
190         acquireOperation();
191         sendBatchedModifications();
192
193         OnComplete<Object> onComplete = new OnComplete<Object>() {
194             @Override
195             public void onComplete(Throwable failure, Object response) throws Throwable {
196                 if(failure != null) {
197                     if(LOG.isDebugEnabled()) {
198                         LOG.debug("Tx {} {} operation failed: {}", getIdentifier(), readCmd.getClass().getSimpleName(),
199                                 failure);
200                     }
201                     returnFuture.setException(new ReadFailedException("Error checking " + readCmd.getClass().getSimpleName()
202                             + " for path " + readCmd.getPath(), failure));
203                 } else {
204                     if(LOG.isDebugEnabled()) {
205                         LOG.debug("Tx {} {} operation succeeded", getIdentifier(), readCmd.getClass().getSimpleName());
206                     }
207                     readCmd.processResponse(response, returnFuture);
208                 }
209             }
210         };
211
212         Future<Object> future = executeOperationAsync(readCmd);
213
214         future.onComplete(onComplete, actorContext.getClientDispatcher());
215     }
216
217     /**
218      * Acquire operation from the limiter if the hand-off has completed. If
219      * the hand-off is still ongoing, this method does nothing.
220      */
221     private final void acquireOperation() {
222         if (isOperationHandOffComplete()) {
223             limiter.acquire();
224         }
225     }
226
227     @Override
228     public boolean usesOperationLimiting() {
229         return true;
230     }
231 }