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.SettableFuture;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.HashMap;
24 import java.util.List;
26 import java.util.Map.Entry;
28 import org.opendaylight.controller.cluster.datastore.identifiers.TransactionIdentifier;
29 import org.opendaylight.controller.cluster.datastore.messages.AbstractRead;
30 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
31 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
32 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
33 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
34 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
35 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
36 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
37 import org.opendaylight.controller.cluster.datastore.utils.NormalizedNodeAggregator;
38 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
39 import org.opendaylight.controller.sal.core.spi.data.AbstractDOMStoreTransaction;
40 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
41 import org.opendaylight.yangtools.util.concurrent.MappingCheckedFuture;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import scala.concurrent.Future;
48 import scala.concurrent.Promise;
51 * A transaction potentially spanning multiple backend shards.
53 public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIdentifier> implements DOMStoreReadWriteTransaction {
54 private static enum TransactionState {
59 private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
61 private final Map<String, TransactionContextWrapper> txContextWrappers = new HashMap<>();
62 private final AbstractTransactionContextFactory<?> txContextFactory;
63 private final TransactionType type;
64 private TransactionState state = TransactionState.OPEN;
67 public TransactionProxy(final AbstractTransactionContextFactory<?> txContextFactory, final TransactionType type) {
68 super(txContextFactory.nextIdentifier(), txContextFactory.getActorContext().getDatastoreContext()
69 .isTransactionDebugContextEnabled());
70 this.txContextFactory = txContextFactory;
71 this.type = Preconditions.checkNotNull(type);
73 LOG.debug("New {} Tx - {}", type, getIdentifier());
77 public CheckedFuture<Boolean, ReadFailedException> exists(final YangInstanceIdentifier path) {
78 return executeRead(shardNameFromIdentifier(path), new DataExists(path, DataStoreVersions.CURRENT_VERSION));
81 private <T> CheckedFuture<T, ReadFailedException> executeRead(String shardName, final AbstractRead<T> readCmd) {
82 Preconditions.checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
84 if(LOG.isDebugEnabled()) {
85 LOG.debug("Tx {} {} {}", getIdentifier(), readCmd.getClass().getSimpleName(), readCmd.getPath());
88 final SettableFuture<T> proxyFuture = SettableFuture.create();
89 TransactionContextWrapper contextWrapper = getContextWrapper(shardName);
90 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
92 public void invoke(TransactionContext transactionContext) {
93 transactionContext.executeRead(readCmd, proxyFuture);
97 return MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
101 public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final YangInstanceIdentifier path) {
102 Preconditions.checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
104 LOG.debug("Tx {} read {}", getIdentifier(), path);
106 if (YangInstanceIdentifier.EMPTY.equals(path)) {
107 return readAllData();
109 return 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 = new ArrayList<>(allShardNames.size());
122 for (String shardName : allShardNames) {
123 futures.add(singleShardRead(shardName, YangInstanceIdentifier.EMPTY));
126 final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
127 final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;
129 aggregateFuture = Futures.transform(listFuture, new Function<List<Optional<NormalizedNode<?, ?>>>, Optional<NormalizedNode<?, ?>>>() {
131 public Optional<NormalizedNode<?, ?>> apply(final List<Optional<NormalizedNode<?, ?>>> input) {
133 return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input, txContextFactory.getActorContext().getSchemaContext());
134 } catch (DataValidationFailedException e) {
135 throw new IllegalArgumentException("Failed to aggregate", e);
140 return MappingCheckedFuture.create(aggregateFuture, ReadFailedException.MAPPER);
144 public void delete(final YangInstanceIdentifier path) {
145 executeModification(new DeleteModification(path));
149 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
150 executeModification(new MergeModification(path, data));
154 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
155 executeModification(new WriteModification(path, data));
158 private void executeModification(final AbstractModification modification) {
159 checkModificationState();
161 if(LOG.isDebugEnabled()) {
162 LOG.debug("Tx {} executeModification {} {}", getIdentifier(), modification.getClass().getSimpleName(),
163 modification.getPath());
166 TransactionContextWrapper contextWrapper = getContextWrapper(modification.getPath());
167 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
169 protected void invoke(TransactionContext transactionContext) {
170 transactionContext.executeModification(modification);
175 private void checkModificationState() {
176 Preconditions.checkState(type != TransactionType.READ_ONLY,
177 "Modification operation on read-only transaction is not allowed");
178 Preconditions.checkState(state == TransactionState.OPEN,
179 "Transaction is sealed - further modifications are not allowed");
182 private boolean seal(final TransactionState newState) {
183 if (state == TransactionState.OPEN) {
192 public final void close() {
193 if (!seal(TransactionState.CLOSED)) {
194 Preconditions.checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
196 // Idempotent no-op as per AutoCloseable recommendation
200 for (TransactionContextWrapper contextWrapper : txContextWrappers.values()) {
201 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
203 public void invoke(TransactionContext transactionContext) {
204 transactionContext.closeTransaction();
210 txContextWrappers.clear();
214 public final AbstractThreePhaseCommitCohort<?> ready() {
215 Preconditions.checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
217 final boolean success = seal(TransactionState.READY);
218 Preconditions.checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
220 LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextWrappers.size());
222 final AbstractThreePhaseCommitCohort<?> ret;
223 switch (txContextWrappers.size()) {
225 ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
228 final Entry<String, TransactionContextWrapper> e = Iterables.getOnlyElement(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(TransactionContext transactionContext) {
257 promise.completeWith(getDirectCommitFuture(transactionContext, operationCallbackRef));
260 future = promise.future();
262 // avoid the creation of a promise and a TransactionOperation
263 future = getDirectCommitFuture(transactionContext, operationCallbackRef);
266 return new SingleCommitCohortProxy(txContextFactory.getActorContext(), future, getIdentifier().toString(),
267 operationCallbackRef);
270 private Future<?> getDirectCommitFuture(TransactionContext transactionContext,
271 OperationCallback.Reference operationCallbackRef) {
272 TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
273 txContextFactory.getActorContext());
274 operationCallbackRef.set(rateLimitingCallback);
275 rateLimitingCallback.run();
276 return transactionContext.directCommit();
279 private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort(
280 final Set<Entry<String, TransactionContextWrapper>> txContextWrapperEntries) {
282 final List<ThreePhaseCommitCohortProxy.CohortInfo> cohorts = new ArrayList<>(txContextWrapperEntries.size());
283 for (Entry<String, TransactionContextWrapper> e : txContextWrapperEntries) {
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 = new Supplier<Short>() {
294 return wrapper.getTransactionContext().getTransactionVersion();
298 cohorts.add(new ThreePhaseCommitCohortProxy.CohortInfo(wrapper.readyTransaction(), txVersionSupplier));
301 return new ThreePhaseCommitCohortProxy(txContextFactory.getActorContext(), cohorts,
302 getIdentifier().toString());
305 private String shardNameFromIdentifier(final YangInstanceIdentifier path) {
306 return txContextFactory.getActorContext().getShardStrategyFactory().getStrategy(path).findShard(path);
309 private TransactionContextWrapper getContextWrapper(final YangInstanceIdentifier path) {
310 return getContextWrapper(shardNameFromIdentifier(path));
313 private TransactionContextWrapper getContextWrapper(final String shardName) {
314 final TransactionContextWrapper existing = txContextWrappers.get(shardName);
315 if (existing != null) {
319 final TransactionContextWrapper fresh = txContextFactory.newTransactionContextWrapper(this, shardName);
320 txContextWrappers.put(shardName, fresh);
324 TransactionType getType() {
329 return state != TransactionState.OPEN;
332 ActorContext getActorContext() {
333 return txContextFactory.getActorContext();