Use YangInstanceIdentifier.isEmpty()
[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.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Map.Entry;
28 import java.util.Set;
29 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
30 import org.opendaylight.controller.cluster.datastore.messages.AbstractRead;
31 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
32 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
33 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
34 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
35 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
36 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
37 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
38 import org.opendaylight.controller.cluster.datastore.utils.NormalizedNodeAggregator;
39 import org.opendaylight.mdsal.common.api.MappingCheckedFuture;
40 import org.opendaylight.mdsal.common.api.ReadFailedException;
41 import org.opendaylight.mdsal.dom.spi.store.AbstractDOMStoreTransaction;
42 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import scala.concurrent.Future;
49 import scala.concurrent.Promise;
50
51 /**
52  * A transaction potentially spanning multiple backend shards.
53  */
54 public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIdentifier>
55         implements DOMStoreReadWriteTransaction {
56     private enum TransactionState {
57         OPEN,
58         READY,
59         CLOSED,
60     }
61
62     private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
63
64     private final Map<String, TransactionContextWrapper> txContextWrappers = new HashMap<>();
65     private final AbstractTransactionContextFactory<?> txContextFactory;
66     private final TransactionType type;
67     private TransactionState state = TransactionState.OPEN;
68
69     @VisibleForTesting
70     public TransactionProxy(final AbstractTransactionContextFactory<?> txContextFactory, final TransactionType type) {
71         super(txContextFactory.nextIdentifier(), txContextFactory.getActorContext().getDatastoreContext()
72                 .isTransactionDebugContextEnabled());
73         this.txContextFactory = txContextFactory;
74         this.type = Preconditions.checkNotNull(type);
75
76         LOG.debug("New {} Tx - {}", type, getIdentifier());
77     }
78
79     @Override
80     public CheckedFuture<Boolean, ReadFailedException> exists(final YangInstanceIdentifier path) {
81         return executeRead(shardNameFromIdentifier(path), new DataExists(path, DataStoreVersions.CURRENT_VERSION));
82     }
83
84     private <T> CheckedFuture<T, ReadFailedException> executeRead(final String shardName,
85             final AbstractRead<T> readCmd) {
86         Preconditions.checkState(type != TransactionType.WRITE_ONLY,
87                 "Reads from write-only transactions are not allowed");
88
89         LOG.trace("Tx {} {} {}", getIdentifier(), readCmd.getClass().getSimpleName(), readCmd.getPath());
90
91         final SettableFuture<T> proxyFuture = SettableFuture.create();
92         TransactionContextWrapper contextWrapper = getContextWrapper(shardName);
93         contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
94             @Override
95             public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
96                 transactionContext.executeRead(readCmd, proxyFuture, havePermit);
97             }
98         });
99
100         return MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER);
101     }
102
103     @Override
104     public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final YangInstanceIdentifier path) {
105         Preconditions.checkState(type != TransactionType.WRITE_ONLY,
106                 "Reads from write-only transactions are not allowed");
107         Preconditions.checkNotNull(path, "path should not be null");
108
109         LOG.trace("Tx {} read {}", getIdentifier(), path);
110         return path.isEmpty() ? readAllData() :  singleShardRead(shardNameFromIdentifier(path), path);
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 =
121                 new ArrayList<>(allShardNames.size());
122
123         for (String shardName : allShardNames) {
124             futures.add(singleShardRead(shardName, YangInstanceIdentifier.EMPTY));
125         }
126
127         final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
128         final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;
129
130         aggregateFuture = Futures.transform(listFuture,
131             (Function<List<Optional<NormalizedNode<?, ?>>>, Optional<NormalizedNode<?, ?>>>) input -> {
132                 try {
133                     return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input,
134                             txContextFactory.getActorContext().getSchemaContext(),
135                             txContextFactory.getActorContext().getDatastoreContext().getLogicalStoreType());
136                 } catch (DataValidationFailedException e) {
137                     throw new IllegalArgumentException("Failed to aggregate", e);
138                 }
139             }, MoreExecutors.directExecutor());
140
141         return MappingCheckedFuture.create(aggregateFuture, ReadFailedException.MAPPER);
142     }
143
144     @Override
145     public void delete(final YangInstanceIdentifier path) {
146         executeModification(new DeleteModification(path));
147     }
148
149     @Override
150     public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
151         executeModification(new MergeModification(path, data));
152     }
153
154     @Override
155     public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
156         executeModification(new WriteModification(path, data));
157     }
158
159     private void executeModification(final AbstractModification modification) {
160         checkModificationState();
161
162         LOG.trace("Tx {} executeModification {} {}", getIdentifier(), modification.getClass().getSimpleName(),
163                 modification.getPath());
164
165         TransactionContextWrapper contextWrapper = getContextWrapper(modification.getPath());
166         contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
167             @Override
168             protected void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
169                 transactionContext.executeModification(modification, havePermit);
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(final TransactionContext transactionContext, final Boolean havePermit) {
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(
228                         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(final TransactionContext newTransactionContext, final Boolean havePermit) {
257                     promise.completeWith(getDirectCommitFuture(newTransactionContext, operationCallbackRef,
258                         havePermit));
259                 }
260             });
261             future = promise.future();
262         } else {
263             // avoid the creation of a promise and a TransactionOperation
264             future = getDirectCommitFuture(transactionContext, operationCallbackRef, null);
265         }
266
267         return new SingleCommitCohortProxy(txContextFactory.getActorContext(), future, getIdentifier(),
268             operationCallbackRef);
269     }
270
271     private Future<?> getDirectCommitFuture(final TransactionContext transactionContext,
272             final OperationCallback.Reference operationCallbackRef, final Boolean havePermit) {
273         TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
274                 txContextFactory.getActorContext());
275         operationCallbackRef.set(rateLimitingCallback);
276         rateLimitingCallback.run();
277         return transactionContext.directCommit(havePermit);
278     }
279
280     private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort(
281             final Set<Entry<String, TransactionContextWrapper>> txContextWrapperEntries) {
282
283         final List<ThreePhaseCommitCohortProxy.CohortInfo> cohorts = new ArrayList<>(txContextWrapperEntries.size());
284         for (Entry<String, TransactionContextWrapper> e : txContextWrapperEntries) {
285             LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
286
287             final TransactionContextWrapper wrapper = e.getValue();
288
289             // The remote tx version is obtained the via TransactionContext which may not be available yet so
290             // we pass a Supplier to dynamically obtain it. Once the ready Future is resolved the
291             // TransactionContext is available.
292             Supplier<Short> txVersionSupplier = () -> wrapper.getTransactionContext().getTransactionVersion();
293
294             cohorts.add(new ThreePhaseCommitCohortProxy.CohortInfo(wrapper.readyTransaction(), txVersionSupplier));
295         }
296
297         return new ThreePhaseCommitCohortProxy(txContextFactory.getActorContext(), cohorts, getIdentifier());
298     }
299
300     private String shardNameFromIdentifier(final YangInstanceIdentifier path) {
301         return txContextFactory.getActorContext().getShardStrategyFactory().getStrategy(path).findShard(path);
302     }
303
304     private TransactionContextWrapper getContextWrapper(final YangInstanceIdentifier path) {
305         return getContextWrapper(shardNameFromIdentifier(path));
306     }
307
308     private TransactionContextWrapper getContextWrapper(final String shardName) {
309         final TransactionContextWrapper existing = txContextWrappers.get(shardName);
310         if (existing != null) {
311             return existing;
312         }
313
314         final TransactionContextWrapper fresh = txContextFactory.newTransactionContextWrapper(this, shardName);
315         txContextWrappers.put(shardName, fresh);
316         return fresh;
317     }
318
319     TransactionType getType() {
320         return type;
321     }
322
323     boolean isReady() {
324         return state != TransactionState.OPEN;
325     }
326
327     ActorContext getActorContext() {
328         return txContextFactory.getActorContext();
329     }
330 }