Merge "Add NetconfDevice builder class"
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / sal / connect / netconf / schema / mapping / NetconfMessageTransformer.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.netconf.sal.connect.netconf.schema.mapping;
9
10 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.IETF_NETCONF_NOTIFICATIONS;
11 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_RPC_QNAME;
12 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_URI;
13 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath;
14
15 import com.google.common.base.Function;
16 import com.google.common.base.Preconditions;
17 import com.google.common.collect.Lists;
18 import com.google.common.collect.Maps;
19 import com.google.common.collect.Multimap;
20 import com.google.common.collect.Multimaps;
21 import java.io.IOException;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.Comparator;
25 import java.util.Date;
26 import java.util.List;
27 import java.util.Map;
28 import javax.annotation.Nonnull;
29 import javax.xml.stream.XMLStreamException;
30 import javax.xml.stream.XMLStreamWriter;
31 import javax.xml.transform.dom.DOMResult;
32 import org.opendaylight.controller.config.util.xml.MissingNameSpaceException;
33 import org.opendaylight.controller.config.util.xml.XmlElement;
34 import org.opendaylight.controller.config.util.xml.XmlUtil;
35 import org.opendaylight.controller.md.sal.dom.api.DOMEvent;
36 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
37 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
38 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
39 import org.opendaylight.netconf.api.NetconfMessage;
40 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
41 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
42 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
43 import org.opendaylight.netconf.util.NetconfUtil;
44 import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
45 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
46 import org.opendaylight.yangtools.yang.common.QName;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
50 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
52 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XMLStreamNormalizedNodeStreamWriter;
53 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
54 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
55 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
56 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
57 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
59 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
60 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
61 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65 import org.w3c.dom.Document;
66 import org.w3c.dom.Element;
67
68 public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
69
70     public enum BaseSchema {
71
72         BASE_NETCONF_CTX(
73                 Lists.newArrayList(
74                         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance(),
75                         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.extension.rev131210.$YangModuleInfoImpl.getInstance()
76                 )
77         ),
78         BASE_NETCONF_CTX_WITH_NOTIFICATIONS(
79                 Lists.newArrayList(
80                         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.extension.rev131210.$YangModuleInfoImpl.getInstance(),
81                         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.$YangModuleInfoImpl.getInstance(),
82                         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance(),
83                         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.$YangModuleInfoImpl.getInstance()
84                 )
85         );
86
87         private final Map<QName, RpcDefinition> mappedRpcs;
88         private final SchemaContext schemaContext;
89
90         BaseSchema(List<YangModuleInfo> modules) {
91             try {
92                 final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
93                 moduleInfoBackedContext.addModuleInfos(modules);
94                 schemaContext = moduleInfoBackedContext.tryToCreateSchemaContext().get();
95                 mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), QNAME_FUNCTION);
96             } catch (final RuntimeException e) {
97                 LOG.error("Unable to prepare schema context for base netconf ops", e);
98                 throw new ExceptionInInitializerError(e);
99             }
100         }
101
102         private Map<QName, RpcDefinition> getMappedRpcs() {
103             return mappedRpcs;
104         }
105
106         public SchemaContext getSchemaContext() {
107             return schemaContext;
108         }
109     }
110
111     public static final String MESSAGE_ID_PREFIX = "m";
112
113     private static final Logger LOG= LoggerFactory.getLogger(NetconfMessageTransformer.class);
114
115
116     private static final Function<SchemaNode, QName> QNAME_FUNCTION = new Function<SchemaNode, QName>() {
117         @Override
118         public QName apply(final SchemaNode rpcDefinition) {
119             return rpcDefinition.getQName();
120         }
121     };
122
123     private static final Function<SchemaNode, QName> QNAME_NOREV_FUNCTION = new Function<SchemaNode, QName>() {
124         @Override
125         public QName apply(final SchemaNode notification) {
126             return QNAME_FUNCTION.apply(notification).withoutRevision();
127         }
128     };
129
130     private final SchemaContext schemaContext;
131     private final BaseSchema baseSchema;
132     private final MessageCounter counter;
133     private final Map<QName, RpcDefinition> mappedRpcs;
134     private final Multimap<QName, NotificationDefinition> mappedNotifications;
135     private final DomToNormalizedNodeParserFactory parserFactory;
136
137     public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing) {
138         this(schemaContext, strictParsing, BaseSchema.BASE_NETCONF_CTX);
139     }
140
141     public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing, final BaseSchema baseSchema) {
142         this.counter = new MessageCounter();
143         this.schemaContext = schemaContext;
144         parserFactory = DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext, strictParsing);
145         mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), QNAME_FUNCTION);
146         mappedNotifications = Multimaps.index(schemaContext.getNotifications(), QNAME_NOREV_FUNCTION);
147         this.baseSchema = baseSchema;
148     }
149
150     @Override
151     public synchronized DOMNotification toNotification(final NetconfMessage message) {
152         final Map.Entry<Date, XmlElement> stripped = NetconfMessageTransformUtil.stripNotification(message);
153         final QName notificationNoRev;
154         try {
155             notificationNoRev = QName.create(stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
156         } catch (final MissingNameSpaceException e) {
157             throw new IllegalArgumentException("Unable to parse notification " + message + ", cannot find namespace", e);
158         }
159         final Collection<NotificationDefinition> notificationDefinitions = mappedNotifications.get(notificationNoRev);
160         Preconditions.checkArgument(notificationDefinitions.size() > 0,
161                 "Unable to parse notification %s, unknown notification. Available notifications: %s", notificationDefinitions, mappedNotifications.keySet());
162
163         final NotificationDefinition mostRecentNotification = getMostRecentNotification(notificationDefinitions);
164
165         final ContainerSchemaNode notificationAsContainerSchemaNode = NetconfMessageTransformUtil.createSchemaForNotification(mostRecentNotification);
166
167         final Element element = stripped.getValue().getDomElement();
168         final ContainerNode content;
169         try {
170             content = parserFactory.getContainerNodeParser().parse(Collections.singleton(element),
171                 notificationAsContainerSchemaNode);
172         } catch (IllegalArgumentException e) {
173             throw new IllegalArgumentException(String.format("Failed to parse notification %s", element), e);
174         }
175         return new NetconfDeviceNotification(content, stripped.getKey());
176     }
177
178     private static NotificationDefinition getMostRecentNotification(final Collection<NotificationDefinition> notificationDefinitions) {
179         Comparator<NotificationDefinition> cmp = (o1, o2) -> o1.getQName().getRevision().compareTo(o2.getQName().getRevision());
180
181         return Collections.max(notificationDefinitions, cmp);
182     }
183
184     @Override
185     public NetconfMessage toRpcRequest(SchemaPath rpc, final NormalizedNode<?, ?> payload) {
186         // In case no input for rpc is defined, we can simply construct the payload here
187         final QName rpcQName = rpc.getLastComponent();
188         Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
189
190         // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
191         // If no, use pre built base netconf operations model
192         final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
193         if(needToUseBaseCtx) {
194             currentMappedRpcs = baseSchema.getMappedRpcs();
195         }
196
197         Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName), "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
198         if(currentMappedRpcs.get(rpcQName).getInput() == null) {
199             return new NetconfMessage(prepareDomResultForRpcRequest(rpcQName).getNode().getOwnerDocument());
200         }
201
202         Preconditions.checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpcQName);
203         Preconditions.checkArgument(payload instanceof ContainerNode,
204                 "Transforming an rpc with input: %s, payload has to be a container, but was: %s", rpcQName, payload);
205
206         // Set the path to the input of rpc for the node stream writer
207         rpc = rpc.createChild(QName.create(rpcQName, "input").intern());
208         final DOMResult result = prepareDomResultForRpcRequest(rpcQName);
209
210         try {
211             // 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
212             // This way operations like lock/unlock are supported even if the source for base model was not provided
213             SchemaContext ctx = needToUseBaseCtx ? baseSchema.getSchemaContext() : schemaContext;
214             writeNormalizedRpc(((ContainerNode) payload), result, rpc, ctx);
215         } catch (final XMLStreamException | IOException | IllegalStateException e) {
216             throw new IllegalStateException("Unable to serialize " + rpc, e);
217         }
218
219         final Document node = result.getNode().getOwnerDocument();
220
221         return new NetconfMessage(node);
222     }
223
224     private boolean isBaseOrNotificationRpc(final QName rpc) {
225         return rpc.getNamespace().equals(NETCONF_URI) ||
226                 rpc.getNamespace().equals(IETF_NETCONF_NOTIFICATIONS.getNamespace()) ||
227                 rpc.getNamespace().equals(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
228     }
229
230     private DOMResult prepareDomResultForRpcRequest(final QName rpcQName) {
231         final Document document = XmlUtil.newDocument();
232         final Element rpcNS = document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
233         // set msg id
234         rpcNS.setAttribute(NetconfMessageTransformUtil.MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
235         final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
236         rpcNS.appendChild(elementNS);
237         document.appendChild(rpcNS);
238         return new DOMResult(elementNS);
239     }
240
241     private static void writeNormalizedRpc(final ContainerNode normalized, final DOMResult result,
242             final SchemaPath schemaPath, final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
243         final XMLStreamWriter writer = NetconfUtil.XML_FACTORY.createXMLStreamWriter(result);
244         try {
245             try (final NormalizedNodeStreamWriter normalizedNodeStreamWriter =
246                     XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, schemaPath)) {
247                 try (final SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
248                         new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, schemaPath)) {
249                     Collection<DataContainerChild<?, ?>> value = normalized.getValue();
250                     normalizedNodeWriter.write(value);
251                     normalizedNodeWriter.flush();
252                 }
253             }
254         } finally {
255             try {
256                 writer.close();
257             } catch (final Exception e) {
258                 LOG.warn("Unable to close resource properly", e);
259             }
260         }
261     }
262
263     @Override
264     public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
265         final NormalizedNode<?, ?> normalizedNode;
266         final QName rpcQName = rpc.getLastComponent();
267         if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
268             final Element xmlData = NetconfMessageTransformUtil.getDataSubtree(message.getDocument());
269             final ContainerSchemaNode schemaForDataRead = NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
270             final ContainerNode dataNode;
271
272             try {
273                 dataNode = parserFactory.getContainerNodeParser().parse(Collections.singleton(xmlData), schemaForDataRead);
274             } catch (IllegalArgumentException e) {
275                 throw new IllegalArgumentException(String.format("Failed to parse data response %s", xmlData), e);
276             }
277
278             normalizedNode = Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
279                     .withChild(dataNode).build();
280         } else {
281
282             Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
283
284             // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
285             // If no, use pre built base netconf operations model
286             final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
287             if(needToUseBaseCtx) {
288                 currentMappedRpcs = baseSchema.getMappedRpcs();
289             }
290
291             final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
292             Preconditions.checkArgument(rpcDefinition != null, "Unable to parse response of %s, the rpc is unknown", rpcQName);
293
294             // In case no input for rpc is defined, we can simply construct the payload here
295             if (rpcDefinition.getOutput() == null) {
296                 Preconditions.checkArgument(XmlElement.fromDomDocument(
297                     message.getDocument()).getOnlyChildElementWithSameNamespaceOptionally("ok").isPresent(),
298                     "Unexpected content in response of rpc: %s, %s", rpcDefinition.getQName(), message);
299                 normalizedNode = null;
300             } else {
301                 final Element element = message.getDocument().getDocumentElement();
302                 try {
303                     normalizedNode = parserFactory.getContainerNodeParser().parse(Collections.singleton(element),
304                         rpcDefinition.getOutput());
305                 } catch (IllegalArgumentException e) {
306                     throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
307                 }
308             }
309         }
310         return new DefaultDOMRpcResult(normalizedNode);
311     }
312
313     private static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
314         private final ContainerNode content;
315         private final SchemaPath schemaPath;
316         private final Date eventTime;
317
318         NetconfDeviceNotification(final ContainerNode content, final Date eventTime) {
319             this.content = content;
320             this.eventTime = eventTime;
321             this.schemaPath = toPath(content.getNodeType());
322         }
323
324         @Nonnull
325         @Override
326         public SchemaPath getType() {
327             return schemaPath;
328
329         }
330
331         @Nonnull
332         @Override
333         public ContainerNode getBody() {
334             return content;
335         }
336
337         @Override
338         public Date getEventTime() {
339             return eventTime;
340         }
341     }
342 }