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.text.ParseException;
17 import java.text.SimpleDateFormat;
18 import java.util.AbstractMap;
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.Date;
22 import java.util.List;
24 import java.util.Map.Entry;
25 import javax.xml.stream.XMLStreamException;
26 import javax.xml.stream.XMLStreamWriter;
27 import javax.xml.transform.dom.DOMResult;
28 import javax.xml.transform.dom.DOMSource;
29 import org.opendaylight.controller.config.util.xml.DocumentedException;
30 import org.opendaylight.controller.config.util.xml.XmlElement;
31 import org.opendaylight.controller.config.util.xml.XmlUtil;
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.RpcResultBuilder;
46 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
51 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
53 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XMLStreamNormalizedNodeStreamWriter;
54 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
55 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
56 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
57 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
58 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
60 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
61 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64 import org.w3c.dom.Document;
65 import org.w3c.dom.Element;
67 public class NetconfMessageTransformUtil {
69 private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformUtil.class);
71 public static final String MESSAGE_ID_PREFIX = "m";
72 public static final String MESSAGE_ID_ATTR = "message-id";
74 public static final QName CREATE_SUBSCRIPTION_RPC_QNAME = QName.cachedReference(QName.create(CreateSubscriptionInput.QNAME, "create-subscription"));
75 private static final String SUBTREE = "subtree";
77 // Blank document used for creation of new DOM nodes
78 private static final Document BLANK_DOCUMENT = XmlUtil.newDocument();
79 public static final String EVENT_TIME = "eventTime";
81 private NetconfMessageTransformUtil() {}
83 public static final QName IETF_NETCONF_MONITORING = QName.create(NetconfState.QNAME, "ietf-netconf-monitoring");
84 public static final QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data");
85 public static final QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema");
86 public static final QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT = QName.create(IETF_NETCONF_MONITORING, "format");
87 public static final QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION = QName.create(IETF_NETCONF_MONITORING, "location");
88 public static final QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER = QName.create(IETF_NETCONF_MONITORING, "identifier");
89 public static final QName IETF_NETCONF_MONITORING_SCHEMA_VERSION = QName.create(IETF_NETCONF_MONITORING, "version");
90 public static final QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE = QName.create(IETF_NETCONF_MONITORING, "namespace");
92 public static final QName IETF_NETCONF_NOTIFICATIONS = QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications");
94 public static final QName NETCONF_QNAME = QName.cachedReference(QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "netconf"));
95 public static final URI NETCONF_URI = NETCONF_QNAME.getNamespace();
97 public static final QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data");
98 public static final QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply");
99 public static final QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok");
100 public static final QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option");
101 public static final QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running");
102 public static final QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source");
103 public static final QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate");
104 public static final QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target");
105 public static final QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config");
106 public static final QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit");
107 public static final QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate");
108 public static final QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config");
109 public static final QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation");
110 public static final QName NETCONF_DEFAULT_OPERATION_QNAME = QName.create(NETCONF_OPERATION_QNAME, "default-operation");
111 public static final QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config");
112 public static final QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
113 public static final QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
114 public static final QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type");
115 public static final QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter");
116 public static final QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get");
117 public static final QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc");
119 public static final URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
120 .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
121 public static final String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
123 public static final URI NETCONF_CANDIDATE_URI = URI
124 .create("urn:ietf:params:netconf:capability:candidate:1.0");
126 public static final URI NETCONF_NOTIFICATONS_URI = URI
127 .create("urn:ietf:params:netconf:capability:notification:1.0");
129 public static final URI NETCONF_RUNNING_WRITABLE_URI = URI
130 .create("urn:ietf:params:netconf:capability:writable-running:1.0");
132 public static final QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock");
133 public static final QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock");
135 // Discard changes message
136 public static final ContainerNode DISCARD_CHANGES_RPC_CONTENT =
137 Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NETCONF_DISCARD_CHANGES_QNAME)).build();
139 // Commit changes message
140 public static final ContainerNode COMMIT_RPC_CONTENT =
141 Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NETCONF_COMMIT_QNAME)).build();
144 public static final ContainerNode GET_RPC_CONTENT =
145 Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NETCONF_GET_QNAME)).build();
147 // Create-subscription changes message
148 public static final ContainerNode CREATE_SUBSCRIPTION_RPC_CONTENT =
149 Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CREATE_SUBSCRIPTION_RPC_QNAME)).build();
151 public static final DataContainerChild<?, ?> EMPTY_FILTER;
154 final NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder = Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
155 anyXmlBuilder.withAttributes(Collections.singletonMap(NETCONF_TYPE_QNAME, SUBTREE));
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");
160 anyXmlBuilder.withValue(new DOMSource(element));
162 EMPTY_FILTER = anyXmlBuilder.build();
165 public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier, final SchemaContext ctx) {
166 final NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder = Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
167 anyXmlBuilder.withAttributes(Collections.singletonMap(NETCONF_TYPE_QNAME, SUBTREE));
169 final NormalizedNode<?, ?> filterContent = ImmutableNodes.fromInstanceId(ctx, identifier);
171 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(), Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
172 element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(), "subtree");
175 NetconfUtil.writeNormalizedNode(filterContent, new DOMResult(element), SchemaPath.ROOT, ctx);
176 } catch (IOException | XMLStreamException e) {
177 throw new IllegalStateException("Unable to serialize filter element for path " + identifier, e);
179 anyXmlBuilder.withValue(new DOMSource(element));
181 return anyXmlBuilder.build();
184 public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
185 throws NetconfDocumentedException {
186 final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
187 final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
189 if(inputMsgId.equals(outputMsgId) == false) {
190 final Map<String,String> errorInfo = ImmutableMap.<String,String>builder()
191 .put( "actual-message-id", outputMsgId )
192 .put( "expected-message-id", inputMsgId )
195 throw new NetconfDocumentedException( "Response message contained unknown \"message-id\"",
196 null, NetconfDocumentedException.ErrorType.protocol,
197 NetconfDocumentedException.ErrorTag.bad_attribute,
198 NetconfDocumentedException.ErrorSeverity.error, errorInfo );
202 public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
203 if(NetconfMessageUtil.isErrorMessage(output)) {
204 throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
208 public static RpcError toRpcError( final NetconfDocumentedException ex ) {
209 final StringBuilder infoBuilder = new StringBuilder();
210 final Map<String, String> errorInfo = ex.getErrorInfo();
211 if(errorInfo != null) {
212 for( final Entry<String,String> e: errorInfo.entrySet() ) {
213 infoBuilder.append( '<' ).append( e.getKey() ).append( '>' ).append( e.getValue() )
214 .append( "</" ).append( e.getKey() ).append( '>' );
219 final ErrorSeverity severity = toRpcErrorSeverity( ex.getErrorSeverity() );
220 return severity == ErrorSeverity.ERROR ?
221 RpcResultBuilder.newError(
222 toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
223 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() ) :
224 RpcResultBuilder.newWarning(
225 toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
226 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() );
229 private static ErrorSeverity toRpcErrorSeverity( final NetconfDocumentedException.ErrorSeverity severity ) {
232 return RpcError.ErrorSeverity.WARNING;
234 return RpcError.ErrorSeverity.ERROR;
238 private static RpcError.ErrorType toRpcErrorType(final NetconfDocumentedException.ErrorType type) {
241 return RpcError.ErrorType.PROTOCOL;
243 return RpcError.ErrorType.RPC;
245 return RpcError.ErrorType.TRANSPORT;
247 return RpcError.ErrorType.APPLICATION;
251 public static YangInstanceIdentifier.NodeIdentifier toId(final YangInstanceIdentifier.PathArgument qname) {
252 return toId(qname.getNodeType());
255 public static YangInstanceIdentifier.NodeIdentifier toId(final QName nodeType) {
256 return new YangInstanceIdentifier.NodeIdentifier(nodeType);
259 public static Element getDataSubtree(final Document doc) {
260 return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
263 public static boolean isDataRetrievalOperation(final QName rpc) {
264 return NETCONF_URI.equals(rpc.getNamespace())
265 && (NETCONF_GET_CONFIG_QNAME.getLocalName().equals(rpc.getLocalName())
266 || NETCONF_GET_QNAME.getLocalName().equals(rpc.getLocalName()));
269 public static ContainerSchemaNode createSchemaForDataRead(final SchemaContext schemaContext) {
270 return new NodeContainerProxy(NETCONF_DATA_QNAME, schemaContext.getChildNodes());
273 public static ContainerSchemaNode createSchemaForNotification(final NotificationDefinition next) {
274 return new NodeContainerProxy(next.getQName(), next.getChildNodes(), next.getAvailableAugmentations());
277 public static ContainerNode wrap(final QName name, final DataContainerChild<?, ?>... node) {
278 return Builders.containerBuilder().withNodeIdentifier(toId(name)).withValue(ImmutableList.copyOf(node)).build();
281 public static AnyXmlNode createEditConfigAnyxml(final SchemaContext ctx, final YangInstanceIdentifier dataPath,
282 final Optional<ModifyAction> operation, final Optional<NormalizedNode<?, ?>> lastChildOverride) {
283 final NormalizedNode<?, ?> configContent;
285 if (dataPath.isEmpty()) {
286 Preconditions.checkArgument(lastChildOverride.isPresent(), "Data has to be present when creating structure for top level element");
287 Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild<?, ?>,
288 "Data has to be either container or a list node when creating structure for top level element, but was: %s", lastChildOverride.get());
289 configContent = lastChildOverride.get();
291 final Entry<QName, ModifyAction> modifyOperation =
292 operation.isPresent() ? new AbstractMap.SimpleEntry<>(NETCONF_OPERATION_QNAME, operation.get()) : null;
293 configContent = ImmutableNodes.fromInstanceId(ctx, dataPath, lastChildOverride, Optional.fromNullable(modifyOperation));
296 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(), Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
298 NetconfUtil.writeNormalizedNode(configContent, new DOMResult(element), SchemaPath.ROOT, ctx);
299 } catch (IOException | XMLStreamException e) {
300 throw new IllegalStateException("Unable to serialize edit config content element for path " + dataPath, e);
302 final DOMSource value = new DOMSource(element);
304 return Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_CONFIG_QNAME)).withValue(value).build();
307 public static DataContainerChild<?, ?> createEditConfigStructure(final SchemaContext ctx, final YangInstanceIdentifier dataPath,
308 final Optional<ModifyAction> operation, final Optional<NormalizedNode<?, ?>> lastChildOverride) {
309 return Builders.choiceBuilder().withNodeIdentifier(toId(EditContent.QNAME))
310 .withChild(createEditConfigAnyxml(ctx, dataPath, operation, lastChildOverride)).build();
313 public static SchemaPath toPath(final QName rpc) {
314 return SchemaPath.create(true, rpc);
317 private static final ThreadLocal<SimpleDateFormat> EVENT_TIME_FORMAT = new ThreadLocal<SimpleDateFormat>() {
319 protected SimpleDateFormat initialValue() {
321 final SimpleDateFormat withMillis = new SimpleDateFormat(
322 NetconfNotification.RFC3339_DATE_FORMAT_WITH_MILLIS_BLUEPRINT);
324 return new SimpleDateFormat(NetconfNotification.RFC3339_DATE_FORMAT_BLUEPRINT) {
325 private static final long serialVersionUID = 1L;
327 @Override public Date parse(final String source) throws ParseException {
329 return super.parse(source);
330 } catch (ParseException e) {
331 // In case of failure, try to parse with milliseconds
332 return withMillis.parse(source);
339 public void set(final SimpleDateFormat value) {
340 throw new UnsupportedOperationException();
344 public static Map.Entry<Date, XmlElement> stripNotification(final NetconfMessage message) {
345 final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
346 final List<XmlElement> childElements = xmlElement.getChildElements();
347 Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format.\nExpected 2 childElements," +
348 " actual childElements size is %s", message, childElements.size());
350 final XmlElement eventTimeElement;
351 final XmlElement notificationElement;
353 if (childElements.get(0).getName().equals(EVENT_TIME)) {
354 eventTimeElement = childElements.get(0);
355 notificationElement = childElements.get(1);
357 else if(childElements.get(1).getName().equals(EVENT_TIME)) {
358 eventTimeElement = childElements.get(1);
359 notificationElement = childElements.get(0);
361 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
365 return new AbstractMap.SimpleEntry<>(EVENT_TIME_FORMAT.get().parse(eventTimeElement.getTextContent()), notificationElement);
366 } catch (DocumentedException e) {
367 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
368 } catch (ParseException e) {
369 LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement, 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 public static void writeNormalizedRpc(final ContainerNode normalized, final DOMResult result,
387 final SchemaPath schemaPath, final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
388 final XMLStreamWriter writer = NetconfUtil.XML_FACTORY.createXMLStreamWriter(result);
390 try (final NormalizedNodeStreamWriter normalizedNodeStreamWriter =
391 XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, schemaPath)) {
392 try (final SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
393 new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, schemaPath)) {
394 Collection<DataContainerChild<?, ?>> value = normalized.getValue();
395 normalizedNodeWriter.write(value);
396 normalizedNodeWriter.flush();
402 } catch (final Exception e) {
403 LOG.warn("Unable to close resource properly", e);