Lower verbosity of TransactionProxy logging
[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.controller.md.sal.common.api.data.ReadFailedException;
40 import org.opendaylight.controller.sal.core.spi.data.AbstractDOMStoreTransaction;
41 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
42 import org.opendaylight.mdsal.common.api.MappingCheckedFuture;
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) {
96                 transactionContext.executeRead(readCmd, proxyFuture);
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
108         LOG.trace("Tx {} read {}", getIdentifier(), path);
109
110         if (YangInstanceIdentifier.EMPTY.equals(path)) {
111             return readAllData();
112         } else {
113             return singleShardRead(shardNameFromIdentifier(path), path);
114         }
115     }
116
117     private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> singleShardRead(
118             final String shardName, final YangInstanceIdentifier path) {
119         return executeRead(shardName, new ReadData(path, DataStoreVersions.CURRENT_VERSION));
120     }
121
122     private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readAllData() {
123         final Set<String> allShardNames = txContextFactory.getActorContext().getConfiguration().getAllShardNames();
124         final Collection<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>> futures =
125                 new ArrayList<>(allShardNames.size());
126
127         for (String shardName : allShardNames) {
128             futures.add(singleShardRead(shardName, YangInstanceIdentifier.EMPTY));
129         }
130
131         final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
132         final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;
133
134         aggregateFuture = Futures.transform(listFuture,
135             (Function<List<Optional<NormalizedNode<?, ?>>>, Optional<NormalizedNode<?, ?>>>) input -> {
136                 try {
137                     return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input,
138                             txContextFactory.getActorContext().getSchemaContext(),
139                             txContextFactory.getActorContext().getDatastoreContext().getLogicalStoreType());
140                 } catch (DataValidationFailedException e) {
141                     throw new IllegalArgumentException("Failed to aggregate", e);
142                 }
143             }, MoreExecutors.directExecutor());
144
145         return MappingCheckedFuture.create(aggregateFuture, ReadFailedException.MAPPER);
146     }
147
148     @Override
149     public void delete(final YangInstanceIdentifier path) {
150         executeModification(new DeleteModification(path));
151     }
152
153     @Override
154     public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
155         executeModification(new MergeModification(path, data));
156     }
157
158     @Override
159     public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
160         executeModification(new WriteModification(path, data));
161     }
162
163     private void executeModification(final AbstractModification modification) {
164         checkModificationState();
165
166         LOG.trace("Tx {} executeModification {} {}", getIdentifier(), modification.getClass().getSimpleName(),
167                 modification.getPath());
168
169         TransactionContextWrapper contextWrapper = getContextWrapper(modification.getPath());
170         contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
171             @Override
172             protected void invoke(final TransactionContext transactionContext) {
173                 transactionContext.executeModification(modification);
174             }
175         });
176     }
177
178     private void checkModificationState() {
179         Preconditions.checkState(type != TransactionType.READ_ONLY,
180                 "Modification operation on read-only transaction is not allowed");
181         Preconditions.checkState(state == TransactionState.OPEN,
182                 "Transaction is sealed - further modifications are not allowed");
183     }
184
185     private boolean seal(final TransactionState newState) {
186         if (state == TransactionState.OPEN) {
187             state = newState;
188             return true;
189         } else {
190             return false;
191         }
192     }
193
194     @Override
195     public final void close() {
196         if (!seal(TransactionState.CLOSED)) {
197             Preconditions.checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
198                 getIdentifier());
199             // Idempotent no-op as per AutoCloseable recommendation
200             return;
201         }
202
203         for (TransactionContextWrapper contextWrapper : txContextWrappers.values()) {
204             contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
205                 @Override
206                 public void invoke(final TransactionContext transactionContext) {
207                     transactionContext.closeTransaction();
208                 }
209             });
210         }
211
212
213         txContextWrappers.clear();
214     }
215
216     @Override
217     public final AbstractThreePhaseCommitCohort<?> ready() {
218         Preconditions.checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
219
220         final boolean success = seal(TransactionState.READY);
221         Preconditions.checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
222
223         LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextWrappers.size());
224
225         final AbstractThreePhaseCommitCohort<?> ret;
226         switch (txContextWrappers.size()) {
227             case 0:
228                 ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
229                 break;
230             case 1:
231                 final Entry<String, TransactionContextWrapper> e = Iterables.getOnlyElement(
232                         txContextWrappers.entrySet());
233                 ret = createSingleCommitCohort(e.getKey(), e.getValue());
234                 break;
235             default:
236                 ret = createMultiCommitCohort(txContextWrappers.entrySet());
237         }
238
239         txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
240
241         final Throwable debugContext = getDebugContext();
242         return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
243     }
244
245     @SuppressWarnings({ "rawtypes", "unchecked" })
246     private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
247             final TransactionContextWrapper contextWrapper) {
248
249         LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
250
251         final OperationCallback.Reference operationCallbackRef =
252                 new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
253
254         final TransactionContext transactionContext = contextWrapper.getTransactionContext();
255         final Future future;
256         if (transactionContext == null) {
257             final Promise promise = akka.dispatch.Futures.promise();
258             contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
259                 @Override
260                 public void invoke(final TransactionContext newTransactionContext) {
261                     promise.completeWith(getDirectCommitFuture(newTransactionContext, operationCallbackRef));
262                 }
263             });
264             future = promise.future();
265         } else {
266             // avoid the creation of a promise and a TransactionOperation
267             future = getDirectCommitFuture(transactionContext, operationCallbackRef);
268         }
269
270         return new SingleCommitCohortProxy(txContextFactory.getActorContext(), future, getIdentifier(),
271             operationCallbackRef);
272     }
273
274     private Future<?> getDirectCommitFuture(final TransactionContext transactionContext,
275             final OperationCallback.Reference operationCallbackRef) {
276         TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
277                 txContextFactory.getActorContext());
278         operationCallbackRef.set(rateLimitingCallback);
279         rateLimitingCallback.run();
280         return transactionContext.directCommit();
281     }
282
283     private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort(
284             final Set<Entry<String, TransactionContextWrapper>> txContextWrapperEntries) {
285
286         final List<ThreePhaseCommitCohortProxy.CohortInfo> cohorts = new ArrayList<>(txContextWrapperEntries.size());
287         for (Entry<String, TransactionContextWrapper> e : txContextWrapperEntries) {
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(), txVersionSupplier));
298         }
299
300         return new ThreePhaseCommitCohortProxy(txContextFactory.getActorContext(), cohorts, getIdentifier());
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 }