2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.sal.connect.netconf.sal;
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;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.List;
24 import java.util.Map.Entry;
25 import java.util.concurrent.ExecutionException;
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;
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;
53 * Remote transaction that delegates data change to remote device using netconf messages.
55 final class NetconfDeviceTwoPhaseCommitTransaction implements DataCommitTransaction<InstanceIdentifier, CompositeNode> {
57 private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceTwoPhaseCommitTransaction.class);
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;
65 public NetconfDeviceTwoPhaseCommitTransaction(final RemoteDeviceId id, final RpcImplementation rpc,
66 final DataModification<InstanceIdentifier, CompositeNode> modification,
67 final boolean candidateSupported, final boolean rollbackOnErrorSupported) {
69 this.rpc = Preconditions.checkNotNull(rpc);
70 this.modification = Preconditions.checkNotNull(modification);
71 this.targetNode = getTargetNode(candidateSupported);
72 this.rollbackSupported = rollbackOnErrorSupported;
76 * Prepare phase, sends 1 or more netconf edit config operations to modify the data
78 * In case of failure or unexpected error response, ExecutionException is thrown
80 void prepare() throws InterruptedException, ExecutionException {
81 for (final InstanceIdentifier toRemove : modification.getRemovedConfigurationData()) {
84 for(final Entry<InstanceIdentifier, CompositeNode> toUpdate : modification.getUpdatedConfigurationData().entrySet()) {
85 sendMerge(toUpdate.getKey(),toUpdate.getValue());
89 private void sendMerge(final InstanceIdentifier key, final CompositeNode value) throws InterruptedException, ExecutionException {
90 sendEditRpc(createEditConfigStructure(key, Optional.<String>absent(), Optional.of(value)));
93 private void sendDelete(final InstanceIdentifier toDelete) throws InterruptedException, ExecutionException {
94 sendEditRpc(createEditConfigStructure(toDelete, Optional.of("delete"), Optional.<CompositeNode>absent()));
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
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);
109 private ImmutableCompositeNode createEditConfigRequest(final CompositeNode editStructure) {
110 final CompositeNodeBuilder<ImmutableCompositeNode> ret = ImmutableCompositeNode.builder();
112 final Node<?> targetWrapperNode = ImmutableCompositeNode.create(NETCONF_TARGET_QNAME, ImmutableList.<Node<?>>of(targetNode));
113 ret.add(targetWrapperNode);
115 if(rollbackSupported) {
116 ret.addLeaf(NETCONF_ERROR_OPTION_QNAME, ROLLBACK_ON_ERROR_OPTION);
118 ret.setQName(NETCONF_EDIT_CONFIG_QNAME);
119 ret.add(editStructure);
120 return ret.toInstance();
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);
127 List<PathArgument> reversedPath = Lists.reverse(dataPath.getPath());
129 // Create deepest edit element with expected edit operation
130 CompositeNode previous = getDeepestEditElement(reversedPath.get(0), operation, lastChildOverride);
132 // Remove already processed deepest child
133 reversedPath = Lists.newArrayList(reversedPath);
134 reversedPath.remove(0);
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());
141 addPredicatesToCompositeNodeBuilder(getPredicates(arg), builder);
143 builder.add(previous);
144 previous = builder.toInstance();
146 return ImmutableCompositeNode.create(NETCONF_CONFIG_QNAME, ImmutableList.<Node<?>>of(previous));
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());
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();
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());
167 final Map<QName, Object> predicates = getPredicates(arg);
168 addPredicatesToCompositeNodeBuilder(predicates, builder);
170 if (operation.isPresent()) {
171 builder.setAttribute(NETCONF_OPERATION_QNAME, operation.get());
173 if (lastChildOverride.isPresent()) {
174 final List<Node<?>> children = lastChildOverride.get().getValue();
175 for(final Node<?> child : children) {
176 if(!predicates.containsKey(child.getKey())) {
182 return builder.toInstance();
186 * Send commit rpc to finish the transaction
187 * In case of failure or unexpected error response, ExecutionException is thrown
190 public RpcResult<Void> finish() {
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));
204 private ImmutableCompositeNode getCommitRequest() {
205 final CompositeNodeBuilder<ImmutableCompositeNode> commitInput = ImmutableCompositeNode.builder();
206 commitInput.setQName(NETCONF_COMMIT_QNAME);
207 return commitInput.toInstance();
211 public DataModification<InstanceIdentifier, CompositeNode> getModification() {
212 return this.modification;
216 public RpcResult<Void> rollback() throws IllegalStateException {
217 // TODO BUG-732 implement rollback by sending discard changes
221 public CompositeNode getTargetNode(final boolean candidateSupported) {
222 if(candidateSupported) {
223 return ImmutableCompositeNode.create(NETCONF_CANDIDATE_QNAME, ImmutableList.<Node<?>>of());
225 return ImmutableCompositeNode.create(NETCONF_RUNNING_QNAME, ImmutableList.<Node<?>>of());
229 private static final class RpcResultVoidWrapper implements RpcResult<Void> {
231 private final RpcResult<?> rpcResult;
233 public RpcResultVoidWrapper(final RpcResult<?> rpcResult) {
234 this.rpcResult = rpcResult;
238 public boolean isSuccessful() {
239 return rpcResult.isSuccessful();
243 public Void getResult() {
248 public Collection<RpcError> getErrors() {
249 return rpcResult.getErrors();