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.base.Function;
16 import com.google.common.base.Supplier;
17 import com.google.common.collect.Iterables;
18 import com.google.common.util.concurrent.FluentFuture;
19 import com.google.common.util.concurrent.Futures;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.MoreExecutors;
22 import com.google.common.util.concurrent.SettableFuture;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.List;
27 import java.util.Map.Entry;
28 import java.util.Optional;
30 import java.util.SortedSet;
31 import java.util.TreeMap;
32 import java.util.TreeSet;
33 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
34 import org.opendaylight.controller.cluster.datastore.messages.AbstractRead;
35 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
36 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
37 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
38 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
39 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
40 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
41 import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
42 import org.opendaylight.controller.cluster.datastore.utils.NormalizedNodeAggregator;
43 import org.opendaylight.mdsal.dom.spi.store.AbstractDOMStoreTransaction;
44 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import scala.concurrent.Future;
51 import scala.concurrent.Promise;
54 * A transaction potentially spanning multiple backend shards.
56 public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIdentifier>
57 implements DOMStoreReadWriteTransaction {
58 private enum TransactionState {
64 private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
66 private final Map<String, TransactionContextWrapper> txContextWrappers = new TreeMap<>();
67 private final AbstractTransactionContextFactory<?> txContextFactory;
68 private final TransactionType type;
69 private TransactionState state = TransactionState.OPEN;
72 public TransactionProxy(final AbstractTransactionContextFactory<?> txContextFactory, final TransactionType type) {
73 super(txContextFactory.nextIdentifier(), txContextFactory.getActorUtils().getDatastoreContext()
74 .isTransactionDebugContextEnabled());
75 this.txContextFactory = txContextFactory;
76 this.type = requireNonNull(type);
78 LOG.debug("New {} Tx - {}", type, getIdentifier());
82 public FluentFuture<Boolean> exists(final YangInstanceIdentifier path) {
83 return executeRead(shardNameFromIdentifier(path), new DataExists(path, DataStoreVersions.CURRENT_VERSION));
86 private <T> FluentFuture<T> executeRead(final String shardName, final AbstractRead<T> readCmd) {
87 checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
89 LOG.trace("Tx {} {} {}", getIdentifier(), readCmd.getClass().getSimpleName(), readCmd.getPath());
91 final SettableFuture<T> proxyFuture = SettableFuture.create();
92 TransactionContextWrapper contextWrapper = getContextWrapper(shardName);
93 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
95 public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
96 transactionContext.executeRead(readCmd, proxyFuture, havePermit);
100 return FluentFuture.from(proxyFuture);
104 public FluentFuture<Optional<NormalizedNode<?, ?>>> read(final YangInstanceIdentifier path) {
105 checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
106 requireNonNull(path, "path should not be null");
108 LOG.trace("Tx {} read {}", getIdentifier(), path);
109 return path.isEmpty() ? readAllData() : singleShardRead(shardNameFromIdentifier(path), path);
112 private FluentFuture<Optional<NormalizedNode<?, ?>>> singleShardRead(
113 final String shardName, final YangInstanceIdentifier path) {
114 return executeRead(shardName, new ReadData(path, DataStoreVersions.CURRENT_VERSION));
117 private FluentFuture<Optional<NormalizedNode<?, ?>>> readAllData() {
118 final Set<String> allShardNames = txContextFactory.getActorUtils().getConfiguration().getAllShardNames();
119 final Collection<FluentFuture<Optional<NormalizedNode<?, ?>>>> futures = new ArrayList<>(allShardNames.size());
121 for (String shardName : allShardNames) {
122 futures.add(singleShardRead(shardName, YangInstanceIdentifier.EMPTY));
125 final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
126 final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;
128 aggregateFuture = Futures.transform(listFuture,
129 (Function<List<Optional<NormalizedNode<?, ?>>>, Optional<NormalizedNode<?, ?>>>) input -> {
131 return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input,
132 txContextFactory.getActorUtils().getSchemaContext(),
133 txContextFactory.getActorUtils().getDatastoreContext().getLogicalStoreType());
134 } catch (DataValidationFailedException e) {
135 throw new IllegalArgumentException("Failed to aggregate", e);
137 }, MoreExecutors.directExecutor());
139 return FluentFuture.from(aggregateFuture);
143 public void delete(final YangInstanceIdentifier path) {
144 executeModification(new DeleteModification(path));
148 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
149 executeModification(new MergeModification(path, data));
153 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
154 executeModification(new WriteModification(path, data));
157 private void executeModification(final AbstractModification modification) {
158 checkModificationState();
160 LOG.trace("Tx {} executeModification {} {}", getIdentifier(), modification.getClass().getSimpleName(),
161 modification.getPath());
163 TransactionContextWrapper contextWrapper = getContextWrapper(modification.getPath());
164 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
166 protected void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
167 transactionContext.executeModification(modification, havePermit);
172 private void checkModificationState() {
173 checkState(type != TransactionType.READ_ONLY, "Modification operation on read-only transaction is not allowed");
174 checkState(state == TransactionState.OPEN, "Transaction is sealed - further modifications are not allowed");
177 private boolean seal(final TransactionState newState) {
178 if (state == TransactionState.OPEN) {
187 public final void close() {
188 if (!seal(TransactionState.CLOSED)) {
189 checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
191 // Idempotent no-op as per AutoCloseable recommendation
195 for (TransactionContextWrapper contextWrapper : txContextWrappers.values()) {
196 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
198 public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
199 transactionContext.closeTransaction();
205 txContextWrappers.clear();
209 public final AbstractThreePhaseCommitCohort<?> ready() {
210 checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
212 final boolean success = seal(TransactionState.READY);
213 checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
215 LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextWrappers.size());
217 final AbstractThreePhaseCommitCohort<?> ret;
218 switch (txContextWrappers.size()) {
220 ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
223 final Entry<String, TransactionContextWrapper> e = Iterables.getOnlyElement(
224 txContextWrappers.entrySet());
225 ret = createSingleCommitCohort(e.getKey(), e.getValue());
228 ret = createMultiCommitCohort();
231 txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
233 final Throwable debugContext = getDebugContext();
234 return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
237 @SuppressWarnings({ "rawtypes", "unchecked" })
238 private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
239 final TransactionContextWrapper contextWrapper) {
241 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
243 final OperationCallback.Reference operationCallbackRef =
244 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
246 final TransactionContext transactionContext = contextWrapper.getTransactionContext();
248 if (transactionContext == null) {
249 final Promise promise = akka.dispatch.Futures.promise();
250 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
252 public void invoke(final TransactionContext newTransactionContext, final Boolean havePermit) {
253 promise.completeWith(getDirectCommitFuture(newTransactionContext, operationCallbackRef,
257 future = promise.future();
259 // avoid the creation of a promise and a TransactionOperation
260 future = getDirectCommitFuture(transactionContext, operationCallbackRef, null);
263 return new SingleCommitCohortProxy(txContextFactory.getActorUtils(), future, getIdentifier(),
264 operationCallbackRef);
267 private Future<?> getDirectCommitFuture(final TransactionContext transactionContext,
268 final OperationCallback.Reference operationCallbackRef, final Boolean havePermit) {
269 TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
270 txContextFactory.getActorUtils());
271 operationCallbackRef.set(rateLimitingCallback);
272 rateLimitingCallback.run();
273 return transactionContext.directCommit(havePermit);
276 private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort() {
278 final List<ThreePhaseCommitCohortProxy.CohortInfo> cohorts = new ArrayList<>(txContextWrappers.size());
279 final Optional<SortedSet<String>> shardNames = Optional.of(new TreeSet<>(txContextWrappers.keySet()));
280 for (Entry<String, TransactionContextWrapper> e : txContextWrappers.entrySet()) {
281 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
283 final TransactionContextWrapper wrapper = e.getValue();
285 // The remote tx version is obtained the via TransactionContext which may not be available yet so
286 // we pass a Supplier to dynamically obtain it. Once the ready Future is resolved the
287 // TransactionContext is available.
288 Supplier<Short> txVersionSupplier = () -> wrapper.getTransactionContext().getTransactionVersion();
290 cohorts.add(new ThreePhaseCommitCohortProxy.CohortInfo(wrapper.readyTransaction(shardNames),
294 return new ThreePhaseCommitCohortProxy(txContextFactory.getActorUtils(), cohorts, getIdentifier());
297 private String shardNameFromIdentifier(final YangInstanceIdentifier path) {
298 return txContextFactory.getActorUtils().getShardStrategyFactory().getStrategy(path).findShard(path);
301 private TransactionContextWrapper getContextWrapper(final YangInstanceIdentifier path) {
302 return getContextWrapper(shardNameFromIdentifier(path));
305 private TransactionContextWrapper getContextWrapper(final String shardName) {
306 final TransactionContextWrapper existing = txContextWrappers.get(shardName);
307 if (existing != null) {
311 final TransactionContextWrapper fresh = txContextFactory.newTransactionContextWrapper(this, shardName);
312 txContextWrappers.put(shardName, fresh);
316 TransactionType getType() {
321 return state != TransactionState.OPEN;
324 ActorUtils getActorUtils() {
325 return txContextFactory.getActorUtils();