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