Bump upstream versions
[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 org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_DATA_NODEID;
14 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_NODEID;
15 import static org.opendaylight.netconf.sal.connect.netconf.util.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.AbstractMap.SimpleImmutableEntry;
31 import java.util.Base64;
32 import java.util.Collection;
33 import java.util.HashMap;
34 import java.util.Map;
35 import java.util.Map.Entry;
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.eclipse.jdt.annotation.NonNull;
44 import org.eclipse.jdt.annotation.Nullable;
45 import org.opendaylight.mdsal.binding.runtime.spi.BindingRuntimeHelpers;
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.rev190104.ModulesState;
52 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.YangLibrary;
53 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.module.list.Module;
54 import org.opendaylight.yangtools.util.xml.UntrustedXML;
55 import org.opendaylight.yangtools.yang.common.QName;
56 import org.opendaylight.yangtools.yang.common.Revision;
57 import org.opendaylight.yangtools.yang.common.XMLNamespace;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
60 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
62 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
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.NormalizedNodeResult;
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.getErrors().isEmpty() == false) {
180             LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}",
181                     deviceId, MODULES_STATE_MODULE_LIST, moduleListNodeResult.getErrors());
182             return new LibraryModulesSchemas(ImmutableMap.of());
183         }
184
185         final Optional<DataContainerChild> modulesStateNode =
186                 findModulesStateNode(moduleListNodeResult.getResult());
187         if (modulesStateNode.isPresent()) {
188             final DataContainerChild node = modulesStateNode.get();
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.get();
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.get()).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.get();
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.getIdentifier();
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 NormalizedNodeResult resultHolder = new NormalizedNodeResult();
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         return resultHolder.isFinished() ? Optional.of(resultHolder.getResult()) : Optional.empty();
298     }
299
300     private static Optional<NormalizedNode> readXml(final InputStream in) {
301         try {
302             final DocumentBuilder docBuilder = UntrustedXML.newDocumentBuilder();
303
304             final Document read = docBuilder.parse(in);
305             final Document doc = docBuilder.newDocument();
306             final Element rootElement = doc.createElementNS("urn:ietf:params:xml:ns:yang:ietf-yang-library",
307                     "modules");
308             doc.appendChild(rootElement);
309
310             for (int i = 0; i < read.getElementsByTagName("revision").getLength(); i++) {
311                 final String revision = read.getElementsByTagName("revision").item(i).getTextContent();
312                 if (DATE_PATTERN.matcher(revision).find() || revision.isEmpty()) {
313                     final Node module = doc.importNode(read.getElementsByTagName("module").item(i), true);
314                     rootElement.appendChild(module);
315                 } else {
316                     LOG.warn("Xml contains wrong revision - {} - on module {}", revision,
317                             read.getElementsByTagName("module").item(i).getTextContent());
318                 }
319             }
320
321             final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
322             final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
323             final XmlParserStream xmlParser = XmlParserStream.create(writer, MODULES_STATE_INFERENCE);
324             xmlParser.traverse(new DOMSource(doc.getDocumentElement()));
325             return Optional.of(resultHolder.getResult());
326         } catch (XMLStreamException | URISyntaxException | IOException | SAXException e) {
327             LOG.warn("Unable to parse yang library xml content", e);
328         }
329
330         return Optional.empty();
331     }
332
333     private static @Nullable Entry<QName, URL> createFromEntry(final MapEntryNode moduleNode) {
334         final QName moduleNodeId = moduleNode.getIdentifier().getNodeType();
335         checkArgument(moduleNodeId.equals(Module.QNAME), "Wrong QName %s", moduleNodeId);
336
337         final String moduleName = getSingleChildNodeValue(moduleNode, NAME_NID).get();
338         final Optional<String> revision = getSingleChildNodeValue(moduleNode, REVISION_NID);
339         if (revision.isPresent()) {
340             if (!Revision.STRING_FORMAT_PATTERN.matcher(revision.get()).matches()) {
341                 LOG.warn("Skipping library schema for {}. Revision {} is in wrong format.", moduleNode, revision.get());
342                 return null;
343             }
344         }
345
346         // FIXME leaf schema with url that represents the yang schema resource for this module is not mandatory
347         // don't fail if schema node is not present, just skip the entry or add some default URL
348         final Optional<String> schemaUriAsString = getSingleChildNodeValue(moduleNode, SCHEMA_NID);
349         final String moduleNameSpace = getSingleChildNodeValue(moduleNode, NAMESPACE_NID).get();
350
351         final QName moduleQName = revision.isPresent()
352                 ? QName.create(moduleNameSpace, revision.get(), moduleName)
353                 : QName.create(XMLNamespace.of(moduleNameSpace), moduleName);
354
355         try {
356             return new SimpleImmutableEntry<>(moduleQName, new URL(schemaUriAsString.get()));
357         } catch (final MalformedURLException e) {
358             LOG.warn("Skipping library schema for {}. URL {} representing yang schema resource is not valid",
359                     moduleNode, schemaUriAsString.get());
360             return null;
361         }
362     }
363
364     private static Optional<String> getSingleChildNodeValue(final DataContainerNode schemaNode,
365                                                             final NodeIdentifier childNodeId) {
366         final Optional<DataContainerChild> node = schemaNode.findChildByArg(childNodeId);
367         checkArgument(node.isPresent(), "Child node %s not present", childNodeId.getNodeType());
368         return getValueOfSimpleNode(node.get());
369     }
370
371     private static Optional<String> getValueOfSimpleNode(final NormalizedNode node) {
372         final String valueStr = node.body().toString();
373         return Strings.isNullOrEmpty(valueStr) ? Optional.empty() : Optional.of(valueStr.trim());
374     }
375
376     @Override
377     public Set<QName> getAvailableYangSchemasQNames() {
378         return null;
379     }
380 }