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.PointParam;
35 import org.opendaylight.restconf.api.query.WithDefaultsParam;
36 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
37 import org.opendaylight.restconf.common.errors.RestconfError;
38 import org.opendaylight.restconf.common.errors.RestconfFuture;
39 import org.opendaylight.restconf.common.errors.SettableRestconfFuture;
40 import org.opendaylight.restconf.common.patch.PatchContext;
41 import org.opendaylight.restconf.common.patch.PatchStatusContext;
42 import org.opendaylight.restconf.common.patch.PatchStatusEntity;
43 import org.opendaylight.restconf.nb.rfc8040.Insert;
44 import org.opendaylight.restconf.nb.rfc8040.utils.parser.YangInstanceIdentifierDeserializer;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.with.defaults.rev110601.WithDefaultsMode;
46 import org.opendaylight.yangtools.yang.common.Empty;
47 import org.opendaylight.yangtools.yang.common.ErrorTag;
48 import org.opendaylight.yangtools.yang.common.ErrorType;
49 import org.opendaylight.yangtools.yang.common.QName;
50 import org.opendaylight.yangtools.yang.common.QNameModule;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
55 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
58 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
64 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
71 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
72 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
73 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
74 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
75 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
76 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
77 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
79 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
80 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
87 * Baseline execution strategy for various RESTCONF operations.
89 * @see NetconfRestconfStrategy
90 * @see MdsalRestconfStrategy
92 // FIXME: it seems the first three operations deal with lifecycle of a transaction, while others invoke various
93 // operations. This should be handled through proper allocation indirection.
94 public abstract class RestconfStrategy {
96 * Result of a {@code PUT} request as defined in
97 * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.5">RFC8040 section 4.5</a>. The definition makes it
98 * clear that the logical operation is {@code create-or-replace}.
100 public enum CreateOrReplaceResult {
102 * A new resource has been created.
106 * An existing resources has been replaced.
111 private static final Logger LOG = LoggerFactory.getLogger(RestconfStrategy.class);
118 * Look up the appropriate strategy for a particular mount point.
120 * @param mountPoint Target mount point
121 * @return A strategy, or null if the mount point does not expose a supported interface
122 * @throws NullPointerException if {@code mountPoint} is null
124 public static Optional<RestconfStrategy> forMountPoint(final DOMMountPoint mountPoint) {
125 final Optional<RestconfStrategy> netconf = mountPoint.getService(NetconfDataTreeService.class)
126 .map(NetconfRestconfStrategy::new);
127 if (netconf.isPresent()) {
131 return mountPoint.getService(DOMDataBroker.class).map(MdsalRestconfStrategy::new);
135 * Lock the entire datastore.
137 * @return A {@link RestconfTransaction}. This transaction needs to be either committed or canceled before doing
140 public abstract RestconfTransaction prepareWriteExecution();
143 * Read data from the datastore.
145 * @param store the logical data store which should be modified
146 * @param path the data object path
147 * @return a ListenableFuture containing the result of the read
149 public abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store,
150 YangInstanceIdentifier path);
153 * Read data selected using fields from the datastore.
155 * @param store the logical data store which should be modified
156 * @param path the parent data object path
157 * @param fields paths to selected fields relative to parent path
158 * @return a ListenableFuture containing the result of the read
160 public abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store,
161 YangInstanceIdentifier path, List<YangInstanceIdentifier> fields);
164 * Check if data already exists in the configuration datastore.
166 * @param path the data object path
167 * @return a ListenableFuture containing the result of the check
169 // FIXME: this method should be hosted in RestconfTransaction
170 // FIXME: this method should only be needed in MdsalRestconfStrategy
171 abstract ListenableFuture<Boolean> exists(YangInstanceIdentifier path);
174 * Delete data from the configuration datastore. If the data does not exist, this operation will fail, as outlined
175 * in <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.7">RFC8040 section 4.7</a>
177 * @param path Path to delete
178 * @return A {@link RestconfFuture}
179 * @throws NullPointerException if {@code path} is {@code null}
181 public final @NonNull RestconfFuture<Empty> delete(final YangInstanceIdentifier path) {
182 final var ret = new SettableRestconfFuture<Empty>();
183 delete(ret, requireNonNull(path));
187 protected abstract void delete(@NonNull SettableRestconfFuture<Empty> future, @NonNull YangInstanceIdentifier path);
190 * Merge data into the configuration datastore, as outlined in
191 * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040 section 4.6.1</a>.
193 * @param path Path to merge
194 * @param data Data to merge
195 * @param context Corresponding EffectiveModelContext
196 * @return A {@link RestconfFuture}
197 * @throws NullPointerException if any argument is {@code null}
199 public final @NonNull RestconfFuture<Empty> merge(final YangInstanceIdentifier path, final NormalizedNode data,
200 final EffectiveModelContext context) {
201 final var ret = new SettableRestconfFuture<Empty>();
202 merge(ret, requireNonNull(path), requireNonNull(data), requireNonNull(context));
206 private void merge(final @NonNull SettableRestconfFuture<Empty> future,
207 final @NonNull YangInstanceIdentifier path, final @NonNull NormalizedNode data,
208 final @NonNull EffectiveModelContext context) {
209 final var tx = prepareWriteExecution();
210 // FIXME: this method should be further specialized to eliminate this call -- it is only needed for MD-SAL
211 tx.ensureParentsByMerge(path, context);
212 tx.merge(path, data);
213 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
215 public void onSuccess(final CommitInfo result) {
216 future.set(Empty.value());
220 public void onFailure(final Throwable cause) {
221 future.setFailure(TransactionUtil.decodeException(cause, "MERGE", path));
223 }, MoreExecutors.directExecutor());
227 * Check mount point and prepare variables for put data to DS.
229 * @param path path of data
231 * @param context reference to {@link EffectiveModelContext}
232 * @param insert {@link Insert}
233 * @return A {@link CreateOrReplaceResult}
235 public @NonNull CreateOrReplaceResult putData(final YangInstanceIdentifier path, final NormalizedNode data,
236 final EffectiveModelContext context, final @Nullable Insert insert) {
237 final var exists = TransactionUtil.syncAccess(exists(path), path);
239 final ListenableFuture<? extends CommitInfo> commitFuture;
240 if (insert != null) {
241 final var parentPath = path.coerceParent();
242 checkListAndOrderedType(context, parentPath);
243 commitFuture = insertAndCommitPut(path, data, insert, parentPath, context);
245 commitFuture = replaceAndCommit(prepareWriteExecution(), path, data, context);
248 TransactionUtil.syncCommit(commitFuture, "PUT", path);
249 return exists ? CreateOrReplaceResult.REPLACED : CreateOrReplaceResult.CREATED;
252 private ListenableFuture<? extends CommitInfo> insertAndCommitPut(final YangInstanceIdentifier path,
253 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parentPath,
254 final EffectiveModelContext context) {
255 final var tx = prepareWriteExecution();
257 return switch (insert.insert()) {
259 final var readData = tx.readList(parentPath);
260 if (readData == null || readData.isEmpty()) {
261 yield replaceAndCommit(tx, path, data, context);
263 tx.remove(parentPath);
264 tx.replace(path, data, context);
265 tx.replace(parentPath, readData, context);
268 case LAST -> replaceAndCommit(tx, path, data, context);
270 final var readData = tx.readList(parentPath);
271 if (readData == null || readData.isEmpty()) {
272 yield replaceAndCommit(tx, path, data, context);
274 insertWithPointPut(tx, path, data, verifyNotNull(insert.point()), readData, true, context);
278 final var readData = tx.readList(parentPath);
279 if (readData == null || readData.isEmpty()) {
280 yield replaceAndCommit(tx, path, data, context);
282 insertWithPointPut(tx, path, data, verifyNotNull(insert.point()), readData, false, context);
288 private static void insertWithPointPut(final RestconfTransaction tx, final YangInstanceIdentifier path,
289 final NormalizedNode data, final @NonNull PointParam point, final NormalizedNodeContainer<?> readList,
290 final boolean before, final EffectiveModelContext context) {
291 tx.remove(path.getParent());
292 final var pointArg = YangInstanceIdentifierDeserializer.create(context, point.value()).path
293 .getLastPathArgument();
294 int lastItemPosition = 0;
295 for (var nodeChild : readList.body()) {
296 if (nodeChild.name().equals(pointArg)) {
304 int lastInsertedPosition = 0;
305 final var emptySubtree = ImmutableNodes.fromInstanceId(context, path.getParent());
306 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
307 for (var nodeChild : readList.body()) {
308 if (lastInsertedPosition == lastItemPosition) {
309 tx.replace(path, data, context);
311 final var childPath = path.coerceParent().node(nodeChild.name());
312 tx.replace(childPath, nodeChild, context);
313 lastInsertedPosition++;
317 private static ListenableFuture<? extends CommitInfo> replaceAndCommit(final RestconfTransaction tx,
318 final YangInstanceIdentifier path, final NormalizedNode data, final EffectiveModelContext context) {
319 tx.replace(path, data, context);
323 private static DataSchemaNode checkListAndOrderedType(final EffectiveModelContext ctx,
324 final YangInstanceIdentifier path) {
325 final var dataSchemaNode = DataSchemaContextTree.from(ctx).findChild(path).orElseThrow().dataSchemaNode();
327 final String message;
328 if (dataSchemaNode instanceof ListSchemaNode listSchema) {
329 if (listSchema.isUserOrdered()) {
332 message = "Insert parameter can be used only with ordered-by user list.";
333 } else if (dataSchemaNode instanceof LeafListSchemaNode leafListSchema) {
334 if (leafListSchema.isUserOrdered()) {
335 return leafListSchema;
337 message = "Insert parameter can be used only with ordered-by user leaf-list.";
339 message = "Insert parameter can be used only with list or leaf-list";
341 throw new RestconfDocumentedException(message, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
345 * Check mount point and prepare variables for post data.
349 * @param context reference to actual {@link EffectiveModelContext}
350 * @param insert {@link Insert}
352 public final void postData(final YangInstanceIdentifier path, final NormalizedNode data,
353 final EffectiveModelContext context, final @Nullable Insert insert) {
354 final ListenableFuture<? extends CommitInfo> future;
355 if (insert != null) {
356 final var parentPath = path.coerceParent();
357 checkListAndOrderedType(context, parentPath);
358 future = insertAndCommitPost(path, data, insert, parentPath, context);
360 future = createAndCommit(prepareWriteExecution(), path, data, context);
362 TransactionUtil.syncCommit(future, "POST", path);
365 private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
366 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parent,
367 final EffectiveModelContext context) {
368 final var grandParent = parent.coerceParent();
369 final var tx = prepareWriteExecution();
371 return switch (insert.insert()) {
373 final var readData = tx.readList(grandParent);
374 if (readData == null || readData.isEmpty()) {
375 tx.replace(path, data, context);
377 checkItemDoesNotExists(exists(path), path);
378 tx.remove(grandParent);
379 tx.replace(path, data, context);
380 tx.replace(grandParent, readData, context);
384 case LAST -> createAndCommit(tx, path, data, context);
386 final var readData = tx.readList(grandParent);
387 if (readData == null || readData.isEmpty()) {
388 tx.replace(path, data, context);
390 checkItemDoesNotExists(exists(path), path);
391 insertWithPointPost(tx, path, data, verifyNotNull(insert.point()), readData, grandParent, true,
397 final var readData = tx.readList(grandParent);
398 if (readData == null || readData.isEmpty()) {
399 tx.replace(path, data, context);
401 checkItemDoesNotExists(exists(path), path);
402 insertWithPointPost(tx, path, data, verifyNotNull(insert.point()), readData, grandParent, false,
411 * Process edit operations of one {@link PatchContext}.
413 * @param patch Patch context to be processed
414 * @param context Global schema context
415 * @return {@link PatchStatusContext}
417 public final @NonNull PatchStatusContext patchData(final PatchContext patch, final EffectiveModelContext context) {
418 final var editCollection = new ArrayList<PatchStatusEntity>();
419 final var tx = prepareWriteExecution();
421 boolean noError = true;
422 for (var patchEntity : patch.getData()) {
424 final var targetNode = patchEntity.getTargetNode();
425 final var editId = patchEntity.getEditId();
427 switch (patchEntity.getOperation()) {
430 tx.create(targetNode, patchEntity.getNode(), context);
431 editCollection.add(new PatchStatusEntity(editId, true, null));
432 } catch (RestconfDocumentedException e) {
433 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
439 tx.delete(targetNode);
440 editCollection.add(new PatchStatusEntity(editId, true, null));
441 } catch (RestconfDocumentedException e) {
442 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
448 tx.ensureParentsByMerge(targetNode, context);
449 tx.merge(targetNode, patchEntity.getNode());
450 editCollection.add(new PatchStatusEntity(editId, true, null));
451 } catch (RestconfDocumentedException e) {
452 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
458 tx.replace(targetNode, patchEntity.getNode(), context);
459 editCollection.add(new PatchStatusEntity(editId, true, null));
460 } catch (RestconfDocumentedException e) {
461 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
467 tx.remove(targetNode);
468 editCollection.add(new PatchStatusEntity(editId, true, null));
469 } catch (RestconfDocumentedException e) {
470 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
475 editCollection.add(new PatchStatusEntity(editId, false, List.of(
476 new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
477 "Not supported Yang Patch operation"))));
486 // if no errors then submit transaction, otherwise cancel
489 TransactionUtil.syncCommit(tx.commit(), "PATCH", null);
490 } catch (RestconfDocumentedException e) {
491 // if errors occurred during transaction commit then patch failed and global errors are reported
492 return new PatchStatusContext(patch.getPatchId(), List.copyOf(editCollection), false, e.getErrors());
495 return new PatchStatusContext(patch.getPatchId(), List.copyOf(editCollection), true, null);
498 return new PatchStatusContext(patch.getPatchId(), List.copyOf(editCollection), false, null);
502 private static void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
503 final NormalizedNode data, final PointParam point, final NormalizedNodeContainer<?> readList,
504 final YangInstanceIdentifier grandParentPath, final boolean before, final EffectiveModelContext context) {
505 tx.remove(grandParentPath);
506 final var pointArg = YangInstanceIdentifierDeserializer.create(context, point.value()).path
507 .getLastPathArgument();
508 int lastItemPosition = 0;
509 for (var nodeChild : readList.body()) {
510 if (nodeChild.name().equals(pointArg)) {
518 int lastInsertedPosition = 0;
519 final var emptySubtree = ImmutableNodes.fromInstanceId(context, grandParentPath);
520 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
521 for (var nodeChild : readList.body()) {
522 if (lastInsertedPosition == lastItemPosition) {
523 tx.replace(path, data, context);
525 final YangInstanceIdentifier childPath = grandParentPath.node(nodeChild.name());
526 tx.replace(childPath, nodeChild, context);
527 lastInsertedPosition++;
531 private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
532 final YangInstanceIdentifier path, final NormalizedNode data, final EffectiveModelContext context) {
534 tx.create(path, data, context);
535 } catch (RestconfDocumentedException e) {
536 // close transaction if any and pass exception further
545 * Check if items do NOT already exists at specified {@code path}.
547 * @param existsFuture if checked data exists
548 * @param path Path to be checked
549 * @throws RestconfDocumentedException if data already exists.
551 static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
552 final YangInstanceIdentifier path) {
553 if (TransactionUtil.syncAccess(existsFuture, path)) {
554 LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
555 throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
561 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
562 * inside of object {@link RestconfStrategy} provided as a parameter.
564 * @param content type of data to read (config, state, all)
565 * @param path the path to read
566 * @param defaultsMode value of with-defaults parameter
567 * @param ctx schema context
568 * @return {@link NormalizedNode}
570 public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
571 final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode,
572 final EffectiveModelContext ctx) {
573 return switch (content) {
575 // PREPARE STATE DATA NODE
576 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
577 // PREPARE CONFIG DATA NODE
578 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
580 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
581 : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode(), ctx));
584 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
585 yield defaultsMode == null ? read : prepareDataByParamWithDef(read, path, defaultsMode.mode(), ctx);
587 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
592 * Read specific type of data from data store via transaction with specified subtrees that should only be read.
593 * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
595 * @param content type of data to read (config, state, all)
596 * @param path the parent path to read
597 * @param withDefa value of with-defaults parameter
598 * @param ctx schema context
599 * @param fields paths to selected subtrees which should be read, relative to to the parent path
600 * @return {@link NormalizedNode}
602 public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
603 final @NonNull YangInstanceIdentifier path, final @Nullable WithDefaultsParam withDefa,
604 final @NonNull EffectiveModelContext ctx, final @NonNull List<YangInstanceIdentifier> fields) {
605 return switch (content) {
607 // PREPARE STATE DATA NODE
608 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
609 // PREPARE CONFIG DATA NODE
610 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
612 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, withDefa == null ? configDataNode
613 : prepareDataByParamWithDef(configDataNode, path, withDefa.mode(), ctx));
616 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
617 yield withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa.mode(), ctx);
619 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
623 private static NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData,
624 final YangInstanceIdentifier path, final WithDefaultsMode defaultsMode, final EffectiveModelContext ctx) {
625 final boolean trim = switch (defaultsMode) {
627 case Explicit -> false;
628 case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
629 "Unsupported with-defaults value " + defaultsMode.getName());
632 final var ctxNode = DataSchemaContextTree.from(ctx).findChild(path).orElseThrow();
633 if (readData instanceof ContainerNode container) {
634 final var builder = Builders.containerBuilder().withNodeIdentifier(container.name());
635 buildCont(builder, container.body(), ctxNode, trim);
636 return builder.build();
637 } else if (readData instanceof MapEntryNode mapEntry) {
638 if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
639 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
642 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(mapEntry.name());
643 buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
644 return builder.build();
646 throw new IllegalStateException("Unhandled data contract " + readData.contract());
650 private static void buildMapEntryBuilder(
651 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
652 final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
653 final boolean trim, final List<QName> keys) {
654 for (var child : children) {
655 final var childCtx = getChildContext(ctxNode, child);
657 if (child instanceof ContainerNode container) {
658 appendContainer(builder, container, childCtx, trim);
659 } else if (child instanceof MapNode map) {
660 appendMap(builder, map, childCtx, trim);
661 } else if (child instanceof LeafNode<?> leaf) {
662 appendLeaf(builder, leaf, childCtx, trim, keys);
664 // FIXME: we should never hit this, throw an ISE if this ever happens
665 LOG.debug("Ignoring unhandled child contract {}", child.contract());
670 private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
671 final DataSchemaContext ctxNode, final boolean trim) {
672 final var childBuilder = Builders.containerBuilder().withNodeIdentifier(container.name());
673 buildCont(childBuilder, container.body(), ctxNode, trim);
674 builder.withChild(childBuilder.build());
677 private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
678 final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
679 if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
680 throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
683 // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
684 final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
686 // This is a combined check for when we need to emit the leaf.
688 // We always have to emit key leaf values
689 keys.contains(leafSchema.getQName())
690 // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
692 // When data is retrieved with a <with-defaults> parameter equal to
693 // 'trim', data nodes MUST NOT be reported if they contain the schema
694 // default value. Non-configuration data nodes containing the schema
695 // default value MUST NOT be reported.
697 || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
698 // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
699 // grasp what we are doing here... emit only if it matches default ???!!!
700 // FIXME: The WithDefaultsParam.EXPLICIT says:
702 // Data nodes set to the YANG default by the client are reported.
704 // and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
706 // If the "with-defaults" parameter is set to "explicit", then the
707 // server MUST adhere to the default-reporting behavior defined in
708 // Section 3.3 of [RFC6243].
710 // and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
712 // When data is retrieved with a <with-defaults> parameter equal to
713 // 'explicit', a data node that was set by a client to its schema
714 // default value MUST be reported. A conceptual data node that would be
715 // set by the server to the schema default value MUST NOT be reported.
716 // Non-configuration data nodes containing the schema default value MUST
719 // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
720 // This seems to disregard the 'trim = true' case semantics (see above).
721 // Combining the above, though, these checks are missing the 'non-config' check, which would
722 // distinguish, but barring that this check is superfluous and results in the wrong semantics.
723 // Without that input, this really should be covered by the previous case.
724 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
725 builder.withChild(leaf);
729 private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
730 final DataSchemaContext childCtx, final boolean trim) {
731 if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
732 throw new IllegalStateException("Input " + map + " does not match " + childCtx);
735 final var childBuilder = switch (map.ordering()) {
736 case SYSTEM -> Builders.mapBuilder();
737 case USER -> Builders.orderedMapBuilder();
739 buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
740 listSchema.getKeyDefinition());
741 builder.withChild(childBuilder.build());
744 private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
745 final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
746 final List<@NonNull QName> keys) {
747 for (var entry : entries) {
748 final var childCtx = getChildContext(ctxNode, entry);
749 final var mapEntryBuilder = Builders.mapEntryBuilder().withNodeIdentifier(entry.name());
750 buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
751 builder.withChild(mapEntryBuilder.build());
755 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
756 final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
757 for (var child : children) {
758 final var childCtx = getChildContext(ctxNode, child);
759 if (child instanceof ContainerNode container) {
760 appendContainer(builder, container, childCtx, trim);
761 } else if (child instanceof MapNode map) {
762 appendMap(builder, map, childCtx, trim);
763 } else if (child instanceof LeafNode<?> leaf) {
764 appendLeaf(builder, leaf, childCtx, trim, List.of());
769 private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
770 final NormalizedNode child) {
771 final var childId = child.name();
772 final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
774 if (childCtx == null) {
775 throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
780 private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
781 final YangInstanceIdentifier path) {
782 return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
786 * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
787 * specified subtrees that should only be read.
789 * @param store datastore type
790 * @param path parent path to selected fields
791 * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
792 * in {@link RestconfStrategy} if any
793 * @param fields paths to selected subtrees which should be read, relative to to the parent path
794 * @return {@link NormalizedNode}
796 private @Nullable NormalizedNode readDataViaTransaction(final @NonNull LogicalDatastoreType store,
797 final @NonNull YangInstanceIdentifier path, final @NonNull List<YangInstanceIdentifier> fields) {
798 return TransactionUtil.syncAccess(read(store, path, fields), path).orElse(null);
801 private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
802 final NormalizedNode configDataNode) {
804 if (stateDataNode == null && configDataNode == null) {
808 // return config data
809 if (stateDataNode == null) {
810 return configDataNode;
814 if (configDataNode == null) {
815 return stateDataNode;
818 // merge data from config and state
819 return mergeStateAndConfigData(stateDataNode, configDataNode);
823 * Merge state and config data into a single NormalizedNode.
825 * @param stateDataNode data node of state data
826 * @param configDataNode data node of config data
827 * @return {@link NormalizedNode}
829 private static @NonNull NormalizedNode mergeStateAndConfigData(
830 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
831 validateNodeMerge(stateDataNode, configDataNode);
832 // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
833 if (configDataNode instanceof RpcDefinition) {
834 return prepareRpcData(configDataNode, stateDataNode);
836 return prepareData(configDataNode, stateDataNode);
841 * Validates whether the two NormalizedNodes can be merged.
843 * @param stateDataNode data node of state data
844 * @param configDataNode data node of config data
846 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
847 final @NonNull NormalizedNode configDataNode) {
848 final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
849 final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
850 if (!moduleOfStateData.equals(moduleOfConfigData)) {
851 throw new RestconfDocumentedException("Unable to merge data from different modules.");
856 * Prepare and map data for rpc.
858 * @param configDataNode data node of config data
859 * @param stateDataNode data node of state data
860 * @return {@link NormalizedNode}
862 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
863 final @NonNull NormalizedNode stateDataNode) {
864 final var mapEntryBuilder = Builders.mapEntryBuilder()
865 .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
868 mapRpcDataNode(configDataNode, mapEntryBuilder);
870 mapRpcDataNode(stateDataNode, mapEntryBuilder);
872 return Builders.mapBuilder()
873 .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
874 .addChild(mapEntryBuilder.build())
879 * Map node to map entry builder.
881 * @param dataNode data node
882 * @param mapEntryBuilder builder for mapping data
884 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
885 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
886 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
890 * Prepare and map all data from DS.
892 * @param configDataNode data node of config data
893 * @param stateDataNode data node of state data
894 * @return {@link NormalizedNode}
896 @SuppressWarnings("unchecked")
897 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
898 final @NonNull NormalizedNode stateDataNode) {
899 if (configDataNode instanceof UserMapNode configMap) {
900 final var builder = Builders.orderedMapBuilder().withNodeIdentifier(configMap.name());
901 mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
902 return builder.build();
903 } else if (configDataNode instanceof SystemMapNode configMap) {
904 final var builder = Builders.mapBuilder().withNodeIdentifier(configMap.name());
905 mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
906 return builder.build();
907 } else if (configDataNode instanceof MapEntryNode configEntry) {
908 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(configEntry.name());
909 mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
910 return builder.build();
911 } else if (configDataNode instanceof ContainerNode configContaienr) {
912 final var builder = Builders.containerBuilder().withNodeIdentifier(configContaienr.name());
913 mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
914 return builder.build();
915 } else if (configDataNode instanceof ChoiceNode configChoice) {
916 final var builder = Builders.choiceBuilder().withNodeIdentifier(configChoice.name());
917 mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
918 return builder.build();
919 } else if (configDataNode instanceof LeafNode configLeaf) {
920 // config trumps oper
922 } else if (configDataNode instanceof UserLeafSetNode) {
923 final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
924 final var builder = Builders.<Object>orderedLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
925 mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
926 return builder.build();
927 } else if (configDataNode instanceof SystemLeafSetNode) {
928 final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
929 final var builder = Builders.<Object>leafSetBuilder().withNodeIdentifier(configLeafSet.name());
930 mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
931 return builder.build();
932 } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
933 // config trumps oper
935 } else if (configDataNode instanceof UnkeyedListNode configList) {
936 final var builder = Builders.unkeyedListBuilder().withNodeIdentifier(configList.name());
937 mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
938 return builder.build();
939 } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
940 final var builder = Builders.unkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
941 mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
942 return builder.build();
944 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
949 * Map value from container node to builder.
951 * @param configData collection of config data nodes
952 * @param stateData collection of state data nodes
953 * @param builder builder
955 private static <T extends NormalizedNode> void mapValueToBuilder(
956 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
957 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
958 final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
959 final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
961 // merge config and state data of children with different identifiers
962 mapDataToBuilder(configMap, stateMap, builder);
964 // merge config and state data of children with the same identifiers
965 mergeDataToBuilder(configMap, stateMap, builder);
969 * Map data with different identifiers to builder. Data with different identifiers can be just added
970 * as childs to parent node.
972 * @param configMap map of config data nodes
973 * @param stateMap map of state data nodes
974 * @param builder - builder
976 private static <T extends NormalizedNode> void mapDataToBuilder(
977 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
978 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
979 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
980 y -> builder.addChild(y.getValue()));
981 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
982 y -> builder.addChild(y.getValue()));
986 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
987 * go one level down with {@code prepareData} method.
989 * @param configMap immutable config data
990 * @param stateMap immutable state data
991 * @param builder - builder
993 @SuppressWarnings("unchecked")
994 private static <T extends NormalizedNode> void mergeDataToBuilder(
995 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
996 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
997 // it is enough to process only config data because operational contains the same data
998 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
999 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));