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.io.CharSource;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.Futures;
17 import com.google.common.util.concurrent.ListenableFuture;
18 import com.google.common.util.concurrent.MoreExecutors;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.List;
24 import java.util.NoSuchElementException;
25 import java.util.Optional;
26 import java.util.function.BiFunction;
27 import java.util.function.Function;
28 import java.util.stream.Collectors;
29 import org.eclipse.jdt.annotation.NonNull;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.opendaylight.mdsal.common.api.CommitInfo;
32 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
33 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
34 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
35 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
36 import org.opendaylight.mdsal.dom.api.DOMRpcService;
37 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
38 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
39 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
40 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
41 import org.opendaylight.restconf.api.query.ContentParam;
42 import org.opendaylight.restconf.api.query.WithDefaultsParam;
43 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
44 import org.opendaylight.restconf.common.errors.RestconfError;
45 import org.opendaylight.restconf.common.errors.RestconfFuture;
46 import org.opendaylight.restconf.common.errors.SettableRestconfFuture;
47 import org.opendaylight.restconf.common.patch.PatchContext;
48 import org.opendaylight.restconf.common.patch.PatchStatusContext;
49 import org.opendaylight.restconf.common.patch.PatchStatusEntity;
50 import org.opendaylight.restconf.nb.rfc8040.Insert;
51 import org.opendaylight.restconf.nb.rfc8040.utils.parser.YangInstanceIdentifierSerializer;
52 import org.opendaylight.restconf.server.api.DataPostResult.CreateResource;
53 import org.opendaylight.restconf.server.api.DataPutResult;
54 import org.opendaylight.restconf.server.api.DatabindContext;
55 import org.opendaylight.restconf.server.api.OperationsPostResult;
56 import org.opendaylight.restconf.server.spi.OperationInput;
57 import org.opendaylight.restconf.server.spi.RpcImplementation;
58 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.with.defaults.rev110601.WithDefaultsMode;
59 import org.opendaylight.yangtools.yang.common.Empty;
60 import org.opendaylight.yangtools.yang.common.ErrorTag;
61 import org.opendaylight.yangtools.yang.common.ErrorType;
62 import org.opendaylight.yangtools.yang.common.QName;
63 import org.opendaylight.yangtools.yang.common.QNameModule;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
68 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
71 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
75 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
76 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
77 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
78 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
79 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
80 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
81 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
82 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
83 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
84 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
85 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
86 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
87 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
88 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
89 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
91 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
92 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
94 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
95 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
96 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleEffectiveStatement;
97 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
98 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
99 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
100 import org.opendaylight.yangtools.yang.model.repo.api.YinTextSchemaSource;
101 import org.slf4j.Logger;
102 import org.slf4j.LoggerFactory;
105 * Baseline execution strategy for various RESTCONF operations.
107 * @see NetconfRestconfStrategy
108 * @see MdsalRestconfStrategy
110 // FIXME: it seems the first three operations deal with lifecycle of a transaction, while others invoke various
111 // operations. This should be handled through proper allocation indirection.
112 public abstract class RestconfStrategy {
113 private static final Logger LOG = LoggerFactory.getLogger(RestconfStrategy.class);
115 private final @NonNull DatabindContext databind;
116 private final @NonNull ImmutableMap<QName, RpcImplementation> localRpcs;
117 private final DOMYangTextSourceProvider sourceProvider;
118 private final DOMRpcService rpcService;
120 RestconfStrategy(final DatabindContext databind, final ImmutableMap<QName, RpcImplementation> localRpcs,
121 final @Nullable DOMRpcService rpcService, final DOMYangTextSourceProvider sourceProvider) {
122 this.databind = requireNonNull(databind);
123 this.localRpcs = requireNonNull(localRpcs);
124 this.rpcService = rpcService;
125 this.sourceProvider = sourceProvider;
129 * Look up the appropriate strategy for a particular mount point.
131 * @param databind {@link DatabindContext} of target mount point
132 * @param mountPoint Target mount point
133 * @return A strategy, or null if the mount point does not expose a supported interface
134 * @throws NullPointerException if any argument is {@code null}
136 public static @Nullable RestconfStrategy forMountPoint(final DatabindContext databind,
137 final DOMMountPoint mountPoint) {
138 final var rpcService = mountPoint.getService(DOMRpcService.class).orElse(null);
139 final var sourceProvider = mountPoint.getService(DOMSchemaService.class)
140 .flatMap(schema -> Optional.ofNullable(schema.getExtensions().getInstance(DOMYangTextSourceProvider.class)))
143 final var netconfService = mountPoint.getService(NetconfDataTreeService.class);
144 if (netconfService.isPresent()) {
145 return new NetconfRestconfStrategy(databind, netconfService.orElseThrow(), rpcService, sourceProvider);
147 final var dataBroker = mountPoint.getService(DOMDataBroker.class);
148 if (dataBroker.isPresent()) {
149 return new MdsalRestconfStrategy(databind, dataBroker.orElseThrow(), rpcService, sourceProvider);
154 public final @NonNull DatabindContext databind() {
158 public final @NonNull EffectiveModelContext modelContext() {
159 return databind.modelContext();
163 * Lock the entire datastore.
165 * @return A {@link RestconfTransaction}. This transaction needs to be either committed or canceled before doing
168 abstract RestconfTransaction prepareWriteExecution();
171 * Read data from the datastore.
173 * @param store the logical data store which should be modified
174 * @param path the data object path
175 * @return a ListenableFuture containing the result of the read
177 abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path);
180 * Read data selected using fields from the datastore.
182 * @param store the logical data store which should be modified
183 * @param path the parent data object path
184 * @param fields paths to selected fields relative to parent path
185 * @return a ListenableFuture containing the result of the read
187 abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path,
188 List<YangInstanceIdentifier> fields);
191 * Check if data already exists in the configuration datastore.
193 * @param path the data object path
194 * @return a ListenableFuture containing the result of the check
196 // FIXME: this method should be hosted in RestconfTransaction
197 // FIXME: this method should only be needed in MdsalRestconfStrategy
198 abstract ListenableFuture<Boolean> exists(YangInstanceIdentifier path);
201 * Delete data from the configuration datastore. If the data does not exist, this operation will fail, as outlined
202 * in <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.7">RFC8040 section 4.7</a>
204 * @param path Path to delete
205 * @return A {@link RestconfFuture}
206 * @throws NullPointerException if {@code path} is {@code null}
208 public final @NonNull RestconfFuture<Empty> delete(final YangInstanceIdentifier path) {
209 final var ret = new SettableRestconfFuture<Empty>();
210 delete(ret, requireNonNull(path));
214 abstract void delete(@NonNull SettableRestconfFuture<Empty> future, @NonNull YangInstanceIdentifier path);
217 * Merge data into the configuration datastore, as outlined in
218 * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040 section 4.6.1</a>.
220 * @param path Path to merge
221 * @param data Data to merge
222 * @return A {@link RestconfFuture}
223 * @throws NullPointerException if any argument is {@code null}
225 public final @NonNull RestconfFuture<Empty> merge(final YangInstanceIdentifier path, final NormalizedNode data) {
226 final var ret = new SettableRestconfFuture<Empty>();
227 merge(ret, requireNonNull(path), requireNonNull(data));
231 private void merge(final @NonNull SettableRestconfFuture<Empty> future, final @NonNull YangInstanceIdentifier path,
232 final @NonNull NormalizedNode data) {
233 final var tx = prepareWriteExecution();
234 // FIXME: this method should be further specialized to eliminate this call -- it is only needed for MD-SAL
235 tx.ensureParentsByMerge(path);
236 tx.merge(path, data);
237 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
239 public void onSuccess(final CommitInfo result) {
240 future.set(Empty.value());
244 public void onFailure(final Throwable cause) {
245 future.setFailure(TransactionUtil.decodeException(cause, "MERGE", path, modelContext()));
247 }, MoreExecutors.directExecutor());
251 * Check mount point and prepare variables for put data to DS.
253 * @param path path of data
255 * @param insert {@link Insert}
256 * @return A {@link DataPutResult}
258 public final RestconfFuture<DataPutResult> putData(final YangInstanceIdentifier path,
259 final NormalizedNode data, final @Nullable Insert insert) {
260 final var exists = TransactionUtil.syncAccess(exists(path), path);
262 final ListenableFuture<? extends CommitInfo> commitFuture;
263 if (insert != null) {
264 final var parentPath = path.coerceParent();
265 checkListAndOrderedType(parentPath);
266 commitFuture = insertAndCommitPut(path, data, insert, parentPath);
268 commitFuture = replaceAndCommit(prepareWriteExecution(), path, data);
271 final var ret = new SettableRestconfFuture<DataPutResult>();
273 Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
275 public void onSuccess(final CommitInfo result) {
276 ret.set(exists ? DataPutResult.REPLACED : DataPutResult.CREATED);
280 public void onFailure(final Throwable cause) {
281 ret.setFailure(TransactionUtil.decodeException(cause, "PUT", path, modelContext()));
283 }, MoreExecutors.directExecutor());
288 private ListenableFuture<? extends CommitInfo> insertAndCommitPut(final YangInstanceIdentifier path,
289 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parentPath) {
290 final var tx = prepareWriteExecution();
292 return switch (insert.insert()) {
294 final var readData = tx.readList(parentPath);
295 if (readData == null || readData.isEmpty()) {
296 yield replaceAndCommit(tx, path, data);
298 tx.remove(parentPath);
299 tx.replace(path, data);
300 tx.replace(parentPath, readData);
303 case LAST -> replaceAndCommit(tx, path, data);
305 final var readData = tx.readList(parentPath);
306 if (readData == null || readData.isEmpty()) {
307 yield replaceAndCommit(tx, path, data);
309 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
313 final var readData = tx.readList(parentPath);
314 if (readData == null || readData.isEmpty()) {
315 yield replaceAndCommit(tx, path, data);
317 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
323 private void insertWithPointPut(final RestconfTransaction tx, final YangInstanceIdentifier path,
324 final NormalizedNode data, final @NonNull PathArgument pointArg, final NormalizedNodeContainer<?> readList,
325 final boolean before) {
326 tx.remove(path.getParent());
328 int lastItemPosition = 0;
329 for (var nodeChild : readList.body()) {
330 if (nodeChild.name().equals(pointArg)) {
339 int lastInsertedPosition = 0;
340 final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext(), path.getParent());
341 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
342 for (var nodeChild : readList.body()) {
343 if (lastInsertedPosition == lastItemPosition) {
344 tx.replace(path, data);
346 final var childPath = path.coerceParent().node(nodeChild.name());
347 tx.replace(childPath, nodeChild);
348 lastInsertedPosition++;
352 private static ListenableFuture<? extends CommitInfo> replaceAndCommit(final RestconfTransaction tx,
353 final YangInstanceIdentifier path, final NormalizedNode data) {
354 tx.replace(path, data);
358 private DataSchemaNode checkListAndOrderedType(final YangInstanceIdentifier path) {
359 // FIXME: we have this available in InstanceIdentifierContext
360 final var dataSchemaNode = databind.schemaTree().findChild(path).orElseThrow().dataSchemaNode();
362 final String message;
363 if (dataSchemaNode instanceof ListSchemaNode listSchema) {
364 if (listSchema.isUserOrdered()) {
367 message = "Insert parameter can be used only with ordered-by user list.";
368 } else if (dataSchemaNode instanceof LeafListSchemaNode leafListSchema) {
369 if (leafListSchema.isUserOrdered()) {
370 return leafListSchema;
372 message = "Insert parameter can be used only with ordered-by user leaf-list.";
374 message = "Insert parameter can be used only with list or leaf-list";
376 throw new RestconfDocumentedException(message, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
380 * Check mount point and prepare variables for post data.
384 * @param insert {@link Insert}
385 * @return A {@link RestconfFuture}
387 public final @NonNull RestconfFuture<CreateResource> postData(final YangInstanceIdentifier path,
388 final NormalizedNode data, final @Nullable Insert insert) {
389 final ListenableFuture<? extends CommitInfo> future;
390 if (insert != null) {
391 final var parentPath = path.coerceParent();
392 checkListAndOrderedType(parentPath);
393 future = insertAndCommitPost(path, data, insert, parentPath);
395 future = createAndCommit(prepareWriteExecution(), path, data);
398 final var ret = new SettableRestconfFuture<CreateResource>();
399 Futures.addCallback(future, new FutureCallback<CommitInfo>() {
401 public void onSuccess(final CommitInfo result) {
402 ret.set(new CreateResource(new YangInstanceIdentifierSerializer(databind).serializePath(
403 data instanceof MapNode mapData && !mapData.isEmpty()
404 ? path.node(mapData.body().iterator().next().name()) : path)));
408 public void onFailure(final Throwable cause) {
409 ret.setFailure(TransactionUtil.decodeException(cause, "POST", path, modelContext()));
412 }, MoreExecutors.directExecutor());
416 private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
417 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parent) {
418 final var grandParent = parent.coerceParent();
419 final var tx = prepareWriteExecution();
421 return switch (insert.insert()) {
423 final var readData = tx.readList(grandParent);
424 if (readData == null || readData.isEmpty()) {
425 tx.replace(path, data);
427 checkItemDoesNotExists(exists(path), path);
428 tx.remove(grandParent);
429 tx.replace(path, data);
430 tx.replace(grandParent, readData);
434 case LAST -> createAndCommit(tx, path, data);
436 final var readData = tx.readList(grandParent);
437 if (readData == null || readData.isEmpty()) {
438 tx.replace(path, data);
440 checkItemDoesNotExists(exists(path), path);
441 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, true);
446 final var readData = tx.readList(grandParent);
447 if (readData == null || readData.isEmpty()) {
448 tx.replace(path, data);
450 checkItemDoesNotExists(exists(path), path);
451 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, false);
459 * Process edit operations of one {@link PatchContext}.
461 * @param patch Patch context to be processed
462 * @return {@link PatchStatusContext}
464 public final @NonNull RestconfFuture<PatchStatusContext> patchData(final PatchContext patch) {
465 final var editCollection = new ArrayList<PatchStatusEntity>();
466 final var tx = prepareWriteExecution();
468 boolean noError = true;
469 for (var patchEntity : patch.entities()) {
471 final var targetNode = patchEntity.getTargetNode();
472 final var editId = patchEntity.getEditId();
474 switch (patchEntity.getOperation()) {
477 tx.create(targetNode, patchEntity.getNode());
478 editCollection.add(new PatchStatusEntity(editId, true, null));
479 } catch (RestconfDocumentedException e) {
480 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
486 tx.delete(targetNode);
487 editCollection.add(new PatchStatusEntity(editId, true, null));
488 } catch (RestconfDocumentedException e) {
489 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
495 tx.ensureParentsByMerge(targetNode);
496 tx.merge(targetNode, patchEntity.getNode());
497 editCollection.add(new PatchStatusEntity(editId, true, null));
498 } catch (RestconfDocumentedException e) {
499 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
505 tx.replace(targetNode, patchEntity.getNode());
506 editCollection.add(new PatchStatusEntity(editId, true, null));
507 } catch (RestconfDocumentedException e) {
508 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
514 tx.remove(targetNode);
515 editCollection.add(new PatchStatusEntity(editId, true, null));
516 } catch (RestconfDocumentedException e) {
517 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
522 editCollection.add(new PatchStatusEntity(editId, false, List.of(
523 new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
524 "Not supported Yang Patch operation"))));
533 final var ret = new SettableRestconfFuture<PatchStatusContext>();
537 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false, null));
541 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
543 public void onSuccess(final CommitInfo result) {
544 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), true,
549 public void onFailure(final Throwable cause) {
550 // if errors occurred during transaction commit then patch failed and global errors are reported
551 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false,
552 TransactionUtil.decodeException(cause, "PATCH", null, modelContext()).getErrors()));
554 }, MoreExecutors.directExecutor());
559 private void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
560 final NormalizedNode data, final PathArgument pointArg, final NormalizedNodeContainer<?> readList,
561 final YangInstanceIdentifier grandParentPath, final boolean before) {
562 tx.remove(grandParentPath);
564 int lastItemPosition = 0;
565 for (var nodeChild : readList.body()) {
566 if (nodeChild.name().equals(pointArg)) {
575 int lastInsertedPosition = 0;
576 final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext(), grandParentPath);
577 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
578 for (var nodeChild : readList.body()) {
579 if (lastInsertedPosition == lastItemPosition) {
580 tx.replace(path, data);
582 tx.replace(grandParentPath.node(nodeChild.name()), nodeChild);
583 lastInsertedPosition++;
587 private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
588 final YangInstanceIdentifier path, final NormalizedNode data) {
590 tx.create(path, data);
591 } catch (RestconfDocumentedException e) {
592 // close transaction if any and pass exception further
601 * Check if items do NOT already exists at specified {@code path}.
603 * @param existsFuture if checked data exists
604 * @param path Path to be checked
605 * @throws RestconfDocumentedException if data already exists.
607 static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
608 final YangInstanceIdentifier path) {
609 if (TransactionUtil.syncAccess(existsFuture, path)) {
610 LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
611 throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
617 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
618 * inside of object {@link RestconfStrategy} provided as a parameter.
620 * @param content type of data to read (config, state, all)
621 * @param path the path to read
622 * @param defaultsMode value of with-defaults parameter
623 * @return {@link NormalizedNode}
625 // FIXME: NETCONF-1155: this method should asynchronous
626 public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
627 final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
628 return switch (content) {
630 // PREPARE STATE DATA NODE
631 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
632 // PREPARE CONFIG DATA NODE
633 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
635 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
636 : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
639 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
640 yield defaultsMode == null ? read
641 : prepareDataByParamWithDef(read, path, defaultsMode.mode());
643 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
648 * Read specific type of data from data store via transaction with specified subtrees that should only be read.
649 * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
651 * @param content type of data to read (config, state, all)
652 * @param path the parent path to read
653 * @param withDefa value of with-defaults parameter
654 * @param fields paths to selected subtrees which should be read, relative to to the parent path
655 * @return {@link NormalizedNode}
657 // FIXME: NETCONF-1155: this method should asynchronous
658 public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
659 final @NonNull YangInstanceIdentifier path, final @Nullable WithDefaultsParam withDefa,
660 final @NonNull List<YangInstanceIdentifier> fields) {
661 return switch (content) {
663 // PREPARE STATE DATA NODE
664 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
665 // PREPARE CONFIG DATA NODE
666 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
668 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, withDefa == null ? configDataNode
669 : prepareDataByParamWithDef(configDataNode, path, withDefa.mode()));
672 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
673 yield withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa.mode());
675 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
679 private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
680 final YangInstanceIdentifier path) {
681 return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
685 * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
686 * specified subtrees that should only be read.
688 * @param store datastore type
689 * @param path parent path to selected fields
690 * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
691 * in {@link RestconfStrategy} if any
692 * @param fields paths to selected subtrees which should be read, relative to to the parent path
693 * @return {@link NormalizedNode}
695 private @Nullable NormalizedNode readDataViaTransaction(final @NonNull LogicalDatastoreType store,
696 final @NonNull YangInstanceIdentifier path, final @NonNull List<YangInstanceIdentifier> fields) {
697 return TransactionUtil.syncAccess(read(store, path, fields), path).orElse(null);
700 private NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
701 final WithDefaultsMode defaultsMode) {
702 final boolean trim = switch (defaultsMode) {
704 case Explicit -> false;
705 case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
706 "Unsupported with-defaults value " + defaultsMode.getName());
709 // FIXME: we have this readily available in InstanceIdentifierContext
710 final var ctxNode = databind.schemaTree().findChild(path).orElseThrow();
711 if (readData instanceof ContainerNode container) {
712 final var builder = Builders.containerBuilder().withNodeIdentifier(container.name());
713 buildCont(builder, container.body(), ctxNode, trim);
714 return builder.build();
715 } else if (readData instanceof MapEntryNode mapEntry) {
716 if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
717 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
720 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(mapEntry.name());
721 buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
722 return builder.build();
724 throw new IllegalStateException("Unhandled data contract " + readData.contract());
728 private static void buildMapEntryBuilder(
729 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
730 final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
731 final boolean trim, final List<QName> keys) {
732 for (var child : children) {
733 final var childCtx = getChildContext(ctxNode, child);
735 if (child instanceof ContainerNode container) {
736 appendContainer(builder, container, childCtx, trim);
737 } else if (child instanceof MapNode map) {
738 appendMap(builder, map, childCtx, trim);
739 } else if (child instanceof LeafNode<?> leaf) {
740 appendLeaf(builder, leaf, childCtx, trim, keys);
742 // FIXME: we should never hit this, throw an ISE if this ever happens
743 LOG.debug("Ignoring unhandled child contract {}", child.contract());
748 private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
749 final DataSchemaContext ctxNode, final boolean trim) {
750 final var childBuilder = Builders.containerBuilder().withNodeIdentifier(container.name());
751 buildCont(childBuilder, container.body(), ctxNode, trim);
752 builder.withChild(childBuilder.build());
755 private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
756 final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
757 if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
758 throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
761 // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
762 final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
764 // This is a combined check for when we need to emit the leaf.
766 // We always have to emit key leaf values
767 keys.contains(leafSchema.getQName())
768 // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
770 // When data is retrieved with a <with-defaults> parameter equal to
771 // 'trim', data nodes MUST NOT be reported if they contain the schema
772 // default value. Non-configuration data nodes containing the schema
773 // default value MUST NOT be reported.
775 || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
776 // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
777 // grasp what we are doing here... emit only if it matches default ???!!!
778 // FIXME: The WithDefaultsParam.EXPLICIT says:
780 // Data nodes set to the YANG default by the client are reported.
782 // and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
784 // If the "with-defaults" parameter is set to "explicit", then the
785 // server MUST adhere to the default-reporting behavior defined in
786 // Section 3.3 of [RFC6243].
788 // and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
790 // When data is retrieved with a <with-defaults> parameter equal to
791 // 'explicit', a data node that was set by a client to its schema
792 // default value MUST be reported. A conceptual data node that would be
793 // set by the server to the schema default value MUST NOT be reported.
794 // Non-configuration data nodes containing the schema default value MUST
797 // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
798 // This seems to disregard the 'trim = true' case semantics (see above).
799 // Combining the above, though, these checks are missing the 'non-config' check, which would
800 // distinguish, but barring that this check is superfluous and results in the wrong semantics.
801 // Without that input, this really should be covered by the previous case.
802 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
803 builder.withChild(leaf);
807 private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
808 final DataSchemaContext childCtx, final boolean trim) {
809 if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
810 throw new IllegalStateException("Input " + map + " does not match " + childCtx);
813 final var childBuilder = switch (map.ordering()) {
814 case SYSTEM -> Builders.mapBuilder();
815 case USER -> Builders.orderedMapBuilder();
817 buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
818 listSchema.getKeyDefinition());
819 builder.withChild(childBuilder.build());
822 private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
823 final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
824 final List<@NonNull QName> keys) {
825 for (var entry : entries) {
826 final var childCtx = getChildContext(ctxNode, entry);
827 final var mapEntryBuilder = Builders.mapEntryBuilder().withNodeIdentifier(entry.name());
828 buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
829 builder.withChild(mapEntryBuilder.build());
833 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
834 final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
835 for (var child : children) {
836 final var childCtx = getChildContext(ctxNode, child);
837 if (child instanceof ContainerNode container) {
838 appendContainer(builder, container, childCtx, trim);
839 } else if (child instanceof MapNode map) {
840 appendMap(builder, map, childCtx, trim);
841 } else if (child instanceof LeafNode<?> leaf) {
842 appendLeaf(builder, leaf, childCtx, trim, List.of());
847 private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
848 final NormalizedNode child) {
849 final var childId = child.name();
850 final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
852 if (childCtx == null) {
853 throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
858 private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
859 final NormalizedNode configDataNode) {
861 if (stateDataNode == null && configDataNode == null) {
865 // return config data
866 if (stateDataNode == null) {
867 return configDataNode;
871 if (configDataNode == null) {
872 return stateDataNode;
875 // merge data from config and state
876 return mergeStateAndConfigData(stateDataNode, configDataNode);
880 * Merge state and config data into a single NormalizedNode.
882 * @param stateDataNode data node of state data
883 * @param configDataNode data node of config data
884 * @return {@link NormalizedNode}
886 private static @NonNull NormalizedNode mergeStateAndConfigData(
887 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
888 validateNodeMerge(stateDataNode, configDataNode);
889 // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
890 if (configDataNode instanceof RpcDefinition) {
891 return prepareRpcData(configDataNode, stateDataNode);
893 return prepareData(configDataNode, stateDataNode);
898 * Validates whether the two NormalizedNodes can be merged.
900 * @param stateDataNode data node of state data
901 * @param configDataNode data node of config data
903 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
904 final @NonNull NormalizedNode configDataNode) {
905 final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
906 final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
907 if (!moduleOfStateData.equals(moduleOfConfigData)) {
908 throw new RestconfDocumentedException("Unable to merge data from different modules.");
913 * Prepare and map data for rpc.
915 * @param configDataNode data node of config data
916 * @param stateDataNode data node of state data
917 * @return {@link NormalizedNode}
919 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
920 final @NonNull NormalizedNode stateDataNode) {
921 final var mapEntryBuilder = Builders.mapEntryBuilder()
922 .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
925 mapRpcDataNode(configDataNode, mapEntryBuilder);
927 mapRpcDataNode(stateDataNode, mapEntryBuilder);
929 return Builders.mapBuilder()
930 .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
931 .addChild(mapEntryBuilder.build())
936 * Map node to map entry builder.
938 * @param dataNode data node
939 * @param mapEntryBuilder builder for mapping data
941 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
942 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
943 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
947 * Prepare and map all data from DS.
949 * @param configDataNode data node of config data
950 * @param stateDataNode data node of state data
951 * @return {@link NormalizedNode}
953 @SuppressWarnings("unchecked")
954 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
955 final @NonNull NormalizedNode stateDataNode) {
956 if (configDataNode instanceof UserMapNode configMap) {
957 final var builder = Builders.orderedMapBuilder().withNodeIdentifier(configMap.name());
958 mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
959 return builder.build();
960 } else if (configDataNode instanceof SystemMapNode configMap) {
961 final var builder = Builders.mapBuilder().withNodeIdentifier(configMap.name());
962 mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
963 return builder.build();
964 } else if (configDataNode instanceof MapEntryNode configEntry) {
965 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(configEntry.name());
966 mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
967 return builder.build();
968 } else if (configDataNode instanceof ContainerNode configContaienr) {
969 final var builder = Builders.containerBuilder().withNodeIdentifier(configContaienr.name());
970 mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
971 return builder.build();
972 } else if (configDataNode instanceof ChoiceNode configChoice) {
973 final var builder = Builders.choiceBuilder().withNodeIdentifier(configChoice.name());
974 mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
975 return builder.build();
976 } else if (configDataNode instanceof LeafNode configLeaf) {
977 // config trumps oper
979 } else if (configDataNode instanceof UserLeafSetNode) {
980 final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
981 final var builder = Builders.<Object>orderedLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
982 mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
983 return builder.build();
984 } else if (configDataNode instanceof SystemLeafSetNode) {
985 final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
986 final var builder = Builders.<Object>leafSetBuilder().withNodeIdentifier(configLeafSet.name());
987 mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
988 return builder.build();
989 } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
990 // config trumps oper
992 } else if (configDataNode instanceof UnkeyedListNode configList) {
993 final var builder = Builders.unkeyedListBuilder().withNodeIdentifier(configList.name());
994 mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
995 return builder.build();
996 } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
997 final var builder = Builders.unkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
998 mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
999 return builder.build();
1001 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
1006 * Map value from container node to builder.
1008 * @param configData collection of config data nodes
1009 * @param stateData collection of state data nodes
1010 * @param builder builder
1012 private static <T extends NormalizedNode> void mapValueToBuilder(
1013 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
1014 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1015 final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1016 final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1018 // merge config and state data of children with different identifiers
1019 mapDataToBuilder(configMap, stateMap, builder);
1021 // merge config and state data of children with the same identifiers
1022 mergeDataToBuilder(configMap, stateMap, builder);
1026 * Map data with different identifiers to builder. Data with different identifiers can be just added
1027 * as childs to parent node.
1029 * @param configMap map of config data nodes
1030 * @param stateMap map of state data nodes
1031 * @param builder - builder
1033 private static <T extends NormalizedNode> void mapDataToBuilder(
1034 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1035 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1036 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
1037 y -> builder.addChild(y.getValue()));
1038 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
1039 y -> builder.addChild(y.getValue()));
1043 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
1044 * go one level down with {@code prepareData} method.
1046 * @param configMap immutable config data
1047 * @param stateMap immutable state data
1048 * @param builder - builder
1050 @SuppressWarnings("unchecked")
1051 private static <T extends NormalizedNode> void mergeDataToBuilder(
1052 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1053 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1054 // it is enough to process only config data because operational contains the same data
1055 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1056 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1059 public @NonNull RestconfFuture<OperationsPostResult> invokeRpc(final URI restconfURI, final QName type,
1060 final OperationInput input) {
1061 final var local = localRpcs.get(type);
1062 if (local != null) {
1063 return local.invoke(restconfURI, input);
1065 if (rpcService == null) {
1066 LOG.debug("RPC invocation is not available");
1067 return RestconfFuture.failed(new RestconfDocumentedException("RPC invocation is not available",
1068 ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED));
1071 final var ret = new SettableRestconfFuture<OperationsPostResult>();
1072 Futures.addCallback(rpcService.invokeRpc(requireNonNull(type), input.input()),
1073 new FutureCallback<DOMRpcResult>() {
1075 public void onSuccess(final DOMRpcResult response) {
1076 final var errors = response.errors();
1077 if (errors.isEmpty()) {
1078 ret.set(input.newOperationOutput(response.value()));
1080 LOG.debug("RPC invocation reported {}", response.errors());
1081 ret.setFailure(new RestconfDocumentedException("RPC implementation reported errors", null,
1082 response.errors()));
1087 public void onFailure(final Throwable cause) {
1088 LOG.debug("RPC invocation failed, cause");
1089 if (cause instanceof RestconfDocumentedException ex) {
1092 // TODO: YangNetconfErrorAware if we ever get into a broader invocation scope
1093 ret.setFailure(new RestconfDocumentedException(cause,
1094 new RestconfError(ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage())));
1097 }, MoreExecutors.directExecutor());
1101 public @NonNull RestconfFuture<CharSource> resolveSource(final SourceIdentifier source,
1102 final Class<? extends SchemaSourceRepresentation> representation) {
1103 final var src = requireNonNull(source);
1104 if (YangTextSchemaSource.class.isAssignableFrom(representation)) {
1105 if (sourceProvider != null) {
1106 final var ret = new SettableRestconfFuture<CharSource>();
1107 Futures.addCallback(sourceProvider.getSource(src), new FutureCallback<YangTextSchemaSource>() {
1109 public void onSuccess(final YangTextSchemaSource result) {
1114 public void onFailure(final Throwable cause) {
1115 ret.setFailure(cause instanceof RestconfDocumentedException e ? e
1116 : new RestconfDocumentedException(cause.getMessage(), ErrorType.RPC,
1117 ErrorTag.OPERATION_FAILED, cause));
1119 }, MoreExecutors.directExecutor());
1122 return exportSource(modelContext(), src, YangCharSource::new, YangCharSource::new);
1124 if (YinTextSchemaSource.class.isAssignableFrom(representation)) {
1125 return exportSource(modelContext(), src, YinCharSource.OfModule::new, YinCharSource.OfSubmodule::new);
1127 return RestconfFuture.failed(new RestconfDocumentedException(
1128 "Unsupported source representation " + representation.getName()));
1131 private static @NonNull RestconfFuture<CharSource> exportSource(final EffectiveModelContext modelContext,
1132 final SourceIdentifier source, final Function<ModuleEffectiveStatement, CharSource> moduleCtor,
1133 final BiFunction<ModuleEffectiveStatement, SubmoduleEffectiveStatement, CharSource> submoduleCtor) {
1134 // If the source identifies a module, things are easy
1135 final var name = source.name().getLocalName();
1136 final var optRevision = Optional.ofNullable(source.revision());
1137 final var optModule = modelContext.findModule(name, optRevision);
1138 if (optModule.isPresent()) {
1139 return RestconfFuture.of(moduleCtor.apply(optModule.orElseThrow().asEffectiveStatement()));
1142 // The source could be a submodule, which we need to hunt down
1143 for (var module : modelContext.getModules()) {
1144 for (var submodule : module.getSubmodules()) {
1145 if (name.equals(submodule.getName()) && optRevision.equals(submodule.getRevision())) {
1146 return RestconfFuture.of(submoduleCtor.apply(module.asEffectiveStatement(),
1147 submodule.asEffectiveStatement()));
1152 final var sb = new StringBuilder().append("Source ").append(source.name().getLocalName());
1153 optRevision.ifPresent(rev -> sb.append('@').append(rev));
1154 sb.append(" not found");
1155 return RestconfFuture.failed(new RestconfDocumentedException(sb.toString(),
1156 ErrorType.APPLICATION, ErrorTag.DATA_MISSING));