155bb1fd3e303cfe8aa929fb44322bad90e2e949
[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 static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12
13 import akka.actor.ActorSelection;
14 import com.google.common.annotations.VisibleForTesting;
15 import com.google.common.base.Function;
16 import com.google.common.base.Supplier;
17 import com.google.common.collect.Iterables;
18 import com.google.common.util.concurrent.FluentFuture;
19 import com.google.common.util.concurrent.Futures;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.MoreExecutors;
22 import com.google.common.util.concurrent.SettableFuture;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Map.Entry;
28 import java.util.Optional;
29 import java.util.Set;
30 import java.util.SortedSet;
31 import java.util.TreeMap;
32 import java.util.TreeSet;
33 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
34 import org.opendaylight.controller.cluster.datastore.messages.AbstractRead;
35 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
36 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
37 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
38 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
39 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
40 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
41 import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
42 import org.opendaylight.controller.cluster.datastore.utils.NormalizedNodeAggregator;
43 import org.opendaylight.mdsal.dom.spi.store.AbstractDOMStoreTransaction;
44 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import scala.concurrent.Future;
51 import scala.concurrent.Promise;
52
53 /**
54  * A transaction potentially spanning multiple backend shards.
55  */
56 public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIdentifier>
57         implements DOMStoreReadWriteTransaction {
58     private enum TransactionState {
59         OPEN,
60         READY,
61         CLOSED,
62     }
63
64     private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
65
66     private final Map<String, TransactionContextWrapper> txContextWrappers = new TreeMap<>();
67     private final AbstractTransactionContextFactory<?> txContextFactory;
68     private final TransactionType type;
69     private TransactionState state = TransactionState.OPEN;
70
71     @VisibleForTesting
72     public TransactionProxy(final AbstractTransactionContextFactory<?> txContextFactory, final TransactionType type) {
73         super(txContextFactory.nextIdentifier(), txContextFactory.getActorUtils().getDatastoreContext()
74                 .isTransactionDebugContextEnabled());
75         this.txContextFactory = txContextFactory;
76         this.type = requireNonNull(type);
77
78         LOG.debug("New {} Tx - {}", type, getIdentifier());
79     }
80
81     @Override
82     public FluentFuture<Boolean> exists(final YangInstanceIdentifier path) {
83         return executeRead(shardNameFromIdentifier(path), new DataExists(path, DataStoreVersions.CURRENT_VERSION));
84     }
85
86     private <T> FluentFuture<T> executeRead(final String shardName, final AbstractRead<T> readCmd) {
87         checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
88
89         LOG.trace("Tx {} {} {}", getIdentifier(), readCmd.getClass().getSimpleName(), readCmd.getPath());
90
91         final SettableFuture<T> proxyFuture = SettableFuture.create();
92         TransactionContextWrapper contextWrapper = getContextWrapper(shardName);
93         contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
94             @Override
95             public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
96                 transactionContext.executeRead(readCmd, proxyFuture, havePermit);
97             }
98         });
99
100         return FluentFuture.from(proxyFuture);
101     }
102
103     @Override
104     public FluentFuture<Optional<NormalizedNode<?, ?>>> read(final YangInstanceIdentifier path) {
105         checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
106         requireNonNull(path, "path should not be null");
107
108         LOG.trace("Tx {} read {}", getIdentifier(), path);
109         return path.isEmpty() ? readAllData() :  singleShardRead(shardNameFromIdentifier(path), path);
110     }
111
112     private FluentFuture<Optional<NormalizedNode<?, ?>>> singleShardRead(
113             final String shardName, final YangInstanceIdentifier path) {
114         return executeRead(shardName, new ReadData(path, DataStoreVersions.CURRENT_VERSION));
115     }
116
117     private FluentFuture<Optional<NormalizedNode<?, ?>>> readAllData() {
118         final Set<String> allShardNames = txContextFactory.getActorUtils().getConfiguration().getAllShardNames();
119         final Collection<FluentFuture<Optional<NormalizedNode<?, ?>>>> futures = new ArrayList<>(allShardNames.size());
120
121         for (String shardName : allShardNames) {
122             futures.add(singleShardRead(shardName, YangInstanceIdentifier.EMPTY));
123         }
124
125         final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
126         final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;
127
128         aggregateFuture = Futures.transform(listFuture,
129             (Function<List<Optional<NormalizedNode<?, ?>>>, Optional<NormalizedNode<?, ?>>>) input -> {
130                 try {
131                     return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input,
132                             txContextFactory.getActorUtils().getSchemaContext(),
133                             txContextFactory.getActorUtils().getDatastoreContext().getLogicalStoreType());
134                 } catch (DataValidationFailedException e) {
135                     throw new IllegalArgumentException("Failed to aggregate", e);
136                 }
137             }, MoreExecutors.directExecutor());
138
139         return FluentFuture.from(aggregateFuture);
140     }
141
142     @Override
143     public void delete(final YangInstanceIdentifier path) {
144         executeModification(new DeleteModification(path));
145     }
146
147     @Override
148     public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
149         executeModification(new MergeModification(path, data));
150     }
151
152     @Override
153     public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
154         executeModification(new WriteModification(path, data));
155     }
156
157     private void executeModification(final AbstractModification modification) {
158         checkModificationState();
159
160         LOG.trace("Tx {} executeModification {} {}", getIdentifier(), modification.getClass().getSimpleName(),
161                 modification.getPath());
162
163         TransactionContextWrapper contextWrapper = getContextWrapper(modification.getPath());
164         contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
165             @Override
166             protected void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
167                 transactionContext.executeModification(modification, havePermit);
168             }
169         });
170     }
171
172     private void checkModificationState() {
173         checkState(type != TransactionType.READ_ONLY, "Modification operation on read-only transaction is not allowed");
174         checkState(state == TransactionState.OPEN, "Transaction is sealed - further modifications are not allowed");
175     }
176
177     private boolean seal(final TransactionState newState) {
178         if (state == TransactionState.OPEN) {
179             state = newState;
180             return true;
181         } else {
182             return false;
183         }
184     }
185
186     @Override
187     public final void close() {
188         if (!seal(TransactionState.CLOSED)) {
189             checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
190                 getIdentifier());
191             // Idempotent no-op as per AutoCloseable recommendation
192             return;
193         }
194
195         for (TransactionContextWrapper contextWrapper : txContextWrappers.values()) {
196             contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
197                 @Override
198                 public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
199                     transactionContext.closeTransaction();
200                 }
201             });
202         }
203
204
205         txContextWrappers.clear();
206     }
207
208     @Override
209     public final AbstractThreePhaseCommitCohort<?> ready() {
210         checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
211
212         final boolean success = seal(TransactionState.READY);
213         checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
214
215         LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextWrappers.size());
216
217         final AbstractThreePhaseCommitCohort<?> ret;
218         switch (txContextWrappers.size()) {
219             case 0:
220                 ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
221                 break;
222             case 1:
223                 final Entry<String, TransactionContextWrapper> e = Iterables.getOnlyElement(
224                         txContextWrappers.entrySet());
225                 ret = createSingleCommitCohort(e.getKey(), e.getValue());
226                 break;
227             default:
228                 ret = createMultiCommitCohort();
229         }
230
231         txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
232
233         final Throwable debugContext = getDebugContext();
234         return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
235     }
236
237     @SuppressWarnings({ "rawtypes", "unchecked" })
238     private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
239             final TransactionContextWrapper contextWrapper) {
240
241         LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
242
243         final OperationCallback.Reference operationCallbackRef =
244                 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
245
246         final TransactionContext transactionContext = contextWrapper.getTransactionContext();
247         final Future future;
248         if (transactionContext == null) {
249             final Promise promise = akka.dispatch.Futures.promise();
250             contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
251                 @Override
252                 public void invoke(final TransactionContext newTransactionContext, final Boolean havePermit) {
253                     promise.completeWith(getDirectCommitFuture(newTransactionContext, operationCallbackRef,
254                         havePermit));
255                 }
256             });
257             future = promise.future();
258         } else {
259             // avoid the creation of a promise and a TransactionOperation
260             future = getDirectCommitFuture(transactionContext, operationCallbackRef, null);
261         }
262
263         return new SingleCommitCohortProxy(txContextFactory.getActorUtils(), future, getIdentifier(),
264             operationCallbackRef);
265     }
266
267     private Future<?> getDirectCommitFuture(final TransactionContext transactionContext,
268             final OperationCallback.Reference operationCallbackRef, final Boolean havePermit) {
269         TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
270                 txContextFactory.getActorUtils());
271         operationCallbackRef.set(rateLimitingCallback);
272         rateLimitingCallback.run();
273         return transactionContext.directCommit(havePermit);
274     }
275
276     private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort() {
277
278         final List<ThreePhaseCommitCohortProxy.CohortInfo> cohorts = new ArrayList<>(txContextWrappers.size());
279         final Optional<SortedSet<String>> shardNames = Optional.of(new TreeSet<>(txContextWrappers.keySet()));
280         for (Entry<String, TransactionContextWrapper> e : txContextWrappers.entrySet()) {
281             LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
282
283             final TransactionContextWrapper wrapper = e.getValue();
284
285             // The remote tx version is obtained the via TransactionContext which may not be available yet so
286             // we pass a Supplier to dynamically obtain it. Once the ready Future is resolved the
287             // TransactionContext is available.
288             Supplier<Short> txVersionSupplier = () -> wrapper.getTransactionContext().getTransactionVersion();
289
290             cohorts.add(new ThreePhaseCommitCohortProxy.CohortInfo(wrapper.readyTransaction(shardNames),
291                     txVersionSupplier));
292         }
293
294         return new ThreePhaseCommitCohortProxy(txContextFactory.getActorUtils(), cohorts, getIdentifier());
295     }
296
297     private String shardNameFromIdentifier(final YangInstanceIdentifier path) {
298         return txContextFactory.getActorUtils().getShardStrategyFactory().getStrategy(path).findShard(path);
299     }
300
301     private TransactionContextWrapper getContextWrapper(final YangInstanceIdentifier path) {
302         return getContextWrapper(shardNameFromIdentifier(path));
303     }
304
305     private TransactionContextWrapper getContextWrapper(final String shardName) {
306         final TransactionContextWrapper existing = txContextWrappers.get(shardName);
307         if (existing != null) {
308             return existing;
309         }
310
311         final TransactionContextWrapper fresh = txContextFactory.newTransactionContextWrapper(this, shardName);
312         txContextWrappers.put(shardName, fresh);
313         return fresh;
314     }
315
316     TransactionType getType() {
317         return type;
318     }
319
320     boolean isReady() {
321         return state != TransactionState.OPEN;
322     }
323
324     ActorUtils getActorUtils() {
325         return txContextFactory.getActorUtils();
326     }
327 }