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