Merge "Bug 8351: Enforce check-style rules for restconf - sal-rest-docgen"
[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,
48  *       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     public WriteCandidateTx(final RemoteDeviceId id, final NetconfBaseOps rpc, final boolean rollbackSupport) {
59         super(rpc, id, rollbackSupport);
60     }
61
62     @Override
63     protected synchronized void init() {
64         LOG.trace("{}: Initializing {} transaction", id, getClass().getSimpleName());
65         lock();
66     }
67
68     private void lock() {
69         final FutureCallback<DOMRpcResult> lockCandidateCallback = new FutureCallback<DOMRpcResult>() {
70             @Override
71             public void onSuccess(final DOMRpcResult result) {
72                 if (isSuccess(result)) {
73                     if (LOG.isTraceEnabled()) {
74                         LOG.trace("Lock candidate successful");
75                     }
76                 } else {
77                     LOG.warn("{}: lock candidate invoked unsuccessfully: {}", id, result.getErrors());
78                 }
79             }
80
81             @Override
82             public void onFailure(final Throwable throwable) {
83                 LOG.warn("Lock candidate operation failed. {}", throwable);
84                 discardChanges();
85             }
86         };
87         resultsFutures.add(netOps.lockCandidate(lockCandidateCallback));
88     }
89
90     @Override
91     protected void cleanup() {
92         discardChanges();
93         cleanupOnSuccess();
94     }
95
96     @Override
97     public synchronized CheckedFuture<Void, TransactionCommitFailedException> submit() {
98         final ListenableFuture<Void> commitFutureAsVoid = Futures.transform(commit(),
99                 new Function<RpcResult<TransactionStatus>, Void>() {
100                     @Override
101                     public Void apply(final RpcResult<TransactionStatus> input) {
102                         Preconditions.checkArgument(input.isSuccessful() && input.getErrors().isEmpty(),
103                                 "Submit failed with errors: %s", input.getErrors());
104                         return null;
105                     }
106                 });
107
108         return Futures.makeChecked(commitFutureAsVoid, new Function<Exception, TransactionCommitFailedException>() {
109             @Override
110             public TransactionCommitFailedException apply(final Exception input) {
111                 return new TransactionCommitFailedException(
112                         "Submit of transaction " + getIdentifier() + " failed", input);
113             }
114         });
115     }
116
117     /**
118      * This has to be non blocking since it is called from a callback on commit
119      * and its netty threadpool that is really sensitive to blocking calls.
120      */
121     private void discardChanges() {
122         netOps.discardChanges(new NetconfRpcFutureCallback("Discarding candidate", id));
123     }
124
125     @Override
126     public synchronized ListenableFuture<RpcResult<TransactionStatus>> performCommit() {
127         resultsFutures.add(netOps.commit(new NetconfRpcFutureCallback("Commit", id)));
128         final ListenableFuture<RpcResult<TransactionStatus>> txResult = resultsToTxStatus();
129
130         Futures.addCallback(txResult, new FutureCallback<RpcResult<TransactionStatus>>() {
131             @Override
132             public void onSuccess(@Nullable final RpcResult<TransactionStatus> result) {
133                 cleanupOnSuccess();
134             }
135
136             @Override
137             public void onFailure(final Throwable throwable) {
138                 // TODO If lock is cause of this failure cleanup will issue warning log
139                 // cleanup is trying to do unlock, but this will fail
140                 cleanup();
141             }
142         });
143
144         return txResult;
145     }
146
147     protected void cleanupOnSuccess() {
148         unlock();
149     }
150
151     @Override
152     protected void editConfig(final YangInstanceIdentifier path,
153                               final Optional<NormalizedNode<?, ?>> data,
154                               final DataContainerChild<?, ?> editStructure,
155                               final Optional<ModifyAction> defaultOperation,
156                               final String operation) {
157
158         final NetconfRpcFutureCallback editConfigCallback = new NetconfRpcFutureCallback("Edit candidate", id);
159
160         if (defaultOperation.isPresent()) {
161             resultsFutures.add(netOps.editConfigCandidate(
162                     editConfigCallback, editStructure, defaultOperation.get(), rollbackSupport));
163         } else {
164             resultsFutures.add(netOps.editConfigCandidate(editConfigCallback, editStructure, rollbackSupport));
165         }
166     }
167
168     /**
169      * This has to be non blocking since it is called from a callback on commit
170      * and its netty threadpool that is really sensitive to blocking calls.
171      */
172     private void unlock() {
173         netOps.unlockCandidate(new NetconfRpcFutureCallback("Unlock candidate", id));
174     }
175
176 }