BUG-692 Improve log message when negotiation fails
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / sal / connect / netconf / util / NetconfMessageTransformUtil.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.util;
9
10 import java.net.URI;
11 import java.util.ArrayList;
12 import java.util.Collections;
13 import java.util.List;
14 import java.util.Map;
15 import java.util.Map.Entry;
16
17 import javax.annotation.Nullable;
18
19 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
20 import org.opendaylight.controller.netconf.api.NetconfMessage;
21 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
22 import org.opendaylight.controller.sal.common.util.RpcErrors;
23 import org.opendaylight.yangtools.yang.common.QName;
24 import org.opendaylight.yangtools.yang.common.RpcError;
25 import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
26 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
27 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
28 import org.opendaylight.yangtools.yang.data.api.Node;
29 import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
30 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
31 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
32 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
33 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
34 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
36 import org.w3c.dom.Document;
37 import org.w3c.dom.Element;
38
39 import com.google.common.base.Predicate;
40 import com.google.common.collect.Collections2;
41 import com.google.common.collect.ImmutableList;
42 import com.google.common.collect.ImmutableMap;
43 import com.google.common.collect.Lists;
44 import com.google.common.collect.Sets;
45
46 public class NetconfMessageTransformUtil {
47
48     private NetconfMessageTransformUtil() {
49     }
50
51     public static final QName IETF_NETCONF_MONITORING = QName.create("urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring", "2010-10-04", "ietf-netconf-monitoring");
52     public static URI NETCONF_URI = URI.create("urn:ietf:params:xml:ns:netconf:base:1.0");
53     public static QName NETCONF_QNAME = QName.create(NETCONF_URI, null, "netconf");
54     public static QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data");
55     public static QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply");
56     public static QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option");
57     public static QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running");
58     static List<Node<?>> RUNNING = Collections.<Node<?>> singletonList(new SimpleNodeTOImpl<>(NETCONF_RUNNING_QNAME, null, null));
59     public static QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source");
60     public static CompositeNode CONFIG_SOURCE_RUNNING = new CompositeNodeTOImpl(NETCONF_SOURCE_QNAME, null, RUNNING);
61     public static QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate");
62     public static QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target");
63     public static QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config");
64     public static QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit");
65     public static QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation");
66     public static QName NETCONF_DEFAULT_OPERATION_QNAME = QName.create(NETCONF_OPERATION_QNAME, "default-operation");
67     public static QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config");
68     public static QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
69     public static QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type");
70     public static QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter");
71     public static QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get");
72     public static QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc");
73     public static URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
74             .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
75     public static String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
76
77     public static Node<?> toFilterStructure(final InstanceIdentifier identifier) {
78         Node<?> previous = null;
79         if (identifier.getPath().isEmpty()) {
80             return null;
81         }
82
83         for (final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument component : Lists
84                 .reverse(identifier.getPath())) {
85             if (component instanceof InstanceIdentifier.NodeIdentifierWithPredicates) {
86                 previous = toNode((InstanceIdentifier.NodeIdentifierWithPredicates)component, previous);
87             } else {
88                 previous = toNode(component, previous);
89             }
90         }
91         return filter("subtree", previous);
92     }
93
94     static Node<?> toNode(final InstanceIdentifier.NodeIdentifierWithPredicates argument, final Node<?> node) {
95         final List<Node<?>> list = new ArrayList<>();
96         for (final Map.Entry<QName, Object> arg : argument.getKeyValues().entrySet()) {
97             list.add(new SimpleNodeTOImpl(arg.getKey(), null, arg.getValue()));
98         }
99         if (node != null) {
100             list.add(node);
101         }
102         return new CompositeNodeTOImpl(argument.getNodeType(), null, list);
103     }
104
105     public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
106         throws NetconfDocumentedException {
107         final String inputMsgId = input.getDocument().getDocumentElement().getAttribute("message-id");
108         final String outputMsgId = output.getDocument().getDocumentElement().getAttribute("message-id");
109
110         if(inputMsgId.equals(outputMsgId) == false) {
111             Map<String,String> errorInfo = ImmutableMap.<String,String>builder()
112                 .put( "actual-message-id", outputMsgId )
113                 .put( "expected-message-id", inputMsgId )
114                 .build();
115
116             throw new NetconfDocumentedException( "Response message contained unknown \"message-id\"",
117                     null, NetconfDocumentedException.ErrorType.protocol,
118                     NetconfDocumentedException.ErrorTag.bad_attribute,
119                     NetconfDocumentedException.ErrorSeverity.error, errorInfo );
120         }
121     }
122
123     public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
124         if(NetconfMessageUtil.isErrorMessage(output)) {
125             throw NetconfDocumentedException.fromXMLDocument( output.getDocument() );
126         }
127     }
128
129     public static RpcError toRpcError( NetconfDocumentedException ex )
130     {
131         StringBuilder infoBuilder = new StringBuilder();
132         Map<String, String> errorInfo = ex.getErrorInfo();
133         if( errorInfo != null )
134         {
135             for( Entry<String,String> e: errorInfo.entrySet() ) {
136                 infoBuilder.append( '<' ).append( e.getKey() ).append( '>' ).append( e.getValue() )
137                            .append( "</" ).append( e.getKey() ).append( '>' );
138
139             }
140         }
141
142         return RpcErrors.getRpcError( null, ex.getErrorTag().getTagValue(), infoBuilder.toString(),
143                                       toRpcErrorSeverity( ex.getErrorSeverity() ), ex.getLocalizedMessage(),
144                                       toRpcErrorType( ex.getErrorType() ), ex.getCause() );
145     }
146
147     private static ErrorSeverity toRpcErrorSeverity( NetconfDocumentedException.ErrorSeverity severity ) {
148         switch( severity ) {
149             case warning:
150                 return RpcError.ErrorSeverity.WARNING;
151             default:
152                 return RpcError.ErrorSeverity.ERROR;
153         }
154     }
155
156     private static RpcError.ErrorType toRpcErrorType( NetconfDocumentedException.ErrorType type )
157     {
158         switch( type ) {
159             case protocol:
160                 return RpcError.ErrorType.PROTOCOL;
161             case rpc:
162                 return RpcError.ErrorType.RPC;
163             case transport:
164                 return RpcError.ErrorType.TRANSPORT;
165             default:
166                 return RpcError.ErrorType.APPLICATION;
167         }
168     }
169
170     public static CompositeNode flattenInput(final CompositeNode node) {
171         final QName inputQName = QName.create(node.getNodeType(), "input");
172         final CompositeNode input = node.getFirstCompositeByName(inputQName);
173         if (input == null)
174             return node;
175         if (input instanceof CompositeNode) {
176
177             final List<Node<?>> nodes = ImmutableList.<Node<?>> builder() //
178                     .addAll(input.getValue()) //
179                     .addAll(Collections2.filter(node.getValue(), new Predicate<Node<?>>() {
180                         @Override
181                         public boolean apply(@Nullable final Node<?> input) {
182                             return input.getNodeType() != inputQName;
183                         }
184                     })) //
185                     .build();
186
187             return ImmutableCompositeNode.create(node.getNodeType(), nodes);
188         }
189
190         return input;
191     }
192
193     static Node<?> toNode(final InstanceIdentifier.PathArgument argument, final Node<?> node) {
194         if (node != null) {
195             return new CompositeNodeTOImpl(argument.getNodeType(), null, Collections.<Node<?>> singletonList(node));
196         } else {
197             return new SimpleNodeTOImpl<Void>(argument.getNodeType(), null, null);
198         }
199     }
200
201     public static Element getDataSubtree(final Document doc) {
202         return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
203     }
204
205     public static boolean isDataRetrievalOperation(final QName rpc) {
206         return NETCONF_URI.equals(rpc.getNamespace())
207                 && (rpc.getLocalName().equals(NETCONF_GET_CONFIG_QNAME.getLocalName()) || rpc.getLocalName().equals(
208                         NETCONF_GET_QNAME.getLocalName()));
209     }
210
211     public static boolean isDataEditOperation(final QName rpc) {
212         return NETCONF_URI.equals(rpc.getNamespace())
213                 && rpc.getLocalName().equals(NETCONF_EDIT_CONFIG_QNAME.getLocalName());
214     }
215
216     /**
217      * Creates artificial schema node for edit-config rpc. This artificial schema looks like:
218      * <pre>
219      * {@code
220      * rpc
221      *   edit-config
222      *     config
223      *         // All schema nodes from remote schema
224      *     config
225      *   edit-config
226      * rpc
227      * }
228      * </pre>
229      *
230      * This makes the translation of rpc edit-config request(especially the config node)
231      * to xml use schema which is crucial for some types of nodes e.g. identity-ref.
232      */
233     public static DataNodeContainer createSchemaForEdit(final SchemaContext schemaContext) {
234         final QName config = QName.create(NETCONF_EDIT_CONFIG_QNAME, "config");
235         final QName editConfig = QName.create(NETCONF_EDIT_CONFIG_QNAME, "edit-config");
236         final NodeContainerProxy configProxy = new NodeContainerProxy(config, schemaContext.getChildNodes());
237         final NodeContainerProxy editConfigProxy = new NodeContainerProxy(editConfig, Sets.<DataSchemaNode>newHashSet(configProxy));
238         return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(editConfigProxy));
239     }
240
241     public static CompositeNodeTOImpl wrap(final QName name, final Node<?> node) {
242         if (node != null) {
243             return new CompositeNodeTOImpl(name, null, Collections.<Node<?>> singletonList(node));
244         } else {
245             return new CompositeNodeTOImpl(name, null, Collections.<Node<?>> emptyList());
246         }
247     }
248
249     public static CompositeNodeTOImpl wrap(final QName name, final Node<?> additional, final Node<?> node) {
250         if (node != null) {
251             return new CompositeNodeTOImpl(name, null, ImmutableList.of(additional, node));
252         } else {
253             return new CompositeNodeTOImpl(name, null, ImmutableList.<Node<?>> of(additional));
254         }
255     }
256
257     static ImmutableCompositeNode filter(final String type, final Node<?> node) {
258         final CompositeNodeBuilder<ImmutableCompositeNode> it = ImmutableCompositeNode.builder(); //
259         it.setQName(NETCONF_FILTER_QNAME);
260         it.setAttribute(NETCONF_TYPE_QNAME, type);
261         if (node != null) {
262             return it.add(node).toInstance();
263         } else {
264             return it.toInstance();
265         }
266     }
267
268 }