Move checking/logging out of executeModification()
[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         checkModificationState("delete", path);
142
143         executeModification(new DeleteModification(path));
144     }
145
146     @Override
147     public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
148         checkModificationState("merge", path);
149
150         executeModification(new MergeModification(path, data));
151     }
152
153     @Override
154     public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
155         checkModificationState("write", path);
156
157         executeModification(new WriteModification(path, data));
158     }
159
160     private void executeModification(final AbstractModification modification) {
161         final TransactionContextWrapper contextWrapper = getContextWrapper(modification.getPath());
162         contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
163             @Override
164             protected void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
165                 transactionContext.executeModification(modification, havePermit);
166             }
167         });
168     }
169
170     private void checkModificationState(final String opName, final YangInstanceIdentifier path) {
171         checkState(type != TransactionType.READ_ONLY, "Modification operation on read-only transaction is not allowed");
172         checkState(state == TransactionState.OPEN, "Transaction is sealed - further modifications are not allowed");
173         LOG.trace("Tx {} {} {}", getIdentifier(), opName, path);
174     }
175
176     private boolean seal(final TransactionState newState) {
177         if (state == TransactionState.OPEN) {
178             state = newState;
179             return true;
180         }
181         return false;
182     }
183
184     @Override
185     public final void close() {
186         if (!seal(TransactionState.CLOSED)) {
187             checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
188                 getIdentifier());
189             // Idempotent no-op as per AutoCloseable recommendation
190             return;
191         }
192
193         for (TransactionContextWrapper contextWrapper : txContextWrappers.values()) {
194             contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
195                 @Override
196                 public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
197                     transactionContext.closeTransaction();
198                 }
199             });
200         }
201
202
203         txContextWrappers.clear();
204     }
205
206     @Override
207     public final AbstractThreePhaseCommitCohort<?> ready() {
208         checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
209
210         final boolean success = seal(TransactionState.READY);
211         checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
212
213         LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextWrappers.size());
214
215         final AbstractThreePhaseCommitCohort<?> ret;
216         switch (txContextWrappers.size()) {
217             case 0:
218                 ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
219                 break;
220             case 1:
221                 final Entry<String, TransactionContextWrapper> e = Iterables.getOnlyElement(
222                         txContextWrappers.entrySet());
223                 ret = createSingleCommitCohort(e.getKey(), e.getValue());
224                 break;
225             default:
226                 ret = createMultiCommitCohort();
227         }
228
229         txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
230
231         final Throwable debugContext = getDebugContext();
232         return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
233     }
234
235     @SuppressWarnings({ "rawtypes", "unchecked" })
236     private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
237             final TransactionContextWrapper contextWrapper) {
238
239         LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
240
241         final OperationCallback.Reference operationCallbackRef =
242                 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
243
244         final TransactionContext transactionContext = contextWrapper.getTransactionContext();
245         final Future future;
246         if (transactionContext == null) {
247             final Promise promise = akka.dispatch.Futures.promise();
248             contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
249                 @Override
250                 public void invoke(final TransactionContext newTransactionContext, final Boolean havePermit) {
251                     promise.completeWith(getDirectCommitFuture(newTransactionContext, operationCallbackRef,
252                         havePermit));
253                 }
254             });
255             future = promise.future();
256         } else {
257             // avoid the creation of a promise and a TransactionOperation
258             future = getDirectCommitFuture(transactionContext, operationCallbackRef, null);
259         }
260
261         return new SingleCommitCohortProxy(txContextFactory.getActorUtils(), future, getIdentifier(),
262             operationCallbackRef);
263     }
264
265     private Future<?> getDirectCommitFuture(final TransactionContext transactionContext,
266             final OperationCallback.Reference operationCallbackRef, final Boolean havePermit) {
267         TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
268                 txContextFactory.getActorUtils());
269         operationCallbackRef.set(rateLimitingCallback);
270         rateLimitingCallback.run();
271         return transactionContext.directCommit(havePermit);
272     }
273
274     private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort() {
275
276         final List<ThreePhaseCommitCohortProxy.CohortInfo> cohorts = new ArrayList<>(txContextWrappers.size());
277         final Optional<SortedSet<String>> shardNames = Optional.of(new TreeSet<>(txContextWrappers.keySet()));
278         for (Entry<String, TransactionContextWrapper> e : txContextWrappers.entrySet()) {
279             LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
280
281             final TransactionContextWrapper wrapper = e.getValue();
282
283             // The remote tx version is obtained the via TransactionContext which may not be available yet so
284             // we pass a Supplier to dynamically obtain it. Once the ready Future is resolved the
285             // TransactionContext is available.
286             cohorts.add(new ThreePhaseCommitCohortProxy.CohortInfo(wrapper.readyTransaction(shardNames),
287                 () -> wrapper.getTransactionContext().getTransactionVersion()));
288         }
289
290         return new ThreePhaseCommitCohortProxy(txContextFactory.getActorUtils(), cohorts, getIdentifier());
291     }
292
293     private String shardNameFromIdentifier(final YangInstanceIdentifier path) {
294         return txContextFactory.getActorUtils().getShardStrategyFactory().getStrategy(path).findShard(path);
295     }
296
297     private TransactionContextWrapper getContextWrapper(final YangInstanceIdentifier path) {
298         return getContextWrapper(shardNameFromIdentifier(path));
299     }
300
301     private TransactionContextWrapper getContextWrapper(final String shardName) {
302         final TransactionContextWrapper existing = txContextWrappers.get(shardName);
303         if (existing != null) {
304             return existing;
305         }
306
307         final TransactionContextWrapper fresh = txContextFactory.newTransactionContextWrapper(this, shardName);
308         txContextWrappers.put(shardName, fresh);
309         return fresh;
310     }
311
312     TransactionType getType() {
313         return type;
314     }
315
316     boolean isReady() {
317         return state != TransactionState.OPEN;
318     }
319
320     ActorUtils getActorUtils() {
321         return txContextFactory.getActorUtils();
322     }
323 }