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.SettableFuture;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.HashMap;
24 import java.util.List;
26 import java.util.Map.Entry;
28 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
29 import org.opendaylight.controller.cluster.datastore.messages.AbstractRead;
30 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
31 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
32 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
33 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
34 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
35 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
36 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
37 import org.opendaylight.controller.cluster.datastore.utils.NormalizedNodeAggregator;
38 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
39 import org.opendaylight.controller.sal.core.spi.data.AbstractDOMStoreTransaction;
40 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
41 import org.opendaylight.yangtools.util.concurrent.MappingCheckedFuture;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import scala.concurrent.Future;
48 import scala.concurrent.Promise;
51 * A transaction potentially spanning multiple backend shards.
53 public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIdentifier>
54 implements DOMStoreReadWriteTransaction {
55 private enum TransactionState {
61 private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
63 private final Map<String, TransactionContextWrapper> txContextWrappers = new HashMap<>();
64 private final AbstractTransactionContextFactory<?> txContextFactory;
65 private final TransactionType type;
66 private TransactionState state = TransactionState.OPEN;
69 public TransactionProxy(final AbstractTransactionContextFactory<?> txContextFactory, final TransactionType type) {
70 super(txContextFactory.nextIdentifier(), txContextFactory.getActorContext().getDatastoreContext()
71 .isTransactionDebugContextEnabled());
72 this.txContextFactory = txContextFactory;
73 this.type = Preconditions.checkNotNull(type);
75 LOG.debug("New {} Tx - {}", type, getIdentifier());
79 public CheckedFuture<Boolean, ReadFailedException> exists(final YangInstanceIdentifier path) {
80 return executeRead(shardNameFromIdentifier(path), new DataExists(path, DataStoreVersions.CURRENT_VERSION));
83 private <T> CheckedFuture<T, ReadFailedException> executeRead(String shardName, final AbstractRead<T> readCmd) {
84 Preconditions.checkState(type != TransactionType.WRITE_ONLY,
85 "Reads from write-only transactions are not allowed");
87 LOG.debug("Tx {} {} {}", getIdentifier(), readCmd.getClass().getSimpleName(), readCmd.getPath());
89 final SettableFuture<T> proxyFuture = SettableFuture.create();
90 TransactionContextWrapper contextWrapper = getContextWrapper(shardName);
91 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
93 public void invoke(TransactionContext transactionContext) {
94 transactionContext.executeRead(readCmd, proxyFuture);
98 return MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
102 public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final YangInstanceIdentifier path) {
103 Preconditions.checkState(type != TransactionType.WRITE_ONLY,
104 "Reads from write-only transactions are not allowed");
106 LOG.debug("Tx {} read {}", getIdentifier(), path);
108 if (YangInstanceIdentifier.EMPTY.equals(path)) {
109 return readAllData();
111 return singleShardRead(shardNameFromIdentifier(path), path);
115 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> singleShardRead(
116 final String shardName, final YangInstanceIdentifier path) {
117 return executeRead(shardName, new ReadData(path, DataStoreVersions.CURRENT_VERSION));
120 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readAllData() {
121 final Set<String> allShardNames = txContextFactory.getActorContext().getConfiguration().getAllShardNames();
122 final Collection<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>> futures =
123 new ArrayList<>(allShardNames.size());
125 for (String shardName : allShardNames) {
126 futures.add(singleShardRead(shardName, YangInstanceIdentifier.EMPTY));
129 final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
130 final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;
132 aggregateFuture = Futures.transform(listFuture,
133 (Function<List<Optional<NormalizedNode<?, ?>>>, Optional<NormalizedNode<?, ?>>>) input -> {
135 return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input,
136 txContextFactory.getActorContext().getSchemaContext(),
137 txContextFactory.getActorContext().getDatastoreContext().getLogicalStoreType());
138 } catch (DataValidationFailedException e) {
139 throw new IllegalArgumentException("Failed to aggregate", e);
143 return MappingCheckedFuture.create(aggregateFuture, ReadFailedException.MAPPER);
147 public void delete(final YangInstanceIdentifier path) {
148 executeModification(new DeleteModification(path));
152 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
153 executeModification(new MergeModification(path, data));
157 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
158 executeModification(new WriteModification(path, data));
161 private void executeModification(final AbstractModification modification) {
162 checkModificationState();
164 LOG.debug("Tx {} executeModification {} {}", getIdentifier(), modification.getClass().getSimpleName(),
165 modification.getPath());
167 TransactionContextWrapper contextWrapper = getContextWrapper(modification.getPath());
168 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
170 protected void invoke(TransactionContext transactionContext) {
171 transactionContext.executeModification(modification);
176 private void checkModificationState() {
177 Preconditions.checkState(type != TransactionType.READ_ONLY,
178 "Modification operation on read-only transaction is not allowed");
179 Preconditions.checkState(state == TransactionState.OPEN,
180 "Transaction is sealed - further modifications are not allowed");
183 private boolean seal(final TransactionState newState) {
184 if (state == TransactionState.OPEN) {
193 public final void close() {
194 if (!seal(TransactionState.CLOSED)) {
195 Preconditions.checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
197 // Idempotent no-op as per AutoCloseable recommendation
201 for (TransactionContextWrapper contextWrapper : txContextWrappers.values()) {
202 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
204 public void invoke(TransactionContext transactionContext) {
205 transactionContext.closeTransaction();
211 txContextWrappers.clear();
215 public final AbstractThreePhaseCommitCohort<?> ready() {
216 Preconditions.checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
218 final boolean success = seal(TransactionState.READY);
219 Preconditions.checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
221 LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextWrappers.size());
223 final AbstractThreePhaseCommitCohort<?> ret;
224 switch (txContextWrappers.size()) {
226 ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
229 final Entry<String, TransactionContextWrapper> e = Iterables.getOnlyElement(
230 txContextWrappers.entrySet());
231 ret = createSingleCommitCohort(e.getKey(), e.getValue());
234 ret = createMultiCommitCohort(txContextWrappers.entrySet());
237 txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
239 final Throwable debugContext = getDebugContext();
240 return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
243 @SuppressWarnings({ "rawtypes", "unchecked" })
244 private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
245 final TransactionContextWrapper contextWrapper) {
247 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
249 final OperationCallback.Reference operationCallbackRef =
250 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
252 final TransactionContext transactionContext = contextWrapper.getTransactionContext();
254 if (transactionContext == null) {
255 final Promise promise = akka.dispatch.Futures.promise();
256 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
258 public void invoke(TransactionContext newTransactionContext) {
259 promise.completeWith(getDirectCommitFuture(newTransactionContext, operationCallbackRef));
262 future = promise.future();
264 // avoid the creation of a promise and a TransactionOperation
265 future = getDirectCommitFuture(transactionContext, operationCallbackRef);
268 return new SingleCommitCohortProxy(txContextFactory.getActorContext(), future, getIdentifier(),
269 operationCallbackRef);
272 private Future<?> getDirectCommitFuture(TransactionContext transactionContext,
273 OperationCallback.Reference operationCallbackRef) {
274 TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
275 txContextFactory.getActorContext());
276 operationCallbackRef.set(rateLimitingCallback);
277 rateLimitingCallback.run();
278 return transactionContext.directCommit();
281 private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort(
282 final Set<Entry<String, TransactionContextWrapper>> txContextWrapperEntries) {
284 final List<ThreePhaseCommitCohortProxy.CohortInfo> cohorts = new ArrayList<>(txContextWrapperEntries.size());
285 for (Entry<String, TransactionContextWrapper> e : txContextWrapperEntries) {
286 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
288 final TransactionContextWrapper wrapper = e.getValue();
290 // The remote tx version is obtained the via TransactionContext which may not be available yet so
291 // we pass a Supplier to dynamically obtain it. Once the ready Future is resolved the
292 // TransactionContext is available.
293 Supplier<Short> txVersionSupplier = () -> wrapper.getTransactionContext().getTransactionVersion();
295 cohorts.add(new ThreePhaseCommitCohortProxy.CohortInfo(wrapper.readyTransaction(), txVersionSupplier));
298 return new ThreePhaseCommitCohortProxy(txContextFactory.getActorContext(), cohorts, getIdentifier());
301 private String shardNameFromIdentifier(final YangInstanceIdentifier path) {
302 return txContextFactory.getActorContext().getShardStrategyFactory().getStrategy(path).findShard(path);
305 private TransactionContextWrapper getContextWrapper(final YangInstanceIdentifier path) {
306 return getContextWrapper(shardNameFromIdentifier(path));
309 private TransactionContextWrapper getContextWrapper(final String shardName) {
310 final TransactionContextWrapper existing = txContextWrappers.get(shardName);
311 if (existing != null) {
315 final TransactionContextWrapper fresh = txContextFactory.newTransactionContextWrapper(this, shardName);
316 txContextWrappers.put(shardName, fresh);
320 TransactionType getType() {
325 return state != TransactionState.OPEN;
328 ActorContext getActorContext() {
329 return txContextFactory.getActorContext();