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