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