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