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 com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import com.google.common.util.concurrent.MoreExecutors;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.List;
21 import java.util.NoSuchElementException;
22 import java.util.Optional;
23 import java.util.function.Function;
24 import java.util.stream.Collectors;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.opendaylight.mdsal.common.api.CommitInfo;
28 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
29 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
30 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
31 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
32 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
33 import org.opendaylight.restconf.api.query.ContentParam;
34 import org.opendaylight.restconf.api.query.WithDefaultsParam;
35 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
36 import org.opendaylight.restconf.common.errors.RestconfError;
37 import org.opendaylight.restconf.common.errors.RestconfFuture;
38 import org.opendaylight.restconf.common.errors.SettableRestconfFuture;
39 import org.opendaylight.restconf.common.patch.PatchContext;
40 import org.opendaylight.restconf.common.patch.PatchStatusContext;
41 import org.opendaylight.restconf.common.patch.PatchStatusEntity;
42 import org.opendaylight.restconf.nb.rfc8040.Insert;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.with.defaults.rev110601.WithDefaultsMode;
44 import org.opendaylight.yangtools.yang.common.Empty;
45 import org.opendaylight.yangtools.yang.common.ErrorTag;
46 import org.opendaylight.yangtools.yang.common.ErrorType;
47 import org.opendaylight.yangtools.yang.common.QName;
48 import org.opendaylight.yangtools.yang.common.QNameModule;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
53 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
56 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
62 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
69 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
70 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
71 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
72 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
73 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
74 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
75 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
76 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
77 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
80 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
81 import org.slf4j.Logger;
82 import org.slf4j.LoggerFactory;
85 * Baseline execution strategy for various RESTCONF operations.
87 * @see NetconfRestconfStrategy
88 * @see MdsalRestconfStrategy
90 // FIXME: it seems the first three operations deal with lifecycle of a transaction, while others invoke various
91 // operations. This should be handled through proper allocation indirection.
92 public abstract class RestconfStrategy {
94 * Result of a {@code PUT} request as defined in
95 * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.5">RFC8040 section 4.5</a>. The definition makes it
96 * clear that the logical operation is {@code create-or-replace}.
98 public enum CreateOrReplaceResult {
100 * A new resource has been created.
104 * An existing resources has been replaced.
109 private static final Logger LOG = LoggerFactory.getLogger(RestconfStrategy.class);
111 private final @NonNull EffectiveModelContext modelContext;
113 RestconfStrategy(final EffectiveModelContext modelContext) {
114 this.modelContext = requireNonNull(modelContext);
118 * Look up the appropriate strategy for a particular mount point.
120 * @param modelContext {@link EffectiveModelContext} of target mount point
121 * @param mountPoint Target mount point
122 * @return A strategy, or null if the mount point does not expose a supported interface
123 * @throws NullPointerException if any argument is {@code null}
125 public static @Nullable RestconfStrategy forMountPoint(final EffectiveModelContext modelContext,
126 final DOMMountPoint mountPoint) {
127 final var netconfService = mountPoint.getService(NetconfDataTreeService.class);
128 if (netconfService.isPresent()) {
129 return new NetconfRestconfStrategy(modelContext, netconfService.orElseThrow());
131 final var dataBroker = mountPoint.getService(DOMDataBroker.class);
132 if (dataBroker.isPresent()) {
133 return new MdsalRestconfStrategy(modelContext, dataBroker.orElseThrow());
138 public final @NonNull EffectiveModelContext modelContext() {
143 * Lock the entire datastore.
145 * @return A {@link RestconfTransaction}. This transaction needs to be either committed or canceled before doing
148 abstract RestconfTransaction prepareWriteExecution();
151 * Read data from the datastore.
153 * @param store the logical data store which should be modified
154 * @param path the data object path
155 * @return a ListenableFuture containing the result of the read
157 abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path);
160 * Read data selected using fields from the datastore.
162 * @param store the logical data store which should be modified
163 * @param path the parent data object path
164 * @param fields paths to selected fields relative to parent path
165 * @return a ListenableFuture containing the result of the read
167 abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path,
168 List<YangInstanceIdentifier> fields);
171 * Check if data already exists in the configuration datastore.
173 * @param path the data object path
174 * @return a ListenableFuture containing the result of the check
176 // FIXME: this method should be hosted in RestconfTransaction
177 // FIXME: this method should only be needed in MdsalRestconfStrategy
178 abstract ListenableFuture<Boolean> exists(YangInstanceIdentifier path);
181 * Delete data from the configuration datastore. If the data does not exist, this operation will fail, as outlined
182 * in <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.7">RFC8040 section 4.7</a>
184 * @param path Path to delete
185 * @return A {@link RestconfFuture}
186 * @throws NullPointerException if {@code path} is {@code null}
188 public final @NonNull RestconfFuture<Empty> delete(final YangInstanceIdentifier path) {
189 final var ret = new SettableRestconfFuture<Empty>();
190 delete(ret, requireNonNull(path));
194 abstract void delete(@NonNull SettableRestconfFuture<Empty> future, @NonNull YangInstanceIdentifier path);
197 * Merge data into the configuration datastore, as outlined in
198 * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040 section 4.6.1</a>.
200 * @param path Path to merge
201 * @param data Data to merge
202 * @return A {@link RestconfFuture}
203 * @throws NullPointerException if any argument is {@code null}
205 public final @NonNull RestconfFuture<Empty> merge(final YangInstanceIdentifier path, final NormalizedNode data) {
206 final var ret = new SettableRestconfFuture<Empty>();
207 merge(ret, requireNonNull(path), requireNonNull(data));
211 private void merge(final @NonNull SettableRestconfFuture<Empty> future, final @NonNull YangInstanceIdentifier path,
212 final @NonNull NormalizedNode data) {
213 final var tx = prepareWriteExecution();
214 // FIXME: this method should be further specialized to eliminate this call -- it is only needed for MD-SAL
215 tx.ensureParentsByMerge(path);
216 tx.merge(path, data);
217 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
219 public void onSuccess(final CommitInfo result) {
220 future.set(Empty.value());
224 public void onFailure(final Throwable cause) {
225 future.setFailure(TransactionUtil.decodeException(cause, "MERGE", path));
227 }, MoreExecutors.directExecutor());
231 * Check mount point and prepare variables for put data to DS.
233 * @param path path of data
235 * @param insert {@link Insert}
236 * @return A {@link CreateOrReplaceResult}
238 public final @NonNull CreateOrReplaceResult putData(final YangInstanceIdentifier path, final NormalizedNode data,
239 final @Nullable Insert insert) {
240 final var exists = TransactionUtil.syncAccess(exists(path), path);
242 final ListenableFuture<? extends CommitInfo> commitFuture;
243 if (insert != null) {
244 final var parentPath = path.coerceParent();
245 checkListAndOrderedType(parentPath);
246 commitFuture = insertAndCommitPut(path, data, insert, parentPath);
248 commitFuture = replaceAndCommit(prepareWriteExecution(), path, data);
251 TransactionUtil.syncCommit(commitFuture, "PUT", path);
252 return exists ? CreateOrReplaceResult.REPLACED : CreateOrReplaceResult.CREATED;
255 private ListenableFuture<? extends CommitInfo> insertAndCommitPut(final YangInstanceIdentifier path,
256 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parentPath) {
257 final var tx = prepareWriteExecution();
259 return switch (insert.insert()) {
261 final var readData = tx.readList(parentPath);
262 if (readData == null || readData.isEmpty()) {
263 yield replaceAndCommit(tx, path, data);
265 tx.remove(parentPath);
266 tx.replace(path, data);
267 tx.replace(parentPath, readData);
270 case LAST -> replaceAndCommit(tx, path, data);
272 final var readData = tx.readList(parentPath);
273 if (readData == null || readData.isEmpty()) {
274 yield replaceAndCommit(tx, path, data);
276 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
280 final var readData = tx.readList(parentPath);
281 if (readData == null || readData.isEmpty()) {
282 yield replaceAndCommit(tx, path, data);
284 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
290 private void insertWithPointPut(final RestconfTransaction tx, final YangInstanceIdentifier path,
291 final NormalizedNode data, final @NonNull PathArgument pointArg, final NormalizedNodeContainer<?> readList,
292 final boolean before) {
293 tx.remove(path.getParent());
295 int lastItemPosition = 0;
296 for (var nodeChild : readList.body()) {
297 if (nodeChild.name().equals(pointArg)) {
306 int lastInsertedPosition = 0;
307 final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext, path.getParent());
308 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
309 for (var nodeChild : readList.body()) {
310 if (lastInsertedPosition == lastItemPosition) {
311 tx.replace(path, data);
313 final var childPath = path.coerceParent().node(nodeChild.name());
314 tx.replace(childPath, nodeChild);
315 lastInsertedPosition++;
319 private static ListenableFuture<? extends CommitInfo> replaceAndCommit(final RestconfTransaction tx,
320 final YangInstanceIdentifier path, final NormalizedNode data) {
321 tx.replace(path, data);
325 private DataSchemaNode checkListAndOrderedType(final YangInstanceIdentifier path) {
326 // FIXME: we have this available in InstanceIdentifierContext
327 final var dataSchemaNode = DataSchemaContextTree.from(modelContext).findChild(path).orElseThrow()
330 final String message;
331 if (dataSchemaNode instanceof ListSchemaNode listSchema) {
332 if (listSchema.isUserOrdered()) {
335 message = "Insert parameter can be used only with ordered-by user list.";
336 } else if (dataSchemaNode instanceof LeafListSchemaNode leafListSchema) {
337 if (leafListSchema.isUserOrdered()) {
338 return leafListSchema;
340 message = "Insert parameter can be used only with ordered-by user leaf-list.";
342 message = "Insert parameter can be used only with list or leaf-list";
344 throw new RestconfDocumentedException(message, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
348 * Check mount point and prepare variables for post data.
352 * @param insert {@link Insert}
354 public final void postData(final YangInstanceIdentifier path, final NormalizedNode data,
355 final @Nullable Insert insert) {
356 final ListenableFuture<? extends CommitInfo> future;
357 if (insert != null) {
358 final var parentPath = path.coerceParent();
359 checkListAndOrderedType(parentPath);
360 future = insertAndCommitPost(path, data, insert, parentPath);
362 future = createAndCommit(prepareWriteExecution(), path, data);
364 TransactionUtil.syncCommit(future, "POST", path);
367 private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
368 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parent) {
369 final var grandParent = parent.coerceParent();
370 final var tx = prepareWriteExecution();
372 return switch (insert.insert()) {
374 final var readData = tx.readList(grandParent);
375 if (readData == null || readData.isEmpty()) {
376 tx.replace(path, data);
378 checkItemDoesNotExists(exists(path), path);
379 tx.remove(grandParent);
380 tx.replace(path, data);
381 tx.replace(grandParent, readData);
385 case LAST -> createAndCommit(tx, path, data);
387 final var readData = tx.readList(grandParent);
388 if (readData == null || readData.isEmpty()) {
389 tx.replace(path, data);
391 checkItemDoesNotExists(exists(path), path);
392 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, true);
397 final var readData = tx.readList(grandParent);
398 if (readData == null || readData.isEmpty()) {
399 tx.replace(path, data);
401 checkItemDoesNotExists(exists(path), path);
402 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, false);
410 * Process edit operations of one {@link PatchContext}.
412 * @param patch Patch context to be processed
413 * @return {@link PatchStatusContext}
415 public final @NonNull PatchStatusContext patchData(final PatchContext patch) {
416 final var editCollection = new ArrayList<PatchStatusEntity>();
417 final var tx = prepareWriteExecution();
419 boolean noError = true;
420 for (var patchEntity : patch.entities()) {
422 final var targetNode = patchEntity.getTargetNode();
423 final var editId = patchEntity.getEditId();
425 switch (patchEntity.getOperation()) {
428 tx.create(targetNode, patchEntity.getNode());
429 editCollection.add(new PatchStatusEntity(editId, true, null));
430 } catch (RestconfDocumentedException e) {
431 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
437 tx.delete(targetNode);
438 editCollection.add(new PatchStatusEntity(editId, true, null));
439 } catch (RestconfDocumentedException e) {
440 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
446 tx.ensureParentsByMerge(targetNode);
447 tx.merge(targetNode, patchEntity.getNode());
448 editCollection.add(new PatchStatusEntity(editId, true, null));
449 } catch (RestconfDocumentedException e) {
450 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
456 tx.replace(targetNode, patchEntity.getNode());
457 editCollection.add(new PatchStatusEntity(editId, true, null));
458 } catch (RestconfDocumentedException e) {
459 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
465 tx.remove(targetNode);
466 editCollection.add(new PatchStatusEntity(editId, true, null));
467 } catch (RestconfDocumentedException e) {
468 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
473 editCollection.add(new PatchStatusEntity(editId, false, List.of(
474 new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
475 "Not supported Yang Patch operation"))));
484 // if no errors then submit transaction, otherwise cancel
485 final var patchId = patch.patchId();
488 TransactionUtil.syncCommit(tx.commit(), "PATCH", null);
489 } catch (RestconfDocumentedException e) {
490 // if errors occurred during transaction commit then patch failed and global errors are reported
491 return new PatchStatusContext(modelContext, patchId, List.copyOf(editCollection), false, e.getErrors());
494 return new PatchStatusContext(modelContext, patchId, List.copyOf(editCollection), true, null);
497 return new PatchStatusContext(modelContext, patchId, List.copyOf(editCollection), false, null);
501 private void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
502 final NormalizedNode data, final PathArgument pointArg, final NormalizedNodeContainer<?> readList,
503 final YangInstanceIdentifier grandParentPath, final boolean before) {
504 tx.remove(grandParentPath);
506 int lastItemPosition = 0;
507 for (var nodeChild : readList.body()) {
508 if (nodeChild.name().equals(pointArg)) {
517 int lastInsertedPosition = 0;
518 final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext, grandParentPath);
519 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
520 for (var nodeChild : readList.body()) {
521 if (lastInsertedPosition == lastItemPosition) {
522 tx.replace(path, data);
524 tx.replace(grandParentPath.node(nodeChild.name()), nodeChild);
525 lastInsertedPosition++;
529 private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
530 final YangInstanceIdentifier path, final NormalizedNode data) {
532 tx.create(path, data);
533 } catch (RestconfDocumentedException e) {
534 // close transaction if any and pass exception further
543 * Check if items do NOT already exists at specified {@code path}.
545 * @param existsFuture if checked data exists
546 * @param path Path to be checked
547 * @throws RestconfDocumentedException if data already exists.
549 static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
550 final YangInstanceIdentifier path) {
551 if (TransactionUtil.syncAccess(existsFuture, path)) {
552 LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
553 throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
559 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
560 * inside of object {@link RestconfStrategy} provided as a parameter.
562 * @param content type of data to read (config, state, all)
563 * @param path the path to read
564 * @param defaultsMode value of with-defaults parameter
565 * @return {@link NormalizedNode}
567 public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
568 final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
569 return switch (content) {
571 // PREPARE STATE DATA NODE
572 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
573 // PREPARE CONFIG DATA NODE
574 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
576 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
577 : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
580 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
581 yield defaultsMode == null ? read
582 : prepareDataByParamWithDef(read, path, defaultsMode.mode());
584 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
589 * Read specific type of data from data store via transaction with specified subtrees that should only be read.
590 * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
592 * @param content type of data to read (config, state, all)
593 * @param path the parent path to read
594 * @param withDefa value of with-defaults parameter
595 * @param fields paths to selected subtrees which should be read, relative to to the parent path
596 * @return {@link NormalizedNode}
598 public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
599 final @NonNull YangInstanceIdentifier path, final @Nullable WithDefaultsParam withDefa,
600 final @NonNull List<YangInstanceIdentifier> fields) {
601 return switch (content) {
603 // PREPARE STATE DATA NODE
604 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
605 // PREPARE CONFIG DATA NODE
606 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
608 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, withDefa == null ? configDataNode
609 : prepareDataByParamWithDef(configDataNode, path, withDefa.mode()));
612 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
613 yield withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa.mode());
615 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
619 private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
620 final YangInstanceIdentifier path) {
621 return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
625 * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
626 * specified subtrees that should only be read.
628 * @param store datastore type
629 * @param path parent path to selected fields
630 * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
631 * in {@link RestconfStrategy} if any
632 * @param fields paths to selected subtrees which should be read, relative to to the parent path
633 * @return {@link NormalizedNode}
635 private @Nullable NormalizedNode readDataViaTransaction(final @NonNull LogicalDatastoreType store,
636 final @NonNull YangInstanceIdentifier path, final @NonNull List<YangInstanceIdentifier> fields) {
637 return TransactionUtil.syncAccess(read(store, path, fields), path).orElse(null);
640 private NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
641 final WithDefaultsMode defaultsMode) {
642 final boolean trim = switch (defaultsMode) {
644 case Explicit -> false;
645 case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
646 "Unsupported with-defaults value " + defaultsMode.getName());
649 // FIXME: we have this readily available in InstanceIdentifierContext
650 final var ctxNode = DataSchemaContextTree.from(modelContext).findChild(path).orElseThrow();
651 if (readData instanceof ContainerNode container) {
652 final var builder = Builders.containerBuilder().withNodeIdentifier(container.name());
653 buildCont(builder, container.body(), ctxNode, trim);
654 return builder.build();
655 } else if (readData instanceof MapEntryNode mapEntry) {
656 if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
657 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
660 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(mapEntry.name());
661 buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
662 return builder.build();
664 throw new IllegalStateException("Unhandled data contract " + readData.contract());
668 private static void buildMapEntryBuilder(
669 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
670 final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
671 final boolean trim, final List<QName> keys) {
672 for (var child : children) {
673 final var childCtx = getChildContext(ctxNode, child);
675 if (child instanceof ContainerNode container) {
676 appendContainer(builder, container, childCtx, trim);
677 } else if (child instanceof MapNode map) {
678 appendMap(builder, map, childCtx, trim);
679 } else if (child instanceof LeafNode<?> leaf) {
680 appendLeaf(builder, leaf, childCtx, trim, keys);
682 // FIXME: we should never hit this, throw an ISE if this ever happens
683 LOG.debug("Ignoring unhandled child contract {}", child.contract());
688 private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
689 final DataSchemaContext ctxNode, final boolean trim) {
690 final var childBuilder = Builders.containerBuilder().withNodeIdentifier(container.name());
691 buildCont(childBuilder, container.body(), ctxNode, trim);
692 builder.withChild(childBuilder.build());
695 private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
696 final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
697 if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
698 throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
701 // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
702 final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
704 // This is a combined check for when we need to emit the leaf.
706 // We always have to emit key leaf values
707 keys.contains(leafSchema.getQName())
708 // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
710 // When data is retrieved with a <with-defaults> parameter equal to
711 // 'trim', data nodes MUST NOT be reported if they contain the schema
712 // default value. Non-configuration data nodes containing the schema
713 // default value MUST NOT be reported.
715 || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
716 // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
717 // grasp what we are doing here... emit only if it matches default ???!!!
718 // FIXME: The WithDefaultsParam.EXPLICIT says:
720 // Data nodes set to the YANG default by the client are reported.
722 // and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
724 // If the "with-defaults" parameter is set to "explicit", then the
725 // server MUST adhere to the default-reporting behavior defined in
726 // Section 3.3 of [RFC6243].
728 // and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
730 // When data is retrieved with a <with-defaults> parameter equal to
731 // 'explicit', a data node that was set by a client to its schema
732 // default value MUST be reported. A conceptual data node that would be
733 // set by the server to the schema default value MUST NOT be reported.
734 // Non-configuration data nodes containing the schema default value MUST
737 // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
738 // This seems to disregard the 'trim = true' case semantics (see above).
739 // Combining the above, though, these checks are missing the 'non-config' check, which would
740 // distinguish, but barring that this check is superfluous and results in the wrong semantics.
741 // Without that input, this really should be covered by the previous case.
742 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
743 builder.withChild(leaf);
747 private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
748 final DataSchemaContext childCtx, final boolean trim) {
749 if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
750 throw new IllegalStateException("Input " + map + " does not match " + childCtx);
753 final var childBuilder = switch (map.ordering()) {
754 case SYSTEM -> Builders.mapBuilder();
755 case USER -> Builders.orderedMapBuilder();
757 buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
758 listSchema.getKeyDefinition());
759 builder.withChild(childBuilder.build());
762 private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
763 final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
764 final List<@NonNull QName> keys) {
765 for (var entry : entries) {
766 final var childCtx = getChildContext(ctxNode, entry);
767 final var mapEntryBuilder = Builders.mapEntryBuilder().withNodeIdentifier(entry.name());
768 buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
769 builder.withChild(mapEntryBuilder.build());
773 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
774 final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
775 for (var child : children) {
776 final var childCtx = getChildContext(ctxNode, child);
777 if (child instanceof ContainerNode container) {
778 appendContainer(builder, container, childCtx, trim);
779 } else if (child instanceof MapNode map) {
780 appendMap(builder, map, childCtx, trim);
781 } else if (child instanceof LeafNode<?> leaf) {
782 appendLeaf(builder, leaf, childCtx, trim, List.of());
787 private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
788 final NormalizedNode child) {
789 final var childId = child.name();
790 final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
792 if (childCtx == null) {
793 throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
798 private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
799 final NormalizedNode configDataNode) {
801 if (stateDataNode == null && configDataNode == null) {
805 // return config data
806 if (stateDataNode == null) {
807 return configDataNode;
811 if (configDataNode == null) {
812 return stateDataNode;
815 // merge data from config and state
816 return mergeStateAndConfigData(stateDataNode, configDataNode);
820 * Merge state and config data into a single NormalizedNode.
822 * @param stateDataNode data node of state data
823 * @param configDataNode data node of config data
824 * @return {@link NormalizedNode}
826 private static @NonNull NormalizedNode mergeStateAndConfigData(
827 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
828 validateNodeMerge(stateDataNode, configDataNode);
829 // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
830 if (configDataNode instanceof RpcDefinition) {
831 return prepareRpcData(configDataNode, stateDataNode);
833 return prepareData(configDataNode, stateDataNode);
838 * Validates whether the two NormalizedNodes can be merged.
840 * @param stateDataNode data node of state data
841 * @param configDataNode data node of config data
843 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
844 final @NonNull NormalizedNode configDataNode) {
845 final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
846 final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
847 if (!moduleOfStateData.equals(moduleOfConfigData)) {
848 throw new RestconfDocumentedException("Unable to merge data from different modules.");
853 * Prepare and map data for rpc.
855 * @param configDataNode data node of config data
856 * @param stateDataNode data node of state data
857 * @return {@link NormalizedNode}
859 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
860 final @NonNull NormalizedNode stateDataNode) {
861 final var mapEntryBuilder = Builders.mapEntryBuilder()
862 .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
865 mapRpcDataNode(configDataNode, mapEntryBuilder);
867 mapRpcDataNode(stateDataNode, mapEntryBuilder);
869 return Builders.mapBuilder()
870 .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
871 .addChild(mapEntryBuilder.build())
876 * Map node to map entry builder.
878 * @param dataNode data node
879 * @param mapEntryBuilder builder for mapping data
881 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
882 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
883 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
887 * Prepare and map all data from DS.
889 * @param configDataNode data node of config data
890 * @param stateDataNode data node of state data
891 * @return {@link NormalizedNode}
893 @SuppressWarnings("unchecked")
894 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
895 final @NonNull NormalizedNode stateDataNode) {
896 if (configDataNode instanceof UserMapNode configMap) {
897 final var builder = Builders.orderedMapBuilder().withNodeIdentifier(configMap.name());
898 mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
899 return builder.build();
900 } else if (configDataNode instanceof SystemMapNode configMap) {
901 final var builder = Builders.mapBuilder().withNodeIdentifier(configMap.name());
902 mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
903 return builder.build();
904 } else if (configDataNode instanceof MapEntryNode configEntry) {
905 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(configEntry.name());
906 mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
907 return builder.build();
908 } else if (configDataNode instanceof ContainerNode configContaienr) {
909 final var builder = Builders.containerBuilder().withNodeIdentifier(configContaienr.name());
910 mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
911 return builder.build();
912 } else if (configDataNode instanceof ChoiceNode configChoice) {
913 final var builder = Builders.choiceBuilder().withNodeIdentifier(configChoice.name());
914 mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
915 return builder.build();
916 } else if (configDataNode instanceof LeafNode configLeaf) {
917 // config trumps oper
919 } else if (configDataNode instanceof UserLeafSetNode) {
920 final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
921 final var builder = Builders.<Object>orderedLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
922 mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
923 return builder.build();
924 } else if (configDataNode instanceof SystemLeafSetNode) {
925 final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
926 final var builder = Builders.<Object>leafSetBuilder().withNodeIdentifier(configLeafSet.name());
927 mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
928 return builder.build();
929 } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
930 // config trumps oper
932 } else if (configDataNode instanceof UnkeyedListNode configList) {
933 final var builder = Builders.unkeyedListBuilder().withNodeIdentifier(configList.name());
934 mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
935 return builder.build();
936 } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
937 final var builder = Builders.unkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
938 mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
939 return builder.build();
941 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
946 * Map value from container node to builder.
948 * @param configData collection of config data nodes
949 * @param stateData collection of state data nodes
950 * @param builder builder
952 private static <T extends NormalizedNode> void mapValueToBuilder(
953 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
954 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
955 final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
956 final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
958 // merge config and state data of children with different identifiers
959 mapDataToBuilder(configMap, stateMap, builder);
961 // merge config and state data of children with the same identifiers
962 mergeDataToBuilder(configMap, stateMap, builder);
966 * Map data with different identifiers to builder. Data with different identifiers can be just added
967 * as childs to parent node.
969 * @param configMap map of config data nodes
970 * @param stateMap map of state data nodes
971 * @param builder - builder
973 private static <T extends NormalizedNode> void mapDataToBuilder(
974 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
975 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
976 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
977 y -> builder.addChild(y.getValue()));
978 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
979 y -> builder.addChild(y.getValue()));
983 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
984 * go one level down with {@code prepareData} method.
986 * @param configMap immutable config data
987 * @param stateMap immutable state data
988 * @param builder - builder
990 @SuppressWarnings("unchecked")
991 private static <T extends NormalizedNode> void mergeDataToBuilder(
992 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
993 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
994 // it is enough to process only config data because operational contains the same data
995 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
996 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));