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.collect.ImmutableMap;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import com.google.common.util.concurrent.MoreExecutors;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.List;
23 import java.util.NoSuchElementException;
24 import java.util.Optional;
25 import java.util.function.Function;
26 import java.util.stream.Collectors;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.opendaylight.mdsal.common.api.CommitInfo;
30 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
31 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
32 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
33 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
34 import org.opendaylight.mdsal.dom.api.DOMRpcService;
35 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
36 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
37 import org.opendaylight.restconf.api.query.ContentParam;
38 import org.opendaylight.restconf.api.query.WithDefaultsParam;
39 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
40 import org.opendaylight.restconf.common.errors.RestconfError;
41 import org.opendaylight.restconf.common.errors.RestconfFuture;
42 import org.opendaylight.restconf.common.errors.SettableRestconfFuture;
43 import org.opendaylight.restconf.common.patch.PatchContext;
44 import org.opendaylight.restconf.common.patch.PatchStatusContext;
45 import org.opendaylight.restconf.common.patch.PatchStatusEntity;
46 import org.opendaylight.restconf.nb.rfc8040.Insert;
47 import org.opendaylight.restconf.server.spi.OperationInput;
48 import org.opendaylight.restconf.server.spi.OperationOutput;
49 import org.opendaylight.restconf.server.spi.RpcImplementation;
50 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.with.defaults.rev110601.WithDefaultsMode;
51 import org.opendaylight.yangtools.yang.common.Empty;
52 import org.opendaylight.yangtools.yang.common.ErrorTag;
53 import org.opendaylight.yangtools.yang.common.ErrorType;
54 import org.opendaylight.yangtools.yang.common.QName;
55 import org.opendaylight.yangtools.yang.common.QNameModule;
56 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
60 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
63 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
69 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
75 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
76 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
77 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
78 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
79 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
80 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
81 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
82 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
84 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
88 import org.slf4j.Logger;
89 import org.slf4j.LoggerFactory;
92 * Baseline execution strategy for various RESTCONF operations.
94 * @see NetconfRestconfStrategy
95 * @see MdsalRestconfStrategy
97 // FIXME: it seems the first three operations deal with lifecycle of a transaction, while others invoke various
98 // operations. This should be handled through proper allocation indirection.
99 public abstract class RestconfStrategy {
101 * Result of a {@code PUT} request as defined in
102 * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.5">RFC8040 section 4.5</a>. The definition makes it
103 * clear that the logical operation is {@code create-or-replace}.
105 public enum CreateOrReplaceResult {
107 * A new resource has been created.
111 * An existing resources has been replaced.
116 private static final Logger LOG = LoggerFactory.getLogger(RestconfStrategy.class);
118 private final @NonNull EffectiveModelContext modelContext;
119 private final @NonNull ImmutableMap<QName, RpcImplementation> localRpcs;
120 private final DOMRpcService rpcService;
122 RestconfStrategy(final EffectiveModelContext modelContext, final ImmutableMap<QName, RpcImplementation> localRpcs,
123 final @Nullable DOMRpcService rpcService) {
124 this.modelContext = requireNonNull(modelContext);
125 this.localRpcs = requireNonNull(localRpcs);
126 this.rpcService = rpcService;
130 * Look up the appropriate strategy for a particular mount point.
132 * @param modelContext {@link EffectiveModelContext} of target mount point
133 * @param mountPoint Target mount point
134 * @return A strategy, or null if the mount point does not expose a supported interface
135 * @throws NullPointerException if any argument is {@code null}
137 public static @Nullable RestconfStrategy forMountPoint(final EffectiveModelContext modelContext,
138 final DOMMountPoint mountPoint) {
139 final var rpcService = mountPoint.getService(DOMRpcService.class).orElse(null);
141 final var netconfService = mountPoint.getService(NetconfDataTreeService.class);
142 if (netconfService.isPresent()) {
143 return new NetconfRestconfStrategy(modelContext, netconfService.orElseThrow(), rpcService);
145 final var dataBroker = mountPoint.getService(DOMDataBroker.class);
146 if (dataBroker.isPresent()) {
147 return new MdsalRestconfStrategy(modelContext, dataBroker.orElseThrow(), rpcService);
152 public final @NonNull EffectiveModelContext modelContext() {
157 * Lock the entire datastore.
159 * @return A {@link RestconfTransaction}. This transaction needs to be either committed or canceled before doing
162 abstract RestconfTransaction prepareWriteExecution();
165 * Read data from the datastore.
167 * @param store the logical data store which should be modified
168 * @param path the data object path
169 * @return a ListenableFuture containing the result of the read
171 abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path);
174 * Read data selected using fields from the datastore.
176 * @param store the logical data store which should be modified
177 * @param path the parent data object path
178 * @param fields paths to selected fields relative to parent path
179 * @return a ListenableFuture containing the result of the read
181 abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path,
182 List<YangInstanceIdentifier> fields);
185 * Check if data already exists in the configuration datastore.
187 * @param path the data object path
188 * @return a ListenableFuture containing the result of the check
190 // FIXME: this method should be hosted in RestconfTransaction
191 // FIXME: this method should only be needed in MdsalRestconfStrategy
192 abstract ListenableFuture<Boolean> exists(YangInstanceIdentifier path);
195 * Delete data from the configuration datastore. If the data does not exist, this operation will fail, as outlined
196 * in <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.7">RFC8040 section 4.7</a>
198 * @param path Path to delete
199 * @return A {@link RestconfFuture}
200 * @throws NullPointerException if {@code path} is {@code null}
202 public final @NonNull RestconfFuture<Empty> delete(final YangInstanceIdentifier path) {
203 final var ret = new SettableRestconfFuture<Empty>();
204 delete(ret, requireNonNull(path));
208 abstract void delete(@NonNull SettableRestconfFuture<Empty> future, @NonNull YangInstanceIdentifier path);
211 * Merge data into the configuration datastore, as outlined in
212 * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040 section 4.6.1</a>.
214 * @param path Path to merge
215 * @param data Data to merge
216 * @return A {@link RestconfFuture}
217 * @throws NullPointerException if any argument is {@code null}
219 public final @NonNull RestconfFuture<Empty> merge(final YangInstanceIdentifier path, final NormalizedNode data) {
220 final var ret = new SettableRestconfFuture<Empty>();
221 merge(ret, requireNonNull(path), requireNonNull(data));
225 private void merge(final @NonNull SettableRestconfFuture<Empty> future, final @NonNull YangInstanceIdentifier path,
226 final @NonNull NormalizedNode data) {
227 final var tx = prepareWriteExecution();
228 // FIXME: this method should be further specialized to eliminate this call -- it is only needed for MD-SAL
229 tx.ensureParentsByMerge(path);
230 tx.merge(path, data);
231 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
233 public void onSuccess(final CommitInfo result) {
234 future.set(Empty.value());
238 public void onFailure(final Throwable cause) {
239 future.setFailure(TransactionUtil.decodeException(cause, "MERGE", path, modelContext));
241 }, MoreExecutors.directExecutor());
245 * Check mount point and prepare variables for put data to DS.
247 * @param path path of data
249 * @param insert {@link Insert}
250 * @return A {@link CreateOrReplaceResult}
252 public final RestconfFuture<CreateOrReplaceResult> putData(final YangInstanceIdentifier path,
253 final NormalizedNode data, final @Nullable Insert insert) {
254 final var exists = TransactionUtil.syncAccess(exists(path), path);
256 final ListenableFuture<? extends CommitInfo> commitFuture;
257 if (insert != null) {
258 final var parentPath = path.coerceParent();
259 checkListAndOrderedType(parentPath);
260 commitFuture = insertAndCommitPut(path, data, insert, parentPath);
262 commitFuture = replaceAndCommit(prepareWriteExecution(), path, data);
265 final var ret = new SettableRestconfFuture<CreateOrReplaceResult>();
267 Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
269 public void onSuccess(final CommitInfo result) {
270 ret.set(exists ? CreateOrReplaceResult.REPLACED : CreateOrReplaceResult.CREATED);
274 public void onFailure(final Throwable cause) {
275 ret.setFailure(TransactionUtil.decodeException(cause, "PUT", path, modelContext));
277 }, MoreExecutors.directExecutor());
282 private ListenableFuture<? extends CommitInfo> insertAndCommitPut(final YangInstanceIdentifier path,
283 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parentPath) {
284 final var tx = prepareWriteExecution();
286 return switch (insert.insert()) {
288 final var readData = tx.readList(parentPath);
289 if (readData == null || readData.isEmpty()) {
290 yield replaceAndCommit(tx, path, data);
292 tx.remove(parentPath);
293 tx.replace(path, data);
294 tx.replace(parentPath, readData);
297 case LAST -> replaceAndCommit(tx, path, data);
299 final var readData = tx.readList(parentPath);
300 if (readData == null || readData.isEmpty()) {
301 yield replaceAndCommit(tx, path, data);
303 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
307 final var readData = tx.readList(parentPath);
308 if (readData == null || readData.isEmpty()) {
309 yield replaceAndCommit(tx, path, data);
311 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
317 private void insertWithPointPut(final RestconfTransaction tx, final YangInstanceIdentifier path,
318 final NormalizedNode data, final @NonNull PathArgument pointArg, final NormalizedNodeContainer<?> readList,
319 final boolean before) {
320 tx.remove(path.getParent());
322 int lastItemPosition = 0;
323 for (var nodeChild : readList.body()) {
324 if (nodeChild.name().equals(pointArg)) {
333 int lastInsertedPosition = 0;
334 final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext, path.getParent());
335 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
336 for (var nodeChild : readList.body()) {
337 if (lastInsertedPosition == lastItemPosition) {
338 tx.replace(path, data);
340 final var childPath = path.coerceParent().node(nodeChild.name());
341 tx.replace(childPath, nodeChild);
342 lastInsertedPosition++;
346 private static ListenableFuture<? extends CommitInfo> replaceAndCommit(final RestconfTransaction tx,
347 final YangInstanceIdentifier path, final NormalizedNode data) {
348 tx.replace(path, data);
352 private DataSchemaNode checkListAndOrderedType(final YangInstanceIdentifier path) {
353 // FIXME: we have this available in InstanceIdentifierContext
354 final var dataSchemaNode = DataSchemaContextTree.from(modelContext).findChild(path).orElseThrow()
357 final String message;
358 if (dataSchemaNode instanceof ListSchemaNode listSchema) {
359 if (listSchema.isUserOrdered()) {
362 message = "Insert parameter can be used only with ordered-by user list.";
363 } else if (dataSchemaNode instanceof LeafListSchemaNode leafListSchema) {
364 if (leafListSchema.isUserOrdered()) {
365 return leafListSchema;
367 message = "Insert parameter can be used only with ordered-by user leaf-list.";
369 message = "Insert parameter can be used only with list or leaf-list";
371 throw new RestconfDocumentedException(message, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
375 * Check mount point and prepare variables for post data.
379 * @param insert {@link Insert}
380 * @return A {@link RestconfFuture}
382 public final RestconfFuture<Empty> postData(final YangInstanceIdentifier path, final NormalizedNode data,
383 final @Nullable Insert insert) {
384 final ListenableFuture<? extends CommitInfo> future;
385 if (insert != null) {
386 final var parentPath = path.coerceParent();
387 checkListAndOrderedType(parentPath);
388 future = insertAndCommitPost(path, data, insert, parentPath);
390 future = createAndCommit(prepareWriteExecution(), path, data);
392 final var ret = new SettableRestconfFuture<Empty>();
394 Futures.addCallback(future, new FutureCallback<CommitInfo>() {
396 public void onSuccess(final CommitInfo result) {
397 ret.set(Empty.value());
401 public void onFailure(final Throwable cause) {
402 ret.setFailure(TransactionUtil.decodeException(cause, "POST", path, modelContext));
404 }, MoreExecutors.directExecutor());
409 private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
410 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parent) {
411 final var grandParent = parent.coerceParent();
412 final var tx = prepareWriteExecution();
414 return switch (insert.insert()) {
416 final var readData = tx.readList(grandParent);
417 if (readData == null || readData.isEmpty()) {
418 tx.replace(path, data);
420 checkItemDoesNotExists(exists(path), path);
421 tx.remove(grandParent);
422 tx.replace(path, data);
423 tx.replace(grandParent, readData);
427 case LAST -> createAndCommit(tx, path, data);
429 final var readData = tx.readList(grandParent);
430 if (readData == null || readData.isEmpty()) {
431 tx.replace(path, data);
433 checkItemDoesNotExists(exists(path), path);
434 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, true);
439 final var readData = tx.readList(grandParent);
440 if (readData == null || readData.isEmpty()) {
441 tx.replace(path, data);
443 checkItemDoesNotExists(exists(path), path);
444 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, false);
452 * Process edit operations of one {@link PatchContext}.
454 * @param patch Patch context to be processed
455 * @return {@link PatchStatusContext}
457 public final @NonNull RestconfFuture<PatchStatusContext> patchData(final PatchContext patch) {
458 final var editCollection = new ArrayList<PatchStatusEntity>();
459 final var tx = prepareWriteExecution();
461 boolean noError = true;
462 for (var patchEntity : patch.entities()) {
464 final var targetNode = patchEntity.getTargetNode();
465 final var editId = patchEntity.getEditId();
467 switch (patchEntity.getOperation()) {
470 tx.create(targetNode, patchEntity.getNode());
471 editCollection.add(new PatchStatusEntity(editId, true, null));
472 } catch (RestconfDocumentedException e) {
473 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
479 tx.delete(targetNode);
480 editCollection.add(new PatchStatusEntity(editId, true, null));
481 } catch (RestconfDocumentedException e) {
482 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
488 tx.ensureParentsByMerge(targetNode);
489 tx.merge(targetNode, patchEntity.getNode());
490 editCollection.add(new PatchStatusEntity(editId, true, null));
491 } catch (RestconfDocumentedException e) {
492 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
498 tx.replace(targetNode, patchEntity.getNode());
499 editCollection.add(new PatchStatusEntity(editId, true, null));
500 } catch (RestconfDocumentedException e) {
501 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
507 tx.remove(targetNode);
508 editCollection.add(new PatchStatusEntity(editId, true, null));
509 } catch (RestconfDocumentedException e) {
510 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
515 editCollection.add(new PatchStatusEntity(editId, false, List.of(
516 new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
517 "Not supported Yang Patch operation"))));
526 final var ret = new SettableRestconfFuture<PatchStatusContext>();
530 ret.set(new PatchStatusContext(modelContext, patch.patchId(), List.copyOf(editCollection), false, null));
534 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
536 public void onSuccess(final CommitInfo result) {
537 ret.set(new PatchStatusContext(modelContext, patch.patchId(), List.copyOf(editCollection), true, null));
541 public void onFailure(final Throwable cause) {
542 // if errors occurred during transaction commit then patch failed and global errors are reported
543 ret.set(new PatchStatusContext(modelContext, patch.patchId(), List.copyOf(editCollection), false,
544 TransactionUtil.decodeException(cause, "PATCH", null, modelContext).getErrors()));
546 }, MoreExecutors.directExecutor());
551 private void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
552 final NormalizedNode data, final PathArgument pointArg, final NormalizedNodeContainer<?> readList,
553 final YangInstanceIdentifier grandParentPath, final boolean before) {
554 tx.remove(grandParentPath);
556 int lastItemPosition = 0;
557 for (var nodeChild : readList.body()) {
558 if (nodeChild.name().equals(pointArg)) {
567 int lastInsertedPosition = 0;
568 final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext, grandParentPath);
569 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
570 for (var nodeChild : readList.body()) {
571 if (lastInsertedPosition == lastItemPosition) {
572 tx.replace(path, data);
574 tx.replace(grandParentPath.node(nodeChild.name()), nodeChild);
575 lastInsertedPosition++;
579 private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
580 final YangInstanceIdentifier path, final NormalizedNode data) {
582 tx.create(path, data);
583 } catch (RestconfDocumentedException e) {
584 // close transaction if any and pass exception further
593 * Check if items do NOT already exists at specified {@code path}.
595 * @param existsFuture if checked data exists
596 * @param path Path to be checked
597 * @throws RestconfDocumentedException if data already exists.
599 static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
600 final YangInstanceIdentifier path) {
601 if (TransactionUtil.syncAccess(existsFuture, path)) {
602 LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
603 throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
609 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
610 * inside of object {@link RestconfStrategy} provided as a parameter.
612 * @param content type of data to read (config, state, all)
613 * @param path the path to read
614 * @param defaultsMode value of with-defaults parameter
615 * @return {@link NormalizedNode}
617 // FIXME: NETCONF-1155: this method should asynchronous
618 public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
619 final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
620 return switch (content) {
622 // PREPARE STATE DATA NODE
623 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
624 // PREPARE CONFIG DATA NODE
625 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
627 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
628 : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
631 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
632 yield defaultsMode == null ? read
633 : prepareDataByParamWithDef(read, path, defaultsMode.mode());
635 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
640 * Read specific type of data from data store via transaction with specified subtrees that should only be read.
641 * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
643 * @param content type of data to read (config, state, all)
644 * @param path the parent path to read
645 * @param withDefa value of with-defaults parameter
646 * @param fields paths to selected subtrees which should be read, relative to to the parent path
647 * @return {@link NormalizedNode}
649 // FIXME: NETCONF-1155: this method should asynchronous
650 public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
651 final @NonNull YangInstanceIdentifier path, final @Nullable WithDefaultsParam withDefa,
652 final @NonNull List<YangInstanceIdentifier> fields) {
653 return switch (content) {
655 // PREPARE STATE DATA NODE
656 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
657 // PREPARE CONFIG DATA NODE
658 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
660 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, withDefa == null ? configDataNode
661 : prepareDataByParamWithDef(configDataNode, path, withDefa.mode()));
664 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
665 yield withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa.mode());
667 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
671 private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
672 final YangInstanceIdentifier path) {
673 return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
677 * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
678 * specified subtrees that should only be read.
680 * @param store datastore type
681 * @param path parent path to selected fields
682 * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
683 * in {@link RestconfStrategy} if any
684 * @param fields paths to selected subtrees which should be read, relative to to the parent path
685 * @return {@link NormalizedNode}
687 private @Nullable NormalizedNode readDataViaTransaction(final @NonNull LogicalDatastoreType store,
688 final @NonNull YangInstanceIdentifier path, final @NonNull List<YangInstanceIdentifier> fields) {
689 return TransactionUtil.syncAccess(read(store, path, fields), path).orElse(null);
692 private NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
693 final WithDefaultsMode defaultsMode) {
694 final boolean trim = switch (defaultsMode) {
696 case Explicit -> false;
697 case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
698 "Unsupported with-defaults value " + defaultsMode.getName());
701 // FIXME: we have this readily available in InstanceIdentifierContext
702 final var ctxNode = DataSchemaContextTree.from(modelContext).findChild(path).orElseThrow();
703 if (readData instanceof ContainerNode container) {
704 final var builder = Builders.containerBuilder().withNodeIdentifier(container.name());
705 buildCont(builder, container.body(), ctxNode, trim);
706 return builder.build();
707 } else if (readData instanceof MapEntryNode mapEntry) {
708 if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
709 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
712 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(mapEntry.name());
713 buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
714 return builder.build();
716 throw new IllegalStateException("Unhandled data contract " + readData.contract());
720 private static void buildMapEntryBuilder(
721 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
722 final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
723 final boolean trim, final List<QName> keys) {
724 for (var child : children) {
725 final var childCtx = getChildContext(ctxNode, child);
727 if (child instanceof ContainerNode container) {
728 appendContainer(builder, container, childCtx, trim);
729 } else if (child instanceof MapNode map) {
730 appendMap(builder, map, childCtx, trim);
731 } else if (child instanceof LeafNode<?> leaf) {
732 appendLeaf(builder, leaf, childCtx, trim, keys);
734 // FIXME: we should never hit this, throw an ISE if this ever happens
735 LOG.debug("Ignoring unhandled child contract {}", child.contract());
740 private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
741 final DataSchemaContext ctxNode, final boolean trim) {
742 final var childBuilder = Builders.containerBuilder().withNodeIdentifier(container.name());
743 buildCont(childBuilder, container.body(), ctxNode, trim);
744 builder.withChild(childBuilder.build());
747 private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
748 final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
749 if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
750 throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
753 // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
754 final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
756 // This is a combined check for when we need to emit the leaf.
758 // We always have to emit key leaf values
759 keys.contains(leafSchema.getQName())
760 // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
762 // When data is retrieved with a <with-defaults> parameter equal to
763 // 'trim', data nodes MUST NOT be reported if they contain the schema
764 // default value. Non-configuration data nodes containing the schema
765 // default value MUST NOT be reported.
767 || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
768 // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
769 // grasp what we are doing here... emit only if it matches default ???!!!
770 // FIXME: The WithDefaultsParam.EXPLICIT says:
772 // Data nodes set to the YANG default by the client are reported.
774 // and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
776 // If the "with-defaults" parameter is set to "explicit", then the
777 // server MUST adhere to the default-reporting behavior defined in
778 // Section 3.3 of [RFC6243].
780 // and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
782 // When data is retrieved with a <with-defaults> parameter equal to
783 // 'explicit', a data node that was set by a client to its schema
784 // default value MUST be reported. A conceptual data node that would be
785 // set by the server to the schema default value MUST NOT be reported.
786 // Non-configuration data nodes containing the schema default value MUST
789 // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
790 // This seems to disregard the 'trim = true' case semantics (see above).
791 // Combining the above, though, these checks are missing the 'non-config' check, which would
792 // distinguish, but barring that this check is superfluous and results in the wrong semantics.
793 // Without that input, this really should be covered by the previous case.
794 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
795 builder.withChild(leaf);
799 private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
800 final DataSchemaContext childCtx, final boolean trim) {
801 if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
802 throw new IllegalStateException("Input " + map + " does not match " + childCtx);
805 final var childBuilder = switch (map.ordering()) {
806 case SYSTEM -> Builders.mapBuilder();
807 case USER -> Builders.orderedMapBuilder();
809 buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
810 listSchema.getKeyDefinition());
811 builder.withChild(childBuilder.build());
814 private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
815 final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
816 final List<@NonNull QName> keys) {
817 for (var entry : entries) {
818 final var childCtx = getChildContext(ctxNode, entry);
819 final var mapEntryBuilder = Builders.mapEntryBuilder().withNodeIdentifier(entry.name());
820 buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
821 builder.withChild(mapEntryBuilder.build());
825 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
826 final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
827 for (var child : children) {
828 final var childCtx = getChildContext(ctxNode, child);
829 if (child instanceof ContainerNode container) {
830 appendContainer(builder, container, childCtx, trim);
831 } else if (child instanceof MapNode map) {
832 appendMap(builder, map, childCtx, trim);
833 } else if (child instanceof LeafNode<?> leaf) {
834 appendLeaf(builder, leaf, childCtx, trim, List.of());
839 private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
840 final NormalizedNode child) {
841 final var childId = child.name();
842 final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
844 if (childCtx == null) {
845 throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
850 private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
851 final NormalizedNode configDataNode) {
853 if (stateDataNode == null && configDataNode == null) {
857 // return config data
858 if (stateDataNode == null) {
859 return configDataNode;
863 if (configDataNode == null) {
864 return stateDataNode;
867 // merge data from config and state
868 return mergeStateAndConfigData(stateDataNode, configDataNode);
872 * Merge state and config data into a single NormalizedNode.
874 * @param stateDataNode data node of state data
875 * @param configDataNode data node of config data
876 * @return {@link NormalizedNode}
878 private static @NonNull NormalizedNode mergeStateAndConfigData(
879 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
880 validateNodeMerge(stateDataNode, configDataNode);
881 // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
882 if (configDataNode instanceof RpcDefinition) {
883 return prepareRpcData(configDataNode, stateDataNode);
885 return prepareData(configDataNode, stateDataNode);
890 * Validates whether the two NormalizedNodes can be merged.
892 * @param stateDataNode data node of state data
893 * @param configDataNode data node of config data
895 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
896 final @NonNull NormalizedNode configDataNode) {
897 final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
898 final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
899 if (!moduleOfStateData.equals(moduleOfConfigData)) {
900 throw new RestconfDocumentedException("Unable to merge data from different modules.");
905 * Prepare and map data for rpc.
907 * @param configDataNode data node of config data
908 * @param stateDataNode data node of state data
909 * @return {@link NormalizedNode}
911 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
912 final @NonNull NormalizedNode stateDataNode) {
913 final var mapEntryBuilder = Builders.mapEntryBuilder()
914 .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
917 mapRpcDataNode(configDataNode, mapEntryBuilder);
919 mapRpcDataNode(stateDataNode, mapEntryBuilder);
921 return Builders.mapBuilder()
922 .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
923 .addChild(mapEntryBuilder.build())
928 * Map node to map entry builder.
930 * @param dataNode data node
931 * @param mapEntryBuilder builder for mapping data
933 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
934 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
935 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
939 * Prepare and map all data from DS.
941 * @param configDataNode data node of config data
942 * @param stateDataNode data node of state data
943 * @return {@link NormalizedNode}
945 @SuppressWarnings("unchecked")
946 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
947 final @NonNull NormalizedNode stateDataNode) {
948 if (configDataNode instanceof UserMapNode configMap) {
949 final var builder = Builders.orderedMapBuilder().withNodeIdentifier(configMap.name());
950 mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
951 return builder.build();
952 } else if (configDataNode instanceof SystemMapNode configMap) {
953 final var builder = Builders.mapBuilder().withNodeIdentifier(configMap.name());
954 mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
955 return builder.build();
956 } else if (configDataNode instanceof MapEntryNode configEntry) {
957 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(configEntry.name());
958 mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
959 return builder.build();
960 } else if (configDataNode instanceof ContainerNode configContaienr) {
961 final var builder = Builders.containerBuilder().withNodeIdentifier(configContaienr.name());
962 mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
963 return builder.build();
964 } else if (configDataNode instanceof ChoiceNode configChoice) {
965 final var builder = Builders.choiceBuilder().withNodeIdentifier(configChoice.name());
966 mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
967 return builder.build();
968 } else if (configDataNode instanceof LeafNode configLeaf) {
969 // config trumps oper
971 } else if (configDataNode instanceof UserLeafSetNode) {
972 final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
973 final var builder = Builders.<Object>orderedLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
974 mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
975 return builder.build();
976 } else if (configDataNode instanceof SystemLeafSetNode) {
977 final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
978 final var builder = Builders.<Object>leafSetBuilder().withNodeIdentifier(configLeafSet.name());
979 mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
980 return builder.build();
981 } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
982 // config trumps oper
984 } else if (configDataNode instanceof UnkeyedListNode configList) {
985 final var builder = Builders.unkeyedListBuilder().withNodeIdentifier(configList.name());
986 mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
987 return builder.build();
988 } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
989 final var builder = Builders.unkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
990 mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
991 return builder.build();
993 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
998 * Map value from container node to builder.
1000 * @param configData collection of config data nodes
1001 * @param stateData collection of state data nodes
1002 * @param builder builder
1004 private static <T extends NormalizedNode> void mapValueToBuilder(
1005 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
1006 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1007 final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1008 final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1010 // merge config and state data of children with different identifiers
1011 mapDataToBuilder(configMap, stateMap, builder);
1013 // merge config and state data of children with the same identifiers
1014 mergeDataToBuilder(configMap, stateMap, builder);
1018 * Map data with different identifiers to builder. Data with different identifiers can be just added
1019 * as childs to parent node.
1021 * @param configMap map of config data nodes
1022 * @param stateMap map of state data nodes
1023 * @param builder - builder
1025 private static <T extends NormalizedNode> void mapDataToBuilder(
1026 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1027 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1028 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
1029 y -> builder.addChild(y.getValue()));
1030 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
1031 y -> builder.addChild(y.getValue()));
1035 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
1036 * go one level down with {@code prepareData} method.
1038 * @param configMap immutable config data
1039 * @param stateMap immutable state data
1040 * @param builder - builder
1042 @SuppressWarnings("unchecked")
1043 private static <T extends NormalizedNode> void mergeDataToBuilder(
1044 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1045 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1046 // it is enough to process only config data because operational contains the same data
1047 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1048 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1051 public @NonNull RestconfFuture<OperationOutput> invokeRpc(final URI restconfURI, final QName type,
1052 final OperationInput input) {
1053 final var local = localRpcs.get(type);
1054 if (local != null) {
1055 return local.invoke(restconfURI, input);
1057 if (rpcService == null) {
1058 LOG.debug("RPC invocation is not available");
1059 return RestconfFuture.failed(new RestconfDocumentedException("RPC invocation is not available",
1060 ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED));
1063 final var ret = new SettableRestconfFuture<OperationOutput>();
1064 Futures.addCallback(rpcService.invokeRpc(requireNonNull(type), input.input()),
1065 new FutureCallback<DOMRpcResult>() {
1067 public void onSuccess(final DOMRpcResult response) {
1068 final var errors = response.errors();
1069 if (errors.isEmpty()) {
1070 ret.set(input.newOperationOutput(response.value()));
1072 LOG.debug("RPC invocation reported {}", response.errors());
1073 ret.setFailure(new RestconfDocumentedException("RPC implementation reported errors", null,
1074 response.errors()));
1079 public void onFailure(final Throwable cause) {
1080 LOG.debug("RPC invocation failed, cause");
1081 if (cause instanceof RestconfDocumentedException ex) {
1084 // TODO: YangNetconfErrorAware if we ever get into a broader invocation scope
1085 ret.setFailure(new RestconfDocumentedException(cause,
1086 new RestconfError(ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage())));
1089 }, MoreExecutors.directExecutor());