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.utils.ActorContext;
29 import org.opendaylight.controller.cluster.datastore.utils.NormalizedNodeAggregator;
30 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
31 import org.opendaylight.controller.sal.core.spi.data.AbstractDOMStoreTransaction;
32 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
33 import org.opendaylight.yangtools.util.concurrent.MappingCheckedFuture;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import scala.concurrent.Future;
40 import scala.concurrent.Promise;
43 * A transaction potentially spanning multiple backend shards.
45 public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIdentifier> implements DOMStoreReadWriteTransaction {
46 private static enum TransactionState {
51 private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
53 private final Map<String, TransactionContextWrapper> txContextWrappers = new HashMap<>();
54 private final AbstractTransactionContextFactory<?> txContextFactory;
55 private final TransactionType type;
56 private TransactionState state = TransactionState.OPEN;
59 public TransactionProxy(final AbstractTransactionContextFactory<?> txContextFactory, final TransactionType type) {
60 super(txContextFactory.nextIdentifier(), txContextFactory.getActorContext().getDatastoreContext()
61 .isTransactionDebugContextEnabled());
62 this.txContextFactory = txContextFactory;
63 this.type = Preconditions.checkNotNull(type);
65 LOG.debug("New {} Tx - {}", type, getIdentifier());
69 public CheckedFuture<Boolean, ReadFailedException> exists(final YangInstanceIdentifier path) {
70 Preconditions.checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
72 LOG.debug("Tx {} exists {}", getIdentifier(), path);
74 final SettableFuture<Boolean> proxyFuture = SettableFuture.create();
75 TransactionContextWrapper contextWrapper = getContextWrapper(path);
76 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
78 public void invoke(TransactionContext transactionContext) {
79 transactionContext.dataExists(path, proxyFuture);
83 return MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
87 public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final YangInstanceIdentifier path) {
88 Preconditions.checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
90 LOG.debug("Tx {} read {}", getIdentifier(), path);
92 if (YangInstanceIdentifier.EMPTY.equals(path)) {
95 return singleShardRead(shardNameFromIdentifier(path), path);
99 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> singleShardRead(
100 final String shardName, final YangInstanceIdentifier path) {
101 final SettableFuture<Optional<NormalizedNode<?, ?>>> proxyFuture = SettableFuture.create();
102 TransactionContextWrapper contextWrapper = getContextWrapper(shardName);
103 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
105 public void invoke(TransactionContext transactionContext) {
106 transactionContext.readData(path, proxyFuture);
110 return MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
113 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readAllData() {
114 final Set<String> allShardNames = txContextFactory.getActorContext().getConfiguration().getAllShardNames();
115 final Collection<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>> futures = new ArrayList<>(allShardNames.size());
117 for (String shardName : allShardNames) {
118 futures.add(singleShardRead(shardName, YangInstanceIdentifier.EMPTY));
121 final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
122 final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;
124 aggregateFuture = Futures.transform(listFuture, new Function<List<Optional<NormalizedNode<?, ?>>>, Optional<NormalizedNode<?, ?>>>() {
126 public Optional<NormalizedNode<?, ?>> apply(final List<Optional<NormalizedNode<?, ?>>> input) {
128 return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input, txContextFactory.getActorContext().getSchemaContext());
129 } catch (DataValidationFailedException e) {
130 throw new IllegalArgumentException("Failed to aggregate", e);
135 return MappingCheckedFuture.create(aggregateFuture, ReadFailedException.MAPPER);
139 public void delete(final YangInstanceIdentifier path) {
140 checkModificationState();
142 LOG.debug("Tx {} delete {}", getIdentifier(), path);
144 TransactionContextWrapper contextWrapper = getContextWrapper(path);
145 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
147 public void invoke(TransactionContext transactionContext) {
148 transactionContext.deleteData(path);
154 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
155 checkModificationState();
157 LOG.debug("Tx {} merge {}", getIdentifier(), path);
159 TransactionContextWrapper contextWrapper = getContextWrapper(path);
160 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
162 public void invoke(TransactionContext transactionContext) {
163 transactionContext.mergeData(path, data);
169 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
170 checkModificationState();
172 LOG.debug("Tx {} write {}", getIdentifier(), path);
174 TransactionContextWrapper contextWrapper = getContextWrapper(path);
175 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
177 public void invoke(TransactionContext transactionContext) {
178 transactionContext.writeData(path, data);
183 private void checkModificationState() {
184 Preconditions.checkState(type != TransactionType.READ_ONLY,
185 "Modification operation on read-only transaction is not allowed");
186 Preconditions.checkState(state == TransactionState.OPEN,
187 "Transaction is sealed - further modifications are not allowed");
190 private boolean seal(final TransactionState newState) {
191 if (state == TransactionState.OPEN) {
200 public final void close() {
201 if (!seal(TransactionState.CLOSED)) {
202 Preconditions.checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
204 // Idempotent no-op as per AutoCloseable recommendation
208 for (TransactionContextWrapper contextWrapper : txContextWrappers.values()) {
209 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
211 public void invoke(TransactionContext transactionContext) {
212 transactionContext.closeTransaction();
218 txContextWrappers.clear();
222 public final AbstractThreePhaseCommitCohort<?> ready() {
223 Preconditions.checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
225 final boolean success = seal(TransactionState.READY);
226 Preconditions.checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
228 LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextWrappers.size());
230 final AbstractThreePhaseCommitCohort<?> ret;
231 switch (txContextWrappers.size()) {
233 ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
236 final Entry<String, TransactionContextWrapper> e = Iterables.getOnlyElement(txContextWrappers.entrySet());
237 ret = createSingleCommitCohort(e.getKey(), e.getValue());
240 ret = createMultiCommitCohort(txContextWrappers.entrySet());
243 txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
245 final Throwable debugContext = getDebugContext();
246 return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
249 private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
250 final TransactionContextWrapper contextWrapper) {
252 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
254 final OperationCallback.Reference operationCallbackRef =
255 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
257 final TransactionContext transactionContext = contextWrapper.getTransactionContext();
259 if (transactionContext == null) {
260 final Promise promise = akka.dispatch.Futures.promise();
261 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
263 public void invoke(TransactionContext transactionContext) {
264 promise.completeWith(getReadyOrDirectCommitFuture(transactionContext, operationCallbackRef));
267 future = promise.future();
269 // avoid the creation of a promise and a TransactionOperation
270 future = getReadyOrDirectCommitFuture(transactionContext, operationCallbackRef);
273 return new SingleCommitCohortProxy(txContextFactory.getActorContext(), future, getIdentifier().toString(),
274 operationCallbackRef);
277 private Future<?> getReadyOrDirectCommitFuture(TransactionContext transactionContext,
278 OperationCallback.Reference operationCallbackRef) {
279 if (transactionContext.supportsDirectCommit()) {
280 TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
281 txContextFactory.getActorContext());
282 operationCallbackRef.set(rateLimitingCallback);
283 rateLimitingCallback.run();
284 return transactionContext.directCommit();
286 return transactionContext.readyTransaction();
290 private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort(
291 final Set<Entry<String, TransactionContextWrapper>> txContextWrapperEntries) {
293 final List<Future<ActorSelection>> cohortFutures = new ArrayList<>(txContextWrapperEntries.size());
294 for (Entry<String, TransactionContextWrapper> e : txContextWrapperEntries) {
295 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
297 cohortFutures.add(e.getValue().readyTransaction());
300 return new ThreePhaseCommitCohortProxy(txContextFactory.getActorContext(), cohortFutures, getIdentifier().toString());
303 private String shardNameFromIdentifier(final YangInstanceIdentifier path) {
304 return txContextFactory.getActorContext().getShardStrategyFactory().getStrategy(path).findShard(path);
307 private TransactionContextWrapper getContextWrapper(final YangInstanceIdentifier path) {
308 return getContextWrapper(shardNameFromIdentifier(path));
311 private TransactionContextWrapper getContextWrapper(final String shardName) {
312 final TransactionContextWrapper existing = txContextWrappers.get(shardName);
313 if (existing != null) {
317 final TransactionContextWrapper fresh = txContextFactory.newTransactionContextWrapper(this, shardName);
318 txContextWrappers.put(shardName, fresh);
322 TransactionType getType() {
327 return state != TransactionState.OPEN;
330 ActorContext getActorContext() {
331 return txContextFactory.getActorContext();