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.DOMRpcResult;
32 import org.opendaylight.mdsal.dom.api.DOMRpcService;
33 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
34 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
35 import org.opendaylight.restconf.api.query.ContentParam;
36 import org.opendaylight.restconf.api.query.WithDefaultsParam;
37 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
38 import org.opendaylight.restconf.common.errors.RestconfError;
39 import org.opendaylight.restconf.common.errors.RestconfFuture;
40 import org.opendaylight.restconf.common.errors.SettableRestconfFuture;
41 import org.opendaylight.restconf.common.patch.PatchContext;
42 import org.opendaylight.restconf.common.patch.PatchStatusContext;
43 import org.opendaylight.restconf.common.patch.PatchStatusEntity;
44 import org.opendaylight.restconf.nb.rfc8040.Insert;
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);
113 private final @NonNull EffectiveModelContext modelContext;
114 private final @Nullable DOMRpcService rpcService;
116 RestconfStrategy(final EffectiveModelContext modelContext, final @Nullable DOMRpcService rpcService) {
117 this.modelContext = requireNonNull(modelContext);
118 this.rpcService = rpcService;
122 * Look up the appropriate strategy for a particular mount point.
124 * @param modelContext {@link EffectiveModelContext} of target mount point
125 * @param mountPoint Target mount point
126 * @return A strategy, or null if the mount point does not expose a supported interface
127 * @throws NullPointerException if any argument is {@code null}
129 public static @Nullable RestconfStrategy forMountPoint(final EffectiveModelContext modelContext,
130 final DOMMountPoint mountPoint) {
131 final var rpcService = mountPoint.getService(DOMRpcService.class).orElse(null);
133 final var netconfService = mountPoint.getService(NetconfDataTreeService.class);
134 if (netconfService.isPresent()) {
135 return new NetconfRestconfStrategy(modelContext, netconfService.orElseThrow(), rpcService);
137 final var dataBroker = mountPoint.getService(DOMDataBroker.class);
138 if (dataBroker.isPresent()) {
139 return new MdsalRestconfStrategy(modelContext, dataBroker.orElseThrow(), rpcService);
144 public final @NonNull EffectiveModelContext modelContext() {
149 * Lock the entire datastore.
151 * @return A {@link RestconfTransaction}. This transaction needs to be either committed or canceled before doing
154 abstract RestconfTransaction prepareWriteExecution();
157 * Read data from the datastore.
159 * @param store the logical data store which should be modified
160 * @param path the data object path
161 * @return a ListenableFuture containing the result of the read
163 abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path);
166 * Read data selected using fields from the datastore.
168 * @param store the logical data store which should be modified
169 * @param path the parent data object path
170 * @param fields paths to selected fields relative to parent path
171 * @return a ListenableFuture containing the result of the read
173 abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path,
174 List<YangInstanceIdentifier> fields);
177 * Check if data already exists in the configuration datastore.
179 * @param path the data object path
180 * @return a ListenableFuture containing the result of the check
182 // FIXME: this method should be hosted in RestconfTransaction
183 // FIXME: this method should only be needed in MdsalRestconfStrategy
184 abstract ListenableFuture<Boolean> exists(YangInstanceIdentifier path);
187 * Delete data from the configuration datastore. If the data does not exist, this operation will fail, as outlined
188 * in <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.7">RFC8040 section 4.7</a>
190 * @param path Path to delete
191 * @return A {@link RestconfFuture}
192 * @throws NullPointerException if {@code path} is {@code null}
194 public final @NonNull RestconfFuture<Empty> delete(final YangInstanceIdentifier path) {
195 final var ret = new SettableRestconfFuture<Empty>();
196 delete(ret, requireNonNull(path));
200 abstract void delete(@NonNull SettableRestconfFuture<Empty> future, @NonNull YangInstanceIdentifier path);
203 * Merge data into the configuration datastore, as outlined in
204 * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040 section 4.6.1</a>.
206 * @param path Path to merge
207 * @param data Data to merge
208 * @return A {@link RestconfFuture}
209 * @throws NullPointerException if any argument is {@code null}
211 public final @NonNull RestconfFuture<Empty> merge(final YangInstanceIdentifier path, final NormalizedNode data) {
212 final var ret = new SettableRestconfFuture<Empty>();
213 merge(ret, requireNonNull(path), requireNonNull(data));
217 private void merge(final @NonNull SettableRestconfFuture<Empty> future, final @NonNull YangInstanceIdentifier path,
218 final @NonNull NormalizedNode data) {
219 final var tx = prepareWriteExecution();
220 // FIXME: this method should be further specialized to eliminate this call -- it is only needed for MD-SAL
221 tx.ensureParentsByMerge(path);
222 tx.merge(path, data);
223 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
225 public void onSuccess(final CommitInfo result) {
226 future.set(Empty.value());
230 public void onFailure(final Throwable cause) {
231 future.setFailure(TransactionUtil.decodeException(cause, "MERGE", path));
233 }, MoreExecutors.directExecutor());
237 * Check mount point and prepare variables for put data to DS.
239 * @param path path of data
241 * @param insert {@link Insert}
242 * @return A {@link CreateOrReplaceResult}
244 public final @NonNull CreateOrReplaceResult putData(final YangInstanceIdentifier path, final NormalizedNode data,
245 final @Nullable Insert insert) {
246 final var exists = TransactionUtil.syncAccess(exists(path), path);
248 final ListenableFuture<? extends CommitInfo> commitFuture;
249 if (insert != null) {
250 final var parentPath = path.coerceParent();
251 checkListAndOrderedType(parentPath);
252 commitFuture = insertAndCommitPut(path, data, insert, parentPath);
254 commitFuture = replaceAndCommit(prepareWriteExecution(), path, data);
257 TransactionUtil.syncCommit(commitFuture, "PUT", path);
258 return exists ? CreateOrReplaceResult.REPLACED : CreateOrReplaceResult.CREATED;
261 private ListenableFuture<? extends CommitInfo> insertAndCommitPut(final YangInstanceIdentifier path,
262 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parentPath) {
263 final var tx = prepareWriteExecution();
265 return switch (insert.insert()) {
267 final var readData = tx.readList(parentPath);
268 if (readData == null || readData.isEmpty()) {
269 yield replaceAndCommit(tx, path, data);
271 tx.remove(parentPath);
272 tx.replace(path, data);
273 tx.replace(parentPath, readData);
276 case LAST -> replaceAndCommit(tx, path, data);
278 final var readData = tx.readList(parentPath);
279 if (readData == null || readData.isEmpty()) {
280 yield replaceAndCommit(tx, path, data);
282 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
286 final var readData = tx.readList(parentPath);
287 if (readData == null || readData.isEmpty()) {
288 yield replaceAndCommit(tx, path, data);
290 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
296 private void insertWithPointPut(final RestconfTransaction tx, final YangInstanceIdentifier path,
297 final NormalizedNode data, final @NonNull PathArgument pointArg, final NormalizedNodeContainer<?> readList,
298 final boolean before) {
299 tx.remove(path.getParent());
301 int lastItemPosition = 0;
302 for (var nodeChild : readList.body()) {
303 if (nodeChild.name().equals(pointArg)) {
312 int lastInsertedPosition = 0;
313 final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext, path.getParent());
314 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
315 for (var nodeChild : readList.body()) {
316 if (lastInsertedPosition == lastItemPosition) {
317 tx.replace(path, data);
319 final var childPath = path.coerceParent().node(nodeChild.name());
320 tx.replace(childPath, nodeChild);
321 lastInsertedPosition++;
325 private static ListenableFuture<? extends CommitInfo> replaceAndCommit(final RestconfTransaction tx,
326 final YangInstanceIdentifier path, final NormalizedNode data) {
327 tx.replace(path, data);
331 private DataSchemaNode checkListAndOrderedType(final YangInstanceIdentifier path) {
332 // FIXME: we have this available in InstanceIdentifierContext
333 final var dataSchemaNode = DataSchemaContextTree.from(modelContext).findChild(path).orElseThrow()
336 final String message;
337 if (dataSchemaNode instanceof ListSchemaNode listSchema) {
338 if (listSchema.isUserOrdered()) {
341 message = "Insert parameter can be used only with ordered-by user list.";
342 } else if (dataSchemaNode instanceof LeafListSchemaNode leafListSchema) {
343 if (leafListSchema.isUserOrdered()) {
344 return leafListSchema;
346 message = "Insert parameter can be used only with ordered-by user leaf-list.";
348 message = "Insert parameter can be used only with list or leaf-list";
350 throw new RestconfDocumentedException(message, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
354 * Check mount point and prepare variables for post data.
358 * @param insert {@link Insert}
360 public final void postData(final YangInstanceIdentifier path, final NormalizedNode data,
361 final @Nullable Insert insert) {
362 final ListenableFuture<? extends CommitInfo> future;
363 if (insert != null) {
364 final var parentPath = path.coerceParent();
365 checkListAndOrderedType(parentPath);
366 future = insertAndCommitPost(path, data, insert, parentPath);
368 future = createAndCommit(prepareWriteExecution(), path, data);
370 TransactionUtil.syncCommit(future, "POST", path);
373 private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
374 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parent) {
375 final var grandParent = parent.coerceParent();
376 final var tx = prepareWriteExecution();
378 return switch (insert.insert()) {
380 final var readData = tx.readList(grandParent);
381 if (readData == null || readData.isEmpty()) {
382 tx.replace(path, data);
384 checkItemDoesNotExists(exists(path), path);
385 tx.remove(grandParent);
386 tx.replace(path, data);
387 tx.replace(grandParent, readData);
391 case LAST -> createAndCommit(tx, path, data);
393 final var readData = tx.readList(grandParent);
394 if (readData == null || readData.isEmpty()) {
395 tx.replace(path, data);
397 checkItemDoesNotExists(exists(path), path);
398 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, true);
403 final var readData = tx.readList(grandParent);
404 if (readData == null || readData.isEmpty()) {
405 tx.replace(path, data);
407 checkItemDoesNotExists(exists(path), path);
408 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, false);
416 * Process edit operations of one {@link PatchContext}.
418 * @param patch Patch context to be processed
419 * @return {@link PatchStatusContext}
421 public final @NonNull PatchStatusContext patchData(final PatchContext patch) {
422 final var editCollection = new ArrayList<PatchStatusEntity>();
423 final var tx = prepareWriteExecution();
425 boolean noError = true;
426 for (var patchEntity : patch.entities()) {
428 final var targetNode = patchEntity.getTargetNode();
429 final var editId = patchEntity.getEditId();
431 switch (patchEntity.getOperation()) {
434 tx.create(targetNode, patchEntity.getNode());
435 editCollection.add(new PatchStatusEntity(editId, true, null));
436 } catch (RestconfDocumentedException e) {
437 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
443 tx.delete(targetNode);
444 editCollection.add(new PatchStatusEntity(editId, true, null));
445 } catch (RestconfDocumentedException e) {
446 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
452 tx.ensureParentsByMerge(targetNode);
453 tx.merge(targetNode, patchEntity.getNode());
454 editCollection.add(new PatchStatusEntity(editId, true, null));
455 } catch (RestconfDocumentedException e) {
456 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
462 tx.replace(targetNode, patchEntity.getNode());
463 editCollection.add(new PatchStatusEntity(editId, true, null));
464 } catch (RestconfDocumentedException e) {
465 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
471 tx.remove(targetNode);
472 editCollection.add(new PatchStatusEntity(editId, true, null));
473 } catch (RestconfDocumentedException e) {
474 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
479 editCollection.add(new PatchStatusEntity(editId, false, List.of(
480 new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
481 "Not supported Yang Patch operation"))));
490 // if no errors then submit transaction, otherwise cancel
491 final var patchId = patch.patchId();
494 TransactionUtil.syncCommit(tx.commit(), "PATCH", null);
495 } catch (RestconfDocumentedException e) {
496 // if errors occurred during transaction commit then patch failed and global errors are reported
497 return new PatchStatusContext(modelContext, patchId, List.copyOf(editCollection), false, e.getErrors());
500 return new PatchStatusContext(modelContext, patchId, List.copyOf(editCollection), true, null);
503 return new PatchStatusContext(modelContext, patchId, List.copyOf(editCollection), false, null);
507 private void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
508 final NormalizedNode data, final PathArgument pointArg, final NormalizedNodeContainer<?> readList,
509 final YangInstanceIdentifier grandParentPath, final boolean before) {
510 tx.remove(grandParentPath);
512 int lastItemPosition = 0;
513 for (var nodeChild : readList.body()) {
514 if (nodeChild.name().equals(pointArg)) {
523 int lastInsertedPosition = 0;
524 final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext, grandParentPath);
525 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
526 for (var nodeChild : readList.body()) {
527 if (lastInsertedPosition == lastItemPosition) {
528 tx.replace(path, data);
530 tx.replace(grandParentPath.node(nodeChild.name()), nodeChild);
531 lastInsertedPosition++;
535 private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
536 final YangInstanceIdentifier path, final NormalizedNode data) {
538 tx.create(path, data);
539 } catch (RestconfDocumentedException e) {
540 // close transaction if any and pass exception further
549 * Check if items do NOT already exists at specified {@code path}.
551 * @param existsFuture if checked data exists
552 * @param path Path to be checked
553 * @throws RestconfDocumentedException if data already exists.
555 static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
556 final YangInstanceIdentifier path) {
557 if (TransactionUtil.syncAccess(existsFuture, path)) {
558 LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
559 throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
565 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
566 * inside of object {@link RestconfStrategy} provided as a parameter.
568 * @param content type of data to read (config, state, all)
569 * @param path the path to read
570 * @param defaultsMode value of with-defaults parameter
571 * @return {@link NormalizedNode}
573 public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
574 final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
575 return switch (content) {
577 // PREPARE STATE DATA NODE
578 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
579 // PREPARE CONFIG DATA NODE
580 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
582 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
583 : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
586 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
587 yield defaultsMode == null ? read
588 : prepareDataByParamWithDef(read, path, defaultsMode.mode());
590 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
595 * Read specific type of data from data store via transaction with specified subtrees that should only be read.
596 * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
598 * @param content type of data to read (config, state, all)
599 * @param path the parent path to read
600 * @param withDefa value of with-defaults parameter
601 * @param fields paths to selected subtrees which should be read, relative to to the parent path
602 * @return {@link NormalizedNode}
604 public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
605 final @NonNull YangInstanceIdentifier path, final @Nullable WithDefaultsParam withDefa,
606 final @NonNull List<YangInstanceIdentifier> fields) {
607 return switch (content) {
609 // PREPARE STATE DATA NODE
610 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
611 // PREPARE CONFIG DATA NODE
612 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
614 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, withDefa == null ? configDataNode
615 : prepareDataByParamWithDef(configDataNode, path, withDefa.mode()));
618 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
619 yield withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa.mode());
621 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
625 private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
626 final YangInstanceIdentifier path) {
627 return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
631 * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
632 * specified subtrees that should only be read.
634 * @param store datastore type
635 * @param path parent path to selected fields
636 * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
637 * in {@link RestconfStrategy} if any
638 * @param fields paths to selected subtrees which should be read, relative to to the parent path
639 * @return {@link NormalizedNode}
641 private @Nullable NormalizedNode readDataViaTransaction(final @NonNull LogicalDatastoreType store,
642 final @NonNull YangInstanceIdentifier path, final @NonNull List<YangInstanceIdentifier> fields) {
643 return TransactionUtil.syncAccess(read(store, path, fields), path).orElse(null);
646 private NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
647 final WithDefaultsMode defaultsMode) {
648 final boolean trim = switch (defaultsMode) {
650 case Explicit -> false;
651 case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
652 "Unsupported with-defaults value " + defaultsMode.getName());
655 // FIXME: we have this readily available in InstanceIdentifierContext
656 final var ctxNode = DataSchemaContextTree.from(modelContext).findChild(path).orElseThrow();
657 if (readData instanceof ContainerNode container) {
658 final var builder = Builders.containerBuilder().withNodeIdentifier(container.name());
659 buildCont(builder, container.body(), ctxNode, trim);
660 return builder.build();
661 } else if (readData instanceof MapEntryNode mapEntry) {
662 if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
663 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
666 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(mapEntry.name());
667 buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
668 return builder.build();
670 throw new IllegalStateException("Unhandled data contract " + readData.contract());
674 private static void buildMapEntryBuilder(
675 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
676 final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
677 final boolean trim, final List<QName> keys) {
678 for (var child : children) {
679 final var childCtx = getChildContext(ctxNode, child);
681 if (child instanceof ContainerNode container) {
682 appendContainer(builder, container, childCtx, trim);
683 } else if (child instanceof MapNode map) {
684 appendMap(builder, map, childCtx, trim);
685 } else if (child instanceof LeafNode<?> leaf) {
686 appendLeaf(builder, leaf, childCtx, trim, keys);
688 // FIXME: we should never hit this, throw an ISE if this ever happens
689 LOG.debug("Ignoring unhandled child contract {}", child.contract());
694 private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
695 final DataSchemaContext ctxNode, final boolean trim) {
696 final var childBuilder = Builders.containerBuilder().withNodeIdentifier(container.name());
697 buildCont(childBuilder, container.body(), ctxNode, trim);
698 builder.withChild(childBuilder.build());
701 private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
702 final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
703 if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
704 throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
707 // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
708 final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
710 // This is a combined check for when we need to emit the leaf.
712 // We always have to emit key leaf values
713 keys.contains(leafSchema.getQName())
714 // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
716 // When data is retrieved with a <with-defaults> parameter equal to
717 // 'trim', data nodes MUST NOT be reported if they contain the schema
718 // default value. Non-configuration data nodes containing the schema
719 // default value MUST NOT be reported.
721 || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
722 // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
723 // grasp what we are doing here... emit only if it matches default ???!!!
724 // FIXME: The WithDefaultsParam.EXPLICIT says:
726 // Data nodes set to the YANG default by the client are reported.
728 // and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
730 // If the "with-defaults" parameter is set to "explicit", then the
731 // server MUST adhere to the default-reporting behavior defined in
732 // Section 3.3 of [RFC6243].
734 // and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
736 // When data is retrieved with a <with-defaults> parameter equal to
737 // 'explicit', a data node that was set by a client to its schema
738 // default value MUST be reported. A conceptual data node that would be
739 // set by the server to the schema default value MUST NOT be reported.
740 // Non-configuration data nodes containing the schema default value MUST
743 // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
744 // This seems to disregard the 'trim = true' case semantics (see above).
745 // Combining the above, though, these checks are missing the 'non-config' check, which would
746 // distinguish, but barring that this check is superfluous and results in the wrong semantics.
747 // Without that input, this really should be covered by the previous case.
748 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
749 builder.withChild(leaf);
753 private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
754 final DataSchemaContext childCtx, final boolean trim) {
755 if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
756 throw new IllegalStateException("Input " + map + " does not match " + childCtx);
759 final var childBuilder = switch (map.ordering()) {
760 case SYSTEM -> Builders.mapBuilder();
761 case USER -> Builders.orderedMapBuilder();
763 buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
764 listSchema.getKeyDefinition());
765 builder.withChild(childBuilder.build());
768 private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
769 final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
770 final List<@NonNull QName> keys) {
771 for (var entry : entries) {
772 final var childCtx = getChildContext(ctxNode, entry);
773 final var mapEntryBuilder = Builders.mapEntryBuilder().withNodeIdentifier(entry.name());
774 buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
775 builder.withChild(mapEntryBuilder.build());
779 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
780 final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
781 for (var child : children) {
782 final var childCtx = getChildContext(ctxNode, child);
783 if (child instanceof ContainerNode container) {
784 appendContainer(builder, container, childCtx, trim);
785 } else if (child instanceof MapNode map) {
786 appendMap(builder, map, childCtx, trim);
787 } else if (child instanceof LeafNode<?> leaf) {
788 appendLeaf(builder, leaf, childCtx, trim, List.of());
793 private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
794 final NormalizedNode child) {
795 final var childId = child.name();
796 final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
798 if (childCtx == null) {
799 throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
804 private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
805 final NormalizedNode configDataNode) {
807 if (stateDataNode == null && configDataNode == null) {
811 // return config data
812 if (stateDataNode == null) {
813 return configDataNode;
817 if (configDataNode == null) {
818 return stateDataNode;
821 // merge data from config and state
822 return mergeStateAndConfigData(stateDataNode, configDataNode);
826 * Merge state and config data into a single NormalizedNode.
828 * @param stateDataNode data node of state data
829 * @param configDataNode data node of config data
830 * @return {@link NormalizedNode}
832 private static @NonNull NormalizedNode mergeStateAndConfigData(
833 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
834 validateNodeMerge(stateDataNode, configDataNode);
835 // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
836 if (configDataNode instanceof RpcDefinition) {
837 return prepareRpcData(configDataNode, stateDataNode);
839 return prepareData(configDataNode, stateDataNode);
844 * Validates whether the two NormalizedNodes can be merged.
846 * @param stateDataNode data node of state data
847 * @param configDataNode data node of config data
849 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
850 final @NonNull NormalizedNode configDataNode) {
851 final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
852 final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
853 if (!moduleOfStateData.equals(moduleOfConfigData)) {
854 throw new RestconfDocumentedException("Unable to merge data from different modules.");
859 * Prepare and map data for rpc.
861 * @param configDataNode data node of config data
862 * @param stateDataNode data node of state data
863 * @return {@link NormalizedNode}
865 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
866 final @NonNull NormalizedNode stateDataNode) {
867 final var mapEntryBuilder = Builders.mapEntryBuilder()
868 .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
871 mapRpcDataNode(configDataNode, mapEntryBuilder);
873 mapRpcDataNode(stateDataNode, mapEntryBuilder);
875 return Builders.mapBuilder()
876 .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
877 .addChild(mapEntryBuilder.build())
882 * Map node to map entry builder.
884 * @param dataNode data node
885 * @param mapEntryBuilder builder for mapping data
887 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
888 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
889 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
893 * Prepare and map all data from DS.
895 * @param configDataNode data node of config data
896 * @param stateDataNode data node of state data
897 * @return {@link NormalizedNode}
899 @SuppressWarnings("unchecked")
900 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
901 final @NonNull NormalizedNode stateDataNode) {
902 if (configDataNode instanceof UserMapNode configMap) {
903 final var builder = Builders.orderedMapBuilder().withNodeIdentifier(configMap.name());
904 mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
905 return builder.build();
906 } else if (configDataNode instanceof SystemMapNode configMap) {
907 final var builder = Builders.mapBuilder().withNodeIdentifier(configMap.name());
908 mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
909 return builder.build();
910 } else if (configDataNode instanceof MapEntryNode configEntry) {
911 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(configEntry.name());
912 mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
913 return builder.build();
914 } else if (configDataNode instanceof ContainerNode configContaienr) {
915 final var builder = Builders.containerBuilder().withNodeIdentifier(configContaienr.name());
916 mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
917 return builder.build();
918 } else if (configDataNode instanceof ChoiceNode configChoice) {
919 final var builder = Builders.choiceBuilder().withNodeIdentifier(configChoice.name());
920 mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
921 return builder.build();
922 } else if (configDataNode instanceof LeafNode configLeaf) {
923 // config trumps oper
925 } else if (configDataNode instanceof UserLeafSetNode) {
926 final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
927 final var builder = Builders.<Object>orderedLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
928 mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
929 return builder.build();
930 } else if (configDataNode instanceof SystemLeafSetNode) {
931 final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
932 final var builder = Builders.<Object>leafSetBuilder().withNodeIdentifier(configLeafSet.name());
933 mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
934 return builder.build();
935 } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
936 // config trumps oper
938 } else if (configDataNode instanceof UnkeyedListNode configList) {
939 final var builder = Builders.unkeyedListBuilder().withNodeIdentifier(configList.name());
940 mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
941 return builder.build();
942 } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
943 final var builder = Builders.unkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
944 mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
945 return builder.build();
947 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
952 * Map value from container node to builder.
954 * @param configData collection of config data nodes
955 * @param stateData collection of state data nodes
956 * @param builder builder
958 private static <T extends NormalizedNode> void mapValueToBuilder(
959 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
960 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
961 final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
962 final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
964 // merge config and state data of children with different identifiers
965 mapDataToBuilder(configMap, stateMap, builder);
967 // merge config and state data of children with the same identifiers
968 mergeDataToBuilder(configMap, stateMap, builder);
972 * Map data with different identifiers to builder. Data with different identifiers can be just added
973 * as childs to parent node.
975 * @param configMap map of config data nodes
976 * @param stateMap map of state data nodes
977 * @param builder - builder
979 private static <T extends NormalizedNode> void mapDataToBuilder(
980 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
981 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
982 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
983 y -> builder.addChild(y.getValue()));
984 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
985 y -> builder.addChild(y.getValue()));
989 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
990 * go one level down with {@code prepareData} method.
992 * @param configMap immutable config data
993 * @param stateMap immutable state data
994 * @param builder - builder
996 @SuppressWarnings("unchecked")
997 private static <T extends NormalizedNode> void mergeDataToBuilder(
998 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
999 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1000 // it is enough to process only config data because operational contains the same data
1001 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1002 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1005 public @NonNull RestconfFuture<Optional<ContainerNode>> invokeRpc(final QName type, final ContainerNode input) {
1006 final var ret = new SettableRestconfFuture<Optional<ContainerNode>>();
1008 final var local = rpcService;
1009 if (local != null) {
1010 Futures.addCallback(local.invokeRpc(requireNonNull(type), requireNonNull(input)),
1011 new FutureCallback<DOMRpcResult>() {
1013 public void onSuccess(final DOMRpcResult response) {
1014 final var errors = response.errors();
1015 if (errors.isEmpty()) {
1016 ret.set(Optional.ofNullable(response.value()));
1018 LOG.debug("RPC invocation reported {}", response.errors());
1019 ret.setFailure(new RestconfDocumentedException("RPC implementation reported errors", null,
1020 response.errors()));
1025 public void onFailure(final Throwable cause) {
1026 LOG.debug("RPC invocation failed, cause");
1027 if (cause instanceof RestconfDocumentedException ex) {
1030 // TODO: YangNetconfErrorAware if we ever get into a broader invocation scope
1031 ret.setFailure(new RestconfDocumentedException(cause,
1032 new RestconfError(ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage())));
1035 }, MoreExecutors.directExecutor());
1037 LOG.debug("RPC invocation is not available");
1038 ret.setFailure(new RestconfDocumentedException("RPC invocation is not available",
1039 ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED));