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