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 java.util.concurrent.Semaphore;
28 import java.util.concurrent.TimeUnit;
29 import org.opendaylight.controller.cluster.datastore.identifiers.TransactionIdentifier;
30 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
31 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
32 import org.opendaylight.controller.cluster.datastore.utils.NormalizedNodeAggregator;
33 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
34 import org.opendaylight.controller.sal.core.spi.data.AbstractDOMStoreTransaction;
35 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
36 import org.opendaylight.yangtools.util.concurrent.MappingCheckedFuture;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import scala.concurrent.Future;
43 import scala.concurrent.Promise;
46 * A transaction potentially spanning multiple backend shards.
48 public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIdentifier> implements DOMStoreReadWriteTransaction {
49 private static enum TransactionState {
54 private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
56 private final Map<String, TransactionContextWrapper> txContextAdapters = new HashMap<>();
57 private final AbstractTransactionContextFactory<?> txContextFactory;
58 private final TransactionType type;
59 private TransactionState state = TransactionState.OPEN;
60 private volatile OperationCompleter operationCompleter;
61 private volatile Semaphore operationLimiter;
64 public TransactionProxy(final AbstractTransactionContextFactory<?> txContextFactory, final TransactionType type) {
65 super(txContextFactory.nextIdentifier(), txContextFactory.getActorContext().getDatastoreContext()
66 .isTransactionDebugContextEnabled());
67 this.txContextFactory = txContextFactory;
68 this.type = Preconditions.checkNotNull(type);
70 LOG.debug("New {} Tx - {}", type, getIdentifier());
74 public CheckedFuture<Boolean, ReadFailedException> exists(final YangInstanceIdentifier path) {
75 Preconditions.checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
77 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();
104 return singleShardRead(shardNameFromIdentifier(path), path);
108 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> singleShardRead(
109 final String shardName, final YangInstanceIdentifier path) {
110 final SettableFuture<Optional<NormalizedNode<?, ?>>> proxyFuture = SettableFuture.create();
111 TransactionContextWrapper contextAdapter = getContextAdapter(shardName);
112 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
114 public void invoke(TransactionContext transactionContext) {
115 transactionContext.readData(path, proxyFuture);
119 return MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
122 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readAllData() {
123 final Set<String> allShardNames = txContextFactory.getActorContext().getConfiguration().getAllShardNames();
124 final Collection<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>> futures = new ArrayList<>(allShardNames.size());
126 for (String shardName : allShardNames) {
127 futures.add(singleShardRead(shardName, YangInstanceIdentifier.EMPTY));
130 final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
131 final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;
133 aggregateFuture = Futures.transform(listFuture, new Function<List<Optional<NormalizedNode<?, ?>>>, Optional<NormalizedNode<?, ?>>>() {
135 public Optional<NormalizedNode<?, ?>> apply(final List<Optional<NormalizedNode<?, ?>>> input) {
137 return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input, txContextFactory.getActorContext().getSchemaContext());
138 } catch (DataValidationFailedException e) {
139 throw new IllegalArgumentException("Failed to aggregate", e);
144 return MappingCheckedFuture.create(aggregateFuture, ReadFailedException.MAPPER);
148 public void delete(final YangInstanceIdentifier path) {
149 checkModificationState();
151 LOG.debug("Tx {} delete {}", getIdentifier(), path);
155 TransactionContextWrapper contextAdapter = getContextAdapter(path);
156 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
158 public void invoke(TransactionContext transactionContext) {
159 transactionContext.deleteData(path);
165 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
166 checkModificationState();
168 LOG.debug("Tx {} merge {}", getIdentifier(), path);
172 TransactionContextWrapper contextAdapter = getContextAdapter(path);
173 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
175 public void invoke(TransactionContext transactionContext) {
176 transactionContext.mergeData(path, data);
182 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
183 checkModificationState();
185 LOG.debug("Tx {} write {}", getIdentifier(), path);
189 TransactionContextWrapper contextAdapter = getContextAdapter(path);
190 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
192 public void invoke(TransactionContext transactionContext) {
193 transactionContext.writeData(path, data);
198 private void checkModificationState() {
199 Preconditions.checkState(type != TransactionType.READ_ONLY,
200 "Modification operation on read-only transaction is not allowed");
201 Preconditions.checkState(state == TransactionState.OPEN,
202 "Transaction is sealed - further modifications are not allowed");
205 private boolean seal(final TransactionState newState) {
206 if (state == TransactionState.OPEN) {
215 public final void close() {
216 if (!seal(TransactionState.CLOSED)) {
217 Preconditions.checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
219 // Idempotent no-op as per AutoCloseable recommendation
223 for (TransactionContextWrapper contextAdapter : txContextAdapters.values()) {
224 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
226 public void invoke(TransactionContext transactionContext) {
227 transactionContext.closeTransaction();
233 txContextAdapters.clear();
237 public final AbstractThreePhaseCommitCohort<?> ready() {
238 Preconditions.checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
240 final boolean success = seal(TransactionState.READY);
241 Preconditions.checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
243 LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextAdapters.size());
245 final AbstractThreePhaseCommitCohort<?> ret;
246 switch (txContextAdapters.size()) {
248 ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
251 final Entry<String, TransactionContextWrapper> e = Iterables.getOnlyElement(txContextAdapters.entrySet());
252 ret = createSingleCommitCohort(e.getKey(), e.getValue());
255 ret = createMultiCommitCohort(txContextAdapters.entrySet());
258 txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
260 final Throwable debugContext = getDebugContext();
261 return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
264 private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
265 final TransactionContextWrapper contextAdapter) {
268 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
270 final OperationCallback.Reference operationCallbackRef =
271 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
273 final TransactionContext transactionContext = contextAdapter.getTransactionContext();
275 if (transactionContext == null) {
276 final Promise promise = akka.dispatch.Futures.promise();
277 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
279 public void invoke(TransactionContext transactionContext) {
280 promise.completeWith(getReadyOrDirectCommitFuture(transactionContext, operationCallbackRef));
283 future = promise.future();
285 // avoid the creation of a promise and a TransactionOperation
286 future = getReadyOrDirectCommitFuture(transactionContext, operationCallbackRef);
289 return new SingleCommitCohortProxy(txContextFactory.getActorContext(), future, getIdentifier().toString(),
290 operationCallbackRef);
293 private Future<?> getReadyOrDirectCommitFuture(TransactionContext transactionContext,
294 OperationCallback.Reference operationCallbackRef) {
295 if (transactionContext.supportsDirectCommit()) {
296 TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
297 txContextFactory.getActorContext());
298 operationCallbackRef.set(rateLimitingCallback);
299 rateLimitingCallback.run();
300 return transactionContext.directCommit();
302 return transactionContext.readyTransaction();
306 private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort(
307 final Set<Entry<String, TransactionContextWrapper>> txContextAdapterEntries) {
310 final List<Future<ActorSelection>> cohortFutures = new ArrayList<>(txContextAdapterEntries.size());
311 for (Entry<String, TransactionContextWrapper> e : txContextAdapterEntries) {
312 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
314 TransactionContextWrapper contextAdapter = e.getValue();
315 final TransactionContext transactionContext = contextAdapter.getTransactionContext();
316 Future<ActorSelection> future;
317 if (transactionContext != null) {
318 // avoid the creation of a promise and a TransactionOperation
319 future = transactionContext.readyTransaction();
321 final Promise<ActorSelection> promise = akka.dispatch.Futures.promise();
322 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
324 public void invoke(TransactionContext transactionContext) {
325 promise.completeWith(transactionContext.readyTransaction());
329 future = promise.future();
332 cohortFutures.add(future);
335 return new ThreePhaseCommitCohortProxy(txContextFactory.getActorContext(), cohortFutures, getIdentifier().toString());
338 private static String shardNameFromIdentifier(final YangInstanceIdentifier path) {
339 return ShardStrategyFactory.getStrategy(path).findShard(path);
342 private TransactionContextWrapper getContextAdapter(final YangInstanceIdentifier path) {
343 return getContextAdapter(shardNameFromIdentifier(path));
346 private TransactionContextWrapper getContextAdapter(final String shardName) {
347 final TransactionContextWrapper existing = txContextAdapters.get(shardName);
348 if (existing != null) {
352 final TransactionContextWrapper fresh = txContextFactory.newTransactionAdapter(this, shardName);
353 txContextAdapters.put(shardName, fresh);
357 TransactionType getType() {
362 return state != TransactionState.OPEN;
365 ActorContext getActorContext() {
366 return txContextFactory.getActorContext();
369 OperationCompleter getCompleter() {
370 OperationCompleter ret = operationCompleter;
372 final Semaphore s = getLimiter();
373 ret = new OperationCompleter(s);
374 operationCompleter = ret;
380 Semaphore getLimiter() {
381 Semaphore ret = operationLimiter;
383 // Note : Currently mailbox-capacity comes from akka.conf and not from the config-subsystem
384 ret = new Semaphore(getActorContext().getTransactionOutstandingOperationLimit());
385 operationLimiter = ret;
390 void throttleOperation() {
391 throttleOperation(1);
394 private void throttleOperation(int acquirePermits) {
396 if (!getLimiter().tryAcquire(acquirePermits,
397 getActorContext().getDatastoreContext().getOperationTimeoutInSeconds(), TimeUnit.SECONDS)){
398 LOG.warn("Failed to acquire operation permit for transaction {}", getIdentifier());
400 } catch (InterruptedException e) {
401 if (LOG.isDebugEnabled()) {
402 LOG.debug("Interrupted when trying to acquire operation permit for transaction {}", getIdentifier(), e);
404 LOG.warn("Interrupted when trying to acquire operation permit for transaction {}", getIdentifier());