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