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