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.mdsal.common.api.MappingCheckedFuture;
42 import org.opendaylight.mdsal.common.api.ReadFailedException;
43 import org.opendaylight.mdsal.dom.spi.store.AbstractDOMStoreTransaction;
44 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
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");
109 Preconditions.checkNotNull(path, "path should not be null");
111 LOG.trace("Tx {} read {}", getIdentifier(), path);
112 return path.isEmpty() ? readAllData() : 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);
141 }, MoreExecutors.directExecutor());
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.trace("Tx {} executeModification {} {}", getIdentifier(), modification.getClass().getSimpleName(),
165 modification.getPath());
167 TransactionContextWrapper contextWrapper = getContextWrapper(modification.getPath());
168 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
170 protected void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
171 transactionContext.executeModification(modification, havePermit);
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(final TransactionContext transactionContext, final Boolean havePermit) {
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();
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(final TransactionContext newTransactionContext, final Boolean havePermit) {
259 promise.completeWith(getDirectCommitFuture(newTransactionContext, operationCallbackRef,
263 future = promise.future();
265 // avoid the creation of a promise and a TransactionOperation
266 future = getDirectCommitFuture(transactionContext, operationCallbackRef, null);
269 return new SingleCommitCohortProxy(txContextFactory.getActorContext(), future, getIdentifier(),
270 operationCallbackRef);
273 private Future<?> getDirectCommitFuture(final TransactionContext transactionContext,
274 final OperationCallback.Reference operationCallbackRef, final Boolean havePermit) {
275 TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
276 txContextFactory.getActorContext());
277 operationCallbackRef.set(rateLimitingCallback);
278 rateLimitingCallback.run();
279 return transactionContext.directCommit(havePermit);
282 private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort() {
284 final List<ThreePhaseCommitCohortProxy.CohortInfo> cohorts = new ArrayList<>(txContextWrappers.size());
285 final java.util.Optional<SortedSet<String>> shardNames =
286 java.util.Optional.of(new TreeSet<>(txContextWrappers.keySet()));
287 for (Entry<String, TransactionContextWrapper> e : txContextWrappers.entrySet()) {
288 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
290 final TransactionContextWrapper wrapper = e.getValue();
292 // The remote tx version is obtained the via TransactionContext which may not be available yet so
293 // we pass a Supplier to dynamically obtain it. Once the ready Future is resolved the
294 // TransactionContext is available.
295 Supplier<Short> txVersionSupplier = () -> wrapper.getTransactionContext().getTransactionVersion();
297 cohorts.add(new ThreePhaseCommitCohortProxy.CohortInfo(wrapper.readyTransaction(shardNames),
301 return new ThreePhaseCommitCohortProxy(txContextFactory.getActorContext(), cohorts, getIdentifier());
304 private String shardNameFromIdentifier(final YangInstanceIdentifier path) {
305 return txContextFactory.getActorContext().getShardStrategyFactory().getStrategy(path).findShard(path);
308 private TransactionContextWrapper getContextWrapper(final YangInstanceIdentifier path) {
309 return getContextWrapper(shardNameFromIdentifier(path));
312 private TransactionContextWrapper getContextWrapper(final String shardName) {
313 final TransactionContextWrapper existing = txContextWrappers.get(shardName);
314 if (existing != null) {
318 final TransactionContextWrapper fresh = txContextFactory.newTransactionContextWrapper(this, shardName);
319 txContextWrappers.put(shardName, fresh);
323 TransactionType getType() {
328 return state != TransactionState.OPEN;
331 ActorContext getActorContext() {
332 return txContextFactory.getActorContext();