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.base.Supplier;
16 import com.google.common.collect.Iterables;
17 import com.google.common.util.concurrent.CheckedFuture;
18 import com.google.common.util.concurrent.Futures;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import com.google.common.util.concurrent.MoreExecutors;
21 import com.google.common.util.concurrent.SettableFuture;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.List;
26 import java.util.Map.Entry;
28 import java.util.SortedSet;
29 import java.util.TreeMap;
30 import java.util.TreeSet;
31 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
32 import org.opendaylight.controller.cluster.datastore.messages.AbstractRead;
33 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
34 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
35 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
36 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
37 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
38 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
39 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
40 import org.opendaylight.controller.cluster.datastore.utils.NormalizedNodeAggregator;
41 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
42 import org.opendaylight.controller.sal.core.spi.data.AbstractDOMStoreTransaction;
43 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
44 import org.opendaylight.mdsal.common.api.MappingCheckedFuture;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import scala.concurrent.Future;
51 import scala.concurrent.Promise;
54 * A transaction potentially spanning multiple backend shards.
56 public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIdentifier>
57 implements DOMStoreReadWriteTransaction {
58 private enum TransactionState {
64 private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
66 private final Map<String, TransactionContextWrapper> txContextWrappers = new TreeMap<>();
67 private final AbstractTransactionContextFactory<?> txContextFactory;
68 private final TransactionType type;
69 private TransactionState state = TransactionState.OPEN;
72 public TransactionProxy(final AbstractTransactionContextFactory<?> txContextFactory, final TransactionType type) {
73 super(txContextFactory.nextIdentifier(), txContextFactory.getActorContext().getDatastoreContext()
74 .isTransactionDebugContextEnabled());
75 this.txContextFactory = txContextFactory;
76 this.type = Preconditions.checkNotNull(type);
78 LOG.debug("New {} Tx - {}", type, getIdentifier());
82 public CheckedFuture<Boolean, ReadFailedException> exists(final YangInstanceIdentifier path) {
83 return executeRead(shardNameFromIdentifier(path), new DataExists(path, DataStoreVersions.CURRENT_VERSION));
86 private <T> CheckedFuture<T, ReadFailedException> executeRead(final String shardName,
87 final AbstractRead<T> readCmd) {
88 Preconditions.checkState(type != TransactionType.WRITE_ONLY,
89 "Reads from write-only transactions are not allowed");
91 LOG.trace("Tx {} {} {}", getIdentifier(), readCmd.getClass().getSimpleName(), readCmd.getPath());
93 final SettableFuture<T> proxyFuture = SettableFuture.create();
94 TransactionContextWrapper contextWrapper = getContextWrapper(shardName);
95 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
97 public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
98 transactionContext.executeRead(readCmd, proxyFuture, havePermit);
102 return MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
106 public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final YangInstanceIdentifier path) {
107 Preconditions.checkState(type != TransactionType.WRITE_ONLY,
108 "Reads from write-only transactions are not allowed");
110 LOG.trace("Tx {} read {}", getIdentifier(), path);
112 if (YangInstanceIdentifier.EMPTY.equals(path)) {
113 return readAllData();
115 return singleShardRead(shardNameFromIdentifier(path), path);
119 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> singleShardRead(
120 final String shardName, final YangInstanceIdentifier path) {
121 return executeRead(shardName, new ReadData(path, DataStoreVersions.CURRENT_VERSION));
124 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readAllData() {
125 final Set<String> allShardNames = txContextFactory.getActorContext().getConfiguration().getAllShardNames();
126 final Collection<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>> futures =
127 new ArrayList<>(allShardNames.size());
129 for (String shardName : allShardNames) {
130 futures.add(singleShardRead(shardName, YangInstanceIdentifier.EMPTY));
133 final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
134 final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;
136 aggregateFuture = Futures.transform(listFuture,
137 (Function<List<Optional<NormalizedNode<?, ?>>>, Optional<NormalizedNode<?, ?>>>) input -> {
139 return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input,
140 txContextFactory.getActorContext().getSchemaContext(),
141 txContextFactory.getActorContext().getDatastoreContext().getLogicalStoreType());
142 } catch (DataValidationFailedException e) {
143 throw new IllegalArgumentException("Failed to aggregate", e);
145 }, MoreExecutors.directExecutor());
147 return MappingCheckedFuture.create(aggregateFuture, ReadFailedException.MAPPER);
151 public void delete(final YangInstanceIdentifier path) {
152 executeModification(new DeleteModification(path));
156 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
157 executeModification(new MergeModification(path, data));
161 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
162 executeModification(new WriteModification(path, data));
165 private void executeModification(final AbstractModification modification) {
166 checkModificationState();
168 LOG.trace("Tx {} executeModification {} {}", getIdentifier(), modification.getClass().getSimpleName(),
169 modification.getPath());
171 TransactionContextWrapper contextWrapper = getContextWrapper(modification.getPath());
172 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
174 protected void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
175 transactionContext.executeModification(modification, havePermit);
180 private void checkModificationState() {
181 Preconditions.checkState(type != TransactionType.READ_ONLY,
182 "Modification operation on read-only transaction is not allowed");
183 Preconditions.checkState(state == TransactionState.OPEN,
184 "Transaction is sealed - further modifications are not allowed");
187 private boolean seal(final TransactionState newState) {
188 if (state == TransactionState.OPEN) {
197 public final void close() {
198 if (!seal(TransactionState.CLOSED)) {
199 Preconditions.checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
201 // Idempotent no-op as per AutoCloseable recommendation
205 for (TransactionContextWrapper contextWrapper : txContextWrappers.values()) {
206 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
208 public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
209 transactionContext.closeTransaction();
215 txContextWrappers.clear();
219 public final AbstractThreePhaseCommitCohort<?> ready() {
220 Preconditions.checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
222 final boolean success = seal(TransactionState.READY);
223 Preconditions.checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
225 LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextWrappers.size());
227 final AbstractThreePhaseCommitCohort<?> ret;
228 switch (txContextWrappers.size()) {
230 ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
233 final Entry<String, TransactionContextWrapper> e = Iterables.getOnlyElement(
234 txContextWrappers.entrySet());
235 ret = createSingleCommitCohort(e.getKey(), e.getValue());
238 ret = createMultiCommitCohort();
241 txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
243 final Throwable debugContext = getDebugContext();
244 return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
247 @SuppressWarnings({ "rawtypes", "unchecked" })
248 private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
249 final TransactionContextWrapper contextWrapper) {
251 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
253 final OperationCallback.Reference operationCallbackRef =
254 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
256 final TransactionContext transactionContext = contextWrapper.getTransactionContext();
258 if (transactionContext == null) {
259 final Promise promise = akka.dispatch.Futures.promise();
260 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
262 public void invoke(final TransactionContext newTransactionContext, final Boolean havePermit) {
263 promise.completeWith(getDirectCommitFuture(newTransactionContext, operationCallbackRef,
267 future = promise.future();
269 // avoid the creation of a promise and a TransactionOperation
270 future = getDirectCommitFuture(transactionContext, operationCallbackRef, null);
273 return new SingleCommitCohortProxy(txContextFactory.getActorContext(), future, getIdentifier(),
274 operationCallbackRef);
277 private Future<?> getDirectCommitFuture(final TransactionContext transactionContext,
278 final OperationCallback.Reference operationCallbackRef, final Boolean havePermit) {
279 TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
280 txContextFactory.getActorContext());
281 operationCallbackRef.set(rateLimitingCallback);
282 rateLimitingCallback.run();
283 return transactionContext.directCommit(havePermit);
286 private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort() {
288 final List<ThreePhaseCommitCohortProxy.CohortInfo> cohorts = new ArrayList<>(txContextWrappers.size());
289 final java.util.Optional<SortedSet<String>> shardNames =
290 java.util.Optional.of(new TreeSet<>(txContextWrappers.keySet()));
291 for (Entry<String, TransactionContextWrapper> e : txContextWrappers.entrySet()) {
292 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
294 final TransactionContextWrapper wrapper = e.getValue();
296 // The remote tx version is obtained the via TransactionContext which may not be available yet so
297 // we pass a Supplier to dynamically obtain it. Once the ready Future is resolved the
298 // TransactionContext is available.
299 Supplier<Short> txVersionSupplier = () -> wrapper.getTransactionContext().getTransactionVersion();
301 cohorts.add(new ThreePhaseCommitCohortProxy.CohortInfo(wrapper.readyTransaction(shardNames),
305 return new ThreePhaseCommitCohortProxy(txContextFactory.getActorContext(), cohorts, getIdentifier());
308 private String shardNameFromIdentifier(final YangInstanceIdentifier path) {
309 return txContextFactory.getActorContext().getShardStrategyFactory().getStrategy(path).findShard(path);
312 private TransactionContextWrapper getContextWrapper(final YangInstanceIdentifier path) {
313 return getContextWrapper(shardNameFromIdentifier(path));
316 private TransactionContextWrapper getContextWrapper(final String shardName) {
317 final TransactionContextWrapper existing = txContextWrappers.get(shardName);
318 if (existing != null) {
322 final TransactionContextWrapper fresh = txContextFactory.newTransactionContextWrapper(this, shardName);
323 txContextWrappers.put(shardName, fresh);
327 TransactionType getType() {
332 return state != TransactionState.OPEN;
335 ActorContext getActorContext() {
336 return txContextFactory.getActorContext();