Fix ApiPathNormalizer value handling
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / server / spi / ApiPathNormalizer.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. 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.spi;
9
10 import static com.google.common.base.Verify.verify;
11 import static com.google.common.base.Verify.verifyNotNull;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.base.VerifyException;
15 import com.google.common.collect.ImmutableMap;
16 import java.util.ArrayList;
17 import java.util.List;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.opendaylight.restconf.api.ApiPath;
21 import org.opendaylight.restconf.api.ApiPath.ListInstance;
22 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
23 import org.opendaylight.restconf.nb.rfc8040.Insert.PointNormalizer;
24 import org.opendaylight.restconf.server.api.DatabindContext;
25 import org.opendaylight.restconf.server.spi.ApiPathNormalizer.Path.Data;
26 import org.opendaylight.restconf.server.spi.ApiPathNormalizer.Path.Rpc;
27 import org.opendaylight.yangtools.yang.common.ErrorTag;
28 import org.opendaylight.yangtools.yang.common.ErrorType;
29 import org.opendaylight.yangtools.yang.common.QName;
30 import org.opendaylight.yangtools.yang.common.QNameModule;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
35 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
36 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext.PathMixin;
37 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
38 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
40 import org.opendaylight.yangtools.yang.model.api.EffectiveStatementInference;
41 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.stmt.ActionEffectiveStatement;
44 import org.opendaylight.yangtools.yang.model.api.stmt.InputEffectiveStatement;
45 import org.opendaylight.yangtools.yang.model.api.stmt.OutputEffectiveStatement;
46 import org.opendaylight.yangtools.yang.model.api.stmt.RpcEffectiveStatement;
47 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
48 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
49 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
50
51 /**
52  * Utility for normalizing {@link ApiPath}s. An {@link ApiPath} can represent a number of different constructs, as
53  * denoted to in the {@link Path} interface hierarchy.
54  *
55  * <p>
56  * This process is governed by
57  * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-3.5.3">RFC8040, section 3.5.3</a>. The URI provides the
58  * equivalent of NETCONF XML filter encoding, with data values being escaped RFC7891 strings.
59  */
60 public final class ApiPathNormalizer implements PointNormalizer {
61     /**
62      * A normalized {@link ApiPath}. This can be either
63      * <ul>
64      *   <li>a {@link Data} pointing to a datastore resource, or</li>
65      *   <li>an {@link Rpc} pointing to a YANG {@code rpc} statement, or</li>
66      *   <li>an {@link Action} pointing to an instantiation of a YANG {@code action} statement</li>
67      * </ul>
68      */
69     @NonNullByDefault
70     public sealed interface Path {
71         /**
72          * Returns the {@link EffectiveStatementInference} made by this path.
73          *
74          * @return the {@link EffectiveStatementInference} made by this path
75          */
76         Inference inference();
77
78         /**
79          * A {@link Path} denoting an invocation of a YANG {@code action}.
80          *
81          * @param inference the {@link EffectiveStatementInference} made by this path
82          * @param instance the {@link YangInstanceIdentifier} of the instance being referenced, guaranteed to be
83          *        non-empty
84          * @param action the {@code action}
85          */
86         record Action(Inference inference, YangInstanceIdentifier instance, ActionEffectiveStatement action)
87                 implements OperationPath, InstanceReference {
88             public Action {
89                 requireNonNull(inference);
90                 requireNonNull(action);
91                 if (instance.isEmpty()) {
92                     throw new IllegalArgumentException("action must be instantiated on a data resource");
93                 }
94             }
95
96             @Override
97             public InputEffectiveStatement inputStatement() {
98                 return action.input();
99             }
100
101             @Override
102             public OutputEffectiveStatement outputStatement() {
103                 return action.output();
104             }
105         }
106
107         /**
108          * A {@link Path} denoting a datastore instance.
109          *
110          * @param inference the {@link EffectiveStatementInference} made by this path
111          * @param instance the {@link YangInstanceIdentifier} of the instance being referenced,
112          *                 {@link YangInstanceIdentifier#empty()} denotes the datastore
113          * @param schema the {@link DataSchemaContext} of the datastore instance
114          */
115         // FIXME: split into 'Datastore' and 'Data' with non-empty instance, so we can bind to correct
116         //        instance-identifier semantics, which does not allow YangInstanceIdentifier.empty()
117         record Data(Inference inference, YangInstanceIdentifier instance, DataSchemaContext schema)
118                 implements InstanceReference {
119             public Data {
120                 requireNonNull(inference);
121                 requireNonNull(instance);
122                 requireNonNull(schema);
123             }
124         }
125
126         /**
127          * A {@link Path} denoting an invocation of a YANG {@code rpc}.
128          *
129          * @param inference the {@link EffectiveStatementInference} made by this path
130          * @param rpc the {@code rpc}
131          */
132         record Rpc(Inference inference, RpcEffectiveStatement rpc) implements OperationPath {
133             public Rpc {
134                 requireNonNull(inference);
135                 requireNonNull(rpc);
136             }
137
138             @Override
139             public InputEffectiveStatement inputStatement() {
140                 return rpc.input();
141             }
142
143             @Override
144             public OutputEffectiveStatement outputStatement() {
145                 return rpc.output();
146             }
147         }
148     }
149
150     /**
151      * An intermediate trait of {@link Path}s which are referencing a YANG data resource. This can be either
152      * a {@link Data}, or an {@link Action}}.
153      */
154     @NonNullByDefault
155     public sealed interface InstanceReference extends Path {
156         /**
157          * Returns the {@link YangInstanceIdentifier} of the instance being referenced.
158          *
159          * @return the {@link YangInstanceIdentifier} of the instance being referenced,
160          *         {@link YangInstanceIdentifier#empty()} denotes the datastora
161          */
162         YangInstanceIdentifier instance();
163     }
164
165     /**
166      * An intermediate trait of {@link Path}s which are referencing a YANG operation. This can be either
167      * an {@link Action} on an {@link Rpc}.
168      */
169     @NonNullByDefault
170     public sealed interface OperationPath extends Path {
171         /**
172          * Returns the {@code input} statement of this operation.
173          *
174          * @return the {@code input} statement of this operation
175          */
176         InputEffectiveStatement inputStatement();
177
178         /**
179          * Returns the {@code output} statement of this operation.
180          *
181          * @return the {@code output} statement of this operation
182          */
183         OutputEffectiveStatement outputStatement();
184     }
185
186     private final @NonNull EffectiveModelContext modelContext;
187     private final @NonNull DatabindContext databind;
188
189     public ApiPathNormalizer(final DatabindContext databind) {
190         this.databind = requireNonNull(databind);
191         modelContext = databind.modelContext();
192     }
193
194     public @NonNull Path normalizePath(final ApiPath apiPath) {
195         final var it = apiPath.steps().iterator();
196         if (!it.hasNext()) {
197             return new Data(Inference.ofDataTreePath(modelContext), YangInstanceIdentifier.of(),
198                 databind.schemaTree().getRoot());
199         }
200
201         // First step is somewhat special:
202         // - it has to contain a module qualifier
203         // - it has to consider RPCs, for which we need SchemaContext
204         //
205         // We therefore peel that first iteration here and not worry about those details in further iterations
206         var step = it.next();
207         final var firstModule = step.module();
208         if (firstModule == null) {
209             throw new RestconfDocumentedException(
210                 "First member must use namespace-qualified form, '" + step.identifier() + "' does not",
211                 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
212         }
213
214         var namespace = resolveNamespace(firstModule);
215         var qname = step.identifier().bindTo(namespace);
216
217         // We go through more modern APIs here to get this special out of the way quickly
218         final var optRpc = modelContext.findModuleStatement(namespace).orElseThrow()
219             .findSchemaTreeNode(RpcEffectiveStatement.class, qname);
220         if (optRpc.isPresent()) {
221             final var rpc = optRpc.orElseThrow();
222
223             // We have found an RPC match,
224             if (it.hasNext()) {
225                 throw new RestconfDocumentedException("First step in the path resolves to RPC '" + qname + "' and "
226                     + "therefore it must be the only step present", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
227             }
228             if (step instanceof ListInstance) {
229                 throw new RestconfDocumentedException("First step in the path resolves to RPC '" + qname + "' and "
230                     + "therefore it must not contain key values", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
231             }
232
233             final var stack = SchemaInferenceStack.of(modelContext);
234             final var stmt = stack.enterSchemaTree(rpc.argument());
235             verify(rpc.equals(stmt), "Expecting %s, inferred %s", rpc, stmt);
236             return new OperationPath.Rpc(stack.toInference(), rpc);
237         }
238
239         final var stack = SchemaInferenceStack.of(modelContext);
240         final var path = new ArrayList<PathArgument>();
241         DataSchemaContext parentNode = databind.schemaTree().getRoot();
242         while (true) {
243             final var parentSchema = parentNode.dataSchemaNode();
244             if (parentSchema instanceof ActionNodeContainer actionParent) {
245                 final var optAction = actionParent.findAction(qname);
246                 if (optAction.isPresent()) {
247                     final var action = optAction.orElseThrow();
248
249                     if (it.hasNext()) {
250                         throw new RestconfDocumentedException("Request path resolves to action '" + qname + "' and "
251                             + "therefore it must not continue past it", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
252                     }
253                     if (step instanceof ListInstance) {
254                         throw new RestconfDocumentedException("Request path resolves to action '" + qname + "' and "
255                             + "therefore it must not contain key values",
256                             ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
257                     }
258
259                     final var stmt = stack.enterSchemaTree(qname);
260                     final var actionStmt = action.asEffectiveStatement();
261                     verify(actionStmt.equals(stmt), "Expecting %s, inferred %s", actionStmt, stmt);
262
263                     return new OperationPath.Action(stack.toInference(), YangInstanceIdentifier.of(path), actionStmt);
264                 }
265             }
266
267             // Resolve the child step with respect to data schema tree
268             final var found = parentNode instanceof DataSchemaContext.Composite composite
269                 ? composite.enterChild(stack, qname) : null;
270             if (found == null) {
271                 throw new RestconfDocumentedException("Schema for '" + qname + "' not found",
272                     ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
273             }
274
275             // Now add all mixins encountered to the path
276             var childNode = found;
277             while (childNode instanceof PathMixin currentMixin) {
278                 path.add(currentMixin.mixinPathStep());
279                 childNode = verifyNotNull(currentMixin.enterChild(stack, qname),
280                     "Mixin %s is missing child for %s while resolving %s", childNode, qname, found);
281             }
282
283             final PathArgument pathArg;
284             if (step instanceof ListInstance listStep) {
285                 final var values = listStep.keyValues();
286                 final var schema = childNode.dataSchemaNode();
287                 pathArg = schema instanceof ListSchemaNode listSchema
288                     ? prepareNodeWithPredicates(stack, qname, listSchema, values)
289                         // FIXME: recognize only leaf-list here, which has only a single item
290                         : prepareNodeWithValue(stack, qname, schema, values);
291             } else {
292                 if (childNode.dataSchemaNode() instanceof ListSchemaNode list && !list.getKeyDefinition().isEmpty()) {
293                     throw new RestconfDocumentedException(
294                         "Entry '" + qname + "' requires key or value predicate to be present.",
295                         ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE);
296                 }
297                 pathArg = childNode.getPathStep();
298             }
299
300             path.add(pathArg);
301
302             if (!it.hasNext()) {
303                 return new Data(stack.toInference(), YangInstanceIdentifier.of(path), childNode);
304             }
305
306             parentNode = childNode;
307             step = it.next();
308             final var module = step.module();
309             if (module != null) {
310                 namespace = resolveNamespace(module);
311             }
312
313             qname = step.identifier().bindTo(namespace);
314         }
315     }
316
317     public @NonNull Data normalizeDataPath(final ApiPath apiPath) {
318         final var path = normalizePath(apiPath);
319         if (path instanceof Data dataPath) {
320             return dataPath;
321         }
322         throw new RestconfDocumentedException("Point '" + apiPath + "' resolves to non-data " + path,
323             ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
324     }
325
326     @Override
327     public PathArgument normalizePoint(final ApiPath value) {
328         final var path = normalizePath(value);
329         if (path instanceof Data dataPath) {
330             final var lastArg = dataPath.instance().getLastPathArgument();
331             if (lastArg != null) {
332                 return lastArg;
333             }
334             throw new IllegalArgumentException("Point '" + value + "' resolves to an empty path");
335         }
336         throw new IllegalArgumentException("Point '" + value + "' resolves to non-data " + path);
337     }
338
339     public Path.@NonNull Rpc normalizeRpcPath(final ApiPath apiPath) {
340         final var steps = apiPath.steps();
341         return switch (steps.size()) {
342             case 0 -> throw new RestconfDocumentedException("RPC name must be present", ErrorType.PROTOCOL,
343                 ErrorTag.DATA_MISSING);
344             case 1 -> normalizeRpcPath(steps.get(0));
345             default -> throw new RestconfDocumentedException(apiPath + " does not refer to an RPC", ErrorType.PROTOCOL,
346                 ErrorTag.DATA_MISSING);
347         };
348     }
349
350     public Path.@NonNull Rpc normalizeRpcPath(final ApiPath.Step step) {
351         final var firstModule = step.module();
352         if (firstModule == null) {
353             throw new RestconfDocumentedException(
354                 "First member must use namespace-qualified form, '" + step.identifier() + "' does not",
355                 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
356         }
357
358         final var namespace = resolveNamespace(firstModule);
359         final var qname = step.identifier().bindTo(namespace);
360         final var stack = SchemaInferenceStack.of(modelContext);
361         final SchemaTreeEffectiveStatement<?> stmt;
362         try {
363             stmt = stack.enterSchemaTree(qname);
364         } catch (IllegalArgumentException e) {
365             throw new RestconfDocumentedException(qname + " does not refer to an RPC", ErrorType.PROTOCOL,
366                 ErrorTag.DATA_MISSING, e);
367         }
368         if (stmt instanceof RpcEffectiveStatement rpc) {
369             return new Rpc(stack.toInference(), rpc);
370         }
371         throw new RestconfDocumentedException(qname + " does not refer to an RPC", ErrorType.PROTOCOL,
372             ErrorTag.DATA_MISSING);
373     }
374
375     public @NonNull InstanceReference normalizeDataOrActionPath(final ApiPath apiPath) {
376         // FIXME: optimize this
377         final var path = normalizePath(apiPath);
378         if (path instanceof Data dataPath) {
379             return dataPath;
380         }
381         if (path instanceof OperationPath.Action actionPath) {
382             return actionPath;
383         }
384         throw new RestconfDocumentedException("Unexpected path " + path, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
385     }
386
387     private NodeIdentifierWithPredicates prepareNodeWithPredicates(final SchemaInferenceStack stack, final QName qname,
388             final @NonNull ListSchemaNode schema, final List<@NonNull String> keyValues) {
389         final var keyDef = schema.getKeyDefinition();
390         final var keySize = keyDef.size();
391         final var varSize = keyValues.size();
392         if (keySize != varSize) {
393             throw new RestconfDocumentedException(
394                 "Schema for " + qname + " requires " + keySize + " key values, " + varSize + " supplied",
395                 ErrorType.PROTOCOL, keySize > varSize ? ErrorTag.MISSING_ATTRIBUTE : ErrorTag.UNKNOWN_ATTRIBUTE);
396         }
397
398         final var values = ImmutableMap.<QName, Object>builderWithExpectedSize(keySize);
399         final var tmp = stack.copy();
400         for (int i = 0; i < keySize; ++i) {
401             final QName keyName = keyDef.get(i);
402             final var child = schema.getDataChildByName(keyName);
403             tmp.enterSchemaTree(keyName);
404             values.put(keyName, prepareValueByType(tmp, child, keyValues.get(i)));
405             tmp.exit();
406         }
407
408         return NodeIdentifierWithPredicates.of(qname, values.build());
409     }
410
411     private Object prepareValueByType(final SchemaInferenceStack stack, final DataSchemaNode schemaNode,
412             final @NonNull String value) {
413         if (schemaNode instanceof TypedDataSchemaNode typedSchema) {
414             return parserJsonValue(stack, typedSchema, value);
415         }
416         throw new VerifyException("Unhandled schema " + schemaNode + " decoding '" + value + "'");
417     }
418
419     private Object parserJsonValue(final SchemaInferenceStack stack, final TypedDataSchemaNode schemaNode,
420             final String value) {
421         // As per https://www.rfc-editor.org/rfc/rfc8040#page-29:
422         //            The syntax for
423         //            "api-identifier" and "key-value" MUST conform to the JSON identifier
424         //            encoding rules in Section 4 of [RFC7951]: The RESTCONF root resource
425         //            path is required.  Additional sub-resource identifiers are optional.
426         //            The characters in a key value string are constrained, and some
427         //            characters need to be percent-encoded, as described in Section 3.5.3.
428         try {
429             return databind.jsonCodecs().codecFor(schemaNode, stack).parseValue(null, value);
430         } catch (IllegalArgumentException e) {
431             throw new RestconfDocumentedException("Invalid value '" + value + "' for " + schemaNode.getQName(),
432                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
433         }
434     }
435
436     private NodeWithValue<?> prepareNodeWithValue(final SchemaInferenceStack stack, final QName qname,
437             final DataSchemaNode schema, final List<String> keyValues) {
438         // TODO: qname should be always equal to schema.getQName(), right?
439         return new NodeWithValue<>(qname, prepareValueByType(stack, schema,
440             // FIXME: ahem: we probably want to do something differently here
441             keyValues.get(0)));
442     }
443
444     private @NonNull QNameModule resolveNamespace(final String moduleName) {
445         final var it = modelContext.findModuleStatements(moduleName).iterator();
446         if (it.hasNext()) {
447             return it.next().localQNameModule();
448         }
449         throw new RestconfDocumentedException("Failed to lookup for module with name '" + moduleName + "'.",
450             ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
451     }
452 }