2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.netconf.sal.connect.netconf.util;
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;
16 import java.time.format.DateTimeParseException;
17 import java.util.AbstractMap;
18 import java.util.Collection;
19 import java.util.Collections;
20 import java.util.Date;
21 import java.util.List;
23 import java.util.Map.Entry;
24 import javax.xml.stream.XMLStreamException;
25 import javax.xml.stream.XMLStreamWriter;
26 import javax.xml.transform.dom.DOMResult;
27 import javax.xml.transform.dom.DOMSource;
28 import org.opendaylight.controller.config.util.xml.DocumentedException;
29 import org.opendaylight.controller.config.util.xml.XmlElement;
30 import org.opendaylight.controller.config.util.xml.XmlUtil;
31 import org.opendaylight.netconf.api.FailedNetconfMessage;
32 import org.opendaylight.netconf.api.NetconfDocumentedException;
33 import org.opendaylight.netconf.api.NetconfMessage;
34 import org.opendaylight.netconf.notifications.NetconfNotification;
35 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
36 import org.opendaylight.netconf.util.NetconfUtil;
37 import org.opendaylight.netconf.util.messages.NetconfMessageUtil;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.EditContent;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
41 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
42 import org.opendaylight.yangtools.yang.common.QName;
43 import org.opendaylight.yangtools.yang.common.RpcError;
44 import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
45 import org.opendaylight.yangtools.yang.common.RpcResult;
46 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
47 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
51 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
54 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
56 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XMLStreamNormalizedNodeStreamWriter;
57 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
58 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
59 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
60 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
61 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
63 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
64 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
67 import org.w3c.dom.Document;
68 import org.w3c.dom.Element;
70 public class NetconfMessageTransformUtil {
72 private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformUtil.class);
74 public static final String MESSAGE_ID_PREFIX = "m";
75 public static final String MESSAGE_ID_ATTR = "message-id";
77 public static final QName CREATE_SUBSCRIPTION_RPC_QNAME = QName.create(CreateSubscriptionInput.QNAME, "create-subscription").intern();
78 private static final String SUBTREE = "subtree";
80 // Blank document used for creation of new DOM nodes
81 private static final Document BLANK_DOCUMENT = XmlUtil.newDocument();
82 public static final String EVENT_TIME = "eventTime";
84 private NetconfMessageTransformUtil() {}
86 public static final QName IETF_NETCONF_MONITORING = QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
87 public static final QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data").intern();
88 public static final QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema").intern();
89 public static final QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT = QName.create(IETF_NETCONF_MONITORING, "format").intern();
90 public static final QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION = QName.create(IETF_NETCONF_MONITORING, "location").intern();
91 public static final QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER = QName.create(IETF_NETCONF_MONITORING, "identifier").intern();
92 public static final QName IETF_NETCONF_MONITORING_SCHEMA_VERSION = QName.create(IETF_NETCONF_MONITORING, "version").intern();
93 public static final QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE = QName.create(IETF_NETCONF_MONITORING, "namespace").intern();
95 public static final QName IETF_NETCONF_NOTIFICATIONS = QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications").intern();
97 public static final QName NETCONF_QNAME = QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "netconf").intern();
98 public static final URI NETCONF_URI = NETCONF_QNAME.getNamespace();
100 public static final QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data").intern();
101 public static final QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply").intern();
102 public static final QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok").intern();
103 public static final QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option").intern();
104 public static final QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running").intern();
105 public static final QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source").intern();
106 public static final QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate").intern();
107 public static final QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target").intern();
108 public static final QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config").intern();
109 public static final QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit").intern();
110 public static final QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate").intern();
111 public static final QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config").intern();
112 public static final QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation").intern();
113 public static final QName NETCONF_DEFAULT_OPERATION_QNAME = QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
114 public static final QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config").intern();
115 public static final QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
116 public static final QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
117 public static final QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type").intern();
118 public static final QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter").intern();
119 public static final QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get").intern();
120 public static final QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc").intern();
122 public static final URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
123 .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
124 public static final String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
126 public static final URI NETCONF_CANDIDATE_URI = URI
127 .create("urn:ietf:params:netconf:capability:candidate:1.0");
129 public static final URI NETCONF_NOTIFICATONS_URI = URI
130 .create("urn:ietf:params:netconf:capability:notification:1.0");
132 public static final URI NETCONF_RUNNING_WRITABLE_URI = URI
133 .create("urn:ietf:params:netconf:capability:writable-running:1.0");
135 public static final QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock").intern();
136 public static final QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock").intern();
138 // Discard changes message
139 public static final ContainerNode DISCARD_CHANGES_RPC_CONTENT =
140 Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(NETCONF_DISCARD_CHANGES_QNAME)).build();
142 // Commit changes message
143 public static final ContainerNode COMMIT_RPC_CONTENT =
144 Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(NETCONF_COMMIT_QNAME)).build();
147 public static final ContainerNode GET_RPC_CONTENT =
148 Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(NETCONF_GET_QNAME)).build();
150 // Create-subscription changes message
151 public static final ContainerNode CREATE_SUBSCRIPTION_RPC_CONTENT =
152 Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(CREATE_SUBSCRIPTION_RPC_QNAME)).build();
154 public static final DataContainerChild<?, ?> EMPTY_FILTER;
157 final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder = Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
158 anyXmlBuilder.withAttributes(Collections.singletonMap(NETCONF_TYPE_QNAME, SUBTREE));
160 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(), Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
161 element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(), "subtree");
163 anyXmlBuilder.withValue(new DOMSource(element));
165 EMPTY_FILTER = anyXmlBuilder.build();
168 public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier, final SchemaContext ctx) {
169 final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder = Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
170 anyXmlBuilder.withAttributes(Collections.singletonMap(NETCONF_TYPE_QNAME, SUBTREE));
172 final NormalizedNode<?, ?> filterContent = ImmutableNodes.fromInstanceId(ctx, identifier);
174 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(), Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
175 element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(), "subtree");
178 NetconfUtil.writeNormalizedNode(filterContent, new DOMResult(element), SchemaPath.ROOT, ctx);
179 } catch (IOException | XMLStreamException e) {
180 throw new IllegalStateException("Unable to serialize filter element for path " + identifier, e);
182 anyXmlBuilder.withValue(new DOMSource(element));
184 return anyXmlBuilder.build();
187 public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
188 throws NetconfDocumentedException {
189 final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
190 final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
192 if(inputMsgId.equals(outputMsgId) == false) {
193 final Map<String,String> errorInfo = ImmutableMap.<String,String>builder()
194 .put( "actual-message-id", outputMsgId )
195 .put( "expected-message-id", inputMsgId )
198 throw new NetconfDocumentedException( "Response message contained unknown \"message-id\"",
199 null, NetconfDocumentedException.ErrorType.PROTOCOL,
200 NetconfDocumentedException.ErrorTag.BAD_ATTRIBUTE,
201 NetconfDocumentedException.ErrorSeverity.ERROR, errorInfo);
205 public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
206 if(NetconfMessageUtil.isErrorMessage(output)) {
207 throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
211 public static RpcError toRpcError( final NetconfDocumentedException ex ) {
212 final StringBuilder infoBuilder = new StringBuilder();
213 final Map<String, String> errorInfo = ex.getErrorInfo();
214 if(errorInfo != null) {
215 for( final Entry<String,String> e: errorInfo.entrySet() ) {
216 infoBuilder.append( '<' ).append( e.getKey() ).append( '>' ).append( e.getValue() )
217 .append( "</" ).append( e.getKey() ).append( '>' );
222 final ErrorSeverity severity = toRpcErrorSeverity( ex.getErrorSeverity() );
223 return severity == ErrorSeverity.ERROR ?
224 RpcResultBuilder.newError(
225 toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
226 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() ) :
227 RpcResultBuilder.newWarning(
228 toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
229 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() );
232 private static ErrorSeverity toRpcErrorSeverity( final NetconfDocumentedException.ErrorSeverity severity ) {
235 return RpcError.ErrorSeverity.WARNING;
237 return RpcError.ErrorSeverity.ERROR;
241 private static RpcError.ErrorType toRpcErrorType(final NetconfDocumentedException.ErrorType type) {
244 return RpcError.ErrorType.PROTOCOL;
246 return RpcError.ErrorType.RPC;
248 return RpcError.ErrorType.TRANSPORT;
250 return RpcError.ErrorType.APPLICATION;
254 public static NodeIdentifier toId(final PathArgument qname) {
255 return toId(qname.getNodeType());
258 public static NodeIdentifier toId(final QName nodeType) {
259 return new NodeIdentifier(nodeType);
262 public static Element getDataSubtree(final Document doc) {
263 return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
266 public static boolean isDataRetrievalOperation(final QName rpc) {
267 return NETCONF_URI.equals(rpc.getNamespace())
268 && (NETCONF_GET_CONFIG_QNAME.getLocalName().equals(rpc.getLocalName())
269 || NETCONF_GET_QNAME.getLocalName().equals(rpc.getLocalName()));
272 public static ContainerSchemaNode createSchemaForDataRead(final SchemaContext schemaContext) {
273 return new NodeContainerProxy(NETCONF_DATA_QNAME, schemaContext.getChildNodes());
276 public static ContainerSchemaNode createSchemaForNotification(final NotificationDefinition next) {
277 return new NodeContainerProxy(next.getQName(), next.getChildNodes(), next.getAvailableAugmentations());
280 public static ContainerNode wrap(final QName name, final DataContainerChild<?, ?>... node) {
281 return Builders.containerBuilder().withNodeIdentifier(toId(name)).withValue(ImmutableList.copyOf(node)).build();
284 public static AnyXmlNode createEditConfigAnyxml(final SchemaContext ctx, final YangInstanceIdentifier dataPath,
285 final Optional<ModifyAction> operation, final Optional<NormalizedNode<?, ?>> lastChildOverride) {
286 final NormalizedNode<?, ?> configContent;
288 if (dataPath.isEmpty()) {
289 Preconditions.checkArgument(lastChildOverride.isPresent(), "Data has to be present when creating structure for top level element");
290 Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild<?, ?>,
291 "Data has to be either container or a list node when creating structure for top level element, but was: %s", lastChildOverride.get());
292 configContent = lastChildOverride.get();
294 final Entry<QName, ModifyAction> modifyOperation =
295 operation.isPresent() ? new AbstractMap.SimpleEntry<>(NETCONF_OPERATION_QNAME, operation.get()) : null;
296 configContent = ImmutableNodes.fromInstanceId(ctx, dataPath, lastChildOverride, Optional.fromNullable(modifyOperation));
299 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(), Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
301 NetconfUtil.writeNormalizedNode(configContent, new DOMResult(element), SchemaPath.ROOT, ctx);
302 } catch (IOException | XMLStreamException e) {
303 throw new IllegalStateException("Unable to serialize edit config content element for path " + dataPath, e);
305 final DOMSource value = new DOMSource(element);
307 return Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_CONFIG_QNAME)).withValue(value).build();
310 public static DataContainerChild<?, ?> createEditConfigStructure(final SchemaContext ctx, final YangInstanceIdentifier dataPath,
311 final Optional<ModifyAction> operation, final Optional<NormalizedNode<?, ?>> lastChildOverride) {
312 return Builders.choiceBuilder().withNodeIdentifier(toId(EditContent.QNAME))
313 .withChild(createEditConfigAnyxml(ctx, dataPath, operation, lastChildOverride)).build();
316 public static SchemaPath toPath(final QName rpc) {
317 return SchemaPath.create(true, rpc);
320 public static Map.Entry<Date, XmlElement> stripNotification(final NetconfMessage message) {
321 final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
322 final List<XmlElement> childElements = xmlElement.getChildElements();
323 Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format.\nExpected 2 childElements," +
324 " actual childElements size is %s", message, childElements.size());
326 final XmlElement eventTimeElement;
327 final XmlElement notificationElement;
329 if (childElements.get(0).getName().equals(EVENT_TIME)) {
330 eventTimeElement = childElements.get(0);
331 notificationElement = childElements.get(1);
333 else if(childElements.get(1).getName().equals(EVENT_TIME)) {
334 eventTimeElement = childElements.get(1);
335 notificationElement = childElements.get(0);
337 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
341 return new AbstractMap.SimpleEntry<>(
342 NetconfNotification.RFC3339_DATE_PARSER.apply(eventTimeElement.getTextContent()),
343 notificationElement);
344 } catch (final DocumentedException e) {
345 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
346 } catch (final DateTimeParseException e) {
347 LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement, NetconfNotification.UNKNOWN_EVENT_TIME, e);
348 return new AbstractMap.SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME, notificationElement);
352 public static DOMResult prepareDomResultForRpcRequest(final QName rpcQName, final MessageCounter counter) {
353 final Document document = XmlUtil.newDocument();
354 final Element rpcNS =
355 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
357 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
358 final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
359 rpcNS.appendChild(elementNS);
360 document.appendChild(rpcNS);
361 return new DOMResult(elementNS);
364 public static void writeNormalizedRpc(final ContainerNode normalized, final DOMResult result,
365 final SchemaPath schemaPath, final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
366 final XMLStreamWriter writer = NetconfUtil.XML_FACTORY.createXMLStreamWriter(result);
368 try (final NormalizedNodeStreamWriter normalizedNodeStreamWriter =
369 XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, schemaPath)) {
370 try (final SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
371 new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, schemaPath)) {
372 final Collection<DataContainerChild<?, ?>> value = normalized.getValue();
373 normalizedNodeWriter.write(value);
374 normalizedNodeWriter.flush();
380 } catch (final Exception e) {
381 LOG.warn("Unable to close resource properly", e);
386 public static RpcResult<NetconfMessage> toRpcResult(final FailedNetconfMessage message) {
387 return RpcResultBuilder.<NetconfMessage>failed()
390 new NetconfDocumentedException(
391 message.getException().getMessage(),
392 DocumentedException.ErrorType.APPLICATION,
393 DocumentedException.ErrorTag.MALFORMED_MESSAGE,
394 DocumentedException.ErrorSeverity.ERROR)))