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.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;
45 public abstract class AbstractWriteTx implements DOMDataWriteTransaction {
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 =
110 netOps.createEditConfigStrcture(Optional.fromNullable(data),
111 Optional.of(ModifyAction.REPLACE), path);
112 editConfig(path, Optional.fromNullable(data), editStructure, Optional.absent(), "put");
116 public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
117 final NormalizedNode<?, ?> data) {
118 checkEditable(store);
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);
127 final DataContainerChild<?, ?> editStructure =
128 netOps.createEditConfigStrcture(Optional.fromNullable(data),
129 Optional.absent(), path);
130 editConfig(path, Optional.fromNullable(data), editStructure, Optional.absent(), "merge");
134 * Check whether the data to be written consists only from mixins.
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;
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");
154 public @NonNull FluentFuture<? extends @NonNull CommitInfo> commit() {
155 final SettableFuture<CommitInfo> resultFuture = SettableFuture.create();
156 Futures.addCallback(commitConfiguration(), new FutureCallback<RpcResult<Void>>() {
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()])));
167 resultFuture.set(CommitInfo.empty());
171 public void onFailure(Throwable failure) {
172 resultFuture.setException(new TransactionCommitFailedException(
173 String.format("Commit of transaction %s failed", getIdentifier()), failure));
175 }, MoreExecutors.directExecutor());
177 return FluentFuture.from(resultFuture);
180 protected final ListenableFuture<RpcResult<Void>> commitConfiguration() {
181 listeners.forEach(listener -> listener.onTransactionSubmitted(this));
184 final ListenableFuture<RpcResult<Void>> result = performCommit();
185 Futures.addCallback(result, new FutureCallback<RpcResult<Void>>() {
187 public void onSuccess(@Nonnull final RpcResult<Void> rpcResult) {
188 if (rpcResult.isSuccessful()) {
189 listeners.forEach(txListener -> txListener.onTransactionSuccessful(AbstractWriteTx.this));
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));
199 public void onFailure(final Throwable throwable) {
200 listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, throwable));
202 }, MoreExecutors.directExecutor());
206 protected abstract ListenableFuture<RpcResult<Void>> performCommit();
208 private void checkEditable(final LogicalDatastoreType store) {
210 Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION,
211 "Can edit only configuration data, not %s", store);
214 protected abstract void editConfig(YangInstanceIdentifier path, Optional<NormalizedNode<?, ?>> data,
215 DataContainerChild<?, ?> editStructure,
216 Optional<ModifyAction> defaultOperation, String operation);
218 protected ListenableFuture<RpcResult<Void>> resultsToTxStatus() {
219 final SettableFuture<RpcResult<Void>> transformed = SettableFuture.create();
221 Futures.addCallback(Futures.allAsList(resultsFutures), new FutureCallback<List<DOMRpcResult>>() {
223 public void onSuccess(@Nonnull final List<DOMRpcResult> domRpcResults) {
224 if (!transformed.isDone()) {
225 extractResult(domRpcResults, transformed);
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);
240 }, MoreExecutors.directExecutor());
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;
254 eType = DocumentedException.ErrorType.RPC;
257 eType = DocumentedException.ErrorType.PROTOCOL;
260 eType = DocumentedException.ErrorType.TRANSPORT;
263 eType = DocumentedException.ErrorType.APPLICATION;
266 eType = DocumentedException.ErrorType.APPLICATION;
269 final RpcError.ErrorSeverity severity = error.getSeverity();
270 final DocumentedException.ErrorSeverity eSeverity;
273 eSeverity = DocumentedException.ErrorSeverity.ERROR;
276 eSeverity = DocumentedException.ErrorSeverity.WARNING;
279 eSeverity = DocumentedException.ErrorSeverity.ERROR;
282 final String message;
283 if (error.getMessage() == null || error.getMessage().isEmpty()) {
284 message = id + ":RPC during tx failed";
286 message = error.getMessage();
288 final NetconfDocumentedException exception = new NetconfDocumentedException(message,
290 DocumentedException.ErrorTag.from(error.getTag()),
292 transformed.setException(exception);
297 transformed.set(RpcResultBuilder.<Void>success().build());
300 AutoCloseable addListener(final TxListener listener) {
301 listeners.add(listener);
302 return () -> listeners.remove(listener);