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