Migrate callers of NormalizedNode.getIdentifier()
[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.NormalizationResult;
66 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
67 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactory;
68 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
69 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
70 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
71 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
72 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
73 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizationResultHolder;
74 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
75 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
76 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
77 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
80 import org.w3c.dom.Document;
81 import org.w3c.dom.Element;
82 import org.w3c.dom.Node;
83 import org.xml.sax.SAXException;
84
85 /**
86  * Holds URLs with YANG schema resources for all yang modules reported in
87  * ietf-netconf-yang-library/modules-state/modules node.
88  */
89 public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
90
91     private static final Logger LOG = LoggerFactory.getLogger(LibraryModulesSchemas.class);
92     private static final Pattern DATE_PATTERN = Pattern.compile("(\\d{4}-\\d{2}-\\d{2})");
93     private static final EffectiveModelContext LIBRARY_CONTEXT = BindingRuntimeHelpers.createEffectiveModel(
94         YangLibrary.class);
95     private static final Inference MODULES_STATE_INFERENCE =
96         SchemaInferenceStack.ofDataTreePath(LIBRARY_CONTEXT, ModulesState.QNAME).toInference();
97
98     // FIXME: this is legacy RFC7895, add support for RFC8525 containers, too
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 @NonNull 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 = new SourceIdentifier(entry.getKey().getLocalName(),
130                 entry.getKey().getRevision().map(Revision::toString).orElse(null));
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                 connection.setRequestProperty("Authorization",
152                     "Basic " + Base64.getEncoder().encodeToString(userpass.getBytes(StandardCharsets.UTF_8)));
153             }
154
155             return createFromURLConnection(connection);
156
157         } catch (final IOException e) {
158             LOG.warn("Unable to download yang library from {}", url, e);
159             return new LibraryModulesSchemas(ImmutableMap.of());
160         }
161     }
162
163
164     public static LibraryModulesSchemas create(final NetconfDeviceRpc deviceRpc, final RemoteDeviceId deviceId) {
165         final DOMRpcResult moduleListNodeResult;
166         try {
167             moduleListNodeResult =
168                     deviceRpc.invokeRpc(NETCONF_GET_QNAME, GET_MODULES_STATE_MODULE_LIST_RPC).get();
169         } catch (final InterruptedException e) {
170             Thread.currentThread().interrupt();
171             throw new IllegalStateException(deviceId + ": Interrupted while waiting for response to "
172                     + MODULES_STATE_MODULE_LIST, e);
173         } catch (final ExecutionException e) {
174             LOG.warn("{}: Unable to detect available schemas, get to {} failed", deviceId,
175                     MODULES_STATE_MODULE_LIST, e);
176             return new LibraryModulesSchemas(ImmutableMap.of());
177         }
178
179         if (!moduleListNodeResult.errors().isEmpty()) {
180             LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}",
181                     deviceId, MODULES_STATE_MODULE_LIST, moduleListNodeResult.errors());
182             return new LibraryModulesSchemas(ImmutableMap.of());
183         }
184
185         final Optional<DataContainerChild> modulesStateNode =
186                 findModulesStateNode(moduleListNodeResult.value());
187         if (modulesStateNode.isPresent()) {
188             final DataContainerChild node = modulesStateNode.orElseThrow();
189             checkState(node instanceof ContainerNode, "Expecting container containing schemas, but was %s", node);
190             return create((ContainerNode) node);
191         }
192
193         LOG.warn("{}: Unable to detect available schemas, get to {} was empty", deviceId, MODULES_STATE_NID);
194         return new LibraryModulesSchemas(ImmutableMap.of());
195     }
196
197     private static LibraryModulesSchemas create(final ContainerNode modulesStateNode) {
198         final Optional<DataContainerChild> moduleListNode = modulesStateNode.findChildByArg(MODULE_NID);
199         checkState(moduleListNode.isPresent(), "Unable to find list: %s in %s", MODULE_NID, modulesStateNode);
200         final DataContainerChild node = moduleListNode.orElseThrow();
201         checkState(node instanceof MapNode, "Unexpected structure for container: %s in : %s. Expecting a list",
202             MODULE_NID, modulesStateNode);
203
204         final MapNode moduleList = (MapNode) node;
205         final Collection<MapEntryNode> modules = moduleList.body();
206         final ImmutableMap.Builder<QName, URL> schemasMapping = ImmutableMap.builderWithExpectedSize(modules.size());
207         for (final MapEntryNode moduleNode : modules) {
208             final Entry<QName, URL> entry = createFromEntry(moduleNode);
209             if (entry != null) {
210                 schemasMapping.put(entry);
211             }
212         }
213
214         return new LibraryModulesSchemas(schemasMapping.build());
215     }
216
217     /**
218      * Resolves URLs with YANG schema resources from modules-state.
219      * @param url URL pointing to yang library
220      * @return Resolved URLs with YANG schema resources for all yang modules from yang library
221      */
222     public static LibraryModulesSchemas create(final String url) {
223         final URLConnection connection;
224         try {
225             connection = new URL(requireNonNull(url)).openConnection();
226         } catch (final IOException e) {
227             LOG.warn("Unable to download yang library from {}", url, e);
228             return new LibraryModulesSchemas(ImmutableMap.of());
229         }
230
231         if (connection instanceof HttpURLConnection) {
232             connection.setRequestProperty("Accept", "application/xml");
233         }
234         return createFromURLConnection(connection);
235     }
236
237     private static Optional<DataContainerChild> findModulesStateNode(final NormalizedNode result) {
238         if (result == null) {
239             return Optional.empty();
240         }
241         final Optional<DataContainerChild> dataNode = ((DataContainerNode) result).findChildByArg(NETCONF_DATA_NODEID);
242         if (dataNode.isEmpty()) {
243             return Optional.empty();
244         }
245
246         return ((DataContainerNode) dataNode.orElseThrow()).findChildByArg(MODULES_STATE_NID);
247     }
248
249     private static LibraryModulesSchemas createFromURLConnection(final URLConnection connection) {
250
251         String contentType = connection.getContentType();
252
253         // TODO try to guess Json also from intput stream
254         if (guessJsonFromFileName(connection.getURL().getFile())) {
255             contentType = "application/json";
256         }
257
258         requireNonNull(contentType, "Content type unknown");
259         checkState(contentType.equals("application/json") || contentType.equals("application/xml"),
260                 "Only XML and JSON types are supported.");
261
262         Optional<NormalizedNode> optionalModulesStateNode = Optional.empty();
263         try (InputStream in = connection.getInputStream()) {
264             optionalModulesStateNode = contentType.equals("application/json") ? readJson(in) : readXml(in);
265         } catch (final IOException e) {
266             LOG.warn("Unable to download yang library from {}", connection.getURL(), e);
267         }
268
269         if (optionalModulesStateNode.isEmpty()) {
270             return new LibraryModulesSchemas(ImmutableMap.of());
271         }
272
273         final NormalizedNode modulesStateNode = optionalModulesStateNode.orElseThrow();
274         checkState(modulesStateNode instanceof ContainerNode, "Expecting container containing module list, but was %s",
275             modulesStateNode);
276         final ContainerNode modulesState = (ContainerNode) modulesStateNode;
277         final NodeIdentifier nodeName = modulesState.name();
278         checkState(MODULES_STATE_NID.equals(nodeName), "Wrong container identifier %s", nodeName);
279
280         return create((ContainerNode) modulesStateNode);
281     }
282
283     private static boolean guessJsonFromFileName(final String fileName) {
284         final int i = fileName.lastIndexOf('.');
285         return i != 1 && ".json".equalsIgnoreCase(fileName.substring(i));
286     }
287
288     private static Optional<NormalizedNode> readJson(final InputStream in) {
289         final NormalizationResultHolder resultHolder = new NormalizationResultHolder();
290         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
291
292         final JsonParserStream jsonParser = JsonParserStream.create(writer, JSON_CODECS);
293         final JsonReader reader = new JsonReader(new InputStreamReader(in, Charset.defaultCharset()));
294
295         jsonParser.parse(reader);
296
297         final NormalizationResult result = resultHolder.result();
298         return result == null ? Optional.empty() : Optional.of(result.data());
299     }
300
301     private static Optional<NormalizedNode> readXml(final InputStream in) {
302         try {
303             final DocumentBuilder docBuilder = UntrustedXML.newDocumentBuilder();
304
305             final Document read = docBuilder.parse(in);
306             final Document doc = docBuilder.newDocument();
307             final Element rootElement = doc.createElementNS(ModulesState.QNAME.getNamespace().toString(),
308                 ModulesState.QNAME.getLocalName());
309             doc.appendChild(rootElement);
310
311             // FIXME: also namespace?!
312             final var revisions = read.getElementsByTagName("revision");
313
314             for (int i = 0, length = revisions.getLength(); i < length; i++) {
315                 final String revision = revisions.item(i).getTextContent();
316                 if (DATE_PATTERN.matcher(revision).find() || revision.isEmpty()) {
317                     final Node module = doc.importNode(read.getElementsByTagName("module").item(i), true);
318                     rootElement.appendChild(module);
319                 } else {
320                     LOG.warn("Xml contains wrong revision - {} - on module {}", revision,
321                             read.getElementsByTagName("module").item(i).getTextContent());
322                 }
323             }
324
325             final NormalizationResultHolder resultHolder = new NormalizationResultHolder();
326             final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
327             final XmlParserStream xmlParser = XmlParserStream.create(writer, MODULES_STATE_INFERENCE);
328             xmlParser.traverse(new DOMSource(doc.getDocumentElement()));
329             return Optional.of(resultHolder.getResult().data());
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         final QName moduleNodeId = moduleNode.name().getNodeType();
339         checkArgument(moduleNodeId.equals(Module.QNAME), "Wrong QName %s", moduleNodeId);
340
341         final String moduleName = getSingleChildNodeValue(moduleNode, NAME_NID).orElseThrow();
342         final Optional<String> revision = getSingleChildNodeValue(moduleNode, REVISION_NID);
343         if (revision.isPresent()) {
344             final var rev = revision.orElseThrow();
345             if (!Revision.STRING_FORMAT_PATTERN.matcher(rev).matches()) {
346                 LOG.warn("Skipping library schema for {}. Revision {} is in wrong format.", moduleNode, rev);
347                 return null;
348             }
349         }
350
351         // FIXME leaf schema with url that represents the yang schema resource for this module is not mandatory
352         // don't fail if schema node is not present, just skip the entry or add some default URL
353         final Optional<String> schemaUriAsString = getSingleChildNodeValue(moduleNode, SCHEMA_NID);
354         final String moduleNameSpace = getSingleChildNodeValue(moduleNode, NAMESPACE_NID).orElseThrow();
355
356         final QName moduleQName = revision.isPresent()
357                 ? QName.create(moduleNameSpace, revision.orElseThrow(), moduleName)
358                 : QName.create(XMLNamespace.of(moduleNameSpace), moduleName);
359
360         try {
361             return Map.entry(moduleQName, new URL(schemaUriAsString.orElseThrow()));
362         } catch (final MalformedURLException e) {
363             LOG.warn("Skipping library schema for {}. URL {} representing yang schema resource is not valid",
364                     moduleNode, schemaUriAsString.orElseThrow());
365             return null;
366         }
367     }
368
369     private static Optional<String> getSingleChildNodeValue(final DataContainerNode schemaNode,
370                                                             final NodeIdentifier childNodeId) {
371         final Optional<DataContainerChild> node = schemaNode.findChildByArg(childNodeId);
372         checkArgument(node.isPresent(), "Child node %s not present", childNodeId.getNodeType());
373         return getValueOfSimpleNode(node.orElseThrow());
374     }
375
376     private static Optional<String> getValueOfSimpleNode(final NormalizedNode node) {
377         final String valueStr = node.body().toString();
378         return Strings.isNullOrEmpty(valueStr) ? Optional.empty() : Optional.of(valueStr.trim());
379     }
380
381     @Override
382     public Set<QName> getAvailableYangSchemasQNames() {
383         return null;
384     }
385 }