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