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