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