a0622d719c41fa60a0ed1c4d5823dc5a9a0ef802
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / 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.netconf.sal.connect.netconf.util;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableList;
13 import com.google.common.collect.ImmutableMap;
14 import java.io.IOException;
15 import java.net.URI;
16 import java.util.AbstractMap;
17 import java.util.Collections;
18 import java.util.Map;
19 import java.util.Map.Entry;
20 import javax.xml.stream.XMLStreamException;
21 import javax.xml.transform.dom.DOMResult;
22 import javax.xml.transform.dom.DOMSource;
23 import org.opendaylight.controller.config.util.xml.XmlUtil;
24 import org.opendaylight.netconf.api.NetconfDocumentedException;
25 import org.opendaylight.netconf.api.NetconfMessage;
26 import org.opendaylight.netconf.util.NetconfUtil;
27 import org.opendaylight.netconf.util.messages.NetconfMessageUtil;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.EditContent;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
32 import org.opendaylight.yangtools.yang.common.QName;
33 import org.opendaylight.yangtools.yang.common.RpcError;
34 import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
35 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
36 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
38 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
41 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
42 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
43 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
44 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
45 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
47 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
48 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import org.w3c.dom.Document;
52 import org.w3c.dom.Element;
53
54 public class NetconfMessageTransformUtil {
55
56     private static final Logger LOG= LoggerFactory.getLogger(NetconfMessageTransformUtil.class);
57
58     public static final String MESSAGE_ID_ATTR = "message-id";
59
60     public static final QName CREATE_SUBSCRIPTION_RPC_QNAME = QName.cachedReference(QName.create(CreateSubscriptionInput.QNAME, "create-subscription"));
61     private static final String SUBTREE = "subtree";
62
63     // Blank document used for creation of new DOM nodes
64     private static final Document BLANK_DOCUMENT = XmlUtil.newDocument();
65     public static final String EVENT_TIME = "eventTime";
66
67     private NetconfMessageTransformUtil() {}
68
69     public static final QName IETF_NETCONF_MONITORING = QName.create(NetconfState.QNAME, "ietf-netconf-monitoring");
70     public static final QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data");
71     public static final QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema");
72     public static final QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT = QName.create(IETF_NETCONF_MONITORING, "format");
73     public static final QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION = QName.create(IETF_NETCONF_MONITORING, "location");
74     public static final QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER = QName.create(IETF_NETCONF_MONITORING, "identifier");
75     public static final QName IETF_NETCONF_MONITORING_SCHEMA_VERSION = QName.create(IETF_NETCONF_MONITORING, "version");
76     public static final QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE = QName.create(IETF_NETCONF_MONITORING, "namespace");
77
78     public static final QName IETF_NETCONF_NOTIFICATIONS = QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications");
79
80     public static final QName NETCONF_QNAME = QName.cachedReference(QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "netconf"));
81     public static final URI NETCONF_URI = NETCONF_QNAME.getNamespace();
82
83     public static final QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data");
84     public static final QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply");
85     public static final QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok");
86     public static final QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option");
87     public static final QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running");
88     public static final QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source");
89     public static final QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate");
90     public static final QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target");
91     public static final QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config");
92     public static final QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit");
93     public static final QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate");
94     public static final QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config");
95     public static final QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation");
96     public static final QName NETCONF_DEFAULT_OPERATION_QNAME = QName.create(NETCONF_OPERATION_QNAME, "default-operation");
97     public static final QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config");
98     public static final QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
99     public static final QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
100     public static final QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type");
101     public static final QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter");
102     public static final QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get");
103     public static final QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc");
104
105     public static final URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
106             .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
107     public static final String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
108
109     public static final URI NETCONF_CANDIDATE_URI = URI
110             .create("urn:ietf:params:netconf:capability:candidate:1.0");
111
112     public static final URI NETCONF_NOTIFICATONS_URI = URI
113             .create("urn:ietf:params:netconf:capability:notification:1.0");
114
115     public static final URI NETCONF_RUNNING_WRITABLE_URI = URI
116             .create("urn:ietf:params:netconf:capability:writable-running:1.0");
117
118     public static final QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock");
119     public static final QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock");
120
121     // Discard changes message
122     public static final ContainerNode DISCARD_CHANGES_RPC_CONTENT =
123             Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NETCONF_DISCARD_CHANGES_QNAME)).build();
124
125     // Commit changes message
126     public static final ContainerNode COMMIT_RPC_CONTENT =
127             Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NETCONF_COMMIT_QNAME)).build();
128
129     // Get message
130     public static final ContainerNode GET_RPC_CONTENT =
131             Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NETCONF_GET_QNAME)).build();
132
133     // Create-subscription changes message
134     public static final ContainerNode CREATE_SUBSCRIPTION_RPC_CONTENT =
135             Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CREATE_SUBSCRIPTION_RPC_QNAME)).build();
136
137     public static final DataContainerChild<?, ?> EMPTY_FILTER;
138
139     static {
140         final NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder = Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
141         anyXmlBuilder.withAttributes(Collections.singletonMap(NETCONF_TYPE_QNAME, SUBTREE));
142
143         final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(), Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
144         element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(), "subtree");
145
146         anyXmlBuilder.withValue(new DOMSource(element));
147
148         EMPTY_FILTER = anyXmlBuilder.build();
149     }
150
151     public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier, final SchemaContext ctx) {
152         final NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder = Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
153         anyXmlBuilder.withAttributes(Collections.singletonMap(NETCONF_TYPE_QNAME, SUBTREE));
154
155         final NormalizedNode<?, ?> filterContent = ImmutableNodes.fromInstanceId(ctx, identifier);
156
157         final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(), Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
158         element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(), "subtree");
159
160         try {
161             NetconfUtil.writeNormalizedNode(filterContent, new DOMResult(element), SchemaPath.ROOT, ctx);
162         } catch (IOException | XMLStreamException e) {
163             throw new IllegalStateException("Unable to serialize filter element for path " + identifier, e);
164         }
165         anyXmlBuilder.withValue(new DOMSource(element));
166
167         return anyXmlBuilder.build();
168     }
169
170     public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
171             throws NetconfDocumentedException {
172         final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
173         final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
174
175         if(inputMsgId.equals(outputMsgId) == false) {
176             final Map<String,String> errorInfo = ImmutableMap.<String,String>builder()
177                     .put( "actual-message-id", outputMsgId )
178                     .put( "expected-message-id", inputMsgId )
179                     .build();
180
181             throw new NetconfDocumentedException( "Response message contained unknown \"message-id\"",
182                     null, NetconfDocumentedException.ErrorType.protocol,
183                     NetconfDocumentedException.ErrorTag.bad_attribute,
184                     NetconfDocumentedException.ErrorSeverity.error, errorInfo );
185         }
186     }
187
188     public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
189         if(NetconfMessageUtil.isErrorMessage(output)) {
190             throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
191         }
192     }
193
194     public static RpcError toRpcError( final NetconfDocumentedException ex ) {
195         final StringBuilder infoBuilder = new StringBuilder();
196         final Map<String, String> errorInfo = ex.getErrorInfo();
197         if(errorInfo != null) {
198             for( final Entry<String,String> e: errorInfo.entrySet() ) {
199                 infoBuilder.append( '<' ).append( e.getKey() ).append( '>' ).append( e.getValue() )
200                 .append( "</" ).append( e.getKey() ).append( '>' );
201
202             }
203         }
204
205         final ErrorSeverity severity = toRpcErrorSeverity( ex.getErrorSeverity() );
206         return severity == ErrorSeverity.ERROR ?
207                 RpcResultBuilder.newError(
208                         toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
209                         ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() ) :
210                             RpcResultBuilder.newWarning(
211                                     toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
212                                     ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() );
213     }
214
215     private static ErrorSeverity toRpcErrorSeverity( final NetconfDocumentedException.ErrorSeverity severity ) {
216         switch (severity) {
217         case warning:
218             return RpcError.ErrorSeverity.WARNING;
219         default:
220             return RpcError.ErrorSeverity.ERROR;
221         }
222     }
223
224     private static RpcError.ErrorType toRpcErrorType(final NetconfDocumentedException.ErrorType type) {
225         switch (type) {
226         case protocol:
227             return RpcError.ErrorType.PROTOCOL;
228         case rpc:
229             return RpcError.ErrorType.RPC;
230         case transport:
231             return RpcError.ErrorType.TRANSPORT;
232         default:
233             return RpcError.ErrorType.APPLICATION;
234         }
235     }
236
237     public static YangInstanceIdentifier.NodeIdentifier toId(final YangInstanceIdentifier.PathArgument qname) {
238         return toId(qname.getNodeType());
239     }
240
241     public static YangInstanceIdentifier.NodeIdentifier toId(final QName nodeType) {
242         return new YangInstanceIdentifier.NodeIdentifier(nodeType);
243     }
244
245     public static Element getDataSubtree(final Document doc) {
246         return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
247     }
248
249     public static boolean isDataRetrievalOperation(final QName rpc) {
250         return NETCONF_URI.equals(rpc.getNamespace())
251                 && (NETCONF_GET_CONFIG_QNAME.getLocalName().equals(rpc.getLocalName())
252                 || NETCONF_GET_QNAME.getLocalName().equals(rpc.getLocalName()));
253     }
254
255     public static ContainerSchemaNode createSchemaForDataRead(final SchemaContext schemaContext) {
256         return new NodeContainerProxy(NETCONF_DATA_QNAME, schemaContext.getChildNodes());
257     }
258
259     public static ContainerSchemaNode createSchemaForNotification(final NotificationDefinition next) {
260         return new NodeContainerProxy(next.getQName(), next.getChildNodes(), next.getAvailableAugmentations());
261     }
262
263     public static ContainerNode wrap(final QName name, final DataContainerChild<?, ?>... node) {
264         return Builders.containerBuilder().withNodeIdentifier(toId(name)).withValue(ImmutableList.copyOf(node)).build();
265     }
266
267     public static DataContainerChild<?, ?> createEditConfigStructure(final SchemaContext ctx, final YangInstanceIdentifier dataPath,
268                                                                      final Optional<ModifyAction> operation, final Optional<NormalizedNode<?, ?>> lastChildOverride) {
269         final NormalizedNode<?, ?> configContent;
270
271         if (dataPath.isEmpty()) {
272             Preconditions.checkArgument(lastChildOverride.isPresent(), "Data has to be present when creating structure for top level element");
273             Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild<?, ?>,
274                     "Data has to be either container or a list node when creating structure for top level element, but was: %s", lastChildOverride.get());
275             configContent = lastChildOverride.get();
276         } else {
277             final Entry<QName, ModifyAction> modifyOperation =
278                     operation.isPresent() ? new AbstractMap.SimpleEntry<>(NETCONF_OPERATION_QNAME, operation.get()) : null;
279             configContent = ImmutableNodes.fromInstanceId(ctx, dataPath, lastChildOverride, Optional.fromNullable(modifyOperation));
280         }
281
282         final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(), Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
283         try {
284             NetconfUtil.writeNormalizedNode(configContent, new DOMResult(element), SchemaPath.ROOT, ctx);
285         } catch (IOException | XMLStreamException e) {
286             throw new IllegalStateException("Unable to serialize edit config content element for path " + dataPath, e);
287         }
288         final DOMSource value = new DOMSource(element);
289
290         return Builders.choiceBuilder().withNodeIdentifier(toId(EditContent.QNAME)).withChild(
291                 Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_CONFIG_QNAME)).withValue(value).build()).build();
292     }
293
294     public static SchemaPath toPath(final QName rpc) {
295         return SchemaPath.create(true, rpc);
296     }
297
298 }