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