Deprecated Rpcs and RpcErrors helper classes
[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.connect.netconf.util.NetconfMessageTransformUtil;
37 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
38 import org.opendaylight.controller.sal.core.api.RpcImplementation;
39 import org.opendaylight.yangtools.yang.common.QName;
40 import org.opendaylight.yangtools.yang.common.RpcError;
41 import org.opendaylight.yangtools.yang.common.RpcResult;
42 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
43 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
44 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
45 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
46 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
47 import org.opendaylight.yangtools.yang.data.api.Node;
48 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
49 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
50 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
51 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 /**
56  *  Remote transaction that delegates data change to remote device using netconf messages.
57  */
58 final class NetconfDeviceTwoPhaseCommitTransaction implements DataCommitTransaction<InstanceIdentifier, CompositeNode> {
59
60     private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceTwoPhaseCommitTransaction.class);
61
62     private final DataModification<InstanceIdentifier, CompositeNode> modification;
63     private final RpcImplementation rpc;
64     private final boolean rollbackSupported;
65     private final RemoteDeviceId id;
66     private final CompositeNode targetNode;
67
68     public NetconfDeviceTwoPhaseCommitTransaction(final RemoteDeviceId id, final RpcImplementation rpc,
69             final DataModification<InstanceIdentifier, CompositeNode> modification,
70             final boolean candidateSupported, final boolean rollbackOnErrorSupported) {
71         this.id = id;
72         this.rpc = Preconditions.checkNotNull(rpc);
73         this.modification = Preconditions.checkNotNull(modification);
74         this.targetNode = getTargetNode(candidateSupported);
75         this.rollbackSupported = rollbackOnErrorSupported;
76     }
77
78     /**
79      * Prepare phase, sends 1 or more netconf edit config operations to modify the data
80      *
81      * In case of failure or unexpected error response, ExecutionException is thrown
82      */
83     void prepare() throws InterruptedException, ExecutionException {
84         for (final InstanceIdentifier toRemove : modification.getRemovedConfigurationData()) {
85             sendDelete(toRemove);
86         }
87         for(final Entry<InstanceIdentifier, CompositeNode> toUpdate : modification.getUpdatedConfigurationData().entrySet()) {
88             sendMerge(toUpdate.getKey(),toUpdate.getValue());
89         }
90     }
91
92     private void sendMerge(final InstanceIdentifier key, final CompositeNode value) throws InterruptedException, ExecutionException {
93         sendEditRpc(createEditConfigStructure(key, Optional.<String>absent(), Optional.of(value)), Optional.<String>absent());
94     }
95
96     private void sendDelete(final InstanceIdentifier toDelete) throws InterruptedException, ExecutionException {
97         // FIXME use org.opendaylight.yangtools.yang.data.api.ModifyAction instead of strings
98         // TODO add string lowercase value to ModifyAction enum entries
99         sendEditRpc(createEditConfigStructure(toDelete, Optional.of("delete"), Optional.<CompositeNode>absent()), Optional.of("none"));
100     }
101
102     private void sendEditRpc(final CompositeNode editStructure, final Optional<String> 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<String> 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             SimpleNode<String> defOp = NodeFactory.createImmutableSimpleNode(NETCONF_DEFAULT_OPERATION_QNAME, null, 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<String> 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<String> 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, 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     /**
200      * Send commit rpc to finish the transaction
201      * In case of failure or unexpected error response, ExecutionException is thrown
202      */
203     @Override
204     public RpcResult<Void> finish() {
205         try {
206             final RpcResult<?> rpcResult = rpc.invokeRpc(NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME, getCommitRequest()).get();
207             return new RpcResultVoidWrapper(rpcResult);
208         } catch (final InterruptedException e) {
209             Thread.currentThread().interrupt();
210             throw new RuntimeException(id + ": Interrupted while waiting for response", e);
211         } catch (final ExecutionException e) {
212             LOG.warn("{}: Failed to finish commit operation", id, e);
213             return RpcResultBuilder.<Void>failed().withError( RpcError.ErrorType.APPLICATION,
214                             id + ": Unexpected operation error during commit operation", e ).build();
215         }
216     }
217
218     private ImmutableCompositeNode getCommitRequest() {
219         final CompositeNodeBuilder<ImmutableCompositeNode> commitInput = ImmutableCompositeNode.builder();
220         commitInput.setQName(NETCONF_COMMIT_QNAME);
221         return commitInput.toInstance();
222     }
223
224     @Override
225     public DataModification<InstanceIdentifier, CompositeNode> getModification() {
226         return this.modification;
227     }
228
229     @Override
230     public RpcResult<Void> rollback() throws IllegalStateException {
231         // TODO BUG-732 implement rollback by sending discard changes
232         return null;
233     }
234
235     public CompositeNode getTargetNode(final boolean candidateSupported) {
236         if(candidateSupported) {
237             return ImmutableCompositeNode.create(NETCONF_CANDIDATE_QNAME, ImmutableList.<Node<?>>of());
238         } else {
239             return ImmutableCompositeNode.create(NETCONF_RUNNING_QNAME, ImmutableList.<Node<?>>of());
240         }
241     }
242
243     private static final class RpcResultVoidWrapper implements RpcResult<Void> {
244
245         private final RpcResult<?> rpcResult;
246
247         public RpcResultVoidWrapper(final RpcResult<?> rpcResult) {
248             this.rpcResult = rpcResult;
249         }
250
251         @Override
252         public boolean isSuccessful() {
253             return rpcResult.isSuccessful();
254         }
255
256         @Override
257         public Void getResult() {
258             return null;
259         }
260
261         @Override
262         public Collection<RpcError> getErrors() {
263             return rpcResult.getErrors();
264         }
265     }
266 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.