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 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 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 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 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.entities()) {
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
487 final var patchId = patch.patchId();
490 TransactionUtil.syncCommit(tx.commit(), "PATCH", null);
491 } catch (RestconfDocumentedException e) {
492 // if errors occurred during transaction commit then patch failed and global errors are reported
493 return new PatchStatusContext(context, patchId, List.copyOf(editCollection), false, e.getErrors());
496 return new PatchStatusContext(context, patchId, List.copyOf(editCollection), true, null);
499 return new PatchStatusContext(context, patchId, List.copyOf(editCollection), false, null);
503 private static void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
504 final NormalizedNode data, final PointParam point, final NormalizedNodeContainer<?> readList,
505 final YangInstanceIdentifier grandParentPath, final boolean before, final EffectiveModelContext context) {
506 tx.remove(grandParentPath);
507 final var pointArg = YangInstanceIdentifierDeserializer.create(context, point.value()).path
508 .getLastPathArgument();
509 int lastItemPosition = 0;
510 for (var nodeChild : readList.body()) {
511 if (nodeChild.name().equals(pointArg)) {
519 int lastInsertedPosition = 0;
520 final var emptySubtree = ImmutableNodes.fromInstanceId(context, grandParentPath);
521 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
522 for (var nodeChild : readList.body()) {
523 if (lastInsertedPosition == lastItemPosition) {
524 tx.replace(path, data, context);
526 final YangInstanceIdentifier childPath = grandParentPath.node(nodeChild.name());
527 tx.replace(childPath, nodeChild, context);
528 lastInsertedPosition++;
532 private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
533 final YangInstanceIdentifier path, final NormalizedNode data, final EffectiveModelContext context) {
535 tx.create(path, data, context);
536 } catch (RestconfDocumentedException e) {
537 // close transaction if any and pass exception further
546 * Check if items do NOT already exists at specified {@code path}.
548 * @param existsFuture if checked data exists
549 * @param path Path to be checked
550 * @throws RestconfDocumentedException if data already exists.
552 static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
553 final YangInstanceIdentifier path) {
554 if (TransactionUtil.syncAccess(existsFuture, path)) {
555 LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
556 throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
562 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
563 * inside of object {@link RestconfStrategy} provided as a parameter.
565 * @param content type of data to read (config, state, all)
566 * @param path the path to read
567 * @param defaultsMode value of with-defaults parameter
568 * @param ctx schema context
569 * @return {@link NormalizedNode}
571 public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
572 final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode,
573 final EffectiveModelContext ctx) {
574 return switch (content) {
576 // PREPARE STATE DATA NODE
577 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
578 // PREPARE CONFIG DATA NODE
579 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
581 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
582 : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode(), ctx));
585 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
586 yield defaultsMode == null ? read : prepareDataByParamWithDef(read, path, defaultsMode.mode(), ctx);
588 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
593 * Read specific type of data from data store via transaction with specified subtrees that should only be read.
594 * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
596 * @param content type of data to read (config, state, all)
597 * @param path the parent path to read
598 * @param withDefa value of with-defaults parameter
599 * @param ctx schema context
600 * @param fields paths to selected subtrees which should be read, relative to to the parent path
601 * @return {@link NormalizedNode}
603 public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
604 final @NonNull YangInstanceIdentifier path, final @Nullable WithDefaultsParam withDefa,
605 final @NonNull EffectiveModelContext ctx, final @NonNull List<YangInstanceIdentifier> fields) {
606 return switch (content) {
608 // PREPARE STATE DATA NODE
609 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
610 // PREPARE CONFIG DATA NODE
611 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
613 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, withDefa == null ? configDataNode
614 : prepareDataByParamWithDef(configDataNode, path, withDefa.mode(), ctx));
617 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
618 yield withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa.mode(), ctx);
620 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
624 private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
625 final YangInstanceIdentifier path) {
626 return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
630 * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
631 * specified subtrees that should only be read.
633 * @param store datastore type
634 * @param path parent path to selected fields
635 * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
636 * in {@link RestconfStrategy} if any
637 * @param fields paths to selected subtrees which should be read, relative to to the parent path
638 * @return {@link NormalizedNode}
640 private @Nullable NormalizedNode readDataViaTransaction(final @NonNull LogicalDatastoreType store,
641 final @NonNull YangInstanceIdentifier path, final @NonNull List<YangInstanceIdentifier> fields) {
642 return TransactionUtil.syncAccess(read(store, path, fields), path).orElse(null);
645 private static NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData,
646 final YangInstanceIdentifier path, final WithDefaultsMode defaultsMode, final EffectiveModelContext ctx) {
647 final boolean trim = switch (defaultsMode) {
649 case Explicit -> false;
650 case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
651 "Unsupported with-defaults value " + defaultsMode.getName());
654 final var ctxNode = DataSchemaContextTree.from(ctx).findChild(path).orElseThrow();
655 if (readData instanceof ContainerNode container) {
656 final var builder = Builders.containerBuilder().withNodeIdentifier(container.name());
657 buildCont(builder, container.body(), ctxNode, trim);
658 return builder.build();
659 } else if (readData instanceof MapEntryNode mapEntry) {
660 if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
661 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
664 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(mapEntry.name());
665 buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
666 return builder.build();
668 throw new IllegalStateException("Unhandled data contract " + readData.contract());
672 private static void buildMapEntryBuilder(
673 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
674 final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
675 final boolean trim, final List<QName> keys) {
676 for (var child : children) {
677 final var childCtx = getChildContext(ctxNode, child);
679 if (child instanceof ContainerNode container) {
680 appendContainer(builder, container, childCtx, trim);
681 } else if (child instanceof MapNode map) {
682 appendMap(builder, map, childCtx, trim);
683 } else if (child instanceof LeafNode<?> leaf) {
684 appendLeaf(builder, leaf, childCtx, trim, keys);
686 // FIXME: we should never hit this, throw an ISE if this ever happens
687 LOG.debug("Ignoring unhandled child contract {}", child.contract());
692 private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
693 final DataSchemaContext ctxNode, final boolean trim) {
694 final var childBuilder = Builders.containerBuilder().withNodeIdentifier(container.name());
695 buildCont(childBuilder, container.body(), ctxNode, trim);
696 builder.withChild(childBuilder.build());
699 private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
700 final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
701 if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
702 throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
705 // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
706 final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
708 // This is a combined check for when we need to emit the leaf.
710 // We always have to emit key leaf values
711 keys.contains(leafSchema.getQName())
712 // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
714 // When data is retrieved with a <with-defaults> parameter equal to
715 // 'trim', data nodes MUST NOT be reported if they contain the schema
716 // default value. Non-configuration data nodes containing the schema
717 // default value MUST NOT be reported.
719 || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
720 // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
721 // grasp what we are doing here... emit only if it matches default ???!!!
722 // FIXME: The WithDefaultsParam.EXPLICIT says:
724 // Data nodes set to the YANG default by the client are reported.
726 // and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
728 // If the "with-defaults" parameter is set to "explicit", then the
729 // server MUST adhere to the default-reporting behavior defined in
730 // Section 3.3 of [RFC6243].
732 // and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
734 // When data is retrieved with a <with-defaults> parameter equal to
735 // 'explicit', a data node that was set by a client to its schema
736 // default value MUST be reported. A conceptual data node that would be
737 // set by the server to the schema default value MUST NOT be reported.
738 // Non-configuration data nodes containing the schema default value MUST
741 // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
742 // This seems to disregard the 'trim = true' case semantics (see above).
743 // Combining the above, though, these checks are missing the 'non-config' check, which would
744 // distinguish, but barring that this check is superfluous and results in the wrong semantics.
745 // Without that input, this really should be covered by the previous case.
746 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
747 builder.withChild(leaf);
751 private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
752 final DataSchemaContext childCtx, final boolean trim) {
753 if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
754 throw new IllegalStateException("Input " + map + " does not match " + childCtx);
757 final var childBuilder = switch (map.ordering()) {
758 case SYSTEM -> Builders.mapBuilder();
759 case USER -> Builders.orderedMapBuilder();
761 buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
762 listSchema.getKeyDefinition());
763 builder.withChild(childBuilder.build());
766 private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
767 final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
768 final List<@NonNull QName> keys) {
769 for (var entry : entries) {
770 final var childCtx = getChildContext(ctxNode, entry);
771 final var mapEntryBuilder = Builders.mapEntryBuilder().withNodeIdentifier(entry.name());
772 buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
773 builder.withChild(mapEntryBuilder.build());
777 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
778 final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
779 for (var child : children) {
780 final var childCtx = getChildContext(ctxNode, child);
781 if (child instanceof ContainerNode container) {
782 appendContainer(builder, container, childCtx, trim);
783 } else if (child instanceof MapNode map) {
784 appendMap(builder, map, childCtx, trim);
785 } else if (child instanceof LeafNode<?> leaf) {
786 appendLeaf(builder, leaf, childCtx, trim, List.of());
791 private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
792 final NormalizedNode child) {
793 final var childId = child.name();
794 final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
796 if (childCtx == null) {
797 throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
802 private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
803 final NormalizedNode configDataNode) {
805 if (stateDataNode == null && configDataNode == null) {
809 // return config data
810 if (stateDataNode == null) {
811 return configDataNode;
815 if (configDataNode == null) {
816 return stateDataNode;
819 // merge data from config and state
820 return mergeStateAndConfigData(stateDataNode, configDataNode);
824 * Merge state and config data into a single NormalizedNode.
826 * @param stateDataNode data node of state data
827 * @param configDataNode data node of config data
828 * @return {@link NormalizedNode}
830 private static @NonNull NormalizedNode mergeStateAndConfigData(
831 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
832 validateNodeMerge(stateDataNode, configDataNode);
833 // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
834 if (configDataNode instanceof RpcDefinition) {
835 return prepareRpcData(configDataNode, stateDataNode);
837 return prepareData(configDataNode, stateDataNode);
842 * Validates whether the two NormalizedNodes can be merged.
844 * @param stateDataNode data node of state data
845 * @param configDataNode data node of config data
847 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
848 final @NonNull NormalizedNode configDataNode) {
849 final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
850 final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
851 if (!moduleOfStateData.equals(moduleOfConfigData)) {
852 throw new RestconfDocumentedException("Unable to merge data from different modules.");
857 * Prepare and map data for rpc.
859 * @param configDataNode data node of config data
860 * @param stateDataNode data node of state data
861 * @return {@link NormalizedNode}
863 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
864 final @NonNull NormalizedNode stateDataNode) {
865 final var mapEntryBuilder = Builders.mapEntryBuilder()
866 .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
869 mapRpcDataNode(configDataNode, mapEntryBuilder);
871 mapRpcDataNode(stateDataNode, mapEntryBuilder);
873 return Builders.mapBuilder()
874 .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
875 .addChild(mapEntryBuilder.build())
880 * Map node to map entry builder.
882 * @param dataNode data node
883 * @param mapEntryBuilder builder for mapping data
885 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
886 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
887 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
891 * Prepare and map all data from DS.
893 * @param configDataNode data node of config data
894 * @param stateDataNode data node of state data
895 * @return {@link NormalizedNode}
897 @SuppressWarnings("unchecked")
898 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
899 final @NonNull NormalizedNode stateDataNode) {
900 if (configDataNode instanceof UserMapNode configMap) {
901 final var builder = Builders.orderedMapBuilder().withNodeIdentifier(configMap.name());
902 mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
903 return builder.build();
904 } else if (configDataNode instanceof SystemMapNode configMap) {
905 final var builder = Builders.mapBuilder().withNodeIdentifier(configMap.name());
906 mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
907 return builder.build();
908 } else if (configDataNode instanceof MapEntryNode configEntry) {
909 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(configEntry.name());
910 mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
911 return builder.build();
912 } else if (configDataNode instanceof ContainerNode configContaienr) {
913 final var builder = Builders.containerBuilder().withNodeIdentifier(configContaienr.name());
914 mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
915 return builder.build();
916 } else if (configDataNode instanceof ChoiceNode configChoice) {
917 final var builder = Builders.choiceBuilder().withNodeIdentifier(configChoice.name());
918 mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
919 return builder.build();
920 } else if (configDataNode instanceof LeafNode configLeaf) {
921 // config trumps oper
923 } else if (configDataNode instanceof UserLeafSetNode) {
924 final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
925 final var builder = Builders.<Object>orderedLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
926 mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
927 return builder.build();
928 } else if (configDataNode instanceof SystemLeafSetNode) {
929 final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
930 final var builder = Builders.<Object>leafSetBuilder().withNodeIdentifier(configLeafSet.name());
931 mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
932 return builder.build();
933 } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
934 // config trumps oper
936 } else if (configDataNode instanceof UnkeyedListNode configList) {
937 final var builder = Builders.unkeyedListBuilder().withNodeIdentifier(configList.name());
938 mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
939 return builder.build();
940 } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
941 final var builder = Builders.unkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
942 mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
943 return builder.build();
945 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
950 * Map value from container node to builder.
952 * @param configData collection of config data nodes
953 * @param stateData collection of state data nodes
954 * @param builder builder
956 private static <T extends NormalizedNode> void mapValueToBuilder(
957 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
958 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
959 final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
960 final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
962 // merge config and state data of children with different identifiers
963 mapDataToBuilder(configMap, stateMap, builder);
965 // merge config and state data of children with the same identifiers
966 mergeDataToBuilder(configMap, stateMap, builder);
970 * Map data with different identifiers to builder. Data with different identifiers can be just added
971 * as childs to parent node.
973 * @param configMap map of config data nodes
974 * @param stateMap map of state data nodes
975 * @param builder - builder
977 private static <T extends NormalizedNode> void mapDataToBuilder(
978 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
979 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
980 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
981 y -> builder.addChild(y.getValue()));
982 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
983 y -> builder.addChild(y.getValue()));
987 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
988 * go one level down with {@code prepareData} method.
990 * @param configMap immutable config data
991 * @param stateMap immutable state data
992 * @param builder - builder
994 @SuppressWarnings("unchecked")
995 private static <T extends NormalizedNode> void mergeDataToBuilder(
996 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
997 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
998 // it is enough to process only config data because operational contains the same data
999 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1000 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));