Refactor pretty printing
[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.common.errors.RestconfDocumentedException;
34 import org.opendaylight.restconf.common.errors.RestconfFuture;
35 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
36 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.MdsalRestconfStrategy;
37 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfStrategy;
38 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfStrategy.StrategyAndTail;
39 import org.opendaylight.restconf.server.api.ChildBody;
40 import org.opendaylight.restconf.server.api.DataGetParams;
41 import org.opendaylight.restconf.server.api.DataGetResult;
42 import org.opendaylight.restconf.server.api.DataPatchResult;
43 import org.opendaylight.restconf.server.api.DataPostBody;
44 import org.opendaylight.restconf.server.api.DataPostResult;
45 import org.opendaylight.restconf.server.api.DataPostResult.CreateResource;
46 import org.opendaylight.restconf.server.api.DataPutResult;
47 import org.opendaylight.restconf.server.api.DataYangPatchResult;
48 import org.opendaylight.restconf.server.api.DatabindContext;
49 import org.opendaylight.restconf.server.api.InvokeResult;
50 import org.opendaylight.restconf.server.api.ModulesGetResult;
51 import org.opendaylight.restconf.server.api.OperationInputBody;
52 import org.opendaylight.restconf.server.api.OperationsGetResult;
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 PatchBody body) {
197         return localStrategy().dataPATCH(ApiPath.empty(), body);
198     }
199
200     @Override
201     public RestconfFuture<DataYangPatchResult> dataPATCH(final ApiPath identifier, final PatchBody 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<CreateResource> dataPOST(final ChildBody body, final Map<String, String> queryParameters) {
213         return localStrategy().dataCreatePOST(body, queryParameters);
214     }
215
216     @Override
217     public RestconfFuture<? extends DataPostResult> dataPOST(final ApiPath identifier, final DataPostBody body,
218             final Map<String, String> queryParameters) {
219         final StrategyAndTail strategyAndTail;
220         try {
221             strategyAndTail = localStrategy().resolveStrategy(identifier);
222         } catch (RestconfDocumentedException e) {
223             return RestconfFuture.failed(e);
224         }
225         return strategyAndTail.strategy().dataPOST(strategyAndTail.tail(), body, queryParameters);
226     }
227
228     @Override
229     public RestconfFuture<DataPutResult> dataPUT(final ResourceBody body, final Map<String, String> query) {
230         return localStrategy().dataPUT(ApiPath.empty(), body, query);
231     }
232
233     @Override
234     public RestconfFuture<DataPutResult> dataPUT(final ApiPath identifier, final ResourceBody body,
235              final Map<String, String> queryParameters) {
236         final StrategyAndTail strategyAndTail;
237         try {
238             strategyAndTail = localStrategy().resolveStrategy(identifier);
239         } catch (RestconfDocumentedException e) {
240             return RestconfFuture.failed(e);
241         }
242         return strategyAndTail.strategy().dataPUT(strategyAndTail.tail(), body, queryParameters);
243     }
244
245     @Override
246     public RestconfFuture<ModulesGetResult> modulesYangGET(final String fileName, final String revision) {
247         return modulesGET(fileName, revision, YangTextSource.class);
248     }
249
250     @Override
251     public RestconfFuture<ModulesGetResult> modulesYangGET(final ApiPath mountPath, final String fileName,
252             final String revision) {
253         return modulesGET(mountPath, fileName, revision, YangTextSource.class);
254     }
255
256     @Override
257     public RestconfFuture<ModulesGetResult> modulesYinGET(final String fileName, final String revision) {
258         return modulesGET(fileName, revision, YinTextSource.class);
259     }
260
261     @Override
262     public RestconfFuture<ModulesGetResult> modulesYinGET(final ApiPath mountPath, final String fileName,
263             final String revision) {
264         return modulesGET(mountPath, fileName, revision, YinTextSource.class);
265     }
266
267     private @NonNull RestconfFuture<ModulesGetResult> modulesGET(final String fileName, final String revision,
268             final Class<? extends SourceRepresentation> representation) {
269         return modulesGET(localStrategy(), fileName, revision, representation);
270     }
271
272     private @NonNull RestconfFuture<ModulesGetResult> modulesGET(final ApiPath mountPath, final String fileName,
273             final String revision, final Class<? extends SourceRepresentation> representation) {
274         final var mountOffset = mountPath.indexOf("yang-ext", "mount");
275         if (mountOffset != mountPath.steps().size() - 1) {
276             return RestconfFuture.failed(new RestconfDocumentedException("Mount path has to end with yang-ext:mount"));
277         }
278
279         final StrategyAndTail stratAndTail;
280         try {
281             stratAndTail = localStrategy().resolveStrategy(mountPath);
282         } catch (RestconfDocumentedException e) {
283             return RestconfFuture.failed(e);
284         }
285         // FIXME: require remnant to be empty
286         return modulesGET(stratAndTail.strategy(), fileName, revision, representation);
287     }
288
289     private static @NonNull RestconfFuture<ModulesGetResult> modulesGET(final RestconfStrategy strategy,
290             final String moduleName, final String revisionStr,
291             final Class<? extends SourceRepresentation> representation) {
292         if (moduleName == null) {
293             return RestconfFuture.failed(new RestconfDocumentedException("Module name must be supplied",
294                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE));
295         }
296         if (moduleName.isEmpty() || !YangNames.IDENTIFIER_START.matches(moduleName.charAt(0))) {
297             return RestconfFuture.failed(new RestconfDocumentedException(
298                 "Identifier must start with character from set 'a-zA-Z_", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE));
299         }
300         if (moduleName.toUpperCase(Locale.ROOT).startsWith("XML")) {
301             return RestconfFuture.failed(new RestconfDocumentedException(
302                 "Identifier must NOT start with XML ignore case", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE));
303         }
304         if (YangNames.NOT_IDENTIFIER_PART.matchesAnyOf(moduleName.substring(1))) {
305             return RestconfFuture.failed(new RestconfDocumentedException(
306                 "Supplied name has not expected identifier format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE));
307         }
308
309         // YANG Revision-compliant string is required
310         final Revision revision;
311         try {
312             revision = Revision.ofNullable(revisionStr).orElse(null);
313         } catch (final DateTimeParseException e) {
314             return RestconfFuture.failed(new RestconfDocumentedException(
315                 "Supplied revision is not in expected date format YYYY-mm-dd",
316                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
317         }
318
319         return strategy.resolveSource(new SourceIdentifier(moduleName, revision), representation)
320             .transform(ModulesGetResult::new);
321     }
322
323     @Override
324     public RestconfFuture<OperationsGetResult> operationsGET() {
325         return localStrategy().operationsGET();
326     }
327
328     @Override
329     public RestconfFuture<OperationsGetResult> operationsGET(final ApiPath operation) {
330         final StrategyAndTail strategyAndTail;
331         try {
332             strategyAndTail = localStrategy().resolveStrategy(operation);
333         } catch (RestconfDocumentedException e) {
334             return RestconfFuture.failed(e);
335         }
336         return strategyAndTail.strategy().operationsGET(strategyAndTail.tail());
337     }
338
339     @Override
340     public RestconfFuture<InvokeResult> operationsPOST(final URI restconfURI, final ApiPath apiPath,
341             final Map<String, String> queryParameters, final OperationInputBody body) {
342         final StrategyAndTail strategyAndTail;
343         try {
344             strategyAndTail = localStrategy().resolveStrategy(apiPath);
345         } catch (RestconfDocumentedException e) {
346             return RestconfFuture.failed(e);
347         }
348         final var strategy = strategyAndTail.strategy();
349         return strategy.operationsPOST(restconfURI, strategyAndTail.tail(), queryParameters, body);
350     }
351
352     @Override
353     public RestconfFuture<NormalizedNodePayload> yangLibraryVersionGET() {
354         final var stack = SchemaInferenceStack.of(localStrategy().modelContext());
355         try {
356             stack.enterYangData(YangApi.NAME);
357             stack.enterDataTree(Restconf.QNAME);
358             stack.enterDataTree(YANG_LIBRARY_VERSION);
359         } catch (IllegalArgumentException e) {
360             return RestconfFuture.failed(new RestconfDocumentedException("RESTCONF is not available"));
361         }
362         return RestconfFuture.of(new NormalizedNodePayload(stack.toInference(),
363             ImmutableNodes.leafNode(YANG_LIBRARY_VERSION, stack.modelContext().findModuleStatements("ietf-yang-library")
364                 .iterator().next().localQNameModule().revisionUnion().unionString())));
365     }
366 }