4178ed1fb51bd5694c821ce6ab6405e80980b7aa
[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.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.ListenerRegistration;
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 ListenerRegistration<?> 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     public EffectiveModelContext get() {
141         return schemaContext;
142     }
143
144     private void putData(final ContainerNode normNode) {
145         final DOMDataTreeWriteTransaction wTx = domDataBroker.newWriteOnlyTransaction();
146         wTx.put(LogicalDatastoreType.OPERATIONAL,
147                 YangInstanceIdentifier.create(NodeIdentifier.create(normNode.getIdentifier().getNodeType())), normNode);
148         try {
149             wTx.commit().get();
150         } catch (InterruptedException e) {
151             throw new RestconfDocumentedException("Problem occurred while putting data to DS.", e);
152         } catch (ExecutionException e) {
153             final TransactionCommitFailedException failure = Throwables.getCauseAs(e,
154                 TransactionCommitFailedException.class);
155             if (failure.getCause() instanceof ConflictingModificationAppliedException) {
156                 /*
157                  * Ignore error when another cluster node is already putting the same data to DS.
158                  * We expect that cluster is homogeneous and that node was going to write the same data
159                  * (that means no retry is needed). Transaction chain reset must be invoked to be able
160                  * to continue writing data with another transaction after failed transaction.
161                  * This is workaround for bug https://bugs.opendaylight.org/show_bug.cgi?id=7728
162                  */
163                 LOG.warn("Ignoring that another cluster node is already putting the same data to DS.", e);
164             } else {
165                 throw new RestconfDocumentedException("Problem occurred while putting data to DS.", failure);
166             }
167         }
168     }
169
170     /**
171      * Map capabilites by ietf-restconf-monitoring.
172      *
173      * @param monitoringModule ietf-restconf-monitoring module
174      * @return mapped capabilites
175      */
176     @VisibleForTesting
177     static ContainerNode mapCapabilites() {
178         return Builders.containerBuilder()
179             .withNodeIdentifier(new NodeIdentifier(RestconfState.QNAME))
180             .withChild(Builders.containerBuilder()
181                 .withNodeIdentifier(new NodeIdentifier(Capabilities.QNAME))
182                 .withChild(Builders.<String>orderedLeafSetBuilder()
183                     .withNodeIdentifier(new NodeIdentifier(CAPABILITY_QNAME))
184                     .withChildValue(DepthParam.capabilityUri().toString())
185                     .withChildValue(FieldsParam.capabilityUri().toString())
186                     .withChildValue(FilterParam.capabilityUri().toString())
187                     .withChildValue(AbstractReplayParam.capabilityUri().toString())
188                     .withChildValue(WithDefaultsParam.capabilityUri().toString())
189                     .withChildValue(PrettyPrintParam.capabilityUri().toString())
190                     .withChildValue(LeafNodesOnlyParam.capabilityUri().toString())
191                     .withChildValue(SkipNotificationDataParam.capabilityUri().toString())
192                     .build())
193                 .build())
194             .build();
195     }
196
197     /**
198      * Map data from modules to {@link NormalizedNode}.
199      *
200      * @param modules modules for mapping
201      * @param context schema context
202      * @param moduleSetId module-set-id of actual set
203      * @return mapped data as {@link NormalizedNode}
204      */
205     @VisibleForTesting
206     public static ContainerNode mapModulesByIetfYangLibraryYang(final Collection<? extends Module> modules,
207             final SchemaContext context, final String moduleSetId) {
208         final CollectionNodeBuilder<MapEntryNode, UserMapNode> mapBuilder = Builders.orderedMapBuilder()
209                 .withNodeIdentifier(new NodeIdentifier(IetfYangLibrary.MODULE_QNAME_LIST));
210         for (final Module module : context.getModules()) {
211             fillMapByModules(mapBuilder, IetfYangLibrary.MODULE_QNAME_LIST, false, module, context);
212         }
213         return Builders.containerBuilder()
214             .withNodeIdentifier(new NodeIdentifier(ModulesState.QNAME))
215             .withChild(ImmutableNodes.leafNode(IetfYangLibrary.MODULE_SET_ID_LEAF_QNAME, moduleSetId))
216             .withChild(mapBuilder.build()).build();
217     }
218
219     /**
220      * Map data by the specific module or submodule.
221      *
222      * @param mapBuilder ordered list builder for children
223      * @param mapQName QName corresponding to the list builder
224      * @param isSubmodule true if module is specified as submodule, false otherwise
225      * @param module specific module or submodule
226      * @param context schema context
227      */
228     private static void fillMapByModules(final CollectionNodeBuilder<MapEntryNode, UserMapNode> mapBuilder,
229             final QName mapQName, final boolean isSubmodule, final ModuleLike module, final SchemaContext context) {
230         final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder =
231             newCommonLeafsMapEntryBuilder(mapQName, module);
232
233         mapEntryBuilder.withChild(ImmutableNodes.leafNode(MODULE_SCHEMA_NODEID,
234             "/modules/" + module.getName() + "/"
235             // FIXME: orElse(null) does not seem appropriate here
236             + module.getQNameModule().getRevision().map(Revision::toString).orElse(null)));
237
238         if (!isSubmodule) {
239             mapEntryBuilder.withChild(ImmutableNodes.leafNode(MODULE_NAMESPACE_NODEID,
240                 module.getNamespace().toString()));
241
242             // features - not mandatory
243             if (module.getFeatures() != null && !module.getFeatures().isEmpty()) {
244                 addFeatureLeafList(mapEntryBuilder, module.getFeatures());
245             }
246             // deviations - not mandatory
247             final ConformanceType conformance;
248             if (module.getDeviations() != null && !module.getDeviations().isEmpty()) {
249                 addDeviationList(module, mapEntryBuilder, context);
250                 conformance = ConformanceType.Implement;
251             } else {
252                 conformance = ConformanceType.Import;
253             }
254             mapEntryBuilder.withChild(
255                 ImmutableNodes.leafNode(MODULE_CONFORMANCE_NODEID, conformance.getName()));
256
257             // submodules - not mandatory
258             if (module.getSubmodules() != null && !module.getSubmodules().isEmpty()) {
259                 addSubmodules(module, mapEntryBuilder, context);
260             }
261         }
262         mapBuilder.withChild(mapEntryBuilder.build());
263     }
264
265     /**
266      * Mapping submodules of specific module.
267      *
268      * @param module module with submodules
269      * @param mapEntryBuilder mapEntryBuilder of parent for mapping children
270      * @param ietfYangLibraryModule ietf-yang-library module
271      * @param context schema context
272      */
273     private static void addSubmodules(final ModuleLike module,
274             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder,
275             final SchemaContext context) {
276         final CollectionNodeBuilder<MapEntryNode, UserMapNode> mapBuilder = Builders.orderedMapBuilder()
277             .withNodeIdentifier(new NodeIdentifier(Submodule.QNAME));
278
279         for (final var submodule : module.getSubmodules()) {
280             fillMapByModules(mapBuilder, Submodule.QNAME, true, submodule, context);
281         }
282         mapEntryBuilder.withChild(mapBuilder.build());
283     }
284
285     /**
286      * Mapping deviations of specific module.
287      *
288      * @param module
289      *             module with deviations
290      * @param mapEntryBuilder
291      *             mapEntryBuilder of parent for mapping children
292      * @param context
293      *             schema context
294      */
295     private static void addDeviationList(final ModuleLike module,
296             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder,
297             final SchemaContext context) {
298         final CollectionNodeBuilder<MapEntryNode, SystemMapNode> deviations = Builders.mapBuilder()
299             .withNodeIdentifier(new NodeIdentifier(Deviation.QNAME));
300         for (final var deviation : module.getDeviations()) {
301             final List<QName> ids = deviation.getTargetPath().getNodeIdentifiers();
302             final QName lastComponent = ids.get(ids.size() - 1);
303
304             deviations.withChild(newCommonLeafsMapEntryBuilder(Deviation.QNAME,
305                 context.findModule(lastComponent.getModule()).get())
306                 .build());
307         }
308         mapEntryBuilder.withChild(deviations.build());
309     }
310
311     /**
312      * Mapping features of specific module.
313      *
314      * @param mapEntryBuilder mapEntryBuilder of parent for mapping children
315      * @param features features of specific module
316      */
317     private static void addFeatureLeafList(
318             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder,
319             final Collection<? extends FeatureDefinition> features) {
320         final ListNodeBuilder<String, SystemLeafSetNode<String>> leafSetBuilder = Builders.<String>leafSetBuilder()
321                 .withNodeIdentifier(MODULE_FEATURE_NODEID);
322         for (final FeatureDefinition feature : features) {
323             leafSetBuilder.withChildValue(feature.getQName().getLocalName());
324         }
325         mapEntryBuilder.withChild(leafSetBuilder.build());
326     }
327
328     private static DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> newCommonLeafsMapEntryBuilder(
329             final QName qname, final ModuleLike module) {
330         final var name = module.getName();
331         final var revision = module.getQNameModule().getRevision().map(Revision::toString).orElse("");
332         return Builders.mapEntryBuilder()
333             .withNodeIdentifier(NodeIdentifierWithPredicates.of(qname,
334                 Map.of(MODULE_NAME_NODEID.getNodeType(), name, MODULE_REVISION_NODEID.getNodeType(), revision)))
335             .withChild(ImmutableNodes.leafNode(MODULE_NAME_NODEID, name))
336             .withChild(ImmutableNodes.leafNode(MODULE_REVISION_NODEID, revision));
337     }
338 }