2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.restconf.nb.rfc8040.handlers;
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;
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.base.Throwables;
15 import java.util.Collection;
16 import java.util.List;
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;
77 * Implementation of {@link SchemaContextHandler}.
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.
83 @Component(service = { })
84 public final class SchemaContextHandler implements EffectiveModelContextListener, AutoCloseable {
85 private static final Logger LOG = LoggerFactory.getLogger(SchemaContextHandler.class);
88 static final @NonNull QName CAPABILITY_QNAME = qnameOf("capability");
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());
103 private final AtomicInteger moduleSetId = new AtomicInteger();
104 private final DOMDataBroker domDataBroker;
105 private final Registration listenerRegistration;
107 private volatile EffectiveModelContext schemaContext;
111 public SchemaContextHandler(@Reference final DOMDataBroker domDataBroker,
112 @Reference final DOMSchemaService domSchemaService) {
113 this.domDataBroker = requireNonNull(domDataBroker);
114 listenerRegistration = domSchemaService.registerSchemaContextListener(this);
120 public void close() {
121 listenerRegistration.close();
125 public void onModelContextUpdated(final EffectiveModelContext context) {
126 schemaContext = requireNonNull(context);
128 if (context.findModuleStatement(IetfYangLibrary.MODULE_QNAME).isPresent()) {
129 putData(mapModulesByIetfYangLibraryYang(context.getModules(), context,
130 String.valueOf(moduleSetId.incrementAndGet())));
133 if (schemaContext.findModuleStatement(RestconfState.QNAME.getModule()).isPresent()) {
134 putData(mapCapabilites());
139 EffectiveModelContext get() {
140 return schemaContext;
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);
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) {
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
162 LOG.warn("Ignoring that another cluster node is already putting the same data to DS.", e);
164 throw new RestconfDocumentedException("Problem occurred while putting data to DS.", failure);
170 * Map capabilites by ietf-restconf-monitoring.
172 * @param monitoringModule ietf-restconf-monitoring module
173 * @return mapped capabilites
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())
197 * Map data from modules to {@link NormalizedNode}.
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}
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);
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();
219 * Map data by the specific module or submodule.
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
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);
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)));
238 mapEntryBuilder.withChild(ImmutableNodes.leafNode(MODULE_NAMESPACE_NODEID,
239 module.getNamespace().toString()));
241 // features - not mandatory
242 if (module.getFeatures() != null && !module.getFeatures().isEmpty()) {
243 addFeatureLeafList(mapEntryBuilder, module.getFeatures());
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;
251 conformance = ConformanceType.Import;
253 mapEntryBuilder.withChild(
254 ImmutableNodes.leafNode(MODULE_CONFORMANCE_NODEID, conformance.getName()));
256 // submodules - not mandatory
257 if (module.getSubmodules() != null && !module.getSubmodules().isEmpty()) {
258 addSubmodules(module, mapEntryBuilder, context);
261 mapBuilder.withChild(mapEntryBuilder.build());
265 * Mapping submodules of specific module.
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
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));
278 for (final var submodule : module.getSubmodules()) {
279 fillMapByModules(mapBuilder, Submodule.QNAME, true, submodule, context);
281 mapEntryBuilder.withChild(mapBuilder.build());
285 * Mapping deviations of specific module.
288 * module with deviations
289 * @param mapEntryBuilder
290 * mapEntryBuilder of parent for mapping children
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);
303 deviations.withChild(newCommonLeafsMapEntryBuilder(Deviation.QNAME,
304 context.findModule(lastComponent.getModule()).get())
307 mapEntryBuilder.withChild(deviations.build());
311 * Mapping features of specific module.
313 * @param mapEntryBuilder mapEntryBuilder of parent for mapping children
314 * @param features features of specific module
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());
324 mapEntryBuilder.withChild(leafSetBuilder.build());
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));