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