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.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;
41 public abstract class AbstractWriteTx implements DOMDataWriteTransaction {
43 private static final Logger LOG = LoggerFactory.getLogger(AbstractWriteTx.class);
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;
53 public AbstractWriteTx(final NetconfBaseOps netOps, final RemoteDeviceId id, final boolean rollbackSupport) {
56 this.rollbackSupport = rollbackSupport;
57 this.resultsFutures = Lists.newArrayList();
61 protected static boolean isSuccess(final DOMRpcResult result) {
62 return result.getErrors().isEmpty();
65 protected void checkNotFinished() {
66 Preconditions.checkState(!isFinished(), "%s: Transaction %s already finished", id, getIdentifier());
69 protected boolean isFinished() {
74 public synchronized boolean cancel() {
78 listeners.forEach(listener -> listener.onTransactionCancelled(this));
84 protected abstract void init();
86 protected abstract void cleanup();
89 public Object getIdentifier() {
94 public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
95 final NormalizedNode<?, ?> data) {
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);
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");
112 public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
113 final NormalizedNode<?, ?> data) {
114 checkEditable(store);
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);
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");
130 * Check whether the data to be written consists only from mixins.
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;
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");
149 protected final ListenableFuture<RpcResult<Void>> commitConfiguration() {
150 listeners.forEach(listener -> listener.onTransactionSubmitted(this));
153 final ListenableFuture<RpcResult<Void>> result = performCommit();
154 Futures.addCallback(result, new FutureCallback<RpcResult<Void>>() {
156 public void onSuccess(@Nonnull final RpcResult<Void> rpcResult) {
157 if (rpcResult.isSuccessful()) {
158 listeners.forEach(txListener -> txListener.onTransactionSuccessful(AbstractWriteTx.this));
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));
168 public void onFailure(final Throwable throwable) {
169 listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, throwable));
171 }, MoreExecutors.directExecutor());
175 protected abstract ListenableFuture<RpcResult<Void>> performCommit();
177 private void checkEditable(final LogicalDatastoreType store) {
179 Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION,
180 "Can edit only configuration data, not %s", store);
183 protected abstract void editConfig(YangInstanceIdentifier path, Optional<NormalizedNode<?, ?>> data,
184 DataContainerChild<?, ?> editStructure,
185 Optional<ModifyAction> defaultOperation, String operation);
187 protected ListenableFuture<RpcResult<Void>> resultsToTxStatus() {
188 final SettableFuture<RpcResult<Void>> transformed = SettableFuture.create();
190 Futures.addCallback(Futures.allAsList(resultsFutures), new FutureCallback<List<DOMRpcResult>>() {
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);
204 if (!transformed.isDone()) {
205 transformed.set(RpcResultBuilder.<Void>success().build());
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);
220 }, MoreExecutors.directExecutor());
225 AutoCloseable addListener(final TxListener listener) {
226 listeners.add(listener);
227 return () -> listeners.remove(listener);