Merge changes from topic 'ListenerAdapterTreeMigration'
[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.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;
41
42 public abstract class AbstractWriteTx implements DOMDataWriteTransaction {
43
44     private static final Logger LOG  = LoggerFactory.getLogger(AbstractWriteTx.class);
45
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;
53
54     public AbstractWriteTx(final NetconfBaseOps netOps, final RemoteDeviceId id, final boolean rollbackSupport) {
55         this.netOps = netOps;
56         this.id = id;
57         this.rollbackSupport = rollbackSupport;
58         this.resultsFutures = Lists.newArrayList();
59         init();
60     }
61
62     protected static boolean isSuccess(final DOMRpcResult result) {
63         return result.getErrors().isEmpty();
64     }
65
66     protected void checkNotFinished() {
67         Preconditions.checkState(!isFinished(), "%s: Transaction %s already finished", id, getIdentifier());
68     }
69
70     protected boolean isFinished() {
71         return finished;
72     }
73
74     @Override
75     public synchronized boolean cancel() {
76         if (isFinished()) {
77             return false;
78         }
79         listeners.forEach(listener -> listener.onTransactionCancelled(this));
80         finished = true;
81         cleanup();
82         return true;
83     }
84
85     protected abstract void init();
86
87     protected abstract void cleanup();
88
89     @Override
90     public Object getIdentifier() {
91         return this;
92     }
93
94     @Override
95     public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
96                                  final NormalizedNode<?, ?> data) {
97         checkEditable(store);
98
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);
103             return;
104         }
105
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.of(ModifyAction.NONE), "put");
110     }
111
112     @Override
113     public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
114                                    final NormalizedNode<?, ?> data) {
115         checkEditable(store);
116
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);
121             return;
122         }
123
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");
128     }
129
130     /**
131      * Check whether the data to be written consists only from mixins.
132      */
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;
138     }
139
140     @Override
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");
148     }
149
150     @Override
151     public final ListenableFuture<RpcResult<TransactionStatus>> commit() {
152         listeners.forEach(listener -> listener.onTransactionSubmitted(this));
153         checkNotFinished();
154         finished = true;
155         final ListenableFuture<RpcResult<TransactionStatus>> result = performCommit();
156         Futures.addCallback(result, new FutureCallback<RpcResult<TransactionStatus>>() {
157             @Override
158             public void onSuccess(@Nullable final RpcResult<TransactionStatus> result) {
159                 if (result != null && result.isSuccessful()) {
160                     listeners.forEach(txListener -> txListener.onTransactionSuccessful(AbstractWriteTx.this));
161                 } else {
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));
166                 }
167             }
168
169             @Override
170             public void onFailure(final Throwable throwable) {
171                 listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, throwable));
172             }
173         }, MoreExecutors.directExecutor());
174         return result;
175     }
176
177     protected abstract ListenableFuture<RpcResult<TransactionStatus>> performCommit();
178
179     private void checkEditable(final LogicalDatastoreType store) {
180         checkNotFinished();
181         Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION,
182                 "Can edit only configuration data, not %s", store);
183     }
184
185     protected abstract void editConfig(YangInstanceIdentifier path, Optional<NormalizedNode<?, ?>> data,
186                                        DataContainerChild<?, ?> editStructure,
187                                        Optional<ModifyAction> defaultOperation, String operation);
188
189     protected ListenableFuture<RpcResult<TransactionStatus>> resultsToTxStatus() {
190         final SettableFuture<RpcResult<TransactionStatus>> transformed = SettableFuture.create();
191
192         Futures.addCallback(Futures.allAsList(resultsFutures), new FutureCallback<List<DOMRpcResult>>() {
193             @Override
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);
203                     }
204                 });
205
206                 if (!transformed.isDone()) {
207                     transformed.set(RpcResultBuilder.success(TransactionStatus.COMMITED).build());
208                 }
209             }
210
211             @Override
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);
221             }
222         }, MoreExecutors.directExecutor());
223
224         return transformed;
225     }
226
227     AutoCloseable addListener(final TxListener listener) {
228         listeners.add(listener);
229         return () -> listeners.remove(listener);
230     }
231 }