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.Nullable;
22 import org.opendaylight.controller.config.util.xml.DocumentedException;
23 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
24 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
25 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
26 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
27 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
28 import org.opendaylight.netconf.api.NetconfDocumentedException;
29 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfBaseOps;
30 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
31 import org.opendaylight.yangtools.yang.common.RpcError;
32 import org.opendaylight.yangtools.yang.common.RpcResult;
33 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
34 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
37 import org.opendaylight.yangtools.yang.data.api.schema.MixinNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
42 public abstract class AbstractWriteTx implements DOMDataWriteTransaction {
44 private static final Logger LOG = LoggerFactory.getLogger(AbstractWriteTx.class);
46 protected final RemoteDeviceId id;
47 protected final NetconfBaseOps netOps;
48 protected final boolean rollbackSupport;
49 protected final List<ListenableFuture<DOMRpcResult>> resultsFutures;
50 private final List<TxListener> listeners = new CopyOnWriteArrayList<>();
51 // Allow commit to be called only once
52 protected boolean finished = false;
54 public AbstractWriteTx(final NetconfBaseOps netOps, final RemoteDeviceId id, final boolean rollbackSupport) {
57 this.rollbackSupport = rollbackSupport;
58 this.resultsFutures = Lists.newArrayList();
62 protected static boolean isSuccess(final DOMRpcResult result) {
63 return result.getErrors().isEmpty();
66 protected void checkNotFinished() {
67 Preconditions.checkState(!isFinished(), "%s: Transaction %s already finished", id, getIdentifier());
70 protected boolean isFinished() {
75 public synchronized boolean cancel() {
79 listeners.forEach(listener -> listener.onTransactionCancelled(this));
85 protected abstract void init();
87 protected abstract void cleanup();
90 public Object getIdentifier() {
95 public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
96 final NormalizedNode<?, ?> data) {
99 // Trying to write only mixin nodes (not visible when serialized).
100 // Ignoring. Some devices cannot handle empty edit-config rpc
101 if (containsOnlyNonVisibleData(path, data)) {
102 LOG.debug("Ignoring put for {} and data {}. Resulting data structure is empty.", path, data);
106 final DataContainerChild<?, ?> editStructure =
107 netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data),
108 Optional.of(ModifyAction.REPLACE), path);
109 editConfig(path, Optional.fromNullable(data), editStructure, Optional.<ModifyAction>absent(), "put");
113 public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
114 final NormalizedNode<?, ?> data) {
115 checkEditable(store);
117 // Trying to write only mixin nodes (not visible when serialized).
118 // Ignoring. Some devices cannot handle empty edit-config rpc
119 if (containsOnlyNonVisibleData(path, data)) {
120 LOG.debug("Ignoring merge for {} and data {}. Resulting data structure is empty.", path, data);
124 final DataContainerChild<?, ?> editStructure =
125 netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data),
126 Optional.<ModifyAction>absent(), path);
127 editConfig(path, Optional.fromNullable(data), editStructure, Optional.<ModifyAction>absent(), "merge");
131 * Check whether the data to be written consists only from mixins.
133 private static boolean containsOnlyNonVisibleData(final YangInstanceIdentifier path,
134 final NormalizedNode<?, ?> data) {
135 // There's only one such case:top level list (pathArguments == 1 && data is Mixin)
136 // any other mixin nodes are contained by a "regular" node thus visible when serialized
137 return path.getPathArguments().size() == 1 && data instanceof MixinNode;
141 public synchronized void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
142 checkEditable(store);
143 final DataContainerChild<?, ?> editStructure =
144 netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>absent(),
145 Optional.of(ModifyAction.DELETE), path);
146 editConfig(path, Optional.<NormalizedNode<?, ?>>absent(),
147 editStructure, Optional.of(ModifyAction.NONE), "delete");
151 public final ListenableFuture<RpcResult<TransactionStatus>> commit() {
152 listeners.forEach(listener -> listener.onTransactionSubmitted(this));
155 final ListenableFuture<RpcResult<TransactionStatus>> result = performCommit();
156 Futures.addCallback(result, new FutureCallback<RpcResult<TransactionStatus>>() {
158 public void onSuccess(@Nullable final RpcResult<TransactionStatus> result) {
159 if (result != null && result.isSuccessful()) {
160 listeners.forEach(txListener -> txListener.onTransactionSuccessful(AbstractWriteTx.this));
162 final TransactionCommitFailedException cause =
163 new TransactionCommitFailedException("Transaction failed",
164 result.getErrors().toArray(new RpcError[result.getErrors().size()]));
165 listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, cause));
170 public void onFailure(final Throwable throwable) {
171 listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, throwable));
173 }, MoreExecutors.directExecutor());
177 protected abstract ListenableFuture<RpcResult<TransactionStatus>> performCommit();
179 private void checkEditable(final LogicalDatastoreType store) {
181 Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION,
182 "Can edit only configuration data, not %s", store);
185 protected abstract void editConfig(YangInstanceIdentifier path, Optional<NormalizedNode<?, ?>> data,
186 DataContainerChild<?, ?> editStructure,
187 Optional<ModifyAction> defaultOperation, String operation);
189 protected ListenableFuture<RpcResult<TransactionStatus>> resultsToTxStatus() {
190 final SettableFuture<RpcResult<TransactionStatus>> transformed = SettableFuture.create();
192 Futures.addCallback(Futures.allAsList(resultsFutures), new FutureCallback<List<DOMRpcResult>>() {
194 public void onSuccess(final List<DOMRpcResult> domRpcResults) {
195 domRpcResults.forEach(domRpcResult -> {
196 if (!domRpcResult.getErrors().isEmpty() && !transformed.isDone()) {
197 final NetconfDocumentedException exception =
198 new NetconfDocumentedException(id + ":RPC during tx failed",
199 DocumentedException.ErrorType.APPLICATION,
200 DocumentedException.ErrorTag.OPERATION_FAILED,
201 DocumentedException.ErrorSeverity.ERROR);
202 transformed.setException(exception);
206 if (!transformed.isDone()) {
207 transformed.set(RpcResultBuilder.success(TransactionStatus.COMMITED).build());
212 public void onFailure(final Throwable throwable) {
213 final NetconfDocumentedException exception =
214 new NetconfDocumentedException(
215 id + ":RPC during tx returned an exception",
216 new Exception(throwable),
217 DocumentedException.ErrorType.APPLICATION,
218 DocumentedException.ErrorTag.OPERATION_FAILED,
219 DocumentedException.ErrorSeverity.ERROR);
220 transformed.setException(exception);
222 }, MoreExecutors.directExecutor());
227 AutoCloseable addListener(final TxListener listener) {
228 listeners.add(listener);
229 return () -> listeners.remove(listener);