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