Remove sal.connect.netconf.util
[netconf.git] / plugins / netconf-client-mdsal / src / main / java / org / opendaylight / netconf / sal / connect / netconf / sal / AbstractWriteTx.java
1 /*
2  * Copyright (c) 2014, 2015 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.netconf.sal.connect.netconf.sal;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12
13 import com.google.common.util.concurrent.FluentFuture;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import com.google.common.util.concurrent.MoreExecutors;
18 import com.google.common.util.concurrent.SettableFuture;
19 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
20 import java.util.ArrayList;
21 import java.util.List;
22 import java.util.Optional;
23 import java.util.concurrent.CopyOnWriteArrayList;
24 import org.opendaylight.mdsal.common.api.CommitInfo;
25 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
26 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
27 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
28 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
29 import org.opendaylight.netconf.api.EffectiveOperation;
30 import org.opendaylight.netconf.api.NetconfDocumentedException;
31 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceId;
32 import org.opendaylight.netconf.client.mdsal.impl.NetconfBaseOps;
33 import org.opendaylight.yangtools.yang.common.ErrorSeverity;
34 import org.opendaylight.yangtools.yang.common.ErrorTag;
35 import org.opendaylight.yangtools.yang.common.ErrorType;
36 import org.opendaylight.yangtools.yang.common.RpcError;
37 import org.opendaylight.yangtools.yang.common.RpcResult;
38 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
41 import org.opendaylight.yangtools.yang.data.api.schema.MixinNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 abstract class AbstractWriteTx implements DOMDataTreeWriteTransaction {
47     private static final Logger LOG  = LoggerFactory.getLogger(AbstractWriteTx.class);
48
49     final RemoteDeviceId id;
50     final NetconfBaseOps netOps;
51     final boolean rollbackSupport;
52     final List<ListenableFuture<? extends DOMRpcResult>> resultsFutures = new ArrayList<>();
53     private final List<TxListener> listeners = new CopyOnWriteArrayList<>();
54     // Allow commit to be called only once
55     volatile boolean finished = false;
56     final boolean isLockAllowed;
57
58     @SuppressFBWarnings(value = "MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR", justification = "Behavior-only subclasses")
59     AbstractWriteTx(final RemoteDeviceId id, final NetconfBaseOps netconfOps, final boolean rollbackSupport,
60             final boolean isLockAllowed) {
61         netOps = netconfOps;
62         this.id = id;
63         this.rollbackSupport = rollbackSupport;
64         this.isLockAllowed = isLockAllowed;
65         init();
66     }
67
68     static boolean isSuccess(final DOMRpcResult result) {
69         return result.errors().isEmpty();
70     }
71
72     void checkNotFinished() {
73         checkState(!isFinished(), "%s: Transaction %s already finished", id, getIdentifier());
74     }
75
76     boolean isFinished() {
77         return finished;
78     }
79
80     @Override
81     public synchronized boolean cancel() {
82         if (isFinished()) {
83             return false;
84         }
85         listeners.forEach(listener -> listener.onTransactionCancelled(this));
86         finished = true;
87         cleanup();
88         return true;
89     }
90
91     // FIXME: only called from ctor which needs @SuppressDBWarnings. Refactor class hierarchy without this method (here)
92     abstract void init();
93
94     abstract void cleanup();
95
96     @Override
97     public Object getIdentifier() {
98         return this;
99     }
100
101     @Override
102     public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
103                                  final NormalizedNode data) {
104         checkEditable(store);
105
106         // Trying to write only mixin nodes (not visible when serialized).
107         // Ignoring. Some devices cannot handle empty edit-config rpc
108         if (containsOnlyNonVisibleData(path, data)) {
109             LOG.debug("Ignoring put for {} and data {}. Resulting data structure is empty.", path, data);
110             return;
111         }
112
113         final DataContainerChild editStructure = netOps.createEditConfigStructure(Optional.ofNullable(data),
114                         Optional.of(EffectiveOperation.REPLACE), path);
115         editConfig(path, Optional.ofNullable(data), editStructure, Optional.empty(), "put");
116     }
117
118     @Override
119     public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
120                                    final NormalizedNode data) {
121         checkEditable(store);
122
123         // Trying to write only mixin nodes (not visible when serialized).
124         // Ignoring. Some devices cannot handle empty edit-config rpc
125         if (containsOnlyNonVisibleData(path, data)) {
126             LOG.debug("Ignoring merge for {} and data {}. Resulting data structure is empty.", path, data);
127             return;
128         }
129
130         final DataContainerChild editStructure =  netOps.createEditConfigStructure(Optional.ofNullable(data),
131             Optional.empty(), path);
132         editConfig(path, Optional.ofNullable(data), editStructure, Optional.empty(), "merge");
133     }
134
135     /**
136      * Check whether the data to be written consists only from mixins.
137      */
138     private static boolean containsOnlyNonVisibleData(final YangInstanceIdentifier path, final NormalizedNode data) {
139         // There's only one such case:top level list (pathArguments == 1 && data is Mixin)
140         // any other mixin nodes are contained by a "regular" node thus visible when serialized
141         return path.getPathArguments().size() == 1 && data instanceof MixinNode;
142     }
143
144     @Override
145     public synchronized void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
146         checkEditable(store);
147         final DataContainerChild editStructure = netOps.createEditConfigStructure(Optional.empty(),
148                         Optional.of(EffectiveOperation.DELETE), path);
149         editConfig(path, Optional.empty(), editStructure, Optional.of(EffectiveOperation.NONE), "delete");
150     }
151
152     @Override
153     public FluentFuture<? extends CommitInfo> commit() {
154         final SettableFuture<CommitInfo> resultFuture = SettableFuture.create();
155         Futures.addCallback(commitConfiguration(), new FutureCallback<RpcResult<Void>>() {
156             @Override
157             public void onSuccess(final RpcResult<Void> result) {
158                 if (!result.isSuccessful()) {
159                     resultFuture.setException(new TransactionCommitFailedException(
160                         String.format("Commit of transaction %s failed", getIdentifier()),
161                         result.getErrors().toArray(new RpcError[0])));
162                     return;
163                 }
164
165                 resultFuture.set(CommitInfo.empty());
166             }
167
168             @Override
169             public void onFailure(final Throwable failure) {
170                 resultFuture.setException(new TransactionCommitFailedException(
171                         String.format("Commit of transaction %s failed", getIdentifier()), failure));
172             }
173         }, MoreExecutors.directExecutor());
174
175         return FluentFuture.from(resultFuture);
176     }
177
178     final ListenableFuture<RpcResult<Void>> commitConfiguration() {
179         listeners.forEach(listener -> listener.onTransactionSubmitted(this));
180         checkNotFinished();
181         finished = true;
182         final ListenableFuture<RpcResult<Void>> result = performCommit();
183         Futures.addCallback(result, new FutureCallback<RpcResult<Void>>() {
184             @Override
185             public void onSuccess(final RpcResult<Void> rpcResult) {
186                 if (rpcResult.isSuccessful()) {
187                     listeners.forEach(txListener -> txListener.onTransactionSuccessful(AbstractWriteTx.this));
188                 } else {
189                     final TransactionCommitFailedException cause =
190                             new TransactionCommitFailedException("Transaction failed",
191                                     rpcResult.getErrors().toArray(new RpcError[rpcResult.getErrors().size()]));
192                     listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, cause));
193                 }
194             }
195
196             @Override
197             public void onFailure(final Throwable throwable) {
198                 listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, throwable));
199             }
200         }, MoreExecutors.directExecutor());
201         return result;
202     }
203
204     abstract ListenableFuture<RpcResult<Void>> performCommit();
205
206     private void checkEditable(final LogicalDatastoreType store) {
207         checkNotFinished();
208         checkArgument(store == LogicalDatastoreType.CONFIGURATION,
209                 "Can edit only configuration data, not %s", store);
210     }
211
212     abstract void editConfig(YangInstanceIdentifier path, Optional<NormalizedNode> data,
213                              DataContainerChild editStructure, Optional<EffectiveOperation> defaultOperation,
214                              String operation);
215
216     ListenableFuture<RpcResult<Void>> resultsToTxStatus() {
217         final SettableFuture<RpcResult<Void>> transformed = SettableFuture.create();
218
219         Futures.addCallback(Futures.allAsList(resultsFutures), new FutureCallback<List<DOMRpcResult>>() {
220             @Override
221             public void onSuccess(final List<DOMRpcResult> domRpcResults) {
222                 if (!transformed.isDone()) {
223                     extractResult(domRpcResults, transformed);
224                 }
225             }
226
227             @Override
228             public void onFailure(final Throwable throwable) {
229                 final NetconfDocumentedException exception =
230                         new NetconfDocumentedException(
231                                 id + ":RPC during tx returned an exception" + throwable.getMessage(),
232                                 // FIXME: add proper unmask/wrap to ExecutionException
233                                 new Exception(throwable),
234                                 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, ErrorSeverity.ERROR);
235                 transformed.setException(exception);
236             }
237         }, MoreExecutors.directExecutor());
238
239         return transformed;
240     }
241
242     private void extractResult(final List<DOMRpcResult> domRpcResults,
243                                final SettableFuture<RpcResult<Void>> transformed) {
244         ErrorType errType = ErrorType.APPLICATION;
245         ErrorSeverity errSeverity = ErrorSeverity.ERROR;
246         StringBuilder msgBuilder = new StringBuilder();
247         boolean errorsEncouneterd = false;
248         ErrorTag errorTag = ErrorTag.OPERATION_FAILED;
249
250         for (final DOMRpcResult domRpcResult : domRpcResults) {
251             if (!domRpcResult.errors().isEmpty()) {
252                 errorsEncouneterd = true;
253                 final RpcError error = domRpcResult.errors().iterator().next();
254
255                 errType = error.getErrorType();
256                 errSeverity = error.getSeverity();
257                 msgBuilder.append(error.getMessage());
258                 msgBuilder.append(error.getInfo());
259                 errorTag = error.getTag();
260             }
261         }
262         if (errorsEncouneterd) {
263             final NetconfDocumentedException exception = new NetconfDocumentedException(
264                     id + ":RPC during tx failed. " + msgBuilder, errType, errorTag, errSeverity);
265             transformed.setException(exception);
266             return;
267         }
268         transformed.set(RpcResultBuilder.<Void>success().build());
269     }
270
271     AutoCloseable addListener(final TxListener listener) {
272         listeners.add(listener);
273         return () -> listeners.remove(listener);
274     }
275 }