Deprecate ReadData/DataExists protobuff messages
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / RemoteTransactionContextSupport.java
1 /*
2  * Copyright (c) 2015 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  * Copyright (c) 2015 Cisco 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.pattern.AskTimeoutException;
14 import akka.util.Timeout;
15 import com.google.common.base.Preconditions;
16 import java.util.concurrent.TimeUnit;
17 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
18 import org.opendaylight.controller.cluster.datastore.exceptions.ShardLeaderNotRespondingException;
19 import org.opendaylight.controller.cluster.datastore.identifiers.TransactionIdentifier;
20 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
21 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
22 import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
23 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26 import scala.concurrent.Future;
27 import scala.concurrent.duration.FiniteDuration;
28
29 /**
30  * Handles creation of TransactionContext instances for remote transactions. This class creates
31  * remote transactions, if necessary, by sending CreateTransaction messages with retries, up to a limit,
32  * if the shard doesn't have a leader yet. This is done by scheduling a retry task after a short delay.
33  * <p>
34  * The end result from a completed CreateTransaction message is a TransactionContext that is
35  * used to perform transaction operations. Transaction operations that occur before the
36  * CreateTransaction completes are cache via a TransactionContextWrapper and executed once the
37  * CreateTransaction completes, successfully or not.
38  */
39 final class RemoteTransactionContextSupport {
40     private static final Logger LOG = LoggerFactory.getLogger(RemoteTransactionContextSupport.class);
41
42     private static final long CREATE_TX_TRY_INTERVAL_IN_MS = 1000;
43     private static final long MAX_CREATE_TX_MSG_TIMEOUT_IN_MS = 5000;
44
45     private final TransactionProxy parent;
46     private final String shardName;
47
48     /**
49      * The target primary shard.
50      */
51     private volatile PrimaryShardInfo primaryShardInfo;
52
53     /**
54      * The total timeout for creating a tx on the primary shard.
55      */
56     private volatile long totalCreateTxTimeout;
57
58     private final Timeout createTxMessageTimeout;
59
60     private final TransactionContextWrapper transactionContextWrapper;
61
62     RemoteTransactionContextSupport(final TransactionContextWrapper transactionContextWrapper, final TransactionProxy parent,
63             final String shardName) {
64         this.parent = Preconditions.checkNotNull(parent);
65         this.shardName = shardName;
66         this.transactionContextWrapper = transactionContextWrapper;
67
68         // For the total create tx timeout, use 2 times the election timeout. This should be enough time for
69         // a leader re-election to occur if we happen to hit it in transition.
70         totalCreateTxTimeout = parent.getActorContext().getDatastoreContext().getShardRaftConfig()
71                 .getElectionTimeOutInterval().toMillis() * 2;
72
73         // We'll use the operationTimeout for the the create Tx message timeout so it can be set appropriately
74         // for unit tests but cap it at MAX_CREATE_TX_MSG_TIMEOUT_IN_MS. The operationTimeout could be set
75         // larger than the totalCreateTxTimeout in production which we don't want.
76         long operationTimeout = parent.getActorContext().getOperationTimeout().duration().toMillis();
77         createTxMessageTimeout = new Timeout(Math.min(operationTimeout, MAX_CREATE_TX_MSG_TIMEOUT_IN_MS),
78                 TimeUnit.MILLISECONDS);
79     }
80
81     String getShardName() {
82         return shardName;
83     }
84
85     private TransactionType getTransactionType() {
86         return parent.getType();
87     }
88
89     private ActorContext getActorContext() {
90         return parent.getActorContext();
91     }
92
93     private TransactionIdentifier getIdentifier() {
94         return parent.getIdentifier();
95     }
96
97     /**
98      * Sets the target primary shard and initiates a CreateTransaction try.
99      */
100     void setPrimaryShard(PrimaryShardInfo primaryShardInfo) {
101         this.primaryShardInfo = primaryShardInfo;
102
103         if (getTransactionType() == TransactionType.WRITE_ONLY  &&
104                 getActorContext().getDatastoreContext().isWriteOnlyTransactionOptimizationsEnabled()) {
105             ActorSelection primaryShard = primaryShardInfo.getPrimaryShardActor();
106
107             LOG.debug("Tx {} Primary shard {} found - creating WRITE_ONLY transaction context",
108                 getIdentifier(), primaryShard);
109
110             // For write-only Tx's we prepare the transaction modifications directly on the shard actor
111             // to avoid the overhead of creating a separate transaction actor.
112             transactionContextWrapper.executePriorTransactionOperations(createValidTransactionContext(
113                     primaryShard, primaryShard.path().toString(), primaryShardInfo.getPrimaryShardVersion()));
114         } else {
115             tryCreateTransaction();
116         }
117     }
118
119     /**
120      * Performs a CreateTransaction try async.
121      */
122     private void tryCreateTransaction() {
123         if(LOG.isDebugEnabled()) {
124             LOG.debug("Tx {} Primary shard {} found - trying create transaction", getIdentifier(),
125                     primaryShardInfo.getPrimaryShardActor());
126         }
127
128         Object serializedCreateMessage = new CreateTransaction(getIdentifier().toString(),
129                 getTransactionType().ordinal(), getIdentifier().getChainId(),
130                     primaryShardInfo.getPrimaryShardVersion()).toSerializable();
131
132         Future<Object> createTxFuture = getActorContext().executeOperationAsync(
133                 primaryShardInfo.getPrimaryShardActor(), serializedCreateMessage, createTxMessageTimeout);
134
135         createTxFuture.onComplete(new OnComplete<Object>() {
136             @Override
137             public void onComplete(Throwable failure, Object response) {
138                 onCreateTransactionComplete(failure, response);
139             }
140         }, getActorContext().getClientDispatcher());
141     }
142
143     private void tryFindPrimaryShard() {
144         LOG.debug("Tx {} Retrying findPrimaryShardAsync for shard {}", getIdentifier(), shardName);
145
146         this.primaryShardInfo = null;
147         Future<PrimaryShardInfo> findPrimaryFuture = getActorContext().findPrimaryShardAsync(shardName);
148         findPrimaryFuture.onComplete(new OnComplete<PrimaryShardInfo>() {
149             @Override
150             public void onComplete(final Throwable failure, final PrimaryShardInfo primaryShardInfo) {
151                 onFindPrimaryShardComplete(failure, primaryShardInfo);
152             }
153         }, getActorContext().getClientDispatcher());
154     }
155
156     private void onFindPrimaryShardComplete(final Throwable failure, final PrimaryShardInfo primaryShardInfo) {
157         if (failure == null) {
158             this.primaryShardInfo = primaryShardInfo;
159             tryCreateTransaction();
160         } else {
161             LOG.debug("Tx {}: Find primary for shard {} failed", getIdentifier(), shardName, failure);
162
163             onCreateTransactionComplete(failure, null);
164         }
165     }
166
167     private void onCreateTransactionComplete(Throwable failure, Object response) {
168         // An AskTimeoutException will occur if the local shard forwards to an unavailable remote leader or
169         // the cached remote leader actor is no longer available.
170         boolean retryCreateTransaction = primaryShardInfo != null &&
171                 (failure instanceof NoShardLeaderException || failure instanceof AskTimeoutException);
172         if(retryCreateTransaction) {
173             // Schedule a retry unless we're out of retries. Note: totalCreateTxTimeout is volatile as it may
174             // be written by different threads however not concurrently, therefore decrementing it
175             // non-atomically here is ok.
176             if(totalCreateTxTimeout > 0) {
177                 long scheduleInterval = CREATE_TX_TRY_INTERVAL_IN_MS;
178                 if(failure instanceof AskTimeoutException) {
179                     // Since we use the createTxMessageTimeout for the CreateTransaction request and it timed
180                     // out, subtract it from the total timeout. Also since the createTxMessageTimeout period
181                     // has already elapsed, we can immediately schedule the retry (10 ms is virtually immediate).
182                     totalCreateTxTimeout -= createTxMessageTimeout.duration().toMillis();
183                     scheduleInterval = 10;
184                 }
185
186                 totalCreateTxTimeout -= scheduleInterval;
187
188                 LOG.debug("Tx {}: create tx on shard {} failed with exception \"{}\" - scheduling retry in {} ms",
189                         getIdentifier(), shardName, failure, scheduleInterval);
190
191                 getActorContext().getActorSystem().scheduler().scheduleOnce(
192                         FiniteDuration.create(scheduleInterval, TimeUnit.MILLISECONDS),
193                         new Runnable() {
194                             @Override
195                             public void run() {
196                                 tryFindPrimaryShard();
197                             }
198                         }, getActorContext().getClientDispatcher());
199                 return;
200             }
201         }
202
203         createTransactionContext(failure, response);
204     }
205
206     private void createTransactionContext(Throwable failure, Object response) {
207         // Create the TransactionContext from the response or failure. Store the new
208         // TransactionContext locally until we've completed invoking the
209         // TransactionOperations. This avoids thread timing issues which could cause
210         // out-of-order TransactionOperations. Eg, on a modification operation, if the
211         // TransactionContext is non-null, then we directly call the TransactionContext.
212         // However, at the same time, the code may be executing the cached
213         // TransactionOperations. So to avoid thus timing, we don't publish the
214         // TransactionContext until after we've executed all cached TransactionOperations.
215         TransactionContext localTransactionContext;
216         if(failure != null) {
217             LOG.debug("Tx {} Creating NoOpTransaction because of error", getIdentifier(), failure);
218
219             Throwable resultingEx = failure;
220             if(failure instanceof AskTimeoutException) {
221                 resultingEx = new ShardLeaderNotRespondingException(String.format(
222                         "Could not create a %s transaction on shard %s. The shard leader isn't responding.",
223                         parent.getType(), shardName), failure);
224             } else if(!(failure instanceof NoShardLeaderException)) {
225                 resultingEx = new Exception(String.format(
226                     "Error creating %s transaction on shard %s", parent.getType(), shardName), failure);
227             }
228
229             localTransactionContext = new NoOpTransactionContext(resultingEx, getIdentifier());
230         } else if (CreateTransactionReply.isSerializedType(response)) {
231             localTransactionContext = createValidTransactionContext(
232                     CreateTransactionReply.fromSerializable(response));
233         } else {
234             IllegalArgumentException exception = new IllegalArgumentException(String.format(
235                     "Invalid reply type %s for CreateTransaction", response.getClass()));
236
237             localTransactionContext = new NoOpTransactionContext(exception, getIdentifier());
238         }
239
240         transactionContextWrapper.executePriorTransactionOperations(localTransactionContext);
241     }
242
243     private TransactionContext createValidTransactionContext(CreateTransactionReply reply) {
244         LOG.debug("Tx {} Received {}", getIdentifier(), reply);
245
246         return createValidTransactionContext(getActorContext().actorSelection(reply.getTransactionPath()),
247                 reply.getTransactionPath(), primaryShardInfo.getPrimaryShardVersion());
248     }
249
250     private TransactionContext createValidTransactionContext(ActorSelection transactionActor, String transactionPath,
251             short remoteTransactionVersion) {
252         final TransactionContext ret = new RemoteTransactionContext(transactionContextWrapper.getIdentifier(),
253                 transactionActor, getActorContext(), remoteTransactionVersion, transactionContextWrapper.getLimiter());
254
255         if(parent.getType() == TransactionType.READ_ONLY) {
256             TransactionContextCleanup.track(this, ret);
257         }
258
259         return ret;
260     }
261 }
262