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.YangInstanceIdentifier.NodeIdentifier;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
50 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
53 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
55 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XMLStreamNormalizedNodeStreamWriter;
56 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
57 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
58 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
59 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
60 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
62 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
63 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66 import org.w3c.dom.Document;
67 import org.w3c.dom.Element;
69 public class NetconfMessageTransformUtil {
71 private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformUtil.class);
73 public static final String MESSAGE_ID_PREFIX = "m";
74 public static final String MESSAGE_ID_ATTR = "message-id";
76 public static final QName CREATE_SUBSCRIPTION_RPC_QNAME = QName.create(CreateSubscriptionInput.QNAME, "create-subscription").intern();
77 private static final String SUBTREE = "subtree";
79 // Blank document used for creation of new DOM nodes
80 private static final Document BLANK_DOCUMENT = XmlUtil.newDocument();
81 public static final String EVENT_TIME = "eventTime";
83 private NetconfMessageTransformUtil() {}
85 public static final QName IETF_NETCONF_MONITORING = QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
86 public static final QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data").intern();
87 public static final QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema").intern();
88 public static final QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT = QName.create(IETF_NETCONF_MONITORING, "format").intern();
89 public static final QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION = QName.create(IETF_NETCONF_MONITORING, "location").intern();
90 public static final QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER = QName.create(IETF_NETCONF_MONITORING, "identifier").intern();
91 public static final QName IETF_NETCONF_MONITORING_SCHEMA_VERSION = QName.create(IETF_NETCONF_MONITORING, "version").intern();
92 public static final QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE = QName.create(IETF_NETCONF_MONITORING, "namespace").intern();
94 public static final QName IETF_NETCONF_NOTIFICATIONS = QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications").intern();
96 public static final QName NETCONF_QNAME = QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "netconf").intern();
97 public static final URI NETCONF_URI = NETCONF_QNAME.getNamespace();
99 public static final QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data").intern();
100 public static final QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply").intern();
101 public static final QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok").intern();
102 public static final QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option").intern();
103 public static final QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running").intern();
104 public static final QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source").intern();
105 public static final QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate").intern();
106 public static final QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target").intern();
107 public static final QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config").intern();
108 public static final QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit").intern();
109 public static final QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate").intern();
110 public static final QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config").intern();
111 public static final QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation").intern();
112 public static final QName NETCONF_DEFAULT_OPERATION_QNAME = QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
113 public static final QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config").intern();
114 public static final QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
115 public static final QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
116 public static final QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type").intern();
117 public static final QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter").intern();
118 public static final QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get").intern();
119 public static final QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc").intern();
121 public static final URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
122 .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
123 public static final String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
125 public static final URI NETCONF_CANDIDATE_URI = URI
126 .create("urn:ietf:params:netconf:capability:candidate:1.0");
128 public static final URI NETCONF_NOTIFICATONS_URI = URI
129 .create("urn:ietf:params:netconf:capability:notification:1.0");
131 public static final URI NETCONF_RUNNING_WRITABLE_URI = URI
132 .create("urn:ietf:params:netconf:capability:writable-running:1.0");
134 public static final QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock").intern();
135 public static final QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock").intern();
137 // Discard changes message
138 public static final ContainerNode DISCARD_CHANGES_RPC_CONTENT =
139 Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(NETCONF_DISCARD_CHANGES_QNAME)).build();
141 // Commit changes message
142 public static final ContainerNode COMMIT_RPC_CONTENT =
143 Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(NETCONF_COMMIT_QNAME)).build();
146 public static final ContainerNode GET_RPC_CONTENT =
147 Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(NETCONF_GET_QNAME)).build();
149 // Create-subscription changes message
150 public static final ContainerNode CREATE_SUBSCRIPTION_RPC_CONTENT =
151 Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(CREATE_SUBSCRIPTION_RPC_QNAME)).build();
153 public static final DataContainerChild<?, ?> EMPTY_FILTER;
156 final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder = Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
157 anyXmlBuilder.withAttributes(Collections.singletonMap(NETCONF_TYPE_QNAME, SUBTREE));
159 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(), Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
160 element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(), "subtree");
162 anyXmlBuilder.withValue(new DOMSource(element));
164 EMPTY_FILTER = anyXmlBuilder.build();
167 public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier, final SchemaContext ctx) {
168 final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder = Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
169 anyXmlBuilder.withAttributes(Collections.singletonMap(NETCONF_TYPE_QNAME, SUBTREE));
171 final NormalizedNode<?, ?> filterContent = ImmutableNodes.fromInstanceId(ctx, identifier);
173 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(), Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
174 element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(), "subtree");
177 NetconfUtil.writeNormalizedNode(filterContent, new DOMResult(element), SchemaPath.ROOT, ctx);
178 } catch (IOException | XMLStreamException e) {
179 throw new IllegalStateException("Unable to serialize filter element for path " + identifier, e);
181 anyXmlBuilder.withValue(new DOMSource(element));
183 return anyXmlBuilder.build();
186 public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
187 throws NetconfDocumentedException {
188 final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
189 final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
191 if(inputMsgId.equals(outputMsgId) == false) {
192 final Map<String,String> errorInfo = ImmutableMap.<String,String>builder()
193 .put( "actual-message-id", outputMsgId )
194 .put( "expected-message-id", inputMsgId )
197 throw new NetconfDocumentedException( "Response message contained unknown \"message-id\"",
198 null, NetconfDocumentedException.ErrorType.protocol,
199 NetconfDocumentedException.ErrorTag.bad_attribute,
200 NetconfDocumentedException.ErrorSeverity.error, errorInfo );
204 public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
205 if(NetconfMessageUtil.isErrorMessage(output)) {
206 throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
210 public static RpcError toRpcError( final NetconfDocumentedException ex ) {
211 final StringBuilder infoBuilder = new StringBuilder();
212 final Map<String, String> errorInfo = ex.getErrorInfo();
213 if(errorInfo != null) {
214 for( final Entry<String,String> e: errorInfo.entrySet() ) {
215 infoBuilder.append( '<' ).append( e.getKey() ).append( '>' ).append( e.getValue() )
216 .append( "</" ).append( e.getKey() ).append( '>' );
221 final ErrorSeverity severity = toRpcErrorSeverity( ex.getErrorSeverity() );
222 return severity == ErrorSeverity.ERROR ?
223 RpcResultBuilder.newError(
224 toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
225 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() ) :
226 RpcResultBuilder.newWarning(
227 toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
228 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() );
231 private static ErrorSeverity toRpcErrorSeverity( final NetconfDocumentedException.ErrorSeverity severity ) {
234 return RpcError.ErrorSeverity.WARNING;
236 return RpcError.ErrorSeverity.ERROR;
240 private static RpcError.ErrorType toRpcErrorType(final NetconfDocumentedException.ErrorType type) {
243 return RpcError.ErrorType.PROTOCOL;
245 return RpcError.ErrorType.RPC;
247 return RpcError.ErrorType.TRANSPORT;
249 return RpcError.ErrorType.APPLICATION;
253 public static NodeIdentifier toId(final PathArgument qname) {
254 return toId(qname.getNodeType());
257 public static NodeIdentifier toId(final QName nodeType) {
258 return new NodeIdentifier(nodeType);
261 public static Element getDataSubtree(final Document doc) {
262 return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
265 public static boolean isDataRetrievalOperation(final QName rpc) {
266 return NETCONF_URI.equals(rpc.getNamespace())
267 && (NETCONF_GET_CONFIG_QNAME.getLocalName().equals(rpc.getLocalName())
268 || NETCONF_GET_QNAME.getLocalName().equals(rpc.getLocalName()));
271 public static ContainerSchemaNode createSchemaForDataRead(final SchemaContext schemaContext) {
272 return new NodeContainerProxy(NETCONF_DATA_QNAME, schemaContext.getChildNodes());
275 public static ContainerSchemaNode createSchemaForNotification(final NotificationDefinition next) {
276 return new NodeContainerProxy(next.getQName(), next.getChildNodes(), next.getAvailableAugmentations());
279 public static ContainerNode wrap(final QName name, final DataContainerChild<?, ?>... node) {
280 return Builders.containerBuilder().withNodeIdentifier(toId(name)).withValue(ImmutableList.copyOf(node)).build();
283 public static AnyXmlNode createEditConfigAnyxml(final SchemaContext ctx, final YangInstanceIdentifier dataPath,
284 final Optional<ModifyAction> operation, final Optional<NormalizedNode<?, ?>> lastChildOverride) {
285 final NormalizedNode<?, ?> configContent;
287 if (dataPath.isEmpty()) {
288 Preconditions.checkArgument(lastChildOverride.isPresent(), "Data has to be present when creating structure for top level element");
289 Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild<?, ?>,
290 "Data has to be either container or a list node when creating structure for top level element, but was: %s", lastChildOverride.get());
291 configContent = lastChildOverride.get();
293 final Entry<QName, ModifyAction> modifyOperation =
294 operation.isPresent() ? new AbstractMap.SimpleEntry<>(NETCONF_OPERATION_QNAME, operation.get()) : null;
295 configContent = ImmutableNodes.fromInstanceId(ctx, dataPath, lastChildOverride, Optional.fromNullable(modifyOperation));
298 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(), Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
300 NetconfUtil.writeNormalizedNode(configContent, new DOMResult(element), SchemaPath.ROOT, ctx);
301 } catch (IOException | XMLStreamException e) {
302 throw new IllegalStateException("Unable to serialize edit config content element for path " + dataPath, e);
304 final DOMSource value = new DOMSource(element);
306 return Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_CONFIG_QNAME)).withValue(value).build();
309 public static DataContainerChild<?, ?> createEditConfigStructure(final SchemaContext ctx, final YangInstanceIdentifier dataPath,
310 final Optional<ModifyAction> operation, final Optional<NormalizedNode<?, ?>> lastChildOverride) {
311 return Builders.choiceBuilder().withNodeIdentifier(toId(EditContent.QNAME))
312 .withChild(createEditConfigAnyxml(ctx, dataPath, operation, lastChildOverride)).build();
315 public static SchemaPath toPath(final QName rpc) {
316 return SchemaPath.create(true, rpc);
319 private static final ThreadLocal<SimpleDateFormat> EVENT_TIME_FORMAT = new ThreadLocal<SimpleDateFormat>() {
321 protected SimpleDateFormat initialValue() {
323 final SimpleDateFormat withMillis = new SimpleDateFormat(
324 NetconfNotification.RFC3339_DATE_FORMAT_WITH_MILLIS_BLUEPRINT);
326 return new SimpleDateFormat(NetconfNotification.RFC3339_DATE_FORMAT_BLUEPRINT) {
327 private static final long serialVersionUID = 1L;
329 @Override public Date parse(final String source) throws ParseException {
331 return super.parse(source);
332 } catch (ParseException e) {
333 // In case of failure, try to parse with milliseconds
334 return withMillis.parse(source);
341 public void set(final SimpleDateFormat value) {
342 throw new UnsupportedOperationException();
346 public static Map.Entry<Date, XmlElement> stripNotification(final NetconfMessage message) {
347 final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
348 final List<XmlElement> childElements = xmlElement.getChildElements();
349 Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format.\nExpected 2 childElements," +
350 " actual childElements size is %s", message, childElements.size());
352 final XmlElement eventTimeElement;
353 final XmlElement notificationElement;
355 if (childElements.get(0).getName().equals(EVENT_TIME)) {
356 eventTimeElement = childElements.get(0);
357 notificationElement = childElements.get(1);
359 else if(childElements.get(1).getName().equals(EVENT_TIME)) {
360 eventTimeElement = childElements.get(1);
361 notificationElement = childElements.get(0);
363 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
367 return new AbstractMap.SimpleEntry<>(EVENT_TIME_FORMAT.get().parse(eventTimeElement.getTextContent()), notificationElement);
368 } catch (DocumentedException e) {
369 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
370 } catch (ParseException e) {
371 LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement, NetconfNotification.UNKNOWN_EVENT_TIME, e);
372 return new AbstractMap.SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME, notificationElement);
376 public static DOMResult prepareDomResultForRpcRequest(final QName rpcQName, final MessageCounter counter) {
377 final Document document = XmlUtil.newDocument();
378 final Element rpcNS =
379 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
381 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
382 final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
383 rpcNS.appendChild(elementNS);
384 document.appendChild(rpcNS);
385 return new DOMResult(elementNS);
388 public static void writeNormalizedRpc(final ContainerNode normalized, final DOMResult result,
389 final SchemaPath schemaPath, final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
390 final XMLStreamWriter writer = NetconfUtil.XML_FACTORY.createXMLStreamWriter(result);
392 try (final NormalizedNodeStreamWriter normalizedNodeStreamWriter =
393 XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, schemaPath)) {
394 try (final SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
395 new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, schemaPath)) {
396 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);