Fix findbugs violations in netconf
[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.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.List;
20 import java.util.concurrent.CopyOnWriteArrayList;
21 import javax.annotation.Nonnull;
22 import org.opendaylight.controller.config.util.xml.DocumentedException;
23 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
24 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
25 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
26 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
27 import org.opendaylight.netconf.api.NetconfDocumentedException;
28 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfBaseOps;
29 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
30 import org.opendaylight.yangtools.yang.common.RpcError;
31 import org.opendaylight.yangtools.yang.common.RpcResult;
32 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
33 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
36 import org.opendaylight.yangtools.yang.data.api.schema.MixinNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 public abstract class AbstractWriteTx implements DOMDataWriteTransaction {
42
43     private static final Logger LOG  = LoggerFactory.getLogger(AbstractWriteTx.class);
44
45     protected final RemoteDeviceId id;
46     protected final NetconfBaseOps netOps;
47     protected final boolean rollbackSupport;
48     protected final List<ListenableFuture<DOMRpcResult>> resultsFutures;
49     private final List<TxListener> listeners = new CopyOnWriteArrayList<>();
50     // Allow commit to be called only once
51     protected volatile boolean finished = false;
52
53     public AbstractWriteTx(final NetconfBaseOps netOps, final RemoteDeviceId id, final boolean rollbackSupport) {
54         this.netOps = netOps;
55         this.id = id;
56         this.rollbackSupport = rollbackSupport;
57         this.resultsFutures = Lists.newArrayList();
58         init();
59     }
60
61     protected static boolean isSuccess(final DOMRpcResult result) {
62         return result.getErrors().isEmpty();
63     }
64
65     protected void checkNotFinished() {
66         Preconditions.checkState(!isFinished(), "%s: Transaction %s already finished", id, getIdentifier());
67     }
68
69     protected boolean isFinished() {
70         return finished;
71     }
72
73     @Override
74     public synchronized boolean cancel() {
75         if (isFinished()) {
76             return false;
77         }
78         listeners.forEach(listener -> listener.onTransactionCancelled(this));
79         finished = true;
80         cleanup();
81         return true;
82     }
83
84     protected abstract void init();
85
86     protected abstract void cleanup();
87
88     @Override
89     public Object getIdentifier() {
90         return this;
91     }
92
93     @Override
94     public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
95                                  final NormalizedNode<?, ?> data) {
96         checkEditable(store);
97
98         // Trying to write only mixin nodes (not visible when serialized).
99         // Ignoring. Some devices cannot handle empty edit-config rpc
100         if (containsOnlyNonVisibleData(path, data)) {
101             LOG.debug("Ignoring put for {} and data {}. Resulting data structure is empty.", path, data);
102             return;
103         }
104
105         final DataContainerChild<?, ?> editStructure =
106                 netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data),
107                         Optional.of(ModifyAction.REPLACE), path);
108         editConfig(path, Optional.fromNullable(data), editStructure, Optional.of(ModifyAction.NONE), "put");
109     }
110
111     @Override
112     public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
113                                    final NormalizedNode<?, ?> data) {
114         checkEditable(store);
115
116         // Trying to write only mixin nodes (not visible when serialized).
117         // Ignoring. Some devices cannot handle empty edit-config rpc
118         if (containsOnlyNonVisibleData(path, data)) {
119             LOG.debug("Ignoring merge for {} and data {}. Resulting data structure is empty.", path, data);
120             return;
121         }
122
123         final DataContainerChild<?, ?> editStructure =
124                 netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data),
125                         Optional.<ModifyAction>absent(), path);
126         editConfig(path, Optional.fromNullable(data), editStructure, Optional.<ModifyAction>absent(), "merge");
127     }
128
129     /**
130      * Check whether the data to be written consists only from mixins.
131      */
132     private static boolean containsOnlyNonVisibleData(final YangInstanceIdentifier path,
133                                                       final NormalizedNode<?, ?> data) {
134         // There's only one such case:top level list (pathArguments == 1 && data is Mixin)
135         // any other mixin nodes are contained by a "regular" node thus visible when serialized
136         return path.getPathArguments().size() == 1 && data instanceof MixinNode;
137     }
138
139     @Override
140     public synchronized void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
141         checkEditable(store);
142         final DataContainerChild<?, ?> editStructure =
143                 netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>absent(),
144                         Optional.of(ModifyAction.DELETE), path);
145         editConfig(path, Optional.<NormalizedNode<?, ?>>absent(),
146                 editStructure, Optional.of(ModifyAction.NONE), "delete");
147     }
148
149     protected final ListenableFuture<RpcResult<Void>> commitConfiguration() {
150         listeners.forEach(listener -> listener.onTransactionSubmitted(this));
151         checkNotFinished();
152         finished = true;
153         final ListenableFuture<RpcResult<Void>> result = performCommit();
154         Futures.addCallback(result, new FutureCallback<RpcResult<Void>>() {
155             @Override
156             public void onSuccess(@Nonnull final RpcResult<Void> rpcResult) {
157                 if (rpcResult.isSuccessful()) {
158                     listeners.forEach(txListener -> txListener.onTransactionSuccessful(AbstractWriteTx.this));
159                 } else {
160                     final TransactionCommitFailedException cause =
161                             new TransactionCommitFailedException("Transaction failed",
162                                     rpcResult.getErrors().toArray(new RpcError[rpcResult.getErrors().size()]));
163                     listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, cause));
164                 }
165             }
166
167             @Override
168             public void onFailure(final Throwable throwable) {
169                 listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, throwable));
170             }
171         }, MoreExecutors.directExecutor());
172         return result;
173     }
174
175     protected abstract ListenableFuture<RpcResult<Void>> performCommit();
176
177     private void checkEditable(final LogicalDatastoreType store) {
178         checkNotFinished();
179         Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION,
180                 "Can edit only configuration data, not %s", store);
181     }
182
183     protected abstract void editConfig(YangInstanceIdentifier path, Optional<NormalizedNode<?, ?>> data,
184                                        DataContainerChild<?, ?> editStructure,
185                                        Optional<ModifyAction> defaultOperation, String operation);
186
187     protected ListenableFuture<RpcResult<Void>> resultsToTxStatus() {
188         final SettableFuture<RpcResult<Void>> transformed = SettableFuture.create();
189
190         Futures.addCallback(Futures.allAsList(resultsFutures), new FutureCallback<List<DOMRpcResult>>() {
191             @Override
192             public void onSuccess(@Nonnull final List<DOMRpcResult> domRpcResults) {
193                 domRpcResults.forEach(domRpcResult -> {
194                     if (!domRpcResult.getErrors().isEmpty() && !transformed.isDone()) {
195                         final NetconfDocumentedException exception =
196                                 new NetconfDocumentedException(id + ":RPC during tx failed",
197                                         DocumentedException.ErrorType.APPLICATION,
198                                         DocumentedException.ErrorTag.OPERATION_FAILED,
199                                         DocumentedException.ErrorSeverity.ERROR);
200                         transformed.setException(exception);
201                     }
202                 });
203
204                 if (!transformed.isDone()) {
205                     transformed.set(RpcResultBuilder.<Void>success().build());
206                 }
207             }
208
209             @Override
210             public void onFailure(final Throwable throwable) {
211                 final NetconfDocumentedException exception =
212                         new NetconfDocumentedException(
213                                 id + ":RPC during tx returned an exception",
214                                 new Exception(throwable),
215                                 DocumentedException.ErrorType.APPLICATION,
216                                 DocumentedException.ErrorTag.OPERATION_FAILED,
217                                 DocumentedException.ErrorSeverity.ERROR);
218                 transformed.setException(exception);
219             }
220         }, MoreExecutors.directExecutor());
221
222         return transformed;
223     }
224
225     AutoCloseable addListener(final TxListener listener) {
226         listeners.add(listener);
227         return () -> listeners.remove(listener);
228     }
229 }