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