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.collect.Iterables;
16 import com.google.common.util.concurrent.CheckedFuture;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.SettableFuture;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.HashMap;
23 import java.util.List;
25 import java.util.Map.Entry;
27 import org.opendaylight.controller.cluster.datastore.identifiers.TransactionIdentifier;
28 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
29 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
30 import org.opendaylight.controller.cluster.datastore.utils.NormalizedNodeAggregator;
31 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
32 import org.opendaylight.controller.sal.core.spi.data.AbstractDOMStoreTransaction;
33 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
34 import org.opendaylight.yangtools.util.concurrent.MappingCheckedFuture;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import scala.concurrent.Future;
41 import scala.concurrent.Promise;
44 * A transaction potentially spanning multiple backend shards.
46 public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIdentifier> implements DOMStoreReadWriteTransaction {
47 private static enum TransactionState {
52 private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
54 private final Map<String, TransactionContextWrapper> txContextWrappers = new HashMap<>();
55 private final AbstractTransactionContextFactory<?> txContextFactory;
56 private final TransactionType type;
57 private TransactionState state = TransactionState.OPEN;
60 public TransactionProxy(final AbstractTransactionContextFactory<?> txContextFactory, final TransactionType type) {
61 super(txContextFactory.nextIdentifier(), txContextFactory.getActorContext().getDatastoreContext()
62 .isTransactionDebugContextEnabled());
63 this.txContextFactory = txContextFactory;
64 this.type = Preconditions.checkNotNull(type);
66 LOG.debug("New {} Tx - {}", type, getIdentifier());
70 public CheckedFuture<Boolean, ReadFailedException> exists(final YangInstanceIdentifier path) {
71 Preconditions.checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
73 LOG.debug("Tx {} exists {}", getIdentifier(), path);
75 final SettableFuture<Boolean> proxyFuture = SettableFuture.create();
76 TransactionContextWrapper contextWrapper = getContextWrapper(path);
77 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
79 public void invoke(TransactionContext transactionContext) {
80 transactionContext.dataExists(path, proxyFuture);
84 return MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
88 public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final YangInstanceIdentifier path) {
89 Preconditions.checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
91 LOG.debug("Tx {} read {}", getIdentifier(), path);
93 if (YangInstanceIdentifier.EMPTY.equals(path)) {
96 return singleShardRead(shardNameFromIdentifier(path), path);
100 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> singleShardRead(
101 final String shardName, final YangInstanceIdentifier path) {
102 final SettableFuture<Optional<NormalizedNode<?, ?>>> proxyFuture = SettableFuture.create();
103 TransactionContextWrapper contextWrapper = getContextWrapper(shardName);
104 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
106 public void invoke(TransactionContext transactionContext) {
107 transactionContext.readData(path, proxyFuture);
111 return MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
114 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readAllData() {
115 final Set<String> allShardNames = txContextFactory.getActorContext().getConfiguration().getAllShardNames();
116 final Collection<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>> futures = new ArrayList<>(allShardNames.size());
118 for (String shardName : allShardNames) {
119 futures.add(singleShardRead(shardName, YangInstanceIdentifier.EMPTY));
122 final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
123 final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;
125 aggregateFuture = Futures.transform(listFuture, new Function<List<Optional<NormalizedNode<?, ?>>>, Optional<NormalizedNode<?, ?>>>() {
127 public Optional<NormalizedNode<?, ?>> apply(final List<Optional<NormalizedNode<?, ?>>> input) {
129 return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input, txContextFactory.getActorContext().getSchemaContext());
130 } catch (DataValidationFailedException e) {
131 throw new IllegalArgumentException("Failed to aggregate", e);
136 return MappingCheckedFuture.create(aggregateFuture, ReadFailedException.MAPPER);
140 public void delete(final YangInstanceIdentifier path) {
141 checkModificationState();
143 LOG.debug("Tx {} delete {}", getIdentifier(), path);
145 TransactionContextWrapper contextWrapper = getContextWrapper(path);
146 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
148 public void invoke(TransactionContext transactionContext) {
149 transactionContext.deleteData(path);
155 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
156 checkModificationState();
158 LOG.debug("Tx {} merge {}", getIdentifier(), path);
160 TransactionContextWrapper contextWrapper = getContextWrapper(path);
161 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
163 public void invoke(TransactionContext transactionContext) {
164 transactionContext.mergeData(path, data);
170 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
171 checkModificationState();
173 LOG.debug("Tx {} write {}", getIdentifier(), path);
175 TransactionContextWrapper contextWrapper = getContextWrapper(path);
176 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
178 public void invoke(TransactionContext transactionContext) {
179 transactionContext.writeData(path, data);
184 private void checkModificationState() {
185 Preconditions.checkState(type != TransactionType.READ_ONLY,
186 "Modification operation on read-only transaction is not allowed");
187 Preconditions.checkState(state == TransactionState.OPEN,
188 "Transaction is sealed - further modifications are not allowed");
191 private boolean seal(final TransactionState newState) {
192 if (state == TransactionState.OPEN) {
201 public final void close() {
202 if (!seal(TransactionState.CLOSED)) {
203 Preconditions.checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
205 // Idempotent no-op as per AutoCloseable recommendation
209 for (TransactionContextWrapper contextWrapper : txContextWrappers.values()) {
210 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
212 public void invoke(TransactionContext transactionContext) {
213 transactionContext.closeTransaction();
219 txContextWrappers.clear();
223 public final AbstractThreePhaseCommitCohort<?> ready() {
224 Preconditions.checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
226 final boolean success = seal(TransactionState.READY);
227 Preconditions.checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
229 LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextWrappers.size());
231 final AbstractThreePhaseCommitCohort<?> ret;
232 switch (txContextWrappers.size()) {
234 ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
237 final Entry<String, TransactionContextWrapper> e = Iterables.getOnlyElement(txContextWrappers.entrySet());
238 ret = createSingleCommitCohort(e.getKey(), e.getValue());
241 ret = createMultiCommitCohort(txContextWrappers.entrySet());
244 txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
246 final Throwable debugContext = getDebugContext();
247 return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
250 private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
251 final TransactionContextWrapper contextWrapper) {
253 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
255 final OperationCallback.Reference operationCallbackRef =
256 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
258 final TransactionContext transactionContext = contextWrapper.getTransactionContext();
260 if (transactionContext == null) {
261 final Promise promise = akka.dispatch.Futures.promise();
262 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
264 public void invoke(TransactionContext transactionContext) {
265 promise.completeWith(getReadyOrDirectCommitFuture(transactionContext, operationCallbackRef));
268 future = promise.future();
270 // avoid the creation of a promise and a TransactionOperation
271 future = getReadyOrDirectCommitFuture(transactionContext, operationCallbackRef);
274 return new SingleCommitCohortProxy(txContextFactory.getActorContext(), future, getIdentifier().toString(),
275 operationCallbackRef);
278 private Future<?> getReadyOrDirectCommitFuture(TransactionContext transactionContext,
279 OperationCallback.Reference operationCallbackRef) {
280 if (transactionContext.supportsDirectCommit()) {
281 TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
282 txContextFactory.getActorContext());
283 operationCallbackRef.set(rateLimitingCallback);
284 rateLimitingCallback.run();
285 return transactionContext.directCommit();
287 return transactionContext.readyTransaction();
291 private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort(
292 final Set<Entry<String, TransactionContextWrapper>> txContextWrapperEntries) {
294 final List<Future<ActorSelection>> cohortFutures = new ArrayList<>(txContextWrapperEntries.size());
295 for (Entry<String, TransactionContextWrapper> e : txContextWrapperEntries) {
296 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
298 cohortFutures.add(e.getValue().readyTransaction());
301 return new ThreePhaseCommitCohortProxy(txContextFactory.getActorContext(), cohortFutures, getIdentifier().toString());
304 private static String shardNameFromIdentifier(final YangInstanceIdentifier path) {
305 return ShardStrategyFactory.getStrategy(path).findShard(path);
308 private TransactionContextWrapper getContextWrapper(final YangInstanceIdentifier path) {
309 return getContextWrapper(shardNameFromIdentifier(path));
312 private TransactionContextWrapper getContextWrapper(final String shardName) {
313 final TransactionContextWrapper existing = txContextWrappers.get(shardName);
314 if (existing != null) {
318 final TransactionContextWrapper fresh = txContextFactory.newTransactionContextWrapper(this, shardName);
319 txContextWrappers.put(shardName, fresh);
323 TransactionType getType() {
328 return state != TransactionState.OPEN;
331 ActorContext getActorContext() {
332 return txContextFactory.getActorContext();