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