Merge "Implement AsyncWriteTransaction.commit()"
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / sal / connect / netconf / sal / tx / AbstractWriteTx.java
1 /*
2  * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.netconf.sal.connect.netconf.sal.tx;
10
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;
47
48 public abstract class AbstractWriteTx implements DOMDataWriteTransaction {
49
50     private static final Logger LOG  = LoggerFactory.getLogger(AbstractWriteTx.class);
51
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;
59
60     public AbstractWriteTx(final NetconfBaseOps netOps, final RemoteDeviceId id, final boolean rollbackSupport) {
61         this.netOps = netOps;
62         this.id = id;
63         this.rollbackSupport = rollbackSupport;
64         this.resultsFutures = Lists.newArrayList();
65         init();
66     }
67
68     protected static boolean isSuccess(final DOMRpcResult result) {
69         return result.getErrors().isEmpty();
70     }
71
72     protected void checkNotFinished() {
73         Preconditions.checkState(!isFinished(), "%s: Transaction %s already finished", id, getIdentifier());
74     }
75
76     protected boolean isFinished() {
77         return finished;
78     }
79
80     @Override
81     public synchronized boolean cancel() {
82         if (isFinished()) {
83             return false;
84         }
85         listeners.forEach(listener -> listener.onTransactionCancelled(this));
86         finished = true;
87         cleanup();
88         return true;
89     }
90
91     protected abstract void init();
92
93     protected abstract void cleanup();
94
95     @Override
96     public Object getIdentifier() {
97         return this;
98     }
99
100     @Override
101     public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
102                                  final NormalizedNode<?, ?> data) {
103         checkEditable(store);
104
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);
109             return;
110         }
111
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");
116     }
117
118     @Override
119     public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
120                                    final NormalizedNode<?, ?> data) {
121         checkEditable(store);
122
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);
127             return;
128         }
129
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");
134     }
135
136     /**
137      * Check whether the data to be written consists only from mixins.
138      */
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;
144     }
145
146     @Override
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");
154     }
155
156     @Override
157     public CheckedFuture<Void, TransactionCommitFailedException> submit() {
158         return MappingCheckedFuture.create(commit().transform(ignored -> null, MoreExecutors.directExecutor()),
159             new ExceptionMapper<TransactionCommitFailedException>("commit", TransactionCommitFailedException.class) {
160                 @Override
161                 protected TransactionCommitFailedException newWithCause(String message, Throwable cause) {
162                     return new TransactionCommitFailedException(message, cause);
163                 }
164             });
165     }
166
167     @Override
168     public @NonNull FluentFuture<? extends @NonNull CommitInfo> commit() {
169         final SettableFuture<CommitInfo> resultFuture = SettableFuture.create();
170         Futures.addCallback(commitConfiguration(), new FutureCallback<RpcResult<Void>>() {
171             @Override
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()])));
178                     return;
179                 }
180
181                 resultFuture.set(CommitInfo.empty());
182             }
183
184             @Override
185             public void onFailure(Throwable failure) {
186                 resultFuture.setException(new TransactionCommitFailedException(
187                         String.format("Commit of transaction %s failed", getIdentifier()), failure));
188             }
189         }, MoreExecutors.directExecutor());
190
191         return FluentFuture.from(resultFuture);
192     }
193
194     protected final ListenableFuture<RpcResult<Void>> commitConfiguration() {
195         listeners.forEach(listener -> listener.onTransactionSubmitted(this));
196         checkNotFinished();
197         finished = true;
198         final ListenableFuture<RpcResult<Void>> result = performCommit();
199         Futures.addCallback(result, new FutureCallback<RpcResult<Void>>() {
200             @Override
201             public void onSuccess(@Nonnull final RpcResult<Void> rpcResult) {
202                 if (rpcResult.isSuccessful()) {
203                     listeners.forEach(txListener -> txListener.onTransactionSuccessful(AbstractWriteTx.this));
204                 } else {
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));
209                 }
210             }
211
212             @Override
213             public void onFailure(final Throwable throwable) {
214                 listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, throwable));
215             }
216         }, MoreExecutors.directExecutor());
217         return result;
218     }
219
220     protected abstract ListenableFuture<RpcResult<Void>> performCommit();
221
222     private void checkEditable(final LogicalDatastoreType store) {
223         checkNotFinished();
224         Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION,
225                 "Can edit only configuration data, not %s", store);
226     }
227
228     protected abstract void editConfig(YangInstanceIdentifier path, Optional<NormalizedNode<?, ?>> data,
229                                        DataContainerChild<?, ?> editStructure,
230                                        Optional<ModifyAction> defaultOperation, String operation);
231
232     protected ListenableFuture<RpcResult<Void>> resultsToTxStatus() {
233         final SettableFuture<RpcResult<Void>> transformed = SettableFuture.create();
234
235         Futures.addCallback(Futures.allAsList(resultsFutures), new FutureCallback<List<DOMRpcResult>>() {
236             @Override
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);
246                     }
247                 });
248
249                 if (!transformed.isDone()) {
250                     transformed.set(RpcResultBuilder.<Void>success().build());
251                 }
252             }
253
254             @Override
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);
264             }
265         }, MoreExecutors.directExecutor());
266
267         return transformed;
268     }
269
270     AutoCloseable addListener(final TxListener listener) {
271         listeners.add(listener);
272         return () -> listeners.remove(listener);
273     }
274 }