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.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.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.ListenerRegistration;
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.api.schema.tree.ConflictingModificationAppliedException;
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.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.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
73 * Implementation of {@link SchemaContextHandler}.
75 // FIXME: this really is a service which is maintaining ietf-yang-library contents inside the datastore. It really
76 // should live in MD-SAL and be a dynamic store fragment. As a first step we should be turning this into a
77 // completely standalone application.
79 public class SchemaContextHandler implements EffectiveModelContextListener, AutoCloseable {
80 private static final Logger LOG = LoggerFactory.getLogger(SchemaContextHandler.class);
83 static final @NonNull QName CAPABILITY_QNAME = qnameOf("capability");
85 private static final NodeIdentifier MODULE_CONFORMANCE_NODEID =
86 NodeIdentifier.create(QName.create(IetfYangLibrary.MODULE_QNAME, "conformance-type").intern());
87 private static final NodeIdentifier MODULE_FEATURE_NODEID =
88 NodeIdentifier.create(QName.create(IetfYangLibrary.MODULE_QNAME, "feature").intern());
89 private static final NodeIdentifier MODULE_NAME_NODEID =
90 NodeIdentifier.create(QName.create(IetfYangLibrary.MODULE_QNAME, "name").intern());
91 private static final NodeIdentifier MODULE_NAMESPACE_NODEID =
92 NodeIdentifier.create(QName.create(IetfYangLibrary.MODULE_QNAME, "namespace").intern());
93 private static final NodeIdentifier MODULE_REVISION_NODEID =
94 NodeIdentifier.create(QName.create(IetfYangLibrary.MODULE_QNAME, "revision").intern());
95 private static final NodeIdentifier MODULE_SCHEMA_NODEID =
96 NodeIdentifier.create(QName.create(IetfYangLibrary.MODULE_QNAME, "schema").intern());
98 private final AtomicInteger moduleSetId = new AtomicInteger(0);
100 private final DOMDataBroker domDataBroker;
101 private final DOMSchemaService domSchemaService;
102 private ListenerRegistration<?> listenerRegistration;
104 private volatile EffectiveModelContext schemaContext;
107 public SchemaContextHandler(final DOMDataBroker domDataBroker, final DOMSchemaService domSchemaService) {
108 this.domDataBroker = requireNonNull(domDataBroker);
109 this.domSchemaService = requireNonNull(domSchemaService);
114 listenerRegistration = domSchemaService.registerSchemaContextListener(this);
119 public void close() {
120 if (listenerRegistration != null) {
121 listenerRegistration.close();
126 public void onModelContextUpdated(final EffectiveModelContext context) {
127 schemaContext = requireNonNull(context);
129 if (context.findModuleStatement(IetfYangLibrary.MODULE_QNAME).isPresent()) {
130 putData(mapModulesByIetfYangLibraryYang(context.getModules(), context,
131 String.valueOf(moduleSetId.incrementAndGet())));
134 if (schemaContext.findModuleStatement(RestconfState.QNAME.getModule()).isPresent()) {
135 putData(mapCapabilites());
139 public 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(LeafNodesOnlyParam.capabilityUri().toString())
189 .withChildValue(SkipNotificationDataParam.capabilityUri().toString())
196 * Map data from modules to {@link NormalizedNode}.
198 * @param modules modules for mapping
199 * @param context schema context
200 * @param moduleSetId module-set-id of actual set
201 * @return mapped data as {@link NormalizedNode}
204 public static ContainerNode mapModulesByIetfYangLibraryYang(final Collection<? extends Module> modules,
205 final SchemaContext context, final String moduleSetId) {
206 final CollectionNodeBuilder<MapEntryNode, UserMapNode> mapBuilder = Builders.orderedMapBuilder()
207 .withNodeIdentifier(new NodeIdentifier(IetfYangLibrary.MODULE_QNAME_LIST));
208 for (final Module module : context.getModules()) {
209 fillMapByModules(mapBuilder, IetfYangLibrary.MODULE_QNAME_LIST, false, module, context);
211 return Builders.containerBuilder()
212 .withNodeIdentifier(new NodeIdentifier(ModulesState.QNAME))
213 .withChild(ImmutableNodes.leafNode(IetfYangLibrary.MODULE_SET_ID_LEAF_QNAME, moduleSetId))
214 .withChild(mapBuilder.build()).build();
218 * Map data by the specific module or submodule.
220 * @param mapBuilder ordered list builder for children
221 * @param mapQName QName corresponding to the list builder
222 * @param isSubmodule true if module is specified as submodule, false otherwise
223 * @param module specific module or submodule
224 * @param context schema context
226 private static void fillMapByModules(final CollectionNodeBuilder<MapEntryNode, UserMapNode> mapBuilder,
227 final QName mapQName, final boolean isSubmodule, final ModuleLike module, final SchemaContext context) {
228 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder =
229 newCommonLeafsMapEntryBuilder(mapQName, module);
231 mapEntryBuilder.withChild(ImmutableNodes.leafNode(MODULE_SCHEMA_NODEID,
232 "/modules/" + module.getName() + "/"
233 // FIXME: orElse(null) does not seem appropriate here
234 + module.getQNameModule().getRevision().map(Revision::toString).orElse(null)));
237 mapEntryBuilder.withChild(ImmutableNodes.leafNode(MODULE_NAMESPACE_NODEID,
238 module.getNamespace().toString()));
240 // features - not mandatory
241 if (module.getFeatures() != null && !module.getFeatures().isEmpty()) {
242 addFeatureLeafList(mapEntryBuilder, module.getFeatures());
244 // deviations - not mandatory
245 final ConformanceType conformance;
246 if (module.getDeviations() != null && !module.getDeviations().isEmpty()) {
247 addDeviationList(module, mapEntryBuilder, context);
248 conformance = ConformanceType.Implement;
250 conformance = ConformanceType.Import;
252 mapEntryBuilder.withChild(
253 ImmutableNodes.leafNode(MODULE_CONFORMANCE_NODEID, conformance.getName()));
255 // submodules - not mandatory
256 if (module.getSubmodules() != null && !module.getSubmodules().isEmpty()) {
257 addSubmodules(module, mapEntryBuilder, context);
260 mapBuilder.withChild(mapEntryBuilder.build());
264 * Mapping submodules of specific module.
266 * @param module module with submodules
267 * @param mapEntryBuilder mapEntryBuilder of parent for mapping children
268 * @param ietfYangLibraryModule ietf-yang-library module
269 * @param context schema context
271 private static void addSubmodules(final ModuleLike module,
272 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder,
273 final SchemaContext context) {
274 final CollectionNodeBuilder<MapEntryNode, UserMapNode> mapBuilder = Builders.orderedMapBuilder()
275 .withNodeIdentifier(new NodeIdentifier(Submodule.QNAME));
277 for (final var submodule : module.getSubmodules()) {
278 fillMapByModules(mapBuilder, Submodule.QNAME, true, submodule, context);
280 mapEntryBuilder.withChild(mapBuilder.build());
284 * Mapping deviations of specific module.
287 * module with deviations
288 * @param mapEntryBuilder
289 * mapEntryBuilder of parent for mapping children
293 private static void addDeviationList(final ModuleLike module,
294 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder,
295 final SchemaContext context) {
296 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> deviations = Builders.mapBuilder()
297 .withNodeIdentifier(new NodeIdentifier(Deviation.QNAME));
298 for (final var deviation : module.getDeviations()) {
299 final List<QName> ids = deviation.getTargetPath().getNodeIdentifiers();
300 final QName lastComponent = ids.get(ids.size() - 1);
302 deviations.withChild(newCommonLeafsMapEntryBuilder(Deviation.QNAME,
303 context.findModule(lastComponent.getModule()).get())
306 mapEntryBuilder.withChild(deviations.build());
310 * Mapping features of specific module.
312 * @param mapEntryBuilder mapEntryBuilder of parent for mapping children
313 * @param features features of specific module
315 private static void addFeatureLeafList(
316 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder,
317 final Collection<? extends FeatureDefinition> features) {
318 final ListNodeBuilder<String, SystemLeafSetNode<String>> leafSetBuilder = Builders.<String>leafSetBuilder()
319 .withNodeIdentifier(MODULE_FEATURE_NODEID);
320 for (final FeatureDefinition feature : features) {
321 leafSetBuilder.withChildValue(feature.getQName().getLocalName());
323 mapEntryBuilder.withChild(leafSetBuilder.build());
326 private static DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> newCommonLeafsMapEntryBuilder(
327 final QName qname, final ModuleLike module) {
328 final var name = module.getName();
329 final var revision = module.getQNameModule().getRevision().map(Revision::toString).orElse("");
330 return Builders.mapEntryBuilder()
331 .withNodeIdentifier(NodeIdentifierWithPredicates.of(qname,
332 Map.of(MODULE_NAME_NODEID.getNodeType(), name, MODULE_REVISION_NODEID.getNodeType(), revision)))
333 .withChild(ImmutableNodes.leafNode(MODULE_NAME_NODEID, name))
334 .withChild(ImmutableNodes.leafNode(MODULE_REVISION_NODEID, revision));