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.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;
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(
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();
85 private final Map<QName, URL> availableModels;
87 private static final YangInstanceIdentifier MODULES_STATE_MODULE_LIST =
88 YangInstanceIdentifier.builder().node(ModulesState.QNAME).node(Module.QNAME).build();
90 private static final ContainerNode GET_MODULES_STATE_MODULE_LIST_RPC;
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();
99 private LibraryModulesSchemas(final Map<QName, URL> availableModels) {
100 this.availableModels = availableModels;
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());
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
120 public static LibraryModulesSchemas create(final String url, final String username, final String password) {
121 Preconditions.checkNotNull(url);
123 final URL urlConnection = new URL(url);
124 final URLConnection connection = urlConnection.openConnection();
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());
131 connection.setRequestProperty("Authorization", basicAuth);
134 return createFromURLConnection(connection);
136 } catch (final IOException e) {
137 LOG.warn("Unable to download yang library from {}", url, e);
138 return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
143 public static LibraryModulesSchemas create(final NetconfDeviceRpc deviceRpc, final RemoteDeviceId deviceId) {
144 final DOMRpcResult moduleListNodeResult;
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());
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 Optional<? extends NormalizedNode<?, ?>> findModulesStateNode(final NormalizedNode<?, ?> result) {
178 return Optional.absent();
180 final Optional<DataContainerChild<?, ?>> dataNode = ((DataContainerNode<?>) result).getChild(toId(NETCONF_DATA_QNAME));
181 if(dataNode.isPresent() == false) {
182 return Optional.absent();
185 return ((DataContainerNode<?>) dataNode.get()).getChild(toId(ModulesState.QNAME));
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);
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());
207 return new LibraryModulesSchemas(schemasMapping.build());
210 private static LibraryModulesSchemas createFromURLConnection(final URLConnection connection) {
212 String contentType = connection.getContentType();
214 // TODO try to guess Json also from intput stream
215 if (guessJsonFromFileName(connection.getURL().getFile())) {
216 contentType = "application/json";
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);
226 if (!optionalModulesStateNode.isPresent()) {
227 return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
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);
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);
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());
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());
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
266 public static LibraryModulesSchemas create(final String url) {
267 Preconditions.checkNotNull(url);
269 final URL urlConnection = new URL(url);
270 final URLConnection connection = urlConnection.openConnection();
272 if(connection instanceof HttpURLConnection) {
273 connection.setRequestProperty("Accept", "application/xml");
276 return createFromURLConnection(connection);
278 } catch (final IOException e) {
279 LOG.warn("Unable to download yang library from {}", url, e);
280 return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
284 private static boolean guessJsonFromFileName(final String fileName) {
285 String extension = "";
286 final int i = fileName.lastIndexOf(46);
288 extension = fileName.substring(i).toLowerCase();
291 return extension.equals(".json");
294 private static Optional<NormalizedNode<?, ?>> readJson(final InputStream in) {
295 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
296 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
298 final JsonParserStream jsonParser = JsonParserStream.create(writer, LIBRARY_CONTEXT);
299 final JsonReader reader = new JsonReader(new InputStreamReader(in));
301 jsonParser.parse(reader);
303 return resultHolder.isFinished() ?
304 Optional.of(resultHolder.getResult()) :
305 Optional.<NormalizedNode<?, ?>>absent();
308 private static Optional<NormalizedNode<?, ?>> readXml(final InputStream in) {
309 final DomToNormalizedNodeParserFactory parserFactory =
310 DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, LIBRARY_CONTEXT);
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);
321 return Optional.<NormalizedNode<?, ?>>absent();
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());
328 YangInstanceIdentifier.NodeIdentifier childNodeId =
329 new YangInstanceIdentifier.NodeIdentifier(QName.create(Module.QNAME, "name"));
330 final String moduleName = getSingleChildNodeValue(moduleNode, childNodeId).get();
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();
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);
346 childNodeId = new YangInstanceIdentifier.NodeIdentifier(QName.create(Module.QNAME, "namespace"));
347 final String moduleNameSpace = getSingleChildNodeValue(moduleNode, childNodeId).get();
349 final QName moduleQName = revision.isPresent()
350 ? QName.create(moduleNameSpace, revision.get(), moduleName)
351 : QName.create(URI.create(moduleNameSpace), null, moduleName);
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();
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());
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());
379 public Set<QName> getAvailableYangSchemasQNames() {