Merge "Remove unused isMaster variable in ClusteredNetconfDevice"
[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_URI;
12 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath;
13
14 import com.google.common.base.Function;
15 import com.google.common.base.Preconditions;
16 import com.google.common.collect.Maps;
17 import com.google.common.collect.Multimap;
18 import com.google.common.collect.Multimaps;
19 import java.io.IOException;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.Comparator;
23 import java.util.Date;
24 import java.util.Map;
25 import javax.annotation.Nonnull;
26 import javax.xml.stream.XMLStreamException;
27 import javax.xml.transform.dom.DOMResult;
28 import org.opendaylight.controller.config.util.xml.MissingNameSpaceException;
29 import org.opendaylight.controller.config.util.xml.XmlElement;
30 import org.opendaylight.controller.md.sal.dom.api.DOMEvent;
31 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
32 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
33 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
34 import org.opendaylight.netconf.api.NetconfMessage;
35 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
36 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
37 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
38 import org.opendaylight.yangtools.yang.common.QName;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
42 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
43 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
44 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
45 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
47 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.w3c.dom.Document;
54 import org.w3c.dom.Element;
55
56 public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
57
58     private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformer.class);
59
60     private static final Function<SchemaNode, QName> QNAME_FUNCTION = new Function<SchemaNode, QName>() {
61         @Override
62         public QName apply(final SchemaNode rpcDefinition) {
63             return rpcDefinition.getQName();
64         }
65     };
66
67     private static final Function<SchemaNode, QName> QNAME_NOREV_FUNCTION = new Function<SchemaNode, QName>() {
68         @Override
69         public QName apply(final SchemaNode notification) {
70             return QNAME_FUNCTION.apply(notification).withoutRevision();
71         }
72     };
73
74     private final SchemaContext schemaContext;
75     private final BaseSchema baseSchema;
76     private final MessageCounter counter;
77     private final Map<QName, RpcDefinition> mappedRpcs;
78     private final Multimap<QName, NotificationDefinition> mappedNotifications;
79     private final DomToNormalizedNodeParserFactory parserFactory;
80
81     public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing) {
82         this(schemaContext, strictParsing, BaseSchema.BASE_NETCONF_CTX);
83     }
84
85     public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing, final BaseSchema baseSchema) {
86         this.counter = new MessageCounter();
87         this.schemaContext = schemaContext;
88         parserFactory = DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext, strictParsing);
89         mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), QNAME_FUNCTION);
90         mappedNotifications = Multimaps.index(schemaContext.getNotifications(), QNAME_NOREV_FUNCTION);
91         this.baseSchema = baseSchema;
92     }
93
94     @Override
95     public synchronized DOMNotification toNotification(final NetconfMessage message) {
96         final Map.Entry<Date, XmlElement> stripped = NetconfMessageTransformUtil.stripNotification(message);
97         final QName notificationNoRev;
98         try {
99             notificationNoRev = QName.create(stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
100         } catch (final MissingNameSpaceException e) {
101             throw new IllegalArgumentException("Unable to parse notification " + message + ", cannot find namespace", e);
102         }
103         final Collection<NotificationDefinition> notificationDefinitions = mappedNotifications.get(notificationNoRev);
104         Preconditions.checkArgument(notificationDefinitions.size() > 0,
105                 "Unable to parse notification %s, unknown notification. Available notifications: %s", notificationDefinitions, mappedNotifications.keySet());
106
107         final NotificationDefinition mostRecentNotification = getMostRecentNotification(notificationDefinitions);
108
109         final ContainerSchemaNode notificationAsContainerSchemaNode = NetconfMessageTransformUtil.createSchemaForNotification(mostRecentNotification);
110
111         final Element element = stripped.getValue().getDomElement();
112         final ContainerNode content;
113         try {
114             content = parserFactory.getContainerNodeParser().parse(Collections.singleton(element),
115                 notificationAsContainerSchemaNode);
116         } catch (IllegalArgumentException e) {
117             throw new IllegalArgumentException(String.format("Failed to parse notification %s", element), e);
118         }
119         return new NetconfDeviceNotification(content, stripped.getKey());
120     }
121
122     private static NotificationDefinition getMostRecentNotification(final Collection<NotificationDefinition> notificationDefinitions) {
123         Comparator<NotificationDefinition> cmp = (o1, o2) -> o1.getQName().getRevision().compareTo(o2.getQName().getRevision());
124
125         return Collections.max(notificationDefinitions, cmp);
126     }
127
128     @Override
129     public NetconfMessage toRpcRequest(SchemaPath rpc, final NormalizedNode<?, ?> payload) {
130         // In case no input for rpc is defined, we can simply construct the payload here
131         final QName rpcQName = rpc.getLastComponent();
132         Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
133
134         // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
135         // If no, use pre built base netconf operations model
136         final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
137         if(needToUseBaseCtx) {
138             currentMappedRpcs = baseSchema.getMappedRpcs();
139         }
140
141         Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName), "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
142         if(currentMappedRpcs.get(rpcQName).getInput() == null) {
143             return new NetconfMessage(NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter).getNode().getOwnerDocument());
144         }
145
146         Preconditions.checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpcQName);
147         Preconditions.checkArgument(payload instanceof ContainerNode,
148                 "Transforming an rpc with input: %s, payload has to be a container, but was: %s", rpcQName, payload);
149
150         // Set the path to the input of rpc for the node stream writer
151         rpc = rpc.createChild(QName.create(rpcQName, "input").intern());
152         final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter);
153
154         try {
155             // 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
156             // This way operations like lock/unlock are supported even if the source for base model was not provided
157             SchemaContext ctx = needToUseBaseCtx ? baseSchema.getSchemaContext() : schemaContext;
158             NetconfMessageTransformUtil.writeNormalizedRpc(((ContainerNode) payload), result, rpc, ctx);
159         } catch (final XMLStreamException | IOException | IllegalStateException e) {
160             throw new IllegalStateException("Unable to serialize " + rpc, e);
161         }
162
163         final Document node = result.getNode().getOwnerDocument();
164
165         return new NetconfMessage(node);
166     }
167
168     private boolean isBaseOrNotificationRpc(final QName rpc) {
169         return rpc.getNamespace().equals(NETCONF_URI) ||
170                 rpc.getNamespace().equals(IETF_NETCONF_NOTIFICATIONS.getNamespace()) ||
171                 rpc.getNamespace().equals(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
172     }
173
174
175     @Override
176     public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
177         final NormalizedNode<?, ?> normalizedNode;
178         final QName rpcQName = rpc.getLastComponent();
179         if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
180             final Element xmlData = NetconfMessageTransformUtil.getDataSubtree(message.getDocument());
181             final ContainerSchemaNode schemaForDataRead = NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
182             final ContainerNode dataNode;
183
184             try {
185                 dataNode = parserFactory.getContainerNodeParser().parse(Collections.singleton(xmlData), schemaForDataRead);
186             } catch (IllegalArgumentException e) {
187                 throw new IllegalArgumentException(String.format("Failed to parse data response %s", xmlData), e);
188             }
189
190             normalizedNode = Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
191                     .withChild(dataNode).build();
192         } else {
193
194             Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
195
196             // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
197             // If no, use pre built base netconf operations model
198             final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
199             if(needToUseBaseCtx) {
200                 currentMappedRpcs = baseSchema.getMappedRpcs();
201             }
202
203             final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
204             Preconditions.checkArgument(rpcDefinition != null, "Unable to parse response of %s, the rpc is unknown", rpcQName);
205
206             // In case no input for rpc is defined, we can simply construct the payload here
207             if (rpcDefinition.getOutput() == null) {
208                 Preconditions.checkArgument(XmlElement.fromDomDocument(
209                     message.getDocument()).getOnlyChildElementWithSameNamespaceOptionally("ok").isPresent(),
210                     "Unexpected content in response of rpc: %s, %s", rpcDefinition.getQName(), message);
211                 normalizedNode = null;
212             } else {
213                 final Element element = message.getDocument().getDocumentElement();
214                 try {
215                     normalizedNode = parserFactory.getContainerNodeParser().parse(Collections.singleton(element),
216                         rpcDefinition.getOutput());
217                 } catch (IllegalArgumentException e) {
218                     throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
219                 }
220             }
221         }
222         return new DefaultDOMRpcResult(normalizedNode);
223     }
224
225     private static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
226         private final ContainerNode content;
227         private final SchemaPath schemaPath;
228         private final Date eventTime;
229
230         NetconfDeviceNotification(final ContainerNode content, final Date eventTime) {
231             this.content = content;
232             this.eventTime = eventTime;
233             this.schemaPath = toPath(content.getNodeType());
234         }
235
236         @Nonnull
237         @Override
238         public SchemaPath getType() {
239             return schemaPath;
240
241         }
242
243         @Nonnull
244         @Override
245         public ContainerNode getBody() {
246             return content;
247         }
248
249         @Override
250         public Date getEventTime() {
251             return eventTime;
252         }
253     }
254 }