eb48fdbd96ba56f49e372172855823758bf7ffee
[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.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.Lists;
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 java.util.Collection;
21 import java.util.List;
22 import java.util.concurrent.CopyOnWriteArrayList;
23 import javax.annotation.Nonnull;
24 import org.eclipse.jdt.annotation.NonNull;
25 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
26 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
27 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
28 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
29 import org.opendaylight.mdsal.common.api.CommitInfo;
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 DOMDataWriteTransaction {
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 =
110                 netOps.createEditConfigStrcture(Optional.fromNullable(data),
111                         Optional.of(ModifyAction.REPLACE), path);
112         editConfig(path, Optional.fromNullable(data), editStructure, Optional.absent(), "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 =
128                 netOps.createEditConfigStrcture(Optional.fromNullable(data),
129                         Optional.absent(), path);
130         editConfig(path, Optional.fromNullable(data), editStructure, Optional.absent(), "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 =
147                 netOps.createEditConfigStrcture(Optional.absent(),
148                         Optional.of(ModifyAction.DELETE), path);
149         editConfig(path, Optional.absent(),
150                 editStructure, Optional.of(ModifyAction.NONE), "delete");
151     }
152
153     @Override
154     public @NonNull FluentFuture<? extends @NonNull CommitInfo> commit() {
155         final SettableFuture<CommitInfo> resultFuture = SettableFuture.create();
156         Futures.addCallback(commitConfiguration(), new FutureCallback<RpcResult<Void>>() {
157             @Override
158             public void onSuccess(RpcResult<Void> result) {
159                 if (!result.isSuccessful()) {
160                     final Collection<RpcError> errors = result.getErrors();
161                     resultFuture.setException(new TransactionCommitFailedException(
162                         String.format("Commit of transaction %s failed", getIdentifier()),
163                             errors.toArray(new RpcError[errors.size()])));
164                     return;
165                 }
166
167                 resultFuture.set(CommitInfo.empty());
168             }
169
170             @Override
171             public void onFailure(Throwable failure) {
172                 resultFuture.setException(new TransactionCommitFailedException(
173                         String.format("Commit of transaction %s failed", getIdentifier()), failure));
174             }
175         }, MoreExecutors.directExecutor());
176
177         return FluentFuture.from(resultFuture);
178     }
179
180     protected final ListenableFuture<RpcResult<Void>> commitConfiguration() {
181         listeners.forEach(listener -> listener.onTransactionSubmitted(this));
182         checkNotFinished();
183         finished = true;
184         final ListenableFuture<RpcResult<Void>> result = performCommit();
185         Futures.addCallback(result, new FutureCallback<RpcResult<Void>>() {
186             @Override
187             public void onSuccess(@Nonnull final RpcResult<Void> rpcResult) {
188                 if (rpcResult.isSuccessful()) {
189                     listeners.forEach(txListener -> txListener.onTransactionSuccessful(AbstractWriteTx.this));
190                 } else {
191                     final TransactionCommitFailedException cause =
192                             new TransactionCommitFailedException("Transaction failed",
193                                     rpcResult.getErrors().toArray(new RpcError[rpcResult.getErrors().size()]));
194                     listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, cause));
195                 }
196             }
197
198             @Override
199             public void onFailure(final Throwable throwable) {
200                 listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, throwable));
201             }
202         }, MoreExecutors.directExecutor());
203         return result;
204     }
205
206     protected abstract ListenableFuture<RpcResult<Void>> performCommit();
207
208     private void checkEditable(final LogicalDatastoreType store) {
209         checkNotFinished();
210         Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION,
211                 "Can edit only configuration data, not %s", store);
212     }
213
214     protected abstract void editConfig(YangInstanceIdentifier path, Optional<NormalizedNode<?, ?>> data,
215                                        DataContainerChild<?, ?> editStructure,
216                                        Optional<ModifyAction> defaultOperation, String operation);
217
218     protected ListenableFuture<RpcResult<Void>> resultsToTxStatus() {
219         final SettableFuture<RpcResult<Void>> transformed = SettableFuture.create();
220
221         Futures.addCallback(Futures.allAsList(resultsFutures), new FutureCallback<List<DOMRpcResult>>() {
222             @Override
223             public void onSuccess(@Nonnull final List<DOMRpcResult> domRpcResults) {
224                 if (!transformed.isDone()) {
225                     extractResult(domRpcResults, transformed);
226                 }
227             }
228
229             @Override
230             public void onFailure(final Throwable throwable) {
231                 final NetconfDocumentedException exception =
232                         new NetconfDocumentedException(
233                                 id + ":RPC during tx returned an exception",
234                                 new Exception(throwable),
235                                 DocumentedException.ErrorType.APPLICATION,
236                                 DocumentedException.ErrorTag.OPERATION_FAILED,
237                                 DocumentedException.ErrorSeverity.ERROR);
238                 transformed.setException(exception);
239             }
240         }, MoreExecutors.directExecutor());
241
242         return transformed;
243     }
244
245     private void extractResult(final List<DOMRpcResult> domRpcResults,
246                                final SettableFuture<RpcResult<Void>> transformed) {
247         for (final DOMRpcResult domRpcResult : domRpcResults) {
248             if (!domRpcResult.getErrors().isEmpty()) {
249                 final RpcError error = domRpcResult.getErrors().iterator().next();
250                 final RpcError.ErrorType errorType = error.getErrorType();
251                 final DocumentedException.ErrorType eType;
252                 switch (errorType) {
253                     case RPC:
254                         eType = DocumentedException.ErrorType.RPC;
255                         break;
256                     case PROTOCOL:
257                         eType = DocumentedException.ErrorType.PROTOCOL;
258                         break;
259                     case TRANSPORT:
260                         eType = DocumentedException.ErrorType.TRANSPORT;
261                         break;
262                     case APPLICATION:
263                         eType = DocumentedException.ErrorType.APPLICATION;
264                         break;
265                     default:
266                         eType = DocumentedException.ErrorType.APPLICATION;
267                         break;
268                 }
269                 final RpcError.ErrorSeverity severity = error.getSeverity();
270                 final DocumentedException.ErrorSeverity eSeverity;
271                 switch (severity) {
272                     case ERROR:
273                         eSeverity = DocumentedException.ErrorSeverity.ERROR;
274                         break;
275                     case WARNING:
276                         eSeverity = DocumentedException.ErrorSeverity.WARNING;
277                         break;
278                     default:
279                         eSeverity = DocumentedException.ErrorSeverity.ERROR;
280                         break;
281                 }
282                 final String message;
283                 if (error.getMessage() == null || error.getMessage().isEmpty()) {
284                     message = id + ":RPC during tx failed";
285                 } else {
286                     message = error.getMessage();
287                 }
288                 final NetconfDocumentedException exception = new NetconfDocumentedException(message,
289                         eType,
290                         DocumentedException.ErrorTag.from(error.getTag()),
291                         eSeverity);
292                 transformed.setException(exception);
293                 return;
294             }
295         }
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 }