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.
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
9 package org.opendaylight.controller.cluster.datastore;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
14 import akka.actor.ActorSelection;
15 import akka.dispatch.Futures;
16 import akka.dispatch.OnComplete;
17 import com.google.common.annotations.VisibleForTesting;
18 import com.google.common.util.concurrent.SettableFuture;
19 import java.util.Optional;
20 import java.util.SortedSet;
21 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
22 import org.opendaylight.controller.cluster.datastore.messages.AbstractRead;
23 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
24 import org.opendaylight.controller.cluster.datastore.messages.CloseTransaction;
25 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
26 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
27 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
28 import org.opendaylight.controller.cluster.datastore.modification.Modification;
29 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
30 import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
31 import org.opendaylight.mdsal.common.api.ReadFailedException;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import scala.concurrent.Future;
39 * Redirects front-end transaction operations to a shard for processing. Instances of this class are used
40 * when the destination shard is remote to the caller.
42 * @author Thomas Pantelis
44 final class RemoteTransactionContext extends TransactionContext {
45 private static final Logger LOG = LoggerFactory.getLogger(RemoteTransactionContext.class);
47 private final ActorUtils actorUtils;
48 private final ActorSelection actor;
49 private final OperationLimiter limiter;
51 private BatchedModifications batchedModifications;
52 private int totalBatchedModificationsSent;
53 private int batchPermits;
56 * We have observed a failed modification batch. This transaction context is effectively doomed, as the backend
57 * does not have a correct view of the world. If this happens, we do not limit operations but rather short-cut them
58 * to a either a no-op (modifications) or a failure (reads). Once the transaction is ready, though, we send the
59 * message to resynchronize with the backend, sharing a 'lost message' failure path.
61 private volatile Throwable failedModification;
63 RemoteTransactionContext(final TransactionIdentifier identifier, final ActorSelection actor,
64 final ActorUtils actorUtils, final short remoteTransactionVersion, final OperationLimiter limiter) {
65 super(identifier, remoteTransactionVersion);
66 this.limiter = requireNonNull(limiter);
68 this.actorUtils = actorUtils;
71 private ActorSelection getActor() {
75 protected ActorUtils getActorUtils() {
80 void closeTransaction() {
81 LOG.debug("Tx {} closeTransaction called", getIdentifier());
82 TransactionContextCleanup.untrack(this);
84 actorUtils.sendOperationAsync(getActor(), new CloseTransaction(getTransactionVersion()).toSerializable());
88 Future<Object> directCommit(final Boolean havePermit) {
89 LOG.debug("Tx {} directCommit called", getIdentifier());
91 // Send the remaining batched modifications, if any, with the ready flag set.
92 bumpPermits(havePermit);
93 return sendBatchedModifications(true, true, Optional.empty());
97 Future<ActorSelection> readyTransaction(final Boolean havePermit,
98 final Optional<SortedSet<String>> participatingShardNames) {
99 logModificationCount();
101 LOG.debug("Tx {} readyTransaction called", getIdentifier());
103 // Send the remaining batched modifications, if any, with the ready flag set.
105 bumpPermits(havePermit);
106 Future<Object> lastModificationsFuture = sendBatchedModifications(true, false, participatingShardNames);
108 // Transform the last reply Future into a Future that returns the cohort actor path from
109 // the last reply message. That's the end result of the ready operation.
110 return TransactionReadyReplyMapper.transform(lastModificationsFuture, actorUtils, getIdentifier());
113 private void bumpPermits(final Boolean havePermit) {
114 if (Boolean.TRUE.equals(havePermit)) {
119 private BatchedModifications newBatchedModifications() {
120 return new BatchedModifications(getIdentifier(), getTransactionVersion());
123 private void batchModification(final Modification modification, final boolean havePermit) {
124 incrementModificationCount();
129 if (batchedModifications == null) {
130 batchedModifications = newBatchedModifications();
133 batchedModifications.addModification(modification);
135 if (batchedModifications.getModifications().size()
136 >= actorUtils.getDatastoreContext().getShardBatchedModificationCount()) {
137 sendBatchedModifications();
142 Future<Object> sendBatchedModifications() {
143 return sendBatchedModifications(false, false, Optional.empty());
146 private Future<Object> sendBatchedModifications(final boolean ready, final boolean doCommitOnReady,
147 final Optional<SortedSet<String>> participatingShardNames) {
148 Future<Object> sent = null;
149 if (ready || batchedModifications != null && !batchedModifications.getModifications().isEmpty()) {
150 if (batchedModifications == null) {
151 batchedModifications = newBatchedModifications();
154 LOG.debug("Tx {} sending {} batched modifications, ready: {}", getIdentifier(),
155 batchedModifications.getModifications().size(), ready);
157 batchedModifications.setDoCommitOnReady(doCommitOnReady);
158 batchedModifications.setTotalMessagesSent(++totalBatchedModificationsSent);
160 final BatchedModifications toSend = batchedModifications;
161 final int permitsToRelease = batchPermits;
165 batchedModifications.setReady(participatingShardNames);
166 batchedModifications.setDoCommitOnReady(doCommitOnReady);
167 batchedModifications = null;
169 batchedModifications = newBatchedModifications();
171 final Throwable failure = failedModification;
172 if (failure != null) {
173 // We have observed a modification failure, it does not make sense to send this batch. This speeds
174 // up the time when the application could be blocked due to messages timing out and operation
175 // limiter kicking in.
176 LOG.debug("Tx {} modifications previously failed, not sending a non-ready batch", getIdentifier());
177 limiter.release(permitsToRelease);
178 return Futures.failed(failure);
182 sent = actorUtils.executeOperationAsync(getActor(), toSend.toSerializable(),
183 actorUtils.getTransactionCommitOperationTimeout());
184 sent.onComplete(new OnComplete<>() {
186 public void onComplete(final Throwable failure, final Object success) {
187 if (failure != null) {
188 LOG.debug("Tx {} modifications failed", getIdentifier(), failure);
189 failedModification = failure;
191 LOG.debug("Tx {} modifications completed with {}", getIdentifier(), success);
193 limiter.release(permitsToRelease);
195 }, actorUtils.getClientDispatcher());
202 void executeDelete(final YangInstanceIdentifier path, final Boolean havePermit) {
203 LOG.debug("Tx {} executeDelete called path = {}", getIdentifier(), path);
204 executeModification(new DeleteModification(path), havePermit);
208 void executeMerge(final YangInstanceIdentifier path, final NormalizedNode data, final Boolean havePermit) {
209 LOG.debug("Tx {} executeMerge called path = {}", getIdentifier(), path);
210 executeModification(new MergeModification(path, data), havePermit);
214 void executeWrite(final YangInstanceIdentifier path, final NormalizedNode data, final Boolean havePermit) {
215 LOG.debug("Tx {} executeWrite called path = {}", getIdentifier(), path);
216 executeModification(new WriteModification(path, data), havePermit);
219 private void executeModification(final AbstractModification modification, final Boolean havePermit) {
220 final boolean permitToRelease;
221 if (havePermit == null) {
222 permitToRelease = failedModification == null && acquireOperation();
224 permitToRelease = havePermit;
227 batchModification(modification, permitToRelease);
231 <T> void executeRead(final AbstractRead<T> readCmd, final SettableFuture<T> returnFuture,
232 final Boolean havePermit) {
233 LOG.debug("Tx {} executeRead {} called path = {}", getIdentifier(), readCmd.getClass().getSimpleName(),
236 final Throwable failure = failedModification;
237 if (failure != null) {
238 // If we know there was a previous modification failure, we must not send a read request, as it risks
239 // returning incorrect data. We check this before acquiring an operation simply because we want the app
240 // to complete this transaction as soon as possible.
241 returnFuture.setException(new ReadFailedException("Previous modification failed, cannot "
242 + readCmd.getClass().getSimpleName() + " for path " + readCmd.getPath(), failure));
246 // Send any batched modifications. This is necessary to honor the read uncommitted semantics of the
247 // public API contract.
249 final boolean permitToRelease = havePermit == null ? acquireOperation() : havePermit;
250 sendBatchedModifications();
252 OnComplete<Object> onComplete = new OnComplete<>() {
254 public void onComplete(final Throwable failure, final Object response) {
255 // We have previously acquired an operation, now release it, no matter what happened
256 if (permitToRelease) {
260 if (failure != null) {
261 LOG.debug("Tx {} {} operation failed", getIdentifier(), readCmd.getClass().getSimpleName(),
264 returnFuture.setException(new ReadFailedException("Error checking "
265 + readCmd.getClass().getSimpleName() + " for path " + readCmd.getPath(), failure));
267 LOG.debug("Tx {} {} operation succeeded", getIdentifier(), readCmd.getClass().getSimpleName());
268 readCmd.processResponse(response, returnFuture);
273 final Future<Object> future = actorUtils.executeOperationAsync(getActor(),
274 readCmd.asVersion(getTransactionVersion()).toSerializable(), actorUtils.getOperationTimeout());
275 future.onComplete(onComplete, actorUtils.getClientDispatcher());
279 * Acquire operation from the limiter if the hand-off has completed. If the hand-off is still ongoing, this method
282 * @return True if a permit was successfully acquired, false otherwise
284 private boolean acquireOperation() {
285 checkState(isOperationHandOffComplete(),
286 "Attempted to acquire execute operation permit for transaction %s on actor %s during handoff",
287 getIdentifier(), actor);
289 if (limiter.acquire()) {
293 LOG.warn("Failed to acquire execute operation permit for transaction {} on actor {}", getIdentifier(), actor);
298 boolean usesOperationLimiting() {