BUG-5280: switch transactionIdentifier
[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.cluster.datastore.utils.TransactionIdentifierUtils;
39 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
40 import org.opendaylight.controller.sal.core.spi.data.AbstractDOMStoreTransaction;
41 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
42 import org.opendaylight.yangtools.util.concurrent.MappingCheckedFuture;
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> implements DOMStoreReadWriteTransaction {
55     private static enum TransactionState {
56         OPEN,
57         READY,
58         CLOSED,
59     }
60     private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
61
62     private final Map<String, TransactionContextWrapper> txContextWrappers = new HashMap<>();
63     private final AbstractTransactionContextFactory<?> txContextFactory;
64     private final TransactionType type;
65     private TransactionState state = TransactionState.OPEN;
66
67     @VisibleForTesting
68     public TransactionProxy(final AbstractTransactionContextFactory<?> txContextFactory, final TransactionType type) {
69         super(txContextFactory.nextIdentifier(), txContextFactory.getActorContext().getDatastoreContext()
70                 .isTransactionDebugContextEnabled());
71         this.txContextFactory = txContextFactory;
72         this.type = Preconditions.checkNotNull(type);
73
74         LOG.debug("New {} Tx - {}", type, getIdentifier());
75     }
76
77     @Override
78     public CheckedFuture<Boolean, ReadFailedException> exists(final YangInstanceIdentifier path) {
79         return executeRead(shardNameFromIdentifier(path), new DataExists(path, DataStoreVersions.CURRENT_VERSION));
80     }
81
82     private <T> CheckedFuture<T, ReadFailedException> executeRead(String shardName, final AbstractRead<T> readCmd) {
83         Preconditions.checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
84
85         if(LOG.isDebugEnabled()) {
86             LOG.debug("Tx {} {} {}", getIdentifier(), readCmd.getClass().getSimpleName(), readCmd.getPath());
87         }
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, "Reads from write-only transactions are not allowed");
104
105         LOG.debug("Tx {} read {}", getIdentifier(), path);
106
107         if (YangInstanceIdentifier.EMPTY.equals(path)) {
108             return readAllData();
109         } else {
110             return singleShardRead(shardNameFromIdentifier(path), path);
111         }
112     }
113
114     private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> singleShardRead(
115             final String shardName, final YangInstanceIdentifier path) {
116         return executeRead(shardName, new ReadData(path, DataStoreVersions.CURRENT_VERSION));
117     }
118
119     private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readAllData() {
120         final Set<String> allShardNames = txContextFactory.getActorContext().getConfiguration().getAllShardNames();
121         final Collection<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>> futures = new ArrayList<>(allShardNames.size());
122
123         for (String shardName : allShardNames) {
124             futures.add(singleShardRead(shardName, YangInstanceIdentifier.EMPTY));
125         }
126
127         final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
128         final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;
129
130         aggregateFuture = Futures.transform(listFuture, new Function<List<Optional<NormalizedNode<?, ?>>>, Optional<NormalizedNode<?, ?>>>() {
131             @Override
132             public Optional<NormalizedNode<?, ?>> apply(final List<Optional<NormalizedNode<?, ?>>> input) {
133                 try {
134                     return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input, txContextFactory.getActorContext().getSchemaContext());
135                 } catch (DataValidationFailedException e) {
136                     throw new IllegalArgumentException("Failed to aggregate", e);
137                 }
138             }
139         });
140
141         return MappingCheckedFuture.create(aggregateFuture, ReadFailedException.MAPPER);
142     }
143
144     @Override
145     public void delete(final YangInstanceIdentifier path) {
146         executeModification(new DeleteModification(path));
147     }
148
149     @Override
150     public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
151         executeModification(new MergeModification(path, data));
152     }
153
154     @Override
155     public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
156         executeModification(new WriteModification(path, data));
157     }
158
159     private void executeModification(final AbstractModification modification) {
160         checkModificationState();
161
162         if(LOG.isDebugEnabled()) {
163             LOG.debug("Tx {} executeModification {} {}", getIdentifier(), modification.getClass().getSimpleName(),
164                     modification.getPath());
165         }
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(txContextWrappers.entrySet());
230             ret = createSingleCommitCohort(e.getKey(), e.getValue());
231             break;
232         default:
233             ret = createMultiCommitCohort(txContextWrappers.entrySet());
234         }
235
236         txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
237
238         final Throwable debugContext = getDebugContext();
239         return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
240     }
241
242     @SuppressWarnings({ "rawtypes", "unchecked" })
243     private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
244             final TransactionContextWrapper contextWrapper) {
245
246         LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
247
248         final OperationCallback.Reference operationCallbackRef =
249                 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
250
251         final TransactionContext transactionContext = contextWrapper.getTransactionContext();
252         final Future future;
253         if (transactionContext == null) {
254             final Promise promise = akka.dispatch.Futures.promise();
255             contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
256                 @Override
257                 public void invoke(TransactionContext transactionContext) {
258                     promise.completeWith(getDirectCommitFuture(transactionContext, operationCallbackRef));
259                 }
260             });
261             future = promise.future();
262         } else {
263             // avoid the creation of a promise and a TransactionOperation
264             future = getDirectCommitFuture(transactionContext, operationCallbackRef);
265         }
266
267         return new SingleCommitCohortProxy(txContextFactory.getActorContext(), future, getIdentifier(),
268             operationCallbackRef);
269     }
270
271     private Future<?> getDirectCommitFuture(TransactionContext transactionContext,
272             OperationCallback.Reference operationCallbackRef) {
273         TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
274                 txContextFactory.getActorContext());
275         operationCallbackRef.set(rateLimitingCallback);
276         rateLimitingCallback.run();
277         return transactionContext.directCommit();
278     }
279
280     private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort(
281             final Set<Entry<String, TransactionContextWrapper>> txContextWrapperEntries) {
282
283         final List<ThreePhaseCommitCohortProxy.CohortInfo> cohorts = new ArrayList<>(txContextWrapperEntries.size());
284         for (Entry<String, TransactionContextWrapper> e : txContextWrapperEntries) {
285             LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
286
287             final TransactionContextWrapper wrapper = e.getValue();
288
289             // The remote tx version is obtained the via TransactionContext which may not be available yet so
290             // we pass a Supplier to dynamically obtain it. Once the ready Future is resolved the
291             // TransactionContext is available.
292             Supplier<Short> txVersionSupplier = new Supplier<Short>() {
293                 @Override
294                 public Short get() {
295                     return wrapper.getTransactionContext().getTransactionVersion();
296                 }
297             };
298
299             cohorts.add(new ThreePhaseCommitCohortProxy.CohortInfo(wrapper.readyTransaction(), txVersionSupplier));
300         }
301
302         return new ThreePhaseCommitCohortProxy(txContextFactory.getActorContext(), cohorts,
303                 TransactionIdentifierUtils.actorNameFor(getIdentifier()));
304     }
305
306     private String shardNameFromIdentifier(final YangInstanceIdentifier path) {
307         return txContextFactory.getActorContext().getShardStrategyFactory().getStrategy(path).findShard(path);
308     }
309
310     private TransactionContextWrapper getContextWrapper(final YangInstanceIdentifier path) {
311         return getContextWrapper(shardNameFromIdentifier(path));
312     }
313
314     private TransactionContextWrapper getContextWrapper(final String shardName) {
315         final TransactionContextWrapper existing = txContextWrappers.get(shardName);
316         if (existing != null) {
317             return existing;
318         }
319
320         final TransactionContextWrapper fresh = txContextFactory.newTransactionContextWrapper(this, shardName);
321         txContextWrappers.put(shardName, fresh);
322         return fresh;
323     }
324
325     TransactionType getType() {
326         return type;
327     }
328
329     boolean isReady() {
330         return state != TransactionState.OPEN;
331     }
332
333     ActorContext getActorContext() {
334         return txContextFactory.getActorContext();
335     }
336 }