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