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