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