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 akka.actor.ActorSelection;
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.Function;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Supplier;
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.ActorContext;
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.getActorContext().getDatastoreContext()
72 .isTransactionDebugContextEnabled());
73 this.txContextFactory = txContextFactory;
74 this.type = Preconditions.checkNotNull(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 Preconditions.checkState(type != TransactionType.WRITE_ONLY,
86 "Reads from write-only transactions are not allowed");
88 LOG.trace("Tx {} {} {}", getIdentifier(), readCmd.getClass().getSimpleName(), readCmd.getPath());
90 final SettableFuture<T> proxyFuture = SettableFuture.create();
91 TransactionContextWrapper contextWrapper = getContextWrapper(shardName);
92 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
94 public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
95 transactionContext.executeRead(readCmd, proxyFuture, havePermit);
99 return FluentFuture.from(proxyFuture);
103 public FluentFuture<Optional<NormalizedNode<?, ?>>> read(final YangInstanceIdentifier path) {
104 Preconditions.checkState(type != TransactionType.WRITE_ONLY,
105 "Reads from write-only transactions are not allowed");
106 Preconditions.checkNotNull(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.getActorContext().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.getActorContext().getSchemaContext(),
133 txContextFactory.getActorContext().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 Preconditions.checkState(type != TransactionType.READ_ONLY,
174 "Modification operation on read-only transaction is not allowed");
175 Preconditions.checkState(state == TransactionState.OPEN,
176 "Transaction is sealed - further modifications are not allowed");
179 private boolean seal(final TransactionState newState) {
180 if (state == TransactionState.OPEN) {
189 public final void close() {
190 if (!seal(TransactionState.CLOSED)) {
191 Preconditions.checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
193 // Idempotent no-op as per AutoCloseable recommendation
197 for (TransactionContextWrapper contextWrapper : txContextWrappers.values()) {
198 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
200 public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
201 transactionContext.closeTransaction();
207 txContextWrappers.clear();
211 public final AbstractThreePhaseCommitCohort<?> ready() {
212 Preconditions.checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
214 final boolean success = seal(TransactionState.READY);
215 Preconditions.checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
217 LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextWrappers.size());
219 final AbstractThreePhaseCommitCohort<?> ret;
220 switch (txContextWrappers.size()) {
222 ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
225 final Entry<String, TransactionContextWrapper> e = Iterables.getOnlyElement(
226 txContextWrappers.entrySet());
227 ret = createSingleCommitCohort(e.getKey(), e.getValue());
230 ret = createMultiCommitCohort();
233 txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
235 final Throwable debugContext = getDebugContext();
236 return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
239 @SuppressWarnings({ "rawtypes", "unchecked" })
240 private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
241 final TransactionContextWrapper contextWrapper) {
243 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
245 final OperationCallback.Reference operationCallbackRef =
246 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
248 final TransactionContext transactionContext = contextWrapper.getTransactionContext();
250 if (transactionContext == null) {
251 final Promise promise = akka.dispatch.Futures.promise();
252 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
254 public void invoke(final TransactionContext newTransactionContext, final Boolean havePermit) {
255 promise.completeWith(getDirectCommitFuture(newTransactionContext, operationCallbackRef,
259 future = promise.future();
261 // avoid the creation of a promise and a TransactionOperation
262 future = getDirectCommitFuture(transactionContext, operationCallbackRef, null);
265 return new SingleCommitCohortProxy(txContextFactory.getActorContext(), future, getIdentifier(),
266 operationCallbackRef);
269 private Future<?> getDirectCommitFuture(final TransactionContext transactionContext,
270 final OperationCallback.Reference operationCallbackRef, final Boolean havePermit) {
271 TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
272 txContextFactory.getActorContext());
273 operationCallbackRef.set(rateLimitingCallback);
274 rateLimitingCallback.run();
275 return transactionContext.directCommit(havePermit);
278 private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort() {
280 final List<ThreePhaseCommitCohortProxy.CohortInfo> cohorts = new ArrayList<>(txContextWrappers.size());
281 final java.util.Optional<SortedSet<String>> shardNames =
282 java.util.Optional.of(new TreeSet<>(txContextWrappers.keySet()));
283 for (Entry<String, TransactionContextWrapper> e : txContextWrappers.entrySet()) {
284 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
286 final TransactionContextWrapper wrapper = e.getValue();
288 // The remote tx version is obtained the via TransactionContext which may not be available yet so
289 // we pass a Supplier to dynamically obtain it. Once the ready Future is resolved the
290 // TransactionContext is available.
291 Supplier<Short> txVersionSupplier = () -> wrapper.getTransactionContext().getTransactionVersion();
293 cohorts.add(new ThreePhaseCommitCohortProxy.CohortInfo(wrapper.readyTransaction(shardNames),
297 return new ThreePhaseCommitCohortProxy(txContextFactory.getActorContext(), cohorts, getIdentifier());
300 private String shardNameFromIdentifier(final YangInstanceIdentifier path) {
301 return txContextFactory.getActorContext().getShardStrategyFactory().getStrategy(path).findShard(path);
304 private TransactionContextWrapper getContextWrapper(final YangInstanceIdentifier path) {
305 return getContextWrapper(shardNameFromIdentifier(path));
308 private TransactionContextWrapper getContextWrapper(final String shardName) {
309 final TransactionContextWrapper existing = txContextWrappers.get(shardName);
310 if (existing != null) {
314 final TransactionContextWrapper fresh = txContextFactory.newTransactionContextWrapper(this, shardName);
315 txContextWrappers.put(shardName, fresh);
319 TransactionType getType() {
324 return state != TransactionState.OPEN;
327 ActorContext getActorContext() {
328 return txContextFactory.getActorContext();