2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.datastore;
10 import akka.actor.ActorSelection;
11 import akka.dispatch.Mapper;
12 import akka.dispatch.OnComplete;
13 import com.google.common.base.Optional;
14 import com.google.common.collect.Lists;
15 import com.google.common.util.concurrent.SettableFuture;
16 import java.util.List;
17 import org.opendaylight.controller.cluster.datastore.identifiers.TransactionIdentifier;
18 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
19 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
20 import org.opendaylight.controller.cluster.datastore.messages.CloseTransaction;
21 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
22 import org.opendaylight.controller.cluster.datastore.messages.DataExistsReply;
23 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
24 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
25 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransaction;
26 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
27 import org.opendaylight.controller.cluster.datastore.messages.SerializableMessage;
28 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
29 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
30 import org.opendaylight.controller.cluster.datastore.modification.Modification;
31 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
32 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
33 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
36 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import scala.concurrent.Future;
41 public class TransactionContextImpl extends AbstractTransactionContext {
42 private static final Logger LOG = LoggerFactory.getLogger(TransactionContextImpl.class);
44 private final String transactionChainId;
45 private final ActorContext actorContext;
46 private final ActorSelection actor;
47 private final boolean isTxActorLocal;
48 private final short remoteTransactionVersion;
50 private final OperationCompleter operationCompleter;
51 private BatchedModifications batchedModifications;
53 protected TransactionContextImpl(ActorSelection actor, TransactionIdentifier identifier,
54 String transactionChainId, ActorContext actorContext, SchemaContext schemaContext, boolean isTxActorLocal,
55 short remoteTransactionVersion, OperationCompleter operationCompleter) {
58 this.transactionChainId = transactionChainId;
59 this.actorContext = actorContext;
60 this.isTxActorLocal = isTxActorLocal;
61 this.remoteTransactionVersion = remoteTransactionVersion;
62 this.operationCompleter = operationCompleter;
65 private Future<Object> completeOperation(Future<Object> operationFuture){
66 operationFuture.onComplete(this.operationCompleter, actorContext.getClientDispatcher());
67 return operationFuture;
71 private ActorSelection getActor() {
75 protected ActorContext getActorContext() {
79 protected short getRemoteTransactionVersion() {
80 return remoteTransactionVersion;
83 protected Future<Object> executeOperationAsync(SerializableMessage msg) {
84 return completeOperation(actorContext.executeOperationAsync(getActor(), isTxActorLocal ? msg : msg.toSerializable()));
88 public void closeTransaction() {
89 LOG.debug("Tx {} closeTransaction called", getIdentifier());
91 actorContext.sendOperationAsync(getActor(), CloseTransaction.INSTANCE.toSerializable());
95 public Future<ActorSelection> readyTransaction() {
96 LOG.debug("Tx {} readyTransaction called with {} previous recorded operations pending",
97 getIdentifier(), recordedOperationCount());
99 // Send the remaining batched modifications if any.
101 sendAndRecordBatchedModifications();
103 // Send the ReadyTransaction message to the Tx actor.
105 Future<Object> readyReplyFuture = executeOperationAsync(ReadyTransaction.INSTANCE);
107 return combineRecordedOperationsFutures(readyReplyFuture);
110 protected Future<ActorSelection> combineRecordedOperationsFutures(final Future<Object> withLastReplyFuture) {
111 // Combine all the previously recorded put/merge/delete operation reply Futures and the
112 // ReadyTransactionReply Future into one Future. If any one fails then the combined
113 // Future will fail. We need all prior operations and the ready operation to succeed
114 // in order to attempt commit.
116 List<Future<Object>> futureList = Lists.newArrayListWithCapacity(recordedOperationCount() + 1);
117 copyRecordedOperationFutures(futureList);
118 futureList.add(withLastReplyFuture);
120 Future<Iterable<Object>> combinedFutures = akka.dispatch.Futures.sequence(futureList,
121 actorContext.getClientDispatcher());
123 // Transform the combined Future into a Future that returns the cohort actor path from
124 // the ReadyTransactionReply. That's the end result of the ready operation.
126 return combinedFutures.transform(new Mapper<Iterable<Object>, ActorSelection>() {
128 public ActorSelection checkedApply(Iterable<Object> notUsed) {
129 LOG.debug("Tx {} readyTransaction: pending recorded operations succeeded",
132 // At this point all the Futures succeeded and we need to extract the cohort
133 // actor path from the ReadyTransactionReply. For the recorded operations, they
134 // don't return any data so we're only interested that they completed
135 // successfully. We could be paranoid and verify the correct reply types but
136 // that really should never happen so it's not worth the overhead of
137 // de-serializing each reply.
139 // Note the Future get call here won't block as it's complete.
140 Object serializedReadyReply = withLastReplyFuture.value().get().get();
141 if (serializedReadyReply instanceof ReadyTransactionReply) {
142 return actorContext.actorSelection(((ReadyTransactionReply)serializedReadyReply).getCohortPath());
143 } else if(serializedReadyReply instanceof BatchedModificationsReply) {
144 return actorContext.actorSelection(((BatchedModificationsReply)serializedReadyReply).getCohortPath());
145 } else if(serializedReadyReply.getClass().equals(ReadyTransactionReply.SERIALIZABLE_CLASS)) {
146 ReadyTransactionReply reply = ReadyTransactionReply.fromSerializable(serializedReadyReply);
147 String cohortPath = deserializeCohortPath(reply.getCohortPath());
148 return actorContext.actorSelection(cohortPath);
150 // Throwing an exception here will fail the Future.
151 throw new IllegalArgumentException(String.format("%s: Invalid reply type %s",
152 getIdentifier(), serializedReadyReply.getClass()));
155 }, TransactionProxy.SAME_FAILURE_TRANSFORMER, actorContext.getClientDispatcher());
158 protected String deserializeCohortPath(String cohortPath) {
162 private void batchModification(Modification modification) {
163 if(batchedModifications == null) {
164 batchedModifications = new BatchedModifications(getIdentifier().toString(), remoteTransactionVersion,
168 batchedModifications.addModification(modification);
170 if(batchedModifications.getModifications().size() >=
171 actorContext.getDatastoreContext().getShardBatchedModificationCount()) {
172 sendAndRecordBatchedModifications();
176 private void sendAndRecordBatchedModifications() {
177 Future<Object> sentFuture = sendBatchedModifications();
178 if(sentFuture != null) {
179 recordOperationFuture(sentFuture);
183 protected Future<Object> sendBatchedModifications() {
184 return sendBatchedModifications(false);
187 protected Future<Object> sendBatchedModifications(boolean ready) {
188 Future<Object> sent = null;
189 if(batchedModifications != null) {
190 if(LOG.isDebugEnabled()) {
191 LOG.debug("Tx {} sending {} batched modifications, ready: {}", getIdentifier(),
192 batchedModifications.getModifications().size(), ready);
195 batchedModifications.setReady(ready);
196 sent = executeOperationAsync(batchedModifications);
198 batchedModifications = new BatchedModifications(getIdentifier().toString(), remoteTransactionVersion,
206 public void deleteData(YangInstanceIdentifier path) {
207 LOG.debug("Tx {} deleteData called path = {}", getIdentifier(), path);
209 batchModification(new DeleteModification(path));
213 public void mergeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
214 LOG.debug("Tx {} mergeData called path = {}", getIdentifier(), path);
216 batchModification(new MergeModification(path, data));
220 public void writeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
221 LOG.debug("Tx {} writeData called path = {}", getIdentifier(), path);
223 batchModification(new WriteModification(path, data));
227 public void readData(final YangInstanceIdentifier path,
228 final SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture ) {
230 LOG.debug("Tx {} readData called path = {}", getIdentifier(), path);
232 // Send any batched modifications. This is necessary to honor the read uncommitted semantics of the
233 // public API contract.
235 sendAndRecordBatchedModifications();
237 OnComplete<Object> onComplete = new OnComplete<Object>() {
239 public void onComplete(Throwable failure, Object readResponse) throws Throwable {
240 if(failure != null) {
241 LOG.debug("Tx {} read operation failed: {}", getIdentifier(), failure);
242 returnFuture.setException(new ReadFailedException(
243 "Error reading data for path " + path, failure));
246 LOG.debug("Tx {} read operation succeeded", getIdentifier(), failure);
248 if (readResponse instanceof ReadDataReply) {
249 ReadDataReply reply = (ReadDataReply) readResponse;
250 returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
252 } else if (ReadDataReply.isSerializedType(readResponse)) {
253 ReadDataReply reply = ReadDataReply.fromSerializable(readResponse);
254 returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
257 returnFuture.setException(new ReadFailedException(
258 "Invalid response reading data for path " + path));
264 Future<Object> readFuture = executeOperationAsync(new ReadData(path));
266 readFuture.onComplete(onComplete, actorContext.getClientDispatcher());
270 public void dataExists(final YangInstanceIdentifier path, final SettableFuture<Boolean> returnFuture) {
272 LOG.debug("Tx {} dataExists called path = {}", getIdentifier(), path);
274 // Send any batched modifications. This is necessary to honor the read uncommitted semantics of the
275 // public API contract.
277 sendAndRecordBatchedModifications();
279 OnComplete<Object> onComplete = new OnComplete<Object>() {
281 public void onComplete(Throwable failure, Object response) throws Throwable {
282 if(failure != null) {
283 LOG.debug("Tx {} dataExists operation failed: {}", getIdentifier(), failure);
284 returnFuture.setException(new ReadFailedException(
285 "Error checking data exists for path " + path, failure));
287 LOG.debug("Tx {} dataExists operation succeeded", getIdentifier(), failure);
289 if (response instanceof DataExistsReply) {
290 returnFuture.set(Boolean.valueOf(((DataExistsReply) response).exists()));
292 } else if (response.getClass().equals(DataExistsReply.SERIALIZABLE_CLASS)) {
293 returnFuture.set(Boolean.valueOf(DataExistsReply.fromSerializable(response).exists()));
296 returnFuture.setException(new ReadFailedException(
297 "Invalid response checking exists for path " + path));
303 Future<Object> future = executeOperationAsync(new DataExists(path));
305 future.onComplete(onComplete, actorContext.getClientDispatcher());