Merge "Bug 5824: Migrate netconf to the new XML parser"
[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 javax.xml.bind.DatatypeConverter.printBase64Binary;
11 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_DATA_QNAME;
12 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_QNAME;
13 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toId;
14 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath;
15
16 import com.google.common.base.Optional;
17 import com.google.common.base.Preconditions;
18 import com.google.common.base.Strings;
19 import com.google.common.collect.ImmutableMap;
20 import com.google.common.collect.Maps;
21 import com.google.gson.stream.JsonReader;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.InputStreamReader;
25 import java.io.StringReader;
26 import java.net.HttpURLConnection;
27 import java.net.MalformedURLException;
28 import java.net.URI;
29 import java.net.URL;
30 import java.net.URLConnection;
31 import java.util.AbstractMap;
32 import java.util.Collections;
33 import java.util.Map;
34 import java.util.Set;
35 import java.util.concurrent.ExecutionException;
36 import java.util.regex.Pattern;
37 import javax.xml.parsers.DocumentBuilder;
38 import org.opendaylight.controller.config.util.xml.XmlUtil;
39 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
40 import org.opendaylight.mdsal.binding.generator.impl.ModuleInfoBackedContext;
41 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemas;
42 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
43 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
44 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.ModulesState;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.module.list.Module;
47 import org.opendaylight.yangtools.util.xml.UntrustedXML;
48 import org.opendaylight.yangtools.yang.common.QName;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
52 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
57 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
58 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
59 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
60 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
61 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
62 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
63 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
64 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
67 import org.w3c.dom.Document;
68 import org.w3c.dom.Element;
69 import org.w3c.dom.Node;
70
71 /**
72  * Holds URLs with YANG schema resources for all yang modules reported in
73  * ietf-netconf-yang-library/modules-state/modules node.
74  */
75 public class LibraryModulesSchemas implements NetconfDeviceSchemas {
76
77     private static final Logger LOG = LoggerFactory.getLogger(LibraryModulesSchemas.class);
78     private static final Pattern DATE_PATTERN = Pattern.compile("(\\d{4}-\\d{2}-\\d{2})");
79     private static final SchemaContext LIBRARY_CONTEXT;
80
81     static {
82         final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
83         moduleInfoBackedContext.registerModuleInfo(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang
84                 .library.rev160409.$YangModuleInfoImpl.getInstance());
85         LIBRARY_CONTEXT = moduleInfoBackedContext.tryToCreateSchemaContext().get();
86     }
87
88     private final Map<QName, URL> availableModels;
89
90     private static final YangInstanceIdentifier MODULES_STATE_MODULE_LIST =
91             YangInstanceIdentifier.builder().node(ModulesState.QNAME).node(Module.QNAME).build();
92
93     private static final ContainerNode GET_MODULES_STATE_MODULE_LIST_RPC;
94
95     static {
96         final DataContainerChild<?, ?> filter =
97                 NetconfMessageTransformUtil.toFilterStructure(MODULES_STATE_MODULE_LIST, LIBRARY_CONTEXT);
98         GET_MODULES_STATE_MODULE_LIST_RPC =
99                 Builders.containerBuilder().withNodeIdentifier(toId(NETCONF_GET_QNAME)).withChild(filter).build();
100     }
101
102     private LibraryModulesSchemas(final Map<QName, URL> availableModels) {
103         this.availableModels = availableModels;
104     }
105
106     public Map<SourceIdentifier, URL> getAvailableModels() {
107         final Map<SourceIdentifier, URL> result = Maps.newHashMap();
108         for (final Map.Entry<QName, URL> entry : availableModels.entrySet()) {
109             final SourceIdentifier sId = RevisionSourceIdentifier
110                 .create(entry.getKey().getLocalName(), Optional.fromNullable(entry.getKey().getFormattedRevision()));
111             result.put(sId, entry.getValue());
112         }
113
114         return result;
115     }
116
117
118     /**
119      * Resolves URLs with YANG schema resources from modules-state. Uses basic http authenticaiton
120      *
121      * @param url URL pointing to yang library
122      * @return Resolved URLs with YANG schema resources for all yang modules from yang library
123      */
124     public static LibraryModulesSchemas create(final String url, final String username, final String password) {
125         Preconditions.checkNotNull(url);
126         try {
127             final URL urlConnection = new URL(url);
128             final URLConnection connection = urlConnection.openConnection();
129
130             if (connection instanceof HttpURLConnection) {
131                 connection.setRequestProperty("Accept", "application/xml");
132                 final String userpass = username + ":" + password;
133                 final String basicAuth = "Basic " + printBase64Binary(userpass.getBytes());
134
135                 connection.setRequestProperty("Authorization", basicAuth);
136             }
137
138             return createFromURLConnection(connection);
139
140         } catch (final IOException e) {
141             LOG.warn("Unable to download yang library from {}", url, e);
142             return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
143         }
144     }
145
146
147     public static LibraryModulesSchemas create(final NetconfDeviceRpc deviceRpc, final RemoteDeviceId deviceId) {
148         final DOMRpcResult moduleListNodeResult;
149         try {
150             moduleListNodeResult =
151                     deviceRpc.invokeRpc(toPath(NETCONF_GET_QNAME), GET_MODULES_STATE_MODULE_LIST_RPC).get();
152         } catch (final InterruptedException e) {
153             Thread.currentThread().interrupt();
154             throw new RuntimeException(deviceId + ": Interrupted while waiting for response to "
155                     + MODULES_STATE_MODULE_LIST, e);
156         } catch (final ExecutionException e) {
157             LOG.warn("{}: Unable to detect available schemas, get to {} failed", deviceId,
158                     MODULES_STATE_MODULE_LIST, e);
159             return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
160         }
161
162         if (moduleListNodeResult.getErrors().isEmpty() == false) {
163             LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}",
164                     deviceId, MODULES_STATE_MODULE_LIST, moduleListNodeResult.getErrors());
165             return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
166         }
167
168
169         final Optional<? extends NormalizedNode<?, ?>> modulesStateNode =
170                 findModulesStateNode(moduleListNodeResult.getResult());
171         if (modulesStateNode.isPresent()) {
172             Preconditions.checkState(modulesStateNode.get() instanceof ContainerNode,
173                     "Expecting container containing schemas, but was %s", modulesStateNode.get());
174             return create(((ContainerNode) modulesStateNode.get()));
175         } else {
176             LOG.warn("{}: Unable to detect available schemas, get to {} was empty", deviceId, toId(ModulesState.QNAME));
177             return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
178         }
179     }
180
181     private static LibraryModulesSchemas create(final ContainerNode modulesStateNode) {
182         final YangInstanceIdentifier.NodeIdentifier moduleListNodeId =
183                 new YangInstanceIdentifier.NodeIdentifier(Module.QNAME);
184         final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> moduleListNode =
185                 modulesStateNode.getChild(moduleListNodeId);
186         Preconditions.checkState(moduleListNode.isPresent(),
187                 "Unable to find list: %s in %s", moduleListNodeId, modulesStateNode);
188         Preconditions.checkState(moduleListNode.get() instanceof MapNode,
189                 "Unexpected structure for container: %s in : %s. Expecting a list",
190                 moduleListNodeId, modulesStateNode);
191
192         final ImmutableMap.Builder<QName, URL> schemasMapping = new ImmutableMap.Builder<>();
193         for (final MapEntryNode moduleNode : ((MapNode) moduleListNode.get()).getValue()) {
194             final Optional<Map.Entry<QName, URL>> schemaMappingEntry = createFromEntry(moduleNode);
195             if (schemaMappingEntry.isPresent()) {
196                 schemasMapping.put(createFromEntry(moduleNode).get());
197             }
198         }
199
200         return new LibraryModulesSchemas(schemasMapping.build());
201     }
202
203     /**
204      * Resolves URLs with YANG schema resources from modules-state.
205      * @param url URL pointing to yang library
206      * @return Resolved URLs with YANG schema resources for all yang modules from yang library
207      */
208     public static LibraryModulesSchemas create(final String url) {
209         Preconditions.checkNotNull(url);
210         try {
211             final URL urlConnection = new URL(url);
212             final URLConnection connection = urlConnection.openConnection();
213
214             if (connection instanceof HttpURLConnection) {
215                 connection.setRequestProperty("Accept", "application/xml");
216             }
217
218             return createFromURLConnection(connection);
219
220         } catch (final IOException e) {
221             LOG.warn("Unable to download yang library from {}", url, e);
222             return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
223         }
224     }
225
226     private static Optional<? extends NormalizedNode<?, ?>> findModulesStateNode(final NormalizedNode<?, ?> result) {
227         if (result == null) {
228             return Optional.absent();
229         }
230         final Optional<DataContainerChild<?, ?>> dataNode =
231                 ((DataContainerNode<?>) result).getChild(toId(NETCONF_DATA_QNAME));
232         if (dataNode.isPresent() == false) {
233             return Optional.absent();
234         }
235
236         return ((DataContainerNode<?>) dataNode.get()).getChild(toId(ModulesState.QNAME));
237     }
238
239     private static LibraryModulesSchemas createFromURLConnection(final URLConnection connection) {
240
241         String contentType = connection.getContentType();
242
243         // TODO try to guess Json also from intput stream
244         if (guessJsonFromFileName(connection.getURL().getFile())) {
245             contentType = "application/json";
246         }
247
248         Preconditions.checkNotNull(contentType, "Content type unknown");
249         Preconditions.checkState(contentType.equals("application/json") || contentType.equals("application/xml"),
250                 "Only XML and JSON types are supported.");
251         try (InputStream in = connection.getInputStream()) {
252             final Optional<NormalizedNode<?, ?>> optionalModulesStateNode =
253                     contentType.equals("application/json") ? readJson(in) : readXml(in);
254
255             if (!optionalModulesStateNode.isPresent()) {
256                 return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
257             }
258
259             final NormalizedNode<?, ?> modulesStateNode = optionalModulesStateNode.get();
260             Preconditions.checkState(modulesStateNode.getNodeType().equals(ModulesState.QNAME),
261                     "Wrong QName %s", modulesStateNode.getNodeType());
262             Preconditions.checkState(modulesStateNode instanceof ContainerNode,
263                     "Expecting container containing module list, but was %s", modulesStateNode);
264
265             final YangInstanceIdentifier.NodeIdentifier moduleListNodeId =
266                     new YangInstanceIdentifier.NodeIdentifier(Module.QNAME);
267             final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> moduleListNode =
268                     ((ContainerNode) modulesStateNode).getChild(moduleListNodeId);
269             Preconditions.checkState(moduleListNode.isPresent(),
270                     "Unable to find list: %s in %s", moduleListNodeId, modulesStateNode);
271             Preconditions.checkState(moduleListNode.get() instanceof MapNode,
272                     "Unexpected structure for container: %s in : %s. Expecting a list",
273                     moduleListNodeId, modulesStateNode);
274
275             final ImmutableMap.Builder<QName, URL> schemasMapping = new ImmutableMap.Builder<>();
276             for (final MapEntryNode moduleNode : ((MapNode) moduleListNode.get()).getValue()) {
277                 final Optional<Map.Entry<QName, URL>> schemaMappingEntry = createFromEntry(moduleNode);
278                 if (schemaMappingEntry.isPresent()) {
279                     schemasMapping.put(createFromEntry(moduleNode).get());
280                 }
281             }
282
283             return new LibraryModulesSchemas(schemasMapping.build());
284         } catch (final IOException e) {
285             LOG.warn("Unable to download yang library from {}", connection.getURL(), e);
286             return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
287         }
288     }
289
290     private static boolean guessJsonFromFileName(final String fileName) {
291         String extension = "";
292         final int i = fileName.lastIndexOf(46);
293         if (i != -1) {
294             extension = fileName.substring(i).toLowerCase();
295         }
296
297         return extension.equals(".json");
298     }
299
300     private static Optional<NormalizedNode<?, ?>> readJson(final InputStream in) {
301         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
302         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
303
304         final JsonParserStream jsonParser = JsonParserStream.create(writer, LIBRARY_CONTEXT);
305         final JsonReader reader = new JsonReader(new InputStreamReader(in));
306
307         jsonParser.parse(reader);
308
309         return resultHolder.isFinished()
310                 ? Optional.of(resultHolder.getResult()) : Optional.<NormalizedNode<?, ?>>absent();
311     }
312
313     @SuppressWarnings("checkstyle:IllegalCatch")
314     private static Optional<NormalizedNode<?, ?>> readXml(final InputStream in) {
315         try {
316             final DocumentBuilder docBuilder = UntrustedXML.newDocumentBuilder();
317
318             final Document read = docBuilder.parse(in);
319             final Document doc = docBuilder.newDocument();
320             final Element rootElement = doc.createElementNS("urn:ietf:params:xml:ns:yang:ietf-yang-library",
321                     "modules");
322             doc.appendChild(rootElement);
323
324             for (int i = 0; i < read.getElementsByTagName("revision").getLength(); i++) {
325                 final String revision = read.getElementsByTagName("revision").item(i).getTextContent();
326                 if (DATE_PATTERN.matcher(revision).find() || revision.isEmpty()) {
327                     final Node module = doc.importNode(read.getElementsByTagName("module").item(i), true);
328                     rootElement.appendChild(module);
329                 } else {
330                     LOG.warn("Xml contains wrong revision - {} - on module {}", revision,
331                             read.getElementsByTagName("module").item(i).getTextContent());
332                 }
333             }
334
335             final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
336             final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
337             final XmlParserStream xmlParser = XmlParserStream.create(writer, LIBRARY_CONTEXT,
338                     LIBRARY_CONTEXT.getDataChildByName(ModulesState.QNAME));
339
340             xmlParser.parse(UntrustedXML.createXMLStreamReader(new StringReader(XmlUtil.toString(
341                     doc.getDocumentElement(), false))));
342             final NormalizedNode<?, ?> parsed = resultHolder.getResult();
343             return Optional.of(parsed);
344         } catch (final Exception e) {
345             LOG.warn("Unable to parse yang library xml content", e);
346         }
347
348         return Optional.<NormalizedNode<?, ?>>absent();
349     }
350
351     private static Optional<Map.Entry<QName, URL>> createFromEntry(final MapEntryNode moduleNode) {
352         Preconditions.checkArgument(
353                 moduleNode.getNodeType().equals(Module.QNAME), "Wrong QName %s", moduleNode.getNodeType());
354
355         YangInstanceIdentifier.NodeIdentifier childNodeId =
356                 new YangInstanceIdentifier.NodeIdentifier(QName.create(Module.QNAME, "name"));
357         final String moduleName = getSingleChildNodeValue(moduleNode, childNodeId).get();
358
359         childNodeId = new YangInstanceIdentifier.NodeIdentifier(QName.create(Module.QNAME, "revision"));
360         final Optional<String> revision = getSingleChildNodeValue(moduleNode, childNodeId);
361         if (revision.isPresent()) {
362             if (!SourceIdentifier.REVISION_PATTERN.matcher(revision.get()).matches()) {
363                 LOG.warn("Skipping library schema for {}. Revision {} is in wrong format.", moduleNode, revision.get());
364                 return Optional.<Map.Entry<QName, URL>>absent();
365             }
366         }
367
368         // FIXME leaf schema with url that represents the yang schema resource for this module is not mandatory
369         // don't fail if schema node is not present, just skip the entry or add some default URL
370         childNodeId = new YangInstanceIdentifier.NodeIdentifier(QName.create(Module.QNAME, "schema"));
371         final Optional<String> schemaUriAsString = getSingleChildNodeValue(moduleNode, childNodeId);
372
373         childNodeId = new YangInstanceIdentifier.NodeIdentifier(QName.create(Module.QNAME, "namespace"));
374         final String moduleNameSpace = getSingleChildNodeValue(moduleNode, childNodeId).get();
375
376         final QName moduleQName = revision.isPresent()
377                 ? QName.create(moduleNameSpace, revision.get(), moduleName)
378                 : QName.create(URI.create(moduleNameSpace), null, moduleName);
379
380         try {
381             return Optional.<Map.Entry<QName, URL>>of(new AbstractMap.SimpleImmutableEntry<>(
382                     moduleQName, new URL(schemaUriAsString.get())));
383         } catch (final MalformedURLException e) {
384             LOG.warn("Skipping library schema for {}. URL {} representing yang schema resource is not valid",
385                     moduleNode, schemaUriAsString.get());
386             return Optional.<Map.Entry<QName, URL>>absent();
387         }
388     }
389
390     private static Optional<String> getSingleChildNodeValue(final DataContainerNode<?> schemaNode,
391                                                             final YangInstanceIdentifier.NodeIdentifier childNodeId) {
392         final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> node =
393                 schemaNode.getChild(childNodeId);
394         Preconditions.checkArgument(node.isPresent(), "Child node %s not present", childNodeId.getNodeType());
395         return getValueOfSimpleNode(node.get());
396     }
397
398     private static Optional<String> getValueOfSimpleNode(
399             final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
400         final Object value = node.getValue();
401         return value == null || Strings.isNullOrEmpty(value.toString())
402                 ? Optional.<String>absent() : Optional.of(value.toString().trim());
403     }
404
405     @Override
406     public Set<QName> getAvailableYangSchemasQNames() {
407         return null;
408     }
409 }