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;
12 import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.fromInstanceId;
14 import com.google.common.annotations.VisibleForTesting;
15 import com.google.common.collect.ImmutableMap;
16 import com.google.common.io.CharSource;
17 import com.google.common.util.concurrent.FutureCallback;
18 import com.google.common.util.concurrent.Futures;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import com.google.common.util.concurrent.MoreExecutors;
21 import java.io.IOException;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.List;
27 import java.util.NoSuchElementException;
28 import java.util.Optional;
29 import java.util.concurrent.CancellationException;
30 import java.util.function.BiFunction;
31 import java.util.function.Function;
32 import java.util.stream.Collectors;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.eclipse.jdt.annotation.NonNullByDefault;
35 import org.eclipse.jdt.annotation.Nullable;
36 import org.opendaylight.mdsal.common.api.CommitInfo;
37 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
38 import org.opendaylight.mdsal.dom.api.DOMActionException;
39 import org.opendaylight.mdsal.dom.api.DOMActionResult;
40 import org.opendaylight.mdsal.dom.api.DOMActionService;
41 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
42 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
43 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
44 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
45 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
46 import org.opendaylight.mdsal.dom.api.DOMRpcService;
47 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
48 import org.opendaylight.mdsal.dom.api.DOMSchemaService.YangTextSourceExtension;
49 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
50 import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult;
51 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
52 import org.opendaylight.restconf.api.ApiPath;
53 import org.opendaylight.restconf.api.FormattableBody;
54 import org.opendaylight.restconf.api.query.ContentParam;
55 import org.opendaylight.restconf.api.query.WithDefaultsParam;
56 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
57 import org.opendaylight.restconf.common.errors.RestconfError;
58 import org.opendaylight.restconf.common.errors.RestconfFuture;
59 import org.opendaylight.restconf.common.errors.SettableRestconfFuture;
60 import org.opendaylight.restconf.common.patch.PatchContext;
61 import org.opendaylight.restconf.common.patch.PatchStatusContext;
62 import org.opendaylight.restconf.common.patch.PatchStatusEntity;
63 import org.opendaylight.restconf.nb.rfc8040.Insert;
64 import org.opendaylight.restconf.nb.rfc8040.legacy.ErrorTags;
65 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
66 import org.opendaylight.restconf.nb.rfc8040.legacy.QueryParameters;
67 import org.opendaylight.restconf.server.api.ChildBody;
68 import org.opendaylight.restconf.server.api.ConfigurationMetadata;
69 import org.opendaylight.restconf.server.api.DataGetParams;
70 import org.opendaylight.restconf.server.api.DataGetResult;
71 import org.opendaylight.restconf.server.api.DataPatchResult;
72 import org.opendaylight.restconf.server.api.DataPostBody;
73 import org.opendaylight.restconf.server.api.DataPostResult;
74 import org.opendaylight.restconf.server.api.DataPostResult.CreateResource;
75 import org.opendaylight.restconf.server.api.DataPutResult;
76 import org.opendaylight.restconf.server.api.DataYangPatchResult;
77 import org.opendaylight.restconf.server.api.DatabindContext;
78 import org.opendaylight.restconf.server.api.DatabindPath;
79 import org.opendaylight.restconf.server.api.DatabindPath.Action;
80 import org.opendaylight.restconf.server.api.DatabindPath.Data;
81 import org.opendaylight.restconf.server.api.DatabindPath.InstanceReference;
82 import org.opendaylight.restconf.server.api.DatabindPath.OperationPath;
83 import org.opendaylight.restconf.server.api.DatabindPath.Rpc;
84 import org.opendaylight.restconf.server.api.InvokeParams;
85 import org.opendaylight.restconf.server.api.InvokeResult;
86 import org.opendaylight.restconf.server.api.OperationInputBody;
87 import org.opendaylight.restconf.server.api.OperationOutputBody;
88 import org.opendaylight.restconf.server.api.PatchBody;
89 import org.opendaylight.restconf.server.api.ResourceBody;
90 import org.opendaylight.restconf.server.spi.ApiPathCanonizer;
91 import org.opendaylight.restconf.server.spi.ApiPathNormalizer;
92 import org.opendaylight.restconf.server.spi.DefaultResourceContext;
93 import org.opendaylight.restconf.server.spi.OperationInput;
94 import org.opendaylight.restconf.server.spi.OperationsResource;
95 import org.opendaylight.restconf.server.spi.RpcImplementation;
96 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.with.defaults.rev110601.WithDefaultsMode;
97 import org.opendaylight.yangtools.yang.common.Empty;
98 import org.opendaylight.yangtools.yang.common.ErrorTag;
99 import org.opendaylight.yangtools.yang.common.ErrorType;
100 import org.opendaylight.yangtools.yang.common.QName;
101 import org.opendaylight.yangtools.yang.common.QNameModule;
102 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
103 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
104 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
105 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
106 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
107 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
108 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
109 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
110 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
111 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
112 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
113 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
114 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
115 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
116 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
117 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
118 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
119 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
120 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
121 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
122 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
123 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
124 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
125 import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
126 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
127 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
128 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
129 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
130 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
131 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
132 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
133 import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
134 import org.opendaylight.yangtools.yang.model.api.source.SourceRepresentation;
135 import org.opendaylight.yangtools.yang.model.api.source.YangTextSource;
136 import org.opendaylight.yangtools.yang.model.api.source.YinTextSource;
137 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
138 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleEffectiveStatement;
139 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
140 import org.slf4j.Logger;
141 import org.slf4j.LoggerFactory;
144 * Baseline execution strategy for various RESTCONF operations.
146 * @see NetconfRestconfStrategy
147 * @see MdsalRestconfStrategy
149 // FIXME: it seems the first three operations deal with lifecycle of a transaction, while others invoke various
150 // operations. This should be handled through proper allocation indirection.
151 public abstract class RestconfStrategy {
153 public record StrategyAndPath(RestconfStrategy strategy, Data path) {
154 public StrategyAndPath {
155 requireNonNull(strategy);
156 requireNonNull(path);
161 * Result of a partial {@link ApiPath} lookup for the purposes of supporting {@code yang-ext:mount}-delimited mount
162 * points with possible nesting.
164 * @param strategy the strategy to use
165 * @param tail the {@link ApiPath} tail to use with the strategy
168 public record StrategyAndTail(RestconfStrategy strategy, ApiPath tail) {
169 public StrategyAndTail {
170 requireNonNull(strategy);
171 requireNonNull(tail);
175 private static final Logger LOG = LoggerFactory.getLogger(RestconfStrategy.class);
176 private static final @NonNull DataPutResult PUT_CREATED = new DataPutResult(true);
177 private static final @NonNull DataPutResult PUT_REPLACED = new DataPutResult(false);
178 private static final @NonNull DataPatchResult PATCH_EMPTY = new DataPatchResult();
180 private final @NonNull ImmutableMap<QName, RpcImplementation> localRpcs;
181 private final @NonNull ApiPathNormalizer pathNormalizer;
182 private final @NonNull DatabindContext databind;
183 private final YangTextSourceExtension sourceProvider;
184 private final DOMMountPointService mountPointService;
185 private final DOMActionService actionService;
186 private final DOMRpcService rpcService;
187 private final OperationsResource operations;
189 RestconfStrategy(final DatabindContext databind, final ImmutableMap<QName, RpcImplementation> localRpcs,
190 final @Nullable DOMRpcService rpcService, final @Nullable DOMActionService actionService,
191 final YangTextSourceExtension sourceProvider, final @Nullable DOMMountPointService mountPointService) {
192 this.databind = requireNonNull(databind);
193 this.localRpcs = requireNonNull(localRpcs);
194 this.rpcService = rpcService;
195 this.actionService = actionService;
196 this.sourceProvider = sourceProvider;
197 this.mountPointService = mountPointService;
198 pathNormalizer = new ApiPathNormalizer(databind);
199 operations = new OperationsResource(pathNormalizer);
202 public final @NonNull StrategyAndPath resolveStrategyPath(final ApiPath path) {
203 final var andTail = resolveStrategy(path);
204 final var strategy = andTail.strategy();
205 return new StrategyAndPath(strategy, strategy.pathNormalizer.normalizeDataPath(andTail.tail()));
209 * Resolve any and all {@code yang-ext:mount} to the target {@link StrategyAndTail}.
211 * @param path {@link ApiPath} to resolve
212 * @return A strategy and the remaining path
213 * @throws NullPointerException if {@code path} is {@code null}
215 public final @NonNull StrategyAndTail resolveStrategy(final ApiPath path) {
216 var mount = path.indexOf("yang-ext", "mount");
218 return new StrategyAndTail(this, path);
220 if (mountPointService == null) {
221 throw new RestconfDocumentedException("Mount point service is not available",
222 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
224 final var mountPath = path.subPath(0, mount);
225 final var dataPath = pathNormalizer.normalizeDataPath(path.subPath(0, mount));
226 final var mountPoint = mountPointService.getMountPoint(dataPath.instance())
227 .orElseThrow(() -> new RestconfDocumentedException("Mount point '" + mountPath + "' does not exist",
228 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
230 return createStrategy(mountPath, mountPoint).resolveStrategy(path.subPath(mount + 1));
233 private static @NonNull RestconfStrategy createStrategy(final ApiPath mountPath, final DOMMountPoint mountPoint) {
234 final var mountSchemaService = mountPoint.getService(DOMSchemaService.class)
235 .orElseThrow(() -> new RestconfDocumentedException(
236 "Mount point '" + mountPath + "' does not expose DOMSchemaService",
237 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
238 final var mountModelContext = mountSchemaService.getGlobalContext();
239 if (mountModelContext == null) {
240 throw new RestconfDocumentedException("Mount point '" + mountPath + "' does not have any models",
241 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT);
243 final var mountDatabind = DatabindContext.ofModel(mountModelContext);
244 final var mountPointService = mountPoint.getService(DOMMountPointService.class).orElse(null);
245 final var rpcService = mountPoint.getService(DOMRpcService.class).orElse(null);
246 final var actionService = mountPoint.getService(DOMActionService.class).orElse(null);
247 final var sourceProvider = mountPoint.getService(DOMSchemaService.class)
248 .flatMap(schema -> Optional.ofNullable(schema.extension(YangTextSourceExtension.class)))
251 final var netconfService = mountPoint.getService(NetconfDataTreeService.class);
252 if (netconfService.isPresent()) {
253 return new NetconfRestconfStrategy(mountDatabind, netconfService.orElseThrow(), rpcService, actionService,
254 sourceProvider, mountPointService);
256 final var dataBroker = mountPoint.getService(DOMDataBroker.class);
257 if (dataBroker.isPresent()) {
258 return new MdsalRestconfStrategy(mountDatabind, dataBroker.orElseThrow(), rpcService, actionService,
259 sourceProvider, mountPointService);
261 LOG.warn("Mount point {} does not expose a suitable access interface", mountPath);
262 throw new RestconfDocumentedException("Could not find a supported access interface in mount point",
263 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, mountPoint.getIdentifier());
266 public final @NonNull DatabindContext databind() {
270 public final @NonNull EffectiveModelContext modelContext() {
271 return databind.modelContext();
275 * Lock the entire datastore.
277 * @return A {@link RestconfTransaction}. This transaction needs to be either committed or canceled before doing
280 abstract RestconfTransaction prepareWriteExecution();
283 * Read data from the datastore.
285 * @param store the logical data store which should be modified
286 * @param path the data object path
287 * @return a ListenableFuture containing the result of the read
289 abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path);
292 * Check if data already exists in the configuration datastore.
294 * @param path the data object path
295 * @return a ListenableFuture containing the result of the check
297 // FIXME: this method should be hosted in RestconfTransaction
298 // FIXME: this method should only be needed in MdsalRestconfStrategy
299 abstract ListenableFuture<Boolean> exists(YangInstanceIdentifier path);
302 final @NonNull RestconfFuture<DataPatchResult> merge(final YangInstanceIdentifier path, final NormalizedNode data) {
303 final var ret = new SettableRestconfFuture<DataPatchResult>();
304 merge(ret, requireNonNull(path), requireNonNull(data));
308 private void merge(final @NonNull SettableRestconfFuture<DataPatchResult> future,
309 final @NonNull YangInstanceIdentifier path, final @NonNull NormalizedNode data) {
310 final var tx = prepareWriteExecution();
311 // FIXME: this method should be further specialized to eliminate this call -- it is only needed for MD-SAL
312 tx.ensureParentsByMerge(path);
313 tx.merge(path, data);
314 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
316 public void onSuccess(final CommitInfo result) {
317 // TODO: extract details once CommitInfo can communicate them
318 future.set(PATCH_EMPTY);
322 public void onFailure(final Throwable cause) {
323 future.setFailure(TransactionUtil.decodeException(cause, "MERGE", path, modelContext()));
325 }, MoreExecutors.directExecutor());
328 public @NonNull RestconfFuture<DataPutResult> dataPUT(final ApiPath apiPath, final ResourceBody body,
329 final Map<String, String> queryParameters) {
332 path = pathNormalizer.normalizeDataPath(apiPath);
333 } catch (RestconfDocumentedException e) {
334 return RestconfFuture.failed(e);
339 insert = Insert.ofQueryParameters(databind, queryParameters);
340 } catch (IllegalArgumentException e) {
341 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
342 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
344 final NormalizedNode data;
346 data = body.toNormalizedNode(path);
347 } catch (RestconfDocumentedException e) {
348 return RestconfFuture.failed(e);
350 return putData(path.instance(), data, insert);
354 * Check mount point and prepare variables for put data to DS.
356 * @param path path of data
358 * @param insert {@link Insert}
359 * @return A {@link DataPutResult}
361 public final @NonNull RestconfFuture<DataPutResult> putData(final YangInstanceIdentifier path,
362 final NormalizedNode data, final @Nullable Insert insert) {
363 final var exists = TransactionUtil.syncAccess(exists(path), path);
365 final ListenableFuture<? extends CommitInfo> commitFuture;
366 if (insert != null) {
367 final var parentPath = path.coerceParent();
368 checkListAndOrderedType(parentPath);
369 commitFuture = insertAndCommitPut(path, data, insert, parentPath);
371 commitFuture = replaceAndCommit(prepareWriteExecution(), path, data);
374 final var ret = new SettableRestconfFuture<DataPutResult>();
376 Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
378 public void onSuccess(final CommitInfo result) {
379 ret.set(exists ? PUT_REPLACED : PUT_CREATED);
383 public void onFailure(final Throwable cause) {
384 ret.setFailure(TransactionUtil.decodeException(cause, "PUT", path, modelContext()));
386 }, MoreExecutors.directExecutor());
391 private ListenableFuture<? extends CommitInfo> insertAndCommitPut(final YangInstanceIdentifier path,
392 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parentPath) {
393 final var tx = prepareWriteExecution();
395 return switch (insert.insert()) {
397 final var readData = tx.readList(parentPath);
398 if (readData == null || readData.isEmpty()) {
399 yield replaceAndCommit(tx, path, data);
401 tx.remove(parentPath);
402 tx.replace(path, data);
403 tx.replace(parentPath, readData);
406 case LAST -> replaceAndCommit(tx, path, data);
408 final var readData = tx.readList(parentPath);
409 if (readData == null || readData.isEmpty()) {
410 yield replaceAndCommit(tx, path, data);
412 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
416 final var readData = tx.readList(parentPath);
417 if (readData == null || readData.isEmpty()) {
418 yield replaceAndCommit(tx, path, data);
420 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
426 private void insertWithPointPut(final RestconfTransaction tx, final YangInstanceIdentifier path,
427 final NormalizedNode data, final @NonNull PathArgument pointArg, final NormalizedNodeContainer<?> readList,
428 final boolean before) {
429 tx.remove(path.getParent());
431 int lastItemPosition = 0;
432 for (var nodeChild : readList.body()) {
433 if (nodeChild.name().equals(pointArg)) {
442 int lastInsertedPosition = 0;
443 final var emptySubtree = fromInstanceId(modelContext(), path.getParent());
444 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
445 for (var nodeChild : readList.body()) {
446 if (lastInsertedPosition == lastItemPosition) {
447 tx.replace(path, data);
449 final var childPath = path.coerceParent().node(nodeChild.name());
450 tx.replace(childPath, nodeChild);
451 lastInsertedPosition++;
454 // In case we are inserting after last element
456 if (lastInsertedPosition == lastItemPosition) {
457 tx.replace(path, data);
462 private static ListenableFuture<? extends CommitInfo> replaceAndCommit(final RestconfTransaction tx,
463 final YangInstanceIdentifier path, final NormalizedNode data) {
464 tx.replace(path, data);
468 private DataSchemaNode checkListAndOrderedType(final YangInstanceIdentifier path) {
469 // FIXME: we have this available in InstanceIdentifierContext
470 final var dataSchemaNode = databind.schemaTree().findChild(path).orElseThrow().dataSchemaNode();
472 final String message;
473 if (dataSchemaNode instanceof ListSchemaNode listSchema) {
474 if (listSchema.isUserOrdered()) {
477 message = "Insert parameter can be used only with ordered-by user list.";
478 } else if (dataSchemaNode instanceof LeafListSchemaNode leafListSchema) {
479 if (leafListSchema.isUserOrdered()) {
480 return leafListSchema;
482 message = "Insert parameter can be used only with ordered-by user leaf-list.";
484 message = "Insert parameter can be used only with list or leaf-list";
486 throw new RestconfDocumentedException(message, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
490 * Check mount point and prepare variables for post data.
494 * @param insert {@link Insert}
495 * @return A {@link RestconfFuture}
497 public final @NonNull RestconfFuture<CreateResource> postData(final YangInstanceIdentifier path,
498 final NormalizedNode data, final @Nullable Insert insert) {
499 final ListenableFuture<? extends CommitInfo> future;
500 if (insert != null) {
501 checkListAndOrderedType(path);
502 future = insertAndCommitPost(path, data, insert);
504 future = createAndCommit(prepareWriteExecution(), path, data);
507 final var ret = new SettableRestconfFuture<CreateResource>();
508 Futures.addCallback(future, new FutureCallback<CommitInfo>() {
510 public void onSuccess(final CommitInfo result) {
511 ret.set(new CreateResource(new ApiPathCanonizer(databind).dataToApiPath(
512 data instanceof MapNode mapData && !mapData.isEmpty()
513 ? path.node(mapData.body().iterator().next().name()) : path).toString()));
517 public void onFailure(final Throwable cause) {
518 ret.setFailure(TransactionUtil.decodeException(cause, "POST", path, modelContext()));
521 }, MoreExecutors.directExecutor());
525 private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
526 final NormalizedNode data, final @NonNull Insert insert) {
527 final var tx = prepareWriteExecution();
529 return switch (insert.insert()) {
531 final var readData = tx.readList(path);
532 if (readData == null || readData.isEmpty()) {
533 tx.replace(path, data);
535 checkListDataDoesNotExist(path, data);
537 tx.replace(path, data);
538 tx.replace(path, readData);
542 case LAST -> createAndCommit(tx, path, data);
544 final var readData = tx.readList(path);
545 if (readData == null || readData.isEmpty()) {
546 tx.replace(path, data);
548 checkListDataDoesNotExist(path, data);
549 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
554 final var readData = tx.readList(path);
555 if (readData == null || readData.isEmpty()) {
556 tx.replace(path, data);
558 checkListDataDoesNotExist(path, data);
559 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
567 * Merge data into the configuration datastore, as outlined in
568 * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040 section 4.6.1</a>.
570 * @param apiPath Path to merge
571 * @param body Data to merge
572 * @return A {@link RestconfFuture}
573 * @throws NullPointerException if any argument is {@code null}
575 public final @NonNull RestconfFuture<DataPatchResult> dataPATCH(final ApiPath apiPath, final ResourceBody body) {
578 path = pathNormalizer.normalizeDataPath(apiPath);
579 } catch (RestconfDocumentedException e) {
580 return RestconfFuture.failed(e);
583 final NormalizedNode data;
585 data = body.toNormalizedNode(path);
586 } catch (RestconfDocumentedException e) {
587 return RestconfFuture.failed(e);
590 return merge(path.instance(), data);
593 public final @NonNull RestconfFuture<DataYangPatchResult> dataPATCH(final ApiPath apiPath, final PatchBody body) {
596 path = pathNormalizer.normalizeDataPath(apiPath);
597 } catch (RestconfDocumentedException e) {
598 return RestconfFuture.failed(e);
601 final PatchContext patch;
603 patch = body.toPatchContext(new DefaultResourceContext(path));
604 } catch (IOException e) {
605 LOG.debug("Error parsing YANG Patch input", e);
606 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
607 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
609 return patchData(patch);
613 * Process edit operations of one {@link PatchContext}.
615 * @param patch Patch context to be processed
616 * @return {@link PatchStatusContext}
618 public final @NonNull RestconfFuture<DataYangPatchResult> patchData(final PatchContext patch) {
619 final var editCollection = new ArrayList<PatchStatusEntity>();
620 final var tx = prepareWriteExecution();
622 boolean noError = true;
623 for (var patchEntity : patch.entities()) {
625 final var targetNode = patchEntity.getTargetNode();
626 final var editId = patchEntity.getEditId();
628 switch (patchEntity.getOperation()) {
631 tx.create(targetNode, patchEntity.getNode());
632 editCollection.add(new PatchStatusEntity(editId, true, null));
633 } catch (RestconfDocumentedException e) {
634 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
640 tx.delete(targetNode);
641 editCollection.add(new PatchStatusEntity(editId, true, null));
642 } catch (RestconfDocumentedException e) {
643 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
649 tx.ensureParentsByMerge(targetNode);
650 tx.merge(targetNode, patchEntity.getNode());
651 editCollection.add(new PatchStatusEntity(editId, true, null));
652 } catch (RestconfDocumentedException e) {
653 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
659 tx.replace(targetNode, patchEntity.getNode());
660 editCollection.add(new PatchStatusEntity(editId, true, null));
661 } catch (RestconfDocumentedException e) {
662 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
668 tx.remove(targetNode);
669 editCollection.add(new PatchStatusEntity(editId, true, null));
670 } catch (RestconfDocumentedException e) {
671 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
676 editCollection.add(new PatchStatusEntity(editId, false, List.of(
677 new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
678 "Not supported Yang Patch operation"))));
687 final var ret = new SettableRestconfFuture<DataYangPatchResult>();
691 ret.set(new DataYangPatchResult(
692 new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false, null)));
696 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
698 public void onSuccess(final CommitInfo result) {
699 ret.set(new DataYangPatchResult(
700 new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), true, null)));
704 public void onFailure(final Throwable cause) {
705 // if errors occurred during transaction commit then patch failed and global errors are reported
706 ret.set(new DataYangPatchResult(
707 new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false,
708 TransactionUtil.decodeException(cause, "PATCH", null, modelContext()).getErrors())));
710 }, MoreExecutors.directExecutor());
715 private void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
716 final NormalizedNode data, final PathArgument pointArg, final NormalizedNodeContainer<?> readList,
717 final boolean before) {
720 int lastItemPosition = 0;
721 for (var nodeChild : readList.body()) {
722 if (nodeChild.name().equals(pointArg)) {
731 int lastInsertedPosition = 0;
732 for (var nodeChild : readList.body()) {
733 if (lastInsertedPosition == lastItemPosition) {
734 tx.replace(path, data);
736 tx.replace(path.node(nodeChild.name()), nodeChild);
737 lastInsertedPosition++;
740 // In case we are inserting after last element
742 if (lastInsertedPosition == lastItemPosition) {
743 tx.replace(path, data);
748 private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
749 final YangInstanceIdentifier path, final NormalizedNode data) {
751 tx.create(path, data);
752 } catch (RestconfDocumentedException e) {
753 // close transaction if any and pass exception further
762 * Check if child items do NOT already exists in List at specified {@code path}.
764 * @param data Data to be checked
765 * @param path Path to be checked
766 * @throws RestconfDocumentedException if data already exists.
768 private void checkListDataDoesNotExist(final YangInstanceIdentifier path, final NormalizedNode data) {
769 if (data instanceof NormalizedNodeContainer<?> dataNode) {
770 for (final var node : dataNode.body()) {
771 checkItemDoesNotExists(exists(path.node(node.name())), path.node(node.name()));
774 throw new RestconfDocumentedException("Unexpected node type: " + data.getClass().getName());
779 * Check if items do NOT already exists at specified {@code path}.
781 * @param existsFuture if checked data exists
782 * @param path Path to be checked
783 * @throws RestconfDocumentedException if data already exists.
785 static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
786 final YangInstanceIdentifier path) {
787 if (TransactionUtil.syncAccess(existsFuture, path)) {
788 LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
789 throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
795 * Delete data from the configuration datastore. If the data does not exist, this operation will fail, as outlined
796 * in <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.7">RFC8040 section 4.7</a>
798 * @param apiPath Path to delete
799 * @return A {@link RestconfFuture}
800 * @throws NullPointerException if {@code apiPath} is {@code null}
802 @SuppressWarnings("checkstyle:abbreviationAsWordInName")
803 public final @NonNull RestconfFuture<Empty> dataDELETE(final ApiPath apiPath) {
806 path = pathNormalizer.normalizeDataPath(apiPath);
807 } catch (RestconfDocumentedException e) {
808 return RestconfFuture.failed(e);
811 // FIXME: reject empty YangInstanceIdentifier, as datastores may not be deleted
812 final var ret = new SettableRestconfFuture<Empty>();
813 delete(ret, path.instance());
817 abstract void delete(@NonNull SettableRestconfFuture<Empty> future, @NonNull YangInstanceIdentifier path);
819 public final @NonNull RestconfFuture<DataGetResult> dataGET(final ApiPath apiPath,
820 final DataGetParams params) {
823 path = pathNormalizer.normalizeDataPath(apiPath);
824 } catch (RestconfDocumentedException e) {
825 return RestconfFuture.failed(e);
827 return dataGET(path, params);
830 abstract @NonNull RestconfFuture<DataGetResult> dataGET(Data path, DataGetParams params);
832 static final @NonNull RestconfFuture<DataGetResult> completeDataGET(final Inference inference,
833 final QueryParameters queryParams, final @Nullable NormalizedNode node,
834 final @Nullable ConfigurationMetadata metadata) {
836 return RestconfFuture.failed(new RestconfDocumentedException(
837 "Request could not be completed because the relevant data model content does not exist",
838 ErrorType.PROTOCOL, ErrorTag.DATA_MISSING));
841 final var payload = new NormalizedNodePayload(inference, node, queryParams);
842 return RestconfFuture.of(metadata == null ? new DataGetResult(payload)
843 : new DataGetResult(payload, metadata.entityTag(), metadata.lastModified()));
847 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
848 * inside of object {@link RestconfStrategy} provided as a parameter.
850 * @param content type of data to read (config, state, all)
851 * @param path the path to read
852 * @param defaultsMode value of with-defaults parameter
853 * @return {@link NormalizedNode}
855 // FIXME: NETCONF-1155: this method should asynchronous
857 final @Nullable NormalizedNode readData(final @NonNull ContentParam content,
858 final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
859 return switch (content) {
861 // PREPARE STATE DATA NODE
862 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
863 // PREPARE CONFIG DATA NODE
864 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
866 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
867 : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
870 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
871 yield defaultsMode == null ? read
872 : prepareDataByParamWithDef(read, path, defaultsMode.mode());
874 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
878 private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
879 final YangInstanceIdentifier path) {
880 return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
883 final NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
884 final WithDefaultsMode defaultsMode) {
885 final boolean trim = switch (defaultsMode) {
887 case Explicit -> false;
888 case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
889 "Unsupported with-defaults value " + defaultsMode.getName());
892 // FIXME: we have this readily available in InstanceIdentifierContext
893 final var ctxNode = databind.schemaTree().findChild(path).orElseThrow();
894 if (readData instanceof ContainerNode container) {
895 final var builder = ImmutableNodes.newContainerBuilder().withNodeIdentifier(container.name());
896 buildCont(builder, container.body(), ctxNode, trim);
897 return builder.build();
898 } else if (readData instanceof MapEntryNode mapEntry) {
899 if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
900 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
903 final var builder = ImmutableNodes.newMapEntryBuilder().withNodeIdentifier(mapEntry.name());
904 buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
905 return builder.build();
907 throw new IllegalStateException("Unhandled data contract " + readData.contract());
911 private static void buildMapEntryBuilder(
912 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
913 final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
914 final boolean trim, final List<QName> keys) {
915 for (var child : children) {
916 final var childCtx = getChildContext(ctxNode, child);
918 if (child instanceof ContainerNode container) {
919 appendContainer(builder, container, childCtx, trim);
920 } else if (child instanceof MapNode map) {
921 appendMap(builder, map, childCtx, trim);
922 } else if (child instanceof LeafNode<?> leaf) {
923 appendLeaf(builder, leaf, childCtx, trim, keys);
925 // FIXME: we should never hit this, throw an ISE if this ever happens
926 LOG.debug("Ignoring unhandled child contract {}", child.contract());
931 private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
932 final DataSchemaContext ctxNode, final boolean trim) {
933 final var childBuilder = ImmutableNodes.newContainerBuilder().withNodeIdentifier(container.name());
934 buildCont(childBuilder, container.body(), ctxNode, trim);
935 builder.withChild(childBuilder.build());
938 private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
939 final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
940 if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
941 throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
944 // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
945 final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
947 // This is a combined check for when we need to emit the leaf.
949 // We always have to emit key leaf values
950 keys.contains(leafSchema.getQName())
951 // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
953 // When data is retrieved with a <with-defaults> parameter equal to
954 // 'trim', data nodes MUST NOT be reported if they contain the schema
955 // default value. Non-configuration data nodes containing the schema
956 // default value MUST NOT be reported.
958 || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
959 // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
960 // grasp what we are doing here... emit only if it matches default ???!!!
961 // FIXME: The WithDefaultsParam.EXPLICIT says:
963 // Data nodes set to the YANG default by the client are reported.
965 // and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
967 // If the "with-defaults" parameter is set to "explicit", then the
968 // server MUST adhere to the default-reporting behavior defined in
969 // Section 3.3 of [RFC6243].
971 // and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
973 // When data is retrieved with a <with-defaults> parameter equal to
974 // 'explicit', a data node that was set by a client to its schema
975 // default value MUST be reported. A conceptual data node that would be
976 // set by the server to the schema default value MUST NOT be reported.
977 // Non-configuration data nodes containing the schema default value MUST
980 // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
981 // This seems to disregard the 'trim = true' case semantics (see above).
982 // Combining the above, though, these checks are missing the 'non-config' check, which would
983 // distinguish, but barring that this check is superfluous and results in the wrong semantics.
984 // Without that input, this really should be covered by the previous case.
985 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
986 builder.withChild(leaf);
990 private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
991 final DataSchemaContext childCtx, final boolean trim) {
992 if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
993 throw new IllegalStateException("Input " + map + " does not match " + childCtx);
996 final var childBuilder = switch (map.ordering()) {
997 case SYSTEM -> ImmutableNodes.newSystemMapBuilder();
998 case USER -> ImmutableNodes.newUserMapBuilder();
1000 buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
1001 listSchema.getKeyDefinition());
1002 builder.withChild(childBuilder.build());
1005 private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
1006 final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
1007 final List<@NonNull QName> keys) {
1008 for (var entry : entries) {
1009 final var childCtx = getChildContext(ctxNode, entry);
1010 final var mapEntryBuilder = ImmutableNodes.newMapEntryBuilder().withNodeIdentifier(entry.name());
1011 buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
1012 builder.withChild(mapEntryBuilder.build());
1016 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
1017 final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
1018 for (var child : children) {
1019 final var childCtx = getChildContext(ctxNode, child);
1020 if (child instanceof ContainerNode container) {
1021 appendContainer(builder, container, childCtx, trim);
1022 } else if (child instanceof MapNode map) {
1023 appendMap(builder, map, childCtx, trim);
1024 } else if (child instanceof LeafNode<?> leaf) {
1025 appendLeaf(builder, leaf, childCtx, trim, List.of());
1030 private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
1031 final NormalizedNode child) {
1032 final var childId = child.name();
1033 final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
1035 if (childCtx == null) {
1036 throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
1041 static final NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
1042 final NormalizedNode configDataNode) {
1043 if (stateDataNode == null) {
1044 // No state, return config
1045 return configDataNode;
1047 if (configDataNode == null) {
1048 // No config, return state
1049 return stateDataNode;
1051 // merge config and state
1052 return mergeStateAndConfigData(stateDataNode, configDataNode);
1056 * Merge state and config data into a single NormalizedNode.
1058 * @param stateDataNode data node of state data
1059 * @param configDataNode data node of config data
1060 * @return {@link NormalizedNode}
1062 private static @NonNull NormalizedNode mergeStateAndConfigData(
1063 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
1064 validateNodeMerge(stateDataNode, configDataNode);
1065 // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
1066 if (configDataNode instanceof RpcDefinition) {
1067 return prepareRpcData(configDataNode, stateDataNode);
1069 return prepareData(configDataNode, stateDataNode);
1074 * Validates whether the two NormalizedNodes can be merged.
1076 * @param stateDataNode data node of state data
1077 * @param configDataNode data node of config data
1079 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
1080 final @NonNull NormalizedNode configDataNode) {
1081 final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
1082 final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
1083 if (!moduleOfStateData.equals(moduleOfConfigData)) {
1084 throw new RestconfDocumentedException("Unable to merge data from different modules.");
1089 * Prepare and map data for rpc.
1091 * @param configDataNode data node of config data
1092 * @param stateDataNode data node of state data
1093 * @return {@link NormalizedNode}
1095 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
1096 final @NonNull NormalizedNode stateDataNode) {
1097 final var mapEntryBuilder = ImmutableNodes.newMapEntryBuilder()
1098 .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
1101 mapRpcDataNode(configDataNode, mapEntryBuilder);
1103 mapRpcDataNode(stateDataNode, mapEntryBuilder);
1105 return ImmutableNodes.newSystemMapBuilder()
1106 .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
1107 .addChild(mapEntryBuilder.build())
1112 * Map node to map entry builder.
1114 * @param dataNode data node
1115 * @param mapEntryBuilder builder for mapping data
1117 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
1118 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
1119 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
1123 * Prepare and map all data from DS.
1125 * @param configDataNode data node of config data
1126 * @param stateDataNode data node of state data
1127 * @return {@link NormalizedNode}
1129 @SuppressWarnings("unchecked")
1130 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
1131 final @NonNull NormalizedNode stateDataNode) {
1132 if (configDataNode instanceof UserMapNode configMap) {
1133 final var builder = ImmutableNodes.newUserMapBuilder().withNodeIdentifier(configMap.name());
1134 mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
1135 return builder.build();
1136 } else if (configDataNode instanceof SystemMapNode configMap) {
1137 final var builder = ImmutableNodes.newSystemMapBuilder().withNodeIdentifier(configMap.name());
1138 mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
1139 return builder.build();
1140 } else if (configDataNode instanceof MapEntryNode configEntry) {
1141 final var builder = ImmutableNodes.newMapEntryBuilder().withNodeIdentifier(configEntry.name());
1142 mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
1143 return builder.build();
1144 } else if (configDataNode instanceof ContainerNode configContaienr) {
1145 final var builder = ImmutableNodes.newContainerBuilder().withNodeIdentifier(configContaienr.name());
1146 mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
1147 return builder.build();
1148 } else if (configDataNode instanceof ChoiceNode configChoice) {
1149 final var builder = ImmutableNodes.newChoiceBuilder().withNodeIdentifier(configChoice.name());
1150 mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
1151 return builder.build();
1152 } else if (configDataNode instanceof LeafNode configLeaf) {
1153 // config trumps oper
1155 } else if (configDataNode instanceof UserLeafSetNode) {
1156 final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
1157 final var builder = ImmutableNodes.<Object>newUserLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
1158 mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
1159 return builder.build();
1160 } else if (configDataNode instanceof SystemLeafSetNode) {
1161 final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
1162 final var builder = ImmutableNodes.<Object>newSystemLeafSetBuilder()
1163 .withNodeIdentifier(configLeafSet.name());
1164 mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
1165 return builder.build();
1166 } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
1167 // config trumps oper
1169 } else if (configDataNode instanceof UnkeyedListNode configList) {
1170 final var builder = ImmutableNodes.newUnkeyedListBuilder().withNodeIdentifier(configList.name());
1171 mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
1172 return builder.build();
1173 } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
1174 final var builder = ImmutableNodes.newUnkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
1175 mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
1176 return builder.build();
1178 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
1183 * Map value from container node to builder.
1185 * @param configData collection of config data nodes
1186 * @param stateData collection of state data nodes
1187 * @param builder builder
1189 private static <T extends NormalizedNode> void mapValueToBuilder(
1190 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
1191 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1192 final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1193 final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1195 // merge config and state data of children with different identifiers
1196 mapDataToBuilder(configMap, stateMap, builder);
1198 // merge config and state data of children with the same identifiers
1199 mergeDataToBuilder(configMap, stateMap, builder);
1203 * Map data with different identifiers to builder. Data with different identifiers can be just added
1204 * as childs to parent node.
1206 * @param configMap map of config data nodes
1207 * @param stateMap map of state data nodes
1208 * @param builder - builder
1210 private static <T extends NormalizedNode> void mapDataToBuilder(
1211 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1212 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1213 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
1214 y -> builder.addChild(y.getValue()));
1215 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
1216 y -> builder.addChild(y.getValue()));
1220 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
1221 * go one level down with {@code prepareData} method.
1223 * @param configMap immutable config data
1224 * @param stateMap immutable state data
1225 * @param builder - builder
1227 @SuppressWarnings("unchecked")
1228 private static <T extends NormalizedNode> void mergeDataToBuilder(
1229 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1230 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1231 // it is enough to process only config data because operational contains the same data
1232 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1233 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1236 public @NonNull RestconfFuture<FormattableBody> operationsGET() {
1237 return operations.httpGET();
1240 public @NonNull RestconfFuture<FormattableBody> operationsGET(final ApiPath apiPath) {
1241 return operations.httpGET(apiPath);
1244 public @NonNull RestconfFuture<InvokeResult> operationsPOST(final URI restconfURI, final ApiPath apiPath,
1245 final Map<String, String> queryParameters, final OperationInputBody body) {
1248 path = pathNormalizer.normalizeRpcPath(apiPath);
1249 } catch (RestconfDocumentedException e) {
1250 return RestconfFuture.failed(e);
1253 final InvokeParams params;
1255 params = InvokeParams.ofQueryParameters(queryParameters);
1256 } catch (IllegalArgumentException e) {
1257 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
1258 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
1261 final ContainerNode data;
1263 data = body.toContainerNode(path);
1264 } catch (IOException e) {
1265 LOG.debug("Error reading input", e);
1266 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1267 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1270 final var type = path.rpc().argument();
1271 final var local = localRpcs.get(type);
1272 if (local != null) {
1273 return local.invoke(restconfURI, new OperationInput(path, data))
1274 .transform(output -> outputToInvokeResult(path, params, output));
1276 if (rpcService == null) {
1277 LOG.debug("RPC invocation is not available");
1278 return RestconfFuture.failed(new RestconfDocumentedException("RPC invocation is not available",
1279 ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED));
1282 final var ret = new SettableRestconfFuture<InvokeResult>();
1283 Futures.addCallback(rpcService.invokeRpc(type, data), new FutureCallback<DOMRpcResult>() {
1285 public void onSuccess(final DOMRpcResult response) {
1286 final var errors = response.errors();
1287 if (errors.isEmpty()) {
1288 ret.set(outputToInvokeResult(path, params, response.value()));
1290 LOG.debug("RPC invocation reported {}", response.errors());
1291 ret.setFailure(new RestconfDocumentedException("RPC implementation reported errors", null,
1292 response.errors()));
1297 public void onFailure(final Throwable cause) {
1298 LOG.debug("RPC invocation failed, cause");
1299 if (cause instanceof RestconfDocumentedException ex) {
1302 // TODO: YangNetconfErrorAware if we ever get into a broader invocation scope
1303 ret.setFailure(new RestconfDocumentedException(cause,
1304 new RestconfError(ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage())));
1307 }, MoreExecutors.directExecutor());
1311 private static @NonNull InvokeResult outputToInvokeResult(final @NonNull OperationPath path,
1312 final @NonNull InvokeParams params, final @Nullable ContainerNode value) {
1313 return value == null || value.isEmpty() ? InvokeResult.EMPTY
1314 : new InvokeResult(new OperationOutputBody(params, path, value));
1317 public @NonNull RestconfFuture<CharSource> resolveSource(final SourceIdentifier source,
1318 final Class<? extends SourceRepresentation> representation) {
1319 final var src = requireNonNull(source);
1320 if (YangTextSource.class.isAssignableFrom(representation)) {
1321 if (sourceProvider != null) {
1322 final var ret = new SettableRestconfFuture<CharSource>();
1323 Futures.addCallback(sourceProvider.getYangTexttSource(src), new FutureCallback<>() {
1325 public void onSuccess(final YangTextSource result) {
1330 public void onFailure(final Throwable cause) {
1331 ret.setFailure(cause instanceof RestconfDocumentedException e ? e
1332 : new RestconfDocumentedException(cause.getMessage(), ErrorType.RPC,
1333 ErrorTag.OPERATION_FAILED, cause));
1335 }, MoreExecutors.directExecutor());
1338 return exportSource(modelContext(), src, YangCharSource::new, YangCharSource::new);
1340 if (YinTextSource.class.isAssignableFrom(representation)) {
1341 return exportSource(modelContext(), src, YinCharSource.OfModule::new, YinCharSource.OfSubmodule::new);
1343 return RestconfFuture.failed(new RestconfDocumentedException(
1344 "Unsupported source representation " + representation.getName()));
1347 private static @NonNull RestconfFuture<CharSource> exportSource(final EffectiveModelContext modelContext,
1348 final SourceIdentifier source, final Function<ModuleEffectiveStatement, CharSource> moduleCtor,
1349 final BiFunction<ModuleEffectiveStatement, SubmoduleEffectiveStatement, CharSource> submoduleCtor) {
1350 // If the source identifies a module, things are easy
1351 final var name = source.name().getLocalName();
1352 final var optRevision = Optional.ofNullable(source.revision());
1353 final var optModule = modelContext.findModule(name, optRevision);
1354 if (optModule.isPresent()) {
1355 return RestconfFuture.of(moduleCtor.apply(optModule.orElseThrow().asEffectiveStatement()));
1358 // The source could be a submodule, which we need to hunt down
1359 for (var module : modelContext.getModules()) {
1360 for (var submodule : module.getSubmodules()) {
1361 if (name.equals(submodule.getName()) && optRevision.equals(submodule.getRevision())) {
1362 return RestconfFuture.of(submoduleCtor.apply(module.asEffectiveStatement(),
1363 submodule.asEffectiveStatement()));
1368 final var sb = new StringBuilder().append("Source ").append(source.name().getLocalName());
1369 optRevision.ifPresent(rev -> sb.append('@').append(rev));
1370 sb.append(" not found");
1371 return RestconfFuture.failed(new RestconfDocumentedException(sb.toString(),
1372 ErrorType.APPLICATION, ErrorTag.DATA_MISSING));
1375 public final @NonNull RestconfFuture<? extends DataPostResult> dataPOST(final ApiPath apiPath,
1376 final DataPostBody body, final Map<String, String> queryParameters) {
1377 if (apiPath.steps().isEmpty()) {
1378 return dataCreatePOST(body.toResource(), queryParameters);
1380 final InstanceReference path;
1382 path = pathNormalizer.normalizeDataOrActionPath(apiPath);
1383 } catch (RestconfDocumentedException e) {
1384 return RestconfFuture.failed(e);
1386 if (path instanceof Data dataPath) {
1387 try (var resourceBody = body.toResource()) {
1388 return dataCreatePOST(dataPath, resourceBody, queryParameters);
1391 if (path instanceof Action actionPath) {
1392 try (var inputBody = body.toOperationInput()) {
1393 return dataInvokePOST(actionPath, inputBody, queryParameters);
1396 // Note: this should never happen
1397 // FIXME: we should be able to eliminate this path with Java 21+ pattern matching
1398 return RestconfFuture.failed(new RestconfDocumentedException("Unhandled path " + path));
1401 public @NonNull RestconfFuture<CreateResource> dataCreatePOST(final ChildBody body,
1402 final Map<String, String> queryParameters) {
1403 return dataCreatePOST(new DatabindPath.Data(databind), body, queryParameters);
1406 private @NonNull RestconfFuture<CreateResource> dataCreatePOST(final DatabindPath.Data path, final ChildBody body,
1407 final Map<String, String> queryParameters) {
1408 final Insert insert;
1410 insert = Insert.ofQueryParameters(path.databind(), queryParameters);
1411 } catch (IllegalArgumentException e) {
1412 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
1413 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
1416 final var payload = body.toPayload(path);
1417 return postData(concat(path.instance(), payload.prefix()), payload.body(), insert);
1420 private static YangInstanceIdentifier concat(final YangInstanceIdentifier parent, final List<PathArgument> args) {
1422 for (var arg : args) {
1423 ret = ret.node(arg);
1428 private @NonNull RestconfFuture<InvokeResult> dataInvokePOST(final @NonNull Action path,
1429 final @NonNull OperationInputBody body, final Map<String, String> queryParameters) {
1430 final InvokeParams params;
1432 params = InvokeParams.ofQueryParameters(queryParameters);
1433 } catch (IllegalArgumentException e) {
1434 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
1435 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
1438 final ContainerNode input;
1440 input = body.toContainerNode(path);
1441 } catch (IOException e) {
1442 LOG.debug("Error reading input", e);
1443 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1444 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1447 if (actionService == null) {
1448 return RestconfFuture.failed(new RestconfDocumentedException("DOMActionService is missing."));
1451 return dataInvokePOST(actionService, path, input)
1452 .transform(result -> outputToInvokeResult(path, params, result.getOutput().orElse(null)));
1456 * Invoke Action via ActionServiceHandler.
1458 * @param input input data
1459 * @param yangIId invocation context
1460 * @param schemaPath schema path of data
1461 * @param actionService action service to invoke action
1462 * @return {@link DOMActionResult}
1464 private static RestconfFuture<DOMActionResult> dataInvokePOST(final DOMActionService actionService,
1465 final Action path, final @NonNull ContainerNode input) {
1466 final var ret = new SettableRestconfFuture<DOMActionResult>();
1468 Futures.addCallback(actionService.invokeAction(
1469 path.inference().toSchemaInferenceStack().toSchemaNodeIdentifier(),
1470 DOMDataTreeIdentifier.of(LogicalDatastoreType.OPERATIONAL, path.instance()), input),
1471 new FutureCallback<DOMActionResult>() {
1473 public void onSuccess(final DOMActionResult result) {
1474 final var errors = result.getErrors();
1475 LOG.debug("InvokeAction Error Message {}", errors);
1476 if (errors.isEmpty()) {
1479 ret.setFailure(new RestconfDocumentedException("InvokeAction Error Message ", null, errors));
1484 public void onFailure(final Throwable cause) {
1485 if (cause instanceof DOMActionException) {
1486 ret.set(new SimpleDOMActionResult(List.of(RpcResultBuilder.newError(
1487 ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage()))));
1488 } else if (cause instanceof RestconfDocumentedException e) {
1490 } else if (cause instanceof CancellationException) {
1491 ret.setFailure(new RestconfDocumentedException("Action cancelled while executing",
1492 ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, cause));
1494 ret.setFailure(new RestconfDocumentedException("Invocation failed", cause));
1497 }, MoreExecutors.directExecutor());