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