BUG-2673: Introduced new more low-level DOM Data Change APIs
[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.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Predicate;
13 import com.google.common.collect.Collections2;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.ImmutableMap;
16 import com.google.common.collect.Iterables;
17 import com.google.common.collect.Lists;
18 import com.google.common.collect.Sets;
19 import java.net.URI;
20 import java.util.ArrayList;
21 import java.util.Collections;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Map.Entry;
25 import javax.annotation.Nullable;
26 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
27 import org.opendaylight.controller.netconf.api.NetconfMessage;
28 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
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.ModifyAction;
36 import org.opendaylight.yangtools.yang.data.api.Node;
37 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
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     public static QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source");
71     public static QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate");
72     public static QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target");
73     public static QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config");
74     public static QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit");
75     public static QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate");
76     public static QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config");
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     public static URI NETCONF_RUNNING_WRITABLE_URI = URI
95             .create("urn:ietf:params:netconf:capability:writable-running:1.0");
96
97     public static QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock");
98     public static QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock");
99
100     // Discard changes message
101     public static final CompositeNode DISCARD_CHANGES_RPC_CONTENT =
102             NodeFactory.createImmutableCompositeNode(NETCONF_DISCARD_CHANGES_QNAME, null, Collections.<Node<?>>emptyList());
103
104     // Commit changes message
105     public static final CompositeNode COMMIT_RPC_CONTENT =
106             NodeFactory.createImmutableCompositeNode(NETCONF_COMMIT_QNAME, null, Collections.<Node<?>>emptyList());
107
108     public static Node<?> toFilterStructure(final YangInstanceIdentifier identifier) {
109         Node<?> previous = null;
110         if (Iterables.isEmpty(identifier.getPathArguments())) {
111             return null;
112         }
113
114         for (final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument component : identifier.getReversePathArguments()) {
115             if (component instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
116                 previous = toNode((YangInstanceIdentifier.NodeIdentifierWithPredicates)component, previous);
117             } else {
118                 previous = toNode(component, previous);
119             }
120         }
121         return filter("subtree", previous);
122     }
123
124     static Node<?> toNode(final YangInstanceIdentifier.NodeIdentifierWithPredicates argument, final Node<?> node) {
125         final List<Node<?>> list = new ArrayList<>();
126         for (final Map.Entry<QName, Object> arg : argument.getKeyValues().entrySet()) {
127             list.add(new SimpleNodeTOImpl(arg.getKey(), null, arg.getValue()));
128         }
129         if (node != null) {
130             list.add(node);
131         }
132         return new CompositeNodeTOImpl(argument.getNodeType(), null, list);
133     }
134
135     public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
136             throws NetconfDocumentedException {
137         final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
138         final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
139
140         if(inputMsgId.equals(outputMsgId) == false) {
141             Map<String,String> errorInfo = ImmutableMap.<String,String>builder()
142                     .put( "actual-message-id", outputMsgId )
143                     .put( "expected-message-id", inputMsgId )
144                     .build();
145
146             throw new NetconfDocumentedException( "Response message contained unknown \"message-id\"",
147                     null, NetconfDocumentedException.ErrorType.protocol,
148                     NetconfDocumentedException.ErrorTag.bad_attribute,
149                     NetconfDocumentedException.ErrorSeverity.error, errorInfo );
150         }
151     }
152
153     public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
154         if(NetconfMessageUtil.isErrorMessage(output)) {
155             throw NetconfDocumentedException.fromXMLDocument( output.getDocument() );
156         }
157     }
158
159     public static RpcError toRpcError( final NetconfDocumentedException ex )
160     {
161         StringBuilder infoBuilder = new StringBuilder();
162         Map<String, String> errorInfo = ex.getErrorInfo();
163         if( errorInfo != null )
164         {
165             for( Entry<String,String> e: errorInfo.entrySet() ) {
166                 infoBuilder.append( '<' ).append( e.getKey() ).append( '>' ).append( e.getValue() )
167                 .append( "</" ).append( e.getKey() ).append( '>' );
168
169             }
170         }
171
172         ErrorSeverity severity = toRpcErrorSeverity( ex.getErrorSeverity() );
173         return severity == ErrorSeverity.ERROR ?
174                 RpcResultBuilder.newError(
175                         toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
176                         ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() ) :
177                             RpcResultBuilder.newWarning(
178                                     toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
179                                     ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() );
180     }
181
182     private static ErrorSeverity toRpcErrorSeverity( final NetconfDocumentedException.ErrorSeverity severity ) {
183         switch( severity ) {
184         case warning:
185             return RpcError.ErrorSeverity.WARNING;
186         default:
187             return RpcError.ErrorSeverity.ERROR;
188         }
189     }
190
191     private static RpcError.ErrorType toRpcErrorType( final NetconfDocumentedException.ErrorType type )
192     {
193         switch( type ) {
194         case protocol:
195             return RpcError.ErrorType.PROTOCOL;
196         case rpc:
197             return RpcError.ErrorType.RPC;
198         case transport:
199             return RpcError.ErrorType.TRANSPORT;
200         default:
201             return RpcError.ErrorType.APPLICATION;
202         }
203     }
204
205     public static CompositeNode flattenInput(final CompositeNode node) {
206         final QName inputQName = QName.create(node.getNodeType(), "input");
207         final CompositeNode input = node.getFirstCompositeByName(inputQName);
208         if (input == null) {
209             return node;
210         }
211         if (input instanceof CompositeNode) {
212
213             final List<Node<?>> nodes = ImmutableList.<Node<?>> builder() //
214                     .addAll(input.getValue()) //
215                     .addAll(Collections2.filter(node.getValue(), new Predicate<Node<?>>() {
216                         @Override
217                         public boolean apply(@Nullable final Node<?> input) {
218                             return !inputQName.equals(input.getNodeType());
219                         }
220                     })) //
221                     .build();
222
223             return ImmutableCompositeNode.create(node.getNodeType(), nodes);
224         }
225
226         return input;
227     }
228
229     static Node<?> toNode(final YangInstanceIdentifier.PathArgument argument, final Node<?> node) {
230         if (node != null) {
231             return new CompositeNodeTOImpl(argument.getNodeType(), null, Collections.<Node<?>> singletonList(node));
232         } else {
233             return new SimpleNodeTOImpl<Void>(argument.getNodeType(), null, null);
234         }
235     }
236
237     public static Element getDataSubtree(final Document doc) {
238         return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
239     }
240
241     public static boolean isDataRetrievalOperation(final QName rpc) {
242         return NETCONF_URI.equals(rpc.getNamespace())
243                 && (rpc.getLocalName().equals(NETCONF_GET_CONFIG_QNAME.getLocalName()) || rpc.getLocalName().equals(
244                         NETCONF_GET_QNAME.getLocalName()));
245     }
246
247     public static boolean isGetOperation(final QName rpc) {
248         return NETCONF_URI.equals(rpc.getNamespace()) && rpc.getLocalName().equals(NETCONF_GET_QNAME.getLocalName());
249     }
250
251     public static boolean isGetConfigOperation(final QName rpc) {
252         return NETCONF_URI.equals(rpc.getNamespace()) && rpc.getLocalName().equals(NETCONF_GET_CONFIG_QNAME.getLocalName());
253     }
254
255     public static boolean isDataEditOperation(final QName rpc) {
256         return NETCONF_URI.equals(rpc.getNamespace())
257                 && rpc.getLocalName().equals(NETCONF_EDIT_CONFIG_QNAME.getLocalName());
258     }
259
260     /**
261      * Creates artificial schema node for edit-config rpc. This artificial schema looks like:
262      * <pre>
263      * {@code
264      * rpc
265      *   edit-config
266      *     config
267      *         // All schema nodes from remote schema
268      *     config
269      *   edit-config
270      * rpc
271      * }
272      * </pre>
273      *
274      * This makes the translation of rpc edit-config request(especially the config node)
275      * to xml use schema which is crucial for some types of nodes e.g. identity-ref.
276      */
277     public static DataNodeContainer createSchemaForEdit(final SchemaContext schemaContext) {
278         final QName config = QName.create(NETCONF_EDIT_CONFIG_QNAME, "config");
279         final QName editConfig = QName.create(NETCONF_EDIT_CONFIG_QNAME, "edit-config");
280         final NodeContainerProxy configProxy = new NodeContainerProxy(config, schemaContext.getChildNodes());
281         final NodeContainerProxy editConfigProxy = new NodeContainerProxy(editConfig, Sets.<DataSchemaNode>newHashSet(configProxy));
282         return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(editConfigProxy));
283     }
284
285     /**
286      * Creates artificial schema node for edit-config rpc. This artificial schema looks like:
287      * <pre>
288      * {@code
289      * rpc
290      *   get
291      *     filter
292      *         // All schema nodes from remote schema
293      *     filter
294      *   get
295      * rpc
296      * }
297      * </pre>
298      *
299      * This makes the translation of rpc get request(especially the config node)
300      * to xml use schema which is crucial for some types of nodes e.g. identity-ref.
301      */
302     public static DataNodeContainer createSchemaForGet(final SchemaContext schemaContext) {
303         final QName filter = QName.create(NETCONF_GET_QNAME, "filter");
304         final QName get = QName.create(NETCONF_GET_QNAME, "get");
305         final NodeContainerProxy configProxy = new NodeContainerProxy(filter, schemaContext.getChildNodes());
306         final NodeContainerProxy editConfigProxy = new NodeContainerProxy(get, Sets.<DataSchemaNode>newHashSet(configProxy));
307         return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(editConfigProxy));
308     }
309
310     /**
311      * Creates artificial schema node for get rpc. This artificial schema looks like:
312      * <pre>
313      * {@code
314      * rpc
315      *   get-config
316      *     filter
317      *         // All schema nodes from remote schema
318      *     filter
319      *   get-config
320      * rpc
321      * }
322      * </pre>
323      *
324      * This makes the translation of rpc get-config request(especially the config node)
325      * to xml use schema which is crucial for some types of nodes e.g. identity-ref.
326      */
327     public static DataNodeContainer createSchemaForGetConfig(final SchemaContext schemaContext) {
328         final QName filter = QName.create(NETCONF_GET_CONFIG_QNAME, "filter");
329         final QName getConfig = QName.create(NETCONF_GET_CONFIG_QNAME, "get-config");
330         final NodeContainerProxy configProxy = new NodeContainerProxy(filter, schemaContext.getChildNodes());
331         final NodeContainerProxy editConfigProxy = new NodeContainerProxy(getConfig, Sets.<DataSchemaNode>newHashSet(configProxy));
332         return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(editConfigProxy));
333     }
334
335
336     public static Optional<RpcDefinition> findSchemaForRpc(final QName rpcName, final SchemaContext schemaContext) {
337         Preconditions.checkNotNull(rpcName);
338         Preconditions.checkNotNull(schemaContext);
339
340         for (final RpcDefinition rpcDefinition : schemaContext.getOperations()) {
341             if(rpcDefinition.getQName().equals(rpcName)) {
342                 return Optional.of(rpcDefinition);
343             }
344         }
345
346         return Optional.absent();
347     }
348
349     /**
350      * Creates artificial schema node for schema defined rpc. This artificial schema looks like:
351      * <pre>
352      * {@code
353      * rpc
354      *   rpc-name
355      *      // All schema nodes from remote schema
356      *   rpc-name
357      * rpc
358      * }
359      * </pre>
360      *
361      * This makes the translation of schema defined rpc request
362      * to xml use schema which is crucial for some types of nodes e.g. identity-ref.
363      */
364     public static DataNodeContainer createSchemaForRpc(final RpcDefinition rpcDefinition) {
365         final NodeContainerProxy rpcBodyProxy = new NodeContainerProxy(rpcDefinition.getQName(), rpcDefinition.getInput().getChildNodes());
366         return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(rpcBodyProxy));
367     }
368
369     public static CompositeNodeTOImpl wrap(final QName name, final Node<?> node) {
370         if (node != null) {
371             return new CompositeNodeTOImpl(name, null, Collections.<Node<?>> singletonList(node));
372         } else {
373             return new CompositeNodeTOImpl(name, null, Collections.<Node<?>> emptyList());
374         }
375     }
376
377     public static CompositeNodeTOImpl wrap(final QName name, final Node<?> additional, final Node<?> node) {
378         if (node != null) {
379             return new CompositeNodeTOImpl(name, null, ImmutableList.of(additional, node));
380         } else {
381             return new CompositeNodeTOImpl(name, null, ImmutableList.<Node<?>> of(additional));
382         }
383     }
384
385     static ImmutableCompositeNode filter(final String type, final Node<?> node) {
386         final CompositeNodeBuilder<ImmutableCompositeNode> it = ImmutableCompositeNode.builder(); //
387         it.setQName(NETCONF_FILTER_QNAME);
388         it.setAttribute(NETCONF_TYPE_QNAME, type);
389         if (node != null) {
390             return it.add(node).toInstance();
391         } else {
392             return it.toInstance();
393         }
394     }
395
396     public static Node<?> findNode(final CompositeNode node, final YangInstanceIdentifier identifier) {
397
398         Node<?> current = node;
399         for (final YangInstanceIdentifier.PathArgument arg : identifier.getPathArguments()) {
400             if (current instanceof SimpleNode<?>) {
401                 return null;
402             } else if (current instanceof CompositeNode) {
403                 final CompositeNode currentComposite = (CompositeNode) current;
404
405                 current = currentComposite.getFirstCompositeByName(arg.getNodeType());
406                 if (current == null) {
407                     current = currentComposite.getFirstCompositeByName(arg.getNodeType().withoutRevision());
408                 }
409                 if (current == null) {
410                     current = currentComposite.getFirstSimpleByName(arg.getNodeType());
411                 }
412                 if (current == null) {
413                     current = currentComposite.getFirstSimpleByName(arg.getNodeType().withoutRevision());
414                 }
415                 if (current == null) {
416                     return null;
417                 }
418             }
419         }
420         return current;
421     }
422
423     public static String modifyOperationToXmlString(final ModifyAction operation) {
424         return operation.name().toLowerCase();
425     }
426
427
428     public static CompositeNode createEditConfigStructure(final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
429                                                     final Optional<CompositeNode> lastChildOverride) {
430         Preconditions.checkArgument(Iterables.isEmpty(dataPath.getPathArguments()) == false, "Instance identifier with empty path %s", dataPath);
431
432         List<YangInstanceIdentifier.PathArgument> reversedPath = Lists.reverse(dataPath.getPath());
433
434         // Create deepest edit element with expected edit operation
435         CompositeNode previous = getDeepestEditElement(reversedPath.get(0), operation, lastChildOverride);
436
437         // Remove already processed deepest child
438         reversedPath = Lists.newArrayList(reversedPath);
439         reversedPath.remove(0);
440
441         // Create edit structure in reversed order
442         for (final YangInstanceIdentifier.PathArgument arg : reversedPath) {
443             final CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
444             builder.setQName(arg.getNodeType());
445
446             addPredicatesToCompositeNodeBuilder(getPredicates(arg), builder);
447
448             builder.add(previous);
449             previous = builder.toInstance();
450         }
451         return ImmutableCompositeNode.create(NETCONF_CONFIG_QNAME, ImmutableList.<Node<?>>of(previous));
452     }
453
454     public static void addPredicatesToCompositeNodeBuilder(final Map<QName, Object> predicates, final CompositeNodeBuilder<ImmutableCompositeNode> builder) {
455         for (final Map.Entry<QName, Object> entry : predicates.entrySet()) {
456             builder.addLeaf(entry.getKey(), entry.getValue());
457         }
458     }
459
460     public static Map<QName, Object> getPredicates(final YangInstanceIdentifier.PathArgument arg) {
461         Map<QName, Object> predicates = Collections.emptyMap();
462         if (arg instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
463             predicates = ((YangInstanceIdentifier.NodeIdentifierWithPredicates) arg).getKeyValues();
464         }
465         return predicates;
466     }
467
468     public static CompositeNode getDeepestEditElement(final YangInstanceIdentifier.PathArgument arg, final Optional<ModifyAction> operation, final Optional<CompositeNode> lastChildOverride) {
469         final CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
470         builder.setQName(arg.getNodeType());
471
472         final Map<QName, Object> predicates = getPredicates(arg);
473         addPredicatesToCompositeNodeBuilder(predicates, builder);
474
475         if (operation.isPresent()) {
476             builder.setAttribute(NETCONF_OPERATION_QNAME, modifyOperationToXmlString(operation.get()));
477         }
478         if (lastChildOverride.isPresent()) {
479             final List<Node<?>> children = lastChildOverride.get().getValue();
480             for(final Node<?> child : children) {
481                 if(!predicates.containsKey(child.getKey())) {
482                     builder.add(child);
483                 }
484             }
485         }
486
487         return builder.toInstance();
488     }
489 }