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.Lists;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.List;
29 import java.util.Map.Entry;
30 import java.util.concurrent.ExecutionException;
31 import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler.DataCommitTransaction;
32 import org.opendaylight.controller.md.sal.common.api.data.DataModification;
33 import org.opendaylight.controller.sal.common.util.RpcErrors;
34 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
35 import org.opendaylight.controller.sal.connect.util.FailedRpcResult;
36 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
37 import org.opendaylight.controller.sal.core.api.RpcImplementation;
38 import org.opendaylight.yangtools.yang.common.QName;
39 import org.opendaylight.yangtools.yang.common.RpcError;
40 import org.opendaylight.yangtools.yang.common.RpcResult;
41 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
42 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
44 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
45 import org.opendaylight.yangtools.yang.data.api.Node;
46 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
47 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
48 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
49 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
54 * Remote transaction that delegates data change to remote device using netconf messages.
56 final class NetconfDeviceTwoPhaseCommitTransaction implements DataCommitTransaction<InstanceIdentifier, CompositeNode> {
58 private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceTwoPhaseCommitTransaction.class);
60 private final DataModification<InstanceIdentifier, CompositeNode> modification;
61 private final RpcImplementation rpc;
62 private final boolean rollbackSupported;
63 private final RemoteDeviceId id;
64 private final CompositeNode targetNode;
66 public NetconfDeviceTwoPhaseCommitTransaction(final RemoteDeviceId id, final RpcImplementation rpc,
67 final DataModification<InstanceIdentifier, CompositeNode> modification,
68 final boolean candidateSupported, final boolean rollbackOnErrorSupported) {
70 this.rpc = Preconditions.checkNotNull(rpc);
71 this.modification = Preconditions.checkNotNull(modification);
72 this.targetNode = getTargetNode(candidateSupported);
73 this.rollbackSupported = rollbackOnErrorSupported;
77 * Prepare phase, sends 1 or more netconf edit config operations to modify the data
79 * In case of failure or unexpected error response, ExecutionException is thrown
81 void prepare() throws InterruptedException, ExecutionException {
82 for (final InstanceIdentifier toRemove : modification.getRemovedConfigurationData()) {
85 for(final Entry<InstanceIdentifier, CompositeNode> toUpdate : modification.getUpdatedConfigurationData().entrySet()) {
86 sendMerge(toUpdate.getKey(),toUpdate.getValue());
90 private void sendMerge(final InstanceIdentifier key, final CompositeNode value) throws InterruptedException, ExecutionException {
91 sendEditRpc(createEditConfigStructure(key, Optional.<String>absent(), Optional.of(value)), Optional.<String>absent());
94 private void sendDelete(final InstanceIdentifier toDelete) throws InterruptedException, ExecutionException {
95 // FIXME use org.opendaylight.yangtools.yang.data.api.ModifyAction instead of strings
96 // TODO add string lowercase value to ModifyAction enum entries
97 sendEditRpc(createEditConfigStructure(toDelete, Optional.of("delete"), Optional.<CompositeNode>absent()), Optional.of("none"));
100 private void sendEditRpc(final CompositeNode editStructure, final Optional<String> defaultOperation) throws InterruptedException, ExecutionException {
101 final ImmutableCompositeNode editConfigRequest = createEditConfigRequest(editStructure, defaultOperation);
102 final RpcResult<CompositeNode> rpcResult = rpc.invokeRpc(NETCONF_EDIT_CONFIG_QNAME, editConfigRequest).get();
105 if(rpcResult.isSuccessful() == false) {
106 throw new ExecutionException(
107 String.format("%s: Pre-commit rpc failed, request: %s, errors: %s", id, editConfigRequest, rpcResult.getErrors()), null);
111 private ImmutableCompositeNode createEditConfigRequest(final CompositeNode editStructure, Optional<String> defaultOperation) {
112 final CompositeNodeBuilder<ImmutableCompositeNode> ret = ImmutableCompositeNode.builder();
115 final Node<?> targetWrapperNode = ImmutableCompositeNode.create(NETCONF_TARGET_QNAME, ImmutableList.<Node<?>>of(targetNode));
116 ret.add(targetWrapperNode);
119 if(defaultOperation.isPresent()) {
120 SimpleNode<String> defOp = NodeFactory.createImmutableSimpleNode(NETCONF_DEFAULT_OPERATION_QNAME, null, defaultOperation.get());
125 if(rollbackSupported) {
126 ret.addLeaf(NETCONF_ERROR_OPTION_QNAME, ROLLBACK_ON_ERROR_OPTION);
129 ret.setQName(NETCONF_EDIT_CONFIG_QNAME);
131 ret.add(editStructure);
132 return ret.toInstance();
135 private CompositeNode createEditConfigStructure(final InstanceIdentifier dataPath, final Optional<String> operation,
136 final Optional<CompositeNode> lastChildOverride) {
137 Preconditions.checkArgument(dataPath.getPath().isEmpty() == false, "Instance identifier with empty path %s", dataPath);
139 List<PathArgument> reversedPath = Lists.reverse(dataPath.getPath());
141 // Create deepest edit element with expected edit operation
142 CompositeNode previous = getDeepestEditElement(reversedPath.get(0), operation, lastChildOverride);
144 // Remove already processed deepest child
145 reversedPath = Lists.newArrayList(reversedPath);
146 reversedPath.remove(0);
148 // Create edit structure in reversed order
149 for (final PathArgument arg : reversedPath) {
150 final CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
151 builder.setQName(arg.getNodeType());
153 addPredicatesToCompositeNodeBuilder(getPredicates(arg), builder);
155 builder.add(previous);
156 previous = builder.toInstance();
158 return ImmutableCompositeNode.create(NETCONF_CONFIG_QNAME, ImmutableList.<Node<?>>of(previous));
161 private void addPredicatesToCompositeNodeBuilder(final Map<QName, Object> predicates, final CompositeNodeBuilder<ImmutableCompositeNode> builder) {
162 for (final Entry<QName, Object> entry : predicates.entrySet()) {
163 builder.addLeaf(entry.getKey(), entry.getValue());
167 private Map<QName, Object> getPredicates(final PathArgument arg) {
168 Map<QName, Object> predicates = Collections.emptyMap();
169 if (arg instanceof NodeIdentifierWithPredicates) {
170 predicates = ((NodeIdentifierWithPredicates) arg).getKeyValues();
175 private CompositeNode getDeepestEditElement(final PathArgument arg, final Optional<String> operation, final Optional<CompositeNode> lastChildOverride) {
176 final CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
177 builder.setQName(arg.getNodeType());
179 final Map<QName, Object> predicates = getPredicates(arg);
180 addPredicatesToCompositeNodeBuilder(predicates, builder);
182 if (operation.isPresent()) {
183 builder.setAttribute(NETCONF_OPERATION_QNAME, operation.get());
185 if (lastChildOverride.isPresent()) {
186 final List<Node<?>> children = lastChildOverride.get().getValue();
187 for(final Node<?> child : children) {
188 if(!predicates.containsKey(child.getKey())) {
194 return builder.toInstance();
198 * Send commit rpc to finish the transaction
199 * In case of failure or unexpected error response, ExecutionException is thrown
202 public RpcResult<Void> finish() {
204 final RpcResult<?> rpcResult = rpc.invokeRpc(NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME, getCommitRequest()).get();
205 return new RpcResultVoidWrapper(rpcResult);
206 } catch (final InterruptedException e) {
207 Thread.currentThread().interrupt();
208 throw new RuntimeException(id + ": Interrupted while waiting for response", e);
209 } catch (final ExecutionException e) {
210 LOG.warn("{}: Failed to finish commit operation", id, e);
211 return new FailedRpcResult<>(RpcErrors.getRpcError(null, null, null, RpcError.ErrorSeverity.ERROR,
212 id + ": Unexpected operation error during commit operation", RpcError.ErrorType.APPLICATION, e));
216 private ImmutableCompositeNode getCommitRequest() {
217 final CompositeNodeBuilder<ImmutableCompositeNode> commitInput = ImmutableCompositeNode.builder();
218 commitInput.setQName(NETCONF_COMMIT_QNAME);
219 return commitInput.toInstance();
223 public DataModification<InstanceIdentifier, CompositeNode> getModification() {
224 return this.modification;
228 public RpcResult<Void> rollback() throws IllegalStateException {
229 // TODO BUG-732 implement rollback by sending discard changes
233 public CompositeNode getTargetNode(final boolean candidateSupported) {
234 if(candidateSupported) {
235 return ImmutableCompositeNode.create(NETCONF_CANDIDATE_QNAME, ImmutableList.<Node<?>>of());
237 return ImmutableCompositeNode.create(NETCONF_RUNNING_QNAME, ImmutableList.<Node<?>>of());
241 private static final class RpcResultVoidWrapper implements RpcResult<Void> {
243 private final RpcResult<?> rpcResult;
245 public RpcResultVoidWrapper(final RpcResult<?> rpcResult) {
246 this.rpcResult = rpcResult;
250 public boolean isSuccessful() {
251 return rpcResult.isSuccessful();
255 public Void getResult() {
260 public Collection<RpcError> getErrors() {
261 return rpcResult.getErrors();