4064655b46ab9fa4530a2839747eae3d8117e572
[mdsal.git] / yanglib / mdsal-yanglib-rfc8525 / src / main / java / org / opendaylight / mdsal / yanglib / rfc8525 / MountPointContextFactoryImpl.java
1 /*
2  * Copyright (c) 2019 PANTHEON.tech s.r.o. 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.mdsal.yanglib.rfc8525;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verifyNotNull;
12 import static java.util.Objects.requireNonNull;
13
14 import java.net.MalformedURLException;
15 import java.net.URL;
16 import java.util.ArrayList;
17 import java.util.HashSet;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Optional;
21 import java.util.Set;
22 import org.eclipse.jdt.annotation.NonNull;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.opendaylight.mdsal.binding.dom.codec.api.BindingDataObjectCodecTreeNode;
25 import org.opendaylight.mdsal.binding.dom.codec.api.BindingIdentityCodec;
26 import org.opendaylight.mdsal.yanglib.api.SchemaContextResolver;
27 import org.opendaylight.mdsal.yanglib.api.SourceReference;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.datastores.rev180214.Operational;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.ModulesState;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.RevisionIdentifier;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.YangLibrary;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.module.list.CommonLeafs;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.module.list.CommonLeafsRevisionBuilder;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.module.list.Module.ConformanceType;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.module.set.parameters.ImportOnlyModuleRevisionBuilder;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.yang.library.parameters.Datastore;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.yang.library.parameters.DatastoreKey;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.yang.library.parameters.ModuleSet;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.yang.library.parameters.SchemaKey;
41 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.YangIdentifier;
42 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContextFactory;
43 import org.opendaylight.yangtools.rfc8528.data.api.MountPointIdentifier;
44 import org.opendaylight.yangtools.rfc8528.data.api.YangLibraryConstants.ContainerName;
45 import org.opendaylight.yangtools.rfc8528.data.util.AbstractMountPointContextFactory;
46 import org.opendaylight.yangtools.yang.common.QName;
47 import org.opendaylight.yangtools.yang.common.Revision;
48 import org.opendaylight.yangtools.yang.common.XMLNamespace;
49 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
50 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
51 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
52 import org.opendaylight.yangtools.yang.parser.api.YangParserException;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 final class MountPointContextFactoryImpl extends AbstractMountPointContextFactory {
57     private static final Logger LOG = LoggerFactory.getLogger(MountPointContextFactoryImpl.class);
58
59     @SuppressWarnings("deprecation")
60     private final BindingDataObjectCodecTreeNode<ModulesState> legacyCodec;
61     private final BindingDataObjectCodecTreeNode<YangLibrary> codec;
62     private final BindingIdentityCodec identityCodec;
63     private final EffectiveModelContext yangLibContext;
64     private final SchemaContextResolver resolver;
65
66     MountPointContextFactoryImpl(final MountPointIdentifier mountId, final SchemaContextResolver resolver,
67             final EffectiveModelContext yangLibContext,
68             final BindingIdentityCodec identityCodec,
69             final BindingDataObjectCodecTreeNode<YangLibrary> codec,
70             @SuppressWarnings("deprecation")
71             final BindingDataObjectCodecTreeNode<ModulesState> legacyCodec) {
72         super(mountId);
73         this.resolver = requireNonNull(resolver);
74         this.identityCodec = requireNonNull(identityCodec);
75         this.yangLibContext = requireNonNull(yangLibContext);
76         this.codec = requireNonNull(codec);
77         this.legacyCodec = requireNonNull(legacyCodec);
78     }
79
80     @Override
81     protected MountPointContextFactory createContextFactory(final MountPointDefinition mountPoint) {
82         return new MountPointContextFactoryImpl(mountPoint.getIdentifier(), resolver, yangLibContext, identityCodec,
83             codec, legacyCodec);
84     }
85
86     @Override
87     protected Optional<EffectiveModelContext> findSchemaForLibrary(final ContainerName containerName) {
88         switch (containerName) {
89             case RFC7895:
90             case RFC8525:
91                 return Optional.of(yangLibContext);
92             default:
93                 LOG.debug("Unhandled YANG library container {}", containerName);
94                 return Optional.empty();
95         }
96     }
97
98     @Override
99     protected EffectiveModelContext bindLibrary(final ContainerName containerName, final ContainerNode libData)
100             throws YangParserException {
101         switch (containerName) {
102             case RFC7895:
103                 return bindLibrary(verifyNotNull(legacyCodec.deserialize(libData)));
104             case RFC8525:
105                 return bindLibrary(verifyNotNull(codec.deserialize(libData)));
106             default:
107                 throw new IllegalStateException("Unhandled container type " + containerName);
108         }
109     }
110
111     private @NonNull EffectiveModelContext bindLibrary(final @NonNull YangLibrary yangLib) throws YangParserException {
112         final var datastores = yangLib.nonnullDatastore();
113         checkArgument(!datastores.isEmpty(), "No datastore defined");
114
115         final var requiredSources = new ArrayList<SourceReference>();
116         final var librarySources = new ArrayList<SourceReference>();
117         final var supportedFeatures = new HashSet<QName>();
118         final var moduleSet = findModuleSet(yangLib, findSchemaName(datastores, Operational.QNAME));
119         for (var modSet : yangLib.nonnullModuleSet().values()) {
120             if (moduleSet.remove(modSet.getName())) {
121                 fillModules(librarySources, requiredSources, supportedFeatures, modSet);
122             }
123         }
124         checkArgument(moduleSet.isEmpty(), "Failed to resolve module sets %s", moduleSet);
125
126         return resolver.resolveSchemaContext(librarySources, requiredSources, supportedFeatures);
127     }
128
129     @SuppressWarnings("deprecation")
130     private @NonNull EffectiveModelContext bindLibrary(final @NonNull ModulesState modState)
131             throws YangParserException {
132         final var requiredSources = new ArrayList<SourceReference>();
133         final var librarySources = new ArrayList<SourceReference>();
134         final var supportedFeatures = new HashSet<QName>();
135
136         for (var module : modState.nonnullModule().values()) {
137             final var modRef = sourceRefFor(module, module.getSchema());
138
139             final var namespace = XMLNamespace.of(module.requireNamespace().getValue());
140             for (var feature : module.requireFeature()) {
141                 supportedFeatures.add(QName.create(namespace, feature.getValue()).intern());
142             }
143
144             // TODO: take deviations into account
145
146             if (ConformanceType.Import == module.getConformanceType()) {
147                 librarySources.add(modRef);
148             } else {
149                 requiredSources.add(modRef);
150             }
151
152             for (var submodule : module.nonnullSubmodule().values()) {
153                 // Submodules go to library, as they are pulled in as needed
154                 librarySources.add(sourceRefFor(submodule, submodule.getSchema()));
155             }
156         }
157
158         return resolver.resolveSchemaContext(librarySources, requiredSources, supportedFeatures);
159     }
160
161     private String findSchemaName(final Map<DatastoreKey, Datastore> datastores, final QName qname) {
162         final var it = datastores.values().iterator();
163         final var ds = it.next();
164
165         // FIXME: This is ugly, but it is the most compatible thing we can do without knowing the exact requested
166         //        datastore
167         if (it.hasNext() && !qname.equals(identityCodec.fromBinding(ds.getName()))) {
168             do {
169                 final Datastore next = it.next();
170                 if (qname.equals(identityCodec.fromBinding(ds.getName()))) {
171                     return next.getSchema();
172                 }
173             } while (it.hasNext());
174         }
175
176         return ds.getSchema();
177     }
178
179     @SuppressWarnings("deprecation")
180     private static SourceReference sourceRefFor(final CommonLeafs obj, final Uri uri) {
181         final var sourceId = RevisionSourceIdentifier.create(obj.getName().getValue(),
182             CommonLeafsRevisionBuilder.toYangCommon(obj.getRevision()));
183         if (uri != null) {
184             try {
185                 return SourceReference.of(sourceId, new URL(uri.getValue()));
186             } catch (MalformedURLException e) {
187                 LOG.debug("Ignoring invalid schema location {}", uri, e);
188             }
189         }
190
191         return SourceReference.of(sourceId);
192     }
193
194     private static HashSet<String> findModuleSet(final YangLibrary yangLib, final String schemaName) {
195         final var schema = yangLib.nonnullSchema().get(new SchemaKey(schemaName));
196         if (schema == null) {
197             throw new IllegalArgumentException("Failed to find moduleSet for " + schemaName);
198         }
199         return new HashSet<>(schema.getModuleSet());
200     }
201
202     private static void fillModules(final List<SourceReference> librarySources,
203             final List<SourceReference> requiredSources, final Set<QName> supportedFeatures, final ModuleSet modSet) {
204         // TODO: take deviations/features into account
205
206         for (var mod : modSet.nonnullImportOnlyModule().values()) {
207             fillSource(librarySources, mod.getName(), ImportOnlyModuleRevisionBuilder.toYangCommon(mod.getRevision()),
208                 mod.getLocation());
209             mod.nonnullSubmodule().values().forEach(sub -> {
210                 fillSource(librarySources, sub.getName(), toYangCommon(sub.getRevision()), sub.getLocation());
211             });
212         }
213         for (var mod : modSet.nonnullModule().values()) {
214             fillSource(requiredSources, mod.getName(), toYangCommon(mod.getRevision()), mod.getLocation());
215             final var namespace = XMLNamespace.of(mod.requireNamespace().getValue());
216             mod.requireFeature().forEach(feature -> supportedFeatures.add(QName.create(namespace, feature.getValue())));
217             mod.nonnullSubmodule().values().forEach(sub -> {
218                 fillSource(librarySources, sub.getName(), toYangCommon(sub.getRevision()), sub.getLocation());
219             });
220         }
221     }
222
223     private static void fillSource(final List<SourceReference> sources, final YangIdentifier sourceName,
224             final Optional<Revision> revision, final List<Uri> uris) {
225         final var sourceId = RevisionSourceIdentifier.create(sourceName.getValue(), revision);
226         final SourceReference sourceRef;
227         if (uris != null && uris.isEmpty()) {
228             final var locations = new ArrayList<URL>();
229             for (Uri uri : uris) {
230                 try {
231                     locations.add(new URL(uri.getValue()));
232                 } catch (MalformedURLException e) {
233                     LOG.debug("Ignoring invalid schema location {}", uri, e);
234                 }
235             }
236             sourceRef = SourceReference.of(sourceId, locations);
237         } else {
238             sourceRef = SourceReference.of(sourceId);
239         }
240
241         sources.add(sourceRef);
242     }
243
244     private static Optional<Revision> toYangCommon(final @Nullable RevisionIdentifier revisionIdentifier) {
245         return revisionIdentifier == null ? Optional.empty() : Optional.of(Revision.of(revisionIdentifier.getValue()));
246     }
247 }