2 * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.restconf.nb.rfc8040.rests.transactions;
10 import static java.util.Objects.requireNonNull;
11 import static org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.util.concurrent.FluentFuture;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.Futures;
17 import com.google.common.util.concurrent.ListenableFuture;
18 import com.google.common.util.concurrent.MoreExecutors;
19 import com.google.common.util.concurrent.SettableFuture;
20 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.List;
25 import java.util.Optional;
26 import java.util.StringJoiner;
27 import java.util.function.Supplier;
28 import java.util.stream.Collectors;
29 import org.eclipse.jdt.annotation.NonNull;
30 import org.opendaylight.mdsal.common.api.CommitInfo;
31 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
32 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
33 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
34 import org.opendaylight.netconf.api.DocumentedException;
35 import org.opendaylight.netconf.api.NetconfDocumentedException;
36 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
37 import org.opendaylight.yangtools.yang.common.ErrorSeverity;
38 import org.opendaylight.yangtools.yang.common.RpcError;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
44 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
45 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
49 final class NetconfRestconfTransaction extends RestconfTransaction {
51 private static final Logger LOG = LoggerFactory.getLogger(NetconfRestconfTransaction.class);
53 private final NetconfDataTreeService netconfService;
54 private final List<ListenableFuture<? extends DOMRpcResult>> resultsFutures =
55 Collections.synchronizedList(new ArrayList<>());
56 private volatile boolean isLocked = false;
58 NetconfRestconfTransaction(final NetconfDataTreeService netconfService) {
59 this.netconfService = requireNonNull(netconfService);
60 final ListenableFuture<? extends DOMRpcResult> lockResult = netconfService.lock();
61 Futures.addCallback(lockResult, lockOperationCallback, MoreExecutors.directExecutor());
62 resultsFutures.add(lockResult);
66 public void cancel() {
67 resultsFutures.clear();
68 executeWithLogging(netconfService::discardChanges);
69 executeWithLogging(netconfService::unlock);
73 public void delete(final YangInstanceIdentifier path) {
74 enqueueOperation(() -> netconfService.delete(CONFIGURATION, path));
78 public void remove(final YangInstanceIdentifier path) {
79 enqueueOperation(() -> netconfService.remove(CONFIGURATION, path));
83 public void merge(final YangInstanceIdentifier path, final NormalizedNode data) {
84 enqueueOperation(() -> netconfService.merge(CONFIGURATION, path, data, Optional.empty()));
88 public void create(final YangInstanceIdentifier path, final NormalizedNode data,
89 final SchemaContext schemaContext) {
90 if (data instanceof MapNode || data instanceof LeafSetNode) {
91 final NormalizedNode emptySubTree = ImmutableNodes.fromInstanceId(schemaContext, path);
92 merge(YangInstanceIdentifier.create(emptySubTree.getIdentifier()), emptySubTree);
94 for (final NormalizedNode child : ((NormalizedNodeContainer<?>) data).body()) {
95 final YangInstanceIdentifier childPath = path.node(child.getIdentifier());
96 enqueueOperation(() -> netconfService.create(CONFIGURATION, childPath, child, Optional.empty()));
99 enqueueOperation(() -> netconfService.create(CONFIGURATION, path, data, Optional.empty()));
104 public void replace(final YangInstanceIdentifier path, final NormalizedNode data,
105 final SchemaContext schemaContext) {
106 if (data instanceof MapNode || data instanceof LeafSetNode) {
107 final NormalizedNode emptySubTree = ImmutableNodes.fromInstanceId(schemaContext, path);
108 merge(YangInstanceIdentifier.create(emptySubTree.getIdentifier()), emptySubTree);
110 for (final NormalizedNode child : ((NormalizedNodeContainer<?>) data).body()) {
111 final YangInstanceIdentifier childPath = path.node(child.getIdentifier());
112 enqueueOperation(() -> netconfService.replace(CONFIGURATION, childPath, child, Optional.empty()));
115 enqueueOperation(() -> netconfService.replace(CONFIGURATION, path, data, Optional.empty()));
120 public FluentFuture<? extends @NonNull CommitInfo> commit() {
121 final SettableFuture<CommitInfo> commitResult = SettableFuture.create();
123 // First complete all resultsFutures and merge them ...
124 final ListenableFuture<DOMRpcResult> resultErrors = mergeFutures(resultsFutures);
126 // ... then evaluate if there are any problems
127 Futures.addCallback(resultErrors, new FutureCallback<>() {
129 public void onSuccess(final DOMRpcResult result) {
130 final Collection<? extends RpcError> errors = result.getErrors();
131 if (!allWarnings(errors)) {
132 Futures.whenAllComplete(discardAndUnlock()).run(
133 () -> commitResult.setException(toCommitFailedException(errors)),
134 MoreExecutors.directExecutor());
138 // ... no problems so far, initiate commit
139 Futures.addCallback(netconfService.commit(), new FutureCallback<DOMRpcResult>() {
141 public void onSuccess(final DOMRpcResult rpcResult) {
142 final Collection<? extends RpcError> errors = result.getErrors();
143 if (errors.isEmpty()) {
144 Futures.whenAllComplete(netconfService.unlock()).run(
145 () -> commitResult.set(CommitInfo.empty()),
146 MoreExecutors.directExecutor());
147 } else if (allWarnings(errors)) {
148 LOG.info("Commit successful with warnings {}", errors);
149 Futures.whenAllComplete(netconfService.unlock()).run(
150 () -> commitResult.set(CommitInfo.empty()),
151 MoreExecutors.directExecutor());
153 Futures.whenAllComplete(discardAndUnlock()).run(
154 () -> commitResult.setException(toCommitFailedException(errors)),
155 MoreExecutors.directExecutor());
160 public void onFailure(final Throwable throwable) {
161 Futures.whenAllComplete(discardAndUnlock()).run(
162 () -> commitResult.setException(throwable),
163 MoreExecutors.directExecutor());
165 }, MoreExecutors.directExecutor());
169 public void onFailure(final Throwable throwable) {
170 Futures.whenAllComplete(discardAndUnlock()).run(() -> commitResult.setException(throwable),
171 MoreExecutors.directExecutor());
173 }, MoreExecutors.directExecutor());
175 return FluentFuture.from(commitResult);
178 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
179 justification = "https://github.com/spotbugs/spotbugs/issues/811")
180 private List<ListenableFuture<?>> discardAndUnlock() {
181 // execute discard & unlock operations only if lock operation was completed successfully
183 return List.of(netconfService.discardChanges(), netconfService.unlock());
185 return Collections.emptyList();
189 private final FutureCallback<DOMRpcResult> lockOperationCallback = new FutureCallback<>() {
191 public void onSuccess(final DOMRpcResult rpcResult) {
192 if (rpcResult != null && allWarnings(rpcResult.getErrors())) {
198 public void onFailure(final Throwable throwable) {
203 private void enqueueOperation(final Supplier<ListenableFuture<? extends DOMRpcResult>> operation) {
204 final ListenableFuture<? extends DOMRpcResult> operationFuture;
205 synchronized (resultsFutures) {
206 // if we only have result for the lock operation ...
207 if (resultsFutures.size() == 1) {
208 operationFuture = Futures.transformAsync(resultsFutures.get(0),
210 // ... then add new operation to the chain if lock was successful
211 if (result != null && (result.getErrors().isEmpty() || allWarnings(result.getErrors()))) {
212 return operation.get();
214 return Futures.immediateFailedFuture(new NetconfDocumentedException("Lock operation failed",
215 DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.LOCK_DENIED,
216 ErrorSeverity.ERROR));
219 MoreExecutors.directExecutor());
221 // ... otherwise just add operation to the execution chain
222 operationFuture = Futures.transformAsync(resultsFutures.get(resultsFutures.size() - 1),
223 future -> operation.get(),
224 MoreExecutors.directExecutor());
226 // ... finally save operation related future to the list
227 resultsFutures.add(operationFuture);
231 // Transform list of futures related to RPC operation into a single Future
232 private static ListenableFuture<DOMRpcResult> mergeFutures(
233 final List<ListenableFuture<? extends DOMRpcResult>> futures) {
234 return Futures.whenAllComplete(futures).call(() -> {
235 if (futures.size() == 1) {
237 return Futures.getDone(futures.get(0));
240 final var builder = ImmutableList.<RpcError>builder();
241 for (ListenableFuture<? extends DOMRpcResult> future : futures) {
242 builder.addAll(Futures.getDone(future).getErrors());
244 return new DefaultDOMRpcResult(null, builder.build());
245 }, MoreExecutors.directExecutor());
248 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
249 justification = "https://github.com/spotbugs/spotbugs/issues/811")
250 private static TransactionCommitFailedException toCommitFailedException(
251 final Collection<? extends RpcError> errors) {
252 DocumentedException.ErrorType errType = DocumentedException.ErrorType.APPLICATION;
253 ErrorSeverity errSeverity = ErrorSeverity.ERROR;
254 StringJoiner msgBuilder = new StringJoiner(" ");
255 String errorTag = "operation-failed";
256 for (final RpcError error : errors) {
257 switch (error.getErrorType()) {
259 errType = DocumentedException.ErrorType.RPC;
262 errType = DocumentedException.ErrorType.PROTOCOL;
265 errType = DocumentedException.ErrorType.TRANSPORT;
269 errType = DocumentedException.ErrorType.APPLICATION;
272 errSeverity = error.getSeverity().toNetconf();
273 msgBuilder.add(error.getMessage());
274 msgBuilder.add(error.getInfo());
275 errorTag = error.getTag();
278 return new TransactionCommitFailedException("Netconf transaction commit failed",
279 new NetconfDocumentedException("RPC during tx failed. " + msgBuilder.toString(), errType,
280 DocumentedException.ErrorTag.from(errorTag), errSeverity));
283 private static void executeWithLogging(final Supplier<ListenableFuture<? extends DOMRpcResult>> operation) {
284 final ListenableFuture<? extends DOMRpcResult> operationResult = operation.get();
285 Futures.addCallback(operationResult, new FutureCallback<DOMRpcResult>() {
287 public void onSuccess(final DOMRpcResult rpcResult) {
288 if (rpcResult != null && !rpcResult.getErrors().isEmpty()) {
289 LOG.error("Errors occurred during processing of the RPC operation: {}",
290 rpcResult.getErrors().stream().map(Object::toString).collect(Collectors.joining(",")));
295 public void onFailure(final Throwable throwable) {
296 LOG.error("Error processing operation", throwable);
298 }, MoreExecutors.directExecutor());
301 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
302 justification = "https://github.com/spotbugs/spotbugs/issues/811")
303 private static boolean allWarnings(final Collection<? extends @NonNull RpcError> errors) {
304 return errors.stream().allMatch(error -> error.getSeverity() == RpcError.ErrorSeverity.WARNING);