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