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.schema.mapping;
10 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.EVENT_TIME;
11 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.IETF_NETCONF_NOTIFICATIONS;
12 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_RPC_QNAME;
13 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_URI;
14 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath;
16 import com.google.common.base.Function;
17 import com.google.common.base.Preconditions;
18 import com.google.common.collect.Lists;
19 import com.google.common.collect.Maps;
20 import com.google.common.collect.Multimap;
21 import com.google.common.collect.Multimaps;
22 import java.io.IOException;
23 import java.text.ParseException;
24 import java.text.SimpleDateFormat;
25 import java.util.AbstractMap;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.Date;
29 import java.util.List;
31 import javax.annotation.Nonnull;
32 import javax.xml.stream.XMLStreamException;
33 import javax.xml.stream.XMLStreamWriter;
34 import javax.xml.transform.dom.DOMResult;
35 import org.opendaylight.controller.config.util.xml.DocumentedException;
36 import org.opendaylight.controller.config.util.xml.MissingNameSpaceException;
37 import org.opendaylight.controller.config.util.xml.XmlElement;
38 import org.opendaylight.controller.config.util.xml.XmlUtil;
39 import org.opendaylight.controller.md.sal.dom.api.DOMEvent;
40 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
41 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
42 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
43 import org.opendaylight.netconf.api.NetconfMessage;
44 import org.opendaylight.netconf.notifications.NetconfNotification;
45 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
46 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
47 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
48 import org.opendaylight.netconf.util.NetconfUtil;
49 import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
50 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
51 import org.opendaylight.yangtools.yang.common.QName;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
53 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
55 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
57 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XMLStreamNormalizedNodeStreamWriter;
58 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
59 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
60 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
61 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
62 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
64 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
65 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
66 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70 import org.w3c.dom.Document;
71 import org.w3c.dom.Element;
73 public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
75 public enum BaseSchema {
79 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance(),
80 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.extension.rev131210.$YangModuleInfoImpl.getInstance()
83 BASE_NETCONF_CTX_WITH_NOTIFICATIONS(
85 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.extension.rev131210.$YangModuleInfoImpl.getInstance(),
86 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.$YangModuleInfoImpl.getInstance(),
87 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance(),
88 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.$YangModuleInfoImpl.getInstance()
92 private final Map<QName, RpcDefinition> mappedRpcs;
93 private final SchemaContext schemaContext;
95 BaseSchema(List<YangModuleInfo> modules) {
97 final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
98 moduleInfoBackedContext.addModuleInfos(modules);
99 schemaContext = moduleInfoBackedContext.tryToCreateSchemaContext().get();
100 mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), QNAME_FUNCTION);
101 } catch (final RuntimeException e) {
102 LOG.error("Unable to prepare schema context for base netconf ops", e);
103 throw new ExceptionInInitializerError(e);
107 private Map<QName, RpcDefinition> getMappedRpcs() {
111 public SchemaContext getSchemaContext() {
112 return schemaContext;
116 public static final String MESSAGE_ID_PREFIX = "m";
118 private static final Logger LOG= LoggerFactory.getLogger(NetconfMessageTransformer.class);
121 private static final Function<SchemaNode, QName> QNAME_FUNCTION = new Function<SchemaNode, QName>() {
123 public QName apply(final SchemaNode rpcDefinition) {
124 return rpcDefinition.getQName();
128 private static final Function<SchemaNode, QName> QNAME_NOREV_FUNCTION = new Function<SchemaNode, QName>() {
130 public QName apply(final SchemaNode notification) {
131 return QNAME_FUNCTION.apply(notification).withoutRevision();
135 private final SchemaContext schemaContext;
136 private final BaseSchema baseSchema;
137 private final MessageCounter counter;
138 private final Map<QName, RpcDefinition> mappedRpcs;
139 private final Multimap<QName, NotificationDefinition> mappedNotifications;
140 private final DomToNormalizedNodeParserFactory parserFactory;
142 public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing) {
143 this(schemaContext, strictParsing, BaseSchema.BASE_NETCONF_CTX);
146 public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing, final BaseSchema baseSchema) {
147 this.counter = new MessageCounter();
148 this.schemaContext = schemaContext;
149 parserFactory = DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext, strictParsing);
150 mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), QNAME_FUNCTION);
151 mappedNotifications = Multimaps.index(schemaContext.getNotifications(), QNAME_NOREV_FUNCTION);
152 this.baseSchema = baseSchema;
156 public synchronized DOMNotification toNotification(final NetconfMessage message) {
157 final Map.Entry<Date, XmlElement> stripped = stripNotification(message);
158 final QName notificationNoRev;
160 notificationNoRev = QName.create(stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
161 } catch (final MissingNameSpaceException e) {
162 throw new IllegalArgumentException("Unable to parse notification " + message + ", cannot find namespace", e);
165 final Collection<NotificationDefinition> notificationDefinitions = mappedNotifications.get(notificationNoRev);
166 Preconditions.checkArgument(notificationDefinitions.size() > 0,
167 "Unable to parse notification %s, unknown notification. Available notifications: %s", notificationDefinitions, mappedNotifications.keySet());
169 // FIXME if multiple revisions for same notifications are present, we should pick the most recent. Or ?
170 // We should probably just put the most recent notification versions into our map. We can expect that the device sends the data according to the latest available revision of a model.
171 final NotificationDefinition next = notificationDefinitions.iterator().next();
173 // We wrap the notification as a container node in order to reuse the parsers and builders for container node
174 final ContainerSchemaNode notificationAsContainerSchemaNode = NetconfMessageTransformUtil.createSchemaForNotification(next);
176 final Element element = stripped.getValue().getDomElement();
177 final ContainerNode content;
179 content = parserFactory.getContainerNodeParser().parse(Collections.singleton(element),
180 notificationAsContainerSchemaNode);
181 } catch (IllegalArgumentException e) {
182 throw new IllegalArgumentException(String.format("Failed to parse notification %s", element), e);
184 return new NetconfDeviceNotification(content, stripped.getKey());
187 private static final ThreadLocal<SimpleDateFormat> EVENT_TIME_FORMAT = new ThreadLocal<SimpleDateFormat>() {
189 protected SimpleDateFormat initialValue() {
191 final SimpleDateFormat withMillis = new SimpleDateFormat(
192 NetconfNotification.RFC3339_DATE_FORMAT_WITH_MILLIS_BLUEPRINT);
194 return new SimpleDateFormat(NetconfNotification.RFC3339_DATE_FORMAT_BLUEPRINT) {
195 private static final long serialVersionUID = 1L;
197 @Override public Date parse(final String source) throws ParseException {
199 return super.parse(source);
200 } catch (ParseException e) {
201 // In case of failure, try to parse with milliseconds
202 return withMillis.parse(source);
209 public void set(final SimpleDateFormat value) {
210 throw new UnsupportedOperationException();
214 // FIXME move somewhere to util
215 private static Map.Entry<Date, XmlElement> stripNotification(final NetconfMessage message) {
216 final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
217 final List<XmlElement> childElements = xmlElement.getChildElements();
218 Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format", message);
220 final XmlElement eventTimeElement;
221 final XmlElement notificationElement;
223 if (childElements.get(0).getName().equals(EVENT_TIME)) {
224 eventTimeElement = childElements.get(0);
225 notificationElement = childElements.get(1);
227 else if(childElements.get(1).getName().equals(EVENT_TIME)) {
228 eventTimeElement = childElements.get(1);
229 notificationElement = childElements.get(0);
231 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
235 return new AbstractMap.SimpleEntry<>(EVENT_TIME_FORMAT.get().parse(eventTimeElement.getTextContent()), notificationElement);
236 } catch (DocumentedException e) {
237 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
238 } catch (ParseException e) {
239 LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement, NetconfNotification.UNKNOWN_EVENT_TIME, e);
240 return new AbstractMap.SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME, notificationElement);
245 public NetconfMessage toRpcRequest(SchemaPath rpc, final NormalizedNode<?, ?> payload) {
246 // In case no input for rpc is defined, we can simply construct the payload here
247 final QName rpcQName = rpc.getLastComponent();
248 Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
250 // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
251 // If no, use pre built base netconf operations model
252 final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
253 if(needToUseBaseCtx) {
254 currentMappedRpcs = baseSchema.getMappedRpcs();
257 Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName), "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
258 if(currentMappedRpcs.get(rpcQName).getInput() == null) {
259 return new NetconfMessage(prepareDomResultForRpcRequest(rpcQName).getNode().getOwnerDocument());
262 Preconditions.checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpcQName);
263 Preconditions.checkArgument(payload instanceof ContainerNode,
264 "Transforming an rpc with input: %s, payload has to be a container, but was: %s", rpcQName, payload);
266 // Set the path to the input of rpc for the node stream writer
267 rpc = rpc.createChild(QName.create(rpcQName, "input").intern());
268 final DOMResult result = prepareDomResultForRpcRequest(rpcQName);
271 // If the schema context for netconf device does not contain model for base netconf operations, use default pre build context with just the base model
272 // This way operations like lock/unlock are supported even if the source for base model was not provided
273 SchemaContext ctx = needToUseBaseCtx ? baseSchema.getSchemaContext() : schemaContext;
274 writeNormalizedRpc(((ContainerNode) payload), result, rpc, ctx);
275 } catch (final XMLStreamException | IOException | IllegalStateException e) {
276 throw new IllegalStateException("Unable to serialize " + rpc, e);
279 final Document node = result.getNode().getOwnerDocument();
281 return new NetconfMessage(node);
284 private boolean isBaseOrNotificationRpc(final QName rpc) {
285 return rpc.getNamespace().equals(NETCONF_URI) ||
286 rpc.getNamespace().equals(IETF_NETCONF_NOTIFICATIONS.getNamespace()) ||
287 rpc.getNamespace().equals(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
290 private DOMResult prepareDomResultForRpcRequest(final QName rpcQName) {
291 final Document document = XmlUtil.newDocument();
292 final Element rpcNS = document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
294 rpcNS.setAttribute(NetconfMessageTransformUtil.MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
295 final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
296 rpcNS.appendChild(elementNS);
297 document.appendChild(rpcNS);
298 return new DOMResult(elementNS);
301 private static void writeNormalizedRpc(final ContainerNode normalized, final DOMResult result,
302 final SchemaPath schemaPath, final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
303 final XMLStreamWriter writer = NetconfUtil.XML_FACTORY.createXMLStreamWriter(result);
305 try (final NormalizedNodeStreamWriter normalizedNodeStreamWriter =
306 XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, schemaPath)) {
307 try (final SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
308 new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, schemaPath)) {
309 Collection<DataContainerChild<?, ?>> value = normalized.getValue();
310 normalizedNodeWriter.write(value);
311 normalizedNodeWriter.flush();
317 } catch (final Exception e) {
318 LOG.warn("Unable to close resource properly", e);
324 public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
325 final NormalizedNode<?, ?> normalizedNode;
326 final QName rpcQName = rpc.getLastComponent();
327 if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
328 final Element xmlData = NetconfMessageTransformUtil.getDataSubtree(message.getDocument());
329 final ContainerSchemaNode schemaForDataRead = NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
330 final ContainerNode dataNode;
333 dataNode = parserFactory.getContainerNodeParser().parse(Collections.singleton(xmlData), schemaForDataRead);
334 } catch (IllegalArgumentException e) {
335 throw new IllegalArgumentException(String.format("Failed to parse data response %s", xmlData), e);
338 normalizedNode = Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
339 .withChild(dataNode).build();
342 Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
344 // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
345 // If no, use pre built base netconf operations model
346 final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
347 if(needToUseBaseCtx) {
348 currentMappedRpcs = baseSchema.getMappedRpcs();
351 final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
352 Preconditions.checkArgument(rpcDefinition != null, "Unable to parse response of %s, the rpc is unknown", rpcQName);
354 // In case no input for rpc is defined, we can simply construct the payload here
355 if (rpcDefinition.getOutput() == null) {
356 Preconditions.checkArgument(XmlElement.fromDomDocument(
357 message.getDocument()).getOnlyChildElementWithSameNamespaceOptionally("ok").isPresent(),
358 "Unexpected content in response of rpc: %s, %s", rpcDefinition.getQName(), message);
359 normalizedNode = null;
361 final Element element = message.getDocument().getDocumentElement();
363 normalizedNode = parserFactory.getContainerNodeParser().parse(Collections.singleton(element),
364 rpcDefinition.getOutput());
365 } catch (IllegalArgumentException e) {
366 throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
370 return new DefaultDOMRpcResult(normalizedNode);
373 private static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
374 private final ContainerNode content;
375 private final SchemaPath schemaPath;
376 private final Date eventTime;
378 NetconfDeviceNotification(final ContainerNode content, final Date eventTime) {
379 this.content = content;
380 this.eventTime = eventTime;
381 this.schemaPath = toPath(content.getNodeType());
386 public SchemaPath getType() {
393 public ContainerNode getBody() {
398 public Date getEventTime() {