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> txContextAdapters = new HashMap<>();
55 private final AbstractTransactionContextFactory<?> txContextFactory;
56 private final OperationLimiter limiter;
57 private final TransactionType type;
58 private TransactionState state = TransactionState.OPEN;
61 public TransactionProxy(final AbstractTransactionContextFactory<?> txContextFactory, final TransactionType type) {
62 super(txContextFactory.nextIdentifier(), txContextFactory.getActorContext().getDatastoreContext()
63 .isTransactionDebugContextEnabled());
64 this.txContextFactory = txContextFactory;
65 this.type = Preconditions.checkNotNull(type);
67 // Note : Currently mailbox-capacity comes from akka.conf and not from the config-subsystem
68 this.limiter = new OperationLimiter(getIdentifier(),
69 getActorContext().getTransactionOutstandingOperationLimit(),
70 getActorContext().getDatastoreContext().getOperationTimeoutInSeconds());
72 LOG.debug("New {} Tx - {}", type, getIdentifier());
76 public CheckedFuture<Boolean, ReadFailedException> exists(final YangInstanceIdentifier path) {
77 Preconditions.checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
79 LOG.debug("Tx {} exists {}", getIdentifier(), path);
81 final SettableFuture<Boolean> proxyFuture = SettableFuture.create();
82 TransactionContextWrapper contextAdapter = getContextAdapter(path);
83 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
85 public void invoke(TransactionContext transactionContext) {
86 transactionContext.dataExists(path, proxyFuture);
90 return MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
94 public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final YangInstanceIdentifier path) {
95 Preconditions.checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
97 LOG.debug("Tx {} read {}", getIdentifier(), path);
99 if (YangInstanceIdentifier.EMPTY.equals(path)) {
100 return readAllData();
102 return singleShardRead(shardNameFromIdentifier(path), path);
106 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> singleShardRead(
107 final String shardName, final YangInstanceIdentifier path) {
108 final SettableFuture<Optional<NormalizedNode<?, ?>>> proxyFuture = SettableFuture.create();
109 TransactionContextWrapper contextAdapter = getContextAdapter(shardName);
110 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
112 public void invoke(TransactionContext transactionContext) {
113 transactionContext.readData(path, proxyFuture);
117 return MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
120 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readAllData() {
121 final Set<String> allShardNames = txContextFactory.getActorContext().getConfiguration().getAllShardNames();
122 final Collection<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>> futures = new ArrayList<>(allShardNames.size());
124 for (String shardName : allShardNames) {
125 futures.add(singleShardRead(shardName, YangInstanceIdentifier.EMPTY));
128 final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
129 final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;
131 aggregateFuture = Futures.transform(listFuture, new Function<List<Optional<NormalizedNode<?, ?>>>, Optional<NormalizedNode<?, ?>>>() {
133 public Optional<NormalizedNode<?, ?>> apply(final List<Optional<NormalizedNode<?, ?>>> input) {
135 return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input, txContextFactory.getActorContext().getSchemaContext());
136 } catch (DataValidationFailedException e) {
137 throw new IllegalArgumentException("Failed to aggregate", e);
142 return MappingCheckedFuture.create(aggregateFuture, ReadFailedException.MAPPER);
146 public void delete(final YangInstanceIdentifier path) {
147 checkModificationState();
149 LOG.debug("Tx {} delete {}", getIdentifier(), path);
151 TransactionContextWrapper contextAdapter = getContextAdapter(path);
152 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
154 public void invoke(TransactionContext transactionContext) {
155 transactionContext.deleteData(path);
161 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
162 checkModificationState();
164 LOG.debug("Tx {} merge {}", getIdentifier(), path);
166 TransactionContextWrapper contextAdapter = getContextAdapter(path);
167 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
169 public void invoke(TransactionContext transactionContext) {
170 transactionContext.mergeData(path, data);
176 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
177 checkModificationState();
179 LOG.debug("Tx {} write {}", getIdentifier(), path);
181 TransactionContextWrapper contextAdapter = getContextAdapter(path);
182 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
184 public void invoke(TransactionContext transactionContext) {
185 transactionContext.writeData(path, data);
190 private void checkModificationState() {
191 Preconditions.checkState(type != TransactionType.READ_ONLY,
192 "Modification operation on read-only transaction is not allowed");
193 Preconditions.checkState(state == TransactionState.OPEN,
194 "Transaction is sealed - further modifications are not allowed");
197 private boolean seal(final TransactionState newState) {
198 if (state == TransactionState.OPEN) {
207 public final void close() {
208 if (!seal(TransactionState.CLOSED)) {
209 Preconditions.checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
211 // Idempotent no-op as per AutoCloseable recommendation
215 for (TransactionContextWrapper contextAdapter : txContextAdapters.values()) {
216 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
218 public void invoke(TransactionContext transactionContext) {
219 transactionContext.closeTransaction();
225 txContextAdapters.clear();
229 public final AbstractThreePhaseCommitCohort<?> ready() {
230 Preconditions.checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
232 final boolean success = seal(TransactionState.READY);
233 Preconditions.checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
235 LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextAdapters.size());
237 final AbstractThreePhaseCommitCohort<?> ret;
238 switch (txContextAdapters.size()) {
240 ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
243 final Entry<String, TransactionContextWrapper> e = Iterables.getOnlyElement(txContextAdapters.entrySet());
244 ret = createSingleCommitCohort(e.getKey(), e.getValue());
247 ret = createMultiCommitCohort(txContextAdapters.entrySet());
250 txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
252 final Throwable debugContext = getDebugContext();
253 return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
256 private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
257 final TransactionContextWrapper contextAdapter) {
259 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
261 final OperationCallback.Reference operationCallbackRef =
262 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
264 final TransactionContext transactionContext = contextAdapter.getTransactionContext();
266 if (transactionContext == null) {
267 final Promise promise = akka.dispatch.Futures.promise();
268 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
270 public void invoke(TransactionContext transactionContext) {
271 promise.completeWith(getReadyOrDirectCommitFuture(transactionContext, operationCallbackRef));
274 future = promise.future();
276 // avoid the creation of a promise and a TransactionOperation
277 future = getReadyOrDirectCommitFuture(transactionContext, operationCallbackRef);
280 return new SingleCommitCohortProxy(txContextFactory.getActorContext(), future, getIdentifier().toString(),
281 operationCallbackRef);
284 private Future<?> getReadyOrDirectCommitFuture(TransactionContext transactionContext,
285 OperationCallback.Reference operationCallbackRef) {
286 if (transactionContext.supportsDirectCommit()) {
287 TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
288 txContextFactory.getActorContext());
289 operationCallbackRef.set(rateLimitingCallback);
290 rateLimitingCallback.run();
291 return transactionContext.directCommit();
293 return transactionContext.readyTransaction();
297 private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort(
298 final Set<Entry<String, TransactionContextWrapper>> txContextAdapterEntries) {
300 final List<Future<ActorSelection>> cohortFutures = new ArrayList<>(txContextAdapterEntries.size());
301 for (Entry<String, TransactionContextWrapper> e : txContextAdapterEntries) {
302 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
304 cohortFutures.add(e.getValue().readyTransaction());
307 return new ThreePhaseCommitCohortProxy(txContextFactory.getActorContext(), cohortFutures, getIdentifier().toString());
310 private static String shardNameFromIdentifier(final YangInstanceIdentifier path) {
311 return ShardStrategyFactory.getStrategy(path).findShard(path);
314 private TransactionContextWrapper getContextAdapter(final YangInstanceIdentifier path) {
315 return getContextAdapter(shardNameFromIdentifier(path));
318 private TransactionContextWrapper getContextAdapter(final String shardName) {
319 final TransactionContextWrapper existing = txContextAdapters.get(shardName);
320 if (existing != null) {
324 final TransactionContextWrapper fresh = txContextFactory.newTransactionAdapter(this, shardName);
325 txContextAdapters.put(shardName, fresh);
329 TransactionType getType() {
334 return state != TransactionState.OPEN;
337 ActorContext getActorContext() {
338 return txContextFactory.getActorContext();
341 OperationLimiter getLimiter() {