2 * Copyright (c) 2014 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 static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
13 import akka.actor.ActorSelection;
14 import com.google.common.annotations.VisibleForTesting;
15 import com.google.common.collect.Iterables;
16 import com.google.common.util.concurrent.FluentFuture;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.MoreExecutors;
20 import com.google.common.util.concurrent.SettableFuture;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.List;
25 import java.util.Map.Entry;
26 import java.util.Optional;
28 import java.util.SortedSet;
29 import java.util.TreeMap;
30 import java.util.TreeSet;
31 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
32 import org.opendaylight.controller.cluster.datastore.TransactionModificationOperation.DeleteOperation;
33 import org.opendaylight.controller.cluster.datastore.TransactionModificationOperation.MergeOperation;
34 import org.opendaylight.controller.cluster.datastore.TransactionModificationOperation.WriteOperation;
35 import org.opendaylight.controller.cluster.datastore.messages.AbstractRead;
36 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
37 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
38 import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
39 import org.opendaylight.controller.cluster.datastore.utils.NormalizedNodeAggregator;
40 import org.opendaylight.mdsal.dom.spi.store.AbstractDOMStoreTransaction;
41 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import scala.concurrent.Future;
48 import scala.concurrent.Promise;
51 * A transaction potentially spanning multiple backend shards.
53 public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIdentifier>
54 implements DOMStoreReadWriteTransaction {
55 private enum TransactionState {
61 private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
63 private final Map<String, TransactionContextWrapper> txContextWrappers = new TreeMap<>();
64 private final AbstractTransactionContextFactory<?> txContextFactory;
65 private final TransactionType type;
66 private TransactionState state = TransactionState.OPEN;
69 public TransactionProxy(final AbstractTransactionContextFactory<?> txContextFactory, final TransactionType type) {
70 super(txContextFactory.nextIdentifier(), txContextFactory.getActorUtils().getDatastoreContext()
71 .isTransactionDebugContextEnabled());
72 this.txContextFactory = txContextFactory;
73 this.type = requireNonNull(type);
75 LOG.debug("New {} Tx - {}", type, getIdentifier());
79 public FluentFuture<Boolean> exists(final YangInstanceIdentifier path) {
80 return executeRead(shardNameFromIdentifier(path), new DataExists(path, DataStoreVersions.CURRENT_VERSION));
83 private <T> FluentFuture<T> executeRead(final String shardName, final AbstractRead<T> readCmd) {
84 checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
86 LOG.trace("Tx {} {} {}", getIdentifier(), readCmd.getClass().getSimpleName(), readCmd.getPath());
88 final SettableFuture<T> proxyFuture = SettableFuture.create();
89 TransactionContextWrapper contextWrapper = getContextWrapper(shardName);
90 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
92 public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
93 transactionContext.executeRead(readCmd, proxyFuture, havePermit);
97 return FluentFuture.from(proxyFuture);
101 public FluentFuture<Optional<NormalizedNode<?, ?>>> read(final YangInstanceIdentifier path) {
102 checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
103 requireNonNull(path, "path should not be null");
105 LOG.trace("Tx {} read {}", getIdentifier(), path);
106 return path.isEmpty() ? readAllData() : singleShardRead(shardNameFromIdentifier(path), path);
109 private FluentFuture<Optional<NormalizedNode<?, ?>>> singleShardRead(
110 final String shardName, final YangInstanceIdentifier path) {
111 return executeRead(shardName, new ReadData(path, DataStoreVersions.CURRENT_VERSION));
114 private FluentFuture<Optional<NormalizedNode<?, ?>>> readAllData() {
115 final Set<String> allShardNames = txContextFactory.getActorUtils().getConfiguration().getAllShardNames();
116 final Collection<FluentFuture<Optional<NormalizedNode<?, ?>>>> futures = new ArrayList<>(allShardNames.size());
118 for (String shardName : allShardNames) {
119 futures.add(singleShardRead(shardName, YangInstanceIdentifier.empty()));
122 final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
123 final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;
125 aggregateFuture = Futures.transform(listFuture, input -> {
127 return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.empty(), input,
128 txContextFactory.getActorUtils().getSchemaContext(),
129 txContextFactory.getActorUtils().getDatastoreContext().getLogicalStoreType());
130 } catch (DataValidationFailedException e) {
131 throw new IllegalArgumentException("Failed to aggregate", e);
133 }, MoreExecutors.directExecutor());
135 return FluentFuture.from(aggregateFuture);
139 public void delete(final YangInstanceIdentifier path) {
140 checkModificationState("delete", path);
142 executeModification(new DeleteOperation(path));
146 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
147 checkModificationState("merge", path);
149 executeModification(new MergeOperation(path, data));
153 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
154 checkModificationState("write", path);
156 executeModification(new WriteOperation(path, data));
159 private void executeModification(final TransactionModificationOperation operation) {
160 getContextWrapper(operation.path()).maybeExecuteTransactionOperation(operation);
163 private void checkModificationState(final String opName, final YangInstanceIdentifier path) {
164 checkState(type != TransactionType.READ_ONLY, "Modification operation on read-only transaction is not allowed");
165 checkState(state == TransactionState.OPEN, "Transaction is sealed - further modifications are not allowed");
166 LOG.trace("Tx {} {} {}", getIdentifier(), opName, path);
169 private boolean seal(final TransactionState newState) {
170 if (state == TransactionState.OPEN) {
178 public final void close() {
179 if (!seal(TransactionState.CLOSED)) {
180 checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
182 // Idempotent no-op as per AutoCloseable recommendation
186 for (TransactionContextWrapper contextWrapper : txContextWrappers.values()) {
187 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
189 public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
190 transactionContext.closeTransaction();
196 txContextWrappers.clear();
200 public final AbstractThreePhaseCommitCohort<?> ready() {
201 checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
203 final boolean success = seal(TransactionState.READY);
204 checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
206 LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextWrappers.size());
208 final AbstractThreePhaseCommitCohort<?> ret;
209 switch (txContextWrappers.size()) {
211 ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
214 final Entry<String, TransactionContextWrapper> e = Iterables.getOnlyElement(
215 txContextWrappers.entrySet());
216 ret = createSingleCommitCohort(e.getKey(), e.getValue());
219 ret = createMultiCommitCohort();
222 txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
224 final Throwable debugContext = getDebugContext();
225 return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
228 @SuppressWarnings({ "rawtypes", "unchecked" })
229 private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
230 final TransactionContextWrapper contextWrapper) {
232 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
234 final OperationCallback.Reference operationCallbackRef =
235 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
237 final TransactionContext transactionContext = contextWrapper.getTransactionContext();
239 if (transactionContext == null) {
240 final Promise promise = akka.dispatch.Futures.promise();
241 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
243 public void invoke(final TransactionContext newTransactionContext, final Boolean havePermit) {
244 promise.completeWith(getDirectCommitFuture(newTransactionContext, operationCallbackRef,
248 future = promise.future();
250 // avoid the creation of a promise and a TransactionOperation
251 future = getDirectCommitFuture(transactionContext, operationCallbackRef, null);
254 return new SingleCommitCohortProxy(txContextFactory.getActorUtils(), future, getIdentifier(),
255 operationCallbackRef);
258 private Future<?> getDirectCommitFuture(final TransactionContext transactionContext,
259 final OperationCallback.Reference operationCallbackRef, final Boolean havePermit) {
260 TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
261 txContextFactory.getActorUtils());
262 operationCallbackRef.set(rateLimitingCallback);
263 rateLimitingCallback.run();
264 return transactionContext.directCommit(havePermit);
267 private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort() {
269 final List<ThreePhaseCommitCohortProxy.CohortInfo> cohorts = new ArrayList<>(txContextWrappers.size());
270 final Optional<SortedSet<String>> shardNames = Optional.of(new TreeSet<>(txContextWrappers.keySet()));
271 for (Entry<String, TransactionContextWrapper> e : txContextWrappers.entrySet()) {
272 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
274 final TransactionContextWrapper wrapper = e.getValue();
276 // The remote tx version is obtained the via TransactionContext which may not be available yet so
277 // we pass a Supplier to dynamically obtain it. Once the ready Future is resolved the
278 // TransactionContext is available.
279 cohorts.add(new ThreePhaseCommitCohortProxy.CohortInfo(wrapper.readyTransaction(shardNames),
280 () -> wrapper.getTransactionContext().getTransactionVersion()));
283 return new ThreePhaseCommitCohortProxy(txContextFactory.getActorUtils(), cohorts, getIdentifier());
286 private String shardNameFromIdentifier(final YangInstanceIdentifier path) {
287 return txContextFactory.getActorUtils().getShardStrategyFactory().getStrategy(path).findShard(path);
290 private TransactionContextWrapper getContextWrapper(final YangInstanceIdentifier path) {
291 return getContextWrapper(shardNameFromIdentifier(path));
294 private TransactionContextWrapper getContextWrapper(final String shardName) {
295 final TransactionContextWrapper existing = txContextWrappers.get(shardName);
296 if (existing != null) {
300 final TransactionContextWrapper fresh = txContextFactory.newTransactionContextWrapper(this, shardName);
301 txContextWrappers.put(shardName, fresh);
305 TransactionType getType() {
310 return state != TransactionState.OPEN;
313 ActorUtils getActorUtils() {
314 return txContextFactory.getActorUtils();