Merge "Bug 8071 - Do not fail on modules with invalid revision during ...
[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             (Function<RpcResult<TransactionStatus>, Void>) input -> {
100                 Preconditions.checkArgument(input.isSuccessful() && input.getErrors().isEmpty(),
101                         "Submit failed with errors: %s", input.getErrors());
102                 return null;
103             });
104
105         return Futures.makeChecked(commitFutureAsVoid, input -> new TransactionCommitFailedException(
106                 "Submit of transaction " + getIdentifier() + " failed", input));
107     }
108
109     /**
110      * This has to be non blocking since it is called from a callback on commit
111      * and its netty threadpool that is really sensitive to blocking calls.
112      */
113     private void discardChanges() {
114         netOps.discardChanges(new NetconfRpcFutureCallback("Discarding candidate", id));
115     }
116
117     @Override
118     public synchronized ListenableFuture<RpcResult<TransactionStatus>> performCommit() {
119         resultsFutures.add(netOps.commit(new NetconfRpcFutureCallback("Commit", id)));
120         final ListenableFuture<RpcResult<TransactionStatus>> txResult = resultsToTxStatus();
121
122         Futures.addCallback(txResult, new FutureCallback<RpcResult<TransactionStatus>>() {
123             @Override
124             public void onSuccess(@Nullable final RpcResult<TransactionStatus> result) {
125                 cleanupOnSuccess();
126             }
127
128             @Override
129             public void onFailure(final Throwable throwable) {
130                 // TODO If lock is cause of this failure cleanup will issue warning log
131                 // cleanup is trying to do unlock, but this will fail
132                 cleanup();
133             }
134         });
135
136         return txResult;
137     }
138
139     protected void cleanupOnSuccess() {
140         unlock();
141     }
142
143     @Override
144     protected void editConfig(final YangInstanceIdentifier path,
145                               final Optional<NormalizedNode<?, ?>> data,
146                               final DataContainerChild<?, ?> editStructure,
147                               final Optional<ModifyAction> defaultOperation,
148                               final String operation) {
149
150         final NetconfRpcFutureCallback editConfigCallback = new NetconfRpcFutureCallback("Edit candidate", id);
151
152         if (defaultOperation.isPresent()) {
153             resultsFutures.add(netOps.editConfigCandidate(
154                     editConfigCallback, editStructure, defaultOperation.get(), rollbackSupport));
155         } else {
156             resultsFutures.add(netOps.editConfigCandidate(editConfigCallback, editStructure, rollbackSupport));
157         }
158     }
159
160     /**
161      * This has to be non blocking since it is called from a callback on commit
162      * and its netty threadpool that is really sensitive to blocking calls.
163      */
164     private void unlock() {
165         netOps.unlockCandidate(new NetconfRpcFutureCallback("Unlock candidate", id));
166     }
167
168 }