Merge "Fix failing IT tests"
[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 com.google.common.base.Preconditions;
11 import com.google.common.base.Predicate;
12 import com.google.common.collect.Collections2;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.Iterables;
16 import com.google.common.collect.Sets;
17
18 import java.net.URI;
19 import java.util.ArrayList;
20 import java.util.Collections;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Map.Entry;
24
25 import javax.annotation.Nullable;
26
27 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
28 import org.opendaylight.controller.netconf.api.NetconfMessage;
29 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.common.RpcError;
32 import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
33 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
34 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.Node;
37 import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
38 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
39 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
40 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
41 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
42 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
43 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
45 import org.w3c.dom.Document;
46 import org.w3c.dom.Element;
47
48 public class NetconfMessageTransformUtil {
49
50     private NetconfMessageTransformUtil() {}
51
52     public static final QName IETF_NETCONF_MONITORING = QName.create("urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring", "2010-10-04", "ietf-netconf-monitoring");
53     public static URI NETCONF_URI = URI.create("urn:ietf:params:xml:ns:netconf:base:1.0");
54     public static QName NETCONF_QNAME = QName.create(NETCONF_URI, null, "netconf");
55     public static QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data");
56     public static QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply");
57     public static QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option");
58     public static QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running");
59     static List<Node<?>> RUNNING = Collections.<Node<?>> singletonList(new SimpleNodeTOImpl<>(NETCONF_RUNNING_QNAME, null, null));
60     public static QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source");
61     public static CompositeNode CONFIG_SOURCE_RUNNING = new CompositeNodeTOImpl(NETCONF_SOURCE_QNAME, null, RUNNING);
62     public static QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate");
63     public static QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target");
64     public static QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config");
65     public static QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit");
66     public static QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation");
67     public static QName NETCONF_DEFAULT_OPERATION_QNAME = QName.create(NETCONF_OPERATION_QNAME, "default-operation");
68     public static QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config");
69     public static QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
70     public static QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
71     public static QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type");
72     public static QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter");
73     public static QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get");
74     public static QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc");
75
76     public static URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
77             .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
78     public static String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
79
80     public static URI NETCONF_CANDIDATE_URI = URI
81             .create("urn:ietf:params:netconf:capability:candidate:1.0");
82
83     // Discard changes message
84     public static final CompositeNode DISCARD_CHANGES_RPC_CONTENT =
85             NodeFactory.createImmutableCompositeNode(NETCONF_DISCARD_CHANGES_QNAME, null, Collections.<Node<?>>emptyList());
86
87     // Commit changes message
88     public static final CompositeNode COMMIT_RPC_CONTENT =
89             NodeFactory.createImmutableCompositeNode(NETCONF_COMMIT_QNAME, null, Collections.<Node<?>>emptyList());
90
91     public static Node<?> toFilterStructure(final YangInstanceIdentifier identifier) {
92         Node<?> previous = null;
93         if (Iterables.isEmpty(identifier.getPathArguments())) {
94             return null;
95         }
96
97         for (final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument component : identifier.getReversePathArguments()) {
98             if (component instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
99                 previous = toNode((YangInstanceIdentifier.NodeIdentifierWithPredicates)component, previous);
100             } else {
101                 previous = toNode(component, previous);
102             }
103         }
104         return filter("subtree", previous);
105     }
106
107     static Node<?> toNode(final YangInstanceIdentifier.NodeIdentifierWithPredicates argument, final Node<?> node) {
108         final List<Node<?>> list = new ArrayList<>();
109         for (final Map.Entry<QName, Object> arg : argument.getKeyValues().entrySet()) {
110             list.add(new SimpleNodeTOImpl(arg.getKey(), null, arg.getValue()));
111         }
112         if (node != null) {
113             list.add(node);
114         }
115         return new CompositeNodeTOImpl(argument.getNodeType(), null, list);
116     }
117
118     public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
119             throws NetconfDocumentedException {
120         final String inputMsgId = input.getDocument().getDocumentElement().getAttribute("message-id");
121         final String outputMsgId = output.getDocument().getDocumentElement().getAttribute("message-id");
122
123         if(inputMsgId.equals(outputMsgId) == false) {
124             Map<String,String> errorInfo = ImmutableMap.<String,String>builder()
125                     .put( "actual-message-id", outputMsgId )
126                     .put( "expected-message-id", inputMsgId )
127                     .build();
128
129             throw new NetconfDocumentedException( "Response message contained unknown \"message-id\"",
130                     null, NetconfDocumentedException.ErrorType.protocol,
131                     NetconfDocumentedException.ErrorTag.bad_attribute,
132                     NetconfDocumentedException.ErrorSeverity.error, errorInfo );
133         }
134     }
135
136     public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
137         if(NetconfMessageUtil.isErrorMessage(output)) {
138             throw NetconfDocumentedException.fromXMLDocument( output.getDocument() );
139         }
140     }
141
142     public static RpcError toRpcError( final NetconfDocumentedException ex )
143     {
144         StringBuilder infoBuilder = new StringBuilder();
145         Map<String, String> errorInfo = ex.getErrorInfo();
146         if( errorInfo != null )
147         {
148             for( Entry<String,String> e: errorInfo.entrySet() ) {
149                 infoBuilder.append( '<' ).append( e.getKey() ).append( '>' ).append( e.getValue() )
150                 .append( "</" ).append( e.getKey() ).append( '>' );
151
152             }
153         }
154
155         ErrorSeverity severity = toRpcErrorSeverity( ex.getErrorSeverity() );
156         return severity == ErrorSeverity.ERROR ?
157                 RpcResultBuilder.newError(
158                         toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
159                         ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() ) :
160                             RpcResultBuilder.newWarning(
161                                     toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
162                                     ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() );
163     }
164
165     private static ErrorSeverity toRpcErrorSeverity( final NetconfDocumentedException.ErrorSeverity severity ) {
166         switch( severity ) {
167         case warning:
168             return RpcError.ErrorSeverity.WARNING;
169         default:
170             return RpcError.ErrorSeverity.ERROR;
171         }
172     }
173
174     private static RpcError.ErrorType toRpcErrorType( final NetconfDocumentedException.ErrorType type )
175     {
176         switch( type ) {
177         case protocol:
178             return RpcError.ErrorType.PROTOCOL;
179         case rpc:
180             return RpcError.ErrorType.RPC;
181         case transport:
182             return RpcError.ErrorType.TRANSPORT;
183         default:
184             return RpcError.ErrorType.APPLICATION;
185         }
186     }
187
188     public static CompositeNode flattenInput(final CompositeNode node) {
189         final QName inputQName = QName.create(node.getNodeType(), "input");
190         final CompositeNode input = node.getFirstCompositeByName(inputQName);
191         if (input == null) {
192             return node;
193         }
194         if (input instanceof CompositeNode) {
195
196             final List<Node<?>> nodes = ImmutableList.<Node<?>> builder() //
197                     .addAll(input.getValue()) //
198                     .addAll(Collections2.filter(node.getValue(), new Predicate<Node<?>>() {
199                         @Override
200                         public boolean apply(@Nullable final Node<?> input) {
201                             return !inputQName.equals(input.getNodeType());
202                         }
203                     })) //
204                     .build();
205
206             return ImmutableCompositeNode.create(node.getNodeType(), nodes);
207         }
208
209         return input;
210     }
211
212     static Node<?> toNode(final YangInstanceIdentifier.PathArgument argument, final Node<?> node) {
213         if (node != null) {
214             return new CompositeNodeTOImpl(argument.getNodeType(), null, Collections.<Node<?>> singletonList(node));
215         } else {
216             return new SimpleNodeTOImpl<Void>(argument.getNodeType(), null, null);
217         }
218     }
219
220     public static Element getDataSubtree(final Document doc) {
221         return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
222     }
223
224     public static boolean isDataRetrievalOperation(final QName rpc) {
225         return NETCONF_URI.equals(rpc.getNamespace())
226                 && (rpc.getLocalName().equals(NETCONF_GET_CONFIG_QNAME.getLocalName()) || rpc.getLocalName().equals(
227                         NETCONF_GET_QNAME.getLocalName()));
228     }
229
230     public static boolean isGetOperation(final QName rpc) {
231         return NETCONF_URI.equals(rpc.getNamespace()) && rpc.getLocalName().equals(NETCONF_GET_QNAME.getLocalName());
232     }
233
234     public static boolean isGetConfigOperation(final QName rpc) {
235         return NETCONF_URI.equals(rpc.getNamespace()) && rpc.getLocalName().equals(NETCONF_GET_CONFIG_QNAME.getLocalName());
236     }
237
238     public static boolean isDataEditOperation(final QName rpc) {
239         return NETCONF_URI.equals(rpc.getNamespace())
240                 && rpc.getLocalName().equals(NETCONF_EDIT_CONFIG_QNAME.getLocalName());
241     }
242
243     /**
244      * Creates artificial schema node for edit-config rpc. This artificial schema looks like:
245      * <pre>
246      * {@code
247      * rpc
248      *   edit-config
249      *     config
250      *         // All schema nodes from remote schema
251      *     config
252      *   edit-config
253      * rpc
254      * }
255      * </pre>
256      *
257      * This makes the translation of rpc edit-config request(especially the config node)
258      * to xml use schema which is crucial for some types of nodes e.g. identity-ref.
259      */
260     public static DataNodeContainer createSchemaForEdit(final SchemaContext schemaContext) {
261         final QName config = QName.create(NETCONF_EDIT_CONFIG_QNAME, "config");
262         final QName editConfig = QName.create(NETCONF_EDIT_CONFIG_QNAME, "edit-config");
263         final NodeContainerProxy configProxy = new NodeContainerProxy(config, schemaContext.getChildNodes());
264         final NodeContainerProxy editConfigProxy = new NodeContainerProxy(editConfig, Sets.<DataSchemaNode>newHashSet(configProxy));
265         return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(editConfigProxy));
266     }
267
268     /**
269      * Creates artificial schema node for edit-config rpc. This artificial schema looks like:
270      * <pre>
271      * {@code
272      * rpc
273      *   get
274      *     filter
275      *         // All schema nodes from remote schema
276      *     filter
277      *   get
278      * rpc
279      * }
280      * </pre>
281      *
282      * This makes the translation of rpc get request(especially the config node)
283      * to xml use schema which is crucial for some types of nodes e.g. identity-ref.
284      */
285     public static DataNodeContainer createSchemaForGet(final SchemaContext schemaContext) {
286         final QName filter = QName.create(NETCONF_GET_QNAME, "filter");
287         final QName get = QName.create(NETCONF_GET_QNAME, "get");
288         final NodeContainerProxy configProxy = new NodeContainerProxy(filter, schemaContext.getChildNodes());
289         final NodeContainerProxy editConfigProxy = new NodeContainerProxy(get, Sets.<DataSchemaNode>newHashSet(configProxy));
290         return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(editConfigProxy));
291     }
292
293     /**
294      * Creates artificial schema node for get rpc. This artificial schema looks like:
295      * <pre>
296      * {@code
297      * rpc
298      *   get-config
299      *     filter
300      *         // All schema nodes from remote schema
301      *     filter
302      *   get-config
303      * rpc
304      * }
305      * </pre>
306      *
307      * This makes the translation of rpc get-config request(especially the config node)
308      * to xml use schema which is crucial for some types of nodes e.g. identity-ref.
309      */
310     public static DataNodeContainer createSchemaForGetConfig(final SchemaContext schemaContext) {
311         final QName filter = QName.create(NETCONF_GET_CONFIG_QNAME, "filter");
312         final QName getConfig = QName.create(NETCONF_GET_CONFIG_QNAME, "get-config");
313         final NodeContainerProxy configProxy = new NodeContainerProxy(filter, schemaContext.getChildNodes());
314         final NodeContainerProxy editConfigProxy = new NodeContainerProxy(getConfig, Sets.<DataSchemaNode>newHashSet(configProxy));
315         return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(editConfigProxy));
316     }
317
318     /**
319      * Creates artificial schema node for schema defined rpc. This artificial schema looks like:
320      * <pre>
321      * {@code
322      * rpc
323      *   rpc-name
324      *      // All schema nodes from remote schema
325      *   rpc-name
326      * rpc
327      * }
328      * </pre>
329      *
330      * This makes the translation of schema defined rpc request
331      * to xml use schema which is crucial for some types of nodes e.g. identity-ref.
332      */
333     public static DataNodeContainer createSchemaForRpc(final QName rpcName, final SchemaContext schemaContext) {
334         Preconditions.checkNotNull(rpcName);
335         Preconditions.checkNotNull(schemaContext);
336
337         final NodeContainerProxy rpcBodyProxy = new NodeContainerProxy(rpcName, schemaContext.getChildNodes());
338         return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(rpcBodyProxy));
339
340     }
341
342     public static CompositeNodeTOImpl wrap(final QName name, final Node<?> node) {
343         if (node != null) {
344             return new CompositeNodeTOImpl(name, null, Collections.<Node<?>> singletonList(node));
345         } else {
346             return new CompositeNodeTOImpl(name, null, Collections.<Node<?>> emptyList());
347         }
348     }
349
350     public static CompositeNodeTOImpl wrap(final QName name, final Node<?> additional, final Node<?> node) {
351         if (node != null) {
352             return new CompositeNodeTOImpl(name, null, ImmutableList.of(additional, node));
353         } else {
354             return new CompositeNodeTOImpl(name, null, ImmutableList.<Node<?>> of(additional));
355         }
356     }
357
358     static ImmutableCompositeNode filter(final String type, final Node<?> node) {
359         final CompositeNodeBuilder<ImmutableCompositeNode> it = ImmutableCompositeNode.builder(); //
360         it.setQName(NETCONF_FILTER_QNAME);
361         it.setAttribute(NETCONF_TYPE_QNAME, type);
362         if (node != null) {
363             return it.add(node).toInstance();
364         } else {
365             return it.toInstance();
366         }
367     }
368 }