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