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