2 * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.restconf.nb.rfc8040.rests.transactions;
10 import static java.util.Objects.requireNonNull;
11 import static org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION;
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import com.google.common.util.concurrent.MoreExecutors;
18 import java.util.ArrayList;
19 import java.util.HashSet;
20 import java.util.List;
21 import java.util.Optional;
23 import org.eclipse.jdt.annotation.NonNull;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.opendaylight.mdsal.common.api.CommitInfo;
26 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
27 import org.opendaylight.mdsal.dom.api.DOMActionService;
28 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
29 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
30 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
31 import org.opendaylight.mdsal.dom.api.DOMRpcService;
32 import org.opendaylight.mdsal.dom.api.DOMSchemaService.YangTextSourceExtension;
33 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
34 import org.opendaylight.restconf.api.query.FieldsParam;
35 import org.opendaylight.restconf.api.query.FieldsParam.NodeSelector;
36 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
37 import org.opendaylight.restconf.common.errors.RestconfFuture;
38 import org.opendaylight.restconf.common.errors.SettableRestconfFuture;
39 import org.opendaylight.restconf.nb.rfc8040.jersey.providers.ParameterAwareNormalizedNodeWriter;
40 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
41 import org.opendaylight.restconf.nb.rfc8040.legacy.WriterParameters;
42 import org.opendaylight.restconf.server.api.DataGetParams;
43 import org.opendaylight.restconf.server.api.DataGetResult;
44 import org.opendaylight.restconf.server.api.DatabindContext;
45 import org.opendaylight.restconf.server.api.DatabindPath.Data;
46 import org.opendaylight.restconf.server.api.QueryParams;
47 import org.opendaylight.restconf.server.spi.RpcImplementation;
48 import org.opendaylight.restconf.server.spi.YangLibraryVersionResource;
49 import org.opendaylight.yangtools.yang.common.Empty;
50 import org.opendaylight.yangtools.yang.common.ErrorTag;
51 import org.opendaylight.yangtools.yang.common.ErrorType;
52 import org.opendaylight.yangtools.yang.common.QName;
53 import org.opendaylight.yangtools.yang.common.QNameModule;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
55 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
56 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
57 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext.PathMixin;
58 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
61 * Implementation of RESTCONF operations using {@link DOMTransactionChain} and related concepts.
63 * @see DOMTransactionChain
64 * @see DOMDataTreeReadWriteTransaction
66 public final class MdsalRestconfStrategy extends RestconfStrategy {
67 private final @NonNull YangLibraryVersionResource yangLibraryVersion;
68 private final @NonNull DOMDataBroker dataBroker;
70 public MdsalRestconfStrategy(final DatabindContext databind, final DOMDataBroker dataBroker,
71 final ImmutableMap<QName, RpcImplementation> localRpcs, final @Nullable DOMRpcService rpcService,
72 final @Nullable DOMActionService actionService, final @Nullable YangTextSourceExtension sourceProvider,
73 final @Nullable DOMMountPointService mountPointService) {
74 super(databind, localRpcs, rpcService, actionService, sourceProvider, mountPointService);
75 this.dataBroker = requireNonNull(dataBroker);
76 yangLibraryVersion = YangLibraryVersionResource.of(databind);
79 public @NonNull RestconfFuture<NormalizedNodePayload> yangLibraryVersionGET(final QueryParams params) {
80 return yangLibraryVersion.httpGET(params);
84 RestconfTransaction prepareWriteExecution() {
85 return new MdsalRestconfTransaction(modelContext(), dataBroker);
89 void delete(final SettableRestconfFuture<Empty> future, final YangInstanceIdentifier path) {
90 final var tx = dataBroker.newReadWriteTransaction();
91 tx.exists(CONFIGURATION, path).addCallback(new FutureCallback<>() {
93 public void onSuccess(final Boolean result) {
95 cancelTx(new RestconfDocumentedException("Data does not exist", ErrorType.PROTOCOL,
96 ErrorTag.DATA_MISSING, path));
100 tx.delete(CONFIGURATION, path);
101 tx.commit().addCallback(new FutureCallback<CommitInfo>() {
103 public void onSuccess(final CommitInfo result) {
104 future.set(Empty.value());
108 public void onFailure(final Throwable cause) {
109 future.setFailure(new RestconfDocumentedException("Transaction to delete " + path + " failed",
112 }, MoreExecutors.directExecutor());
116 public void onFailure(final Throwable cause) {
117 cancelTx(new RestconfDocumentedException("Failed to access " + path, cause));
120 private void cancelTx(final RestconfDocumentedException ex) {
122 future.setFailure(ex);
124 }, MoreExecutors.directExecutor());
128 RestconfFuture<DataGetResult> dataGET(final Data path, final DataGetParams params) {
129 final var inference = path.inference();
130 final var fields = params.fields();
131 return completeDataGET(inference,
132 fields == null ? WriterParameters.of(params.prettyPrint(), params.depth())
133 : new WriterParameters(params.prettyPrint(), params.depth(),
134 translateFieldsParam(inference.modelContext(), path.schema(), fields)),
135 readData(params.content(), path.instance(), params.withDefaults()), null);
139 ListenableFuture<Optional<NormalizedNode>> read(final LogicalDatastoreType store,
140 final YangInstanceIdentifier path) {
141 try (var tx = dataBroker.newReadOnlyTransaction()) {
142 return tx.read(store, path);
147 ListenableFuture<Boolean> exists(final YangInstanceIdentifier path) {
148 try (var tx = dataBroker.newReadOnlyTransaction()) {
149 return tx.exists(LogicalDatastoreType.CONFIGURATION, path);
154 * Translate a {@link FieldsParam} to a complete list of child nodes organized into levels, suitable for use with
155 * {@link ParameterAwareNormalizedNodeWriter}.
158 * Fields parser that stores set of {@link QName}s in each level. Because of this fact, from the output it is only
159 * possible to assume on what depth the selected element is placed. Identifiers of intermediary mixin nodes are also
160 * flatten to the same level as identifiers of data nodes.<br>
161 * Example: field 'a(/b/c);d/e' ('e' is place under choice node 'x') is parsed into following levels:<br>
163 * level 0: ['a', 'd']
164 * level 1: ['b', 'x', 'e']
168 * @param modelContext EffectiveModelContext
169 * @param startNode {@link DataSchemaContext} of the API request path
170 * @param input input value of fields parameter
171 * @return {@link List} of levels; each level contains set of {@link QName}
174 public static @NonNull List<Set<QName>> translateFieldsParam(final @NonNull EffectiveModelContext modelContext,
175 final DataSchemaContext startNode, final @NonNull FieldsParam input) {
176 final var parsed = new ArrayList<Set<QName>>();
177 processSelectors(parsed, modelContext, startNode.dataSchemaNode().getQName().getModule(), startNode,
178 input.nodeSelectors(), 0);
182 private static void processSelectors(final List<Set<QName>> parsed, final EffectiveModelContext context,
183 final QNameModule startNamespace, final DataSchemaContext startNode, final List<NodeSelector> selectors,
185 final Set<QName> startLevel;
186 if (parsed.size() <= index) {
187 startLevel = new HashSet<>();
188 parsed.add(startLevel);
190 startLevel = parsed.get(index);
192 for (var selector : selectors) {
193 var node = startNode;
194 var namespace = startNamespace;
195 var level = startLevel;
196 var levelIndex = index;
198 // Note: path is guaranteed to have at least one step
199 final var it = selector.path().iterator();
201 // FIXME: The layout of this loop is rather weird, which is due to how prepareQNameLevel() operates. We
202 // need to call it only when we know there is another identifier coming, otherwise we would end
203 // up with empty levels sneaking into the mix.
205 // Dealing with that weirdness requires understanding what the expected end results are and a
206 // larger rewrite of the algorithms involved.
207 final var step = it.next();
208 final var module = step.module();
209 if (module != null) {
210 // FIXME: this is not defensive enough, as we can fail to find the module
211 namespace = context.findModules(module).iterator().next().getQNameModule();
214 // add parsed identifier to results for current level
215 node = addChildToResult(node, step.identifier().bindTo(namespace), level);
221 level = prepareQNameLevel(parsed, level);
225 final var subs = selector.subSelectors();
226 if (!subs.isEmpty()) {
227 processSelectors(parsed, context, namespace, node, subs, levelIndex + 1);
233 * Preparation of the identifiers level that is used as storage for parsed identifiers. If the current level exist
234 * at the index that doesn't equal to the last index of already parsed identifiers, a new level of identifiers
235 * is allocated and pushed to input parsed identifiers.
237 * @param parsedIdentifiers Already parsed list of identifiers grouped to multiple levels.
238 * @param currentLevel Current level of identifiers (set).
239 * @return Existing or new level of identifiers.
241 private static Set<QName> prepareQNameLevel(final List<Set<QName>> parsedIdentifiers,
242 final Set<QName> currentLevel) {
243 final var existingLevel = parsedIdentifiers.stream()
244 .filter(qNameSet -> qNameSet.equals(currentLevel))
246 if (existingLevel.isPresent()) {
247 final int index = parsedIdentifiers.indexOf(existingLevel.orElseThrow());
248 if (index == parsedIdentifiers.size() - 1) {
249 final var nextLevel = new HashSet<QName>();
250 parsedIdentifiers.add(nextLevel);
254 return parsedIdentifiers.get(index + 1);
257 final var nextLevel = new HashSet<QName>();
258 parsedIdentifiers.add(nextLevel);
263 * Add parsed child of current node to result for current level.
265 * @param currentNode current node
266 * @param childQName parsed identifier of child node
267 * @param level current nodes level
268 * @return {@link DataSchemaContextNode}
270 private static DataSchemaContext addChildToResult(final DataSchemaContext currentNode, final QName childQName,
271 final Set<QName> level) {
272 // resolve parent node
273 final var parentNode = resolveMixinNode(currentNode, level, currentNode.dataSchemaNode().getQName());
274 if (parentNode == null) {
275 throw new RestconfDocumentedException(
276 "Not-mixin node missing in " + currentNode.getPathStep().getNodeType().getLocalName(),
277 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
280 // resolve child node
281 final DataSchemaContext childNode = resolveMixinNode(childByQName(parentNode, childQName), level, childQName);
282 if (childNode == null) {
283 throw new RestconfDocumentedException(
284 "Child " + childQName.getLocalName() + " node missing in "
285 + currentNode.getPathStep().getNodeType().getLocalName(),
286 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
289 // add final childNode node to level nodes
290 level.add(childNode.dataSchemaNode().getQName());
294 private static @Nullable DataSchemaContext childByQName(final DataSchemaContext parent, final QName qname) {
295 return parent instanceof DataSchemaContext.Composite composite ? composite.childByQName(qname) : null;
299 * Resolve mixin node by searching for inner nodes until not mixin node or null is found.
300 * All nodes expect of not mixin node are added to current level nodes.
302 * @param node initial mixin or not-mixin node
303 * @param level current nodes level
304 * @param qualifiedName qname of initial node
305 * @return {@link DataSchemaContextNode}
307 private static @Nullable DataSchemaContext resolveMixinNode(final @Nullable DataSchemaContext node,
308 final @NonNull Set<QName> level, final @NonNull QName qualifiedName) {
309 DataSchemaContext currentNode = node;
310 while (currentNode instanceof PathMixin currentMixin) {
311 level.add(qualifiedName);
312 currentNode = currentMixin.childByQName(qualifiedName);