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.access.concepts.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.cluster.datastore.utils.TransactionIdentifierUtils;
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> implements DOMStoreReadWriteTransaction {
55 private static enum TransactionState {
60 private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
62 private final Map<String, TransactionContextWrapper> txContextWrappers = new HashMap<>();
63 private final AbstractTransactionContextFactory<?> txContextFactory;
64 private final TransactionType type;
65 private TransactionState state = TransactionState.OPEN;
68 public TransactionProxy(final AbstractTransactionContextFactory<?> txContextFactory, final TransactionType type) {
69 super(txContextFactory.nextIdentifier(), txContextFactory.getActorContext().getDatastoreContext()
70 .isTransactionDebugContextEnabled());
71 this.txContextFactory = txContextFactory;
72 this.type = Preconditions.checkNotNull(type);
74 LOG.debug("New {} Tx - {}", type, getIdentifier());
78 public CheckedFuture<Boolean, ReadFailedException> exists(final YangInstanceIdentifier path) {
79 return executeRead(shardNameFromIdentifier(path), new DataExists(path, DataStoreVersions.CURRENT_VERSION));
82 private <T> CheckedFuture<T, ReadFailedException> executeRead(String shardName, final AbstractRead<T> readCmd) {
83 Preconditions.checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
85 if(LOG.isDebugEnabled()) {
86 LOG.debug("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(TransactionContext transactionContext) {
94 transactionContext.executeRead(readCmd, proxyFuture);
98 return MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
102 public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final YangInstanceIdentifier path) {
103 Preconditions.checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
105 LOG.debug("Tx {} read {}", getIdentifier(), path);
107 if (YangInstanceIdentifier.EMPTY.equals(path)) {
108 return readAllData();
110 return singleShardRead(shardNameFromIdentifier(path), path);
114 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> singleShardRead(
115 final String shardName, final YangInstanceIdentifier path) {
116 return executeRead(shardName, new ReadData(path, DataStoreVersions.CURRENT_VERSION));
119 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readAllData() {
120 final Set<String> allShardNames = txContextFactory.getActorContext().getConfiguration().getAllShardNames();
121 final Collection<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>> futures = 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, new Function<List<Optional<NormalizedNode<?, ?>>>, Optional<NormalizedNode<?, ?>>>() {
132 public Optional<NormalizedNode<?, ?>> apply(final List<Optional<NormalizedNode<?, ?>>> input) {
134 return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input, txContextFactory.getActorContext().getSchemaContext());
135 } catch (DataValidationFailedException e) {
136 throw new IllegalArgumentException("Failed to aggregate", e);
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 if(LOG.isDebugEnabled()) {
163 LOG.debug("Tx {} executeModification {} {}", getIdentifier(), modification.getClass().getSimpleName(),
164 modification.getPath());
167 TransactionContextWrapper contextWrapper = getContextWrapper(modification.getPath());
168 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
170 protected void invoke(TransactionContext transactionContext) {
171 transactionContext.executeModification(modification);
176 private void checkModificationState() {
177 Preconditions.checkState(type != TransactionType.READ_ONLY,
178 "Modification operation on read-only transaction is not allowed");
179 Preconditions.checkState(state == TransactionState.OPEN,
180 "Transaction is sealed - further modifications are not allowed");
183 private boolean seal(final TransactionState newState) {
184 if (state == TransactionState.OPEN) {
193 public final void close() {
194 if (!seal(TransactionState.CLOSED)) {
195 Preconditions.checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
197 // Idempotent no-op as per AutoCloseable recommendation
201 for (TransactionContextWrapper contextWrapper : txContextWrappers.values()) {
202 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
204 public void invoke(TransactionContext transactionContext) {
205 transactionContext.closeTransaction();
211 txContextWrappers.clear();
215 public final AbstractThreePhaseCommitCohort<?> ready() {
216 Preconditions.checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
218 final boolean success = seal(TransactionState.READY);
219 Preconditions.checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
221 LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextWrappers.size());
223 final AbstractThreePhaseCommitCohort<?> ret;
224 switch (txContextWrappers.size()) {
226 ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
229 final Entry<String, TransactionContextWrapper> e = Iterables.getOnlyElement(txContextWrappers.entrySet());
230 ret = createSingleCommitCohort(e.getKey(), e.getValue());
233 ret = createMultiCommitCohort(txContextWrappers.entrySet());
236 txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
238 final Throwable debugContext = getDebugContext();
239 return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
242 @SuppressWarnings({ "rawtypes", "unchecked" })
243 private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
244 final TransactionContextWrapper contextWrapper) {
246 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
248 final OperationCallback.Reference operationCallbackRef =
249 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
251 final TransactionContext transactionContext = contextWrapper.getTransactionContext();
253 if (transactionContext == null) {
254 final Promise promise = akka.dispatch.Futures.promise();
255 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
257 public void invoke(TransactionContext transactionContext) {
258 promise.completeWith(getDirectCommitFuture(transactionContext, operationCallbackRef));
261 future = promise.future();
263 // avoid the creation of a promise and a TransactionOperation
264 future = getDirectCommitFuture(transactionContext, operationCallbackRef);
267 return new SingleCommitCohortProxy(txContextFactory.getActorContext(), future, getIdentifier(),
268 operationCallbackRef);
271 private Future<?> getDirectCommitFuture(TransactionContext transactionContext,
272 OperationCallback.Reference operationCallbackRef) {
273 TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
274 txContextFactory.getActorContext());
275 operationCallbackRef.set(rateLimitingCallback);
276 rateLimitingCallback.run();
277 return transactionContext.directCommit();
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 = new Supplier<Short>() {
295 return wrapper.getTransactionContext().getTransactionVersion();
299 cohorts.add(new ThreePhaseCommitCohortProxy.CohortInfo(wrapper.readyTransaction(), txVersionSupplier));
302 return new ThreePhaseCommitCohortProxy(txContextFactory.getActorContext(), cohorts,
303 TransactionIdentifierUtils.actorNameFor(getIdentifier()));
306 private String shardNameFromIdentifier(final YangInstanceIdentifier path) {
307 return txContextFactory.getActorContext().getShardStrategyFactory().getStrategy(path).findShard(path);
310 private TransactionContextWrapper getContextWrapper(final YangInstanceIdentifier path) {
311 return getContextWrapper(shardNameFromIdentifier(path));
314 private TransactionContextWrapper getContextWrapper(final String shardName) {
315 final TransactionContextWrapper existing = txContextWrappers.get(shardName);
316 if (existing != null) {
320 final TransactionContextWrapper fresh = txContextFactory.newTransactionContextWrapper(this, shardName);
321 txContextWrappers.put(shardName, fresh);
325 TransactionType getType() {
330 return state != TransactionState.OPEN;
333 ActorContext getActorContext() {
334 return txContextFactory.getActorContext();