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_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;
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;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.List;
31 import java.util.Map.Entry;
32 import java.util.concurrent.ExecutionException;
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;
57 * Remote transaction that delegates data change to remote device using netconf messages.
59 final class NetconfDeviceTwoPhaseCommitTransaction implements DataCommitTransaction<InstanceIdentifier, CompositeNode> {
61 private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceTwoPhaseCommitTransaction.class);
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;
69 public NetconfDeviceTwoPhaseCommitTransaction(final RemoteDeviceId id, final RpcImplementation rpc,
70 final DataModification<InstanceIdentifier, CompositeNode> modification,
71 final boolean candidateSupported, final boolean rollbackOnErrorSupported) {
73 this.rpc = Preconditions.checkNotNull(rpc);
74 this.modification = Preconditions.checkNotNull(modification);
75 this.targetNode = getTargetNode(candidateSupported);
76 this.rollbackSupported = rollbackOnErrorSupported;
80 * Prepare phase, sends 1 or more netconf edit config operations to modify the data
82 * In case of failure or unexpected error response, ExecutionException is thrown
84 void prepare() throws InterruptedException, ExecutionException {
85 for (final InstanceIdentifier toRemove : modification.getRemovedConfigurationData()) {
88 for(final Entry<InstanceIdentifier, CompositeNode> toUpdate : modification.getUpdatedConfigurationData().entrySet()) {
89 sendMerge(toUpdate.getKey(),toUpdate.getValue());
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());
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"));
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();
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);
114 private ImmutableCompositeNode createEditConfigRequest(final CompositeNode editStructure, final Optional<String> defaultOperation) {
115 final CompositeNodeBuilder<ImmutableCompositeNode> ret = ImmutableCompositeNode.builder();
118 final Node<?> targetWrapperNode = ImmutableCompositeNode.create(NETCONF_TARGET_QNAME, ImmutableList.<Node<?>>of(targetNode));
119 ret.add(targetWrapperNode);
122 if(defaultOperation.isPresent()) {
123 SimpleNode<String> defOp = NodeFactory.createImmutableSimpleNode(NETCONF_DEFAULT_OPERATION_QNAME, null, defaultOperation.get());
128 if(rollbackSupported) {
129 ret.addLeaf(NETCONF_ERROR_OPTION_QNAME, ROLLBACK_ON_ERROR_OPTION);
132 ret.setQName(NETCONF_EDIT_CONFIG_QNAME);
134 ret.add(editStructure);
135 return ret.toInstance();
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);
142 List<PathArgument> reversedPath = Lists.reverse(dataPath.getPath());
144 // Create deepest edit element with expected edit operation
145 CompositeNode previous = getDeepestEditElement(reversedPath.get(0), operation, lastChildOverride);
147 // Remove already processed deepest child
148 reversedPath = Lists.newArrayList(reversedPath);
149 reversedPath.remove(0);
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());
156 addPredicatesToCompositeNodeBuilder(getPredicates(arg), builder);
158 builder.add(previous);
159 previous = builder.toInstance();
161 return ImmutableCompositeNode.create(NETCONF_CONFIG_QNAME, ImmutableList.<Node<?>>of(previous));
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());
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();
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());
182 final Map<QName, Object> predicates = getPredicates(arg);
183 addPredicatesToCompositeNodeBuilder(predicates, builder);
185 if (operation.isPresent()) {
186 builder.setAttribute(NETCONF_OPERATION_QNAME, operation.get());
188 if (lastChildOverride.isPresent()) {
189 final List<Node<?>> children = lastChildOverride.get().getValue();
190 for(final Node<?> child : children) {
191 if(!predicates.containsKey(child.getKey())) {
197 return builder.toInstance();
201 * Send commit rpc to finish the transaction
202 * In case of failure or unexpected error response, ExecutionException is thrown
205 public RpcResult<Void> finish() {
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));
219 private ImmutableCompositeNode getCommitRequest() {
220 final CompositeNodeBuilder<ImmutableCompositeNode> commitInput = ImmutableCompositeNode.builder();
221 commitInput.setQName(NETCONF_COMMIT_QNAME);
222 return commitInput.toInstance();
226 public DataModification<InstanceIdentifier, CompositeNode> getModification() {
227 return this.modification;
231 public RpcResult<Void> rollback() throws IllegalStateException {
232 // TODO BUG-732 implement rollback by sending discard changes
236 public CompositeNode getTargetNode(final boolean candidateSupported) {
237 if(candidateSupported) {
238 return ImmutableCompositeNode.create(NETCONF_CANDIDATE_QNAME, ImmutableList.<Node<?>>of());
240 return ImmutableCompositeNode.create(NETCONF_RUNNING_QNAME, ImmutableList.<Node<?>>of());
244 private static final class RpcResultVoidWrapper implements RpcResult<Void> {
246 private final RpcResult<?> rpcResult;
248 public RpcResultVoidWrapper(final RpcResult<?> rpcResult) {
249 this.rpcResult = rpcResult;
253 public boolean isSuccessful() {
254 return rpcResult.isSuccessful();
258 public Void getResult() {
263 public Collection<RpcError> getErrors() {
264 return rpcResult.getErrors();