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.api.DataPutResult;
48 import org.opendaylight.restconf.server.spi.OperationInput;
49 import org.opendaylight.restconf.server.spi.OperationOutput;
50 import org.opendaylight.restconf.server.spi.RpcImplementation;
51 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.with.defaults.rev110601.WithDefaultsMode;
52 import org.opendaylight.yangtools.yang.common.Empty;
53 import org.opendaylight.yangtools.yang.common.ErrorTag;
54 import org.opendaylight.yangtools.yang.common.ErrorType;
55 import org.opendaylight.yangtools.yang.common.QName;
56 import org.opendaylight.yangtools.yang.common.QNameModule;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
61 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
64 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
70 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
75 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
76 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
77 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
78 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
79 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
80 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
81 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
82 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
83 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
85 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
93 * Baseline execution strategy for various RESTCONF operations.
95 * @see NetconfRestconfStrategy
96 * @see MdsalRestconfStrategy
98 // FIXME: it seems the first three operations deal with lifecycle of a transaction, while others invoke various
99 // operations. This should be handled through proper allocation indirection.
100 public abstract class RestconfStrategy {
101 private static final Logger LOG = LoggerFactory.getLogger(RestconfStrategy.class);
103 private final @NonNull EffectiveModelContext modelContext;
104 private final @NonNull ImmutableMap<QName, RpcImplementation> localRpcs;
105 private final DOMRpcService rpcService;
107 RestconfStrategy(final EffectiveModelContext modelContext, final ImmutableMap<QName, RpcImplementation> localRpcs,
108 final @Nullable DOMRpcService rpcService) {
109 this.modelContext = requireNonNull(modelContext);
110 this.localRpcs = requireNonNull(localRpcs);
111 this.rpcService = rpcService;
115 * Look up the appropriate strategy for a particular mount point.
117 * @param modelContext {@link EffectiveModelContext} of target mount point
118 * @param mountPoint Target mount point
119 * @return A strategy, or null if the mount point does not expose a supported interface
120 * @throws NullPointerException if any argument is {@code null}
122 public static @Nullable RestconfStrategy forMountPoint(final EffectiveModelContext modelContext,
123 final DOMMountPoint mountPoint) {
124 final var rpcService = mountPoint.getService(DOMRpcService.class).orElse(null);
126 final var netconfService = mountPoint.getService(NetconfDataTreeService.class);
127 if (netconfService.isPresent()) {
128 return new NetconfRestconfStrategy(modelContext, netconfService.orElseThrow(), rpcService);
130 final var dataBroker = mountPoint.getService(DOMDataBroker.class);
131 if (dataBroker.isPresent()) {
132 return new MdsalRestconfStrategy(modelContext, dataBroker.orElseThrow(), rpcService);
137 public final @NonNull EffectiveModelContext modelContext() {
142 * Lock the entire datastore.
144 * @return A {@link RestconfTransaction}. This transaction needs to be either committed or canceled before doing
147 abstract RestconfTransaction prepareWriteExecution();
150 * Read data from the datastore.
152 * @param store the logical data store which should be modified
153 * @param path the data object path
154 * @return a ListenableFuture containing the result of the read
156 abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path);
159 * Read data selected using fields from the datastore.
161 * @param store the logical data store which should be modified
162 * @param path the parent data object path
163 * @param fields paths to selected fields relative to parent path
164 * @return a ListenableFuture containing the result of the read
166 abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path,
167 List<YangInstanceIdentifier> fields);
170 * Check if data already exists in the configuration datastore.
172 * @param path the data object path
173 * @return a ListenableFuture containing the result of the check
175 // FIXME: this method should be hosted in RestconfTransaction
176 // FIXME: this method should only be needed in MdsalRestconfStrategy
177 abstract ListenableFuture<Boolean> exists(YangInstanceIdentifier path);
180 * Delete data from the configuration datastore. If the data does not exist, this operation will fail, as outlined
181 * in <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.7">RFC8040 section 4.7</a>
183 * @param path Path to delete
184 * @return A {@link RestconfFuture}
185 * @throws NullPointerException if {@code path} is {@code null}
187 public final @NonNull RestconfFuture<Empty> delete(final YangInstanceIdentifier path) {
188 final var ret = new SettableRestconfFuture<Empty>();
189 delete(ret, requireNonNull(path));
193 abstract void delete(@NonNull SettableRestconfFuture<Empty> future, @NonNull YangInstanceIdentifier path);
196 * Merge data into the configuration datastore, as outlined in
197 * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040 section 4.6.1</a>.
199 * @param path Path to merge
200 * @param data Data to merge
201 * @return A {@link RestconfFuture}
202 * @throws NullPointerException if any argument is {@code null}
204 public final @NonNull RestconfFuture<Empty> merge(final YangInstanceIdentifier path, final NormalizedNode data) {
205 final var ret = new SettableRestconfFuture<Empty>();
206 merge(ret, requireNonNull(path), requireNonNull(data));
210 private void merge(final @NonNull SettableRestconfFuture<Empty> future, final @NonNull YangInstanceIdentifier path,
211 final @NonNull NormalizedNode data) {
212 final var tx = prepareWriteExecution();
213 // FIXME: this method should be further specialized to eliminate this call -- it is only needed for MD-SAL
214 tx.ensureParentsByMerge(path);
215 tx.merge(path, data);
216 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
218 public void onSuccess(final CommitInfo result) {
219 future.set(Empty.value());
223 public void onFailure(final Throwable cause) {
224 future.setFailure(TransactionUtil.decodeException(cause, "MERGE", path, modelContext));
226 }, MoreExecutors.directExecutor());
230 * Check mount point and prepare variables for put data to DS.
232 * @param path path of data
234 * @param insert {@link Insert}
235 * @return A {@link DataPutResult}
237 public final RestconfFuture<DataPutResult> putData(final YangInstanceIdentifier path,
238 final NormalizedNode data, final @Nullable Insert insert) {
239 final var exists = TransactionUtil.syncAccess(exists(path), path);
241 final ListenableFuture<? extends CommitInfo> commitFuture;
242 if (insert != null) {
243 final var parentPath = path.coerceParent();
244 checkListAndOrderedType(parentPath);
245 commitFuture = insertAndCommitPut(path, data, insert, parentPath);
247 commitFuture = replaceAndCommit(prepareWriteExecution(), path, data);
250 final var ret = new SettableRestconfFuture<DataPutResult>();
252 Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
254 public void onSuccess(final CommitInfo result) {
255 ret.set(exists ? DataPutResult.REPLACED : DataPutResult.CREATED);
259 public void onFailure(final Throwable cause) {
260 ret.setFailure(TransactionUtil.decodeException(cause, "PUT", path, modelContext));
262 }, MoreExecutors.directExecutor());
267 private ListenableFuture<? extends CommitInfo> insertAndCommitPut(final YangInstanceIdentifier path,
268 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parentPath) {
269 final var tx = prepareWriteExecution();
271 return switch (insert.insert()) {
273 final var readData = tx.readList(parentPath);
274 if (readData == null || readData.isEmpty()) {
275 yield replaceAndCommit(tx, path, data);
277 tx.remove(parentPath);
278 tx.replace(path, data);
279 tx.replace(parentPath, readData);
282 case LAST -> replaceAndCommit(tx, path, data);
284 final var readData = tx.readList(parentPath);
285 if (readData == null || readData.isEmpty()) {
286 yield replaceAndCommit(tx, path, data);
288 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
292 final var readData = tx.readList(parentPath);
293 if (readData == null || readData.isEmpty()) {
294 yield replaceAndCommit(tx, path, data);
296 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
302 private void insertWithPointPut(final RestconfTransaction tx, final YangInstanceIdentifier path,
303 final NormalizedNode data, final @NonNull PathArgument pointArg, final NormalizedNodeContainer<?> readList,
304 final boolean before) {
305 tx.remove(path.getParent());
307 int lastItemPosition = 0;
308 for (var nodeChild : readList.body()) {
309 if (nodeChild.name().equals(pointArg)) {
318 int lastInsertedPosition = 0;
319 final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext, path.getParent());
320 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
321 for (var nodeChild : readList.body()) {
322 if (lastInsertedPosition == lastItemPosition) {
323 tx.replace(path, data);
325 final var childPath = path.coerceParent().node(nodeChild.name());
326 tx.replace(childPath, nodeChild);
327 lastInsertedPosition++;
331 private static ListenableFuture<? extends CommitInfo> replaceAndCommit(final RestconfTransaction tx,
332 final YangInstanceIdentifier path, final NormalizedNode data) {
333 tx.replace(path, data);
337 private DataSchemaNode checkListAndOrderedType(final YangInstanceIdentifier path) {
338 // FIXME: we have this available in InstanceIdentifierContext
339 final var dataSchemaNode = DataSchemaContextTree.from(modelContext).findChild(path).orElseThrow()
342 final String message;
343 if (dataSchemaNode instanceof ListSchemaNode listSchema) {
344 if (listSchema.isUserOrdered()) {
347 message = "Insert parameter can be used only with ordered-by user list.";
348 } else if (dataSchemaNode instanceof LeafListSchemaNode leafListSchema) {
349 if (leafListSchema.isUserOrdered()) {
350 return leafListSchema;
352 message = "Insert parameter can be used only with ordered-by user leaf-list.";
354 message = "Insert parameter can be used only with list or leaf-list";
356 throw new RestconfDocumentedException(message, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
360 * Check mount point and prepare variables for post data.
364 * @param insert {@link Insert}
365 * @return A {@link RestconfFuture}
367 public final RestconfFuture<Empty> postData(final YangInstanceIdentifier path, final NormalizedNode data,
368 final @Nullable Insert insert) {
369 final ListenableFuture<? extends CommitInfo> future;
370 if (insert != null) {
371 final var parentPath = path.coerceParent();
372 checkListAndOrderedType(parentPath);
373 future = insertAndCommitPost(path, data, insert, parentPath);
375 future = createAndCommit(prepareWriteExecution(), path, data);
377 final var ret = new SettableRestconfFuture<Empty>();
379 Futures.addCallback(future, new FutureCallback<CommitInfo>() {
381 public void onSuccess(final CommitInfo result) {
382 ret.set(Empty.value());
386 public void onFailure(final Throwable cause) {
387 ret.setFailure(TransactionUtil.decodeException(cause, "POST", path, modelContext));
389 }, MoreExecutors.directExecutor());
394 private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
395 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parent) {
396 final var grandParent = parent.coerceParent();
397 final var tx = prepareWriteExecution();
399 return switch (insert.insert()) {
401 final var readData = tx.readList(grandParent);
402 if (readData == null || readData.isEmpty()) {
403 tx.replace(path, data);
405 checkItemDoesNotExists(exists(path), path);
406 tx.remove(grandParent);
407 tx.replace(path, data);
408 tx.replace(grandParent, readData);
412 case LAST -> createAndCommit(tx, path, data);
414 final var readData = tx.readList(grandParent);
415 if (readData == null || readData.isEmpty()) {
416 tx.replace(path, data);
418 checkItemDoesNotExists(exists(path), path);
419 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, true);
424 final var readData = tx.readList(grandParent);
425 if (readData == null || readData.isEmpty()) {
426 tx.replace(path, data);
428 checkItemDoesNotExists(exists(path), path);
429 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, false);
437 * Process edit operations of one {@link PatchContext}.
439 * @param patch Patch context to be processed
440 * @return {@link PatchStatusContext}
442 public final @NonNull RestconfFuture<PatchStatusContext> patchData(final PatchContext patch) {
443 final var editCollection = new ArrayList<PatchStatusEntity>();
444 final var tx = prepareWriteExecution();
446 boolean noError = true;
447 for (var patchEntity : patch.entities()) {
449 final var targetNode = patchEntity.getTargetNode();
450 final var editId = patchEntity.getEditId();
452 switch (patchEntity.getOperation()) {
455 tx.create(targetNode, patchEntity.getNode());
456 editCollection.add(new PatchStatusEntity(editId, true, null));
457 } catch (RestconfDocumentedException e) {
458 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
464 tx.delete(targetNode);
465 editCollection.add(new PatchStatusEntity(editId, true, null));
466 } catch (RestconfDocumentedException e) {
467 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
473 tx.ensureParentsByMerge(targetNode);
474 tx.merge(targetNode, patchEntity.getNode());
475 editCollection.add(new PatchStatusEntity(editId, true, null));
476 } catch (RestconfDocumentedException e) {
477 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
483 tx.replace(targetNode, patchEntity.getNode());
484 editCollection.add(new PatchStatusEntity(editId, true, null));
485 } catch (RestconfDocumentedException e) {
486 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
492 tx.remove(targetNode);
493 editCollection.add(new PatchStatusEntity(editId, true, null));
494 } catch (RestconfDocumentedException e) {
495 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
500 editCollection.add(new PatchStatusEntity(editId, false, List.of(
501 new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
502 "Not supported Yang Patch operation"))));
511 final var ret = new SettableRestconfFuture<PatchStatusContext>();
515 ret.set(new PatchStatusContext(modelContext, patch.patchId(), List.copyOf(editCollection), false, null));
519 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
521 public void onSuccess(final CommitInfo result) {
522 ret.set(new PatchStatusContext(modelContext, patch.patchId(), List.copyOf(editCollection), true, null));
526 public void onFailure(final Throwable cause) {
527 // if errors occurred during transaction commit then patch failed and global errors are reported
528 ret.set(new PatchStatusContext(modelContext, patch.patchId(), List.copyOf(editCollection), false,
529 TransactionUtil.decodeException(cause, "PATCH", null, modelContext).getErrors()));
531 }, MoreExecutors.directExecutor());
536 private void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
537 final NormalizedNode data, final PathArgument pointArg, final NormalizedNodeContainer<?> readList,
538 final YangInstanceIdentifier grandParentPath, final boolean before) {
539 tx.remove(grandParentPath);
541 int lastItemPosition = 0;
542 for (var nodeChild : readList.body()) {
543 if (nodeChild.name().equals(pointArg)) {
552 int lastInsertedPosition = 0;
553 final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext, grandParentPath);
554 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
555 for (var nodeChild : readList.body()) {
556 if (lastInsertedPosition == lastItemPosition) {
557 tx.replace(path, data);
559 tx.replace(grandParentPath.node(nodeChild.name()), nodeChild);
560 lastInsertedPosition++;
564 private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
565 final YangInstanceIdentifier path, final NormalizedNode data) {
567 tx.create(path, data);
568 } catch (RestconfDocumentedException e) {
569 // close transaction if any and pass exception further
578 * Check if items do NOT already exists at specified {@code path}.
580 * @param existsFuture if checked data exists
581 * @param path Path to be checked
582 * @throws RestconfDocumentedException if data already exists.
584 static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
585 final YangInstanceIdentifier path) {
586 if (TransactionUtil.syncAccess(existsFuture, path)) {
587 LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
588 throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
594 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
595 * inside of object {@link RestconfStrategy} provided as a parameter.
597 * @param content type of data to read (config, state, all)
598 * @param path the path to read
599 * @param defaultsMode value of with-defaults parameter
600 * @return {@link NormalizedNode}
602 // FIXME: NETCONF-1155: this method should asynchronous
603 public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
604 final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
605 return switch (content) {
607 // PREPARE STATE DATA NODE
608 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
609 // PREPARE CONFIG DATA NODE
610 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
612 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
613 : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
616 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
617 yield defaultsMode == null ? read
618 : prepareDataByParamWithDef(read, path, defaultsMode.mode());
620 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
625 * Read specific type of data from data store via transaction with specified subtrees that should only be read.
626 * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
628 * @param content type of data to read (config, state, all)
629 * @param path the parent path to read
630 * @param withDefa value of with-defaults parameter
631 * @param fields paths to selected subtrees which should be read, relative to to the parent path
632 * @return {@link NormalizedNode}
634 // FIXME: NETCONF-1155: this method should asynchronous
635 public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
636 final @NonNull YangInstanceIdentifier path, final @Nullable WithDefaultsParam withDefa,
637 final @NonNull List<YangInstanceIdentifier> fields) {
638 return switch (content) {
640 // PREPARE STATE DATA NODE
641 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
642 // PREPARE CONFIG DATA NODE
643 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
645 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, withDefa == null ? configDataNode
646 : prepareDataByParamWithDef(configDataNode, path, withDefa.mode()));
649 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
650 yield withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa.mode());
652 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
656 private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
657 final YangInstanceIdentifier path) {
658 return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
662 * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
663 * specified subtrees that should only be read.
665 * @param store datastore type
666 * @param path parent path to selected fields
667 * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
668 * in {@link RestconfStrategy} if any
669 * @param fields paths to selected subtrees which should be read, relative to to the parent path
670 * @return {@link NormalizedNode}
672 private @Nullable NormalizedNode readDataViaTransaction(final @NonNull LogicalDatastoreType store,
673 final @NonNull YangInstanceIdentifier path, final @NonNull List<YangInstanceIdentifier> fields) {
674 return TransactionUtil.syncAccess(read(store, path, fields), path).orElse(null);
677 private NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
678 final WithDefaultsMode defaultsMode) {
679 final boolean trim = switch (defaultsMode) {
681 case Explicit -> false;
682 case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
683 "Unsupported with-defaults value " + defaultsMode.getName());
686 // FIXME: we have this readily available in InstanceIdentifierContext
687 final var ctxNode = DataSchemaContextTree.from(modelContext).findChild(path).orElseThrow();
688 if (readData instanceof ContainerNode container) {
689 final var builder = Builders.containerBuilder().withNodeIdentifier(container.name());
690 buildCont(builder, container.body(), ctxNode, trim);
691 return builder.build();
692 } else if (readData instanceof MapEntryNode mapEntry) {
693 if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
694 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
697 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(mapEntry.name());
698 buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
699 return builder.build();
701 throw new IllegalStateException("Unhandled data contract " + readData.contract());
705 private static void buildMapEntryBuilder(
706 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
707 final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
708 final boolean trim, final List<QName> keys) {
709 for (var child : children) {
710 final var childCtx = getChildContext(ctxNode, child);
712 if (child instanceof ContainerNode container) {
713 appendContainer(builder, container, childCtx, trim);
714 } else if (child instanceof MapNode map) {
715 appendMap(builder, map, childCtx, trim);
716 } else if (child instanceof LeafNode<?> leaf) {
717 appendLeaf(builder, leaf, childCtx, trim, keys);
719 // FIXME: we should never hit this, throw an ISE if this ever happens
720 LOG.debug("Ignoring unhandled child contract {}", child.contract());
725 private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
726 final DataSchemaContext ctxNode, final boolean trim) {
727 final var childBuilder = Builders.containerBuilder().withNodeIdentifier(container.name());
728 buildCont(childBuilder, container.body(), ctxNode, trim);
729 builder.withChild(childBuilder.build());
732 private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
733 final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
734 if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
735 throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
738 // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
739 final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
741 // This is a combined check for when we need to emit the leaf.
743 // We always have to emit key leaf values
744 keys.contains(leafSchema.getQName())
745 // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
747 // When data is retrieved with a <with-defaults> parameter equal to
748 // 'trim', data nodes MUST NOT be reported if they contain the schema
749 // default value. Non-configuration data nodes containing the schema
750 // default value MUST NOT be reported.
752 || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
753 // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
754 // grasp what we are doing here... emit only if it matches default ???!!!
755 // FIXME: The WithDefaultsParam.EXPLICIT says:
757 // Data nodes set to the YANG default by the client are reported.
759 // and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
761 // If the "with-defaults" parameter is set to "explicit", then the
762 // server MUST adhere to the default-reporting behavior defined in
763 // Section 3.3 of [RFC6243].
765 // and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
767 // When data is retrieved with a <with-defaults> parameter equal to
768 // 'explicit', a data node that was set by a client to its schema
769 // default value MUST be reported. A conceptual data node that would be
770 // set by the server to the schema default value MUST NOT be reported.
771 // Non-configuration data nodes containing the schema default value MUST
774 // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
775 // This seems to disregard the 'trim = true' case semantics (see above).
776 // Combining the above, though, these checks are missing the 'non-config' check, which would
777 // distinguish, but barring that this check is superfluous and results in the wrong semantics.
778 // Without that input, this really should be covered by the previous case.
779 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
780 builder.withChild(leaf);
784 private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
785 final DataSchemaContext childCtx, final boolean trim) {
786 if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
787 throw new IllegalStateException("Input " + map + " does not match " + childCtx);
790 final var childBuilder = switch (map.ordering()) {
791 case SYSTEM -> Builders.mapBuilder();
792 case USER -> Builders.orderedMapBuilder();
794 buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
795 listSchema.getKeyDefinition());
796 builder.withChild(childBuilder.build());
799 private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
800 final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
801 final List<@NonNull QName> keys) {
802 for (var entry : entries) {
803 final var childCtx = getChildContext(ctxNode, entry);
804 final var mapEntryBuilder = Builders.mapEntryBuilder().withNodeIdentifier(entry.name());
805 buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
806 builder.withChild(mapEntryBuilder.build());
810 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
811 final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
812 for (var child : children) {
813 final var childCtx = getChildContext(ctxNode, child);
814 if (child instanceof ContainerNode container) {
815 appendContainer(builder, container, childCtx, trim);
816 } else if (child instanceof MapNode map) {
817 appendMap(builder, map, childCtx, trim);
818 } else if (child instanceof LeafNode<?> leaf) {
819 appendLeaf(builder, leaf, childCtx, trim, List.of());
824 private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
825 final NormalizedNode child) {
826 final var childId = child.name();
827 final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
829 if (childCtx == null) {
830 throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
835 private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
836 final NormalizedNode configDataNode) {
838 if (stateDataNode == null && configDataNode == null) {
842 // return config data
843 if (stateDataNode == null) {
844 return configDataNode;
848 if (configDataNode == null) {
849 return stateDataNode;
852 // merge data from config and state
853 return mergeStateAndConfigData(stateDataNode, configDataNode);
857 * Merge state and config data into a single NormalizedNode.
859 * @param stateDataNode data node of state data
860 * @param configDataNode data node of config data
861 * @return {@link NormalizedNode}
863 private static @NonNull NormalizedNode mergeStateAndConfigData(
864 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
865 validateNodeMerge(stateDataNode, configDataNode);
866 // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
867 if (configDataNode instanceof RpcDefinition) {
868 return prepareRpcData(configDataNode, stateDataNode);
870 return prepareData(configDataNode, stateDataNode);
875 * Validates whether the two NormalizedNodes can be merged.
877 * @param stateDataNode data node of state data
878 * @param configDataNode data node of config data
880 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
881 final @NonNull NormalizedNode configDataNode) {
882 final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
883 final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
884 if (!moduleOfStateData.equals(moduleOfConfigData)) {
885 throw new RestconfDocumentedException("Unable to merge data from different modules.");
890 * Prepare and map data for rpc.
892 * @param configDataNode data node of config data
893 * @param stateDataNode data node of state data
894 * @return {@link NormalizedNode}
896 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
897 final @NonNull NormalizedNode stateDataNode) {
898 final var mapEntryBuilder = Builders.mapEntryBuilder()
899 .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
902 mapRpcDataNode(configDataNode, mapEntryBuilder);
904 mapRpcDataNode(stateDataNode, mapEntryBuilder);
906 return Builders.mapBuilder()
907 .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
908 .addChild(mapEntryBuilder.build())
913 * Map node to map entry builder.
915 * @param dataNode data node
916 * @param mapEntryBuilder builder for mapping data
918 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
919 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
920 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
924 * Prepare and map all data from DS.
926 * @param configDataNode data node of config data
927 * @param stateDataNode data node of state data
928 * @return {@link NormalizedNode}
930 @SuppressWarnings("unchecked")
931 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
932 final @NonNull NormalizedNode stateDataNode) {
933 if (configDataNode instanceof UserMapNode configMap) {
934 final var builder = Builders.orderedMapBuilder().withNodeIdentifier(configMap.name());
935 mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
936 return builder.build();
937 } else if (configDataNode instanceof SystemMapNode configMap) {
938 final var builder = Builders.mapBuilder().withNodeIdentifier(configMap.name());
939 mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
940 return builder.build();
941 } else if (configDataNode instanceof MapEntryNode configEntry) {
942 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(configEntry.name());
943 mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
944 return builder.build();
945 } else if (configDataNode instanceof ContainerNode configContaienr) {
946 final var builder = Builders.containerBuilder().withNodeIdentifier(configContaienr.name());
947 mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
948 return builder.build();
949 } else if (configDataNode instanceof ChoiceNode configChoice) {
950 final var builder = Builders.choiceBuilder().withNodeIdentifier(configChoice.name());
951 mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
952 return builder.build();
953 } else if (configDataNode instanceof LeafNode configLeaf) {
954 // config trumps oper
956 } else if (configDataNode instanceof UserLeafSetNode) {
957 final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
958 final var builder = Builders.<Object>orderedLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
959 mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
960 return builder.build();
961 } else if (configDataNode instanceof SystemLeafSetNode) {
962 final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
963 final var builder = Builders.<Object>leafSetBuilder().withNodeIdentifier(configLeafSet.name());
964 mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
965 return builder.build();
966 } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
967 // config trumps oper
969 } else if (configDataNode instanceof UnkeyedListNode configList) {
970 final var builder = Builders.unkeyedListBuilder().withNodeIdentifier(configList.name());
971 mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
972 return builder.build();
973 } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
974 final var builder = Builders.unkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
975 mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
976 return builder.build();
978 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
983 * Map value from container node to builder.
985 * @param configData collection of config data nodes
986 * @param stateData collection of state data nodes
987 * @param builder builder
989 private static <T extends NormalizedNode> void mapValueToBuilder(
990 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
991 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
992 final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
993 final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
995 // merge config and state data of children with different identifiers
996 mapDataToBuilder(configMap, stateMap, builder);
998 // merge config and state data of children with the same identifiers
999 mergeDataToBuilder(configMap, stateMap, builder);
1003 * Map data with different identifiers to builder. Data with different identifiers can be just added
1004 * as childs to parent node.
1006 * @param configMap map of config data nodes
1007 * @param stateMap map of state data nodes
1008 * @param builder - builder
1010 private static <T extends NormalizedNode> void mapDataToBuilder(
1011 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1012 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1013 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
1014 y -> builder.addChild(y.getValue()));
1015 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
1016 y -> builder.addChild(y.getValue()));
1020 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
1021 * go one level down with {@code prepareData} method.
1023 * @param configMap immutable config data
1024 * @param stateMap immutable state data
1025 * @param builder - builder
1027 @SuppressWarnings("unchecked")
1028 private static <T extends NormalizedNode> void mergeDataToBuilder(
1029 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1030 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1031 // it is enough to process only config data because operational contains the same data
1032 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1033 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1036 public @NonNull RestconfFuture<OperationOutput> invokeRpc(final URI restconfURI, final QName type,
1037 final OperationInput input) {
1038 final var local = localRpcs.get(type);
1039 if (local != null) {
1040 return local.invoke(restconfURI, input);
1042 if (rpcService == null) {
1043 LOG.debug("RPC invocation is not available");
1044 return RestconfFuture.failed(new RestconfDocumentedException("RPC invocation is not available",
1045 ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED));
1048 final var ret = new SettableRestconfFuture<OperationOutput>();
1049 Futures.addCallback(rpcService.invokeRpc(requireNonNull(type), input.input()),
1050 new FutureCallback<DOMRpcResult>() {
1052 public void onSuccess(final DOMRpcResult response) {
1053 final var errors = response.errors();
1054 if (errors.isEmpty()) {
1055 ret.set(input.newOperationOutput(response.value()));
1057 LOG.debug("RPC invocation reported {}", response.errors());
1058 ret.setFailure(new RestconfDocumentedException("RPC implementation reported errors", null,
1059 response.errors()));
1064 public void onFailure(final Throwable cause) {
1065 LOG.debug("RPC invocation failed, cause");
1066 if (cause instanceof RestconfDocumentedException ex) {
1069 // TODO: YangNetconfErrorAware if we ever get into a broader invocation scope
1070 ret.setFailure(new RestconfDocumentedException(cause,
1071 new RestconfError(ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage())));
1074 }, MoreExecutors.directExecutor());