Merge "Bug 8071 - Do not fail on modules with invalid revision during ...
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / sal / connect / netconf / LibraryModulesSchemas.java
1 /*
2  * Copyright (c) 2015 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;
9
10 import static javax.xml.bind.DatatypeConverter.printBase64Binary;
11 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_DATA_QNAME;
12 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_QNAME;
13 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toId;
14 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath;
15
16 import com.google.common.base.Optional;
17 import com.google.common.base.Preconditions;
18 import com.google.common.base.Strings;
19 import com.google.common.collect.ImmutableMap;
20 import com.google.common.collect.Maps;
21 import com.google.gson.stream.JsonReader;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.InputStreamReader;
25 import java.io.StringWriter;
26 import java.net.HttpURLConnection;
27 import java.net.MalformedURLException;
28 import java.net.URI;
29 import java.net.URL;
30 import java.net.URLConnection;
31 import java.util.AbstractMap;
32 import java.util.Collections;
33 import java.util.Map;
34 import java.util.Set;
35 import java.util.concurrent.ExecutionException;
36 import java.util.regex.Pattern;
37 import javax.xml.parsers.DocumentBuilder;
38 import javax.xml.transform.OutputKeys;
39 import javax.xml.transform.Transformer;
40 import javax.xml.transform.TransformerException;
41 import javax.xml.transform.TransformerFactory;
42 import javax.xml.transform.dom.DOMSource;
43 import javax.xml.transform.stream.StreamResult;
44 import org.opendaylight.controller.config.util.xml.XmlUtil;
45 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
46 import org.opendaylight.mdsal.binding.generator.impl.ModuleInfoBackedContext;
47 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemas;
48 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
49 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
50 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
51 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.ModulesState;
52 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.module.list.Module;
53 import org.opendaylight.yangtools.util.xml.UntrustedXML;
54 import org.opendaylight.yangtools.yang.common.QName;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
56 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
58 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
63 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
64 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
65 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
66 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
67 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
68 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
69 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
70 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
71 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
72 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
75 import org.w3c.dom.Document;
76 import org.w3c.dom.Element;
77 import org.w3c.dom.Node;
78 import org.xml.sax.SAXException;
79
80 /**
81  * Holds URLs with YANG schema resources for all yang modules reported in
82  * ietf-netconf-yang-library/modules-state/modules node.
83  */
84 public class LibraryModulesSchemas implements NetconfDeviceSchemas {
85
86     private static final Logger LOG = LoggerFactory.getLogger(LibraryModulesSchemas.class);
87     private static final Pattern DATE_PATTERN = Pattern.compile("(\\d{4}-\\d{2}-\\d{2})");
88     private static final SchemaContext LIBRARY_CONTEXT;
89
90     static {
91         final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
92         moduleInfoBackedContext.registerModuleInfo(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang
93                 .library.rev160409.$YangModuleInfoImpl.getInstance());
94         LIBRARY_CONTEXT = moduleInfoBackedContext.tryToCreateSchemaContext().get();
95     }
96
97     private final Map<QName, URL> availableModels;
98
99     private static final YangInstanceIdentifier MODULES_STATE_MODULE_LIST =
100             YangInstanceIdentifier.builder().node(ModulesState.QNAME).node(Module.QNAME).build();
101
102     private static final ContainerNode GET_MODULES_STATE_MODULE_LIST_RPC;
103
104     static {
105         final DataContainerChild<?, ?> filter =
106                 NetconfMessageTransformUtil.toFilterStructure(MODULES_STATE_MODULE_LIST, LIBRARY_CONTEXT);
107         GET_MODULES_STATE_MODULE_LIST_RPC =
108                 Builders.containerBuilder().withNodeIdentifier(toId(NETCONF_GET_QNAME)).withChild(filter).build();
109     }
110
111     private LibraryModulesSchemas(final Map<QName, URL> availableModels) {
112         this.availableModels = availableModels;
113     }
114
115     public Map<SourceIdentifier, URL> getAvailableModels() {
116         final Map<SourceIdentifier, URL> result = Maps.newHashMap();
117         for (final Map.Entry<QName, URL> entry : availableModels.entrySet()) {
118             final SourceIdentifier sId = RevisionSourceIdentifier
119                 .create(entry.getKey().getLocalName(), Optional.fromNullable(entry.getKey().getFormattedRevision()));
120             result.put(sId, entry.getValue());
121         }
122
123         return result;
124     }
125
126
127     /**
128      * Resolves URLs with YANG schema resources from modules-state. Uses basic http authenticaiton
129      *
130      * @param url URL pointing to yang library
131      * @return Resolved URLs with YANG schema resources for all yang modules from yang library
132      */
133     public static LibraryModulesSchemas create(final String url, final String username, final String password) {
134         Preconditions.checkNotNull(url);
135         try {
136             final URL urlConnection = new URL(url);
137             final URLConnection connection = urlConnection.openConnection();
138
139             if (connection instanceof HttpURLConnection) {
140                 connection.setRequestProperty("Accept", "application/xml");
141                 final String userpass = username + ":" + password;
142                 final String basicAuth = "Basic " + printBase64Binary(userpass.getBytes());
143
144                 connection.setRequestProperty("Authorization", basicAuth);
145             }
146
147             return createFromURLConnection(connection);
148
149         } catch (final IOException e) {
150             LOG.warn("Unable to download yang library from {}", url, e);
151             return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
152         }
153     }
154
155
156     public static LibraryModulesSchemas create(final NetconfDeviceRpc deviceRpc, final RemoteDeviceId deviceId) {
157         final DOMRpcResult moduleListNodeResult;
158         try {
159             moduleListNodeResult =
160                     deviceRpc.invokeRpc(toPath(NETCONF_GET_QNAME), GET_MODULES_STATE_MODULE_LIST_RPC).get();
161         } catch (final InterruptedException e) {
162             Thread.currentThread().interrupt();
163             throw new RuntimeException(deviceId + ": Interrupted while waiting for response to "
164                     + MODULES_STATE_MODULE_LIST, e);
165         } catch (final ExecutionException e) {
166             LOG.warn("{}: Unable to detect available schemas, get to {} failed", deviceId,
167                     MODULES_STATE_MODULE_LIST, e);
168             return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
169         }
170
171         if (moduleListNodeResult.getErrors().isEmpty() == false) {
172             LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}",
173                     deviceId, MODULES_STATE_MODULE_LIST, moduleListNodeResult.getErrors());
174             return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
175         }
176
177
178         final Optional<? extends NormalizedNode<?, ?>> modulesStateNode =
179                 findModulesStateNode(moduleListNodeResult.getResult());
180         if (modulesStateNode.isPresent()) {
181             Preconditions.checkState(modulesStateNode.get() instanceof ContainerNode,
182                     "Expecting container containing schemas, but was %s", modulesStateNode.get());
183             return create(((ContainerNode) modulesStateNode.get()));
184         } else {
185             LOG.warn("{}: Unable to detect available schemas, get to {} was empty", deviceId, toId(ModulesState.QNAME));
186             return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
187         }
188     }
189
190     private static LibraryModulesSchemas create(final ContainerNode modulesStateNode) {
191         final YangInstanceIdentifier.NodeIdentifier moduleListNodeId =
192                 new YangInstanceIdentifier.NodeIdentifier(Module.QNAME);
193         final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> moduleListNode =
194                 modulesStateNode.getChild(moduleListNodeId);
195         Preconditions.checkState(moduleListNode.isPresent(),
196                 "Unable to find list: %s in %s", moduleListNodeId, modulesStateNode);
197         Preconditions.checkState(moduleListNode.get() instanceof MapNode,
198                 "Unexpected structure for container: %s in : %s. Expecting a list",
199                 moduleListNodeId, modulesStateNode);
200
201         final ImmutableMap.Builder<QName, URL> schemasMapping = new ImmutableMap.Builder<>();
202         for (final MapEntryNode moduleNode : ((MapNode) moduleListNode.get()).getValue()) {
203             final Optional<Map.Entry<QName, URL>> schemaMappingEntry = createFromEntry(moduleNode);
204             if (schemaMappingEntry.isPresent()) {
205                 schemasMapping.put(createFromEntry(moduleNode).get());
206             }
207         }
208
209         return new LibraryModulesSchemas(schemasMapping.build());
210     }
211
212     /**
213      * Resolves URLs with YANG schema resources from modules-state.
214      * @param url URL pointing to yang library
215      * @return Resolved URLs with YANG schema resources for all yang modules from yang library
216      */
217     public static LibraryModulesSchemas create(final String url) {
218         Preconditions.checkNotNull(url);
219         try {
220             final URL urlConnection = new URL(url);
221             final URLConnection connection = urlConnection.openConnection();
222
223             if (connection instanceof HttpURLConnection) {
224                 connection.setRequestProperty("Accept", "application/xml");
225             }
226
227             return createFromURLConnection(connection);
228
229         } catch (final IOException e) {
230             LOG.warn("Unable to download yang library from {}", url, e);
231             return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
232         }
233     }
234
235     private static Optional<? extends NormalizedNode<?, ?>> findModulesStateNode(final NormalizedNode<?, ?> result) {
236         if (result == null) {
237             return Optional.absent();
238         }
239         final Optional<DataContainerChild<?, ?>> dataNode =
240                 ((DataContainerNode<?>) result).getChild(toId(NETCONF_DATA_QNAME));
241         if (dataNode.isPresent() == false) {
242             return Optional.absent();
243         }
244
245         return ((DataContainerNode<?>) dataNode.get()).getChild(toId(ModulesState.QNAME));
246     }
247
248     private static LibraryModulesSchemas createFromURLConnection(final URLConnection connection) {
249
250         String contentType = connection.getContentType();
251
252         // TODO try to guess Json also from intput stream
253         if (guessJsonFromFileName(connection.getURL().getFile())) {
254             contentType = "application/json";
255         }
256
257         Preconditions.checkNotNull(contentType, "Content type unknown");
258         Preconditions.checkState(contentType.equals("application/json") || contentType.equals("application/xml"),
259                 "Only XML and JSON types are supported.");
260         try (InputStream in = connection.getInputStream()) {
261             final Optional<NormalizedNode<?, ?>> optionalModulesStateNode =
262                     contentType.equals("application/json") ? readJson(in) : readXml(in);
263
264             if (!optionalModulesStateNode.isPresent()) {
265                 return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
266             }
267
268             final NormalizedNode<?, ?> modulesStateNode = optionalModulesStateNode.get();
269             Preconditions.checkState(modulesStateNode.getNodeType().equals(ModulesState.QNAME),
270                     "Wrong QName %s", modulesStateNode.getNodeType());
271             Preconditions.checkState(modulesStateNode instanceof ContainerNode,
272                     "Expecting container containing module list, but was %s", modulesStateNode);
273
274             final YangInstanceIdentifier.NodeIdentifier moduleListNodeId =
275                     new YangInstanceIdentifier.NodeIdentifier(Module.QNAME);
276             final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> moduleListNode =
277                     ((ContainerNode) modulesStateNode).getChild(moduleListNodeId);
278             Preconditions.checkState(moduleListNode.isPresent(),
279                     "Unable to find list: %s in %s", moduleListNodeId, modulesStateNode);
280             Preconditions.checkState(moduleListNode.get() instanceof MapNode,
281                     "Unexpected structure for container: %s in : %s. Expecting a list",
282                     moduleListNodeId, modulesStateNode);
283
284             final ImmutableMap.Builder<QName, URL> schemasMapping = new ImmutableMap.Builder<>();
285             for (final MapEntryNode moduleNode : ((MapNode) moduleListNode.get()).getValue()) {
286                 final Optional<Map.Entry<QName, URL>> schemaMappingEntry = createFromEntry(moduleNode);
287                 if (schemaMappingEntry.isPresent()) {
288                     schemasMapping.put(createFromEntry(moduleNode).get());
289                 }
290             }
291
292             return new LibraryModulesSchemas(schemasMapping.build());
293         } catch (final IOException e) {
294             LOG.warn("Unable to download yang library from {}", connection.getURL(), e);
295             return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
296         }
297     }
298
299     private static boolean guessJsonFromFileName(final String fileName) {
300         String extension = "";
301         final int i = fileName.lastIndexOf(46);
302         if (i != -1) {
303             extension = fileName.substring(i).toLowerCase();
304         }
305
306         return extension.equals(".json");
307     }
308
309     private static Optional<NormalizedNode<?, ?>> readJson(final InputStream in) {
310         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
311         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
312
313         final JsonParserStream jsonParser = JsonParserStream.create(writer, LIBRARY_CONTEXT);
314         final JsonReader reader = new JsonReader(new InputStreamReader(in));
315
316         jsonParser.parse(reader);
317
318         return resultHolder.isFinished()
319                 ? Optional.of(resultHolder.getResult()) : Optional.<NormalizedNode<?, ?>>absent();
320     }
321
322     private static Optional<NormalizedNode<?, ?>> readXml(final InputStream in) {
323         final DomToNormalizedNodeParserFactory parserFactory =
324                 DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, LIBRARY_CONTEXT);
325         try {
326             final DocumentBuilder docBuilder = UntrustedXML.newDocumentBuilder();
327
328             final Document read = docBuilder.parse(in);
329             final Document doc = docBuilder.newDocument();
330             final Element rootElement = doc.createElementNS("urn:ietf:params:xml:ns:yang:ietf-yang-library",
331                     "modules");
332             doc.appendChild(rootElement);
333
334             for (int i = 0; i < read.getElementsByTagName("revision").getLength(); i++) {
335                 final String revision = read.getElementsByTagName("revision").item(i).getTextContent();
336                 if (DATE_PATTERN.matcher(revision).find() || revision.isEmpty()) {
337                     final Node module = doc.importNode(read.getElementsByTagName("module").item(i), true);
338                     rootElement.appendChild(module);
339                 } else {
340                     LOG.warn("Xml contains wrong revision - {} - on module {}", revision,
341                             read.getElementsByTagName("module").item(i).getTextContent());
342                 }
343             }
344
345             final Transformer transformer = TransformerFactory.newInstance().newTransformer();
346             final StringWriter sw = new StringWriter();
347             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
348             transformer.transform(new DOMSource(doc), new StreamResult(sw));
349             final NormalizedNode<?, ?> parsed =
350                     parserFactory.getContainerNodeParser()
351                             .parse(Collections.singleton(XmlUtil.readXmlToElement(sw.toString())),
352                             (ContainerSchemaNode) LIBRARY_CONTEXT.getDataChildByName(ModulesState.QNAME));
353             return Optional.of(parsed);
354         } catch (final SAXException | IOException | TransformerException e) {
355             LOG.warn("Unable to parse yang library xml content", e);
356         }
357
358         return Optional.<NormalizedNode<?, ?>>absent();
359     }
360
361     private static Optional<Map.Entry<QName, URL>> createFromEntry(final MapEntryNode moduleNode) {
362         Preconditions.checkArgument(
363                 moduleNode.getNodeType().equals(Module.QNAME), "Wrong QName %s", moduleNode.getNodeType());
364
365         YangInstanceIdentifier.NodeIdentifier childNodeId =
366                 new YangInstanceIdentifier.NodeIdentifier(QName.create(Module.QNAME, "name"));
367         final String moduleName = getSingleChildNodeValue(moduleNode, childNodeId).get();
368
369         childNodeId = new YangInstanceIdentifier.NodeIdentifier(QName.create(Module.QNAME, "revision"));
370         final Optional<String> revision = getSingleChildNodeValue(moduleNode, childNodeId);
371         if (revision.isPresent()) {
372             if (!SourceIdentifier.REVISION_PATTERN.matcher(revision.get()).matches()) {
373                 LOG.warn("Skipping library schema for {}. Revision {} is in wrong format.", moduleNode, revision.get());
374                 return Optional.<Map.Entry<QName, URL>>absent();
375             }
376         }
377
378         // FIXME leaf schema with url that represents the yang schema resource for this module is not mandatory
379         // don't fail if schema node is not present, just skip the entry or add some default URL
380         childNodeId = new YangInstanceIdentifier.NodeIdentifier(QName.create(Module.QNAME, "schema"));
381         final Optional<String> schemaUriAsString = getSingleChildNodeValue(moduleNode, childNodeId);
382
383         childNodeId = new YangInstanceIdentifier.NodeIdentifier(QName.create(Module.QNAME, "namespace"));
384         final String moduleNameSpace = getSingleChildNodeValue(moduleNode, childNodeId).get();
385
386         final QName moduleQName = revision.isPresent()
387                 ? QName.create(moduleNameSpace, revision.get(), moduleName)
388                 : QName.create(URI.create(moduleNameSpace), null, moduleName);
389
390         try {
391             return Optional.<Map.Entry<QName, URL>>of(new AbstractMap.SimpleImmutableEntry<>(
392                     moduleQName, new URL(schemaUriAsString.get())));
393         } catch (final MalformedURLException e) {
394             LOG.warn("Skipping library schema for {}. URL {} representing yang schema resource is not valid",
395                     moduleNode, schemaUriAsString.get());
396             return Optional.<Map.Entry<QName, URL>>absent();
397         }
398     }
399
400     private static Optional<String> getSingleChildNodeValue(final DataContainerNode<?> schemaNode,
401                                                             final YangInstanceIdentifier.NodeIdentifier childNodeId) {
402         final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> node =
403                 schemaNode.getChild(childNodeId);
404         Preconditions.checkArgument(node.isPresent(), "Child node %s not present", childNodeId.getNodeType());
405         return getValueOfSimpleNode(node.get());
406     }
407
408     private static Optional<String> getValueOfSimpleNode(
409             final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
410         final Object value = node.getValue();
411         return value == null || Strings.isNullOrEmpty(value.toString())
412                 ? Optional.<String>absent() : Optional.of(value.toString().trim());
413     }
414
415     @Override
416     public Set<QName> getAvailableYangSchemasQNames() {
417         return null;
418     }
419 }