2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.netconf.sal.connect.netconf;
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;
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;
29 import java.net.URLConnection;
30 import java.util.AbstractMap;
31 import java.util.Collections;
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;
68 * Holds URLs with YANG schema resources for all yang modules reported in
69 * ietf-netconf-yang-library/modules-state/modules node.
71 public class LibraryModulesSchemas implements NetconfDeviceSchemas {
73 private static final Logger LOG = LoggerFactory.getLogger(LibraryModulesSchemas.class);
75 private static final SchemaContext LIBRARY_CONTEXT;
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();
84 private final Map<QName, URL> availableModels;
86 private static final YangInstanceIdentifier MODULES_STATE_MODULE_LIST =
87 YangInstanceIdentifier.builder().node(ModulesState.QNAME).node(Module.QNAME).build();
89 private static final ContainerNode GET_MODULES_STATE_MODULE_LIST_RPC;
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();
98 private LibraryModulesSchemas(final Map<QName, URL> availableModels) {
99 this.availableModels = availableModels;
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());
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
119 public static LibraryModulesSchemas create(final String url, final String username, final String password) {
120 Preconditions.checkNotNull(url);
122 final URL urlConnection = new URL(url);
123 final URLConnection connection = urlConnection.openConnection();
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());
130 connection.setRequestProperty("Authorization", basicAuth);
133 return createFromURLConnection(connection);
135 } catch (final IOException e) {
136 LOG.warn("Unable to download yang library from {}", url, e);
137 return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
142 public static LibraryModulesSchemas create(final NetconfDeviceRpc deviceRpc, final RemoteDeviceId deviceId) {
143 final DOMRpcResult moduleListNodeResult;
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());
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());
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()));
171 LOG.warn("{}: Unable to detect available schemas, get to {} was empty", deviceId, toId(ModulesState.QNAME));
172 return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
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);
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());
195 return new LibraryModulesSchemas(schemasMapping.build());
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
203 public static LibraryModulesSchemas create(final String url) {
204 Preconditions.checkNotNull(url);
206 final URL urlConnection = new URL(url);
207 final URLConnection connection = urlConnection.openConnection();
209 if (connection instanceof HttpURLConnection) {
210 connection.setRequestProperty("Accept", "application/xml");
213 return createFromURLConnection(connection);
215 } catch (final IOException e) {
216 LOG.warn("Unable to download yang library from {}", url, e);
217 return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
221 private static Optional<? extends NormalizedNode<?, ?>> findModulesStateNode(final NormalizedNode<?, ?> result) {
222 if (result == null) {
223 return Optional.absent();
225 final Optional<DataContainerChild<?, ?>> dataNode =
226 ((DataContainerNode<?>) result).getChild(toId(NETCONF_DATA_QNAME));
227 if (dataNode.isPresent() == false) {
228 return Optional.absent();
231 return ((DataContainerNode<?>) dataNode.get()).getChild(toId(ModulesState.QNAME));
234 private static LibraryModulesSchemas createFromURLConnection(final URLConnection connection) {
236 String contentType = connection.getContentType();
238 // TODO try to guess Json also from intput stream
239 if (guessJsonFromFileName(connection.getURL().getFile())) {
240 contentType = "application/json";
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);
250 if (!optionalModulesStateNode.isPresent()) {
251 return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
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);
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);
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());
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());
285 private static boolean guessJsonFromFileName(final String fileName) {
286 String extension = "";
287 final int i = fileName.lastIndexOf(46);
289 extension = fileName.substring(i).toLowerCase();
292 return extension.equals(".json");
295 private static Optional<NormalizedNode<?, ?>> readJson(final InputStream in) {
296 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
297 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
299 final JsonParserStream jsonParser = JsonParserStream.create(writer, LIBRARY_CONTEXT);
300 final JsonReader reader = new JsonReader(new InputStreamReader(in));
302 jsonParser.parse(reader);
304 return resultHolder.isFinished()
305 ? Optional.of(resultHolder.getResult()) : Optional.<NormalizedNode<?, ?>>absent();
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);
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);
324 return Optional.<NormalizedNode<?, ?>>absent();
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());
331 YangInstanceIdentifier.NodeIdentifier childNodeId =
332 new YangInstanceIdentifier.NodeIdentifier(QName.create(Module.QNAME, "name"));
333 final String moduleName = getSingleChildNodeValue(moduleNode, childNodeId).get();
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();
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);
349 childNodeId = new YangInstanceIdentifier.NodeIdentifier(QName.create(Module.QNAME, "namespace"));
350 final String moduleNameSpace = getSingleChildNodeValue(moduleNode, childNodeId).get();
352 final QName moduleQName = revision.isPresent()
353 ? QName.create(moduleNameSpace, revision.get(), moduleName)
354 : QName.create(URI.create(moduleNameSpace), null, moduleName);
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();
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());
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());
382 public Set<QName> getAvailableYangSchemasQNames() {