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