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