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.databind.DatabindContext;
52 import org.opendaylight.restconf.nb.rfc8040.utils.parser.IdentifierCodec;
53 import org.opendaylight.restconf.server.api.DataPostResult.CreateResource;
54 import org.opendaylight.restconf.server.api.DataPutResult;
55 import org.opendaylight.restconf.server.spi.OperationInput;
56 import org.opendaylight.restconf.server.spi.OperationOutput;
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(IdentifierCodec.serialize(
403 data instanceof MapNode mapData && !mapData.isEmpty()
404 ? path.node(mapData.body().iterator().next().name()) : path,
409 public void onFailure(final Throwable cause) {
410 ret.setFailure(TransactionUtil.decodeException(cause, "POST", path, modelContext()));
413 }, MoreExecutors.directExecutor());
417 private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
418 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parent) {
419 final var grandParent = parent.coerceParent();
420 final var tx = prepareWriteExecution();
422 return switch (insert.insert()) {
424 final var readData = tx.readList(grandParent);
425 if (readData == null || readData.isEmpty()) {
426 tx.replace(path, data);
428 checkItemDoesNotExists(exists(path), path);
429 tx.remove(grandParent);
430 tx.replace(path, data);
431 tx.replace(grandParent, readData);
435 case LAST -> createAndCommit(tx, path, data);
437 final var readData = tx.readList(grandParent);
438 if (readData == null || readData.isEmpty()) {
439 tx.replace(path, data);
441 checkItemDoesNotExists(exists(path), path);
442 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, true);
447 final var readData = tx.readList(grandParent);
448 if (readData == null || readData.isEmpty()) {
449 tx.replace(path, data);
451 checkItemDoesNotExists(exists(path), path);
452 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, false);
460 * Process edit operations of one {@link PatchContext}.
462 * @param patch Patch context to be processed
463 * @return {@link PatchStatusContext}
465 public final @NonNull RestconfFuture<PatchStatusContext> patchData(final PatchContext patch) {
466 final var editCollection = new ArrayList<PatchStatusEntity>();
467 final var tx = prepareWriteExecution();
469 boolean noError = true;
470 for (var patchEntity : patch.entities()) {
472 final var targetNode = patchEntity.getTargetNode();
473 final var editId = patchEntity.getEditId();
475 switch (patchEntity.getOperation()) {
478 tx.create(targetNode, patchEntity.getNode());
479 editCollection.add(new PatchStatusEntity(editId, true, null));
480 } catch (RestconfDocumentedException e) {
481 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
487 tx.delete(targetNode);
488 editCollection.add(new PatchStatusEntity(editId, true, null));
489 } catch (RestconfDocumentedException e) {
490 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
496 tx.ensureParentsByMerge(targetNode);
497 tx.merge(targetNode, patchEntity.getNode());
498 editCollection.add(new PatchStatusEntity(editId, true, null));
499 } catch (RestconfDocumentedException e) {
500 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
506 tx.replace(targetNode, patchEntity.getNode());
507 editCollection.add(new PatchStatusEntity(editId, true, null));
508 } catch (RestconfDocumentedException e) {
509 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
515 tx.remove(targetNode);
516 editCollection.add(new PatchStatusEntity(editId, true, null));
517 } catch (RestconfDocumentedException e) {
518 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
523 editCollection.add(new PatchStatusEntity(editId, false, List.of(
524 new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
525 "Not supported Yang Patch operation"))));
534 final var ret = new SettableRestconfFuture<PatchStatusContext>();
538 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false, null));
542 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
544 public void onSuccess(final CommitInfo result) {
545 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), true,
550 public void onFailure(final Throwable cause) {
551 // if errors occurred during transaction commit then patch failed and global errors are reported
552 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false,
553 TransactionUtil.decodeException(cause, "PATCH", null, modelContext()).getErrors()));
555 }, MoreExecutors.directExecutor());
560 private void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
561 final NormalizedNode data, final PathArgument pointArg, final NormalizedNodeContainer<?> readList,
562 final YangInstanceIdentifier grandParentPath, final boolean before) {
563 tx.remove(grandParentPath);
565 int lastItemPosition = 0;
566 for (var nodeChild : readList.body()) {
567 if (nodeChild.name().equals(pointArg)) {
576 int lastInsertedPosition = 0;
577 final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext(), grandParentPath);
578 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
579 for (var nodeChild : readList.body()) {
580 if (lastInsertedPosition == lastItemPosition) {
581 tx.replace(path, data);
583 tx.replace(grandParentPath.node(nodeChild.name()), nodeChild);
584 lastInsertedPosition++;
588 private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
589 final YangInstanceIdentifier path, final NormalizedNode data) {
591 tx.create(path, data);
592 } catch (RestconfDocumentedException e) {
593 // close transaction if any and pass exception further
602 * Check if items do NOT already exists at specified {@code path}.
604 * @param existsFuture if checked data exists
605 * @param path Path to be checked
606 * @throws RestconfDocumentedException if data already exists.
608 static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
609 final YangInstanceIdentifier path) {
610 if (TransactionUtil.syncAccess(existsFuture, path)) {
611 LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
612 throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
618 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
619 * inside of object {@link RestconfStrategy} provided as a parameter.
621 * @param content type of data to read (config, state, all)
622 * @param path the path to read
623 * @param defaultsMode value of with-defaults parameter
624 * @return {@link NormalizedNode}
626 // FIXME: NETCONF-1155: this method should asynchronous
627 public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
628 final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
629 return switch (content) {
631 // PREPARE STATE DATA NODE
632 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
633 // PREPARE CONFIG DATA NODE
634 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
636 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
637 : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
640 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
641 yield defaultsMode == null ? read
642 : prepareDataByParamWithDef(read, path, defaultsMode.mode());
644 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
649 * Read specific type of data from data store via transaction with specified subtrees that should only be read.
650 * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
652 * @param content type of data to read (config, state, all)
653 * @param path the parent path to read
654 * @param withDefa value of with-defaults parameter
655 * @param fields paths to selected subtrees which should be read, relative to to the parent path
656 * @return {@link NormalizedNode}
658 // FIXME: NETCONF-1155: this method should asynchronous
659 public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
660 final @NonNull YangInstanceIdentifier path, final @Nullable WithDefaultsParam withDefa,
661 final @NonNull List<YangInstanceIdentifier> fields) {
662 return switch (content) {
664 // PREPARE STATE DATA NODE
665 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
666 // PREPARE CONFIG DATA NODE
667 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
669 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, withDefa == null ? configDataNode
670 : prepareDataByParamWithDef(configDataNode, path, withDefa.mode()));
673 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
674 yield withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa.mode());
676 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
680 private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
681 final YangInstanceIdentifier path) {
682 return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
686 * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
687 * specified subtrees that should only be read.
689 * @param store datastore type
690 * @param path parent path to selected fields
691 * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
692 * in {@link RestconfStrategy} if any
693 * @param fields paths to selected subtrees which should be read, relative to to the parent path
694 * @return {@link NormalizedNode}
696 private @Nullable NormalizedNode readDataViaTransaction(final @NonNull LogicalDatastoreType store,
697 final @NonNull YangInstanceIdentifier path, final @NonNull List<YangInstanceIdentifier> fields) {
698 return TransactionUtil.syncAccess(read(store, path, fields), path).orElse(null);
701 private NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
702 final WithDefaultsMode defaultsMode) {
703 final boolean trim = switch (defaultsMode) {
705 case Explicit -> false;
706 case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
707 "Unsupported with-defaults value " + defaultsMode.getName());
710 // FIXME: we have this readily available in InstanceIdentifierContext
711 final var ctxNode = databind.schemaTree().findChild(path).orElseThrow();
712 if (readData instanceof ContainerNode container) {
713 final var builder = Builders.containerBuilder().withNodeIdentifier(container.name());
714 buildCont(builder, container.body(), ctxNode, trim);
715 return builder.build();
716 } else if (readData instanceof MapEntryNode mapEntry) {
717 if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
718 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
721 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(mapEntry.name());
722 buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
723 return builder.build();
725 throw new IllegalStateException("Unhandled data contract " + readData.contract());
729 private static void buildMapEntryBuilder(
730 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
731 final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
732 final boolean trim, final List<QName> keys) {
733 for (var child : children) {
734 final var childCtx = getChildContext(ctxNode, child);
736 if (child instanceof ContainerNode container) {
737 appendContainer(builder, container, childCtx, trim);
738 } else if (child instanceof MapNode map) {
739 appendMap(builder, map, childCtx, trim);
740 } else if (child instanceof LeafNode<?> leaf) {
741 appendLeaf(builder, leaf, childCtx, trim, keys);
743 // FIXME: we should never hit this, throw an ISE if this ever happens
744 LOG.debug("Ignoring unhandled child contract {}", child.contract());
749 private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
750 final DataSchemaContext ctxNode, final boolean trim) {
751 final var childBuilder = Builders.containerBuilder().withNodeIdentifier(container.name());
752 buildCont(childBuilder, container.body(), ctxNode, trim);
753 builder.withChild(childBuilder.build());
756 private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
757 final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
758 if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
759 throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
762 // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
763 final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
765 // This is a combined check for when we need to emit the leaf.
767 // We always have to emit key leaf values
768 keys.contains(leafSchema.getQName())
769 // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
771 // When data is retrieved with a <with-defaults> parameter equal to
772 // 'trim', data nodes MUST NOT be reported if they contain the schema
773 // default value. Non-configuration data nodes containing the schema
774 // default value MUST NOT be reported.
776 || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
777 // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
778 // grasp what we are doing here... emit only if it matches default ???!!!
779 // FIXME: The WithDefaultsParam.EXPLICIT says:
781 // Data nodes set to the YANG default by the client are reported.
783 // and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
785 // If the "with-defaults" parameter is set to "explicit", then the
786 // server MUST adhere to the default-reporting behavior defined in
787 // Section 3.3 of [RFC6243].
789 // and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
791 // When data is retrieved with a <with-defaults> parameter equal to
792 // 'explicit', a data node that was set by a client to its schema
793 // default value MUST be reported. A conceptual data node that would be
794 // set by the server to the schema default value MUST NOT be reported.
795 // Non-configuration data nodes containing the schema default value MUST
798 // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
799 // This seems to disregard the 'trim = true' case semantics (see above).
800 // Combining the above, though, these checks are missing the 'non-config' check, which would
801 // distinguish, but barring that this check is superfluous and results in the wrong semantics.
802 // Without that input, this really should be covered by the previous case.
803 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
804 builder.withChild(leaf);
808 private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
809 final DataSchemaContext childCtx, final boolean trim) {
810 if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
811 throw new IllegalStateException("Input " + map + " does not match " + childCtx);
814 final var childBuilder = switch (map.ordering()) {
815 case SYSTEM -> Builders.mapBuilder();
816 case USER -> Builders.orderedMapBuilder();
818 buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
819 listSchema.getKeyDefinition());
820 builder.withChild(childBuilder.build());
823 private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
824 final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
825 final List<@NonNull QName> keys) {
826 for (var entry : entries) {
827 final var childCtx = getChildContext(ctxNode, entry);
828 final var mapEntryBuilder = Builders.mapEntryBuilder().withNodeIdentifier(entry.name());
829 buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
830 builder.withChild(mapEntryBuilder.build());
834 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
835 final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
836 for (var child : children) {
837 final var childCtx = getChildContext(ctxNode, child);
838 if (child instanceof ContainerNode container) {
839 appendContainer(builder, container, childCtx, trim);
840 } else if (child instanceof MapNode map) {
841 appendMap(builder, map, childCtx, trim);
842 } else if (child instanceof LeafNode<?> leaf) {
843 appendLeaf(builder, leaf, childCtx, trim, List.of());
848 private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
849 final NormalizedNode child) {
850 final var childId = child.name();
851 final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
853 if (childCtx == null) {
854 throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
859 private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
860 final NormalizedNode configDataNode) {
862 if (stateDataNode == null && configDataNode == null) {
866 // return config data
867 if (stateDataNode == null) {
868 return configDataNode;
872 if (configDataNode == null) {
873 return stateDataNode;
876 // merge data from config and state
877 return mergeStateAndConfigData(stateDataNode, configDataNode);
881 * Merge state and config data into a single NormalizedNode.
883 * @param stateDataNode data node of state data
884 * @param configDataNode data node of config data
885 * @return {@link NormalizedNode}
887 private static @NonNull NormalizedNode mergeStateAndConfigData(
888 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
889 validateNodeMerge(stateDataNode, configDataNode);
890 // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
891 if (configDataNode instanceof RpcDefinition) {
892 return prepareRpcData(configDataNode, stateDataNode);
894 return prepareData(configDataNode, stateDataNode);
899 * Validates whether the two NormalizedNodes can be merged.
901 * @param stateDataNode data node of state data
902 * @param configDataNode data node of config data
904 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
905 final @NonNull NormalizedNode configDataNode) {
906 final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
907 final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
908 if (!moduleOfStateData.equals(moduleOfConfigData)) {
909 throw new RestconfDocumentedException("Unable to merge data from different modules.");
914 * Prepare and map data for rpc.
916 * @param configDataNode data node of config data
917 * @param stateDataNode data node of state data
918 * @return {@link NormalizedNode}
920 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
921 final @NonNull NormalizedNode stateDataNode) {
922 final var mapEntryBuilder = Builders.mapEntryBuilder()
923 .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
926 mapRpcDataNode(configDataNode, mapEntryBuilder);
928 mapRpcDataNode(stateDataNode, mapEntryBuilder);
930 return Builders.mapBuilder()
931 .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
932 .addChild(mapEntryBuilder.build())
937 * Map node to map entry builder.
939 * @param dataNode data node
940 * @param mapEntryBuilder builder for mapping data
942 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
943 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
944 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
948 * Prepare and map all data from DS.
950 * @param configDataNode data node of config data
951 * @param stateDataNode data node of state data
952 * @return {@link NormalizedNode}
954 @SuppressWarnings("unchecked")
955 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
956 final @NonNull NormalizedNode stateDataNode) {
957 if (configDataNode instanceof UserMapNode configMap) {
958 final var builder = Builders.orderedMapBuilder().withNodeIdentifier(configMap.name());
959 mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
960 return builder.build();
961 } else if (configDataNode instanceof SystemMapNode configMap) {
962 final var builder = Builders.mapBuilder().withNodeIdentifier(configMap.name());
963 mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
964 return builder.build();
965 } else if (configDataNode instanceof MapEntryNode configEntry) {
966 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(configEntry.name());
967 mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
968 return builder.build();
969 } else if (configDataNode instanceof ContainerNode configContaienr) {
970 final var builder = Builders.containerBuilder().withNodeIdentifier(configContaienr.name());
971 mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
972 return builder.build();
973 } else if (configDataNode instanceof ChoiceNode configChoice) {
974 final var builder = Builders.choiceBuilder().withNodeIdentifier(configChoice.name());
975 mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
976 return builder.build();
977 } else if (configDataNode instanceof LeafNode configLeaf) {
978 // config trumps oper
980 } else if (configDataNode instanceof UserLeafSetNode) {
981 final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
982 final var builder = Builders.<Object>orderedLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
983 mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
984 return builder.build();
985 } else if (configDataNode instanceof SystemLeafSetNode) {
986 final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
987 final var builder = Builders.<Object>leafSetBuilder().withNodeIdentifier(configLeafSet.name());
988 mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
989 return builder.build();
990 } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
991 // config trumps oper
993 } else if (configDataNode instanceof UnkeyedListNode configList) {
994 final var builder = Builders.unkeyedListBuilder().withNodeIdentifier(configList.name());
995 mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
996 return builder.build();
997 } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
998 final var builder = Builders.unkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
999 mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
1000 return builder.build();
1002 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
1007 * Map value from container node to builder.
1009 * @param configData collection of config data nodes
1010 * @param stateData collection of state data nodes
1011 * @param builder builder
1013 private static <T extends NormalizedNode> void mapValueToBuilder(
1014 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
1015 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1016 final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1017 final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1019 // merge config and state data of children with different identifiers
1020 mapDataToBuilder(configMap, stateMap, builder);
1022 // merge config and state data of children with the same identifiers
1023 mergeDataToBuilder(configMap, stateMap, builder);
1027 * Map data with different identifiers to builder. Data with different identifiers can be just added
1028 * as childs to parent node.
1030 * @param configMap map of config data nodes
1031 * @param stateMap map of state data nodes
1032 * @param builder - builder
1034 private static <T extends NormalizedNode> void mapDataToBuilder(
1035 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1036 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1037 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
1038 y -> builder.addChild(y.getValue()));
1039 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
1040 y -> builder.addChild(y.getValue()));
1044 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
1045 * go one level down with {@code prepareData} method.
1047 * @param configMap immutable config data
1048 * @param stateMap immutable state data
1049 * @param builder - builder
1051 @SuppressWarnings("unchecked")
1052 private static <T extends NormalizedNode> void mergeDataToBuilder(
1053 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1054 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1055 // it is enough to process only config data because operational contains the same data
1056 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1057 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1060 public @NonNull RestconfFuture<OperationOutput> invokeRpc(final URI restconfURI, final QName type,
1061 final OperationInput input) {
1062 final var local = localRpcs.get(type);
1063 if (local != null) {
1064 return local.invoke(restconfURI, input);
1066 if (rpcService == null) {
1067 LOG.debug("RPC invocation is not available");
1068 return RestconfFuture.failed(new RestconfDocumentedException("RPC invocation is not available",
1069 ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED));
1072 final var ret = new SettableRestconfFuture<OperationOutput>();
1073 Futures.addCallback(rpcService.invokeRpc(requireNonNull(type), input.input()),
1074 new FutureCallback<DOMRpcResult>() {
1076 public void onSuccess(final DOMRpcResult response) {
1077 final var errors = response.errors();
1078 if (errors.isEmpty()) {
1079 ret.set(input.newOperationOutput(response.value()));
1081 LOG.debug("RPC invocation reported {}", response.errors());
1082 ret.setFailure(new RestconfDocumentedException("RPC implementation reported errors", null,
1083 response.errors()));
1088 public void onFailure(final Throwable cause) {
1089 LOG.debug("RPC invocation failed, cause");
1090 if (cause instanceof RestconfDocumentedException ex) {
1093 // TODO: YangNetconfErrorAware if we ever get into a broader invocation scope
1094 ret.setFailure(new RestconfDocumentedException(cause,
1095 new RestconfError(ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage())));
1098 }, MoreExecutors.directExecutor());
1102 public @NonNull RestconfFuture<CharSource> resolveSource(final SourceIdentifier source,
1103 final Class<? extends SchemaSourceRepresentation> representation) {
1104 final var src = requireNonNull(source);
1105 if (YangTextSchemaSource.class.isAssignableFrom(representation)) {
1106 if (sourceProvider != null) {
1107 final var ret = new SettableRestconfFuture<CharSource>();
1108 Futures.addCallback(sourceProvider.getSource(src), new FutureCallback<YangTextSchemaSource>() {
1110 public void onSuccess(final YangTextSchemaSource result) {
1115 public void onFailure(final Throwable cause) {
1116 ret.setFailure(cause instanceof RestconfDocumentedException e ? e
1117 : new RestconfDocumentedException(cause.getMessage(), ErrorType.RPC,
1118 ErrorTag.OPERATION_FAILED, cause));
1120 }, MoreExecutors.directExecutor());
1123 return exportSource(modelContext(), src, YangCharSource::new, YangCharSource::new);
1125 if (YinTextSchemaSource.class.isAssignableFrom(representation)) {
1126 return exportSource(modelContext(), src, YinCharSource.OfModule::new, YinCharSource.OfSubmodule::new);
1128 return RestconfFuture.failed(new RestconfDocumentedException(
1129 "Unsupported source representation " + representation.getName()));
1132 private static @NonNull RestconfFuture<CharSource> exportSource(final EffectiveModelContext modelContext,
1133 final SourceIdentifier source, final Function<ModuleEffectiveStatement, CharSource> moduleCtor,
1134 final BiFunction<ModuleEffectiveStatement, SubmoduleEffectiveStatement, CharSource> submoduleCtor) {
1135 // If the source identifies a module, things are easy
1136 final var name = source.name().getLocalName();
1137 final var optRevision = Optional.ofNullable(source.revision());
1138 final var optModule = modelContext.findModule(name, optRevision);
1139 if (optModule.isPresent()) {
1140 return RestconfFuture.of(moduleCtor.apply(optModule.orElseThrow().asEffectiveStatement()));
1143 // The source could be a submodule, which we need to hunt down
1144 for (var module : modelContext.getModules()) {
1145 for (var submodule : module.getSubmodules()) {
1146 if (name.equals(submodule.getName()) && optRevision.equals(submodule.getRevision())) {
1147 return RestconfFuture.of(submoduleCtor.apply(module.asEffectiveStatement(),
1148 submodule.asEffectiveStatement()));
1153 final var sb = new StringBuilder().append("Source ").append(source.name().getLocalName());
1154 optRevision.ifPresent(rev -> sb.append('@').append(rev));
1155 sb.append(" not found");
1156 return RestconfFuture.failed(new RestconfDocumentedException(sb.toString(),
1157 ErrorType.APPLICATION, ErrorTag.DATA_MISSING));