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