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.controller.md.sal.common.api.data.ReadFailedException;
40 import org.opendaylight.controller.sal.core.spi.data.AbstractDOMStoreTransaction;
41 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
42 import org.opendaylight.yangtools.util.concurrent.MappingCheckedFuture;
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.debug("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) {
96 transactionContext.executeRead(readCmd, proxyFuture);
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");
108 LOG.debug("Tx {} read {}", getIdentifier(), path);
110 if (YangInstanceIdentifier.EMPTY.equals(path)) {
111 return readAllData();
113 return singleShardRead(shardNameFromIdentifier(path), path);
117 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> singleShardRead(
118 final String shardName, final YangInstanceIdentifier path) {
119 return executeRead(shardName, new ReadData(path, DataStoreVersions.CURRENT_VERSION));
122 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readAllData() {
123 final Set<String> allShardNames = txContextFactory.getActorContext().getConfiguration().getAllShardNames();
124 final Collection<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>> futures =
125 new ArrayList<>(allShardNames.size());
127 for (String shardName : allShardNames) {
128 futures.add(singleShardRead(shardName, YangInstanceIdentifier.EMPTY));
131 final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
132 final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;
134 aggregateFuture = Futures.transform(listFuture,
135 (Function<List<Optional<NormalizedNode<?, ?>>>, Optional<NormalizedNode<?, ?>>>) input -> {
137 return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input,
138 txContextFactory.getActorContext().getSchemaContext(),
139 txContextFactory.getActorContext().getDatastoreContext().getLogicalStoreType());
140 } catch (DataValidationFailedException e) {
141 throw new IllegalArgumentException("Failed to aggregate", e);
143 }, MoreExecutors.directExecutor());
145 return MappingCheckedFuture.create(aggregateFuture, ReadFailedException.MAPPER);
149 public void delete(final YangInstanceIdentifier path) {
150 executeModification(new DeleteModification(path));
154 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
155 executeModification(new MergeModification(path, data));
159 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
160 executeModification(new WriteModification(path, data));
163 private void executeModification(final AbstractModification modification) {
164 checkModificationState();
166 LOG.debug("Tx {} executeModification {} {}", getIdentifier(), modification.getClass().getSimpleName(),
167 modification.getPath());
169 TransactionContextWrapper contextWrapper = getContextWrapper(modification.getPath());
170 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
172 protected void invoke(final TransactionContext transactionContext) {
173 transactionContext.executeModification(modification);
178 private void checkModificationState() {
179 Preconditions.checkState(type != TransactionType.READ_ONLY,
180 "Modification operation on read-only transaction is not allowed");
181 Preconditions.checkState(state == TransactionState.OPEN,
182 "Transaction is sealed - further modifications are not allowed");
185 private boolean seal(final TransactionState newState) {
186 if (state == TransactionState.OPEN) {
195 public final void close() {
196 if (!seal(TransactionState.CLOSED)) {
197 Preconditions.checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
199 // Idempotent no-op as per AutoCloseable recommendation
203 for (TransactionContextWrapper contextWrapper : txContextWrappers.values()) {
204 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
206 public void invoke(final TransactionContext transactionContext) {
207 transactionContext.closeTransaction();
213 txContextWrappers.clear();
217 public final AbstractThreePhaseCommitCohort<?> ready() {
218 Preconditions.checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
220 final boolean success = seal(TransactionState.READY);
221 Preconditions.checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
223 LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextWrappers.size());
225 final AbstractThreePhaseCommitCohort<?> ret;
226 switch (txContextWrappers.size()) {
228 ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
231 final Entry<String, TransactionContextWrapper> e = Iterables.getOnlyElement(
232 txContextWrappers.entrySet());
233 ret = createSingleCommitCohort(e.getKey(), e.getValue());
236 ret = createMultiCommitCohort(txContextWrappers.entrySet());
239 txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
241 final Throwable debugContext = getDebugContext();
242 return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
245 @SuppressWarnings({ "rawtypes", "unchecked" })
246 private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
247 final TransactionContextWrapper contextWrapper) {
249 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
251 final OperationCallback.Reference operationCallbackRef =
252 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
254 final TransactionContext transactionContext = contextWrapper.getTransactionContext();
256 if (transactionContext == null) {
257 final Promise promise = akka.dispatch.Futures.promise();
258 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
260 public void invoke(final TransactionContext newTransactionContext) {
261 promise.completeWith(getDirectCommitFuture(newTransactionContext, operationCallbackRef));
264 future = promise.future();
266 // avoid the creation of a promise and a TransactionOperation
267 future = getDirectCommitFuture(transactionContext, operationCallbackRef);
270 return new SingleCommitCohortProxy(txContextFactory.getActorContext(), future, getIdentifier(),
271 operationCallbackRef);
274 private Future<?> getDirectCommitFuture(final TransactionContext transactionContext,
275 final OperationCallback.Reference operationCallbackRef) {
276 TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
277 txContextFactory.getActorContext());
278 operationCallbackRef.set(rateLimitingCallback);
279 rateLimitingCallback.run();
280 return transactionContext.directCommit();
283 private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort(
284 final Set<Entry<String, TransactionContextWrapper>> txContextWrapperEntries) {
286 final List<ThreePhaseCommitCohortProxy.CohortInfo> cohorts = new ArrayList<>(txContextWrapperEntries.size());
287 for (Entry<String, TransactionContextWrapper> e : txContextWrapperEntries) {
288 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
290 final TransactionContextWrapper wrapper = e.getValue();
292 // The remote tx version is obtained the via TransactionContext which may not be available yet so
293 // we pass a Supplier to dynamically obtain it. Once the ready Future is resolved the
294 // TransactionContext is available.
295 Supplier<Short> txVersionSupplier = () -> wrapper.getTransactionContext().getTransactionVersion();
297 cohorts.add(new ThreePhaseCommitCohortProxy.CohortInfo(wrapper.readyTransaction(), txVersionSupplier));
300 return new ThreePhaseCommitCohortProxy(txContextFactory.getActorContext(), cohorts, getIdentifier());
303 private String shardNameFromIdentifier(final YangInstanceIdentifier path) {
304 return txContextFactory.getActorContext().getShardStrategyFactory().getStrategy(path).findShard(path);
307 private TransactionContextWrapper getContextWrapper(final YangInstanceIdentifier path) {
308 return getContextWrapper(shardNameFromIdentifier(path));
311 private TransactionContextWrapper getContextWrapper(final String shardName) {
312 final TransactionContextWrapper existing = txContextWrappers.get(shardName);
313 if (existing != null) {
317 final TransactionContextWrapper fresh = txContextFactory.newTransactionContextWrapper(this, shardName);
318 txContextWrappers.put(shardName, fresh);
322 TransactionType getType() {
327 return state != TransactionState.OPEN;
330 ActorContext getActorContext() {
331 return txContextFactory.getActorContext();