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);
83 final SettableFuture<Boolean> proxyFuture = SettableFuture.create();
84 TransactionContextWrapper contextAdapter = getContextAdapter(path);
85 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
87 public void invoke(TransactionContext transactionContext) {
88 transactionContext.dataExists(path, proxyFuture);
92 return MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
96 public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final YangInstanceIdentifier path) {
97 Preconditions.checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
99 LOG.debug("Tx {} read {}", getIdentifier(), path);
101 if (YangInstanceIdentifier.EMPTY.equals(path)) {
102 return readAllData();
106 return singleShardRead(shardNameFromIdentifier(path), path);
110 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> singleShardRead(
111 final String shardName, final YangInstanceIdentifier path) {
112 final SettableFuture<Optional<NormalizedNode<?, ?>>> proxyFuture = SettableFuture.create();
113 TransactionContextWrapper contextAdapter = getContextAdapter(shardName);
114 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
116 public void invoke(TransactionContext transactionContext) {
117 transactionContext.readData(path, proxyFuture);
121 return MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
124 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readAllData() {
125 final Set<String> allShardNames = txContextFactory.getActorContext().getConfiguration().getAllShardNames();
126 final Collection<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>> futures = new ArrayList<>(allShardNames.size());
128 for (String shardName : allShardNames) {
129 futures.add(singleShardRead(shardName, YangInstanceIdentifier.EMPTY));
132 final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
133 final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;
135 aggregateFuture = Futures.transform(listFuture, new Function<List<Optional<NormalizedNode<?, ?>>>, Optional<NormalizedNode<?, ?>>>() {
137 public Optional<NormalizedNode<?, ?>> apply(final List<Optional<NormalizedNode<?, ?>>> input) {
139 return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input, txContextFactory.getActorContext().getSchemaContext());
140 } catch (DataValidationFailedException e) {
141 throw new IllegalArgumentException("Failed to aggregate", e);
146 return MappingCheckedFuture.create(aggregateFuture, ReadFailedException.MAPPER);
150 public void delete(final YangInstanceIdentifier path) {
151 checkModificationState();
153 LOG.debug("Tx {} delete {}", getIdentifier(), path);
157 TransactionContextWrapper contextAdapter = getContextAdapter(path);
158 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
160 public void invoke(TransactionContext transactionContext) {
161 transactionContext.deleteData(path);
167 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
168 checkModificationState();
170 LOG.debug("Tx {} merge {}", getIdentifier(), path);
174 TransactionContextWrapper contextAdapter = getContextAdapter(path);
175 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
177 public void invoke(TransactionContext transactionContext) {
178 transactionContext.mergeData(path, data);
184 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
185 checkModificationState();
187 LOG.debug("Tx {} write {}", getIdentifier(), path);
191 TransactionContextWrapper contextAdapter = getContextAdapter(path);
192 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
194 public void invoke(TransactionContext transactionContext) {
195 transactionContext.writeData(path, data);
200 private void checkModificationState() {
201 Preconditions.checkState(type != TransactionType.READ_ONLY,
202 "Modification operation on read-only transaction is not allowed");
203 Preconditions.checkState(state == TransactionState.OPEN,
204 "Transaction is sealed - further modifications are not allowed");
207 private boolean seal(final TransactionState newState) {
208 if (state == TransactionState.OPEN) {
217 public final void close() {
218 if (!seal(TransactionState.CLOSED)) {
219 Preconditions.checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
221 // Idempotent no-op as per AutoCloseable recommendation
225 for (TransactionContextWrapper contextAdapter : txContextAdapters.values()) {
226 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
228 public void invoke(TransactionContext transactionContext) {
229 transactionContext.closeTransaction();
235 txContextAdapters.clear();
239 public final AbstractThreePhaseCommitCohort<?> ready() {
240 Preconditions.checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
242 final boolean success = seal(TransactionState.READY);
243 Preconditions.checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
245 LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextAdapters.size());
247 final AbstractThreePhaseCommitCohort<?> ret;
248 switch (txContextAdapters.size()) {
250 ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
253 final Entry<String, TransactionContextWrapper> e = Iterables.getOnlyElement(txContextAdapters.entrySet());
254 ret = createSingleCommitCohort(e.getKey(), e.getValue());
257 ret = createMultiCommitCohort(txContextAdapters.entrySet());
260 txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
262 final Throwable debugContext = getDebugContext();
263 return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
266 private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
267 final TransactionContextWrapper contextAdapter) {
270 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
272 final OperationCallback.Reference operationCallbackRef =
273 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
275 final TransactionContext transactionContext = contextAdapter.getTransactionContext();
277 if (transactionContext == null) {
278 final Promise promise = akka.dispatch.Futures.promise();
279 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
281 public void invoke(TransactionContext transactionContext) {
282 promise.completeWith(getReadyOrDirectCommitFuture(transactionContext, operationCallbackRef));
285 future = promise.future();
287 // avoid the creation of a promise and a TransactionOperation
288 future = getReadyOrDirectCommitFuture(transactionContext, operationCallbackRef);
291 return new SingleCommitCohortProxy(txContextFactory.getActorContext(), future, getIdentifier().toString(),
292 operationCallbackRef);
295 private Future<?> getReadyOrDirectCommitFuture(TransactionContext transactionContext,
296 OperationCallback.Reference operationCallbackRef) {
297 if (transactionContext.supportsDirectCommit()) {
298 TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
299 txContextFactory.getActorContext());
300 operationCallbackRef.set(rateLimitingCallback);
301 rateLimitingCallback.run();
302 return transactionContext.directCommit();
304 return transactionContext.readyTransaction();
308 private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort(
309 final Set<Entry<String, TransactionContextWrapper>> txContextAdapterEntries) {
312 final List<Future<ActorSelection>> cohortFutures = new ArrayList<>(txContextAdapterEntries.size());
313 for (Entry<String, TransactionContextWrapper> e : txContextAdapterEntries) {
314 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
316 TransactionContextWrapper contextAdapter = e.getValue();
317 final TransactionContext transactionContext = contextAdapter.getTransactionContext();
318 Future<ActorSelection> future;
319 if (transactionContext != null) {
320 // avoid the creation of a promise and a TransactionOperation
321 future = transactionContext.readyTransaction();
323 final Promise<ActorSelection> promise = akka.dispatch.Futures.promise();
324 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
326 public void invoke(TransactionContext transactionContext) {
327 promise.completeWith(transactionContext.readyTransaction());
331 future = promise.future();
334 cohortFutures.add(future);
337 return new ThreePhaseCommitCohortProxy(txContextFactory.getActorContext(), cohortFutures, getIdentifier().toString());
340 private static String shardNameFromIdentifier(final YangInstanceIdentifier path) {
341 return ShardStrategyFactory.getStrategy(path).findShard(path);
344 private TransactionContextWrapper getContextAdapter(final YangInstanceIdentifier path) {
345 return getContextAdapter(shardNameFromIdentifier(path));
348 private TransactionContextWrapper getContextAdapter(final String shardName) {
349 final TransactionContextWrapper existing = txContextAdapters.get(shardName);
350 if (existing != null) {
354 final TransactionContextWrapper fresh = txContextFactory.newTransactionAdapter(this, shardName);
355 txContextAdapters.put(shardName, fresh);
359 TransactionType getType() {
364 return state != TransactionState.OPEN;
367 ActorContext getActorContext() {
368 return txContextFactory.getActorContext();
371 OperationLimiter getLimiter() {