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