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