Shorten nested class references
[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 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toId;
18
19 import com.google.common.base.Strings;
20 import com.google.common.collect.ImmutableMap;
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.net.HttpURLConnection;
26 import java.net.MalformedURLException;
27 import java.net.URI;
28 import java.net.URISyntaxException;
29 import java.net.URL;
30 import java.net.URLConnection;
31 import java.nio.charset.Charset;
32 import java.nio.charset.StandardCharsets;
33 import java.util.AbstractMap.SimpleImmutableEntry;
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.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.YangInstanceIdentifier.NodeIdentifier;
57 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
59 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
64 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactory;
65 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
66 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
67 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
68 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
69 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
70 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
71 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
72 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
73 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
76 import org.w3c.dom.Document;
77 import org.w3c.dom.Element;
78 import org.w3c.dom.Node;
79 import org.xml.sax.SAXException;
80
81 /**
82  * Holds URLs with YANG schema resources for all yang modules reported in
83  * ietf-netconf-yang-library/modules-state/modules node.
84  */
85 public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
86
87     private static final Logger LOG = LoggerFactory.getLogger(LibraryModulesSchemas.class);
88     private static final Pattern DATE_PATTERN = Pattern.compile("(\\d{4}-\\d{2}-\\d{2})");
89     private static final SchemaContext LIBRARY_CONTEXT;
90
91     static {
92         final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
93         moduleInfoBackedContext.registerModuleInfo(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang
94                 .library.rev160621.$YangModuleInfoImpl.getInstance());
95         LIBRARY_CONTEXT = moduleInfoBackedContext.tryToCreateSchemaContext().get();
96     }
97
98     private static final JSONCodecFactory JSON_CODECS = JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02
99             .getShared(LIBRARY_CONTEXT);
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 final ImmutableMap<QName, URL> availableModels;
110
111     private LibraryModulesSchemas(final ImmutableMap<QName, URL> availableModels) {
112         this.availableModels = requireNonNull(availableModels);
113     }
114
115     public Map<SourceIdentifier, URL> getAvailableModels() {
116         final Map<SourceIdentifier, URL> result = new HashMap<>();
117         for (final Map.Entry<QName, URL> entry : availableModels.entrySet()) {
118             final SourceIdentifier sId = RevisionSourceIdentifier.create(entry.getKey().getLocalName(),
119                 entry.getKey().getRevision());
120             result.put(sId, entry.getValue());
121         }
122
123         return result;
124     }
125
126     /**
127      * Resolves URLs with YANG schema resources from modules-state. Uses basic http authenticaiton
128      *
129      * @param url URL pointing to yang library
130      * @return Resolved URLs with YANG schema resources for all yang modules from yang library
131      */
132     public static LibraryModulesSchemas create(final String url, final String username, final String password) {
133         try {
134             final URL urlConnection = new URL(requireNonNull(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(ImmutableMap.of());
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(NETCONF_GET_PATH, 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(ImmutableMap.of());
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(ImmutableMap.of());
173         }
174
175         final Optional<? extends NormalizedNode<?, ?>> modulesStateNode =
176                 findModulesStateNode(moduleListNodeResult.getResult());
177         if (modulesStateNode.isPresent()) {
178             final NormalizedNode<?, ?> node = modulesStateNode.get();
179             checkState(node instanceof ContainerNode, "Expecting container containing schemas, but was %s", node);
180             return create((ContainerNode) node);
181         }
182
183         LOG.warn("{}: Unable to detect available schemas, get to {} was empty", deviceId, toId(ModulesState.QNAME));
184         return new LibraryModulesSchemas(ImmutableMap.of());
185     }
186
187     private static LibraryModulesSchemas create(final ContainerNode modulesStateNode) {
188         final NodeIdentifier moduleListNodeId = new NodeIdentifier(Module.QNAME);
189         final Optional<DataContainerChild<?, ?>> moduleListNode = modulesStateNode.getChild(moduleListNodeId);
190         checkState(moduleListNode.isPresent(), "Unable to find list: %s in %s", moduleListNodeId, modulesStateNode);
191         final DataContainerChild<?, ?> node = moduleListNode.get();
192         checkState(node instanceof MapNode, "Unexpected structure for container: %s in : %s. Expecting a list",
193                 moduleListNodeId, modulesStateNode);
194
195         final ImmutableMap.Builder<QName, URL> schemasMapping = new ImmutableMap.Builder<>();
196         for (final MapEntryNode moduleNode : ((MapNode) node).getValue()) {
197             final Optional<Map.Entry<QName, URL>> schemaMappingEntry = createFromEntry(moduleNode);
198             if (schemaMappingEntry.isPresent()) {
199                 schemasMapping.put(createFromEntry(moduleNode).get());
200             }
201         }
202
203         return new LibraryModulesSchemas(schemasMapping.build());
204     }
205
206     /**
207      * Resolves URLs with YANG schema resources from modules-state.
208      * @param url URL pointing to yang library
209      * @return Resolved URLs with YANG schema resources for all yang modules from yang library
210      */
211     public static LibraryModulesSchemas create(final String url) {
212         try {
213             final URL urlConnection = new URL(requireNonNull(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(ImmutableMap.of());
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         requireNonNull(contentType, "Content type unknown");
251         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(ImmutableMap.of());
259             }
260
261             final NormalizedNode<?, ?> modulesStateNode = optionalModulesStateNode.get();
262             final QName nodeType = modulesStateNode.getNodeType();
263             checkState(nodeType.equals(ModulesState.QNAME), "Wrong QName %s", nodeType);
264             checkState(modulesStateNode instanceof ContainerNode,
265                 "Expecting container containing module list, but was %s", modulesStateNode);
266
267             final NodeIdentifier moduleListNodeId = new NodeIdentifier(Module.QNAME);
268             final Optional<DataContainerChild<?, ?>> moduleListNode =
269                     ((ContainerNode) modulesStateNode).getChild(moduleListNodeId);
270             checkState(moduleListNode.isPresent(), "Unable to find list: %s in %s", moduleListNodeId, modulesStateNode);
271             final DataContainerChild<?, ?> node = moduleListNode.get();
272             checkState(node instanceof MapNode, "Unexpected structure for container: %s in : %s. Expecting a list",
273                     moduleListNodeId, modulesStateNode);
274
275             final ImmutableMap.Builder<QName, URL> schemasMapping = new ImmutableMap.Builder<>();
276             for (final MapEntryNode moduleNode : ((MapNode) node).getValue()) {
277                 final Optional<Map.Entry<QName, URL>> schemaMappingEntry = createFromEntry(moduleNode);
278                 if (schemaMappingEntry.isPresent()) {
279                     schemasMapping.put(createFromEntry(moduleNode).get());
280                 }
281             }
282
283             return new LibraryModulesSchemas(schemasMapping.build());
284         } catch (final IOException e) {
285             LOG.warn("Unable to download yang library from {}", connection.getURL(), e);
286             return new LibraryModulesSchemas(ImmutableMap.of());
287         }
288     }
289
290     private static boolean guessJsonFromFileName(final String fileName) {
291         final int i = fileName.lastIndexOf('.');
292         return i != 1 && ".json".equalsIgnoreCase(fileName.substring(i));
293     }
294
295     private static Optional<NormalizedNode<?, ?>> readJson(final InputStream in) {
296         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
297         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
298
299         final JsonParserStream jsonParser = JsonParserStream.create(writer, JSON_CODECS);
300         final JsonReader reader = new JsonReader(new InputStreamReader(in, Charset.defaultCharset()));
301
302         jsonParser.parse(reader);
303
304         return resultHolder.isFinished() ? Optional.of(resultHolder.getResult()) : Optional.empty();
305     }
306
307     private static Optional<NormalizedNode<?, ?>> readXml(final InputStream in) {
308         try {
309             final DocumentBuilder docBuilder = UntrustedXML.newDocumentBuilder();
310
311             final Document read = docBuilder.parse(in);
312             final Document doc = docBuilder.newDocument();
313             final Element rootElement = doc.createElementNS("urn:ietf:params:xml:ns:yang:ietf-yang-library",
314                     "modules");
315             doc.appendChild(rootElement);
316
317             for (int i = 0; i < read.getElementsByTagName("revision").getLength(); i++) {
318                 final String revision = read.getElementsByTagName("revision").item(i).getTextContent();
319                 if (DATE_PATTERN.matcher(revision).find() || revision.isEmpty()) {
320                     final Node module = doc.importNode(read.getElementsByTagName("module").item(i), true);
321                     rootElement.appendChild(module);
322                 } else {
323                     LOG.warn("Xml contains wrong revision - {} - on module {}", revision,
324                             read.getElementsByTagName("module").item(i).getTextContent());
325                 }
326             }
327
328             final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
329             final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
330             final XmlParserStream xmlParser = XmlParserStream.create(writer, LIBRARY_CONTEXT,
331                     LIBRARY_CONTEXT.getDataChildByName(ModulesState.QNAME));
332             xmlParser.traverse(new DOMSource(doc.getDocumentElement()));
333             final NormalizedNode<?, ?> parsed = resultHolder.getResult();
334             return Optional.of(parsed);
335         } catch (XMLStreamException | URISyntaxException | IOException | SAXException e) {
336             LOG.warn("Unable to parse yang library xml content", e);
337         }
338
339         return Optional.empty();
340     }
341
342     private static Optional<Entry<QName, URL>> createFromEntry(final MapEntryNode moduleNode) {
343         checkArgument(moduleNode.getNodeType().equals(Module.QNAME), "Wrong QName %s", moduleNode.getNodeType());
344
345         NodeIdentifier childNodeId = new NodeIdentifier(QName.create(Module.QNAME, "name"));
346         final String moduleName = getSingleChildNodeValue(moduleNode, childNodeId).get();
347
348         childNodeId = new NodeIdentifier(QName.create(Module.QNAME, "revision"));
349         final Optional<String> revision = getSingleChildNodeValue(moduleNode, childNodeId);
350         if (revision.isPresent()) {
351             if (!Revision.STRING_FORMAT_PATTERN.matcher(revision.get()).matches()) {
352                 LOG.warn("Skipping library schema for {}. Revision {} is in wrong format.", moduleNode, revision.get());
353                 return Optional.empty();
354             }
355         }
356
357         // FIXME leaf schema with url that represents the yang schema resource for this module is not mandatory
358         // don't fail if schema node is not present, just skip the entry or add some default URL
359         childNodeId = new NodeIdentifier(QName.create(Module.QNAME, "schema"));
360         final Optional<String> schemaUriAsString = getSingleChildNodeValue(moduleNode, childNodeId);
361
362         childNodeId = new NodeIdentifier(QName.create(Module.QNAME, "namespace"));
363         final String moduleNameSpace = getSingleChildNodeValue(moduleNode, childNodeId).get();
364
365         final QName moduleQName = revision.isPresent()
366                 ? QName.create(moduleNameSpace, revision.get(), moduleName)
367                 : QName.create(URI.create(moduleNameSpace), moduleName);
368
369         try {
370             return Optional.of(new SimpleImmutableEntry<>(moduleQName, new URL(schemaUriAsString.get())));
371         } catch (final MalformedURLException e) {
372             LOG.warn("Skipping library schema for {}. URL {} representing yang schema resource is not valid",
373                     moduleNode, schemaUriAsString.get());
374             return Optional.empty();
375         }
376     }
377
378     private static Optional<String> getSingleChildNodeValue(final DataContainerNode<?> schemaNode,
379                                                             final NodeIdentifier childNodeId) {
380         final Optional<DataContainerChild<?, ?>> node = schemaNode.getChild(childNodeId);
381         checkArgument(node.isPresent(), "Child node %s not present", childNodeId.getNodeType());
382         return getValueOfSimpleNode(node.get());
383     }
384
385     private static Optional<String> getValueOfSimpleNode(final NormalizedNode<?, ?> node) {
386         final String valueStr = node.getValue().toString();
387         return Strings.isNullOrEmpty(valueStr) ? Optional.empty() : Optional.of(valueStr.trim());
388     }
389
390     @Override
391     public Set<QName> getAvailableYangSchemasQNames() {
392         return null;
393     }
394 }