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