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.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 =
78 QName.create(CreateSubscriptionInput.QNAME, "create-subscription").intern();
79 private static final String SUBTREE = "subtree";
81 // Blank document used for creation of new DOM nodes
82 private static final Document BLANK_DOCUMENT = XmlUtil.newDocument();
83 public static final String EVENT_TIME = "eventTime";
85 private NetconfMessageTransformUtil() {}
87 public static final QName IETF_NETCONF_MONITORING =
88 QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
89 public static final QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data").intern();
90 public static final QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema").intern();
91 public static final QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT =
92 QName.create(IETF_NETCONF_MONITORING, "format").intern();
93 public static final QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION =
94 QName.create(IETF_NETCONF_MONITORING, "location").intern();
95 public static final QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER =
96 QName.create(IETF_NETCONF_MONITORING, "identifier").intern();
97 public static final QName IETF_NETCONF_MONITORING_SCHEMA_VERSION =
98 QName.create(IETF_NETCONF_MONITORING, "version").intern();
99 public static final QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE =
100 QName.create(IETF_NETCONF_MONITORING, "namespace").intern();
102 public static final QName IETF_NETCONF_NOTIFICATIONS =
103 QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications").intern();
105 public static final QName NETCONF_QNAME =
106 QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "netconf").intern();
107 public static final URI NETCONF_URI = NETCONF_QNAME.getNamespace();
109 public static final QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data").intern();
110 public static final QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply").intern();
111 public static final QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok").intern();
112 public static final QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option").intern();
113 public static final QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running").intern();
114 public static final QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source").intern();
115 public static final QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate").intern();
116 public static final QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target").intern();
117 public static final QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config").intern();
118 public static final QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit").intern();
119 public static final QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate").intern();
120 public static final QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config").intern();
121 public static final QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation").intern();
122 public static final QName NETCONF_DEFAULT_OPERATION_QNAME =
123 QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
124 public static final QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config").intern();
125 public static final QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
126 public static final QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
127 public static final QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type").intern();
128 public static final QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter").intern();
129 public static final QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get").intern();
130 public static final QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc").intern();
132 public static final URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
133 .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
134 public static final String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
136 public static final URI NETCONF_CANDIDATE_URI = URI
137 .create("urn:ietf:params:netconf:capability:candidate:1.0");
139 public static final URI NETCONF_NOTIFICATONS_URI = URI
140 .create("urn:ietf:params:netconf:capability:notification:1.0");
142 public static final URI NETCONF_RUNNING_WRITABLE_URI = URI
143 .create("urn:ietf:params:netconf:capability:writable-running:1.0");
145 public static final QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock").intern();
146 public static final QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock").intern();
148 // Discard changes message
149 public static final ContainerNode DISCARD_CHANGES_RPC_CONTENT =
150 Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(NETCONF_DISCARD_CHANGES_QNAME)).build();
152 // Commit changes message
153 public static final ContainerNode COMMIT_RPC_CONTENT =
154 Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(NETCONF_COMMIT_QNAME)).build();
157 public static final ContainerNode GET_RPC_CONTENT =
158 Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(NETCONF_GET_QNAME)).build();
160 // Create-subscription changes message
161 public static final ContainerNode CREATE_SUBSCRIPTION_RPC_CONTENT =
162 Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(CREATE_SUBSCRIPTION_RPC_QNAME)).build();
164 public static final DataContainerChild<?, ?> EMPTY_FILTER;
167 final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder =
168 Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
169 anyXmlBuilder.withAttributes(Collections.singletonMap(NETCONF_TYPE_QNAME, SUBTREE));
171 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
172 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
173 element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(),
174 NETCONF_TYPE_QNAME.getLocalName(), "subtree");
176 anyXmlBuilder.withValue(new DOMSource(element));
178 EMPTY_FILTER = anyXmlBuilder.build();
181 public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier,
182 final SchemaContext ctx) {
183 final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder =
184 Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
185 anyXmlBuilder.withAttributes(Collections.singletonMap(NETCONF_TYPE_QNAME, SUBTREE));
187 final NormalizedNode<?, ?> filterContent = ImmutableNodes.fromInstanceId(ctx, identifier);
189 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
190 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
191 element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
195 NetconfUtil.writeNormalizedNode(filterContent, new DOMResult(element), SchemaPath.ROOT, ctx);
196 } catch (IOException | XMLStreamException e) {
197 throw new IllegalStateException("Unable to serialize filter element for path " + identifier, e);
199 anyXmlBuilder.withValue(new DOMSource(element));
201 return anyXmlBuilder.build();
204 public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
205 throws NetconfDocumentedException {
206 final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
207 final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
209 if (!inputMsgId.equals(outputMsgId)) {
210 final Map<String, String> errorInfo = ImmutableMap.<String, String>builder()
211 .put("actual-message-id", outputMsgId)
212 .put("expected-message-id", inputMsgId)
215 throw new NetconfDocumentedException("Response message contained unknown \"message-id\"",
216 null, NetconfDocumentedException.ErrorType.PROTOCOL,
217 NetconfDocumentedException.ErrorTag.BAD_ATTRIBUTE,
218 NetconfDocumentedException.ErrorSeverity.ERROR, errorInfo);
222 public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
223 if (NetconfMessageUtil.isErrorMessage(output)) {
224 throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
228 public static RpcError toRpcError(final NetconfDocumentedException ex) {
229 final StringBuilder infoBuilder = new StringBuilder();
230 final Map<String, String> errorInfo = ex.getErrorInfo();
231 if (errorInfo != null) {
232 for (final Entry<String, String> e : errorInfo.entrySet()) {
233 infoBuilder.append('<').append(e.getKey()).append('>').append(e.getValue())
234 .append("</").append(e.getKey()).append('>');
239 final ErrorSeverity severity = toRpcErrorSeverity(ex.getErrorSeverity());
240 return severity == ErrorSeverity.ERROR
241 ? RpcResultBuilder.newError(toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
242 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause())
243 : RpcResultBuilder.newWarning(
244 toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
245 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause());
248 private static ErrorSeverity toRpcErrorSeverity(final NetconfDocumentedException.ErrorSeverity severity) {
251 return RpcError.ErrorSeverity.WARNING;
253 return RpcError.ErrorSeverity.ERROR;
257 private static RpcError.ErrorType toRpcErrorType(final NetconfDocumentedException.ErrorType type) {
260 return RpcError.ErrorType.PROTOCOL;
262 return RpcError.ErrorType.RPC;
264 return RpcError.ErrorType.TRANSPORT;
266 return RpcError.ErrorType.APPLICATION;
270 public static NodeIdentifier toId(final PathArgument qname) {
271 return toId(qname.getNodeType());
274 public static NodeIdentifier toId(final QName nodeType) {
275 return new NodeIdentifier(nodeType);
278 public static Element getDataSubtree(final Document doc) {
279 return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
282 public static boolean isDataRetrievalOperation(final QName rpc) {
283 return NETCONF_URI.equals(rpc.getNamespace())
284 && (NETCONF_GET_CONFIG_QNAME.getLocalName().equals(rpc.getLocalName())
285 || NETCONF_GET_QNAME.getLocalName().equals(rpc.getLocalName()));
288 public static ContainerSchemaNode createSchemaForDataRead(final SchemaContext schemaContext) {
289 return new NodeContainerProxy(NETCONF_DATA_QNAME, schemaContext.getChildNodes());
292 public static ContainerSchemaNode createSchemaForNotification(final NotificationDefinition next) {
293 return new NodeContainerProxy(next.getQName(), next.getChildNodes(), next.getAvailableAugmentations());
296 public static ContainerNode wrap(final QName name, final DataContainerChild<?, ?>... node) {
297 return Builders.containerBuilder().withNodeIdentifier(toId(name)).withValue(ImmutableList.copyOf(node)).build();
300 public static AnyXmlNode createEditConfigAnyxml(
301 final SchemaContext ctx, final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
302 final Optional<NormalizedNode<?, ?>> lastChildOverride) {
303 final NormalizedNode<?, ?> configContent;
305 if (dataPath.isEmpty()) {
306 Preconditions.checkArgument(lastChildOverride.isPresent(),
307 "Data has to be present when creating structure for top level element");
308 Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild<?, ?>,
309 "Data has to be either container or a list node when creating structure for top level element, "
310 + "but was: %s", lastChildOverride.get());
311 configContent = lastChildOverride.get();
313 final Entry<QName, ModifyAction> modifyOperation = operation.isPresent()
314 ? new AbstractMap.SimpleEntry<>(NETCONF_OPERATION_QNAME, operation.get()) : null;
315 configContent = ImmutableNodes
316 .fromInstanceId(ctx, dataPath, lastChildOverride, Optional.fromNullable(modifyOperation));
319 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(),
320 Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
322 NetconfUtil.writeNormalizedNode(configContent, new DOMResult(element), SchemaPath.ROOT, ctx);
323 } catch (IOException | XMLStreamException e) {
324 throw new IllegalStateException("Unable to serialize edit config content element for path " + dataPath, e);
326 final DOMSource value = new DOMSource(element);
328 return Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_CONFIG_QNAME)).withValue(value).build();
331 public static DataContainerChild<?, ?> createEditConfigStructure(
332 final SchemaContext ctx, final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
333 final Optional<NormalizedNode<?, ?>> lastChildOverride) {
334 return Builders.choiceBuilder().withNodeIdentifier(toId(EditContent.QNAME))
335 .withChild(createEditConfigAnyxml(ctx, dataPath, operation, lastChildOverride)).build();
338 public static SchemaPath toPath(final QName rpc) {
339 return SchemaPath.create(true, rpc);
342 public static Map.Entry<Date, XmlElement> stripNotification(final NetconfMessage message) {
343 final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
344 final List<XmlElement> childElements = xmlElement.getChildElements();
345 Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format."
346 + "\nExpected 2 childElements, actual childElements size is %s", message, childElements.size());
348 final XmlElement eventTimeElement;
349 final XmlElement notificationElement;
351 if (childElements.get(0).getName().equals(EVENT_TIME)) {
352 eventTimeElement = childElements.get(0);
353 notificationElement = childElements.get(1);
354 } else if (childElements.get(1).getName().equals(EVENT_TIME)) {
355 eventTimeElement = childElements.get(1);
356 notificationElement = childElements.get(0);
358 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
362 return new AbstractMap.SimpleEntry<>(
363 NetconfNotification.RFC3339_DATE_PARSER.apply(eventTimeElement.getTextContent()),
364 notificationElement);
365 } catch (final DocumentedException e) {
366 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
367 } catch (final DateTimeParseException e) {
368 LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement,
369 NetconfNotification.UNKNOWN_EVENT_TIME, e);
370 return new AbstractMap.SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME, notificationElement);
374 public static DOMResult prepareDomResultForRpcRequest(final QName rpcQName, final MessageCounter counter) {
375 final Document document = XmlUtil.newDocument();
376 final Element rpcNS =
377 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
379 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
380 final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
381 rpcNS.appendChild(elementNS);
382 document.appendChild(rpcNS);
383 return new DOMResult(elementNS);
386 @SuppressWarnings("checkstyle:IllegalCatch")
387 public static void writeNormalizedRpc(final ContainerNode normalized, final DOMResult result,
388 final SchemaPath schemaPath,
389 final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
390 final XMLStreamWriter writer = NetconfUtil.XML_FACTORY.createXMLStreamWriter(result);
392 try (NormalizedNodeStreamWriter normalizedNodeStreamWriter =
393 XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, schemaPath)) {
394 try (SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
395 new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, schemaPath)) {
396 final Collection<DataContainerChild<?, ?>> value = normalized.getValue();
397 normalizedNodeWriter.write(value);
398 normalizedNodeWriter.flush();
404 } catch (final Exception e) {
405 LOG.warn("Unable to close resource properly", e);
410 public static RpcResult<NetconfMessage> toRpcResult(final FailedNetconfMessage message) {
411 return RpcResultBuilder.<NetconfMessage>failed()
414 new NetconfDocumentedException(
415 message.getException().getMessage(),
416 DocumentedException.ErrorType.APPLICATION,
417 DocumentedException.ErrorTag.MALFORMED_MESSAGE,
418 DocumentedException.ErrorSeverity.ERROR)))