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