CDS: Implement front-end support for local 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(), 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             TransactionRateLimitingCallback.adjustRateLimitForUnusedTransaction(txContextFactory.getActorContext());
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         return ret;
260     }
261
262     private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
263             final TransactionContextWrapper contextAdapter) {
264         throttleOperation();
265
266         LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
267
268         final OperationCallback.Reference operationCallbackRef =
269                 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
270
271         final TransactionContext transactionContext = contextAdapter.getTransactionContext();
272         final Future future;
273         if (transactionContext == null) {
274             final Promise promise = akka.dispatch.Futures.promise();
275             contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
276                 @Override
277                 public void invoke(TransactionContext transactionContext) {
278                     promise.completeWith(getReadyOrDirectCommitFuture(transactionContext, operationCallbackRef));
279                 }
280             });
281             future = promise.future();
282         } else {
283             // avoid the creation of a promise and a TransactionOperation
284             future = getReadyOrDirectCommitFuture(transactionContext, operationCallbackRef);
285         }
286
287         return new SingleCommitCohortProxy(txContextFactory.getActorContext(), future, getIdentifier().toString(),
288                 operationCallbackRef);
289     }
290
291     private Future<?> getReadyOrDirectCommitFuture(TransactionContext transactionContext,
292             OperationCallback.Reference operationCallbackRef) {
293         if (transactionContext.supportsDirectCommit()) {
294             TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
295                     txContextFactory.getActorContext());
296             operationCallbackRef.set(rateLimitingCallback);
297             rateLimitingCallback.run();
298             return transactionContext.directCommit();
299         } else {
300             return transactionContext.readyTransaction();
301         }
302     }
303
304     private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort(
305             final Set<Entry<String, TransactionContextWrapper>> txContextAdapterEntries) {
306
307         throttleOperation();
308         final List<Future<ActorSelection>> cohortFutures = new ArrayList<>(txContextAdapterEntries.size());
309         for (Entry<String, TransactionContextWrapper> e : txContextAdapterEntries) {
310             LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
311
312             TransactionContextWrapper contextAdapter = e.getValue();
313             final TransactionContext transactionContext = contextAdapter.getTransactionContext();
314             Future<ActorSelection> future;
315             if (transactionContext != null) {
316                 // avoid the creation of a promise and a TransactionOperation
317                 future = transactionContext.readyTransaction();
318             } else {
319                 final Promise<ActorSelection> promise = akka.dispatch.Futures.promise();
320                 contextAdapter.maybeExecuteTransactionOperation(new TransactionOperation() {
321                     @Override
322                     public void invoke(TransactionContext transactionContext) {
323                         promise.completeWith(transactionContext.readyTransaction());
324                     }
325                 });
326
327                 future = promise.future();
328             }
329
330             cohortFutures.add(future);
331         }
332
333         return new ThreePhaseCommitCohortProxy(txContextFactory.getActorContext(), cohortFutures, getIdentifier().toString());
334     }
335
336     private static String shardNameFromIdentifier(final YangInstanceIdentifier path) {
337         return ShardStrategyFactory.getStrategy(path).findShard(path);
338     }
339
340     private TransactionContextWrapper getContextAdapter(final YangInstanceIdentifier path) {
341         return getContextAdapter(shardNameFromIdentifier(path));
342     }
343
344     private TransactionContextWrapper getContextAdapter(final String shardName) {
345         final TransactionContextWrapper existing = txContextAdapters.get(shardName);
346         if (existing != null) {
347             return existing;
348         }
349
350         final TransactionContextWrapper fresh = txContextFactory.newTransactionAdapter(this, shardName);
351         txContextAdapters.put(shardName, fresh);
352         return fresh;
353     }
354
355     TransactionType getType() {
356         return type;
357     }
358
359     boolean isReady() {
360         return state != TransactionState.OPEN;
361     }
362
363     ActorContext getActorContext() {
364         return txContextFactory.getActorContext();
365     }
366
367     OperationCompleter getCompleter() {
368         OperationCompleter ret = operationCompleter;
369         if (ret == null) {
370             final Semaphore s = getLimiter();
371             ret = new OperationCompleter(s);
372             operationCompleter = ret;
373         }
374
375         return ret;
376     }
377
378     Semaphore getLimiter() {
379         Semaphore ret = operationLimiter;
380         if (ret == null) {
381             // Note : Currently mailbox-capacity comes from akka.conf and not from the config-subsystem
382             ret = new Semaphore(getActorContext().getTransactionOutstandingOperationLimit());
383             operationLimiter = ret;
384         }
385         return ret;
386     }
387
388     void throttleOperation() {
389         throttleOperation(1);
390     }
391
392     private void throttleOperation(int acquirePermits) {
393         try {
394             if (!getLimiter().tryAcquire(acquirePermits,
395                 getActorContext().getDatastoreContext().getOperationTimeoutInSeconds(), TimeUnit.SECONDS)){
396                 LOG.warn("Failed to acquire operation permit for transaction {}", getIdentifier());
397             }
398         } catch (InterruptedException e) {
399             if (LOG.isDebugEnabled()) {
400                 LOG.debug("Interrupted when trying to acquire operation permit for transaction {}", getIdentifier(), e);
401             } else {
402                 LOG.warn("Interrupted when trying to acquire operation permit for transaction {}", getIdentifier());
403             }
404         }
405     }
406 }