Convert OperationCompleter to OperationLimiter
[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         limiter.acquire();
82
83         final SettableFuture<Boolean> proxyFuture = SettableFuture.create();
84         TransactionContextWrapper contextAdapter = getContextAdapter(path);
85         contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
86             @Override
87             public void invoke(TransactionContext transactionContext) {
88                 transactionContext.dataExists(path, proxyFuture);
89             }
90         });
91
92         return MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
93     }
94
95     @Override
96     public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final YangInstanceIdentifier path) {
97         Preconditions.checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
98
99         LOG.debug("Tx {} read {}", getIdentifier(), path);
100
101         if (YangInstanceIdentifier.EMPTY.equals(path)) {
102             return readAllData();
103         } else {
104             limiter.acquire();
105
106             return singleShardRead(shardNameFromIdentifier(path), path);
107         }
108     }
109
110     private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> singleShardRead(
111             final String shardName, final YangInstanceIdentifier path) {
112         final SettableFuture<Optional<NormalizedNode<?, ?>>> proxyFuture = SettableFuture.create();
113         TransactionContextWrapper contextAdapter = getContextAdapter(shardName);
114         contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
115             @Override
116             public void invoke(TransactionContext transactionContext) {
117                 transactionContext.readData(path, proxyFuture);
118             }
119         });
120
121         return MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
122     }
123
124     private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readAllData() {
125         final Set<String> allShardNames = txContextFactory.getActorContext().getConfiguration().getAllShardNames();
126         final Collection<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>> futures = new ArrayList<>(allShardNames.size());
127
128         for (String shardName : allShardNames) {
129             futures.add(singleShardRead(shardName, YangInstanceIdentifier.EMPTY));
130         }
131
132         final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
133         final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;
134
135         aggregateFuture = Futures.transform(listFuture, new Function<List<Optional<NormalizedNode<?, ?>>>, Optional<NormalizedNode<?, ?>>>() {
136             @Override
137             public Optional<NormalizedNode<?, ?>> apply(final List<Optional<NormalizedNode<?, ?>>> input) {
138                 try {
139                     return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input, txContextFactory.getActorContext().getSchemaContext());
140                 } catch (DataValidationFailedException e) {
141                     throw new IllegalArgumentException("Failed to aggregate", e);
142                 }
143             }
144         });
145
146         return MappingCheckedFuture.create(aggregateFuture, ReadFailedException.MAPPER);
147     }
148
149     @Override
150     public void delete(final YangInstanceIdentifier path) {
151         checkModificationState();
152
153         LOG.debug("Tx {} delete {}", getIdentifier(), path);
154
155         limiter.acquire();
156
157         TransactionContextWrapper contextAdapter = getContextAdapter(path);
158         contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
159             @Override
160             public void invoke(TransactionContext transactionContext) {
161                 transactionContext.deleteData(path);
162             }
163         });
164     }
165
166     @Override
167     public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
168         checkModificationState();
169
170         LOG.debug("Tx {} merge {}", getIdentifier(), path);
171
172         limiter.acquire();
173
174         TransactionContextWrapper contextAdapter = getContextAdapter(path);
175         contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
176             @Override
177             public void invoke(TransactionContext transactionContext) {
178                 transactionContext.mergeData(path, data);
179             }
180         });
181     }
182
183     @Override
184     public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
185         checkModificationState();
186
187         LOG.debug("Tx {} write {}", getIdentifier(), path);
188
189         limiter.acquire();
190
191         TransactionContextWrapper contextAdapter = getContextAdapter(path);
192         contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
193             @Override
194             public void invoke(TransactionContext transactionContext) {
195                 transactionContext.writeData(path, data);
196             }
197         });
198     }
199
200     private void checkModificationState() {
201         Preconditions.checkState(type != TransactionType.READ_ONLY,
202                 "Modification operation on read-only transaction is not allowed");
203         Preconditions.checkState(state == TransactionState.OPEN,
204                 "Transaction is sealed - further modifications are not allowed");
205     }
206
207     private boolean seal(final TransactionState newState) {
208         if (state == TransactionState.OPEN) {
209             state = newState;
210             return true;
211         } else {
212             return false;
213         }
214     }
215
216     @Override
217     public final void close() {
218         if (!seal(TransactionState.CLOSED)) {
219             Preconditions.checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
220                 getIdentifier());
221             // Idempotent no-op as per AutoCloseable recommendation
222             return;
223         }
224
225         for (TransactionContextWrapper contextAdapter : txContextAdapters.values()) {
226             contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
227                 @Override
228                 public void invoke(TransactionContext transactionContext) {
229                     transactionContext.closeTransaction();
230                 }
231             });
232         }
233
234
235         txContextAdapters.clear();
236     }
237
238     @Override
239     public final AbstractThreePhaseCommitCohort<?> ready() {
240         Preconditions.checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
241
242         final boolean success = seal(TransactionState.READY);
243         Preconditions.checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
244
245         LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextAdapters.size());
246
247         final AbstractThreePhaseCommitCohort<?> ret;
248         switch (txContextAdapters.size()) {
249         case 0:
250             ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
251             break;
252         case 1:
253             final Entry<String, TransactionContextWrapper> e = Iterables.getOnlyElement(txContextAdapters.entrySet());
254             ret = createSingleCommitCohort(e.getKey(), e.getValue());
255             break;
256         default:
257             ret = createMultiCommitCohort(txContextAdapters.entrySet());
258         }
259
260         txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
261
262         final Throwable debugContext = getDebugContext();
263         return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
264     }
265
266     private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
267             final TransactionContextWrapper contextAdapter) {
268         limiter.acquire();
269
270         LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
271
272         final OperationCallback.Reference operationCallbackRef =
273                 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
274
275         final TransactionContext transactionContext = contextAdapter.getTransactionContext();
276         final Future future;
277         if (transactionContext == null) {
278             final Promise promise = akka.dispatch.Futures.promise();
279             contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
280                 @Override
281                 public void invoke(TransactionContext transactionContext) {
282                     promise.completeWith(getReadyOrDirectCommitFuture(transactionContext, operationCallbackRef));
283                 }
284             });
285             future = promise.future();
286         } else {
287             // avoid the creation of a promise and a TransactionOperation
288             future = getReadyOrDirectCommitFuture(transactionContext, operationCallbackRef);
289         }
290
291         return new SingleCommitCohortProxy(txContextFactory.getActorContext(), future, getIdentifier().toString(),
292                 operationCallbackRef);
293     }
294
295     private Future<?> getReadyOrDirectCommitFuture(TransactionContext transactionContext,
296             OperationCallback.Reference operationCallbackRef) {
297         if (transactionContext.supportsDirectCommit()) {
298             TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
299                     txContextFactory.getActorContext());
300             operationCallbackRef.set(rateLimitingCallback);
301             rateLimitingCallback.run();
302             return transactionContext.directCommit();
303         } else {
304             return transactionContext.readyTransaction();
305         }
306     }
307
308     private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort(
309             final Set<Entry<String, TransactionContextWrapper>> txContextAdapterEntries) {
310
311         limiter.acquire();
312         final List<Future<ActorSelection>> cohortFutures = new ArrayList<>(txContextAdapterEntries.size());
313         for (Entry<String, TransactionContextWrapper> e : txContextAdapterEntries) {
314             LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
315
316             TransactionContextWrapper contextAdapter = e.getValue();
317             final TransactionContext transactionContext = contextAdapter.getTransactionContext();
318             Future<ActorSelection> future;
319             if (transactionContext != null) {
320                 // avoid the creation of a promise and a TransactionOperation
321                 future = transactionContext.readyTransaction();
322             } else {
323                 final Promise<ActorSelection> promise = akka.dispatch.Futures.promise();
324                 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
325                     @Override
326                     public void invoke(TransactionContext transactionContext) {
327                         promise.completeWith(transactionContext.readyTransaction());
328                     }
329                 });
330
331                 future = promise.future();
332             }
333
334             cohortFutures.add(future);
335         }
336
337         return new ThreePhaseCommitCohortProxy(txContextFactory.getActorContext(), cohortFutures, getIdentifier().toString());
338     }
339
340     private static String shardNameFromIdentifier(final YangInstanceIdentifier path) {
341         return ShardStrategyFactory.getStrategy(path).findShard(path);
342     }
343
344     private TransactionContextWrapper getContextAdapter(final YangInstanceIdentifier path) {
345         return getContextAdapter(shardNameFromIdentifier(path));
346     }
347
348     private TransactionContextWrapper getContextAdapter(final String shardName) {
349         final TransactionContextWrapper existing = txContextAdapters.get(shardName);
350         if (existing != null) {
351             return existing;
352         }
353
354         final TransactionContextWrapper fresh = txContextFactory.newTransactionAdapter(this, shardName);
355         txContextAdapters.put(shardName, fresh);
356         return fresh;
357     }
358
359     TransactionType getType() {
360         return type;
361     }
362
363     boolean isReady() {
364         return state != TransactionState.OPEN;
365     }
366
367     ActorContext getActorContext() {
368         return txContextFactory.getActorContext();
369     }
370
371     OperationLimiter getLimiter() {
372         return limiter;
373     }
374 }