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