Merge "Add sal-netconf-connector unit tests"
[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.FutureCallback;
16 import com.google.common.util.concurrent.Futures;
17 import com.google.common.util.concurrent.ListenableFuture;
18 import javax.annotation.Nullable;
19 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
20 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
21 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
22 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfBaseOps;
23 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfRpcFutureCallback;
24 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
25 import org.opendaylight.yangtools.yang.common.RpcResult;
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</li>
40  *       <li>Discard changes has to succeed</li>
41  *       <li>If discard is successful, lock is reattempted</li>
42  *       <li>Second lock attempt has to succeed</li>
43  *     </ul>
44  *   </li>
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</li>
48  *     </ul>
49  *   </li>
50  *   <li>Commit and Unlock candidate datastore async</li>
51  * </ol>
52  */
53 public class WriteCandidateTx extends AbstractWriteTx {
54
55     private static final Logger LOG  = LoggerFactory.getLogger(WriteCandidateTx.class);
56
57     public WriteCandidateTx(final RemoteDeviceId id, final NetconfBaseOps rpc, final boolean rollbackSupport) {
58         super(rpc, id, rollbackSupport);
59     }
60
61     @Override
62     protected synchronized void init() {
63         LOG.trace("{}: Initializing {} transaction", id, getClass().getSimpleName());
64         lock();
65     }
66
67     private void lock() {
68         final FutureCallback<DOMRpcResult> lockCandidateCallback = new FutureCallback<DOMRpcResult>() {
69             @Override
70             public void onSuccess(final DOMRpcResult result) {
71                 if (isSuccess(result)) {
72                     if (LOG.isTraceEnabled()) {
73                         LOG.trace("Lock candidate successful");
74                     }
75                 } else {
76                     LOG.warn("{}: lock candidate invoked unsuccessfully: {}", id, result.getErrors());
77                 }
78             }
79
80             @Override
81             public void onFailure(final Throwable t) {
82                 LOG.warn("Lock candidate operation failed. {}", t);
83                 discardChanges();
84             }
85         };
86         resultsFutures.add(netOps.lockCandidate(lockCandidateCallback));
87     }
88
89     @Override
90     protected void cleanup() {
91         discardChanges();
92         cleanupOnSuccess();
93     }
94
95     @Override
96     public synchronized CheckedFuture<Void, TransactionCommitFailedException> submit() {
97         final ListenableFuture<Void> commitFutureAsVoid = Futures.transform(commit(), new Function<RpcResult<TransactionStatus>, Void>() {
98             @Override
99             public Void apply(final RpcResult<TransactionStatus> input) {
100                 Preconditions.checkArgument(input.isSuccessful() && input.getErrors().isEmpty(), "Submit failed with errors: %s", input.getErrors());
101                 return null;
102             }
103         });
104
105         return Futures.makeChecked(commitFutureAsVoid, new Function<Exception, TransactionCommitFailedException>() {
106             @Override
107             public TransactionCommitFailedException apply(final Exception input) {
108                 return new TransactionCommitFailedException("Submit of transaction " + getIdentifier() + " failed", input);
109             }
110         });
111     }
112
113     /**
114      * 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
115      */
116     private void discardChanges() {
117         netOps.discardChanges(new NetconfRpcFutureCallback("Discarding candidate", id));
118     }
119
120     @Override
121     public synchronized ListenableFuture<RpcResult<TransactionStatus>> performCommit() {
122         resultsFutures.add(netOps.commit(new NetconfRpcFutureCallback("Commit", id)));
123         final ListenableFuture<RpcResult<TransactionStatus>> txResult = resultsToTxStatus();
124
125         Futures.addCallback(txResult, new FutureCallback<RpcResult<TransactionStatus>>() {
126             @Override
127             public void onSuccess(@Nullable final RpcResult<TransactionStatus> result) {
128                 cleanupOnSuccess();
129             }
130
131             @Override
132             public void onFailure(final Throwable t) {
133                 // TODO If lock is cause of this failure cleanup will issue warning log
134                 // cleanup is trying to do unlock, but this will fail
135                 cleanup();
136             }
137         });
138
139         return txResult;
140     }
141
142     protected void cleanupOnSuccess() {
143         unlock();
144     }
145
146     @Override
147     protected void editConfig(final YangInstanceIdentifier path,
148                               final Optional<NormalizedNode<?, ?>> data,
149                               final DataContainerChild<?, ?> editStructure,
150                               final Optional<ModifyAction> defaultOperation,
151                               final String operation) {
152
153         final NetconfRpcFutureCallback editConfigCallback = new NetconfRpcFutureCallback("Edit candidate", id);
154
155         if (defaultOperation.isPresent()) {
156             resultsFutures.add(netOps.editConfigCandidate(
157                     editConfigCallback, editStructure, defaultOperation.get(), rollbackSupport));
158         } else {
159             resultsFutures.add(netOps.editConfigCandidate(editConfigCallback, editStructure, rollbackSupport));
160         }
161     }
162
163     /**
164      * 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
165      */
166     private void unlock() {
167         netOps.unlockCandidate(new NetconfRpcFutureCallback("Unlock candidate", id));
168     }
169
170 }