Bump odlparent to 6.0.0
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / sal / connect / netconf / sal / tx / 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.tx;
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.Collection;
22 import java.util.List;
23 import java.util.Optional;
24 import java.util.concurrent.CopyOnWriteArrayList;
25 import org.opendaylight.mdsal.common.api.CommitInfo;
26 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
27 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
28 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
29 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
30 import org.opendaylight.netconf.api.DocumentedException;
31 import org.opendaylight.netconf.api.ModifyAction;
32 import org.opendaylight.netconf.api.NetconfDocumentedException;
33 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfBaseOps;
34 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
35 import org.opendaylight.yangtools.yang.common.RpcError;
36 import org.opendaylight.yangtools.yang.common.RpcResult;
37 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
39 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
40 import org.opendaylight.yangtools.yang.data.api.schema.MixinNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 public abstract class AbstractWriteTx implements DOMDataTreeWriteTransaction {
46
47     private static final Logger LOG  = LoggerFactory.getLogger(AbstractWriteTx.class);
48
49     protected final RemoteDeviceId id;
50     protected final NetconfBaseOps netOps;
51     protected final boolean rollbackSupport;
52     protected final List<ListenableFuture<DOMRpcResult>> resultsFutures = new ArrayList<>();
53     private final List<TxListener> listeners = new CopyOnWriteArrayList<>();
54     // Allow commit to be called only once
55     protected volatile boolean finished = false;
56     protected final boolean isLockAllowed;
57
58     public AbstractWriteTx(final RemoteDeviceId id, final NetconfBaseOps netconfOps, final boolean rollbackSupport,
59             final boolean isLockAllowed) {
60         this.netOps = netconfOps;
61         this.id = id;
62         this.rollbackSupport = rollbackSupport;
63         this.isLockAllowed = isLockAllowed;
64         init();
65     }
66
67     protected static boolean isSuccess(final DOMRpcResult result) {
68         return result.getErrors().isEmpty();
69     }
70
71     protected void checkNotFinished() {
72         checkState(!isFinished(), "%s: Transaction %s already finished", id, getIdentifier());
73     }
74
75     protected boolean isFinished() {
76         return finished;
77     }
78
79     @Override
80     public synchronized boolean cancel() {
81         if (isFinished()) {
82             return false;
83         }
84         listeners.forEach(listener -> listener.onTransactionCancelled(this));
85         finished = true;
86         cleanup();
87         return true;
88     }
89
90     protected abstract void init();
91
92     protected abstract void cleanup();
93
94     @Override
95     public Object getIdentifier() {
96         return this;
97     }
98
99     @Override
100     public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
101                                  final NormalizedNode<?, ?> data) {
102         checkEditable(store);
103
104         // Trying to write only mixin nodes (not visible when serialized).
105         // Ignoring. Some devices cannot handle empty edit-config rpc
106         if (containsOnlyNonVisibleData(path, data)) {
107             LOG.debug("Ignoring put for {} and data {}. Resulting data structure is empty.", path, data);
108             return;
109         }
110
111         final DataContainerChild<?, ?> editStructure = netOps.createEditConfigStrcture(Optional.ofNullable(data),
112                         Optional.of(ModifyAction.REPLACE), path);
113         editConfig(path, Optional.ofNullable(data), editStructure, Optional.empty(), "put");
114     }
115
116     @Override
117     public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
118                                    final NormalizedNode<?, ?> data) {
119         checkEditable(store);
120
121         // Trying to write only mixin nodes (not visible when serialized).
122         // Ignoring. Some devices cannot handle empty edit-config rpc
123         if (containsOnlyNonVisibleData(path, data)) {
124             LOG.debug("Ignoring merge for {} and data {}. Resulting data structure is empty.", path, data);
125             return;
126         }
127
128         final DataContainerChild<?, ?> editStructure =  netOps.createEditConfigStrcture(Optional.ofNullable(data),
129             Optional.empty(), path);
130         editConfig(path, Optional.ofNullable(data), editStructure, Optional.empty(), "merge");
131     }
132
133     /**
134      * Check whether the data to be written consists only from mixins.
135      */
136     private static boolean containsOnlyNonVisibleData(final YangInstanceIdentifier path,
137                                                       final NormalizedNode<?, ?> data) {
138         // There's only one such case:top level list (pathArguments == 1 && data is Mixin)
139         // any other mixin nodes are contained by a "regular" node thus visible when serialized
140         return path.getPathArguments().size() == 1 && data instanceof MixinNode;
141     }
142
143     @Override
144     public synchronized void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
145         checkEditable(store);
146         final DataContainerChild<?, ?> editStructure = netOps.createEditConfigStrcture(Optional.empty(),
147                         Optional.of(ModifyAction.DELETE), path);
148         editConfig(path, Optional.empty(), editStructure, Optional.of(ModifyAction.NONE), "delete");
149     }
150
151     @Override
152     public FluentFuture<? extends CommitInfo> commit() {
153         final SettableFuture<CommitInfo> resultFuture = SettableFuture.create();
154         Futures.addCallback(commitConfiguration(), new FutureCallback<RpcResult<Void>>() {
155             @Override
156             public void onSuccess(final RpcResult<Void> result) {
157                 if (!result.isSuccessful()) {
158                     final Collection<RpcError> errors = result.getErrors();
159                     resultFuture.setException(new TransactionCommitFailedException(
160                         String.format("Commit of transaction %s failed", getIdentifier()),
161                             errors.toArray(new RpcError[errors.size()])));
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     protected 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     protected 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     protected abstract void editConfig(YangInstanceIdentifier path, Optional<NormalizedNode<?, ?>> data,
213                                        DataContainerChild<?, ?> editStructure,
214                                        Optional<ModifyAction> defaultOperation, String operation);
215
216     protected 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                                 new Exception(throwable),
233                                 DocumentedException.ErrorType.APPLICATION,
234                                 DocumentedException.ErrorTag.OPERATION_FAILED,
235                                 DocumentedException.ErrorSeverity.ERROR);
236                 transformed.setException(exception);
237             }
238         }, MoreExecutors.directExecutor());
239
240         return transformed;
241     }
242
243     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
244             justification = "https://github.com/spotbugs/spotbugs/issues/811")
245     private void extractResult(final List<DOMRpcResult> domRpcResults,
246                                final SettableFuture<RpcResult<Void>> transformed) {
247         DocumentedException.ErrorType errType = DocumentedException.ErrorType.APPLICATION;
248         DocumentedException.ErrorSeverity errSeverity = DocumentedException.ErrorSeverity.ERROR;
249         StringBuilder msgBuilder = new StringBuilder();
250         boolean errorsEncouneterd = false;
251         String errorTag = "operation-failed";
252
253         for (final DOMRpcResult domRpcResult : domRpcResults) {
254             if (!domRpcResult.getErrors().isEmpty()) {
255                 errorsEncouneterd = true;
256                 final RpcError error = domRpcResult.getErrors().iterator().next();
257                 final RpcError.ErrorType errorType = error.getErrorType();
258                 switch (errorType) {
259                     case RPC:
260                         errType = DocumentedException.ErrorType.RPC;
261                         break;
262                     case PROTOCOL:
263                         errType = DocumentedException.ErrorType.PROTOCOL;
264                         break;
265                     case TRANSPORT:
266                         errType = DocumentedException.ErrorType.TRANSPORT;
267                         break;
268                     case APPLICATION:
269                         errType = DocumentedException.ErrorType.APPLICATION;
270                         break;
271                     default:
272                         errType = DocumentedException.ErrorType.APPLICATION;
273                         break;
274                 }
275                 final RpcError.ErrorSeverity severity = error.getSeverity();
276                 switch (severity) {
277                     case ERROR:
278                         errSeverity = DocumentedException.ErrorSeverity.ERROR;
279                         break;
280                     case WARNING:
281                         errSeverity = DocumentedException.ErrorSeverity.WARNING;
282                         break;
283                     default:
284                         errSeverity = DocumentedException.ErrorSeverity.ERROR;
285                         break;
286                 }
287                 msgBuilder.append(error.getMessage());
288                 errorTag = error.getTag();
289             }
290         }
291         if (errorsEncouneterd) {
292             final NetconfDocumentedException exception = new NetconfDocumentedException(id
293                     + ":RPC during tx failed. " + msgBuilder.toString(),
294                     errType,
295                     DocumentedException.ErrorTag.from(errorTag),
296                     errSeverity);
297             transformed.setException(exception);
298             return;
299         }
300         transformed.set(RpcResultBuilder.<Void>success().build());
301     }
302
303     AutoCloseable addListener(final TxListener listener) {
304         listeners.add(listener);
305         return () -> listeners.remove(listener);
306     }
307 }