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