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