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.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Supplier;
16 import com.google.common.collect.Iterables;
17 import com.google.common.util.concurrent.CheckedFuture;
18 import com.google.common.util.concurrent.Futures;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import com.google.common.util.concurrent.MoreExecutors;
21 import com.google.common.util.concurrent.SettableFuture;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.HashMap;
25 import java.util.List;
27 import java.util.Map.Entry;
29 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
30 import org.opendaylight.controller.cluster.datastore.messages.AbstractRead;
31 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
32 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
33 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
34 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
35 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
36 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
37 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
38 import org.opendaylight.controller.cluster.datastore.utils.NormalizedNodeAggregator;
39 import org.opendaylight.mdsal.common.api.MappingCheckedFuture;
40 import org.opendaylight.mdsal.common.api.ReadFailedException;
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 HashMap<>();
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 CheckedFuture<Boolean, ReadFailedException> exists(final YangInstanceIdentifier path) {
81 return executeRead(shardNameFromIdentifier(path), new DataExists(path, DataStoreVersions.CURRENT_VERSION));
84 private <T> CheckedFuture<T, ReadFailedException> executeRead(final String shardName,
85 final AbstractRead<T> readCmd) {
86 Preconditions.checkState(type != TransactionType.WRITE_ONLY,
87 "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 MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
104 public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final YangInstanceIdentifier path) {
105 Preconditions.checkState(type != TransactionType.WRITE_ONLY,
106 "Reads from write-only transactions are not allowed");
107 Preconditions.checkNotNull(path, "path should not be null");
109 LOG.trace("Tx {} read {}", getIdentifier(), path);
110 return path.isEmpty() ? readAllData() : singleShardRead(shardNameFromIdentifier(path), path);
113 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> singleShardRead(
114 final String shardName, final YangInstanceIdentifier path) {
115 return executeRead(shardName, new ReadData(path, DataStoreVersions.CURRENT_VERSION));
118 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readAllData() {
119 final Set<String> allShardNames = txContextFactory.getActorContext().getConfiguration().getAllShardNames();
120 final Collection<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>> futures =
121 new ArrayList<>(allShardNames.size());
123 for (String shardName : allShardNames) {
124 futures.add(singleShardRead(shardName, YangInstanceIdentifier.EMPTY));
127 final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
128 final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;
130 aggregateFuture = Futures.transform(listFuture,
131 (Function<List<Optional<NormalizedNode<?, ?>>>, Optional<NormalizedNode<?, ?>>>) input -> {
133 return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input,
134 txContextFactory.getActorContext().getSchemaContext(),
135 txContextFactory.getActorContext().getDatastoreContext().getLogicalStoreType());
136 } catch (DataValidationFailedException e) {
137 throw new IllegalArgumentException("Failed to aggregate", e);
139 }, MoreExecutors.directExecutor());
141 return MappingCheckedFuture.create(aggregateFuture, ReadFailedException.MAPPER);
145 public void delete(final YangInstanceIdentifier path) {
146 executeModification(new DeleteModification(path));
150 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
151 executeModification(new MergeModification(path, data));
155 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
156 executeModification(new WriteModification(path, data));
159 private void executeModification(final AbstractModification modification) {
160 checkModificationState();
162 LOG.trace("Tx {} executeModification {} {}", getIdentifier(), modification.getClass().getSimpleName(),
163 modification.getPath());
165 TransactionContextWrapper contextWrapper = getContextWrapper(modification.getPath());
166 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
168 protected void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
169 transactionContext.executeModification(modification, havePermit);
174 private void checkModificationState() {
175 Preconditions.checkState(type != TransactionType.READ_ONLY,
176 "Modification operation on read-only transaction is not allowed");
177 Preconditions.checkState(state == TransactionState.OPEN,
178 "Transaction is sealed - further modifications are not allowed");
181 private boolean seal(final TransactionState newState) {
182 if (state == TransactionState.OPEN) {
191 public final void close() {
192 if (!seal(TransactionState.CLOSED)) {
193 Preconditions.checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
195 // Idempotent no-op as per AutoCloseable recommendation
199 for (TransactionContextWrapper contextWrapper : txContextWrappers.values()) {
200 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
202 public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
203 transactionContext.closeTransaction();
209 txContextWrappers.clear();
213 public final AbstractThreePhaseCommitCohort<?> ready() {
214 Preconditions.checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
216 final boolean success = seal(TransactionState.READY);
217 Preconditions.checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
219 LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextWrappers.size());
221 final AbstractThreePhaseCommitCohort<?> ret;
222 switch (txContextWrappers.size()) {
224 ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
227 final Entry<String, TransactionContextWrapper> e = Iterables.getOnlyElement(
228 txContextWrappers.entrySet());
229 ret = createSingleCommitCohort(e.getKey(), e.getValue());
232 ret = createMultiCommitCohort(txContextWrappers.entrySet());
235 txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
237 final Throwable debugContext = getDebugContext();
238 return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
241 @SuppressWarnings({ "rawtypes", "unchecked" })
242 private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
243 final TransactionContextWrapper contextWrapper) {
245 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
247 final OperationCallback.Reference operationCallbackRef =
248 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
250 final TransactionContext transactionContext = contextWrapper.getTransactionContext();
252 if (transactionContext == null) {
253 final Promise promise = akka.dispatch.Futures.promise();
254 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
256 public void invoke(final TransactionContext newTransactionContext, final Boolean havePermit) {
257 promise.completeWith(getDirectCommitFuture(newTransactionContext, operationCallbackRef,
261 future = promise.future();
263 // avoid the creation of a promise and a TransactionOperation
264 future = getDirectCommitFuture(transactionContext, operationCallbackRef, null);
267 return new SingleCommitCohortProxy(txContextFactory.getActorContext(), future, getIdentifier(),
268 operationCallbackRef);
271 private Future<?> getDirectCommitFuture(final TransactionContext transactionContext,
272 final OperationCallback.Reference operationCallbackRef, final Boolean havePermit) {
273 TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
274 txContextFactory.getActorContext());
275 operationCallbackRef.set(rateLimitingCallback);
276 rateLimitingCallback.run();
277 return transactionContext.directCommit(havePermit);
280 private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort(
281 final Set<Entry<String, TransactionContextWrapper>> txContextWrapperEntries) {
283 final List<ThreePhaseCommitCohortProxy.CohortInfo> cohorts = new ArrayList<>(txContextWrapperEntries.size());
284 for (Entry<String, TransactionContextWrapper> e : txContextWrapperEntries) {
285 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
287 final TransactionContextWrapper wrapper = e.getValue();
289 // The remote tx version is obtained the via TransactionContext which may not be available yet so
290 // we pass a Supplier to dynamically obtain it. Once the ready Future is resolved the
291 // TransactionContext is available.
292 Supplier<Short> txVersionSupplier = () -> wrapper.getTransactionContext().getTransactionVersion();
294 cohorts.add(new ThreePhaseCommitCohortProxy.CohortInfo(wrapper.readyTransaction(), txVersionSupplier));
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();