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