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