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.mdsal.common.api.MappingCheckedFuture;
42 import org.opendaylight.mdsal.common.api.ReadFailedException;
43 import org.opendaylight.mdsal.dom.spi.store.AbstractDOMStoreTransaction;
44 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
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         Preconditions.checkNotNull(path, "path should not be null");
110
111         LOG.trace("Tx {} read {}", getIdentifier(), path);
112         return path.isEmpty() ? readAllData() :  singleShardRead(shardNameFromIdentifier(path), path);
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             }, MoreExecutors.directExecutor());
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.trace("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(final TransactionContext transactionContext, final Boolean havePermit) {
171                 transactionContext.executeModification(modification, havePermit);
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(final TransactionContext transactionContext, final Boolean havePermit) {
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();
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(final TransactionContext newTransactionContext, final Boolean havePermit) {
259                     promise.completeWith(getDirectCommitFuture(newTransactionContext, operationCallbackRef,
260                         havePermit));
261                 }
262             });
263             future = promise.future();
264         } else {
265             // avoid the creation of a promise and a TransactionOperation
266             future = getDirectCommitFuture(transactionContext, operationCallbackRef, null);
267         }
268
269         return new SingleCommitCohortProxy(txContextFactory.getActorContext(), future, getIdentifier(),
270             operationCallbackRef);
271     }
272
273     private Future<?> getDirectCommitFuture(final TransactionContext transactionContext,
274             final OperationCallback.Reference operationCallbackRef, final Boolean havePermit) {
275         TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
276                 txContextFactory.getActorContext());
277         operationCallbackRef.set(rateLimitingCallback);
278         rateLimitingCallback.run();
279         return transactionContext.directCommit(havePermit);
280     }
281
282     private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort() {
283
284         final List<ThreePhaseCommitCohortProxy.CohortInfo> cohorts = new ArrayList<>(txContextWrappers.size());
285         final java.util.Optional<SortedSet<String>> shardNames =
286                 java.util.Optional.of(new TreeSet<>(txContextWrappers.keySet()));
287         for (Entry<String, TransactionContextWrapper> e : txContextWrappers.entrySet()) {
288             LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
289
290             final TransactionContextWrapper wrapper = e.getValue();
291
292             // The remote tx version is obtained the via TransactionContext which may not be available yet so
293             // we pass a Supplier to dynamically obtain it. Once the ready Future is resolved the
294             // TransactionContext is available.
295             Supplier<Short> txVersionSupplier = () -> wrapper.getTransactionContext().getTransactionVersion();
296
297             cohorts.add(new ThreePhaseCommitCohortProxy.CohortInfo(wrapper.readyTransaction(shardNames),
298                     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 }