Complete implementation of DataChangeListenerProxy
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / sal / connect / netconf / sal / NetconfDeviceTwoPhaseCommitTransaction.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 package org.opendaylight.controller.sal.connect.netconf.sal;
9
10 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_CANDIDATE_QNAME;
11 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME;
12 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_CONFIG_QNAME;
13 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_DEFAULT_OPERATION_QNAME;
14 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME;
15 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_ERROR_OPTION_QNAME;
16 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_OPERATION_QNAME;
17 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_RUNNING_QNAME;
18 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_TARGET_QNAME;
19 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.ROLLBACK_ON_ERROR_OPTION;
20
21 import com.google.common.base.Optional;
22 import com.google.common.base.Preconditions;
23 import com.google.common.collect.ImmutableList;
24 import com.google.common.collect.Lists;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Map.Entry;
30 import java.util.concurrent.ExecutionException;
31 import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler.DataCommitTransaction;
32 import org.opendaylight.controller.md.sal.common.api.data.DataModification;
33 import org.opendaylight.controller.sal.common.util.RpcErrors;
34 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
35 import org.opendaylight.controller.sal.connect.util.FailedRpcResult;
36 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
37 import org.opendaylight.controller.sal.core.api.RpcImplementation;
38 import org.opendaylight.yangtools.yang.common.QName;
39 import org.opendaylight.yangtools.yang.common.RpcError;
40 import org.opendaylight.yangtools.yang.common.RpcResult;
41 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
42 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
44 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
45 import org.opendaylight.yangtools.yang.data.api.Node;
46 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
47 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
48 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
49 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 /**
54  *  Remote transaction that delegates data change to remote device using netconf messages.
55  */
56 final class NetconfDeviceTwoPhaseCommitTransaction implements DataCommitTransaction<InstanceIdentifier, CompositeNode> {
57
58     private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceTwoPhaseCommitTransaction.class);
59
60     private final DataModification<InstanceIdentifier, CompositeNode> modification;
61     private final RpcImplementation rpc;
62     private final boolean rollbackSupported;
63     private final RemoteDeviceId id;
64     private final CompositeNode targetNode;
65
66     public NetconfDeviceTwoPhaseCommitTransaction(final RemoteDeviceId id, final RpcImplementation rpc,
67             final DataModification<InstanceIdentifier, CompositeNode> modification,
68             final boolean candidateSupported, final boolean rollbackOnErrorSupported) {
69         this.id = id;
70         this.rpc = Preconditions.checkNotNull(rpc);
71         this.modification = Preconditions.checkNotNull(modification);
72         this.targetNode = getTargetNode(candidateSupported);
73         this.rollbackSupported = rollbackOnErrorSupported;
74     }
75
76     /**
77      * Prepare phase, sends 1 or more netconf edit config operations to modify the data
78      *
79      * In case of failure or unexpected error response, ExecutionException is thrown
80      */
81     void prepare() throws InterruptedException, ExecutionException {
82         for (final InstanceIdentifier toRemove : modification.getRemovedConfigurationData()) {
83             sendDelete(toRemove);
84         }
85         for(final Entry<InstanceIdentifier, CompositeNode> toUpdate : modification.getUpdatedConfigurationData().entrySet()) {
86             sendMerge(toUpdate.getKey(),toUpdate.getValue());
87         }
88     }
89
90     private void sendMerge(final InstanceIdentifier key, final CompositeNode value) throws InterruptedException, ExecutionException {
91         sendEditRpc(createEditConfigStructure(key, Optional.<String>absent(), Optional.of(value)), Optional.<String>absent());
92     }
93
94     private void sendDelete(final InstanceIdentifier toDelete) throws InterruptedException, ExecutionException {
95         // FIXME use org.opendaylight.yangtools.yang.data.api.ModifyAction instead of strings
96         // TODO add string lowercase value to ModifyAction enum entries
97         sendEditRpc(createEditConfigStructure(toDelete, Optional.of("delete"), Optional.<CompositeNode>absent()), Optional.of("none"));
98     }
99
100     private void sendEditRpc(final CompositeNode editStructure, final Optional<String> defaultOperation) throws InterruptedException, ExecutionException {
101         final ImmutableCompositeNode editConfigRequest = createEditConfigRequest(editStructure, defaultOperation);
102         final RpcResult<CompositeNode> rpcResult = rpc.invokeRpc(NETCONF_EDIT_CONFIG_QNAME, editConfigRequest).get();
103
104         // Check result
105         if(rpcResult.isSuccessful() == false) {
106             throw new ExecutionException(
107                     String.format("%s: Pre-commit rpc failed, request: %s, errors: %s", id, editConfigRequest, rpcResult.getErrors()), null);
108         }
109     }
110
111     private ImmutableCompositeNode createEditConfigRequest(final CompositeNode editStructure, Optional<String> defaultOperation) {
112         final CompositeNodeBuilder<ImmutableCompositeNode> ret = ImmutableCompositeNode.builder();
113
114         // Target
115         final Node<?> targetWrapperNode = ImmutableCompositeNode.create(NETCONF_TARGET_QNAME, ImmutableList.<Node<?>>of(targetNode));
116         ret.add(targetWrapperNode);
117
118         // Default operation
119         if(defaultOperation.isPresent()) {
120             SimpleNode<String> defOp = NodeFactory.createImmutableSimpleNode(NETCONF_DEFAULT_OPERATION_QNAME, null, defaultOperation.get());
121             ret.add(defOp);
122         }
123
124         // Error option
125         if(rollbackSupported) {
126             ret.addLeaf(NETCONF_ERROR_OPTION_QNAME, ROLLBACK_ON_ERROR_OPTION);
127         }
128
129         ret.setQName(NETCONF_EDIT_CONFIG_QNAME);
130         // Edit content
131         ret.add(editStructure);
132         return ret.toInstance();
133     }
134
135     private CompositeNode createEditConfigStructure(final InstanceIdentifier dataPath, final Optional<String> operation,
136                                                     final Optional<CompositeNode> lastChildOverride) {
137         Preconditions.checkArgument(dataPath.getPath().isEmpty() == false, "Instance identifier with empty path %s", dataPath);
138
139         List<PathArgument> reversedPath = Lists.reverse(dataPath.getPath());
140
141         // Create deepest edit element with expected edit operation
142         CompositeNode previous = getDeepestEditElement(reversedPath.get(0), operation, lastChildOverride);
143
144         // Remove already processed deepest child
145         reversedPath = Lists.newArrayList(reversedPath);
146         reversedPath.remove(0);
147
148         // Create edit structure in reversed order
149         for (final PathArgument arg : reversedPath) {
150             final CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
151             builder.setQName(arg.getNodeType());
152
153             addPredicatesToCompositeNodeBuilder(getPredicates(arg), builder);
154
155             builder.add(previous);
156             previous = builder.toInstance();
157         }
158         return ImmutableCompositeNode.create(NETCONF_CONFIG_QNAME, ImmutableList.<Node<?>>of(previous));
159     }
160
161     private void addPredicatesToCompositeNodeBuilder(final Map<QName, Object> predicates, final CompositeNodeBuilder<ImmutableCompositeNode> builder) {
162         for (final Entry<QName, Object> entry : predicates.entrySet()) {
163             builder.addLeaf(entry.getKey(), entry.getValue());
164         }
165     }
166
167     private Map<QName, Object> getPredicates(final PathArgument arg) {
168         Map<QName, Object> predicates = Collections.emptyMap();
169         if (arg instanceof NodeIdentifierWithPredicates) {
170             predicates = ((NodeIdentifierWithPredicates) arg).getKeyValues();
171         }
172         return predicates;
173     }
174
175     private CompositeNode getDeepestEditElement(final PathArgument arg, final Optional<String> operation, final Optional<CompositeNode> lastChildOverride) {
176         final CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
177         builder.setQName(arg.getNodeType());
178
179         final Map<QName, Object> predicates = getPredicates(arg);
180         addPredicatesToCompositeNodeBuilder(predicates, builder);
181
182         if (operation.isPresent()) {
183             builder.setAttribute(NETCONF_OPERATION_QNAME, operation.get());
184         }
185         if (lastChildOverride.isPresent()) {
186             final List<Node<?>> children = lastChildOverride.get().getValue();
187             for(final Node<?> child : children) {
188                 if(!predicates.containsKey(child.getKey())) {
189                     builder.add(child);
190                 }
191             }
192         }
193
194         return builder.toInstance();
195     }
196
197     /**
198      * Send commit rpc to finish the transaction
199      * In case of failure or unexpected error response, ExecutionException is thrown
200      */
201     @Override
202     public RpcResult<Void> finish() {
203         try {
204             final RpcResult<?> rpcResult = rpc.invokeRpc(NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME, getCommitRequest()).get();
205             return new RpcResultVoidWrapper(rpcResult);
206         } catch (final InterruptedException e) {
207             Thread.currentThread().interrupt();
208             throw new RuntimeException(id + ": Interrupted while waiting for response", e);
209         } catch (final ExecutionException e) {
210             LOG.warn("{}: Failed to finish commit operation", id, e);
211             return new FailedRpcResult<>(RpcErrors.getRpcError(null, null, null, RpcError.ErrorSeverity.ERROR,
212                     id + ": Unexpected operation error during commit operation", RpcError.ErrorType.APPLICATION, e));
213         }
214     }
215
216     private ImmutableCompositeNode getCommitRequest() {
217         final CompositeNodeBuilder<ImmutableCompositeNode> commitInput = ImmutableCompositeNode.builder();
218         commitInput.setQName(NETCONF_COMMIT_QNAME);
219         return commitInput.toInstance();
220     }
221
222     @Override
223     public DataModification<InstanceIdentifier, CompositeNode> getModification() {
224         return this.modification;
225     }
226
227     @Override
228     public RpcResult<Void> rollback() throws IllegalStateException {
229         // TODO BUG-732 implement rollback by sending discard changes
230         return null;
231     }
232
233     public CompositeNode getTargetNode(final boolean candidateSupported) {
234         if(candidateSupported) {
235             return ImmutableCompositeNode.create(NETCONF_CANDIDATE_QNAME, ImmutableList.<Node<?>>of());
236         } else {
237             return ImmutableCompositeNode.create(NETCONF_RUNNING_QNAME, ImmutableList.<Node<?>>of());
238         }
239     }
240
241     private static final class RpcResultVoidWrapper implements RpcResult<Void> {
242
243         private final RpcResult<?> rpcResult;
244
245         public RpcResultVoidWrapper(final RpcResult<?> rpcResult) {
246             this.rpcResult = rpcResult;
247         }
248
249         @Override
250         public boolean isSuccessful() {
251             return rpcResult.isSuccessful();
252         }
253
254         @Override
255         public Void getResult() {
256             return null;
257         }
258
259         @Override
260         public Collection<RpcError> getErrors() {
261             return rpcResult.getErrors();
262         }
263     }
264 }