Bump upstreams
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / server / mdsal / MdsalRestconfServer.java
1 /*
2  * Copyright (c) 2023 PANTHEON.tech, s.r.o. 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.server.mdsal;
9
10 import static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.collect.ImmutableMap;
14 import com.google.common.collect.Maps;
15 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
16 import java.lang.invoke.MethodHandles;
17 import java.lang.invoke.VarHandle;
18 import java.net.URI;
19 import java.time.format.DateTimeParseException;
20 import java.util.List;
21 import java.util.Locale;
22 import java.util.Map;
23 import javax.annotation.PreDestroy;
24 import javax.inject.Inject;
25 import javax.inject.Singleton;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.opendaylight.mdsal.dom.api.DOMActionService;
29 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
30 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
31 import org.opendaylight.mdsal.dom.api.DOMRpcService;
32 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
33 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
34 import org.opendaylight.restconf.api.ApiPath;
35 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
36 import org.opendaylight.restconf.common.errors.RestconfFuture;
37 import org.opendaylight.restconf.nb.rfc8040.databind.ChildBody;
38 import org.opendaylight.restconf.nb.rfc8040.databind.DataPostBody;
39 import org.opendaylight.restconf.nb.rfc8040.databind.OperationInputBody;
40 import org.opendaylight.restconf.nb.rfc8040.databind.PatchBody;
41 import org.opendaylight.restconf.nb.rfc8040.databind.ResourceBody;
42 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
43 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.MdsalRestconfStrategy;
44 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfStrategy;
45 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfStrategy.StrategyAndTail;
46 import org.opendaylight.restconf.server.api.DataGetParams;
47 import org.opendaylight.restconf.server.api.DataGetResult;
48 import org.opendaylight.restconf.server.api.DataPatchResult;
49 import org.opendaylight.restconf.server.api.DataPostResult;
50 import org.opendaylight.restconf.server.api.DataPostResult.CreateResource;
51 import org.opendaylight.restconf.server.api.DataPutResult;
52 import org.opendaylight.restconf.server.api.DataYangPatchResult;
53 import org.opendaylight.restconf.server.api.DatabindContext;
54 import org.opendaylight.restconf.server.api.ModulesGetResult;
55 import org.opendaylight.restconf.server.api.OperationsGetResult;
56 import org.opendaylight.restconf.server.api.OperationsPostResult;
57 import org.opendaylight.restconf.server.api.RestconfServer;
58 import org.opendaylight.restconf.server.spi.DatabindProvider;
59 import org.opendaylight.restconf.server.spi.RpcImplementation;
60 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.restconf.rev170126.YangApi;
61 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.restconf.rev170126.restconf.Restconf;
62 import org.opendaylight.yangtools.concepts.Registration;
63 import org.opendaylight.yangtools.yang.common.Empty;
64 import org.opendaylight.yangtools.yang.common.ErrorTag;
65 import org.opendaylight.yangtools.yang.common.ErrorType;
66 import org.opendaylight.yangtools.yang.common.QName;
67 import org.opendaylight.yangtools.yang.common.Revision;
68 import org.opendaylight.yangtools.yang.common.YangNames;
69 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
70 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
71 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextListener;
72 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
73 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
74 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
75 import org.opendaylight.yangtools.yang.model.repo.api.YinTextSchemaSource;
76 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
77 import org.osgi.service.component.annotations.Activate;
78 import org.osgi.service.component.annotations.Component;
79 import org.osgi.service.component.annotations.Deactivate;
80 import org.osgi.service.component.annotations.Reference;
81 import org.slf4j.Logger;
82 import org.slf4j.LoggerFactory;
83
84 /**
85  * A RESTCONF server implemented on top of MD-SAL.
86  */
87 @Singleton
88 @Component(service = { RestconfServer.class, DatabindProvider.class })
89 public final class MdsalRestconfServer
90         implements RestconfServer, DatabindProvider, EffectiveModelContextListener, AutoCloseable {
91     private static final Logger LOG = LoggerFactory.getLogger(MdsalRestconfServer.class);
92     private static final QName YANG_LIBRARY_VERSION = QName.create(Restconf.QNAME, "yang-library-version").intern();
93     private static final VarHandle LOCAL_STRATEGY;
94
95     static {
96         try {
97             LOCAL_STRATEGY = MethodHandles.lookup()
98                 .findVarHandle(MdsalRestconfServer.class, "localStrategy", MdsalRestconfStrategy.class);
99         } catch (NoSuchFieldException | IllegalAccessException e) {
100             throw new ExceptionInInitializerError(e);
101         }
102     }
103
104     private final @NonNull ImmutableMap<QName, RpcImplementation> localRpcs;
105     private final @NonNull DOMMountPointService mountPointService;
106     private final @NonNull DOMDataBroker dataBroker;
107     private final @Nullable DOMRpcService rpcService;
108     private final @Nullable DOMActionService actionService;
109     private final @Nullable DOMYangTextSourceProvider sourceProvider;
110
111     private final Registration reg;
112
113     @SuppressWarnings("unused")
114     @SuppressFBWarnings(value = "URF_UNREAD_FIELD", justification = "https://github.com/spotbugs/spotbugs/issues/2749")
115     private volatile MdsalRestconfStrategy localStrategy;
116
117     @Inject
118     @Activate
119     public MdsalRestconfServer(@Reference final DOMSchemaService schemaService,
120             @Reference final DOMDataBroker dataBroker, @Reference final DOMRpcService rpcService,
121             @Reference final DOMActionService actionService,
122             @Reference final DOMMountPointService mountPointService,
123             @Reference final List<RpcImplementation> localRpcs) {
124         this.dataBroker = requireNonNull(dataBroker);
125         this.rpcService = requireNonNull(rpcService);
126         this.actionService = requireNonNull(actionService);
127         this.mountPointService = requireNonNull(mountPointService);
128         this.localRpcs = Maps.uniqueIndex(localRpcs, RpcImplementation::qname);
129         sourceProvider = schemaService.getExtensions().getInstance(DOMYangTextSourceProvider.class);
130
131         localStrategy = createLocalStrategy(schemaService.getGlobalContext());
132         reg = schemaService.registerSchemaContextListener(this);
133     }
134
135     public MdsalRestconfServer(final DOMSchemaService schemaService, final DOMDataBroker dataBroker,
136             final DOMRpcService rpcService, final DOMActionService actionService,
137             final DOMMountPointService mountPointService, final RpcImplementation... localRpcs) {
138         this(schemaService, dataBroker, rpcService, actionService, mountPointService, List.of(localRpcs));
139     }
140
141     @Override
142     public DatabindContext currentDatabind() {
143         return localStrategy().databind();
144     }
145
146     @Override
147     public void onModelContextUpdated(final EffectiveModelContext newModelContext) {
148         final var local = localStrategy();
149         if (!newModelContext.equals(local.modelContext())) {
150             LOCAL_STRATEGY.setRelease(this, createLocalStrategy(newModelContext));
151         }
152     }
153
154     private @NonNull MdsalRestconfStrategy createLocalStrategy(final EffectiveModelContext modelContext) {
155         return new MdsalRestconfStrategy(DatabindContext.ofModel(modelContext), dataBroker, rpcService, actionService,
156             sourceProvider, mountPointService, localRpcs);
157     }
158
159     private @NonNull MdsalRestconfStrategy localStrategy() {
160         return verifyNotNull((MdsalRestconfStrategy) LOCAL_STRATEGY.getAcquire(this));
161     }
162
163     @PreDestroy
164     @Deactivate
165     @Override
166     public void close() {
167         reg.close();
168         localStrategy = null;
169     }
170
171     @Override
172     public RestconfFuture<Empty> dataDELETE(final ApiPath identifier) {
173         final StrategyAndTail stratAndTail;
174         try {
175             stratAndTail = localStrategy().resolveStrategy(identifier);
176         } catch (RestconfDocumentedException e) {
177             return RestconfFuture.failed(e);
178         }
179         return stratAndTail.strategy().dataDELETE(stratAndTail.tail());
180     }
181
182     @Override
183     public RestconfFuture<DataGetResult> dataGET(final DataGetParams params) {
184         return localStrategy().dataGET(ApiPath.empty(), params);
185     }
186
187     @Override
188     public RestconfFuture<DataGetResult> dataGET(final ApiPath identifier, final DataGetParams params) {
189         final StrategyAndTail stratAndTail;
190         try {
191             stratAndTail = localStrategy().resolveStrategy(identifier);
192         } catch (RestconfDocumentedException e) {
193             return RestconfFuture.failed(e);
194         }
195         return stratAndTail.strategy().dataGET(stratAndTail.tail(), params);
196     }
197
198     @Override
199     public RestconfFuture<DataPatchResult> dataPATCH(final ResourceBody body) {
200         return localStrategy().dataPATCH(ApiPath.empty(), body);
201     }
202
203     @Override
204     public RestconfFuture<DataPatchResult> dataPATCH(final ApiPath identifier, final ResourceBody body) {
205         final StrategyAndTail strategyAndTail;
206         try {
207             strategyAndTail = localStrategy().resolveStrategy(identifier);
208         } catch (RestconfDocumentedException e) {
209             return RestconfFuture.failed(e);
210         }
211         return strategyAndTail.strategy().dataPATCH(strategyAndTail.tail(), body);
212     }
213
214     @Override
215     public RestconfFuture<DataYangPatchResult> dataPATCH(final PatchBody body) {
216         return localStrategy().dataPATCH(ApiPath.empty(), body);
217     }
218
219     @Override
220     public RestconfFuture<DataYangPatchResult> dataPATCH(final ApiPath identifier, final PatchBody body) {
221         final StrategyAndTail strategyAndTail;
222         try {
223             strategyAndTail = localStrategy().resolveStrategy(identifier);
224         } catch (RestconfDocumentedException e) {
225             return RestconfFuture.failed(e);
226         }
227         return strategyAndTail.strategy().dataPATCH(strategyAndTail.tail(), body);
228     }
229
230     @Override
231     public RestconfFuture<CreateResource> dataPOST(final ChildBody body, final Map<String, String> queryParameters) {
232         return localStrategy().dataCreatePOST(body, queryParameters);
233     }
234
235     @Override
236     public RestconfFuture<? extends DataPostResult> dataPOST(final ApiPath identifier, final DataPostBody body,
237             final Map<String, String> queryParameters) {
238         final StrategyAndTail strategyAndTail;
239         try {
240             strategyAndTail = localStrategy().resolveStrategy(identifier);
241         } catch (RestconfDocumentedException e) {
242             return RestconfFuture.failed(e);
243         }
244         return strategyAndTail.strategy().dataPOST(strategyAndTail.tail(), body, queryParameters);
245     }
246
247     @Override
248     public RestconfFuture<DataPutResult> dataPUT(final ResourceBody body, final Map<String, String> query) {
249         return localStrategy().dataPUT(ApiPath.empty(), body, query);
250     }
251
252     @Override
253     public RestconfFuture<DataPutResult> dataPUT(final ApiPath identifier, final ResourceBody body,
254              final Map<String, String> queryParameters) {
255         final StrategyAndTail strategyAndTail;
256         try {
257             strategyAndTail = localStrategy().resolveStrategy(identifier);
258         } catch (RestconfDocumentedException e) {
259             return RestconfFuture.failed(e);
260         }
261         return strategyAndTail.strategy().dataPUT(strategyAndTail.tail(), body, queryParameters);
262     }
263
264     @Override
265     public RestconfFuture<ModulesGetResult> modulesYangGET(final String fileName, final String revision) {
266         return modulesGET(fileName, revision, YangTextSchemaSource.class);
267     }
268
269     @Override
270     public RestconfFuture<ModulesGetResult> modulesYangGET(final ApiPath mountPath, final String fileName,
271             final String revision) {
272         return modulesGET(mountPath, fileName, revision, YangTextSchemaSource.class);
273     }
274
275     @Override
276     public RestconfFuture<ModulesGetResult> modulesYinGET(final String fileName, final String revision) {
277         return modulesGET(fileName, revision, YinTextSchemaSource.class);
278     }
279
280     @Override
281     public RestconfFuture<ModulesGetResult> modulesYinGET(final ApiPath mountPath, final String fileName,
282             final String revision) {
283         return modulesGET(mountPath, fileName, revision, YinTextSchemaSource.class);
284     }
285
286     private @NonNull RestconfFuture<ModulesGetResult> modulesGET(final String fileName, final String revision,
287             final Class<? extends SchemaSourceRepresentation> representation) {
288         return modulesGET(localStrategy(), fileName, revision, representation);
289     }
290
291     private @NonNull RestconfFuture<ModulesGetResult> modulesGET(final ApiPath mountPath, final String fileName,
292             final String revision, final Class<? extends SchemaSourceRepresentation> representation) {
293         final var mountOffset = mountPath.indexOf("yang-ext", "mount");
294         if (mountOffset != mountPath.steps().size() - 1) {
295             return RestconfFuture.failed(new RestconfDocumentedException("Mount path has to end with yang-ext:mount"));
296         }
297
298         final StrategyAndTail stratAndTail;
299         try {
300             stratAndTail = localStrategy().resolveStrategy(mountPath);
301         } catch (RestconfDocumentedException e) {
302             return RestconfFuture.failed(e);
303         }
304         // FIXME: require remnant to be empty
305         return modulesGET(stratAndTail.strategy(), fileName, revision, representation);
306     }
307
308     private static @NonNull RestconfFuture<ModulesGetResult> modulesGET(final RestconfStrategy strategy,
309             final String moduleName, final String revisionStr,
310             final Class<? extends SchemaSourceRepresentation> representation) {
311         if (moduleName == null) {
312             return RestconfFuture.failed(new RestconfDocumentedException("Module name must be supplied",
313                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE));
314         }
315         if (moduleName.isEmpty() || !YangNames.IDENTIFIER_START.matches(moduleName.charAt(0))) {
316             return RestconfFuture.failed(new RestconfDocumentedException(
317                 "Identifier must start with character from set 'a-zA-Z_", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE));
318         }
319         if (moduleName.toUpperCase(Locale.ROOT).startsWith("XML")) {
320             return RestconfFuture.failed(new RestconfDocumentedException(
321                 "Identifier must NOT start with XML ignore case", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE));
322         }
323         if (YangNames.NOT_IDENTIFIER_PART.matchesAnyOf(moduleName.substring(1))) {
324             return RestconfFuture.failed(new RestconfDocumentedException(
325                 "Supplied name has not expected identifier format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE));
326         }
327
328         // YANG Revision-compliant string is required
329         final Revision revision;
330         try {
331             revision = Revision.ofNullable(revisionStr).orElse(null);
332         } catch (final DateTimeParseException e) {
333             return RestconfFuture.failed(new RestconfDocumentedException(
334                 "Supplied revision is not in expected date format YYYY-mm-dd",
335                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
336         }
337
338         return strategy.resolveSource(new SourceIdentifier(moduleName, revision), representation)
339             .transform(ModulesGetResult::new);
340     }
341
342     @Override
343     public RestconfFuture<OperationsGetResult> operationsGET() {
344         return localStrategy().operationsGET();
345     }
346
347     @Override
348     public RestconfFuture<OperationsGetResult> operationsGET(final ApiPath operation) {
349         final StrategyAndTail strategyAndTail;
350         try {
351             strategyAndTail = localStrategy().resolveStrategy(operation);
352         } catch (RestconfDocumentedException e) {
353             return RestconfFuture.failed(e);
354         }
355         return strategyAndTail.strategy().operationsGET(strategyAndTail.tail());
356     }
357
358     @Override
359     public RestconfFuture<OperationsPostResult> operationsPOST(final URI restconfURI, final ApiPath apiPath,
360             final OperationInputBody body) {
361         final StrategyAndTail strategyAndTail;
362         try {
363             strategyAndTail = localStrategy().resolveStrategy(apiPath);
364         } catch (RestconfDocumentedException e) {
365             return RestconfFuture.failed(e);
366         }
367         final var strategy = strategyAndTail.strategy();
368         return strategy.operationsPOST(restconfURI, strategyAndTail.tail(), body);
369     }
370
371     @Override
372     public RestconfFuture<NormalizedNodePayload> yangLibraryVersionGET() {
373         final var stack = SchemaInferenceStack.of(localStrategy().modelContext());
374         try {
375             stack.enterYangData(YangApi.NAME);
376             stack.enterDataTree(Restconf.QNAME);
377             stack.enterDataTree(YANG_LIBRARY_VERSION);
378         } catch (IllegalArgumentException e) {
379             return RestconfFuture.failed(new RestconfDocumentedException("RESTCONF is not available"));
380         }
381         return RestconfFuture.of(new NormalizedNodePayload(stack.toInference(),
382             ImmutableNodes.leafNode(YANG_LIBRARY_VERSION, stack.getEffectiveModelContext()
383                 .findModuleStatements("ietf-yang-library").iterator().next().localQNameModule().getRevision()
384                 .map(Revision::toString).orElse(""))));
385     }
386 }