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 EffectiveModelContext modelContext, final ImmutableMap<QName, RpcImplementation> localRpcs,
121 final @Nullable DOMRpcService rpcService, final DOMYangTextSourceProvider sourceProvider) {
122 // FIXME: pass this down
123 databind = DatabindContext.ofModel(modelContext);
124 this.localRpcs = requireNonNull(localRpcs);
125 this.rpcService = rpcService;
126 this.sourceProvider = sourceProvider;
130 * Look up the appropriate strategy for a particular mount point.
132 * @param modelContext {@link EffectiveModelContext} of target mount point
133 * @param mountPoint Target mount point
134 * @return A strategy, or null if the mount point does not expose a supported interface
135 * @throws NullPointerException if any argument is {@code null}
137 public static @Nullable RestconfStrategy forMountPoint(final EffectiveModelContext modelContext,
138 final DOMMountPoint mountPoint) {
139 final var rpcService = mountPoint.getService(DOMRpcService.class).orElse(null);
140 final var sourceProvider = mountPoint.getService(DOMSchemaService.class)
141 .flatMap(schema -> Optional.ofNullable(schema.getExtensions().getInstance(DOMYangTextSourceProvider.class)))
144 final var netconfService = mountPoint.getService(NetconfDataTreeService.class);
145 if (netconfService.isPresent()) {
146 return new NetconfRestconfStrategy(modelContext, netconfService.orElseThrow(), rpcService, sourceProvider);
148 final var dataBroker = mountPoint.getService(DOMDataBroker.class);
149 if (dataBroker.isPresent()) {
150 return new MdsalRestconfStrategy(modelContext, dataBroker.orElseThrow(), rpcService, sourceProvider);
155 public final @NonNull DatabindContext databind() {
159 public final @NonNull EffectiveModelContext modelContext() {
160 return databind.modelContext();
164 * Lock the entire datastore.
166 * @return A {@link RestconfTransaction}. This transaction needs to be either committed or canceled before doing
169 abstract RestconfTransaction prepareWriteExecution();
172 * Read data from the datastore.
174 * @param store the logical data store which should be modified
175 * @param path the data object path
176 * @return a ListenableFuture containing the result of the read
178 abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path);
181 * Read data selected using fields from the datastore.
183 * @param store the logical data store which should be modified
184 * @param path the parent data object path
185 * @param fields paths to selected fields relative to parent path
186 * @return a ListenableFuture containing the result of the read
188 abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path,
189 List<YangInstanceIdentifier> fields);
192 * Check if data already exists in the configuration datastore.
194 * @param path the data object path
195 * @return a ListenableFuture containing the result of the check
197 // FIXME: this method should be hosted in RestconfTransaction
198 // FIXME: this method should only be needed in MdsalRestconfStrategy
199 abstract ListenableFuture<Boolean> exists(YangInstanceIdentifier path);
202 * Delete data from the configuration datastore. If the data does not exist, this operation will fail, as outlined
203 * in <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.7">RFC8040 section 4.7</a>
205 * @param path Path to delete
206 * @return A {@link RestconfFuture}
207 * @throws NullPointerException if {@code path} is {@code null}
209 public final @NonNull RestconfFuture<Empty> delete(final YangInstanceIdentifier path) {
210 final var ret = new SettableRestconfFuture<Empty>();
211 delete(ret, requireNonNull(path));
215 abstract void delete(@NonNull SettableRestconfFuture<Empty> future, @NonNull YangInstanceIdentifier path);
218 * Merge data into the configuration datastore, as outlined in
219 * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040 section 4.6.1</a>.
221 * @param path Path to merge
222 * @param data Data to merge
223 * @return A {@link RestconfFuture}
224 * @throws NullPointerException if any argument is {@code null}
226 public final @NonNull RestconfFuture<Empty> merge(final YangInstanceIdentifier path, final NormalizedNode data) {
227 final var ret = new SettableRestconfFuture<Empty>();
228 merge(ret, requireNonNull(path), requireNonNull(data));
232 private void merge(final @NonNull SettableRestconfFuture<Empty> future, final @NonNull YangInstanceIdentifier path,
233 final @NonNull NormalizedNode data) {
234 final var tx = prepareWriteExecution();
235 // FIXME: this method should be further specialized to eliminate this call -- it is only needed for MD-SAL
236 tx.ensureParentsByMerge(path);
237 tx.merge(path, data);
238 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
240 public void onSuccess(final CommitInfo result) {
241 future.set(Empty.value());
245 public void onFailure(final Throwable cause) {
246 future.setFailure(TransactionUtil.decodeException(cause, "MERGE", path, modelContext()));
248 }, MoreExecutors.directExecutor());
252 * Check mount point and prepare variables for put data to DS.
254 * @param path path of data
256 * @param insert {@link Insert}
257 * @return A {@link DataPutResult}
259 public final RestconfFuture<DataPutResult> putData(final YangInstanceIdentifier path,
260 final NormalizedNode data, final @Nullable Insert insert) {
261 final var exists = TransactionUtil.syncAccess(exists(path), path);
263 final ListenableFuture<? extends CommitInfo> commitFuture;
264 if (insert != null) {
265 final var parentPath = path.coerceParent();
266 checkListAndOrderedType(parentPath);
267 commitFuture = insertAndCommitPut(path, data, insert, parentPath);
269 commitFuture = replaceAndCommit(prepareWriteExecution(), path, data);
272 final var ret = new SettableRestconfFuture<DataPutResult>();
274 Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
276 public void onSuccess(final CommitInfo result) {
277 ret.set(exists ? DataPutResult.REPLACED : DataPutResult.CREATED);
281 public void onFailure(final Throwable cause) {
282 ret.setFailure(TransactionUtil.decodeException(cause, "PUT", path, modelContext()));
284 }, MoreExecutors.directExecutor());
289 private ListenableFuture<? extends CommitInfo> insertAndCommitPut(final YangInstanceIdentifier path,
290 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parentPath) {
291 final var tx = prepareWriteExecution();
293 return switch (insert.insert()) {
295 final var readData = tx.readList(parentPath);
296 if (readData == null || readData.isEmpty()) {
297 yield replaceAndCommit(tx, path, data);
299 tx.remove(parentPath);
300 tx.replace(path, data);
301 tx.replace(parentPath, readData);
304 case LAST -> replaceAndCommit(tx, path, data);
306 final var readData = tx.readList(parentPath);
307 if (readData == null || readData.isEmpty()) {
308 yield replaceAndCommit(tx, path, data);
310 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
314 final var readData = tx.readList(parentPath);
315 if (readData == null || readData.isEmpty()) {
316 yield replaceAndCommit(tx, path, data);
318 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
324 private void insertWithPointPut(final RestconfTransaction tx, final YangInstanceIdentifier path,
325 final NormalizedNode data, final @NonNull PathArgument pointArg, final NormalizedNodeContainer<?> readList,
326 final boolean before) {
327 tx.remove(path.getParent());
329 int lastItemPosition = 0;
330 for (var nodeChild : readList.body()) {
331 if (nodeChild.name().equals(pointArg)) {
340 int lastInsertedPosition = 0;
341 final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext(), path.getParent());
342 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
343 for (var nodeChild : readList.body()) {
344 if (lastInsertedPosition == lastItemPosition) {
345 tx.replace(path, data);
347 final var childPath = path.coerceParent().node(nodeChild.name());
348 tx.replace(childPath, nodeChild);
349 lastInsertedPosition++;
353 private static ListenableFuture<? extends CommitInfo> replaceAndCommit(final RestconfTransaction tx,
354 final YangInstanceIdentifier path, final NormalizedNode data) {
355 tx.replace(path, data);
359 private DataSchemaNode checkListAndOrderedType(final YangInstanceIdentifier path) {
360 // FIXME: we have this available in InstanceIdentifierContext
361 final var dataSchemaNode = databind.schemaTree().findChild(path).orElseThrow().dataSchemaNode();
363 final String message;
364 if (dataSchemaNode instanceof ListSchemaNode listSchema) {
365 if (listSchema.isUserOrdered()) {
368 message = "Insert parameter can be used only with ordered-by user list.";
369 } else if (dataSchemaNode instanceof LeafListSchemaNode leafListSchema) {
370 if (leafListSchema.isUserOrdered()) {
371 return leafListSchema;
373 message = "Insert parameter can be used only with ordered-by user leaf-list.";
375 message = "Insert parameter can be used only with list or leaf-list";
377 throw new RestconfDocumentedException(message, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
381 * Check mount point and prepare variables for post data.
385 * @param insert {@link Insert}
386 * @return A {@link RestconfFuture}
388 public final @NonNull RestconfFuture<CreateResource> postData(final YangInstanceIdentifier path,
389 final NormalizedNode data, final @Nullable Insert insert) {
390 final ListenableFuture<? extends CommitInfo> future;
391 if (insert != null) {
392 final var parentPath = path.coerceParent();
393 checkListAndOrderedType(parentPath);
394 future = insertAndCommitPost(path, data, insert, parentPath);
396 future = createAndCommit(prepareWriteExecution(), path, data);
399 final var ret = new SettableRestconfFuture<CreateResource>();
400 Futures.addCallback(future, new FutureCallback<CommitInfo>() {
402 public void onSuccess(final CommitInfo result) {
403 ret.set(new CreateResource(IdentifierCodec.serialize(
404 data instanceof MapNode mapData && !mapData.isEmpty()
405 ? path.node(mapData.body().iterator().next().name()) : path,
410 public void onFailure(final Throwable cause) {
411 ret.setFailure(TransactionUtil.decodeException(cause, "POST", path, modelContext()));
414 }, MoreExecutors.directExecutor());
418 private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
419 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parent) {
420 final var grandParent = parent.coerceParent();
421 final var tx = prepareWriteExecution();
423 return switch (insert.insert()) {
425 final var readData = tx.readList(grandParent);
426 if (readData == null || readData.isEmpty()) {
427 tx.replace(path, data);
429 checkItemDoesNotExists(exists(path), path);
430 tx.remove(grandParent);
431 tx.replace(path, data);
432 tx.replace(grandParent, readData);
436 case LAST -> createAndCommit(tx, path, data);
438 final var readData = tx.readList(grandParent);
439 if (readData == null || readData.isEmpty()) {
440 tx.replace(path, data);
442 checkItemDoesNotExists(exists(path), path);
443 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, true);
448 final var readData = tx.readList(grandParent);
449 if (readData == null || readData.isEmpty()) {
450 tx.replace(path, data);
452 checkItemDoesNotExists(exists(path), path);
453 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, false);
461 * Process edit operations of one {@link PatchContext}.
463 * @param patch Patch context to be processed
464 * @return {@link PatchStatusContext}
466 public final @NonNull RestconfFuture<PatchStatusContext> patchData(final PatchContext patch) {
467 final var editCollection = new ArrayList<PatchStatusEntity>();
468 final var tx = prepareWriteExecution();
470 boolean noError = true;
471 for (var patchEntity : patch.entities()) {
473 final var targetNode = patchEntity.getTargetNode();
474 final var editId = patchEntity.getEditId();
476 switch (patchEntity.getOperation()) {
479 tx.create(targetNode, patchEntity.getNode());
480 editCollection.add(new PatchStatusEntity(editId, true, null));
481 } catch (RestconfDocumentedException e) {
482 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
488 tx.delete(targetNode);
489 editCollection.add(new PatchStatusEntity(editId, true, null));
490 } catch (RestconfDocumentedException e) {
491 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
497 tx.ensureParentsByMerge(targetNode);
498 tx.merge(targetNode, patchEntity.getNode());
499 editCollection.add(new PatchStatusEntity(editId, true, null));
500 } catch (RestconfDocumentedException e) {
501 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
507 tx.replace(targetNode, patchEntity.getNode());
508 editCollection.add(new PatchStatusEntity(editId, true, null));
509 } catch (RestconfDocumentedException e) {
510 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
516 tx.remove(targetNode);
517 editCollection.add(new PatchStatusEntity(editId, true, null));
518 } catch (RestconfDocumentedException e) {
519 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
524 editCollection.add(new PatchStatusEntity(editId, false, List.of(
525 new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
526 "Not supported Yang Patch operation"))));
535 final var ret = new SettableRestconfFuture<PatchStatusContext>();
539 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false, null));
543 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
545 public void onSuccess(final CommitInfo result) {
546 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), true,
551 public void onFailure(final Throwable cause) {
552 // if errors occurred during transaction commit then patch failed and global errors are reported
553 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false,
554 TransactionUtil.decodeException(cause, "PATCH", null, modelContext()).getErrors()));
556 }, MoreExecutors.directExecutor());
561 private void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
562 final NormalizedNode data, final PathArgument pointArg, final NormalizedNodeContainer<?> readList,
563 final YangInstanceIdentifier grandParentPath, final boolean before) {
564 tx.remove(grandParentPath);
566 int lastItemPosition = 0;
567 for (var nodeChild : readList.body()) {
568 if (nodeChild.name().equals(pointArg)) {
577 int lastInsertedPosition = 0;
578 final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext(), grandParentPath);
579 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
580 for (var nodeChild : readList.body()) {
581 if (lastInsertedPosition == lastItemPosition) {
582 tx.replace(path, data);
584 tx.replace(grandParentPath.node(nodeChild.name()), nodeChild);
585 lastInsertedPosition++;
589 private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
590 final YangInstanceIdentifier path, final NormalizedNode data) {
592 tx.create(path, data);
593 } catch (RestconfDocumentedException e) {
594 // close transaction if any and pass exception further
603 * Check if items do NOT already exists at specified {@code path}.
605 * @param existsFuture if checked data exists
606 * @param path Path to be checked
607 * @throws RestconfDocumentedException if data already exists.
609 static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
610 final YangInstanceIdentifier path) {
611 if (TransactionUtil.syncAccess(existsFuture, path)) {
612 LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
613 throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
619 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
620 * inside of object {@link RestconfStrategy} provided as a parameter.
622 * @param content type of data to read (config, state, all)
623 * @param path the path to read
624 * @param defaultsMode value of with-defaults parameter
625 * @return {@link NormalizedNode}
627 // FIXME: NETCONF-1155: this method should asynchronous
628 public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
629 final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
630 return switch (content) {
632 // PREPARE STATE DATA NODE
633 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
634 // PREPARE CONFIG DATA NODE
635 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
637 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
638 : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
641 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
642 yield defaultsMode == null ? read
643 : prepareDataByParamWithDef(read, path, defaultsMode.mode());
645 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
650 * Read specific type of data from data store via transaction with specified subtrees that should only be read.
651 * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
653 * @param content type of data to read (config, state, all)
654 * @param path the parent path to read
655 * @param withDefa value of with-defaults parameter
656 * @param fields paths to selected subtrees which should be read, relative to to the parent path
657 * @return {@link NormalizedNode}
659 // FIXME: NETCONF-1155: this method should asynchronous
660 public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
661 final @NonNull YangInstanceIdentifier path, final @Nullable WithDefaultsParam withDefa,
662 final @NonNull List<YangInstanceIdentifier> fields) {
663 return switch (content) {
665 // PREPARE STATE DATA NODE
666 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
667 // PREPARE CONFIG DATA NODE
668 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
670 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, withDefa == null ? configDataNode
671 : prepareDataByParamWithDef(configDataNode, path, withDefa.mode()));
674 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
675 yield withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa.mode());
677 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
681 private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
682 final YangInstanceIdentifier path) {
683 return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
687 * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
688 * specified subtrees that should only be read.
690 * @param store datastore type
691 * @param path parent path to selected fields
692 * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
693 * in {@link RestconfStrategy} if any
694 * @param fields paths to selected subtrees which should be read, relative to to the parent path
695 * @return {@link NormalizedNode}
697 private @Nullable NormalizedNode readDataViaTransaction(final @NonNull LogicalDatastoreType store,
698 final @NonNull YangInstanceIdentifier path, final @NonNull List<YangInstanceIdentifier> fields) {
699 return TransactionUtil.syncAccess(read(store, path, fields), path).orElse(null);
702 private NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
703 final WithDefaultsMode defaultsMode) {
704 final boolean trim = switch (defaultsMode) {
706 case Explicit -> false;
707 case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
708 "Unsupported with-defaults value " + defaultsMode.getName());
711 // FIXME: we have this readily available in InstanceIdentifierContext
712 final var ctxNode = databind.schemaTree().findChild(path).orElseThrow();
713 if (readData instanceof ContainerNode container) {
714 final var builder = Builders.containerBuilder().withNodeIdentifier(container.name());
715 buildCont(builder, container.body(), ctxNode, trim);
716 return builder.build();
717 } else if (readData instanceof MapEntryNode mapEntry) {
718 if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
719 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
722 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(mapEntry.name());
723 buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
724 return builder.build();
726 throw new IllegalStateException("Unhandled data contract " + readData.contract());
730 private static void buildMapEntryBuilder(
731 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
732 final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
733 final boolean trim, final List<QName> keys) {
734 for (var child : children) {
735 final var childCtx = getChildContext(ctxNode, child);
737 if (child instanceof ContainerNode container) {
738 appendContainer(builder, container, childCtx, trim);
739 } else if (child instanceof MapNode map) {
740 appendMap(builder, map, childCtx, trim);
741 } else if (child instanceof LeafNode<?> leaf) {
742 appendLeaf(builder, leaf, childCtx, trim, keys);
744 // FIXME: we should never hit this, throw an ISE if this ever happens
745 LOG.debug("Ignoring unhandled child contract {}", child.contract());
750 private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
751 final DataSchemaContext ctxNode, final boolean trim) {
752 final var childBuilder = Builders.containerBuilder().withNodeIdentifier(container.name());
753 buildCont(childBuilder, container.body(), ctxNode, trim);
754 builder.withChild(childBuilder.build());
757 private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
758 final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
759 if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
760 throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
763 // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
764 final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
766 // This is a combined check for when we need to emit the leaf.
768 // We always have to emit key leaf values
769 keys.contains(leafSchema.getQName())
770 // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
772 // When data is retrieved with a <with-defaults> parameter equal to
773 // 'trim', data nodes MUST NOT be reported if they contain the schema
774 // default value. Non-configuration data nodes containing the schema
775 // default value MUST NOT be reported.
777 || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
778 // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
779 // grasp what we are doing here... emit only if it matches default ???!!!
780 // FIXME: The WithDefaultsParam.EXPLICIT says:
782 // Data nodes set to the YANG default by the client are reported.
784 // and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
786 // If the "with-defaults" parameter is set to "explicit", then the
787 // server MUST adhere to the default-reporting behavior defined in
788 // Section 3.3 of [RFC6243].
790 // and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
792 // When data is retrieved with a <with-defaults> parameter equal to
793 // 'explicit', a data node that was set by a client to its schema
794 // default value MUST be reported. A conceptual data node that would be
795 // set by the server to the schema default value MUST NOT be reported.
796 // Non-configuration data nodes containing the schema default value MUST
799 // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
800 // This seems to disregard the 'trim = true' case semantics (see above).
801 // Combining the above, though, these checks are missing the 'non-config' check, which would
802 // distinguish, but barring that this check is superfluous and results in the wrong semantics.
803 // Without that input, this really should be covered by the previous case.
804 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
805 builder.withChild(leaf);
809 private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
810 final DataSchemaContext childCtx, final boolean trim) {
811 if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
812 throw new IllegalStateException("Input " + map + " does not match " + childCtx);
815 final var childBuilder = switch (map.ordering()) {
816 case SYSTEM -> Builders.mapBuilder();
817 case USER -> Builders.orderedMapBuilder();
819 buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
820 listSchema.getKeyDefinition());
821 builder.withChild(childBuilder.build());
824 private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
825 final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
826 final List<@NonNull QName> keys) {
827 for (var entry : entries) {
828 final var childCtx = getChildContext(ctxNode, entry);
829 final var mapEntryBuilder = Builders.mapEntryBuilder().withNodeIdentifier(entry.name());
830 buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
831 builder.withChild(mapEntryBuilder.build());
835 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
836 final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
837 for (var child : children) {
838 final var childCtx = getChildContext(ctxNode, child);
839 if (child instanceof ContainerNode container) {
840 appendContainer(builder, container, childCtx, trim);
841 } else if (child instanceof MapNode map) {
842 appendMap(builder, map, childCtx, trim);
843 } else if (child instanceof LeafNode<?> leaf) {
844 appendLeaf(builder, leaf, childCtx, trim, List.of());
849 private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
850 final NormalizedNode child) {
851 final var childId = child.name();
852 final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
854 if (childCtx == null) {
855 throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
860 private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
861 final NormalizedNode configDataNode) {
863 if (stateDataNode == null && configDataNode == null) {
867 // return config data
868 if (stateDataNode == null) {
869 return configDataNode;
873 if (configDataNode == null) {
874 return stateDataNode;
877 // merge data from config and state
878 return mergeStateAndConfigData(stateDataNode, configDataNode);
882 * Merge state and config data into a single NormalizedNode.
884 * @param stateDataNode data node of state data
885 * @param configDataNode data node of config data
886 * @return {@link NormalizedNode}
888 private static @NonNull NormalizedNode mergeStateAndConfigData(
889 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
890 validateNodeMerge(stateDataNode, configDataNode);
891 // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
892 if (configDataNode instanceof RpcDefinition) {
893 return prepareRpcData(configDataNode, stateDataNode);
895 return prepareData(configDataNode, stateDataNode);
900 * Validates whether the two NormalizedNodes can be merged.
902 * @param stateDataNode data node of state data
903 * @param configDataNode data node of config data
905 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
906 final @NonNull NormalizedNode configDataNode) {
907 final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
908 final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
909 if (!moduleOfStateData.equals(moduleOfConfigData)) {
910 throw new RestconfDocumentedException("Unable to merge data from different modules.");
915 * Prepare and map data for rpc.
917 * @param configDataNode data node of config data
918 * @param stateDataNode data node of state data
919 * @return {@link NormalizedNode}
921 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
922 final @NonNull NormalizedNode stateDataNode) {
923 final var mapEntryBuilder = Builders.mapEntryBuilder()
924 .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
927 mapRpcDataNode(configDataNode, mapEntryBuilder);
929 mapRpcDataNode(stateDataNode, mapEntryBuilder);
931 return Builders.mapBuilder()
932 .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
933 .addChild(mapEntryBuilder.build())
938 * Map node to map entry builder.
940 * @param dataNode data node
941 * @param mapEntryBuilder builder for mapping data
943 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
944 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
945 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
949 * Prepare and map all data from DS.
951 * @param configDataNode data node of config data
952 * @param stateDataNode data node of state data
953 * @return {@link NormalizedNode}
955 @SuppressWarnings("unchecked")
956 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
957 final @NonNull NormalizedNode stateDataNode) {
958 if (configDataNode instanceof UserMapNode configMap) {
959 final var builder = Builders.orderedMapBuilder().withNodeIdentifier(configMap.name());
960 mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
961 return builder.build();
962 } else if (configDataNode instanceof SystemMapNode configMap) {
963 final var builder = Builders.mapBuilder().withNodeIdentifier(configMap.name());
964 mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
965 return builder.build();
966 } else if (configDataNode instanceof MapEntryNode configEntry) {
967 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(configEntry.name());
968 mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
969 return builder.build();
970 } else if (configDataNode instanceof ContainerNode configContaienr) {
971 final var builder = Builders.containerBuilder().withNodeIdentifier(configContaienr.name());
972 mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
973 return builder.build();
974 } else if (configDataNode instanceof ChoiceNode configChoice) {
975 final var builder = Builders.choiceBuilder().withNodeIdentifier(configChoice.name());
976 mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
977 return builder.build();
978 } else if (configDataNode instanceof LeafNode configLeaf) {
979 // config trumps oper
981 } else if (configDataNode instanceof UserLeafSetNode) {
982 final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
983 final var builder = Builders.<Object>orderedLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
984 mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
985 return builder.build();
986 } else if (configDataNode instanceof SystemLeafSetNode) {
987 final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
988 final var builder = Builders.<Object>leafSetBuilder().withNodeIdentifier(configLeafSet.name());
989 mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
990 return builder.build();
991 } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
992 // config trumps oper
994 } else if (configDataNode instanceof UnkeyedListNode configList) {
995 final var builder = Builders.unkeyedListBuilder().withNodeIdentifier(configList.name());
996 mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
997 return builder.build();
998 } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
999 final var builder = Builders.unkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
1000 mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
1001 return builder.build();
1003 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
1008 * Map value from container node to builder.
1010 * @param configData collection of config data nodes
1011 * @param stateData collection of state data nodes
1012 * @param builder builder
1014 private static <T extends NormalizedNode> void mapValueToBuilder(
1015 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
1016 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1017 final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1018 final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1020 // merge config and state data of children with different identifiers
1021 mapDataToBuilder(configMap, stateMap, builder);
1023 // merge config and state data of children with the same identifiers
1024 mergeDataToBuilder(configMap, stateMap, builder);
1028 * Map data with different identifiers to builder. Data with different identifiers can be just added
1029 * as childs to parent node.
1031 * @param configMap map of config data nodes
1032 * @param stateMap map of state data nodes
1033 * @param builder - builder
1035 private static <T extends NormalizedNode> void mapDataToBuilder(
1036 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1037 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1038 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
1039 y -> builder.addChild(y.getValue()));
1040 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
1041 y -> builder.addChild(y.getValue()));
1045 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
1046 * go one level down with {@code prepareData} method.
1048 * @param configMap immutable config data
1049 * @param stateMap immutable state data
1050 * @param builder - builder
1052 @SuppressWarnings("unchecked")
1053 private static <T extends NormalizedNode> void mergeDataToBuilder(
1054 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1055 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1056 // it is enough to process only config data because operational contains the same data
1057 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1058 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1061 public @NonNull RestconfFuture<OperationOutput> invokeRpc(final URI restconfURI, final QName type,
1062 final OperationInput input) {
1063 final var local = localRpcs.get(type);
1064 if (local != null) {
1065 return local.invoke(restconfURI, input);
1067 if (rpcService == null) {
1068 LOG.debug("RPC invocation is not available");
1069 return RestconfFuture.failed(new RestconfDocumentedException("RPC invocation is not available",
1070 ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED));
1073 final var ret = new SettableRestconfFuture<OperationOutput>();
1074 Futures.addCallback(rpcService.invokeRpc(requireNonNull(type), input.input()),
1075 new FutureCallback<DOMRpcResult>() {
1077 public void onSuccess(final DOMRpcResult response) {
1078 final var errors = response.errors();
1079 if (errors.isEmpty()) {
1080 ret.set(input.newOperationOutput(response.value()));
1082 LOG.debug("RPC invocation reported {}", response.errors());
1083 ret.setFailure(new RestconfDocumentedException("RPC implementation reported errors", null,
1084 response.errors()));
1089 public void onFailure(final Throwable cause) {
1090 LOG.debug("RPC invocation failed, cause");
1091 if (cause instanceof RestconfDocumentedException ex) {
1094 // TODO: YangNetconfErrorAware if we ever get into a broader invocation scope
1095 ret.setFailure(new RestconfDocumentedException(cause,
1096 new RestconfError(ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage())));
1099 }, MoreExecutors.directExecutor());
1103 public @NonNull RestconfFuture<CharSource> resolveSource(final SourceIdentifier source,
1104 final Class<? extends SchemaSourceRepresentation> representation) {
1105 final var src = requireNonNull(source);
1106 if (YangTextSchemaSource.class.isAssignableFrom(representation)) {
1107 if (sourceProvider != null) {
1108 final var ret = new SettableRestconfFuture<CharSource>();
1109 Futures.addCallback(sourceProvider.getSource(src), new FutureCallback<YangTextSchemaSource>() {
1111 public void onSuccess(final YangTextSchemaSource result) {
1116 public void onFailure(final Throwable cause) {
1117 ret.setFailure(cause instanceof RestconfDocumentedException e ? e
1118 : new RestconfDocumentedException(cause.getMessage(), ErrorType.RPC,
1119 ErrorTag.OPERATION_FAILED, cause));
1121 }, MoreExecutors.directExecutor());
1124 return exportSource(modelContext(), src, YangCharSource::new, YangCharSource::new);
1126 if (YinTextSchemaSource.class.isAssignableFrom(representation)) {
1127 return exportSource(modelContext(), src, YinCharSource.OfModule::new, YinCharSource.OfSubmodule::new);
1129 return RestconfFuture.failed(new RestconfDocumentedException(
1130 "Unsupported source representation " + representation.getName()));
1133 private static @NonNull RestconfFuture<CharSource> exportSource(final EffectiveModelContext modelContext,
1134 final SourceIdentifier source, final Function<ModuleEffectiveStatement, CharSource> moduleCtor,
1135 final BiFunction<ModuleEffectiveStatement, SubmoduleEffectiveStatement, CharSource> submoduleCtor) {
1136 // If the source identifies a module, things are easy
1137 final var name = source.name().getLocalName();
1138 final var optRevision = Optional.ofNullable(source.revision());
1139 final var optModule = modelContext.findModule(name, optRevision);
1140 if (optModule.isPresent()) {
1141 return RestconfFuture.of(moduleCtor.apply(optModule.orElseThrow().asEffectiveStatement()));
1144 // The source could be a submodule, which we need to hunt down
1145 for (var module : modelContext.getModules()) {
1146 for (var submodule : module.getSubmodules()) {
1147 if (name.equals(submodule.getName()) && optRevision.equals(submodule.getRevision())) {
1148 return RestconfFuture.of(submoduleCtor.apply(module.asEffectiveStatement(),
1149 submodule.asEffectiveStatement()));
1154 final var sb = new StringBuilder().append("Source ").append(source.name().getLocalName());
1155 optRevision.ifPresent(rev -> sb.append('@').append(rev));
1156 sb.append(" not found");
1157 return RestconfFuture.failed(new RestconfDocumentedException(sb.toString(),
1158 ErrorType.APPLICATION, ErrorTag.DATA_MISSING));