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