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

©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.