2 * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.netconf.sal.connect.netconf.sal.tx;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
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.Collection;
22 import java.util.List;
23 import java.util.Optional;
24 import java.util.concurrent.CopyOnWriteArrayList;
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.ModifyAction;
32 import org.opendaylight.netconf.api.NetconfDocumentedException;
33 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfBaseOps;
34 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
35 import org.opendaylight.yangtools.yang.common.ErrorSeverity;
36 import org.opendaylight.yangtools.yang.common.ErrorType;
37 import org.opendaylight.yangtools.yang.common.RpcError;
38 import org.opendaylight.yangtools.yang.common.RpcResult;
39 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
41 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
42 import org.opendaylight.yangtools.yang.data.api.schema.MixinNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
47 public abstract class AbstractWriteTx implements DOMDataTreeWriteTransaction {
49 private static final Logger LOG = LoggerFactory.getLogger(AbstractWriteTx.class);
51 protected final RemoteDeviceId id;
52 protected final NetconfBaseOps netOps;
53 protected final boolean rollbackSupport;
54 protected final List<ListenableFuture<? extends DOMRpcResult>> resultsFutures = new ArrayList<>();
55 private final List<TxListener> listeners = new CopyOnWriteArrayList<>();
56 // Allow commit to be called only once
57 protected volatile boolean finished = false;
58 protected final boolean isLockAllowed;
60 public AbstractWriteTx(final RemoteDeviceId id, final NetconfBaseOps netconfOps, final boolean rollbackSupport,
61 final boolean isLockAllowed) {
62 this.netOps = netconfOps;
64 this.rollbackSupport = rollbackSupport;
65 this.isLockAllowed = isLockAllowed;
69 protected static boolean isSuccess(final DOMRpcResult result) {
70 return result.getErrors().isEmpty();
73 protected void checkNotFinished() {
74 checkState(!isFinished(), "%s: Transaction %s already finished", id, getIdentifier());
77 protected boolean isFinished() {
82 public synchronized boolean cancel() {
86 listeners.forEach(listener -> listener.onTransactionCancelled(this));
92 protected abstract void init();
94 protected abstract void cleanup();
97 public Object getIdentifier() {
102 public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
103 final NormalizedNode data) {
104 checkEditable(store);
106 // Trying to write only mixin nodes (not visible when serialized).
107 // Ignoring. Some devices cannot handle empty edit-config rpc
108 if (containsOnlyNonVisibleData(path, data)) {
109 LOG.debug("Ignoring put for {} and data {}. Resulting data structure is empty.", path, data);
113 final DataContainerChild editStructure = netOps.createEditConfigStrcture(Optional.ofNullable(data),
114 Optional.of(ModifyAction.REPLACE), path);
115 editConfig(path, Optional.ofNullable(data), editStructure, Optional.empty(), "put");
119 public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
120 final NormalizedNode data) {
121 checkEditable(store);
123 // Trying to write only mixin nodes (not visible when serialized).
124 // Ignoring. Some devices cannot handle empty edit-config rpc
125 if (containsOnlyNonVisibleData(path, data)) {
126 LOG.debug("Ignoring merge for {} and data {}. Resulting data structure is empty.", path, data);
130 final DataContainerChild editStructure = netOps.createEditConfigStrcture(Optional.ofNullable(data),
131 Optional.empty(), path);
132 editConfig(path, Optional.ofNullable(data), editStructure, Optional.empty(), "merge");
136 * Check whether the data to be written consists only from mixins.
138 private static boolean containsOnlyNonVisibleData(final YangInstanceIdentifier path, final NormalizedNode data) {
139 // There's only one such case:top level list (pathArguments == 1 && data is Mixin)
140 // any other mixin nodes are contained by a "regular" node thus visible when serialized
141 return path.getPathArguments().size() == 1 && data instanceof MixinNode;
145 public synchronized void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
146 checkEditable(store);
147 final DataContainerChild editStructure = netOps.createEditConfigStrcture(Optional.empty(),
148 Optional.of(ModifyAction.DELETE), path);
149 editConfig(path, Optional.empty(), editStructure, Optional.of(ModifyAction.NONE), "delete");
153 public FluentFuture<? extends CommitInfo> commit() {
154 final SettableFuture<CommitInfo> resultFuture = SettableFuture.create();
155 Futures.addCallback(commitConfiguration(), new FutureCallback<RpcResult<Void>>() {
157 public void onSuccess(final RpcResult<Void> result) {
158 if (!result.isSuccessful()) {
159 final Collection<RpcError> errors = result.getErrors();
160 resultFuture.setException(new TransactionCommitFailedException(
161 String.format("Commit of transaction %s failed", getIdentifier()),
162 errors.toArray(new RpcError[errors.size()])));
166 resultFuture.set(CommitInfo.empty());
170 public void onFailure(final Throwable failure) {
171 resultFuture.setException(new TransactionCommitFailedException(
172 String.format("Commit of transaction %s failed", getIdentifier()), failure));
174 }, MoreExecutors.directExecutor());
176 return FluentFuture.from(resultFuture);
179 protected final ListenableFuture<RpcResult<Void>> commitConfiguration() {
180 listeners.forEach(listener -> listener.onTransactionSubmitted(this));
183 final ListenableFuture<RpcResult<Void>> result = performCommit();
184 Futures.addCallback(result, new FutureCallback<RpcResult<Void>>() {
186 public void onSuccess(final RpcResult<Void> rpcResult) {
187 if (rpcResult.isSuccessful()) {
188 listeners.forEach(txListener -> txListener.onTransactionSuccessful(AbstractWriteTx.this));
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));
198 public void onFailure(final Throwable throwable) {
199 listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, throwable));
201 }, MoreExecutors.directExecutor());
205 protected abstract ListenableFuture<RpcResult<Void>> performCommit();
207 private void checkEditable(final LogicalDatastoreType store) {
209 checkArgument(store == LogicalDatastoreType.CONFIGURATION,
210 "Can edit only configuration data, not %s", store);
213 protected abstract void editConfig(YangInstanceIdentifier path, Optional<NormalizedNode> data,
214 DataContainerChild editStructure,
215 Optional<ModifyAction> defaultOperation, String operation);
217 protected ListenableFuture<RpcResult<Void>> resultsToTxStatus() {
218 final SettableFuture<RpcResult<Void>> transformed = SettableFuture.create();
220 Futures.addCallback(Futures.allAsList(resultsFutures), new FutureCallback<List<DOMRpcResult>>() {
222 public void onSuccess(final List<DOMRpcResult> domRpcResults) {
223 if (!transformed.isDone()) {
224 extractResult(domRpcResults, transformed);
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 new Exception(throwable),
234 ErrorType.APPLICATION,
235 DocumentedException.ErrorTag.OPERATION_FAILED,
236 ErrorSeverity.ERROR);
237 transformed.setException(exception);
239 }, MoreExecutors.directExecutor());
244 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
245 justification = "https://github.com/spotbugs/spotbugs/issues/811")
246 private void extractResult(final List<DOMRpcResult> domRpcResults,
247 final SettableFuture<RpcResult<Void>> transformed) {
248 ErrorType errType = ErrorType.APPLICATION;
249 ErrorSeverity errSeverity = ErrorSeverity.ERROR;
250 StringBuilder msgBuilder = new StringBuilder();
251 boolean errorsEncouneterd = false;
252 String errorTag = "operation-failed";
254 for (final DOMRpcResult domRpcResult : domRpcResults) {
255 if (!domRpcResult.getErrors().isEmpty()) {
256 errorsEncouneterd = true;
257 final RpcError error = domRpcResult.getErrors().iterator().next();
259 errType = error.getErrorType().toNetconf();
260 errSeverity = error.getSeverity().toNetconf();
261 msgBuilder.append(error.getMessage());
262 msgBuilder.append(error.getInfo());
263 errorTag = error.getTag();
266 if (errorsEncouneterd) {
267 final NetconfDocumentedException exception = new NetconfDocumentedException(id
268 + ":RPC during tx failed. " + msgBuilder.toString(),
270 DocumentedException.ErrorTag.from(errorTag),
272 transformed.setException(exception);
275 transformed.set(RpcResultBuilder.<Void>success().build());
278 AutoCloseable addListener(final TxListener listener) {
279 listeners.add(listener);
280 return () -> listeners.remove(listener);