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
9 package org.opendaylight.netconf.sal.connect.netconf.sal.tx;
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;
45 public abstract class AbstractWriteTx implements DOMDataTreeWriteTransaction {
47 private static final Logger LOG = LoggerFactory.getLogger(AbstractWriteTx.class);
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;
57 public AbstractWriteTx(final NetconfBaseOps netOps, final RemoteDeviceId id, final boolean rollbackSupport) {
60 this.rollbackSupport = rollbackSupport;
61 this.resultsFutures = Lists.newArrayList();
65 protected static boolean isSuccess(final DOMRpcResult result) {
66 return result.getErrors().isEmpty();
69 protected void checkNotFinished() {
70 Preconditions.checkState(!isFinished(), "%s: Transaction %s already finished", id, getIdentifier());
73 protected boolean isFinished() {
78 public synchronized boolean cancel() {
82 listeners.forEach(listener -> listener.onTransactionCancelled(this));
88 protected abstract void init();
90 protected abstract void cleanup();
93 public Object getIdentifier() {
98 public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
99 final NormalizedNode<?, ?> data) {
100 checkEditable(store);
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);
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");
115 public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
116 final NormalizedNode<?, ?> data) {
117 checkEditable(store);
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);
126 final DataContainerChild<?, ?> editStructure = netOps.createEditConfigStrcture(Optional.ofNullable(data),
127 Optional.empty(), path);
128 editConfig(path, Optional.ofNullable(data), editStructure, Optional.empty(), "merge");
132 * Check whether the data to be written consists only from mixins.
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;
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");
150 public @NonNull FluentFuture<? extends @NonNull CommitInfo> commit() {
151 final SettableFuture<CommitInfo> resultFuture = SettableFuture.create();
152 Futures.addCallback(commitConfiguration(), new FutureCallback<RpcResult<Void>>() {
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()])));
163 resultFuture.set(CommitInfo.empty());
167 public void onFailure(final Throwable failure) {
168 resultFuture.setException(new TransactionCommitFailedException(
169 String.format("Commit of transaction %s failed", getIdentifier()), failure));
171 }, MoreExecutors.directExecutor());
173 return FluentFuture.from(resultFuture);
176 protected final ListenableFuture<RpcResult<Void>> commitConfiguration() {
177 listeners.forEach(listener -> listener.onTransactionSubmitted(this));
180 final ListenableFuture<RpcResult<Void>> result = performCommit();
181 Futures.addCallback(result, new FutureCallback<RpcResult<Void>>() {
183 public void onSuccess(@Nonnull final RpcResult<Void> rpcResult) {
184 if (rpcResult.isSuccessful()) {
185 listeners.forEach(txListener -> txListener.onTransactionSuccessful(AbstractWriteTx.this));
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));
195 public void onFailure(final Throwable throwable) {
196 listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, throwable));
198 }, MoreExecutors.directExecutor());
202 protected abstract ListenableFuture<RpcResult<Void>> performCommit();
204 private void checkEditable(final LogicalDatastoreType store) {
206 Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION,
207 "Can edit only configuration data, not %s", store);
210 protected abstract void editConfig(YangInstanceIdentifier path, Optional<NormalizedNode<?, ?>> data,
211 DataContainerChild<?, ?> editStructure,
212 Optional<ModifyAction> defaultOperation, String operation);
214 protected ListenableFuture<RpcResult<Void>> resultsToTxStatus() {
215 final SettableFuture<RpcResult<Void>> transformed = SettableFuture.create();
217 Futures.addCallback(Futures.allAsList(resultsFutures), new FutureCallback<List<DOMRpcResult>>() {
219 public void onSuccess(@Nonnull final List<DOMRpcResult> domRpcResults) {
220 if (!transformed.isDone()) {
221 extractResult(domRpcResults, transformed);
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);
236 }, MoreExecutors.directExecutor());
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";
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();
256 errType = DocumentedException.ErrorType.RPC;
259 errType = DocumentedException.ErrorType.PROTOCOL;
262 errType = DocumentedException.ErrorType.TRANSPORT;
265 errType = DocumentedException.ErrorType.APPLICATION;
268 errType = DocumentedException.ErrorType.APPLICATION;
271 final RpcError.ErrorSeverity severity = error.getSeverity();
274 errSeverity = DocumentedException.ErrorSeverity.ERROR;
277 errSeverity = DocumentedException.ErrorSeverity.WARNING;
280 errSeverity = DocumentedException.ErrorSeverity.ERROR;
283 msgBuilder.append(error.getMessage());
284 errorTag = error.getTag();
287 if (errorsEncouneterd) {
288 final NetconfDocumentedException exception = new NetconfDocumentedException(id
289 + ":RPC during tx failed. " + msgBuilder.toString(),
291 DocumentedException.ErrorTag.from(errorTag),
293 transformed.setException(exception);
296 transformed.set(RpcResultBuilder.<Void>success().build());
299 AutoCloseable addListener(final TxListener listener) {
300 listeners.add(listener);
301 return () -> listeners.remove(listener);