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