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