Turn SchemaContextHandler into a component
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / handlers / SchemaContextHandler.java
1 /*
2  * Copyright (c) 2016 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.restconf.nb.rfc8040.handlers;
9
10 import static java.util.Objects.requireNonNull;
11 import static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.restconf.monitoring.rev170126.$YangModuleInfoImpl.qnameOf;
12
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.base.Throwables;
15 import java.util.Collection;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.concurrent.ExecutionException;
19 import java.util.concurrent.atomic.AtomicInteger;
20 import javax.annotation.PreDestroy;
21 import javax.inject.Inject;
22 import javax.inject.Singleton;
23 import org.eclipse.jdt.annotation.NonNull;
24 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
25 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
26 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
27 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
28 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
29 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
30 import org.opendaylight.restconf.nb.rfc8040.AbstractReplayParam;
31 import org.opendaylight.restconf.nb.rfc8040.DepthParam;
32 import org.opendaylight.restconf.nb.rfc8040.FieldsParam;
33 import org.opendaylight.restconf.nb.rfc8040.FilterParam;
34 import org.opendaylight.restconf.nb.rfc8040.LeafNodesOnlyParam;
35 import org.opendaylight.restconf.nb.rfc8040.PrettyPrintParam;
36 import org.opendaylight.restconf.nb.rfc8040.Rfc8040.IetfYangLibrary;
37 import org.opendaylight.restconf.nb.rfc8040.SkipNotificationDataParam;
38 import org.opendaylight.restconf.nb.rfc8040.WithDefaultsParam;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.restconf.monitoring.rev170126.RestconfState;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.restconf.monitoring.rev170126.restconf.state.Capabilities;
41 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.ModulesState;
42 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.module.list.Module.ConformanceType;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.module.list.module.Deviation;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.module.list.module.Submodule;
45 import org.opendaylight.yangtools.concepts.Registration;
46 import org.opendaylight.yangtools.yang.common.QName;
47 import org.opendaylight.yangtools.yang.common.Revision;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
51 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
58 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
59 import org.opendaylight.yangtools.yang.data.api.schema.builder.ListNodeBuilder;
60 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
61 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
62 import org.opendaylight.yangtools.yang.data.tree.api.ConflictingModificationAppliedException;
63 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
64 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextListener;
65 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
66 import org.opendaylight.yangtools.yang.model.api.Module;
67 import org.opendaylight.yangtools.yang.model.api.ModuleLike;
68 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
69 import org.osgi.service.component.annotations.Activate;
70 import org.osgi.service.component.annotations.Component;
71 import org.osgi.service.component.annotations.Deactivate;
72 import org.osgi.service.component.annotations.Reference;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
75
76 /**
77  * Implementation of {@link SchemaContextHandler}.
78  */
79 // FIXME: this really is a service which is maintaining ietf-yang-library contents inside the datastore. It really
80 //        should live in MD-SAL and be a dynamic store fragment. As a first step we should be turning this into a
81 //        completely standalone application.
82 @Singleton
83 @Component(service = { })
84 public final class SchemaContextHandler implements EffectiveModelContextListener, AutoCloseable {
85     private static final Logger LOG = LoggerFactory.getLogger(SchemaContextHandler.class);
86
87     @VisibleForTesting
88     static final @NonNull QName CAPABILITY_QNAME = qnameOf("capability");
89
90     private static final NodeIdentifier MODULE_CONFORMANCE_NODEID =
91         NodeIdentifier.create(QName.create(IetfYangLibrary.MODULE_QNAME, "conformance-type").intern());
92     private static final NodeIdentifier MODULE_FEATURE_NODEID =
93         NodeIdentifier.create(QName.create(IetfYangLibrary.MODULE_QNAME, "feature").intern());
94     private static final NodeIdentifier MODULE_NAME_NODEID =
95         NodeIdentifier.create(QName.create(IetfYangLibrary.MODULE_QNAME, "name").intern());
96     private static final NodeIdentifier MODULE_NAMESPACE_NODEID =
97         NodeIdentifier.create(QName.create(IetfYangLibrary.MODULE_QNAME, "namespace").intern());
98     private static final NodeIdentifier MODULE_REVISION_NODEID =
99         NodeIdentifier.create(QName.create(IetfYangLibrary.MODULE_QNAME, "revision").intern());
100     private static final NodeIdentifier MODULE_SCHEMA_NODEID =
101         NodeIdentifier.create(QName.create(IetfYangLibrary.MODULE_QNAME, "schema").intern());
102
103     private final AtomicInteger moduleSetId = new AtomicInteger();
104     private final DOMDataBroker domDataBroker;
105     private final Registration listenerRegistration;
106
107     private volatile EffectiveModelContext schemaContext;
108
109     @Inject
110     @Activate
111     public SchemaContextHandler(@Reference final DOMDataBroker domDataBroker,
112             @Reference final DOMSchemaService domSchemaService) {
113         this.domDataBroker = requireNonNull(domDataBroker);
114         listenerRegistration = domSchemaService.registerSchemaContextListener(this);
115     }
116
117     @PreDestroy
118     @Deactivate
119     @Override
120     public void close() {
121         listenerRegistration.close();
122     }
123
124     @Override
125     public void onModelContextUpdated(final EffectiveModelContext context) {
126         schemaContext = requireNonNull(context);
127
128         if (context.findModuleStatement(IetfYangLibrary.MODULE_QNAME).isPresent()) {
129             putData(mapModulesByIetfYangLibraryYang(context.getModules(), context,
130                 String.valueOf(moduleSetId.incrementAndGet())));
131         }
132
133         if (schemaContext.findModuleStatement(RestconfState.QNAME.getModule()).isPresent()) {
134             putData(mapCapabilites());
135         }
136     }
137
138     @VisibleForTesting
139     EffectiveModelContext get() {
140         return schemaContext;
141     }
142
143     private void putData(final ContainerNode normNode) {
144         final DOMDataTreeWriteTransaction wTx = domDataBroker.newWriteOnlyTransaction();
145         wTx.put(LogicalDatastoreType.OPERATIONAL,
146                 YangInstanceIdentifier.create(NodeIdentifier.create(normNode.getIdentifier().getNodeType())), normNode);
147         try {
148             wTx.commit().get();
149         } catch (InterruptedException e) {
150             throw new RestconfDocumentedException("Problem occurred while putting data to DS.", e);
151         } catch (ExecutionException e) {
152             final TransactionCommitFailedException failure = Throwables.getCauseAs(e,
153                 TransactionCommitFailedException.class);
154             if (failure.getCause() instanceof ConflictingModificationAppliedException) {
155                 /*
156                  * Ignore error when another cluster node is already putting the same data to DS.
157                  * We expect that cluster is homogeneous and that node was going to write the same data
158                  * (that means no retry is needed). Transaction chain reset must be invoked to be able
159                  * to continue writing data with another transaction after failed transaction.
160                  * This is workaround for bug https://bugs.opendaylight.org/show_bug.cgi?id=7728
161                  */
162                 LOG.warn("Ignoring that another cluster node is already putting the same data to DS.", e);
163             } else {
164                 throw new RestconfDocumentedException("Problem occurred while putting data to DS.", failure);
165             }
166         }
167     }
168
169     /**
170      * Map capabilites by ietf-restconf-monitoring.
171      *
172      * @param monitoringModule ietf-restconf-monitoring module
173      * @return mapped capabilites
174      */
175     @VisibleForTesting
176     static ContainerNode mapCapabilites() {
177         return Builders.containerBuilder()
178             .withNodeIdentifier(new NodeIdentifier(RestconfState.QNAME))
179             .withChild(Builders.containerBuilder()
180                 .withNodeIdentifier(new NodeIdentifier(Capabilities.QNAME))
181                 .withChild(Builders.<String>orderedLeafSetBuilder()
182                     .withNodeIdentifier(new NodeIdentifier(CAPABILITY_QNAME))
183                     .withChildValue(DepthParam.capabilityUri().toString())
184                     .withChildValue(FieldsParam.capabilityUri().toString())
185                     .withChildValue(FilterParam.capabilityUri().toString())
186                     .withChildValue(AbstractReplayParam.capabilityUri().toString())
187                     .withChildValue(WithDefaultsParam.capabilityUri().toString())
188                     .withChildValue(PrettyPrintParam.capabilityUri().toString())
189                     .withChildValue(LeafNodesOnlyParam.capabilityUri().toString())
190                     .withChildValue(SkipNotificationDataParam.capabilityUri().toString())
191                     .build())
192                 .build())
193             .build();
194     }
195
196     /**
197      * Map data from modules to {@link NormalizedNode}.
198      *
199      * @param modules modules for mapping
200      * @param context schema context
201      * @param moduleSetId module-set-id of actual set
202      * @return mapped data as {@link NormalizedNode}
203      */
204     @VisibleForTesting
205     public static ContainerNode mapModulesByIetfYangLibraryYang(final Collection<? extends Module> modules,
206             final SchemaContext context, final String moduleSetId) {
207         final CollectionNodeBuilder<MapEntryNode, UserMapNode> mapBuilder = Builders.orderedMapBuilder()
208                 .withNodeIdentifier(new NodeIdentifier(IetfYangLibrary.MODULE_QNAME_LIST));
209         for (final Module module : context.getModules()) {
210             fillMapByModules(mapBuilder, IetfYangLibrary.MODULE_QNAME_LIST, false, module, context);
211         }
212         return Builders.containerBuilder()
213             .withNodeIdentifier(new NodeIdentifier(ModulesState.QNAME))
214             .withChild(ImmutableNodes.leafNode(IetfYangLibrary.MODULE_SET_ID_LEAF_QNAME, moduleSetId))
215             .withChild(mapBuilder.build()).build();
216     }
217
218     /**
219      * Map data by the specific module or submodule.
220      *
221      * @param mapBuilder ordered list builder for children
222      * @param mapQName QName corresponding to the list builder
223      * @param isSubmodule true if module is specified as submodule, false otherwise
224      * @param module specific module or submodule
225      * @param context schema context
226      */
227     private static void fillMapByModules(final CollectionNodeBuilder<MapEntryNode, UserMapNode> mapBuilder,
228             final QName mapQName, final boolean isSubmodule, final ModuleLike module, final SchemaContext context) {
229         final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder =
230             newCommonLeafsMapEntryBuilder(mapQName, module);
231
232         mapEntryBuilder.withChild(ImmutableNodes.leafNode(MODULE_SCHEMA_NODEID,
233             "/modules/" + module.getName() + "/"
234             // FIXME: orElse(null) does not seem appropriate here
235             + module.getQNameModule().getRevision().map(Revision::toString).orElse(null)));
236
237         if (!isSubmodule) {
238             mapEntryBuilder.withChild(ImmutableNodes.leafNode(MODULE_NAMESPACE_NODEID,
239                 module.getNamespace().toString()));
240
241             // features - not mandatory
242             if (module.getFeatures() != null && !module.getFeatures().isEmpty()) {
243                 addFeatureLeafList(mapEntryBuilder, module.getFeatures());
244             }
245             // deviations - not mandatory
246             final ConformanceType conformance;
247             if (module.getDeviations() != null && !module.getDeviations().isEmpty()) {
248                 addDeviationList(module, mapEntryBuilder, context);
249                 conformance = ConformanceType.Implement;
250             } else {
251                 conformance = ConformanceType.Import;
252             }
253             mapEntryBuilder.withChild(
254                 ImmutableNodes.leafNode(MODULE_CONFORMANCE_NODEID, conformance.getName()));
255
256             // submodules - not mandatory
257             if (module.getSubmodules() != null && !module.getSubmodules().isEmpty()) {
258                 addSubmodules(module, mapEntryBuilder, context);
259             }
260         }
261         mapBuilder.withChild(mapEntryBuilder.build());
262     }
263
264     /**
265      * Mapping submodules of specific module.
266      *
267      * @param module module with submodules
268      * @param mapEntryBuilder mapEntryBuilder of parent for mapping children
269      * @param ietfYangLibraryModule ietf-yang-library module
270      * @param context schema context
271      */
272     private static void addSubmodules(final ModuleLike module,
273             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder,
274             final SchemaContext context) {
275         final CollectionNodeBuilder<MapEntryNode, UserMapNode> mapBuilder = Builders.orderedMapBuilder()
276             .withNodeIdentifier(new NodeIdentifier(Submodule.QNAME));
277
278         for (final var submodule : module.getSubmodules()) {
279             fillMapByModules(mapBuilder, Submodule.QNAME, true, submodule, context);
280         }
281         mapEntryBuilder.withChild(mapBuilder.build());
282     }
283
284     /**
285      * Mapping deviations of specific module.
286      *
287      * @param module
288      *             module with deviations
289      * @param mapEntryBuilder
290      *             mapEntryBuilder of parent for mapping children
291      * @param context
292      *             schema context
293      */
294     private static void addDeviationList(final ModuleLike module,
295             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder,
296             final SchemaContext context) {
297         final CollectionNodeBuilder<MapEntryNode, SystemMapNode> deviations = Builders.mapBuilder()
298             .withNodeIdentifier(new NodeIdentifier(Deviation.QNAME));
299         for (final var deviation : module.getDeviations()) {
300             final List<QName> ids = deviation.getTargetPath().getNodeIdentifiers();
301             final QName lastComponent = ids.get(ids.size() - 1);
302
303             deviations.withChild(newCommonLeafsMapEntryBuilder(Deviation.QNAME,
304                 context.findModule(lastComponent.getModule()).get())
305                 .build());
306         }
307         mapEntryBuilder.withChild(deviations.build());
308     }
309
310     /**
311      * Mapping features of specific module.
312      *
313      * @param mapEntryBuilder mapEntryBuilder of parent for mapping children
314      * @param features features of specific module
315      */
316     private static void addFeatureLeafList(
317             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder,
318             final Collection<? extends FeatureDefinition> features) {
319         final ListNodeBuilder<String, SystemLeafSetNode<String>> leafSetBuilder = Builders.<String>leafSetBuilder()
320                 .withNodeIdentifier(MODULE_FEATURE_NODEID);
321         for (final FeatureDefinition feature : features) {
322             leafSetBuilder.withChildValue(feature.getQName().getLocalName());
323         }
324         mapEntryBuilder.withChild(leafSetBuilder.build());
325     }
326
327     private static DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> newCommonLeafsMapEntryBuilder(
328             final QName qname, final ModuleLike module) {
329         final var name = module.getName();
330         final var revision = module.getQNameModule().getRevision().map(Revision::toString).orElse("");
331         return Builders.mapEntryBuilder()
332             .withNodeIdentifier(NodeIdentifierWithPredicates.of(qname,
333                 Map.of(MODULE_NAME_NODEID.getNodeType(), name, MODULE_REVISION_NODEID.getNodeType(), revision)))
334             .withChild(ImmutableNodes.leafNode(MODULE_NAME_NODEID, name))
335             .withChild(ImmutableNodes.leafNode(MODULE_REVISION_NODEID, revision));
336     }
337 }