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