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