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.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;
74 * Implementation of {@link SchemaContextHandler}.
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.
80 public class SchemaContextHandler implements EffectiveModelContextListener, AutoCloseable {
81 private static final Logger LOG = LoggerFactory.getLogger(SchemaContextHandler.class);
84 static final @NonNull QName CAPABILITY_QNAME = qnameOf("capability");
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());
99 private final AtomicInteger moduleSetId = new AtomicInteger(0);
101 private final DOMDataBroker domDataBroker;
102 private final DOMSchemaService domSchemaService;
103 private ListenerRegistration<?> listenerRegistration;
105 private volatile EffectiveModelContext schemaContext;
108 public SchemaContextHandler(final DOMDataBroker domDataBroker, final DOMSchemaService domSchemaService) {
109 this.domDataBroker = requireNonNull(domDataBroker);
110 this.domSchemaService = requireNonNull(domSchemaService);
115 listenerRegistration = domSchemaService.registerSchemaContextListener(this);
120 public void close() {
121 if (listenerRegistration != null) {
122 listenerRegistration.close();
127 public void onModelContextUpdated(final EffectiveModelContext context) {
128 schemaContext = requireNonNull(context);
130 if (context.findModuleStatement(IetfYangLibrary.MODULE_QNAME).isPresent()) {
131 putData(mapModulesByIetfYangLibraryYang(context.getModules(), context,
132 String.valueOf(moduleSetId.incrementAndGet())));
135 if (schemaContext.findModuleStatement(RestconfState.QNAME.getModule()).isPresent()) {
136 putData(mapCapabilites());
140 public EffectiveModelContext get() {
141 return schemaContext;
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);
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) {
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
163 LOG.warn("Ignoring that another cluster node is already putting the same data to DS.", e);
165 throw new RestconfDocumentedException("Problem occurred while putting data to DS.", failure);
171 * Map capabilites by ietf-restconf-monitoring.
173 * @param monitoringModule ietf-restconf-monitoring module
174 * @return mapped capabilites
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())
198 * Map data from modules to {@link NormalizedNode}.
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}
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);
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();
220 * Map data by the specific module or submodule.
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
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);
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)));
239 mapEntryBuilder.withChild(ImmutableNodes.leafNode(MODULE_NAMESPACE_NODEID,
240 module.getNamespace().toString()));
242 // features - not mandatory
243 if (module.getFeatures() != null && !module.getFeatures().isEmpty()) {
244 addFeatureLeafList(mapEntryBuilder, module.getFeatures());
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;
252 conformance = ConformanceType.Import;
254 mapEntryBuilder.withChild(
255 ImmutableNodes.leafNode(MODULE_CONFORMANCE_NODEID, conformance.getName()));
257 // submodules - not mandatory
258 if (module.getSubmodules() != null && !module.getSubmodules().isEmpty()) {
259 addSubmodules(module, mapEntryBuilder, context);
262 mapBuilder.withChild(mapEntryBuilder.build());
266 * Mapping submodules of specific module.
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
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));
279 for (final var submodule : module.getSubmodules()) {
280 fillMapByModules(mapBuilder, Submodule.QNAME, true, submodule, context);
282 mapEntryBuilder.withChild(mapBuilder.build());
286 * Mapping deviations of specific module.
289 * module with deviations
290 * @param mapEntryBuilder
291 * mapEntryBuilder of parent for mapping children
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);
304 deviations.withChild(newCommonLeafsMapEntryBuilder(Deviation.QNAME,
305 context.findModule(lastComponent.getModule()).get())
308 mapEntryBuilder.withChild(deviations.build());
312 * Mapping features of specific module.
314 * @param mapEntryBuilder mapEntryBuilder of parent for mapping children
315 * @param features features of specific module
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());
325 mapEntryBuilder.withChild(leafSetBuilder.build());
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));