Implementation of ModuleShardStrategy
[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.ModifyAction;
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.<ModifyAction>absent(), Optional.of(value)), Optional.<ModifyAction>absent());
95     }
96
97     private void sendDelete(final InstanceIdentifier toDelete) throws InterruptedException, ExecutionException {
98         sendEditRpc(createEditConfigStructure(toDelete, Optional.of(ModifyAction.DELETE), Optional.<CompositeNode>absent()), Optional.of(ModifyAction.NONE));
99     }
100
101     private void sendEditRpc(final CompositeNode editStructure, final Optional<ModifyAction> defaultOperation) throws InterruptedException, ExecutionException {
102         final ImmutableCompositeNode editConfigRequest = createEditConfigRequest(editStructure, defaultOperation);
103         final RpcResult<CompositeNode> rpcResult = rpc.invokeRpc(NETCONF_EDIT_CONFIG_QNAME, editConfigRequest).get();
104
105         // Check result
106         if(rpcResult.isSuccessful() == false) {
107             throw new ExecutionException(
108                     String.format("%s: Pre-commit rpc failed, request: %s, errors: %s", id, editConfigRequest, rpcResult.getErrors()), null);
109         }
110     }
111
112     private ImmutableCompositeNode createEditConfigRequest(final CompositeNode editStructure, final Optional<ModifyAction> defaultOperation) {
113         final CompositeNodeBuilder<ImmutableCompositeNode> ret = ImmutableCompositeNode.builder();
114
115         // Target
116         final Node<?> targetWrapperNode = ImmutableCompositeNode.create(NETCONF_TARGET_QNAME, ImmutableList.<Node<?>>of(targetNode));
117         ret.add(targetWrapperNode);
118
119         // Default operation
120         if(defaultOperation.isPresent()) {
121             final SimpleNode<String> defOp = NodeFactory.createImmutableSimpleNode(NETCONF_DEFAULT_OPERATION_QNAME, null, modifyOperationToXmlString(defaultOperation.get()));
122             ret.add(defOp);
123         }
124
125         // Error option
126         if(rollbackSupported) {
127             ret.addLeaf(NETCONF_ERROR_OPTION_QNAME, ROLLBACK_ON_ERROR_OPTION);
128         }
129
130         ret.setQName(NETCONF_EDIT_CONFIG_QNAME);
131         // Edit content
132         ret.add(editStructure);
133         return ret.toInstance();
134     }
135
136     private CompositeNode createEditConfigStructure(final InstanceIdentifier dataPath, final Optional<ModifyAction> operation,
137             final Optional<CompositeNode> lastChildOverride) {
138         Preconditions.checkArgument(Iterables.isEmpty(dataPath.getPathArguments()) == false, "Instance identifier with empty path %s", dataPath);
139
140         List<PathArgument> reversedPath = Lists.reverse(dataPath.getPath());
141
142         // Create deepest edit element with expected edit operation
143         CompositeNode previous = getDeepestEditElement(reversedPath.get(0), operation, lastChildOverride);
144
145         // Remove already processed deepest child
146         reversedPath = Lists.newArrayList(reversedPath);
147         reversedPath.remove(0);
148
149         // Create edit structure in reversed order
150         for (final PathArgument arg : reversedPath) {
151             final CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
152             builder.setQName(arg.getNodeType());
153
154             addPredicatesToCompositeNodeBuilder(getPredicates(arg), builder);
155
156             builder.add(previous);
157             previous = builder.toInstance();
158         }
159         return ImmutableCompositeNode.create(NETCONF_CONFIG_QNAME, ImmutableList.<Node<?>>of(previous));
160     }
161
162     private void addPredicatesToCompositeNodeBuilder(final Map<QName, Object> predicates, final CompositeNodeBuilder<ImmutableCompositeNode> builder) {
163         for (final Entry<QName, Object> entry : predicates.entrySet()) {
164             builder.addLeaf(entry.getKey(), entry.getValue());
165         }
166     }
167
168     private Map<QName, Object> getPredicates(final PathArgument arg) {
169         Map<QName, Object> predicates = Collections.emptyMap();
170         if (arg instanceof NodeIdentifierWithPredicates) {
171             predicates = ((NodeIdentifierWithPredicates) arg).getKeyValues();
172         }
173         return predicates;
174     }
175
176     private CompositeNode getDeepestEditElement(final PathArgument arg, final Optional<ModifyAction> operation, final Optional<CompositeNode> lastChildOverride) {
177         final CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
178         builder.setQName(arg.getNodeType());
179
180         final Map<QName, Object> predicates = getPredicates(arg);
181         addPredicatesToCompositeNodeBuilder(predicates, builder);
182
183         if (operation.isPresent()) {
184             builder.setAttribute(NETCONF_OPERATION_QNAME, modifyOperationToXmlString(operation.get()));
185         }
186         if (lastChildOverride.isPresent()) {
187             final List<Node<?>> children = lastChildOverride.get().getValue();
188             for(final Node<?> child : children) {
189                 if(!predicates.containsKey(child.getKey())) {
190                     builder.add(child);
191                 }
192             }
193         }
194
195         return builder.toInstance();
196     }
197
198     private String modifyOperationToXmlString(final ModifyAction operation) {
199         return operation.name().toLowerCase();
200     }
201
202     /**
203      * Send commit rpc to finish the transaction
204      * In case of failure or unexpected error response, ExecutionException is thrown
205      */
206     @Override
207     public RpcResult<Void> finish() {
208         try {
209             final RpcResult<?> rpcResult = rpc.invokeRpc(NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME, getCommitRequest()).get();
210             return new RpcResultVoidWrapper(rpcResult);
211         } catch (final InterruptedException e) {
212             Thread.currentThread().interrupt();
213             throw new RuntimeException(id + ": Interrupted while waiting for response", e);
214         } catch (final ExecutionException e) {
215             LOG.warn("{}: Failed to finish commit operation", id, e);
216             return RpcResultBuilder.<Void>failed().withError( RpcError.ErrorType.APPLICATION,
217                             id + ": Unexpected operation error during commit operation", e ).build();
218         }
219     }
220
221     private ImmutableCompositeNode getCommitRequest() {
222         final CompositeNodeBuilder<ImmutableCompositeNode> commitInput = ImmutableCompositeNode.builder();
223         commitInput.setQName(NETCONF_COMMIT_QNAME);
224         return commitInput.toInstance();
225     }
226
227     @Override
228     public DataModification<InstanceIdentifier, CompositeNode> getModification() {
229         return this.modification;
230     }
231
232     @Override
233     public RpcResult<Void> rollback() throws IllegalStateException {
234         // TODO BUG-732 implement rollback by sending discard changes
235         return null;
236     }
237
238     public CompositeNode getTargetNode(final boolean candidateSupported) {
239         if(candidateSupported) {
240             return ImmutableCompositeNode.create(NETCONF_CANDIDATE_QNAME, ImmutableList.<Node<?>>of());
241         } else {
242             return ImmutableCompositeNode.create(NETCONF_RUNNING_QNAME, ImmutableList.<Node<?>>of());
243         }
244     }
245
246     private static final class RpcResultVoidWrapper implements RpcResult<Void> {
247
248         private final RpcResult<?> rpcResult;
249
250         public RpcResultVoidWrapper(final RpcResult<?> rpcResult) {
251             this.rpcResult = rpcResult;
252         }
253
254         @Override
255         public boolean isSuccessful() {
256             return rpcResult.isSuccessful();
257         }
258
259         @Override
260         public Void getResult() {
261             return null;
262         }
263
264         @Override
265         public Collection<RpcError> getErrors() {
266             return rpcResult.getErrors();
267         }
268     }
269 }