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.SettableFuture;
18 import java.util.List;
19 import java.util.concurrent.CopyOnWriteArrayList;
20 import javax.annotation.Nullable;
21 import org.opendaylight.controller.config.util.xml.DocumentedException;
22 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
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 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");
150 public final ListenableFuture<RpcResult<TransactionStatus>> commit() {
151 listeners.forEach(listener -> listener.onTransactionSubmitted(this));
154 final ListenableFuture<RpcResult<TransactionStatus>> result = performCommit();
155 Futures.addCallback(result, new FutureCallback<RpcResult<TransactionStatus>>() {
157 public void onSuccess(@Nullable final RpcResult<TransactionStatus> result) {
158 if (result != null && result.isSuccessful()) {
159 listeners.forEach(txListener -> txListener.onTransactionSuccessful(AbstractWriteTx.this));
161 final TransactionCommitFailedException cause =
162 new TransactionCommitFailedException("Transaction failed",
163 result.getErrors().toArray(new RpcError[result.getErrors().size()]));
164 listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, cause));
169 public void onFailure(final Throwable throwable) {
170 listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, throwable));
176 protected abstract ListenableFuture<RpcResult<TransactionStatus>> performCommit();
178 private void checkEditable(final LogicalDatastoreType store) {
180 Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION,
181 "Can edit only configuration data, not %s", store);
184 protected abstract void editConfig(YangInstanceIdentifier path, Optional<NormalizedNode<?, ?>> data,
185 DataContainerChild<?, ?> editStructure,
186 Optional<ModifyAction> defaultOperation, String operation);
188 protected ListenableFuture<RpcResult<TransactionStatus>> resultsToTxStatus() {
189 final SettableFuture<RpcResult<TransactionStatus>> transformed = SettableFuture.create();
191 Futures.addCallback(Futures.allAsList(resultsFutures), new FutureCallback<List<DOMRpcResult>>() {
193 public void onSuccess(final List<DOMRpcResult> domRpcResults) {
194 domRpcResults.forEach(domRpcResult -> {
195 if (!domRpcResult.getErrors().isEmpty() && !transformed.isDone()) {
196 final NetconfDocumentedException exception =
197 new NetconfDocumentedException(id + ":RPC during tx failed",
198 DocumentedException.ErrorType.APPLICATION,
199 DocumentedException.ErrorTag.OPERATION_FAILED,
200 DocumentedException.ErrorSeverity.ERROR);
201 transformed.setException(exception);
205 if (!transformed.isDone()) {
206 transformed.set(RpcResultBuilder.success(TransactionStatus.COMMITED).build());
211 public void onFailure(final Throwable throwable) {
212 final NetconfDocumentedException exception =
213 new NetconfDocumentedException(
214 id + ":RPC during tx returned an exception",
215 new Exception(throwable),
216 DocumentedException.ErrorType.APPLICATION,
217 DocumentedException.ErrorTag.OPERATION_FAILED,
218 DocumentedException.ErrorSeverity.ERROR);
219 transformed.setException(exception);
226 AutoCloseable addListener(final TxListener listener) {
227 listeners.add(listener);
228 return () -> listeners.remove(listener);