Move operation limiter down to TransactionContextWrapper
[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.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.collect.Iterables;
16 import com.google.common.util.concurrent.CheckedFuture;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.SettableFuture;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.HashMap;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.Set;
27 import org.opendaylight.controller.cluster.datastore.identifiers.TransactionIdentifier;
28 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
29 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
30 import org.opendaylight.controller.cluster.datastore.utils.NormalizedNodeAggregator;
31 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
32 import org.opendaylight.controller.sal.core.spi.data.AbstractDOMStoreTransaction;
33 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
34 import org.opendaylight.yangtools.util.concurrent.MappingCheckedFuture;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import scala.concurrent.Future;
41 import scala.concurrent.Promise;
42
43 /**
44  * A transaction potentially spanning multiple backend shards.
45  */
46 public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIdentifier> implements DOMStoreReadWriteTransaction {
47     private static enum TransactionState {
48         OPEN,
49         READY,
50         CLOSED,
51     }
52     private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
53
54     private final Map<String, TransactionContextWrapper> txContextAdapters = new HashMap<>();
55     private final AbstractTransactionContextFactory<?> txContextFactory;
56     private final OperationLimiter limiter;
57     private final TransactionType type;
58     private TransactionState state = TransactionState.OPEN;
59
60     @VisibleForTesting
61     public TransactionProxy(final AbstractTransactionContextFactory<?> txContextFactory, final TransactionType type) {
62         super(txContextFactory.nextIdentifier(), txContextFactory.getActorContext().getDatastoreContext()
63                 .isTransactionDebugContextEnabled());
64         this.txContextFactory = txContextFactory;
65         this.type = Preconditions.checkNotNull(type);
66
67         // Note : Currently mailbox-capacity comes from akka.conf and not from the config-subsystem
68         this.limiter = new OperationLimiter(getIdentifier(),
69             getActorContext().getTransactionOutstandingOperationLimit(),
70             getActorContext().getDatastoreContext().getOperationTimeoutInSeconds());
71
72         LOG.debug("New {} Tx - {}", type, getIdentifier());
73     }
74
75     @Override
76     public CheckedFuture<Boolean, ReadFailedException> exists(final YangInstanceIdentifier path) {
77         Preconditions.checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
78
79         LOG.debug("Tx {} exists {}", getIdentifier(), path);
80
81         final SettableFuture<Boolean> proxyFuture = SettableFuture.create();
82         TransactionContextWrapper contextAdapter = getContextAdapter(path);
83         contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
84             @Override
85             public void invoke(TransactionContext transactionContext) {
86                 transactionContext.dataExists(path, proxyFuture);
87             }
88         });
89
90         return MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
91     }
92
93     @Override
94     public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final YangInstanceIdentifier path) {
95         Preconditions.checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
96
97         LOG.debug("Tx {} read {}", getIdentifier(), path);
98
99         if (YangInstanceIdentifier.EMPTY.equals(path)) {
100             return readAllData();
101         } else {
102             return singleShardRead(shardNameFromIdentifier(path), path);
103         }
104     }
105
106     private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> singleShardRead(
107             final String shardName, final YangInstanceIdentifier path) {
108         final SettableFuture<Optional<NormalizedNode<?, ?>>> proxyFuture = SettableFuture.create();
109         TransactionContextWrapper contextAdapter = getContextAdapter(shardName);
110         contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
111             @Override
112             public void invoke(TransactionContext transactionContext) {
113                 transactionContext.readData(path, proxyFuture);
114             }
115         });
116
117         return MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
118     }
119
120     private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readAllData() {
121         final Set<String> allShardNames = txContextFactory.getActorContext().getConfiguration().getAllShardNames();
122         final Collection<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>> futures = new ArrayList<>(allShardNames.size());
123
124         for (String shardName : allShardNames) {
125             futures.add(singleShardRead(shardName, YangInstanceIdentifier.EMPTY));
126         }
127
128         final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
129         final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;
130
131         aggregateFuture = Futures.transform(listFuture, new Function<List<Optional<NormalizedNode<?, ?>>>, Optional<NormalizedNode<?, ?>>>() {
132             @Override
133             public Optional<NormalizedNode<?, ?>> apply(final List<Optional<NormalizedNode<?, ?>>> input) {
134                 try {
135                     return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input, txContextFactory.getActorContext().getSchemaContext());
136                 } catch (DataValidationFailedException e) {
137                     throw new IllegalArgumentException("Failed to aggregate", e);
138                 }
139             }
140         });
141
142         return MappingCheckedFuture.create(aggregateFuture, ReadFailedException.MAPPER);
143     }
144
145     @Override
146     public void delete(final YangInstanceIdentifier path) {
147         checkModificationState();
148
149         LOG.debug("Tx {} delete {}", getIdentifier(), path);
150
151         TransactionContextWrapper contextAdapter = getContextAdapter(path);
152         contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
153             @Override
154             public void invoke(TransactionContext transactionContext) {
155                 transactionContext.deleteData(path);
156             }
157         });
158     }
159
160     @Override
161     public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
162         checkModificationState();
163
164         LOG.debug("Tx {} merge {}", getIdentifier(), path);
165
166         TransactionContextWrapper contextAdapter = getContextAdapter(path);
167         contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
168             @Override
169             public void invoke(TransactionContext transactionContext) {
170                 transactionContext.mergeData(path, data);
171             }
172         });
173     }
174
175     @Override
176     public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
177         checkModificationState();
178
179         LOG.debug("Tx {} write {}", getIdentifier(), path);
180
181         TransactionContextWrapper contextAdapter = getContextAdapter(path);
182         contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
183             @Override
184             public void invoke(TransactionContext transactionContext) {
185                 transactionContext.writeData(path, data);
186             }
187         });
188     }
189
190     private void checkModificationState() {
191         Preconditions.checkState(type != TransactionType.READ_ONLY,
192                 "Modification operation on read-only transaction is not allowed");
193         Preconditions.checkState(state == TransactionState.OPEN,
194                 "Transaction is sealed - further modifications are not allowed");
195     }
196
197     private boolean seal(final TransactionState newState) {
198         if (state == TransactionState.OPEN) {
199             state = newState;
200             return true;
201         } else {
202             return false;
203         }
204     }
205
206     @Override
207     public final void close() {
208         if (!seal(TransactionState.CLOSED)) {
209             Preconditions.checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
210                 getIdentifier());
211             // Idempotent no-op as per AutoCloseable recommendation
212             return;
213         }
214
215         for (TransactionContextWrapper contextAdapter : txContextAdapters.values()) {
216             contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
217                 @Override
218                 public void invoke(TransactionContext transactionContext) {
219                     transactionContext.closeTransaction();
220                 }
221             });
222         }
223
224
225         txContextAdapters.clear();
226     }
227
228     @Override
229     public final AbstractThreePhaseCommitCohort<?> ready() {
230         Preconditions.checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
231
232         final boolean success = seal(TransactionState.READY);
233         Preconditions.checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
234
235         LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextAdapters.size());
236
237         final AbstractThreePhaseCommitCohort<?> ret;
238         switch (txContextAdapters.size()) {
239         case 0:
240             ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
241             break;
242         case 1:
243             final Entry<String, TransactionContextWrapper> e = Iterables.getOnlyElement(txContextAdapters.entrySet());
244             ret = createSingleCommitCohort(e.getKey(), e.getValue());
245             break;
246         default:
247             ret = createMultiCommitCohort(txContextAdapters.entrySet());
248         }
249
250         txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
251
252         final Throwable debugContext = getDebugContext();
253         return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
254     }
255
256     private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
257             final TransactionContextWrapper contextAdapter) {
258
259         LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
260
261         final OperationCallback.Reference operationCallbackRef =
262                 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
263
264         final TransactionContext transactionContext = contextAdapter.getTransactionContext();
265         final Future future;
266         if (transactionContext == null) {
267             final Promise promise = akka.dispatch.Futures.promise();
268             contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
269                 @Override
270                 public void invoke(TransactionContext transactionContext) {
271                     promise.completeWith(getReadyOrDirectCommitFuture(transactionContext, operationCallbackRef));
272                 }
273             });
274             future = promise.future();
275         } else {
276             // avoid the creation of a promise and a TransactionOperation
277             future = getReadyOrDirectCommitFuture(transactionContext, operationCallbackRef);
278         }
279
280         return new SingleCommitCohortProxy(txContextFactory.getActorContext(), future, getIdentifier().toString(),
281                 operationCallbackRef);
282     }
283
284     private Future<?> getReadyOrDirectCommitFuture(TransactionContext transactionContext,
285             OperationCallback.Reference operationCallbackRef) {
286         if (transactionContext.supportsDirectCommit()) {
287             TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
288                     txContextFactory.getActorContext());
289             operationCallbackRef.set(rateLimitingCallback);
290             rateLimitingCallback.run();
291             return transactionContext.directCommit();
292         } else {
293             return transactionContext.readyTransaction();
294         }
295     }
296
297     private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort(
298             final Set<Entry<String, TransactionContextWrapper>> txContextAdapterEntries) {
299
300         final List<Future<ActorSelection>> cohortFutures = new ArrayList<>(txContextAdapterEntries.size());
301         for (Entry<String, TransactionContextWrapper> e : txContextAdapterEntries) {
302             LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
303
304             cohortFutures.add(e.getValue().readyTransaction());
305         }
306
307         return new ThreePhaseCommitCohortProxy(txContextFactory.getActorContext(), cohortFutures, getIdentifier().toString());
308     }
309
310     private static String shardNameFromIdentifier(final YangInstanceIdentifier path) {
311         return ShardStrategyFactory.getStrategy(path).findShard(path);
312     }
313
314     private TransactionContextWrapper getContextAdapter(final YangInstanceIdentifier path) {
315         return getContextAdapter(shardNameFromIdentifier(path));
316     }
317
318     private TransactionContextWrapper getContextAdapter(final String shardName) {
319         final TransactionContextWrapper existing = txContextAdapters.get(shardName);
320         if (existing != null) {
321             return existing;
322         }
323
324         final TransactionContextWrapper fresh = txContextFactory.newTransactionAdapter(this, shardName);
325         txContextAdapters.put(shardName, fresh);
326         return fresh;
327     }
328
329     TransactionType getType() {
330         return type;
331     }
332
333     boolean isReady() {
334         return state != TransactionState.OPEN;
335     }
336
337     ActorContext getActorContext() {
338         return txContextFactory.getActorContext();
339     }
340
341     OperationLimiter getLimiter() {
342         return limiter;
343     }
344 }