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