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