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 static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
15 import akka.actor.ActorSelection;
16 import com.google.common.annotations.VisibleForTesting;
17 import com.google.common.collect.Iterables;
18 import com.google.common.util.concurrent.FluentFuture;
19 import com.google.common.util.concurrent.Futures;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.MoreExecutors;
22 import com.google.common.util.concurrent.SettableFuture;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.HashMap;
26 import java.util.List;
28 import java.util.Map.Entry;
29 import java.util.Optional;
31 import java.util.SortedSet;
32 import java.util.TreeMap;
33 import java.util.TreeSet;
34 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
35 import org.opendaylight.controller.cluster.datastore.TransactionModificationOperation.DeleteOperation;
36 import org.opendaylight.controller.cluster.datastore.TransactionModificationOperation.MergeOperation;
37 import org.opendaylight.controller.cluster.datastore.TransactionModificationOperation.WriteOperation;
38 import org.opendaylight.controller.cluster.datastore.messages.AbstractRead;
39 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
40 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
41 import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
42 import org.opendaylight.controller.cluster.datastore.utils.NormalizedNodeAggregator;
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.YangInstanceIdentifier.NodeIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
49 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
51 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
52 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import scala.concurrent.Future;
56 import scala.concurrent.Promise;
59 * A transaction potentially spanning multiple backend shards.
61 public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIdentifier>
62 implements DOMStoreReadWriteTransaction {
63 private enum TransactionState {
69 private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
70 private static final DeleteOperation ROOT_DELETE_OPERATION = new DeleteOperation(YangInstanceIdentifier.empty());
72 private final Map<String, AbstractTransactionContextWrapper> txContextWrappers = new TreeMap<>();
73 private final AbstractTransactionContextFactory<?> txContextFactory;
74 private final TransactionType type;
75 private TransactionState state = TransactionState.OPEN;
78 public TransactionProxy(final AbstractTransactionContextFactory<?> txContextFactory, final TransactionType type) {
79 super(txContextFactory.nextIdentifier(), txContextFactory.getActorUtils().getDatastoreContext()
80 .isTransactionDebugContextEnabled());
81 this.txContextFactory = txContextFactory;
82 this.type = requireNonNull(type);
84 LOG.debug("New {} Tx - {}", type, getIdentifier());
88 public FluentFuture<Boolean> exists(final YangInstanceIdentifier path) {
89 return executeRead(shardNameFromIdentifier(path), new DataExists(path, DataStoreVersions.CURRENT_VERSION));
92 private <T> FluentFuture<T> executeRead(final String shardName, final AbstractRead<T> readCmd) {
93 checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
95 LOG.trace("Tx {} {} {}", getIdentifier(), readCmd.getClass().getSimpleName(), readCmd.getPath());
97 final SettableFuture<T> proxyFuture = SettableFuture.create();
98 AbstractTransactionContextWrapper contextWrapper = getContextWrapper(shardName);
99 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
101 public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
102 transactionContext.executeRead(readCmd, proxyFuture, havePermit);
106 return FluentFuture.from(proxyFuture);
110 public FluentFuture<Optional<NormalizedNode>> read(final YangInstanceIdentifier path) {
111 checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
112 requireNonNull(path, "path should not be null");
114 LOG.trace("Tx {} read {}", getIdentifier(), path);
115 return path.isEmpty() ? readAllData() : singleShardRead(shardNameFromIdentifier(path), path);
118 private FluentFuture<Optional<NormalizedNode>> singleShardRead(final String shardName,
119 final YangInstanceIdentifier path) {
120 return executeRead(shardName, new ReadData(path, DataStoreVersions.CURRENT_VERSION));
123 private FluentFuture<Optional<NormalizedNode>> readAllData() {
124 final Set<String> allShardNames = txContextFactory.getActorUtils().getConfiguration().getAllShardNames();
125 final Collection<FluentFuture<Optional<NormalizedNode>>> futures = new ArrayList<>(allShardNames.size());
127 for (String shardName : allShardNames) {
128 futures.add(singleShardRead(shardName, YangInstanceIdentifier.empty()));
131 final ListenableFuture<List<Optional<NormalizedNode>>> listFuture = Futures.allAsList(futures);
132 final ListenableFuture<Optional<NormalizedNode>> aggregateFuture;
134 aggregateFuture = Futures.transform(listFuture, input -> {
136 return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.empty(), input,
137 txContextFactory.getActorUtils().getSchemaContext(),
138 txContextFactory.getActorUtils().getDatastoreContext().getLogicalStoreType());
139 } catch (DataValidationFailedException e) {
140 throw new IllegalArgumentException("Failed to aggregate", e);
142 }, MoreExecutors.directExecutor());
144 return FluentFuture.from(aggregateFuture);
148 public void delete(final YangInstanceIdentifier path) {
149 checkModificationState("delete", path);
151 if (path.isEmpty()) {
154 executeModification(new DeleteOperation(path));
158 private void deleteAllData() {
159 for (String shardName : getActorUtils().getConfiguration().getAllShardNames()) {
160 getContextWrapper(shardName).maybeExecuteTransactionOperation(ROOT_DELETE_OPERATION);
165 public void merge(final YangInstanceIdentifier path, final NormalizedNode data) {
166 checkModificationState("merge", path);
168 if (path.isEmpty()) {
169 mergeAllData(checkRootData(data));
171 executeModification(new MergeOperation(path, data));
175 private void mergeAllData(final ContainerNode rootData) {
176 // Populate requests for individual shards that are being touched
177 final Map<String, DataContainerNodeBuilder<NodeIdentifier, ContainerNode>> rootBuilders = new HashMap<>();
178 for (DataContainerChild child : rootData.body()) {
179 final String shardName = shardNameFromRootChild(child);
180 rootBuilders.computeIfAbsent(shardName,
181 unused -> Builders.containerBuilder().withNodeIdentifier(rootData.getIdentifier()))
185 // Now dispatch all merges
186 for (Entry<String, DataContainerNodeBuilder<NodeIdentifier, ContainerNode>> entry : rootBuilders.entrySet()) {
187 getContextWrapper(entry.getKey()).maybeExecuteTransactionOperation(new MergeOperation(
188 YangInstanceIdentifier.empty(), entry.getValue().build()));
193 public void write(final YangInstanceIdentifier path, final NormalizedNode data) {
194 checkModificationState("write", path);
196 if (path.isEmpty()) {
197 writeAllData(checkRootData(data));
199 executeModification(new WriteOperation(path, data));
203 private void writeAllData(final ContainerNode rootData) {
204 // Open builders for all shards
205 final Map<String, DataContainerNodeBuilder<NodeIdentifier, ContainerNode>> rootBuilders = new HashMap<>();
206 for (String shardName : getActorUtils().getConfiguration().getAllShardNames()) {
207 rootBuilders.put(shardName, Builders.containerBuilder().withNodeIdentifier(rootData.getIdentifier()));
210 // Now distribute children as needed
211 for (DataContainerChild child : rootData.body()) {
212 final String shardName = shardNameFromRootChild(child);
213 verifyNotNull(rootBuilders.get(shardName), "Failed to find builder for %s", shardName).addChild(child);
216 // Now dispatch all writes
217 for (Entry<String, DataContainerNodeBuilder<NodeIdentifier, ContainerNode>> entry : rootBuilders.entrySet()) {
218 getContextWrapper(entry.getKey()).maybeExecuteTransactionOperation(new WriteOperation(
219 YangInstanceIdentifier.empty(), entry.getValue().build()));
223 private void executeModification(final TransactionModificationOperation operation) {
224 getContextWrapper(operation.path()).maybeExecuteTransactionOperation(operation);
227 private static ContainerNode checkRootData(final NormalizedNode data) {
228 // Root has to be a container
229 checkArgument(data instanceof ContainerNode, "Invalid root data %s", data);
230 return (ContainerNode) data;
233 private void checkModificationState(final String opName, final YangInstanceIdentifier path) {
234 checkState(type != TransactionType.READ_ONLY, "Modification operation on read-only transaction is not allowed");
235 checkState(state == TransactionState.OPEN, "Transaction is sealed - further modifications are not allowed");
236 LOG.trace("Tx {} {} {}", getIdentifier(), opName, path);
239 private boolean seal(final TransactionState newState) {
240 if (state == TransactionState.OPEN) {
248 public final void close() {
249 if (!seal(TransactionState.CLOSED)) {
250 checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
252 // Idempotent no-op as per AutoCloseable recommendation
256 for (AbstractTransactionContextWrapper contextWrapper : txContextWrappers.values()) {
257 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
259 public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
260 transactionContext.closeTransaction();
266 txContextWrappers.clear();
270 public final AbstractThreePhaseCommitCohort<?> ready() {
271 checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
273 final boolean success = seal(TransactionState.READY);
274 checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
276 LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextWrappers.size());
278 final AbstractThreePhaseCommitCohort<?> ret;
279 switch (txContextWrappers.size()) {
281 ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
284 final Entry<String, AbstractTransactionContextWrapper> e = Iterables.getOnlyElement(
285 txContextWrappers.entrySet());
286 ret = createSingleCommitCohort(e.getKey(), e.getValue());
289 ret = createMultiCommitCohort();
292 txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
294 final Throwable debugContext = getDebugContext();
295 return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
298 @SuppressWarnings({ "rawtypes", "unchecked" })
299 private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
300 final AbstractTransactionContextWrapper contextWrapper) {
302 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
304 final OperationCallback.Reference operationCallbackRef =
305 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
307 final TransactionContext transactionContext = contextWrapper.getTransactionContext();
309 if (transactionContext == null) {
310 final Promise promise = akka.dispatch.Futures.promise();
311 contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
313 public void invoke(final TransactionContext newTransactionContext, final Boolean havePermit) {
314 promise.completeWith(getDirectCommitFuture(newTransactionContext, operationCallbackRef,
318 future = promise.future();
320 // avoid the creation of a promise and a TransactionOperation
321 future = getDirectCommitFuture(transactionContext, operationCallbackRef, null);
324 return new SingleCommitCohortProxy(txContextFactory.getActorUtils(), future, getIdentifier(),
325 operationCallbackRef);
328 private Future<?> getDirectCommitFuture(final TransactionContext transactionContext,
329 final OperationCallback.Reference operationCallbackRef, final Boolean havePermit) {
330 TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
331 txContextFactory.getActorUtils());
332 operationCallbackRef.set(rateLimitingCallback);
333 rateLimitingCallback.run();
334 return transactionContext.directCommit(havePermit);
337 private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort() {
339 final List<ThreePhaseCommitCohortProxy.CohortInfo> cohorts = new ArrayList<>(txContextWrappers.size());
340 final Optional<SortedSet<String>> shardNames = Optional.of(new TreeSet<>(txContextWrappers.keySet()));
341 for (Entry<String, AbstractTransactionContextWrapper> e : txContextWrappers.entrySet()) {
342 LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
344 final AbstractTransactionContextWrapper wrapper = e.getValue();
346 // The remote tx version is obtained the via TransactionContext which may not be available yet so
347 // we pass a Supplier to dynamically obtain it. Once the ready Future is resolved the
348 // TransactionContext is available.
349 cohorts.add(new ThreePhaseCommitCohortProxy.CohortInfo(wrapper.readyTransaction(shardNames),
350 () -> wrapper.getTransactionContext().getTransactionVersion()));
353 return new ThreePhaseCommitCohortProxy(txContextFactory.getActorUtils(), cohorts, getIdentifier());
356 private String shardNameFromRootChild(final DataContainerChild child) {
357 return shardNameFromIdentifier(YangInstanceIdentifier.create(child.getIdentifier()));
360 private String shardNameFromIdentifier(final YangInstanceIdentifier path) {
361 return getActorUtils().getShardStrategyFactory().getStrategy(path).findShard(path);
364 private AbstractTransactionContextWrapper getContextWrapper(final YangInstanceIdentifier path) {
365 return getContextWrapper(shardNameFromIdentifier(path));
368 private AbstractTransactionContextWrapper getContextWrapper(final String shardName) {
369 final AbstractTransactionContextWrapper existing = txContextWrappers.get(shardName);
370 if (existing != null) {
374 final AbstractTransactionContextWrapper fresh = txContextFactory.newTransactionContextWrapper(this, shardName);
375 txContextWrappers.put(shardName, fresh);
379 TransactionType getType() {
384 return state != TransactionState.OPEN;
387 final ActorUtils getActorUtils() {
388 return txContextFactory.getActorUtils();