Eliminate InstanceIdentifierContext
[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.collect.ImmutableMap;
15 import java.util.ArrayList;
16 import java.util.List;
17 import org.eclipse.jdt.annotation.NonNull;
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.opendaylight.restconf.api.ApiPath;
20 import org.opendaylight.restconf.api.ApiPath.ListInstance;
21 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
22 import org.opendaylight.restconf.nb.rfc8040.Insert.PointNormalizer;
23 import org.opendaylight.restconf.server.api.DatabindContext;
24 import org.opendaylight.restconf.server.spi.ApiPathNormalizer.OperationPath.Rpc;
25 import org.opendaylight.yangtools.yang.common.ErrorTag;
26 import org.opendaylight.yangtools.yang.common.ErrorType;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.common.QNameModule;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
33 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
34 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
35 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext.PathMixin;
36 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
37 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
39 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
43 import org.opendaylight.yangtools.yang.model.api.stmt.ActionEffectiveStatement;
44 import org.opendaylight.yangtools.yang.model.api.stmt.IdentityEffectiveStatement;
45 import org.opendaylight.yangtools.yang.model.api.stmt.InputEffectiveStatement;
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.api.type.IdentityrefTypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
51 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
52 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
53
54 /**
55  * Deserializer for {@link String} to {@link YangInstanceIdentifier} for restconf.
56  */
57 public final class ApiPathNormalizer implements PointNormalizer {
58     @NonNullByDefault
59     public sealed interface Path {
60
61         Inference inference();
62     }
63
64     @NonNullByDefault
65     public sealed interface InstanceReference extends Path {
66
67         YangInstanceIdentifier instance();
68     }
69
70     @NonNullByDefault
71     public record DataPath(Inference inference, YangInstanceIdentifier instance, DataSchemaContext schema)
72             implements InstanceReference {
73         public DataPath {
74             requireNonNull(inference);
75             requireNonNull(instance);
76             requireNonNull(schema);
77         }
78     }
79
80     @NonNullByDefault
81     public sealed interface OperationPath extends Path {
82
83         InputEffectiveStatement inputStatement();
84
85         record Action(Inference inference, YangInstanceIdentifier instance, ActionEffectiveStatement action)
86                 implements OperationPath, InstanceReference {
87             public Action {
88                 requireNonNull(inference);
89                 requireNonNull(action);
90                 requireNonNull(instance);
91             }
92
93             @Override
94             public InputEffectiveStatement inputStatement() {
95                 return action.input();
96             }
97         }
98
99         record Rpc(Inference inference, RpcEffectiveStatement rpc) implements OperationPath {
100             public Rpc {
101                 requireNonNull(inference);
102                 requireNonNull(rpc);
103             }
104
105             @Override
106             public InputEffectiveStatement inputStatement() {
107                 return rpc.input();
108             }
109         }
110     }
111
112     private final @NonNull ApiPathInstanceIdentifierCodec instanceIdentifierCodec;
113     private final @NonNull EffectiveModelContext modelContext;
114     private final @NonNull DatabindContext databind;
115
116     public ApiPathNormalizer(final DatabindContext databind) {
117         this.databind = requireNonNull(databind);
118         modelContext = databind.modelContext();
119         instanceIdentifierCodec = new ApiPathInstanceIdentifierCodec(databind);
120     }
121
122     public @NonNull Path normalizePath(final ApiPath apiPath) {
123         final var it = apiPath.steps().iterator();
124         if (!it.hasNext()) {
125             return new DataPath(Inference.ofDataTreePath(modelContext), YangInstanceIdentifier.of(),
126                 databind.schemaTree().getRoot());
127         }
128
129         // First step is somewhat special:
130         // - it has to contain a module qualifier
131         // - it has to consider RPCs, for which we need SchemaContext
132         //
133         // We therefore peel that first iteration here and not worry about those details in further iterations
134         var step = it.next();
135         final var firstModule = step.module();
136         if (firstModule == null) {
137             throw new RestconfDocumentedException(
138                 "First member must use namespace-qualified form, '" + step.identifier() + "' does not",
139                 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
140         }
141
142         var namespace = resolveNamespace(firstModule);
143         var qname = step.identifier().bindTo(namespace);
144
145         // We go through more modern APIs here to get this special out of the way quickly
146         final var optRpc = modelContext.findModuleStatement(namespace).orElseThrow()
147             .findSchemaTreeNode(RpcEffectiveStatement.class, qname);
148         if (optRpc.isPresent()) {
149             final var rpc = optRpc.orElseThrow();
150
151             // We have found an RPC match,
152             if (it.hasNext()) {
153                 throw new RestconfDocumentedException("First step in the path resolves to RPC '" + qname + "' and "
154                     + "therefore it must be the only step present", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
155             }
156             if (step instanceof ListInstance) {
157                 throw new RestconfDocumentedException("First step in the path resolves to RPC '" + qname + "' and "
158                     + "therefore it must not contain key values", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
159             }
160
161             final var stack = SchemaInferenceStack.of(modelContext);
162             final var stmt = stack.enterSchemaTree(rpc.argument());
163             verify(rpc.equals(stmt), "Expecting %s, inferred %s", rpc, stmt);
164             return new OperationPath.Rpc(stack.toInference(), rpc);
165         }
166
167         final var stack = SchemaInferenceStack.of(modelContext);
168         final var path = new ArrayList<PathArgument>();
169         DataSchemaContext parentNode = databind.schemaTree().getRoot();
170         while (true) {
171             final var parentSchema = parentNode.dataSchemaNode();
172             if (parentSchema instanceof ActionNodeContainer actionParent) {
173                 final var optAction = actionParent.findAction(qname);
174                 if (optAction.isPresent()) {
175                     final var action = optAction.orElseThrow();
176
177                     if (it.hasNext()) {
178                         throw new RestconfDocumentedException("Request path resolves to action '" + qname + "' and "
179                             + "therefore it must not continue past it", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
180                     }
181                     if (step instanceof ListInstance) {
182                         throw new RestconfDocumentedException("Request path resolves to action '" + qname + "' and "
183                             + "therefore it must not contain key values",
184                             ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
185                     }
186
187                     final var stmt = stack.enterSchemaTree(qname);
188                     final var actionStmt = action.asEffectiveStatement();
189                     verify(actionStmt.equals(stmt), "Expecting %s, inferred %s", actionStmt, stmt);
190
191                     return new OperationPath.Action(stack.toInference(), YangInstanceIdentifier.of(path), actionStmt);
192                 }
193             }
194
195             // Resolve the child step with respect to data schema tree
196             final var found = parentNode instanceof DataSchemaContext.Composite composite
197                 ? composite.enterChild(stack, qname) : null;
198             if (found == null) {
199                 throw new RestconfDocumentedException("Schema for '" + qname + "' not found",
200                     ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
201             }
202
203             // Now add all mixins encountered to the path
204             var childNode = found;
205             while (childNode instanceof PathMixin currentMixin) {
206                 path.add(currentMixin.mixinPathStep());
207                 childNode = verifyNotNull(currentMixin.enterChild(stack, qname),
208                     "Mixin %s is missing child for %s while resolving %s", childNode, qname, found);
209             }
210
211             final PathArgument pathArg;
212             if (step instanceof ListInstance listStep) {
213                 final var values = listStep.keyValues();
214                 final var schema = childNode.dataSchemaNode();
215                 pathArg = schema instanceof ListSchemaNode listSchema
216                     ? prepareNodeWithPredicates(stack, qname, listSchema, values)
217                         : prepareNodeWithValue(stack, qname, schema, values);
218             } else {
219                 if (childNode.dataSchemaNode() instanceof ListSchemaNode list && !list.getKeyDefinition().isEmpty()) {
220                     throw new RestconfDocumentedException(
221                         "Entry '" + qname + "' requires key or value predicate to be present.",
222                         ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE);
223                 }
224                 pathArg = childNode.getPathStep();
225             }
226
227             path.add(pathArg);
228
229             if (!it.hasNext()) {
230                 return new DataPath(stack.toInference(), YangInstanceIdentifier.of(path), childNode);
231             }
232
233             parentNode = childNode;
234             step = it.next();
235             final var module = step.module();
236             if (module != null) {
237                 namespace = resolveNamespace(module);
238             }
239
240             qname = step.identifier().bindTo(namespace);
241         }
242     }
243
244     public @NonNull DataPath normalizeDataPath(final ApiPath apiPath) {
245         final var path = normalizePath(apiPath);
246         if (path instanceof DataPath dataPath) {
247             return dataPath;
248         }
249         throw new RestconfDocumentedException("Point '" + apiPath + "' resolves to non-data " + path,
250             ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
251     }
252
253     @Override
254     public PathArgument normalizePoint(final ApiPath value) {
255         final var path = normalizePath(value);
256         if (path instanceof DataPath dataPath) {
257             final var lastArg = dataPath.instance().getLastPathArgument();
258             if (lastArg != null) {
259                 return lastArg;
260             }
261             throw new IllegalArgumentException("Point '" + value + "' resolves to an empty path");
262         }
263         throw new IllegalArgumentException("Point '" + value + "' resolves to non-data " + path);
264     }
265
266     public @NonNull Rpc normalizeRpcPath(final ApiPath apiPath) {
267         final var steps = apiPath.steps();
268         return switch (steps.size()) {
269             case 0 -> throw new RestconfDocumentedException("RPC name must be present", ErrorType.PROTOCOL,
270                 ErrorTag.DATA_MISSING);
271             case 1 -> normalizeRpcPath(steps.get(0));
272             default -> throw new RestconfDocumentedException(apiPath + " does not refer to an RPC", ErrorType.PROTOCOL,
273                 ErrorTag.DATA_MISSING);
274         };
275     }
276
277     public @NonNull Rpc normalizeRpcPath(final ApiPath.Step step) {
278         final var firstModule = step.module();
279         if (firstModule == null) {
280             throw new RestconfDocumentedException(
281                 "First member must use namespace-qualified form, '" + step.identifier() + "' does not",
282                 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
283         }
284
285         final var namespace = resolveNamespace(firstModule);
286         final var qname = step.identifier().bindTo(namespace);
287         final var stack = SchemaInferenceStack.of(modelContext);
288         final SchemaTreeEffectiveStatement<?> stmt;
289         try {
290             stmt = stack.enterSchemaTree(qname);
291         } catch (IllegalArgumentException e) {
292             throw new RestconfDocumentedException(qname + " does not refer to an RPC", ErrorType.PROTOCOL,
293                 ErrorTag.DATA_MISSING, e);
294         }
295         if (stmt instanceof RpcEffectiveStatement rpc) {
296             return new Rpc(stack.toInference(), rpc);
297         }
298         throw new RestconfDocumentedException(qname + " does not refer to an RPC", ErrorType.PROTOCOL,
299             ErrorTag.DATA_MISSING);
300     }
301
302     public @NonNull InstanceReference normalizeDataOrActionPath(final ApiPath apiPath) {
303
304
305         // FIXME: optimize this
306         final var path = normalizePath(apiPath);
307         if (path instanceof DataPath dataPath) {
308             return dataPath;
309         }
310         if (path instanceof OperationPath.Action actionPath) {
311             return actionPath;
312         }
313         throw new RestconfDocumentedException("Unexpected path " + path, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
314     }
315
316     private NodeIdentifierWithPredicates prepareNodeWithPredicates(final SchemaInferenceStack stack, final QName qname,
317             final @NonNull ListSchemaNode schema, final List<@NonNull String> keyValues) {
318         final var keyDef = schema.getKeyDefinition();
319         final var keySize = keyDef.size();
320         final var varSize = keyValues.size();
321         if (keySize != varSize) {
322             throw new RestconfDocumentedException(
323                 "Schema for " + qname + " requires " + keySize + " key values, " + varSize + " supplied",
324                 ErrorType.PROTOCOL, keySize > varSize ? ErrorTag.MISSING_ATTRIBUTE : ErrorTag.UNKNOWN_ATTRIBUTE);
325         }
326
327         final var values = ImmutableMap.<QName, Object>builderWithExpectedSize(keySize);
328         final var tmp = stack.copy();
329         for (int i = 0; i < keySize; ++i) {
330             final QName keyName = keyDef.get(i);
331             final var child = schema.getDataChildByName(keyName);
332             tmp.enterSchemaTree(keyName);
333             values.put(keyName, prepareValueByType(tmp, child, keyValues.get(i)));
334             tmp.exit();
335         }
336
337         return NodeIdentifierWithPredicates.of(qname, values.build());
338     }
339
340     private Object prepareValueByType(final SchemaInferenceStack stack, final DataSchemaNode schemaNode,
341             final @NonNull String value) {
342
343         TypeDefinition<? extends TypeDefinition<?>> typedef;
344         if (schemaNode instanceof LeafListSchemaNode leafList) {
345             typedef = leafList.getType();
346         } else {
347             typedef = ((LeafSchemaNode) schemaNode).getType();
348         }
349         if (typedef instanceof LeafrefTypeDefinition leafref) {
350             typedef = stack.resolveLeafref(leafref);
351         }
352
353         if (typedef instanceof IdentityrefTypeDefinition) {
354             return toIdentityrefQName(value, schemaNode);
355         }
356
357         try {
358             if (typedef instanceof InstanceIdentifierTypeDefinition) {
359                 return instanceIdentifierCodec.deserialize(value);
360             }
361
362             return verifyNotNull(TypeDefinitionAwareCodec.from(typedef),
363                 "Unhandled type %s decoding %s", typedef, value).deserialize(value);
364         } catch (IllegalArgumentException e) {
365             throw new RestconfDocumentedException("Invalid value '" + value + "' for " + schemaNode.getQName(),
366                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
367         }
368     }
369
370     private NodeWithValue<?> prepareNodeWithValue(final SchemaInferenceStack stack, final QName qname,
371             final DataSchemaNode schema, final List<String> keyValues) {
372         // TODO: qname should be always equal to schema.getQName(), right?
373         return new NodeWithValue<>(qname, prepareValueByType(stack, schema,
374             // FIXME: ahem: we probably want to do something differently here
375             keyValues.get(0)));
376     }
377
378     private QName toIdentityrefQName(final String value, final DataSchemaNode schemaNode) {
379         final QNameModule namespace;
380         final String localName;
381         final int firstColon = value.indexOf(':');
382         if (firstColon != -1) {
383             namespace = resolveNamespace(value.substring(0, firstColon));
384             localName = value.substring(firstColon + 1);
385         } else {
386             namespace = schemaNode.getQName().getModule();
387             localName = value;
388         }
389
390         return modelContext.getModuleStatement(namespace)
391             .streamEffectiveSubstatements(IdentityEffectiveStatement.class)
392             .map(IdentityEffectiveStatement::argument)
393             .filter(qname -> localName.equals(qname.getLocalName()))
394             .findFirst()
395             .orElseThrow(() -> new RestconfDocumentedException(
396                 "No identity found for '" + localName + "' in namespace " + namespace,
397                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE));
398     }
399
400     private @NonNull QNameModule resolveNamespace(final String moduleName) {
401         final var it = modelContext.findModuleStatements(moduleName).iterator();
402         if (it.hasNext()) {
403             return it.next().localQNameModule();
404         }
405         throw new RestconfDocumentedException("Failed to lookup for module with name '" + moduleName + "'.",
406             ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
407     }
408 }