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