Refactor TransactionContext.executeModification()
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / TransactionProxy.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.cluster.datastore;
9
10 import static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12
13 import akka.actor.ActorSelection;
14 import com.google.common.annotations.VisibleForTesting;
15 import com.google.common.collect.Iterables;
16 import com.google.common.util.concurrent.FluentFuture;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.MoreExecutors;
20 import com.google.common.util.concurrent.SettableFuture;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.Optional;
27 import java.util.Set;
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.TransactionModificationOperation.DeleteOperation;
33 import org.opendaylight.controller.cluster.datastore.TransactionModificationOperation.MergeOperation;
34 import org.opendaylight.controller.cluster.datastore.TransactionModificationOperation.WriteOperation;
35 import org.opendaylight.controller.cluster.datastore.messages.AbstractRead;
36 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
37 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
38 import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
39 import org.opendaylight.controller.cluster.datastore.utils.NormalizedNodeAggregator;
40 import org.opendaylight.mdsal.dom.spi.store.AbstractDOMStoreTransaction;
41 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
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;
49
50 /**
51  * A transaction potentially spanning multiple backend shards.
52  */
53 public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIdentifier>
54         implements DOMStoreReadWriteTransaction {
55     private enum TransactionState {
56         OPEN,
57         READY,
58         CLOSED,
59     }
60
61     private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
62
63     private final Map<String, TransactionContextWrapper> txContextWrappers = new TreeMap<>();
64     private final AbstractTransactionContextFactory<?> txContextFactory;
65     private final TransactionType type;
66     private TransactionState state = TransactionState.OPEN;
67
68     @VisibleForTesting
69     public TransactionProxy(final AbstractTransactionContextFactory<?> txContextFactory, final TransactionType type) {
70         super(txContextFactory.nextIdentifier(), txContextFactory.getActorUtils().getDatastoreContext()
71                 .isTransactionDebugContextEnabled());
72         this.txContextFactory = txContextFactory;
73         this.type = requireNonNull(type);
74
75         LOG.debug("New {} Tx - {}", type, getIdentifier());
76     }
77
78     @Override
79     public FluentFuture<Boolean> exists(final YangInstanceIdentifier path) {
80         return executeRead(shardNameFromIdentifier(path), new DataExists(path, DataStoreVersions.CURRENT_VERSION));
81     }
82
83     private <T> FluentFuture<T> executeRead(final String shardName, final AbstractRead<T> readCmd) {
84         checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
85
86         LOG.trace("Tx {} {} {}", getIdentifier(), readCmd.getClass().getSimpleName(), readCmd.getPath());
87
88         final SettableFuture<T> proxyFuture = SettableFuture.create();
89         TransactionContextWrapper contextWrapper = getContextWrapper(shardName);
90         contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
91             @Override
92             public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
93                 transactionContext.executeRead(readCmd, proxyFuture, havePermit);
94             }
95         });
96
97         return FluentFuture.from(proxyFuture);
98     }
99
100     @Override
101     public FluentFuture<Optional<NormalizedNode<?, ?>>> read(final YangInstanceIdentifier path) {
102         checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
103         requireNonNull(path, "path should not be null");
104
105         LOG.trace("Tx {} read {}", getIdentifier(), path);
106         return path.isEmpty() ? readAllData() : singleShardRead(shardNameFromIdentifier(path), path);
107     }
108
109     private FluentFuture<Optional<NormalizedNode<?, ?>>> singleShardRead(
110             final String shardName, final YangInstanceIdentifier path) {
111         return executeRead(shardName, new ReadData(path, DataStoreVersions.CURRENT_VERSION));
112     }
113
114     private FluentFuture<Optional<NormalizedNode<?, ?>>> readAllData() {
115         final Set<String> allShardNames = txContextFactory.getActorUtils().getConfiguration().getAllShardNames();
116         final Collection<FluentFuture<Optional<NormalizedNode<?, ?>>>> futures = new ArrayList<>(allShardNames.size());
117
118         for (String shardName : allShardNames) {
119             futures.add(singleShardRead(shardName, YangInstanceIdentifier.empty()));
120         }
121
122         final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
123         final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;
124
125         aggregateFuture = Futures.transform(listFuture, input -> {
126             try {
127                 return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.empty(), input,
128                         txContextFactory.getActorUtils().getSchemaContext(),
129                         txContextFactory.getActorUtils().getDatastoreContext().getLogicalStoreType());
130             } catch (DataValidationFailedException e) {
131                 throw new IllegalArgumentException("Failed to aggregate", e);
132             }
133         }, MoreExecutors.directExecutor());
134
135         return FluentFuture.from(aggregateFuture);
136     }
137
138     @Override
139     public void delete(final YangInstanceIdentifier path) {
140         checkModificationState("delete", path);
141
142         executeModification(new DeleteOperation(path));
143     }
144
145     @Override
146     public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
147         checkModificationState("merge", path);
148
149         executeModification(new MergeOperation(path, data));
150     }
151
152     @Override
153     public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
154         checkModificationState("write", path);
155
156         executeModification(new WriteOperation(path, data));
157     }
158
159     private void executeModification(final TransactionModificationOperation operation) {
160         getContextWrapper(operation.path()).maybeExecuteTransactionOperation(operation);
161     }
162
163     private void checkModificationState(final String opName, final YangInstanceIdentifier path) {
164         checkState(type != TransactionType.READ_ONLY, "Modification operation on read-only transaction is not allowed");
165         checkState(state == TransactionState.OPEN, "Transaction is sealed - further modifications are not allowed");
166         LOG.trace("Tx {} {} {}", getIdentifier(), opName, path);
167     }
168
169     private boolean seal(final TransactionState newState) {
170         if (state == TransactionState.OPEN) {
171             state = newState;
172             return true;
173         }
174         return false;
175     }
176
177     @Override
178     public final void close() {
179         if (!seal(TransactionState.CLOSED)) {
180             checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
181                 getIdentifier());
182             // Idempotent no-op as per AutoCloseable recommendation
183             return;
184         }
185
186         for (TransactionContextWrapper contextWrapper : txContextWrappers.values()) {
187             contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
188                 @Override
189                 public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
190                     transactionContext.closeTransaction();
191                 }
192             });
193         }
194
195
196         txContextWrappers.clear();
197     }
198
199     @Override
200     public final AbstractThreePhaseCommitCohort<?> ready() {
201         checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
202
203         final boolean success = seal(TransactionState.READY);
204         checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
205
206         LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextWrappers.size());
207
208         final AbstractThreePhaseCommitCohort<?> ret;
209         switch (txContextWrappers.size()) {
210             case 0:
211                 ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
212                 break;
213             case 1:
214                 final Entry<String, TransactionContextWrapper> e = Iterables.getOnlyElement(
215                         txContextWrappers.entrySet());
216                 ret = createSingleCommitCohort(e.getKey(), e.getValue());
217                 break;
218             default:
219                 ret = createMultiCommitCohort();
220         }
221
222         txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
223
224         final Throwable debugContext = getDebugContext();
225         return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
226     }
227
228     @SuppressWarnings({ "rawtypes", "unchecked" })
229     private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
230             final TransactionContextWrapper contextWrapper) {
231
232         LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
233
234         final OperationCallback.Reference operationCallbackRef =
235                 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
236
237         final TransactionContext transactionContext = contextWrapper.getTransactionContext();
238         final Future future;
239         if (transactionContext == null) {
240             final Promise promise = akka.dispatch.Futures.promise();
241             contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
242                 @Override
243                 public void invoke(final TransactionContext newTransactionContext, final Boolean havePermit) {
244                     promise.completeWith(getDirectCommitFuture(newTransactionContext, operationCallbackRef,
245                         havePermit));
246                 }
247             });
248             future = promise.future();
249         } else {
250             // avoid the creation of a promise and a TransactionOperation
251             future = getDirectCommitFuture(transactionContext, operationCallbackRef, null);
252         }
253
254         return new SingleCommitCohortProxy(txContextFactory.getActorUtils(), future, getIdentifier(),
255             operationCallbackRef);
256     }
257
258     private Future<?> getDirectCommitFuture(final TransactionContext transactionContext,
259             final OperationCallback.Reference operationCallbackRef, final Boolean havePermit) {
260         TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
261                 txContextFactory.getActorUtils());
262         operationCallbackRef.set(rateLimitingCallback);
263         rateLimitingCallback.run();
264         return transactionContext.directCommit(havePermit);
265     }
266
267     private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort() {
268
269         final List<ThreePhaseCommitCohortProxy.CohortInfo> cohorts = new ArrayList<>(txContextWrappers.size());
270         final Optional<SortedSet<String>> shardNames = Optional.of(new TreeSet<>(txContextWrappers.keySet()));
271         for (Entry<String, TransactionContextWrapper> e : txContextWrappers.entrySet()) {
272             LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
273
274             final TransactionContextWrapper wrapper = e.getValue();
275
276             // The remote tx version is obtained the via TransactionContext which may not be available yet so
277             // we pass a Supplier to dynamically obtain it. Once the ready Future is resolved the
278             // TransactionContext is available.
279             cohorts.add(new ThreePhaseCommitCohortProxy.CohortInfo(wrapper.readyTransaction(shardNames),
280                 () -> wrapper.getTransactionContext().getTransactionVersion()));
281         }
282
283         return new ThreePhaseCommitCohortProxy(txContextFactory.getActorUtils(), cohorts, getIdentifier());
284     }
285
286     private String shardNameFromIdentifier(final YangInstanceIdentifier path) {
287         return txContextFactory.getActorUtils().getShardStrategyFactory().getStrategy(path).findShard(path);
288     }
289
290     private TransactionContextWrapper getContextWrapper(final YangInstanceIdentifier path) {
291         return getContextWrapper(shardNameFromIdentifier(path));
292     }
293
294     private TransactionContextWrapper getContextWrapper(final String shardName) {
295         final TransactionContextWrapper existing = txContextWrappers.get(shardName);
296         if (existing != null) {
297             return existing;
298         }
299
300         final TransactionContextWrapper fresh = txContextFactory.newTransactionContextWrapper(this, shardName);
301         txContextWrappers.put(shardName, fresh);
302         return fresh;
303     }
304
305     TransactionType getType() {
306         return type;
307     }
308
309     boolean isReady() {
310         return state != TransactionState.OPEN;
311     }
312
313     ActorUtils getActorUtils() {
314         return txContextFactory.getActorUtils();
315     }
316 }