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.messages.AbstractRead;
33 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
34 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
35 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
36 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
37 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
38 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
39 import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
40 import org.opendaylight.controller.cluster.datastore.utils.NormalizedNodeAggregator;
41 import org.opendaylight.mdsal.dom.spi.store.AbstractDOMStoreTransaction;
42 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import scala.concurrent.Future;
49 import scala.concurrent.Promise;
52 * A transaction potentially spanning multiple backend shards.
54 public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIdentifier>
55 implements DOMStoreReadWriteTransaction {
56 private enum TransactionState {
62 private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
64 private final Map<String, TransactionContextWrapper> txContextWrappers = new TreeMap<>();
65 private final AbstractTransactionContextFactory<?> txContextFactory;
66 private final TransactionType type;
67 private TransactionState state = TransactionState.OPEN;
70 public TransactionProxy(final AbstractTransactionContextFactory<?> txContextFactory, final TransactionType type) {
71 super(txContextFactory.nextIdentifier(), txContextFactory.getActorUtils().getDatastoreContext()
72 .isTransactionDebugContextEnabled());
73 this.txContextFactory = txContextFactory;
74 this.type = requireNonNull(type);
76 LOG.debug("New {} Tx - {}", type, getIdentifier());
80 public FluentFuture<Boolean> exists(final YangInstanceIdentifier path) {
81 return executeRead(shardNameFromIdentifier(path), new DataExists(path, DataStoreVersions.CURRENT_VERSION));
84 private <T> FluentFuture<T> executeRead(final String shardName, final AbstractRead<T> readCmd) {
85 checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
87 LOG.trace("Tx {} {} {}", getIdentifier(), readCmd.getClass().getSimpleName(), readCmd.getPath());
89 final SettableFuture<T> proxyFuture = SettableFuture.create();
90 TransactionContextWrapper contextWrapper = getContextWrapper(shardName);
91 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
93 public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
94 transactionContext.executeRead(readCmd, proxyFuture, havePermit);
98 return FluentFuture.from(proxyFuture);
102 public FluentFuture<Optional<NormalizedNode<?, ?>>> read(final YangInstanceIdentifier path) {
103 checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
104 requireNonNull(path, "path should not be null");
106 LOG.trace("Tx {} read {}", getIdentifier(), path);
107 return path.isEmpty() ? readAllData() : singleShardRead(shardNameFromIdentifier(path), path);
110 private FluentFuture<Optional<NormalizedNode<?, ?>>> singleShardRead(
111 final String shardName, final YangInstanceIdentifier path) {
112 return executeRead(shardName, new ReadData(path, DataStoreVersions.CURRENT_VERSION));
115 private FluentFuture<Optional<NormalizedNode<?, ?>>> readAllData() {
116 final Set<String> allShardNames = txContextFactory.getActorUtils().getConfiguration().getAllShardNames();
117 final Collection<FluentFuture<Optional<NormalizedNode<?, ?>>>> futures = new ArrayList<>(allShardNames.size());
119 for (String shardName : allShardNames) {
120 futures.add(singleShardRead(shardName, YangInstanceIdentifier.EMPTY));
123 final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
124 final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;
126 aggregateFuture = Futures.transform(listFuture, input -> {
128 return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input,
129 txContextFactory.getActorUtils().getSchemaContext(),
130 txContextFactory.getActorUtils().getDatastoreContext().getLogicalStoreType());
131 } catch (DataValidationFailedException e) {
132 throw new IllegalArgumentException("Failed to aggregate", e);
134 }, MoreExecutors.directExecutor());
136 return FluentFuture.from(aggregateFuture);
140 public void delete(final YangInstanceIdentifier path) {
141 executeModification(new DeleteModification(path));
145 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
146 executeModification(new MergeModification(path, data));
150 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
151 executeModification(new WriteModification(path, data));
154 private void executeModification(final AbstractModification modification) {
155 checkModificationState();
157 LOG.trace("Tx {} executeModification {} {}", getIdentifier(), modification.getClass().getSimpleName(),
158 modification.getPath());
160 TransactionContextWrapper contextWrapper = getContextWrapper(modification.getPath());
161 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
163 protected void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
164 transactionContext.executeModification(modification, havePermit);
169 private void checkModificationState() {
170 checkState(type != TransactionType.READ_ONLY, "Modification operation on read-only transaction is not allowed");
171 checkState(state == TransactionState.OPEN, "Transaction is sealed - further modifications are not allowed");
174 private boolean seal(final TransactionState newState) {
175 if (state == TransactionState.OPEN) {
184 public final void close() {
185 if (!seal(TransactionState.CLOSED)) {
186 checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
188 // Idempotent no-op as per AutoCloseable recommendation
192 for (TransactionContextWrapper contextWrapper : txContextWrappers.values()) {
193 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
195 public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
196 transactionContext.closeTransaction();
202 txContextWrappers.clear();
206 public final AbstractThreePhaseCommitCohort<?> ready() {
207 checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
209 final boolean success = seal(TransactionState.READY);
210 checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
212 LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextWrappers.size());
214 final AbstractThreePhaseCommitCohort<?> ret;
215 switch (txContextWrappers.size()) {
217 ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
220 final Entry<String, TransactionContextWrapper> e = Iterables.getOnlyElement(
221 txContextWrappers.entrySet());
222 ret = createSingleCommitCohort(e.getKey(), e.getValue());
225 ret = createMultiCommitCohort();
228 txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
230 final Throwable debugContext = getDebugContext();
231 return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
234 @SuppressWarnings({ "rawtypes", "unchecked" })
235 private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
236 final TransactionContextWrapper contextWrapper) {
238 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
240 final OperationCallback.Reference operationCallbackRef =
241 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
243 final TransactionContext transactionContext = contextWrapper.getTransactionContext();
245 if (transactionContext == null) {
246 final Promise promise = akka.dispatch.Futures.promise();
247 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
249 public void invoke(final TransactionContext newTransactionContext, final Boolean havePermit) {
250 promise.completeWith(getDirectCommitFuture(newTransactionContext, operationCallbackRef,
254 future = promise.future();
256 // avoid the creation of a promise and a TransactionOperation
257 future = getDirectCommitFuture(transactionContext, operationCallbackRef, null);
260 return new SingleCommitCohortProxy(txContextFactory.getActorUtils(), future, getIdentifier(),
261 operationCallbackRef);
264 private Future<?> getDirectCommitFuture(final TransactionContext transactionContext,
265 final OperationCallback.Reference operationCallbackRef, final Boolean havePermit) {
266 TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
267 txContextFactory.getActorUtils());
268 operationCallbackRef.set(rateLimitingCallback);
269 rateLimitingCallback.run();
270 return transactionContext.directCommit(havePermit);
273 private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort() {
275 final List<ThreePhaseCommitCohortProxy.CohortInfo> cohorts = new ArrayList<>(txContextWrappers.size());
276 final Optional<SortedSet<String>> shardNames = Optional.of(new TreeSet<>(txContextWrappers.keySet()));
277 for (Entry<String, TransactionContextWrapper> e : txContextWrappers.entrySet()) {
278 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
280 final TransactionContextWrapper wrapper = e.getValue();
282 // The remote tx version is obtained the via TransactionContext which may not be available yet so
283 // we pass a Supplier to dynamically obtain it. Once the ready Future is resolved the
284 // TransactionContext is available.
285 cohorts.add(new ThreePhaseCommitCohortProxy.CohortInfo(wrapper.readyTransaction(shardNames),
286 () -> wrapper.getTransactionContext().getTransactionVersion()));
289 return new ThreePhaseCommitCohortProxy(txContextFactory.getActorUtils(), cohorts, getIdentifier());
292 private String shardNameFromIdentifier(final YangInstanceIdentifier path) {
293 return txContextFactory.getActorUtils().getShardStrategyFactory().getStrategy(path).findShard(path);
296 private TransactionContextWrapper getContextWrapper(final YangInstanceIdentifier path) {
297 return getContextWrapper(shardNameFromIdentifier(path));
300 private TransactionContextWrapper getContextWrapper(final String shardName) {
301 final TransactionContextWrapper existing = txContextWrappers.get(shardName);
302 if (existing != null) {
306 final TransactionContextWrapper fresh = txContextFactory.newTransactionContextWrapper(this, shardName);
307 txContextWrappers.put(shardName, fresh);
311 TransactionType getType() {
316 return state != TransactionState.OPEN;
319 ActorUtils getActorUtils() {
320 return txContextFactory.getActorUtils();