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