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.CheckedFuture;
15 import com.google.common.util.concurrent.FluentFuture;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.MoreExecutors;
20 import com.google.common.util.concurrent.SettableFuture;
21 import java.util.Collection;
22 import java.util.List;
23 import java.util.concurrent.CopyOnWriteArrayList;
24 import javax.annotation.Nonnull;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
27 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
28 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
29 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
30 import org.opendaylight.mdsal.common.api.CommitInfo;
31 import org.opendaylight.mdsal.common.api.MappingCheckedFuture;
32 import org.opendaylight.netconf.api.DocumentedException;
33 import org.opendaylight.netconf.api.NetconfDocumentedException;
34 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfBaseOps;
35 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
36 import org.opendaylight.yangtools.util.concurrent.ExceptionMapper;
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.ModifyAction;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
43 import org.opendaylight.yangtools.yang.data.api.schema.MixinNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
48 public abstract class AbstractWriteTx implements DOMDataWriteTransaction {
50 private static final Logger LOG = LoggerFactory.getLogger(AbstractWriteTx.class);
52 protected final RemoteDeviceId id;
53 protected final NetconfBaseOps netOps;
54 protected final boolean rollbackSupport;
55 protected final List<ListenableFuture<DOMRpcResult>> resultsFutures;
56 private final List<TxListener> listeners = new CopyOnWriteArrayList<>();
57 // Allow commit to be called only once
58 protected volatile boolean finished = false;
60 public AbstractWriteTx(final NetconfBaseOps netOps, final RemoteDeviceId id, final boolean rollbackSupport) {
63 this.rollbackSupport = rollbackSupport;
64 this.resultsFutures = Lists.newArrayList();
68 protected static boolean isSuccess(final DOMRpcResult result) {
69 return result.getErrors().isEmpty();
72 protected void checkNotFinished() {
73 Preconditions.checkState(!isFinished(), "%s: Transaction %s already finished", id, getIdentifier());
76 protected boolean isFinished() {
81 public synchronized boolean cancel() {
85 listeners.forEach(listener -> listener.onTransactionCancelled(this));
91 protected abstract void init();
93 protected abstract void cleanup();
96 public Object getIdentifier() {
101 public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
102 final NormalizedNode<?, ?> data) {
103 checkEditable(store);
105 // Trying to write only mixin nodes (not visible when serialized).
106 // Ignoring. Some devices cannot handle empty edit-config rpc
107 if (containsOnlyNonVisibleData(path, data)) {
108 LOG.debug("Ignoring put for {} and data {}. Resulting data structure is empty.", path, data);
112 final DataContainerChild<?, ?> editStructure =
113 netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data),
114 Optional.of(ModifyAction.REPLACE), path);
115 editConfig(path, Optional.fromNullable(data), editStructure, Optional.<ModifyAction>absent(), "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 =
131 netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data),
132 Optional.<ModifyAction>absent(), path);
133 editConfig(path, Optional.fromNullable(data), editStructure, Optional.<ModifyAction>absent(), "merge");
137 * Check whether the data to be written consists only from mixins.
139 private static boolean containsOnlyNonVisibleData(final YangInstanceIdentifier path,
140 final NormalizedNode<?, ?> data) {
141 // There's only one such case:top level list (pathArguments == 1 && data is Mixin)
142 // any other mixin nodes are contained by a "regular" node thus visible when serialized
143 return path.getPathArguments().size() == 1 && data instanceof MixinNode;
147 public synchronized void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
148 checkEditable(store);
149 final DataContainerChild<?, ?> editStructure =
150 netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>absent(),
151 Optional.of(ModifyAction.DELETE), path);
152 editConfig(path, Optional.<NormalizedNode<?, ?>>absent(),
153 editStructure, Optional.of(ModifyAction.NONE), "delete");
157 public CheckedFuture<Void, TransactionCommitFailedException> submit() {
158 return MappingCheckedFuture.create(commit().transform(ignored -> null, MoreExecutors.directExecutor()),
159 new ExceptionMapper<TransactionCommitFailedException>("commit", TransactionCommitFailedException.class) {
161 protected TransactionCommitFailedException newWithCause(String message, Throwable cause) {
162 return new TransactionCommitFailedException(message, cause);
168 public @NonNull FluentFuture<? extends @NonNull CommitInfo> commit() {
169 final SettableFuture<CommitInfo> resultFuture = SettableFuture.create();
170 Futures.addCallback(commitConfiguration(), new FutureCallback<RpcResult<Void>>() {
172 public void onSuccess(RpcResult<Void> result) {
173 if (!result.isSuccessful()) {
174 final Collection<RpcError> errors = result.getErrors();
175 resultFuture.setException(new TransactionCommitFailedException(
176 String.format("Commit of transaction %s failed", getIdentifier()),
177 errors.toArray(new RpcError[errors.size()])));
181 resultFuture.set(CommitInfo.empty());
185 public void onFailure(Throwable failure) {
186 resultFuture.setException(new TransactionCommitFailedException(
187 String.format("Commit of transaction %s failed", getIdentifier()), failure));
189 }, MoreExecutors.directExecutor());
191 return FluentFuture.from(resultFuture);
194 protected final ListenableFuture<RpcResult<Void>> commitConfiguration() {
195 listeners.forEach(listener -> listener.onTransactionSubmitted(this));
198 final ListenableFuture<RpcResult<Void>> result = performCommit();
199 Futures.addCallback(result, new FutureCallback<RpcResult<Void>>() {
201 public void onSuccess(@Nonnull final RpcResult<Void> rpcResult) {
202 if (rpcResult.isSuccessful()) {
203 listeners.forEach(txListener -> txListener.onTransactionSuccessful(AbstractWriteTx.this));
205 final TransactionCommitFailedException cause =
206 new TransactionCommitFailedException("Transaction failed",
207 rpcResult.getErrors().toArray(new RpcError[rpcResult.getErrors().size()]));
208 listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, cause));
213 public void onFailure(final Throwable throwable) {
214 listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, throwable));
216 }, MoreExecutors.directExecutor());
220 protected abstract ListenableFuture<RpcResult<Void>> performCommit();
222 private void checkEditable(final LogicalDatastoreType store) {
224 Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION,
225 "Can edit only configuration data, not %s", store);
228 protected abstract void editConfig(YangInstanceIdentifier path, Optional<NormalizedNode<?, ?>> data,
229 DataContainerChild<?, ?> editStructure,
230 Optional<ModifyAction> defaultOperation, String operation);
232 protected ListenableFuture<RpcResult<Void>> resultsToTxStatus() {
233 final SettableFuture<RpcResult<Void>> transformed = SettableFuture.create();
235 Futures.addCallback(Futures.allAsList(resultsFutures), new FutureCallback<List<DOMRpcResult>>() {
237 public void onSuccess(@Nonnull final List<DOMRpcResult> domRpcResults) {
238 domRpcResults.forEach(domRpcResult -> {
239 if (!domRpcResult.getErrors().isEmpty() && !transformed.isDone()) {
240 final NetconfDocumentedException exception =
241 new NetconfDocumentedException(id + ":RPC during tx failed",
242 DocumentedException.ErrorType.APPLICATION,
243 DocumentedException.ErrorTag.OPERATION_FAILED,
244 DocumentedException.ErrorSeverity.ERROR);
245 transformed.setException(exception);
249 if (!transformed.isDone()) {
250 transformed.set(RpcResultBuilder.<Void>success().build());
255 public void onFailure(final Throwable throwable) {
256 final NetconfDocumentedException exception =
257 new NetconfDocumentedException(
258 id + ":RPC during tx returned an exception",
259 new Exception(throwable),
260 DocumentedException.ErrorType.APPLICATION,
261 DocumentedException.ErrorTag.OPERATION_FAILED,
262 DocumentedException.ErrorSeverity.ERROR);
263 transformed.setException(exception);
265 }, MoreExecutors.directExecutor());
270 AutoCloseable addListener(final TxListener listener) {
271 listeners.add(listener);
272 return () -> listeners.remove(listener);