Merge "Cleanup root pom "name"."
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / sal / connect / netconf / sal / tx / WriteCandidateTx.java
1 /*
2  * Copyright (c) 2014 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.controller.sal.connect.netconf.sal.tx;
10
11 import com.google.common.base.Function;
12 import com.google.common.base.Optional;
13 import com.google.common.util.concurrent.CheckedFuture;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
17 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
18 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
19 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
20 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionPreferences;
21 import org.opendaylight.controller.sal.connect.netconf.util.NetconfBaseOps;
22 import org.opendaylight.controller.sal.connect.netconf.util.NetconfRpcFutureCallback;
23 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
24 import org.opendaylight.yangtools.yang.common.RpcError;
25 import org.opendaylight.yangtools.yang.common.RpcResult;
26 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
27 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
28 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 /**
35  * Tx implementation for netconf devices that support only candidate datastore and no writable running
36  * The sequence goes as:
37  * <ol>
38  * <li/> Lock candidate datastore on tx construction
39  *  <ul>
40  * <li/> Lock has to succeed, if it does not, an attempt to discard changes is made
41  * <li/> Discard changes has to succeed
42  * <li/> If discard is successful, lock is reattempted
43  * <li/> Second lock attempt has to succeed
44  * </ul>
45  * <li/> Edit-config in candidate N times
46  * <ul>
47  * <li/> If any issue occurs during edit, datastore is discarded using discard-changes rpc, unlocked and an exception is thrown async
48  * </ul>
49  * <li/> Commit and Unlock candidate datastore async
50  * </ol>
51  */
52 public class WriteCandidateTx extends AbstractWriteTx {
53
54     private static final Logger LOG  = LoggerFactory.getLogger(WriteCandidateTx.class);
55
56     private static final Function<RpcResult<CompositeNode>, RpcResult<TransactionStatus>> RPC_RESULT_TO_TX_STATUS = new Function<RpcResult<CompositeNode>, RpcResult<TransactionStatus>>() {
57         @Override
58         public RpcResult<TransactionStatus> apply(final RpcResult<CompositeNode> input) {
59             if (input.isSuccessful()) {
60                 return RpcResultBuilder.success(TransactionStatus.COMMITED).build();
61             } else {
62                 final RpcResultBuilder<TransactionStatus> failed = RpcResultBuilder.failed();
63                 for (final RpcError rpcError : input.getErrors()) {
64                     failed.withError(rpcError.getErrorType(), rpcError.getTag(), rpcError.getMessage(),
65                             rpcError.getApplicationTag(), rpcError.getInfo(), rpcError.getCause());
66                 }
67                 return failed.build();
68             }
69         }
70     };
71
72     public WriteCandidateTx(final RemoteDeviceId id, final NetconfBaseOps rpc, final DataNormalizer normalizer, final NetconfSessionPreferences netconfSessionPreferences) {
73         super(rpc, id, normalizer, netconfSessionPreferences);
74     }
75
76     @Override
77     protected synchronized void init() {
78         LOG.trace("{}: Initializing {} transaction", id, getClass().getSimpleName());
79
80         try {
81             lock();
82         } catch (final NetconfDocumentedException e) {
83             try {
84                 LOG.warn("{}: Failed to lock candidate, attempting discard changes", id);
85                 discardChanges();
86                 LOG.warn("{}: Changes discarded successfully, attempting lock", id);
87                 lock();
88             } catch (final NetconfDocumentedException secondE) {
89                 LOG.error("{}: Failed to prepare candidate. Failed to initialize transaction", id, secondE);
90                 throw new RuntimeException(id + ": Failed to prepare candidate. Failed to initialize transaction", secondE);
91             }
92         }
93     }
94
95     private void lock() throws NetconfDocumentedException {
96         try {
97             invokeBlocking("Lock candidate", new Function<NetconfBaseOps, ListenableFuture<RpcResult<CompositeNode>>>() {
98                 @Override
99                 public ListenableFuture<RpcResult<CompositeNode>> apply(final NetconfBaseOps input) {
100                     return input.lockCandidate(new NetconfRpcFutureCallback("Lock candidate", id));
101                 }
102             });
103         } catch (final NetconfDocumentedException e) {
104             LOG.warn("{}: Failed to lock candidate", id, e);
105             throw e;
106         }
107     }
108
109     @Override
110     protected void cleanup() {
111         discardChanges();
112         cleanupOnSuccess();
113     }
114
115     @Override
116     protected void handleEditException(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data, final NetconfDocumentedException e, final String editType) {
117         LOG.warn("{}: Error " + editType + " data to (candidate){}, data: {}, canceling", id, path, data, e);
118         cancel();
119         throw new RuntimeException(id + ": Error while " + editType + ": (candidate)" + path, e);
120     }
121
122     @Override
123     protected void handleDeleteException(final YangInstanceIdentifier path, final NetconfDocumentedException e) {
124         LOG.warn("{}: Error deleting data (candidate){}, canceling", id, path, e);
125         cancel();
126         throw new RuntimeException(id + ": Error while deleting (candidate)" + path, e);
127     }
128
129     @Override
130     public synchronized CheckedFuture<Void, TransactionCommitFailedException> submit() {
131         final ListenableFuture<Void> commitFutureAsVoid = Futures.transform(commit(), new Function<RpcResult<TransactionStatus>, Void>() {
132             @Override
133             public Void apply(final RpcResult<TransactionStatus> input) {
134                 return null;
135             }
136         });
137
138         return Futures.makeChecked(commitFutureAsVoid, new Function<Exception, TransactionCommitFailedException>() {
139             @Override
140             public TransactionCommitFailedException apply(final Exception input) {
141                 return new TransactionCommitFailedException("Submit of transaction " + getIdentifier() + " failed", input);
142             }
143         });
144     }
145
146     /**
147      * This has to be non blocking since it is called from a callback on commit and its netty threadpool that is really sensitive to blocking calls
148      */
149     private void discardChanges() {
150         netOps.discardChanges(new NetconfRpcFutureCallback("Discarding candidate", id));
151     }
152
153     @Override
154     public synchronized ListenableFuture<RpcResult<TransactionStatus>> performCommit() {
155         final ListenableFuture<RpcResult<CompositeNode>> rpcResult = netOps.commit(new NetconfRpcFutureCallback("Commit", id) {
156             @Override
157             public void onSuccess(final RpcResult<CompositeNode> result) {
158                 super.onSuccess(result);
159                 LOG.debug("{}: Write successful, transaction: {}. Unlocking", id, getIdentifier());
160                 cleanupOnSuccess();
161             }
162
163             @Override
164             protected void onUnsuccess(final RpcResult<CompositeNode> result) {
165                 LOG.error("{}: Write failed, transaction {}, discarding changes, unlocking: {}", id, getIdentifier(), result.getErrors());
166                 cleanup();
167             }
168
169             @Override
170             public void onFailure(final Throwable t) {
171                 LOG.error("{}: Write failed, transaction {}, discarding changes, unlocking", id, getIdentifier(), t);
172                 cleanup();
173             }
174         });
175
176         return Futures.transform(rpcResult, RPC_RESULT_TO_TX_STATUS);
177     }
178
179     protected void cleanupOnSuccess() {
180         unlock();
181     }
182
183     @Override
184     protected void editConfig(final CompositeNode editStructure, final Optional<ModifyAction> defaultOperation) throws NetconfDocumentedException {
185         invokeBlocking("Edit candidate", new Function<NetconfBaseOps, ListenableFuture<RpcResult<CompositeNode>>>() {
186             @Override
187             public ListenableFuture<RpcResult<CompositeNode>> apply(final NetconfBaseOps input) {
188                         return defaultOperation.isPresent()
189                                 ? input.editConfigCandidate(new NetconfRpcFutureCallback("Edit candidate", id), editStructure, defaultOperation.get(),
190                                 netconfSessionPreferences.isRollbackSupported())
191                                 : input.editConfigCandidate(new NetconfRpcFutureCallback("Edit candidate", id), editStructure,
192                                 netconfSessionPreferences.isRollbackSupported());
193             }
194         });
195     }
196
197     /**
198      * This has to be non blocking since it is called from a callback on commit and its netty threadpool that is really sensitive to blocking calls
199      */
200     private void unlock() {
201         netOps.unlockCandidate(new NetconfRpcFutureCallback("Unlock candidate", id));
202     }
203
204 }