4a14e6b1362d87f09b510d04b1db522c4b86f2a5
[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 java.lang.invoke.MethodHandles;
16 import java.lang.invoke.VarHandle;
17 import java.net.URI;
18 import java.time.format.DateTimeParseException;
19 import java.util.List;
20 import java.util.Locale;
21 import java.util.Map;
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.mdsal.dom.api.DOMSchemaService;
32 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
33 import org.opendaylight.restconf.api.ApiPath;
34 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
35 import org.opendaylight.restconf.common.errors.RestconfFuture;
36 import org.opendaylight.restconf.nb.rfc8040.databind.ChildBody;
37 import org.opendaylight.restconf.nb.rfc8040.databind.DataPostBody;
38 import org.opendaylight.restconf.nb.rfc8040.databind.OperationInputBody;
39 import org.opendaylight.restconf.nb.rfc8040.databind.PatchBody;
40 import org.opendaylight.restconf.nb.rfc8040.databind.ResourceBody;
41 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
42 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.MdsalRestconfStrategy;
43 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfStrategy;
44 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfStrategy.StrategyAndTail;
45 import org.opendaylight.restconf.server.api.DataGetParams;
46 import org.opendaylight.restconf.server.api.DataGetResult;
47 import org.opendaylight.restconf.server.api.DataPatchResult;
48 import org.opendaylight.restconf.server.api.DataPostResult;
49 import org.opendaylight.restconf.server.api.DataPostResult.CreateResource;
50 import org.opendaylight.restconf.server.api.DataPutResult;
51 import org.opendaylight.restconf.server.api.DataYangPatchResult;
52 import org.opendaylight.restconf.server.api.DatabindContext;
53 import org.opendaylight.restconf.server.api.ModulesGetResult;
54 import org.opendaylight.restconf.server.api.OperationsGetResult;
55 import org.opendaylight.restconf.server.api.OperationsPostResult;
56 import org.opendaylight.restconf.server.api.RestconfServer;
57 import org.opendaylight.restconf.server.spi.DatabindProvider;
58 import org.opendaylight.restconf.server.spi.RpcImplementation;
59 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.restconf.rev170126.YangApi;
60 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.restconf.rev170126.restconf.Restconf;
61 import org.opendaylight.yangtools.concepts.Registration;
62 import org.opendaylight.yangtools.yang.common.Empty;
63 import org.opendaylight.yangtools.yang.common.ErrorTag;
64 import org.opendaylight.yangtools.yang.common.ErrorType;
65 import org.opendaylight.yangtools.yang.common.QName;
66 import org.opendaylight.yangtools.yang.common.Revision;
67 import org.opendaylight.yangtools.yang.common.YangNames;
68 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
69 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
70 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextListener;
71 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
72 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
73 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
74 import org.opendaylight.yangtools.yang.model.repo.api.YinTextSchemaSource;
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
89         implements RestconfServer, DatabindProvider, EffectiveModelContextListener, AutoCloseable {
90     private static final Logger LOG = LoggerFactory.getLogger(MdsalRestconfServer.class);
91     private static final QName YANG_LIBRARY_VERSION = QName.create(Restconf.QNAME, "yang-library-version").intern();
92     private static final VarHandle LOCAL_STRATEGY;
93
94     static {
95         try {
96             LOCAL_STRATEGY = MethodHandles.lookup()
97                 .findVarHandle(MdsalRestconfServer.class, "localStrategy", MdsalRestconfStrategy.class);
98         } catch (NoSuchFieldException | IllegalAccessException e) {
99             throw new ExceptionInInitializerError(e);
100         }
101     }
102
103     private final @NonNull ImmutableMap<QName, RpcImplementation> localRpcs;
104     private final @NonNull DOMMountPointService mountPointService;
105     private final @NonNull DOMDataBroker dataBroker;
106     private final @Nullable DOMRpcService rpcService;
107     private final @Nullable DOMActionService actionService;
108     private final @Nullable DOMYangTextSourceProvider sourceProvider;
109
110     private final Registration reg;
111
112     @SuppressWarnings("unused")
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.getExtensions().getInstance(DOMYangTextSourceProvider.class);
128
129         localStrategy = createLocalStrategy(schemaService.getGlobalContext());
130         reg = schemaService.registerSchemaContextListener(this);
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     @Override
145     public void onModelContextUpdated(final EffectiveModelContext newModelContext) {
146         final var local = localStrategy();
147         if (!newModelContext.equals(local.modelContext())) {
148             LOCAL_STRATEGY.setRelease(this, createLocalStrategy(newModelContext));
149         }
150     }
151
152     private @NonNull MdsalRestconfStrategy createLocalStrategy(final EffectiveModelContext modelContext) {
153         return new MdsalRestconfStrategy(DatabindContext.ofModel(modelContext), dataBroker, rpcService, actionService,
154             sourceProvider, mountPointService, localRpcs);
155     }
156
157     private @NonNull MdsalRestconfStrategy localStrategy() {
158         return verifyNotNull((MdsalRestconfStrategy) LOCAL_STRATEGY.getAcquire(this));
159     }
160
161     @PreDestroy
162     @Deactivate
163     @Override
164     public void close() {
165         reg.close();
166         localStrategy = null;
167     }
168
169     @Override
170     public RestconfFuture<Empty> dataDELETE(final ApiPath identifier) {
171         final StrategyAndTail stratAndTail;
172         try {
173             stratAndTail = localStrategy().resolveStrategy(identifier);
174         } catch (RestconfDocumentedException e) {
175             return RestconfFuture.failed(e);
176         }
177         return stratAndTail.strategy().dataDELETE(stratAndTail.tail());
178     }
179
180     @Override
181     public RestconfFuture<DataGetResult> dataGET(final DataGetParams params) {
182         return localStrategy().dataGET(ApiPath.empty(), params);
183     }
184
185     @Override
186     public RestconfFuture<DataGetResult> dataGET(final ApiPath identifier, final DataGetParams params) {
187         final StrategyAndTail stratAndTail;
188         try {
189             stratAndTail = localStrategy().resolveStrategy(identifier);
190         } catch (RestconfDocumentedException e) {
191             return RestconfFuture.failed(e);
192         }
193         return stratAndTail.strategy().dataGET(stratAndTail.tail(), params);
194     }
195
196     @Override
197     public RestconfFuture<DataPatchResult> dataPATCH(final ResourceBody body) {
198         return localStrategy().dataPATCH(ApiPath.empty(), body);
199     }
200
201     @Override
202     public RestconfFuture<DataPatchResult> dataPATCH(final ApiPath identifier, final ResourceBody body) {
203         final StrategyAndTail strategyAndTail;
204         try {
205             strategyAndTail = localStrategy().resolveStrategy(identifier);
206         } catch (RestconfDocumentedException e) {
207             return RestconfFuture.failed(e);
208         }
209         return strategyAndTail.strategy().dataPATCH(strategyAndTail.tail(), body);
210     }
211
212     @Override
213     public RestconfFuture<DataYangPatchResult> dataPATCH(final PatchBody body) {
214         return localStrategy().dataPATCH(ApiPath.empty(), body);
215     }
216
217     @Override
218     public RestconfFuture<DataYangPatchResult> dataPATCH(final ApiPath identifier, final PatchBody body) {
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().dataPATCH(strategyAndTail.tail(), body);
226     }
227
228     @Override
229     public RestconfFuture<CreateResource> dataPOST(final ChildBody body, final Map<String, String> queryParameters) {
230         return localStrategy().dataCreatePOST(body, queryParameters);
231     }
232
233     @Override
234     public RestconfFuture<? extends DataPostResult> dataPOST(final ApiPath identifier, final DataPostBody 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().dataPOST(strategyAndTail.tail(), body, queryParameters);
243     }
244
245     @Override
246     public RestconfFuture<DataPutResult> dataPUT(final ResourceBody body, final Map<String, String> query) {
247         return localStrategy().dataPUT(ApiPath.empty(), body, query);
248     }
249
250     @Override
251     public RestconfFuture<DataPutResult> dataPUT(final ApiPath identifier, final ResourceBody body,
252              final Map<String, String> queryParameters) {
253         final StrategyAndTail strategyAndTail;
254         try {
255             strategyAndTail = localStrategy().resolveStrategy(identifier);
256         } catch (RestconfDocumentedException e) {
257             return RestconfFuture.failed(e);
258         }
259         return strategyAndTail.strategy().dataPUT(strategyAndTail.tail(), body, queryParameters);
260     }
261
262     @Override
263     public RestconfFuture<ModulesGetResult> modulesYangGET(final String fileName, final String revision) {
264         return modulesGET(fileName, revision, YangTextSchemaSource.class);
265     }
266
267     @Override
268     public RestconfFuture<ModulesGetResult> modulesYangGET(final ApiPath mountPath, final String fileName,
269             final String revision) {
270         return modulesGET(mountPath, fileName, revision, YangTextSchemaSource.class);
271     }
272
273     @Override
274     public RestconfFuture<ModulesGetResult> modulesYinGET(final String fileName, final String revision) {
275         return modulesGET(fileName, revision, YinTextSchemaSource.class);
276     }
277
278     @Override
279     public RestconfFuture<ModulesGetResult> modulesYinGET(final ApiPath mountPath, final String fileName,
280             final String revision) {
281         return modulesGET(mountPath, fileName, revision, YinTextSchemaSource.class);
282     }
283
284     private @NonNull RestconfFuture<ModulesGetResult> modulesGET(final String fileName, final String revision,
285             final Class<? extends SchemaSourceRepresentation> representation) {
286         return modulesGET(localStrategy(), fileName, revision, representation);
287     }
288
289     private @NonNull RestconfFuture<ModulesGetResult> modulesGET(final ApiPath mountPath, final String fileName,
290             final String revision, final Class<? extends SchemaSourceRepresentation> representation) {
291         final var mountOffset = mountPath.indexOf("yang-ext", "mount");
292         if (mountOffset != mountPath.steps().size() - 1) {
293             return RestconfFuture.failed(new RestconfDocumentedException("Mount path has to end with yang-ext:mount"));
294         }
295
296         final StrategyAndTail stratAndTail;
297         try {
298             stratAndTail = localStrategy().resolveStrategy(mountPath);
299         } catch (RestconfDocumentedException e) {
300             return RestconfFuture.failed(e);
301         }
302         // FIXME: require remnant to be empty
303         return modulesGET(stratAndTail.strategy(), fileName, revision, representation);
304     }
305
306     private static @NonNull RestconfFuture<ModulesGetResult> modulesGET(final RestconfStrategy strategy,
307             final String moduleName, final String revisionStr,
308             final Class<? extends SchemaSourceRepresentation> representation) {
309         if (moduleName == null) {
310             return RestconfFuture.failed(new RestconfDocumentedException("Module name must be supplied",
311                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE));
312         }
313         if (moduleName.isEmpty() || !YangNames.IDENTIFIER_START.matches(moduleName.charAt(0))) {
314             return RestconfFuture.failed(new RestconfDocumentedException(
315                 "Identifier must start with character from set 'a-zA-Z_", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE));
316         }
317         if (moduleName.toUpperCase(Locale.ROOT).startsWith("XML")) {
318             return RestconfFuture.failed(new RestconfDocumentedException(
319                 "Identifier must NOT start with XML ignore case", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE));
320         }
321         if (YangNames.NOT_IDENTIFIER_PART.matchesAnyOf(moduleName.substring(1))) {
322             return RestconfFuture.failed(new RestconfDocumentedException(
323                 "Supplied name has not expected identifier format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE));
324         }
325
326         // YANG Revision-compliant string is required
327         final Revision revision;
328         try {
329             revision = Revision.ofNullable(revisionStr).orElse(null);
330         } catch (final DateTimeParseException e) {
331             return RestconfFuture.failed(new RestconfDocumentedException(
332                 "Supplied revision is not in expected date format YYYY-mm-dd",
333                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
334         }
335
336         return strategy.resolveSource(new SourceIdentifier(moduleName, revision), representation)
337             .transform(ModulesGetResult::new);
338     }
339
340     @Override
341     public RestconfFuture<OperationsGetResult> operationsGET() {
342         return localStrategy().operationsGET();
343     }
344
345     @Override
346     public RestconfFuture<OperationsGetResult> operationsGET(final ApiPath operation) {
347         final StrategyAndTail strategyAndTail;
348         try {
349             strategyAndTail = localStrategy().resolveStrategy(operation);
350         } catch (RestconfDocumentedException e) {
351             return RestconfFuture.failed(e);
352         }
353         return strategyAndTail.strategy().operationsGET(strategyAndTail.tail());
354     }
355
356     @Override
357     public RestconfFuture<OperationsPostResult> operationsPOST(final URI restconfURI, final ApiPath apiPath,
358             final OperationInputBody body) {
359         final StrategyAndTail strategyAndTail;
360         try {
361             strategyAndTail = localStrategy().resolveStrategy(apiPath);
362         } catch (RestconfDocumentedException e) {
363             return RestconfFuture.failed(e);
364         }
365         final var strategy = strategyAndTail.strategy();
366         return strategy.operationsPOST(restconfURI, strategyAndTail.tail(), body);
367     }
368
369     @Override
370     public RestconfFuture<NormalizedNodePayload> yangLibraryVersionGET() {
371         final var stack = SchemaInferenceStack.of(localStrategy().modelContext());
372         try {
373             stack.enterYangData(YangApi.NAME);
374             stack.enterDataTree(Restconf.QNAME);
375             stack.enterDataTree(YANG_LIBRARY_VERSION);
376         } catch (IllegalArgumentException e) {
377             return RestconfFuture.failed(new RestconfDocumentedException("RESTCONF is not available"));
378         }
379         return RestconfFuture.of(new NormalizedNodePayload(stack.toInference(),
380             ImmutableNodes.leafNode(YANG_LIBRARY_VERSION, stack.getEffectiveModelContext()
381                 .findModuleStatements("ietf-yang-library").iterator().next().localQNameModule().getRevision()
382                 .map(Revision::toString).orElse(""))));
383     }
384 }