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