Schema determination is asynchronous
[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.yang.svc.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.YangModuleInfoImpl.qnameOf;
16
17 import com.google.common.base.Strings;
18 import com.google.common.collect.ImmutableMap;
19 import com.google.common.util.concurrent.FutureCallback;
20 import com.google.common.util.concurrent.Futures;
21 import com.google.common.util.concurrent.ListenableFuture;
22 import com.google.common.util.concurrent.MoreExecutors;
23 import com.google.common.util.concurrent.SettableFuture;
24 import com.google.gson.stream.JsonReader;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.InputStreamReader;
28 import java.net.HttpURLConnection;
29 import java.net.MalformedURLException;
30 import java.net.URL;
31 import java.net.URLConnection;
32 import java.nio.charset.Charset;
33 import java.nio.charset.StandardCharsets;
34 import java.util.Base64;
35 import java.util.HashMap;
36 import java.util.Map;
37 import java.util.Map.Entry;
38 import java.util.Optional;
39 import java.util.Set;
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.NonNull;
45 import org.eclipse.jdt.annotation.Nullable;
46 import org.opendaylight.mdsal.binding.runtime.spi.BindingRuntimeHelpers;
47 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
48 import org.opendaylight.netconf.client.mdsal.api.NetconfDeviceSchemas;
49 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceId;
50 import org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil;
51 import org.opendaylight.netconf.client.mdsal.spi.NetconfDeviceRpc;
52 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.Get;
53 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.ModulesState;
54 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.YangLibrary;
55 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.module.list.Module;
56 import org.opendaylight.yangtools.util.xml.UntrustedXML;
57 import org.opendaylight.yangtools.yang.common.ErrorSeverity;
58 import org.opendaylight.yangtools.yang.common.OperationFailedException;
59 import org.opendaylight.yangtools.yang.common.QName;
60 import org.opendaylight.yangtools.yang.common.Revision;
61 import org.opendaylight.yangtools.yang.common.XMLNamespace;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
64 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
66 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizationResult;
71 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
72 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactory;
73 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
74 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
75 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
76 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
77 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizationResultHolder;
78 import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
79 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
80 import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
81 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
82 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
85 import org.w3c.dom.Document;
86 import org.w3c.dom.Element;
87 import org.w3c.dom.Node;
88 import org.xml.sax.SAXException;
89
90 /**
91  * Holds URLs with YANG schema resources for all yang modules reported in
92  * ietf-netconf-yang-library/modules-state/modules node.
93  */
94 public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
95     private static final Logger LOG = LoggerFactory.getLogger(LibraryModulesSchemas.class);
96     private static final Pattern DATE_PATTERN = Pattern.compile("(\\d{4}-\\d{2}-\\d{2})");
97     private static final EffectiveModelContext LIBRARY_CONTEXT = BindingRuntimeHelpers.createEffectiveModel(
98         YangLibrary.class);
99     private static final Inference MODULES_STATE_INFERENCE =
100         SchemaInferenceStack.ofDataTreePath(LIBRARY_CONTEXT, ModulesState.QNAME).toInference();
101
102     // FIXME: this is legacy RFC7895, add support for RFC8525 containers, too
103     private static final NodeIdentifier MODULES_STATE_NID = NodeIdentifier.create(ModulesState.QNAME);
104     private static final NodeIdentifier MODULE_NID = NodeIdentifier.create(Module.QNAME);
105     private static final NodeIdentifier NAME_NID = NodeIdentifier.create(qnameOf("name"));
106     private static final NodeIdentifier REVISION_NID = NodeIdentifier.create(qnameOf("revision"));
107     private static final NodeIdentifier SCHEMA_NID = NodeIdentifier.create(qnameOf("schema"));
108     private static final NodeIdentifier NAMESPACE_NID = NodeIdentifier.create(qnameOf("namespace"));
109
110     private static final JSONCodecFactory JSON_CODECS = JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02
111             .getShared(LIBRARY_CONTEXT);
112
113     private static final YangInstanceIdentifier MODULES_STATE_MODULE_LIST =
114             YangInstanceIdentifier.of(MODULES_STATE_NID, MODULE_NID);
115
116     private static final @NonNull ContainerNode GET_MODULES_STATE_MODULE_LIST_RPC = ImmutableNodes.newContainerBuilder()
117             .withNodeIdentifier(NETCONF_GET_NODEID)
118             .withChild(NetconfMessageTransformUtil.toFilterStructure(MODULES_STATE_MODULE_LIST, LIBRARY_CONTEXT))
119             .build();
120     private static final @NonNull LibraryModulesSchemas EMPTY = new LibraryModulesSchemas(ImmutableMap.of());
121
122     private final ImmutableMap<QName, URL> availableModels;
123
124     private LibraryModulesSchemas(final ImmutableMap<QName, URL> availableModels) {
125         this.availableModels = requireNonNull(availableModels);
126     }
127
128     // FIXME: this should work on NetconfRpcService
129     public static ListenableFuture<LibraryModulesSchemas> forDevice(final NetconfDeviceRpc deviceRpc,
130             final RemoteDeviceId deviceId) {
131         final var future = SettableFuture.<LibraryModulesSchemas>create();
132         Futures.addCallback(deviceRpc.invokeNetconf(Get.QNAME, GET_MODULES_STATE_MODULE_LIST_RPC),
133             new FutureCallback<DOMRpcResult>() {
134                 @Override
135                 public void onSuccess(final DOMRpcResult result) {
136                     onGetModulesStateResult(future, deviceId, result);
137                 }
138
139                 @Override
140                 public void onFailure(final Throwable cause) {
141                     // debug, because we expect this error to be reported by caller
142                     LOG.debug("{}: Unable to detect available schemas", deviceId, cause);
143                     future.setException(cause);
144                 }
145             }, MoreExecutors.directExecutor());
146         return future;
147     }
148
149     private static void onGetModulesStateResult(final SettableFuture<LibraryModulesSchemas> future,
150             final RemoteDeviceId deviceId, final DOMRpcResult result) {
151         // Two-pass error reporting: first check if there is a hard error, then log any remaining warnings
152         final var errors = result.errors();
153         if (errors.stream().anyMatch(error -> error.getSeverity() == ErrorSeverity.ERROR)) {
154             // FIXME: a good exception, which can report the contents of errors?
155             future.setException(new OperationFailedException("Failed to get modules-state", errors));
156             return;
157         }
158         for (var error : errors) {
159             LOG.info("{}: schema retrieval warning: {}", deviceId, error);
160         }
161
162         final var value = result.value();
163         if (value == null) {
164             LOG.warn("{}: missing RPC output", deviceId);
165             future.set(EMPTY);
166             return;
167         }
168         final var data = value.childByArg(NETCONF_DATA_NODEID);
169         if (data == null) {
170             LOG.warn("{}: missing RPC data", deviceId);
171             future.set(EMPTY);
172             return;
173         }
174         // FIXME: right: this was never implemented correctly, as the origical code always produces CCE because it
175         //        interpreted 'data' anyxml as a DataContainerNode!
176         future.setException(new UnsupportedOperationException("Missing normalization logic for " + data.prettyTree()));
177     }
178
179     public Map<SourceIdentifier, URL> getAvailableModels() {
180         final var result = new HashMap<SourceIdentifier, URL>();
181         for (var entry : availableModels.entrySet()) {
182             final var sId = new SourceIdentifier(entry.getKey().getLocalName(),
183                 entry.getKey().getRevision().map(Revision::toString).orElse(null));
184             result.put(sId, entry.getValue());
185         }
186
187         return result;
188     }
189
190     /**
191      * Resolves URLs with YANG schema resources from modules-state. Uses basic http authenticaiton
192      *
193      * @param url URL pointing to yang library
194      * @return Resolved URLs with YANG schema resources for all yang modules from yang library
195      */
196     public static LibraryModulesSchemas create(final String url, final String username, final String password) {
197         try {
198             final URL urlConnection = new URL(requireNonNull(url));
199             final URLConnection connection = urlConnection.openConnection();
200
201             if (connection instanceof HttpURLConnection) {
202                 connection.setRequestProperty("Accept", "application/xml");
203                 final String userpass = username + ":" + password;
204                 connection.setRequestProperty("Authorization",
205                     "Basic " + Base64.getEncoder().encodeToString(userpass.getBytes(StandardCharsets.UTF_8)));
206             }
207
208             return createFromURLConnection(connection);
209
210         } catch (final IOException e) {
211             LOG.warn("Unable to download yang library from {}", url, e);
212             return new LibraryModulesSchemas(ImmutableMap.of());
213         }
214     }
215
216     private static LibraryModulesSchemas create(final ContainerNode modulesStateNode) {
217         final Optional<DataContainerChild> moduleListNode = modulesStateNode.findChildByArg(MODULE_NID);
218         checkState(moduleListNode.isPresent(), "Unable to find list: %s in %s", MODULE_NID, modulesStateNode);
219         final var node = moduleListNode.orElseThrow();
220         checkState(node instanceof MapNode, "Unexpected structure for container: %s in : %s. Expecting a list",
221             MODULE_NID, modulesStateNode);
222
223         final var moduleList = (MapNode) node;
224         final var builder = ImmutableMap.<QName, URL>builderWithExpectedSize(moduleList.size());
225         for (var moduleNode : moduleList.body()) {
226             final var entry = createFromEntry(moduleNode);
227             if (entry != null) {
228                 builder.put(entry);
229             }
230         }
231
232         return new LibraryModulesSchemas(builder.build());
233     }
234
235     /**
236      * Resolves URLs with YANG schema resources from modules-state.
237      * @param url URL pointing to yang library
238      * @return Resolved URLs with YANG schema resources for all yang modules from yang library
239      */
240     public static LibraryModulesSchemas create(final String url) {
241         final URLConnection connection;
242         try {
243             connection = new URL(requireNonNull(url)).openConnection();
244         } catch (final IOException e) {
245             LOG.warn("Unable to download yang library from {}", url, e);
246             return new LibraryModulesSchemas(ImmutableMap.of());
247         }
248
249         if (connection instanceof HttpURLConnection) {
250             connection.setRequestProperty("Accept", "application/xml");
251         }
252         return createFromURLConnection(connection);
253     }
254
255     private static LibraryModulesSchemas createFromURLConnection(final URLConnection connection) {
256
257         String contentType = connection.getContentType();
258
259         // TODO try to guess Json also from intput stream
260         if (guessJsonFromFileName(connection.getURL().getFile())) {
261             contentType = "application/json";
262         }
263
264         requireNonNull(contentType, "Content type unknown");
265         checkState(contentType.equals("application/json") || contentType.equals("application/xml"),
266                 "Only XML and JSON types are supported.");
267
268         Optional<NormalizedNode> optionalModulesStateNode = Optional.empty();
269         try (InputStream in = connection.getInputStream()) {
270             optionalModulesStateNode = contentType.equals("application/json") ? readJson(in) : readXml(in);
271         } catch (final IOException e) {
272             LOG.warn("Unable to download yang library from {}", connection.getURL(), e);
273         }
274
275         if (optionalModulesStateNode.isEmpty()) {
276             return new LibraryModulesSchemas(ImmutableMap.of());
277         }
278
279         final NormalizedNode modulesStateNode = optionalModulesStateNode.orElseThrow();
280         checkState(modulesStateNode instanceof ContainerNode, "Expecting container containing module list, but was %s",
281             modulesStateNode);
282         final ContainerNode modulesState = (ContainerNode) modulesStateNode;
283         final NodeIdentifier nodeName = modulesState.name();
284         checkState(MODULES_STATE_NID.equals(nodeName), "Wrong container identifier %s", nodeName);
285
286         return create((ContainerNode) modulesStateNode);
287     }
288
289     private static boolean guessJsonFromFileName(final String fileName) {
290         final int i = fileName.lastIndexOf('.');
291         return i != 1 && ".json".equalsIgnoreCase(fileName.substring(i));
292     }
293
294     private static Optional<NormalizedNode> readJson(final InputStream in) {
295         final NormalizationResultHolder resultHolder = new NormalizationResultHolder();
296         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
297
298         final JsonParserStream jsonParser = JsonParserStream.create(writer, JSON_CODECS);
299         final JsonReader reader = new JsonReader(new InputStreamReader(in, Charset.defaultCharset()));
300
301         jsonParser.parse(reader);
302
303         final NormalizationResult<?> result = resultHolder.result();
304         return result == null ? Optional.empty() : Optional.of(result.data());
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(ModulesState.QNAME.getNamespace().toString(),
314                 ModulesState.QNAME.getLocalName());
315             doc.appendChild(rootElement);
316
317             // FIXME: also namespace?!
318             final var revisions = read.getElementsByTagName("revision");
319
320             for (int i = 0, length = revisions.getLength(); i < length; i++) {
321                 final String revision = revisions.item(i).getTextContent();
322                 if (DATE_PATTERN.matcher(revision).find() || revision.isEmpty()) {
323                     final Node module = doc.importNode(read.getElementsByTagName("module").item(i), true);
324                     rootElement.appendChild(module);
325                 } else {
326                     LOG.warn("Xml contains wrong revision - {} - on module {}", revision,
327                             read.getElementsByTagName("module").item(i).getTextContent());
328                 }
329             }
330
331             final NormalizationResultHolder resultHolder = new NormalizationResultHolder();
332             final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
333             final XmlParserStream xmlParser = XmlParserStream.create(writer, MODULES_STATE_INFERENCE);
334             xmlParser.traverse(new DOMSource(doc.getDocumentElement()));
335             return Optional.of(resultHolder.getResult().data());
336         } catch (XMLStreamException | IOException | SAXException e) {
337             LOG.warn("Unable to parse yang library xml content", e);
338         }
339
340         return Optional.empty();
341     }
342
343     private static @Nullable Entry<QName, URL> createFromEntry(final MapEntryNode moduleNode) {
344         final QName moduleNodeId = moduleNode.name().getNodeType();
345         checkArgument(moduleNodeId.equals(Module.QNAME), "Wrong QName %s", moduleNodeId);
346
347         final String moduleName = getSingleChildNodeValue(moduleNode, NAME_NID).orElseThrow();
348         final Optional<String> revision = getSingleChildNodeValue(moduleNode, REVISION_NID);
349         if (revision.isPresent()) {
350             final var rev = revision.orElseThrow();
351             if (!Revision.STRING_FORMAT_PATTERN.matcher(rev).matches()) {
352                 LOG.warn("Skipping library schema for {}. Revision {} is in wrong format.", moduleNode, rev);
353                 return null;
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         final Optional<String> schemaUriAsString = getSingleChildNodeValue(moduleNode, SCHEMA_NID);
360         final String moduleNameSpace = getSingleChildNodeValue(moduleNode, NAMESPACE_NID).orElseThrow();
361
362         final QName moduleQName = revision.isPresent()
363                 ? QName.create(moduleNameSpace, revision.orElseThrow(), moduleName)
364                 : QName.create(XMLNamespace.of(moduleNameSpace), moduleName);
365
366         try {
367             return Map.entry(moduleQName, new URL(schemaUriAsString.orElseThrow()));
368         } catch (final MalformedURLException e) {
369             LOG.warn("Skipping library schema for {}. URL {} representing yang schema resource is not valid",
370                     moduleNode, schemaUriAsString.orElseThrow());
371             return null;
372         }
373     }
374
375     private static Optional<String> getSingleChildNodeValue(final DataContainerNode schemaNode,
376                                                             final NodeIdentifier childNodeId) {
377         final Optional<DataContainerChild> node = schemaNode.findChildByArg(childNodeId);
378         checkArgument(node.isPresent(), "Child node %s not present", childNodeId.getNodeType());
379         return getValueOfSimpleNode(node.orElseThrow());
380     }
381
382     private static Optional<String> getValueOfSimpleNode(final NormalizedNode node) {
383         final String valueStr = node.body().toString();
384         return Strings.isNullOrEmpty(valueStr) ? Optional.empty() : Optional.of(valueStr.trim());
385     }
386
387     @Override
388     public Set<QName> getAvailableYangSchemasQNames() {
389         return null;
390     }
391 }