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 akka.actor.ActorSelection;
12 import akka.dispatch.Mapper;
13 import akka.dispatch.OnComplete;
14 import com.google.common.base.Optional;
15 import com.google.common.util.concurrent.SettableFuture;
16 import org.opendaylight.controller.cluster.datastore.identifiers.TransactionIdentifier;
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.DataExists;
20 import org.opendaylight.controller.cluster.datastore.messages.DataExistsReply;
21 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
22 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
23 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
24 import org.opendaylight.controller.cluster.datastore.messages.SerializableMessage;
25 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
26 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
27 import org.opendaylight.controller.cluster.datastore.modification.Modification;
28 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
29 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
30 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
32 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35 import scala.concurrent.Future;
37 public class TransactionContextImpl extends AbstractTransactionContext {
38 private static final Logger LOG = LoggerFactory.getLogger(TransactionContextImpl.class);
40 private final String transactionChainId;
41 private final ActorContext actorContext;
42 private final ActorSelection actor;
43 private final boolean isTxActorLocal;
44 private final short remoteTransactionVersion;
46 private final OperationCompleter operationCompleter;
47 private BatchedModifications batchedModifications;
48 private int totalBatchedModificationsSent;
50 protected TransactionContextImpl(ActorSelection actor, TransactionIdentifier identifier,
51 String transactionChainId, ActorContext actorContext, boolean isTxActorLocal,
52 short remoteTransactionVersion, OperationCompleter operationCompleter) {
55 this.transactionChainId = transactionChainId;
56 this.actorContext = actorContext;
57 this.isTxActorLocal = isTxActorLocal;
58 this.remoteTransactionVersion = remoteTransactionVersion;
59 this.operationCompleter = operationCompleter;
62 private Future<Object> completeOperation(Future<Object> operationFuture){
63 operationFuture.onComplete(this.operationCompleter, actorContext.getClientDispatcher());
64 return operationFuture;
68 private ActorSelection getActor() {
72 protected ActorContext getActorContext() {
76 protected short getRemoteTransactionVersion() {
77 return remoteTransactionVersion;
80 protected Future<Object> executeOperationAsync(SerializableMessage msg) {
81 return completeOperation(actorContext.executeOperationAsync(getActor(), isTxActorLocal ? msg : msg.toSerializable()));
85 public void closeTransaction() {
86 LOG.debug("Tx {} closeTransaction called", getIdentifier());
88 actorContext.sendOperationAsync(getActor(), CloseTransaction.INSTANCE.toSerializable());
92 public boolean supportsDirectCommit() {
97 public Future<Object> directCommit() {
98 LOG.debug("Tx {} directCommit called", getIdentifier());
100 // Send the remaining batched modifications, if any, with the ready flag set.
102 return sendBatchedModifications(true, true);
106 public Future<ActorSelection> readyTransaction() {
107 LOG.debug("Tx {} readyTransaction called", getIdentifier());
109 // Send the remaining batched modifications, if any, with the ready flag set.
111 Future<Object> lastModificationsFuture = sendBatchedModifications(true, false);
113 return transformReadyReply(lastModificationsFuture);
116 protected Future<ActorSelection> transformReadyReply(final Future<Object> readyReplyFuture) {
117 // Transform the last reply Future into a Future that returns the cohort actor path from
118 // the last reply message. That's the end result of the ready operation.
120 return readyReplyFuture.transform(new Mapper<Object, ActorSelection>() {
122 public ActorSelection checkedApply(Object serializedReadyReply) {
123 LOG.debug("Tx {} readyTransaction", getIdentifier());
125 // At this point the ready operation succeeded and we need to extract the cohort
126 // actor path from the reply.
127 if(ReadyTransactionReply.isSerializedType(serializedReadyReply)) {
128 ReadyTransactionReply readyTxReply = ReadyTransactionReply.fromSerializable(serializedReadyReply);
129 return actorContext.actorSelection(extractCohortPathFrom(readyTxReply));
132 // Throwing an exception here will fail the Future.
133 throw new IllegalArgumentException(String.format("%s: Invalid reply type %s",
134 getIdentifier(), serializedReadyReply.getClass()));
136 }, TransactionProxy.SAME_FAILURE_TRANSFORMER, actorContext.getClientDispatcher());
139 protected String extractCohortPathFrom(ReadyTransactionReply readyTxReply) {
140 return readyTxReply.getCohortPath();
143 private BatchedModifications newBatchedModifications() {
144 return new BatchedModifications(getIdentifier().toString(), remoteTransactionVersion, transactionChainId);
147 private void batchModification(Modification modification) {
148 if(batchedModifications == null) {
149 batchedModifications = newBatchedModifications();
152 batchedModifications.addModification(modification);
154 if(batchedModifications.getModifications().size() >=
155 actorContext.getDatastoreContext().getShardBatchedModificationCount()) {
156 sendBatchedModifications();
160 protected Future<Object> sendBatchedModifications() {
161 return sendBatchedModifications(false, false);
164 protected Future<Object> sendBatchedModifications(boolean ready, boolean doCommitOnReady) {
165 Future<Object> sent = null;
166 if(ready || (batchedModifications != null && !batchedModifications.getModifications().isEmpty())) {
167 if(batchedModifications == null) {
168 batchedModifications = newBatchedModifications();
171 if(LOG.isDebugEnabled()) {
172 LOG.debug("Tx {} sending {} batched modifications, ready: {}", getIdentifier(),
173 batchedModifications.getModifications().size(), ready);
176 batchedModifications.setReady(ready);
177 batchedModifications.setDoCommitOnReady(doCommitOnReady);
178 batchedModifications.setTotalMessagesSent(++totalBatchedModificationsSent);
179 sent = executeOperationAsync(batchedModifications);
182 batchedModifications = null;
184 batchedModifications = newBatchedModifications();
192 public void deleteData(YangInstanceIdentifier path) {
193 LOG.debug("Tx {} deleteData called path = {}", getIdentifier(), path);
195 batchModification(new DeleteModification(path));
199 public void mergeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
200 LOG.debug("Tx {} mergeData called path = {}", getIdentifier(), path);
202 batchModification(new MergeModification(path, data));
206 public void writeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
207 LOG.debug("Tx {} writeData called path = {}", getIdentifier(), path);
209 batchModification(new WriteModification(path, data));
213 public void readData(final YangInstanceIdentifier path,
214 final SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture ) {
216 LOG.debug("Tx {} readData called path = {}", getIdentifier(), path);
218 // Send any batched modifications. This is necessary to honor the read uncommitted semantics of the
219 // public API contract.
221 sendBatchedModifications();
223 OnComplete<Object> onComplete = new OnComplete<Object>() {
225 public void onComplete(Throwable failure, Object readResponse) throws Throwable {
226 if(failure != null) {
227 LOG.debug("Tx {} read operation failed: {}", getIdentifier(), failure);
228 returnFuture.setException(new ReadFailedException(
229 "Error reading data for path " + path, failure));
232 LOG.debug("Tx {} read operation succeeded", getIdentifier(), failure);
234 if (readResponse instanceof ReadDataReply) {
235 ReadDataReply reply = (ReadDataReply) readResponse;
236 returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
238 } else if (ReadDataReply.isSerializedType(readResponse)) {
239 ReadDataReply reply = ReadDataReply.fromSerializable(readResponse);
240 returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
243 returnFuture.setException(new ReadFailedException(
244 "Invalid response reading data for path " + path));
250 Future<Object> readFuture = executeOperationAsync(new ReadData(path));
252 readFuture.onComplete(onComplete, actorContext.getClientDispatcher());
256 public void dataExists(final YangInstanceIdentifier path, final SettableFuture<Boolean> returnFuture) {
258 LOG.debug("Tx {} dataExists called path = {}", getIdentifier(), path);
260 // Send any batched modifications. This is necessary to honor the read uncommitted semantics of the
261 // public API contract.
263 sendBatchedModifications();
265 OnComplete<Object> onComplete = new OnComplete<Object>() {
267 public void onComplete(Throwable failure, Object response) throws Throwable {
268 if(failure != null) {
269 LOG.debug("Tx {} dataExists operation failed: {}", getIdentifier(), failure);
270 returnFuture.setException(new ReadFailedException(
271 "Error checking data exists for path " + path, failure));
273 LOG.debug("Tx {} dataExists operation succeeded", getIdentifier(), failure);
275 if (response instanceof DataExistsReply) {
276 returnFuture.set(Boolean.valueOf(((DataExistsReply) response).exists()));
278 } else if (response.getClass().equals(DataExistsReply.SERIALIZABLE_CLASS)) {
279 returnFuture.set(Boolean.valueOf(DataExistsReply.fromSerializable(response).exists()));
282 returnFuture.setException(new ReadFailedException(
283 "Invalid response checking exists for path " + path));
289 Future<Object> future = executeOperationAsync(new DataExists(path));
291 future.onComplete(onComplete, actorContext.getClientDispatcher());