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