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.nb.rfc8040.Insert;
62 import org.opendaylight.restconf.nb.rfc8040.legacy.ErrorTags;
63 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
64 import org.opendaylight.restconf.nb.rfc8040.legacy.WriterParameters;
65 import org.opendaylight.restconf.server.api.ChildBody;
66 import org.opendaylight.restconf.server.api.ConfigurationMetadata;
67 import org.opendaylight.restconf.server.api.CreateResourceResult;
68 import org.opendaylight.restconf.server.api.DataGetParams;
69 import org.opendaylight.restconf.server.api.DataGetResult;
70 import org.opendaylight.restconf.server.api.DataPatchResult;
71 import org.opendaylight.restconf.server.api.DataPostBody;
72 import org.opendaylight.restconf.server.api.DataPostResult;
73 import org.opendaylight.restconf.server.api.DataPutResult;
74 import org.opendaylight.restconf.server.api.DataYangPatchParams;
75 import org.opendaylight.restconf.server.api.DataYangPatchResult;
76 import org.opendaylight.restconf.server.api.DatabindContext;
77 import org.opendaylight.restconf.server.api.DatabindPath;
78 import org.opendaylight.restconf.server.api.DatabindPath.Action;
79 import org.opendaylight.restconf.server.api.DatabindPath.Data;
80 import org.opendaylight.restconf.server.api.DatabindPath.InstanceReference;
81 import org.opendaylight.restconf.server.api.DatabindPath.OperationPath;
82 import org.opendaylight.restconf.server.api.DatabindPath.Rpc;
83 import org.opendaylight.restconf.server.api.InvokeParams;
84 import org.opendaylight.restconf.server.api.InvokeResult;
85 import org.opendaylight.restconf.server.api.OperationInputBody;
86 import org.opendaylight.restconf.server.api.PatchBody;
87 import org.opendaylight.restconf.server.api.PatchStatusContext;
88 import org.opendaylight.restconf.server.api.PatchStatusEntity;
89 import org.opendaylight.restconf.server.api.QueryParams;
90 import org.opendaylight.restconf.server.api.ResourceBody;
91 import org.opendaylight.restconf.server.spi.ApiPathCanonizer;
92 import org.opendaylight.restconf.server.spi.ApiPathNormalizer;
93 import org.opendaylight.restconf.server.spi.DefaultResourceContext;
94 import org.opendaylight.restconf.server.spi.HttpGetResource;
95 import org.opendaylight.restconf.server.spi.OperationInput;
96 import org.opendaylight.restconf.server.spi.OperationOutputBody;
97 import org.opendaylight.restconf.server.spi.OperationsResource;
98 import org.opendaylight.restconf.server.spi.RpcImplementation;
99 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.with.defaults.rev110601.WithDefaultsMode;
100 import org.opendaylight.yangtools.yang.common.Empty;
101 import org.opendaylight.yangtools.yang.common.ErrorTag;
102 import org.opendaylight.yangtools.yang.common.ErrorType;
103 import org.opendaylight.yangtools.yang.common.QName;
104 import org.opendaylight.yangtools.yang.common.QNameModule;
105 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
106 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
107 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
108 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
109 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
110 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
111 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
112 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
113 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
114 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
115 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
116 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
117 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
118 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
119 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
120 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
121 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
122 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
123 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
124 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
125 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
126 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
127 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
128 import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
129 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
130 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
131 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
132 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
133 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
134 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
135 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
136 import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
137 import org.opendaylight.yangtools.yang.model.api.source.SourceRepresentation;
138 import org.opendaylight.yangtools.yang.model.api.source.YangTextSource;
139 import org.opendaylight.yangtools.yang.model.api.source.YinTextSource;
140 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
141 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleEffectiveStatement;
142 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
143 import org.slf4j.Logger;
144 import org.slf4j.LoggerFactory;
147 * Baseline execution strategy for various RESTCONF operations.
149 * @see NetconfRestconfStrategy
150 * @see MdsalRestconfStrategy
152 // FIXME: it seems the first three operations deal with lifecycle of a transaction, while others invoke various
153 // operations. This should be handled through proper allocation indirection.
154 public abstract class RestconfStrategy {
156 public record StrategyAndPath(RestconfStrategy strategy, Data path) {
157 public StrategyAndPath {
158 requireNonNull(strategy);
159 requireNonNull(path);
164 * Result of a partial {@link ApiPath} lookup for the purposes of supporting {@code yang-ext:mount}-delimited mount
165 * points with possible nesting.
167 * @param strategy the strategy to use
168 * @param tail the {@link ApiPath} tail to use with the strategy
171 public record StrategyAndTail(RestconfStrategy strategy, ApiPath tail) {
172 public StrategyAndTail {
173 requireNonNull(strategy);
174 requireNonNull(tail);
178 private static final Logger LOG = LoggerFactory.getLogger(RestconfStrategy.class);
179 private static final @NonNull DataPutResult PUT_CREATED = new DataPutResult(true);
180 private static final @NonNull DataPutResult PUT_REPLACED = new DataPutResult(false);
181 private static final @NonNull DataPatchResult PATCH_EMPTY = new DataPatchResult();
183 private final @NonNull ImmutableMap<QName, RpcImplementation> localRpcs;
184 private final @NonNull ApiPathNormalizer pathNormalizer;
185 private final @NonNull DatabindContext databind;
186 private final YangTextSourceExtension sourceProvider;
187 private final DOMMountPointService mountPointService;
188 private final DOMActionService actionService;
189 private final DOMRpcService rpcService;
190 private final HttpGetResource operations;
192 RestconfStrategy(final DatabindContext databind, final ImmutableMap<QName, RpcImplementation> localRpcs,
193 final @Nullable DOMRpcService rpcService, final @Nullable DOMActionService actionService,
194 final @Nullable YangTextSourceExtension sourceProvider,
195 final @Nullable DOMMountPointService mountPointService) {
196 this.databind = requireNonNull(databind);
197 this.localRpcs = requireNonNull(localRpcs);
198 this.rpcService = rpcService;
199 this.actionService = actionService;
200 this.sourceProvider = sourceProvider;
201 this.mountPointService = mountPointService;
202 pathNormalizer = new ApiPathNormalizer(databind);
203 operations = new OperationsResource(pathNormalizer);
206 public final @NonNull StrategyAndPath resolveStrategyPath(final ApiPath path) {
207 final var andTail = resolveStrategy(path);
208 final var strategy = andTail.strategy();
209 return new StrategyAndPath(strategy, strategy.pathNormalizer.normalizeDataPath(andTail.tail()));
213 * Resolve any and all {@code yang-ext:mount} to the target {@link StrategyAndTail}.
215 * @param path {@link ApiPath} to resolve
216 * @return A strategy and the remaining path
217 * @throws NullPointerException if {@code path} is {@code null}
219 public final @NonNull StrategyAndTail resolveStrategy(final ApiPath path) {
220 var mount = path.indexOf("yang-ext", "mount");
222 return new StrategyAndTail(this, path);
224 if (mountPointService == null) {
225 throw new RestconfDocumentedException("Mount point service is not available",
226 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
228 final var mountPath = path.subPath(0, mount);
229 final var dataPath = pathNormalizer.normalizeDataPath(path.subPath(0, mount));
230 final var mountPoint = mountPointService.getMountPoint(dataPath.instance())
231 .orElseThrow(() -> new RestconfDocumentedException("Mount point '" + mountPath + "' does not exist",
232 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
234 return createStrategy(mountPath, mountPoint).resolveStrategy(path.subPath(mount + 1));
237 private static @NonNull RestconfStrategy createStrategy(final ApiPath mountPath, final DOMMountPoint mountPoint) {
238 final var mountSchemaService = mountPoint.getService(DOMSchemaService.class)
239 .orElseThrow(() -> new RestconfDocumentedException(
240 "Mount point '" + mountPath + "' does not expose DOMSchemaService",
241 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
242 final var mountModelContext = mountSchemaService.getGlobalContext();
243 if (mountModelContext == null) {
244 throw new RestconfDocumentedException("Mount point '" + mountPath + "' does not have any models",
245 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT);
247 final var mountDatabind = DatabindContext.ofModel(mountModelContext);
248 final var mountPointService = mountPoint.getService(DOMMountPointService.class).orElse(null);
249 final var rpcService = mountPoint.getService(DOMRpcService.class).orElse(null);
250 final var actionService = mountPoint.getService(DOMActionService.class).orElse(null);
251 final var sourceProvider = mountPoint.getService(DOMSchemaService.class)
252 .flatMap(schema -> Optional.ofNullable(schema.extension(YangTextSourceExtension.class)))
255 final var netconfService = mountPoint.getService(NetconfDataTreeService.class);
256 if (netconfService.isPresent()) {
257 return new NetconfRestconfStrategy(mountDatabind, netconfService.orElseThrow(), rpcService, actionService,
258 sourceProvider, mountPointService);
260 final var dataBroker = mountPoint.getService(DOMDataBroker.class);
261 if (dataBroker.isPresent()) {
262 return new MdsalRestconfStrategy(mountDatabind, dataBroker.orElseThrow(), ImmutableMap.of(), rpcService,
263 actionService, sourceProvider, mountPointService);
265 LOG.warn("Mount point {} does not expose a suitable access interface", mountPath);
266 throw new RestconfDocumentedException("Could not find a supported access interface in mount point",
267 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, mountPoint.getIdentifier());
270 public final @NonNull DatabindContext databind() {
274 public final @NonNull EffectiveModelContext modelContext() {
275 return databind.modelContext();
279 * Lock the entire datastore.
281 * @return A {@link RestconfTransaction}. This transaction needs to be either committed or canceled before doing
284 abstract RestconfTransaction prepareWriteExecution();
287 * Read data from the datastore.
289 * @param store the logical data store which should be modified
290 * @param path the data object path
291 * @return a ListenableFuture containing the result of the read
293 abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path);
296 * Check if data already exists in the configuration datastore.
298 * @param path the data object path
299 * @return a ListenableFuture containing the result of the check
301 // FIXME: this method should be hosted in RestconfTransaction
302 // FIXME: this method should only be needed in MdsalRestconfStrategy
303 abstract ListenableFuture<Boolean> exists(YangInstanceIdentifier path);
306 final @NonNull RestconfFuture<DataPatchResult> merge(final YangInstanceIdentifier path, final NormalizedNode data) {
307 final var ret = new SettableRestconfFuture<DataPatchResult>();
308 merge(ret, requireNonNull(path), requireNonNull(data));
312 private void merge(final @NonNull SettableRestconfFuture<DataPatchResult> future,
313 final @NonNull YangInstanceIdentifier path, final @NonNull NormalizedNode data) {
314 final var tx = prepareWriteExecution();
315 // FIXME: this method should be further specialized to eliminate this call -- it is only needed for MD-SAL
316 tx.ensureParentsByMerge(path);
317 tx.merge(path, data);
318 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
320 public void onSuccess(final CommitInfo result) {
321 // TODO: extract details once CommitInfo can communicate them
322 future.set(PATCH_EMPTY);
326 public void onFailure(final Throwable cause) {
327 future.setFailure(TransactionUtil.decodeException(cause, "MERGE", path, modelContext()));
329 }, MoreExecutors.directExecutor());
332 public @NonNull RestconfFuture<DataPutResult> dataPUT(final ApiPath apiPath, final QueryParams params,
333 final ResourceBody body) {
336 path = pathNormalizer.normalizeDataPath(apiPath);
337 } catch (RestconfDocumentedException e) {
338 return RestconfFuture.failed(e);
343 insert = Insert.of(databind, params);
344 } catch (IllegalArgumentException e) {
345 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
346 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
348 final NormalizedNode data;
350 data = body.toNormalizedNode(path);
351 } catch (RestconfDocumentedException e) {
352 return RestconfFuture.failed(e);
354 return putData(path.instance(), data, insert);
358 * Check mount point and prepare variables for put data to DS.
360 * @param path path of data
362 * @param insert {@link Insert}
363 * @return A {@link DataPutResult}
365 public final @NonNull RestconfFuture<DataPutResult> putData(final YangInstanceIdentifier path,
366 final NormalizedNode data, final @Nullable Insert insert) {
367 final var exists = TransactionUtil.syncAccess(exists(path), path);
369 final ListenableFuture<? extends CommitInfo> commitFuture;
370 if (insert != null) {
371 final var parentPath = path.coerceParent();
372 checkListAndOrderedType(parentPath);
373 commitFuture = insertAndCommitPut(path, data, insert, parentPath);
375 commitFuture = replaceAndCommit(prepareWriteExecution(), path, data);
378 final var ret = new SettableRestconfFuture<DataPutResult>();
380 Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
382 public void onSuccess(final CommitInfo result) {
383 ret.set(exists ? PUT_REPLACED : PUT_CREATED);
387 public void onFailure(final Throwable cause) {
388 ret.setFailure(TransactionUtil.decodeException(cause, "PUT", path, modelContext()));
390 }, MoreExecutors.directExecutor());
395 private ListenableFuture<? extends CommitInfo> insertAndCommitPut(final YangInstanceIdentifier path,
396 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parentPath) {
397 final var tx = prepareWriteExecution();
399 return switch (insert.insert()) {
401 final var readData = tx.readList(parentPath);
402 if (readData == null || readData.isEmpty()) {
403 yield replaceAndCommit(tx, path, data);
405 tx.remove(parentPath);
406 tx.replace(path, data);
407 tx.replace(parentPath, readData);
410 case LAST -> replaceAndCommit(tx, path, data);
412 final var readData = tx.readList(parentPath);
413 if (readData == null || readData.isEmpty()) {
414 yield replaceAndCommit(tx, path, data);
416 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
420 final var readData = tx.readList(parentPath);
421 if (readData == null || readData.isEmpty()) {
422 yield replaceAndCommit(tx, path, data);
424 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
430 private void insertWithPointPut(final RestconfTransaction tx, final YangInstanceIdentifier path,
431 final NormalizedNode data, final @NonNull PathArgument pointArg, final NormalizedNodeContainer<?> readList,
432 final boolean before) {
433 tx.remove(path.getParent());
435 int lastItemPosition = 0;
436 for (var nodeChild : readList.body()) {
437 if (nodeChild.name().equals(pointArg)) {
446 int lastInsertedPosition = 0;
447 final var emptySubtree = fromInstanceId(modelContext(), path.getParent());
448 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
449 for (var nodeChild : readList.body()) {
450 if (lastInsertedPosition == lastItemPosition) {
451 tx.replace(path, data);
453 final var childPath = path.coerceParent().node(nodeChild.name());
454 tx.replace(childPath, nodeChild);
455 lastInsertedPosition++;
458 // In case we are inserting after last element
460 if (lastInsertedPosition == lastItemPosition) {
461 tx.replace(path, data);
466 private static ListenableFuture<? extends CommitInfo> replaceAndCommit(final RestconfTransaction tx,
467 final YangInstanceIdentifier path, final NormalizedNode data) {
468 tx.replace(path, data);
472 private DataSchemaNode checkListAndOrderedType(final YangInstanceIdentifier path) {
473 // FIXME: we have this available in InstanceIdentifierContext
474 final var dataSchemaNode = databind.schemaTree().findChild(path).orElseThrow().dataSchemaNode();
476 final String message;
477 if (dataSchemaNode instanceof ListSchemaNode listSchema) {
478 if (listSchema.isUserOrdered()) {
481 message = "Insert parameter can be used only with ordered-by user list.";
482 } else if (dataSchemaNode instanceof LeafListSchemaNode leafListSchema) {
483 if (leafListSchema.isUserOrdered()) {
484 return leafListSchema;
486 message = "Insert parameter can be used only with ordered-by user leaf-list.";
488 message = "Insert parameter can be used only with list or leaf-list";
490 throw new RestconfDocumentedException(message, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
494 * Check mount point and prepare variables for post data.
498 * @param insert {@link Insert}
499 * @return A {@link RestconfFuture}
501 public final @NonNull RestconfFuture<CreateResourceResult> postData(final YangInstanceIdentifier path,
502 final NormalizedNode data, final @Nullable Insert insert) {
503 final ListenableFuture<? extends CommitInfo> future;
504 if (insert != null) {
505 checkListAndOrderedType(path);
506 future = insertAndCommitPost(path, data, insert);
508 future = createAndCommit(prepareWriteExecution(), path, data);
511 final var ret = new SettableRestconfFuture<CreateResourceResult>();
512 Futures.addCallback(future, new FutureCallback<CommitInfo>() {
514 public void onSuccess(final CommitInfo result) {
515 ret.set(new CreateResourceResult(new ApiPathCanonizer(databind).dataToApiPath(
516 data instanceof MapNode mapData && !mapData.isEmpty()
517 ? path.node(mapData.body().iterator().next().name()) : path)));
521 public void onFailure(final Throwable cause) {
522 ret.setFailure(TransactionUtil.decodeException(cause, "POST", path, modelContext()));
525 }, MoreExecutors.directExecutor());
529 private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
530 final NormalizedNode data, final @NonNull Insert insert) {
531 final var tx = prepareWriteExecution();
533 return switch (insert.insert()) {
535 final var readData = tx.readList(path);
536 if (readData == null || readData.isEmpty()) {
537 tx.replace(path, data);
539 checkListDataDoesNotExist(path, data);
541 tx.replace(path, data);
542 tx.replace(path, readData);
546 case LAST -> createAndCommit(tx, path, data);
548 final var readData = tx.readList(path);
549 if (readData == null || readData.isEmpty()) {
550 tx.replace(path, data);
552 checkListDataDoesNotExist(path, data);
553 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
558 final var readData = tx.readList(path);
559 if (readData == null || readData.isEmpty()) {
560 tx.replace(path, data);
562 checkListDataDoesNotExist(path, data);
563 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
571 * Merge data into the configuration datastore, as outlined in
572 * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040 section 4.6.1</a>.
574 * @param apiPath Path to merge
575 * @param body Data to merge
576 * @return A {@link RestconfFuture}
577 * @throws NullPointerException if any argument is {@code null}
579 public final @NonNull RestconfFuture<DataPatchResult> dataPATCH(final ApiPath apiPath, final ResourceBody body) {
582 path = pathNormalizer.normalizeDataPath(apiPath);
583 } catch (RestconfDocumentedException e) {
584 return RestconfFuture.failed(e);
587 final NormalizedNode data;
589 data = body.toNormalizedNode(path);
590 } catch (RestconfDocumentedException e) {
591 return RestconfFuture.failed(e);
594 return merge(path.instance(), data);
597 public final @NonNull RestconfFuture<DataYangPatchResult> dataPATCH(final ApiPath apiPath, final QueryParams params,
598 final PatchBody body) {
599 final DataYangPatchParams patchParams;
601 patchParams = DataYangPatchParams.of(params);
602 } catch (IllegalArgumentException e) {
603 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
604 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
609 path = pathNormalizer.normalizeDataPath(apiPath);
610 } catch (RestconfDocumentedException e) {
611 return RestconfFuture.failed(e);
614 final PatchContext patch;
616 patch = body.toPatchContext(new DefaultResourceContext(path));
617 } catch (IOException e) {
618 LOG.debug("Error parsing YANG Patch input", e);
619 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
620 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
622 return patchData(patchParams, patch);
626 * Process edit operations of one {@link PatchContext}.
628 * @param patch Patch context to be processed
629 * @return {@link PatchStatusContext}
632 public final @NonNull RestconfFuture<DataYangPatchResult> patchData(final DataYangPatchParams params,
633 final PatchContext patch) {
634 final var editCollection = new ArrayList<PatchStatusEntity>();
635 final var tx = prepareWriteExecution();
637 boolean noError = true;
638 for (var patchEntity : patch.entities()) {
640 final var targetNode = patchEntity.getTargetNode();
641 final var editId = patchEntity.getEditId();
643 switch (patchEntity.getOperation()) {
646 tx.create(targetNode, patchEntity.getNode());
647 editCollection.add(new PatchStatusEntity(editId, true, null));
648 } catch (RestconfDocumentedException e) {
649 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
655 tx.delete(targetNode);
656 editCollection.add(new PatchStatusEntity(editId, true, null));
657 } catch (RestconfDocumentedException e) {
658 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
664 tx.ensureParentsByMerge(targetNode);
665 tx.merge(targetNode, patchEntity.getNode());
666 editCollection.add(new PatchStatusEntity(editId, true, null));
667 } catch (RestconfDocumentedException e) {
668 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
674 tx.replace(targetNode, patchEntity.getNode());
675 editCollection.add(new PatchStatusEntity(editId, true, null));
676 } catch (RestconfDocumentedException e) {
677 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
683 tx.remove(targetNode);
684 editCollection.add(new PatchStatusEntity(editId, true, null));
685 } catch (RestconfDocumentedException e) {
686 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
691 editCollection.add(new PatchStatusEntity(editId, false, List.of(
692 new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
693 "Not supported Yang Patch operation"))));
702 final var ret = new SettableRestconfFuture<DataYangPatchResult>();
706 ret.set(new DataYangPatchResult(params,
707 new PatchStatusContext(databind(), patch.patchId(), List.copyOf(editCollection), false, null)));
711 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
713 public void onSuccess(final CommitInfo result) {
714 ret.set(new DataYangPatchResult(params,
715 new PatchStatusContext(databind(), patch.patchId(), List.copyOf(editCollection), true, null)));
719 public void onFailure(final Throwable cause) {
720 // if errors occurred during transaction commit then patch failed and global errors are reported
721 ret.set(new DataYangPatchResult(params,
722 new PatchStatusContext(databind(), patch.patchId(), List.copyOf(editCollection), false,
723 TransactionUtil.decodeException(cause, "PATCH", null, modelContext()).getErrors())));
725 }, MoreExecutors.directExecutor());
730 private static void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
731 final NormalizedNode data, final PathArgument pointArg, final NormalizedNodeContainer<?> readList,
732 final boolean before) {
735 int lastItemPosition = 0;
736 for (var nodeChild : readList.body()) {
737 if (nodeChild.name().equals(pointArg)) {
746 int lastInsertedPosition = 0;
747 for (var nodeChild : readList.body()) {
748 if (lastInsertedPosition == lastItemPosition) {
749 tx.replace(path, data);
751 tx.replace(path.node(nodeChild.name()), nodeChild);
752 lastInsertedPosition++;
755 // In case we are inserting after last element
757 if (lastInsertedPosition == lastItemPosition) {
758 tx.replace(path, data);
763 private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
764 final YangInstanceIdentifier path, final NormalizedNode data) {
766 tx.create(path, data);
767 } catch (RestconfDocumentedException e) {
768 // close transaction if any and pass exception further
777 * Check if child items do NOT already exists in List at specified {@code path}.
779 * @param data Data to be checked
780 * @param path Path to be checked
781 * @throws RestconfDocumentedException if data already exists.
783 private void checkListDataDoesNotExist(final YangInstanceIdentifier path, final NormalizedNode data) {
784 if (data instanceof NormalizedNodeContainer<?> dataNode) {
785 for (final var node : dataNode.body()) {
786 checkItemDoesNotExists(exists(path.node(node.name())), path.node(node.name()));
789 throw new RestconfDocumentedException("Unexpected node type: " + data.getClass().getName());
794 * Check if items do NOT already exists at specified {@code path}.
796 * @param existsFuture if checked data exists
797 * @param path Path to be checked
798 * @throws RestconfDocumentedException if data already exists.
800 static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
801 final YangInstanceIdentifier path) {
802 if (TransactionUtil.syncAccess(existsFuture, path)) {
803 LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
804 throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
810 * Delete data from the configuration datastore. If the data does not exist, this operation will fail, as outlined
811 * in <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.7">RFC8040 section 4.7</a>
813 * @param apiPath Path to delete
814 * @return A {@link RestconfFuture}
815 * @throws NullPointerException if {@code apiPath} is {@code null}
817 @SuppressWarnings("checkstyle:abbreviationAsWordInName")
818 public final @NonNull RestconfFuture<Empty> dataDELETE(final ApiPath apiPath) {
821 path = pathNormalizer.normalizeDataPath(apiPath);
822 } catch (RestconfDocumentedException e) {
823 return RestconfFuture.failed(e);
826 // FIXME: reject empty YangInstanceIdentifier, as datastores may not be deleted
827 final var ret = new SettableRestconfFuture<Empty>();
828 delete(ret, path.instance());
832 abstract void delete(@NonNull SettableRestconfFuture<Empty> future, @NonNull YangInstanceIdentifier path);
834 public final @NonNull RestconfFuture<DataGetResult> dataGET(final ApiPath apiPath, final QueryParams params) {
837 path = pathNormalizer.normalizeDataPath(apiPath);
838 } catch (RestconfDocumentedException e) {
839 return RestconfFuture.failed(e);
842 final DataGetParams getParams;
844 getParams = DataGetParams.of(params);
845 } catch (IllegalArgumentException e) {
846 return RestconfFuture.failed(new RestconfDocumentedException(e,
847 new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, "Invalid GET /data parameters", null,
850 return dataGET(path, getParams);
853 abstract @NonNull RestconfFuture<DataGetResult> dataGET(Data path, DataGetParams params);
855 static final @NonNull RestconfFuture<DataGetResult> completeDataGET(final Inference inference,
856 final WriterParameters writerParams, final @Nullable NormalizedNode node,
857 final @Nullable ConfigurationMetadata metadata) {
859 return RestconfFuture.failed(new RestconfDocumentedException(
860 "Request could not be completed because the relevant data model content does not exist",
861 ErrorType.PROTOCOL, ErrorTag.DATA_MISSING));
864 final var payload = new NormalizedNodePayload(inference, node, writerParams);
865 return RestconfFuture.of(metadata == null ? new DataGetResult(payload)
866 : new DataGetResult(payload, metadata.entityTag(), metadata.lastModified()));
870 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
871 * inside of object {@link RestconfStrategy} provided as a parameter.
873 * @param content type of data to read (config, state, all)
874 * @param path the path to read
875 * @param defaultsMode value of with-defaults parameter
876 * @return {@link NormalizedNode}
878 // FIXME: NETCONF-1155: this method should asynchronous
880 final @Nullable NormalizedNode readData(final @NonNull ContentParam content,
881 final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
882 return switch (content) {
884 // PREPARE STATE DATA NODE
885 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
886 // PREPARE CONFIG DATA NODE
887 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
889 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
890 : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
893 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
894 yield defaultsMode == null ? read
895 : prepareDataByParamWithDef(read, path, defaultsMode.mode());
897 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
901 private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
902 final YangInstanceIdentifier path) {
903 return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
906 final NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
907 final WithDefaultsMode defaultsMode) {
908 final boolean trim = switch (defaultsMode) {
910 case Explicit -> false;
911 case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
912 "Unsupported with-defaults value " + defaultsMode.getName());
915 // FIXME: we have this readily available in InstanceIdentifierContext
916 final var ctxNode = databind.schemaTree().findChild(path).orElseThrow();
917 if (readData instanceof ContainerNode container) {
918 final var builder = ImmutableNodes.newContainerBuilder().withNodeIdentifier(container.name());
919 buildCont(builder, container.body(), ctxNode, trim);
920 return builder.build();
921 } else if (readData instanceof MapEntryNode mapEntry) {
922 if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
923 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
926 final var builder = ImmutableNodes.newMapEntryBuilder().withNodeIdentifier(mapEntry.name());
927 buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
928 return builder.build();
930 throw new IllegalStateException("Unhandled data contract " + readData.contract());
934 private static void buildMapEntryBuilder(
935 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
936 final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
937 final boolean trim, final List<QName> keys) {
938 for (var child : children) {
939 final var childCtx = getChildContext(ctxNode, child);
941 if (child instanceof ContainerNode container) {
942 appendContainer(builder, container, childCtx, trim);
943 } else if (child instanceof MapNode map) {
944 appendMap(builder, map, childCtx, trim);
945 } else if (child instanceof LeafNode<?> leaf) {
946 appendLeaf(builder, leaf, childCtx, trim, keys);
948 // FIXME: we should never hit this, throw an ISE if this ever happens
949 LOG.debug("Ignoring unhandled child contract {}", child.contract());
954 private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
955 final DataSchemaContext ctxNode, final boolean trim) {
956 final var childBuilder = ImmutableNodes.newContainerBuilder().withNodeIdentifier(container.name());
957 buildCont(childBuilder, container.body(), ctxNode, trim);
958 builder.withChild(childBuilder.build());
961 private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
962 final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
963 if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
964 throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
967 // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
968 final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
970 // This is a combined check for when we need to emit the leaf.
972 // We always have to emit key leaf values
973 keys.contains(leafSchema.getQName())
974 // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
976 // When data is retrieved with a <with-defaults> parameter equal to
977 // 'trim', data nodes MUST NOT be reported if they contain the schema
978 // default value. Non-configuration data nodes containing the schema
979 // default value MUST NOT be reported.
981 || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
982 // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
983 // grasp what we are doing here... emit only if it matches default ???!!!
984 // FIXME: The WithDefaultsParam.EXPLICIT says:
986 // Data nodes set to the YANG default by the client are reported.
988 // and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
990 // If the "with-defaults" parameter is set to "explicit", then the
991 // server MUST adhere to the default-reporting behavior defined in
992 // Section 3.3 of [RFC6243].
994 // and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
996 // When data is retrieved with a <with-defaults> parameter equal to
997 // 'explicit', a data node that was set by a client to its schema
998 // default value MUST be reported. A conceptual data node that would be
999 // set by the server to the schema default value MUST NOT be reported.
1000 // Non-configuration data nodes containing the schema default value MUST
1003 // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
1004 // This seems to disregard the 'trim = true' case semantics (see above).
1005 // Combining the above, though, these checks are missing the 'non-config' check, which would
1006 // distinguish, but barring that this check is superfluous and results in the wrong semantics.
1007 // Without that input, this really should be covered by the previous case.
1008 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
1009 builder.withChild(leaf);
1013 private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
1014 final DataSchemaContext childCtx, final boolean trim) {
1015 if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
1016 throw new IllegalStateException("Input " + map + " does not match " + childCtx);
1019 final var childBuilder = switch (map.ordering()) {
1020 case SYSTEM -> ImmutableNodes.newSystemMapBuilder();
1021 case USER -> ImmutableNodes.newUserMapBuilder();
1023 buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
1024 listSchema.getKeyDefinition());
1025 builder.withChild(childBuilder.build());
1028 private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
1029 final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
1030 final List<@NonNull QName> keys) {
1031 for (var entry : entries) {
1032 final var childCtx = getChildContext(ctxNode, entry);
1033 final var mapEntryBuilder = ImmutableNodes.newMapEntryBuilder().withNodeIdentifier(entry.name());
1034 buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
1035 builder.withChild(mapEntryBuilder.build());
1039 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
1040 final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
1041 for (var child : children) {
1042 final var childCtx = getChildContext(ctxNode, child);
1043 if (child instanceof ContainerNode container) {
1044 appendContainer(builder, container, childCtx, trim);
1045 } else if (child instanceof MapNode map) {
1046 appendMap(builder, map, childCtx, trim);
1047 } else if (child instanceof LeafNode<?> leaf) {
1048 appendLeaf(builder, leaf, childCtx, trim, List.of());
1053 private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
1054 final NormalizedNode child) {
1055 final var childId = child.name();
1056 final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
1058 if (childCtx == null) {
1059 throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
1064 static final NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
1065 final NormalizedNode configDataNode) {
1066 if (stateDataNode == null) {
1067 // No state, return config
1068 return configDataNode;
1070 if (configDataNode == null) {
1071 // No config, return state
1072 return stateDataNode;
1074 // merge config and state
1075 return mergeStateAndConfigData(stateDataNode, configDataNode);
1079 * Merge state and config data into a single NormalizedNode.
1081 * @param stateDataNode data node of state data
1082 * @param configDataNode data node of config data
1083 * @return {@link NormalizedNode}
1085 private static @NonNull NormalizedNode mergeStateAndConfigData(
1086 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
1087 validateNodeMerge(stateDataNode, configDataNode);
1088 // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
1089 if (configDataNode instanceof RpcDefinition) {
1090 return prepareRpcData(configDataNode, stateDataNode);
1092 return prepareData(configDataNode, stateDataNode);
1097 * Validates whether the two NormalizedNodes can be merged.
1099 * @param stateDataNode data node of state data
1100 * @param configDataNode data node of config data
1102 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
1103 final @NonNull NormalizedNode configDataNode) {
1104 final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
1105 final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
1106 if (!moduleOfStateData.equals(moduleOfConfigData)) {
1107 throw new RestconfDocumentedException("Unable to merge data from different modules.");
1112 * Prepare and map data for rpc.
1114 * @param configDataNode data node of config data
1115 * @param stateDataNode data node of state data
1116 * @return {@link NormalizedNode}
1118 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
1119 final @NonNull NormalizedNode stateDataNode) {
1120 final var mapEntryBuilder = ImmutableNodes.newMapEntryBuilder()
1121 .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
1124 mapRpcDataNode(configDataNode, mapEntryBuilder);
1126 mapRpcDataNode(stateDataNode, mapEntryBuilder);
1128 return ImmutableNodes.newSystemMapBuilder()
1129 .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
1130 .addChild(mapEntryBuilder.build())
1135 * Map node to map entry builder.
1137 * @param dataNode data node
1138 * @param mapEntryBuilder builder for mapping data
1140 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
1141 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
1142 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
1146 * Prepare and map all data from DS.
1148 * @param configDataNode data node of config data
1149 * @param stateDataNode data node of state data
1150 * @return {@link NormalizedNode}
1152 @SuppressWarnings("unchecked")
1153 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
1154 final @NonNull NormalizedNode stateDataNode) {
1155 if (configDataNode instanceof UserMapNode configMap) {
1156 final var builder = ImmutableNodes.newUserMapBuilder().withNodeIdentifier(configMap.name());
1157 mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
1158 return builder.build();
1159 } else if (configDataNode instanceof SystemMapNode configMap) {
1160 final var builder = ImmutableNodes.newSystemMapBuilder().withNodeIdentifier(configMap.name());
1161 mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
1162 return builder.build();
1163 } else if (configDataNode instanceof MapEntryNode configEntry) {
1164 final var builder = ImmutableNodes.newMapEntryBuilder().withNodeIdentifier(configEntry.name());
1165 mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
1166 return builder.build();
1167 } else if (configDataNode instanceof ContainerNode configContaienr) {
1168 final var builder = ImmutableNodes.newContainerBuilder().withNodeIdentifier(configContaienr.name());
1169 mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
1170 return builder.build();
1171 } else if (configDataNode instanceof ChoiceNode configChoice) {
1172 final var builder = ImmutableNodes.newChoiceBuilder().withNodeIdentifier(configChoice.name());
1173 mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
1174 return builder.build();
1175 } else if (configDataNode instanceof LeafNode configLeaf) {
1176 // config trumps oper
1178 } else if (configDataNode instanceof UserLeafSetNode) {
1179 final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
1180 final var builder = ImmutableNodes.<Object>newUserLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
1181 mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
1182 return builder.build();
1183 } else if (configDataNode instanceof SystemLeafSetNode) {
1184 final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
1185 final var builder = ImmutableNodes.<Object>newSystemLeafSetBuilder()
1186 .withNodeIdentifier(configLeafSet.name());
1187 mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
1188 return builder.build();
1189 } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
1190 // config trumps oper
1192 } else if (configDataNode instanceof UnkeyedListNode configList) {
1193 final var builder = ImmutableNodes.newUnkeyedListBuilder().withNodeIdentifier(configList.name());
1194 mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
1195 return builder.build();
1196 } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
1197 final var builder = ImmutableNodes.newUnkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
1198 mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
1199 return builder.build();
1201 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
1206 * Map value from container node to builder.
1208 * @param configData collection of config data nodes
1209 * @param stateData collection of state data nodes
1210 * @param builder builder
1212 private static <T extends NormalizedNode> void mapValueToBuilder(
1213 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
1214 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1215 final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1216 final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1218 // merge config and state data of children with different identifiers
1219 mapDataToBuilder(configMap, stateMap, builder);
1221 // merge config and state data of children with the same identifiers
1222 mergeDataToBuilder(configMap, stateMap, builder);
1226 * Map data with different identifiers to builder. Data with different identifiers can be just added
1227 * as childs to parent node.
1229 * @param configMap map of config data nodes
1230 * @param stateMap map of state data nodes
1231 * @param builder - builder
1233 private static <T extends NormalizedNode> void mapDataToBuilder(
1234 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1235 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1236 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
1237 y -> builder.addChild(y.getValue()));
1238 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
1239 y -> builder.addChild(y.getValue()));
1243 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
1244 * go one level down with {@code prepareData} method.
1246 * @param configMap immutable config data
1247 * @param stateMap immutable state data
1248 * @param builder - builder
1250 @SuppressWarnings("unchecked")
1251 private static <T extends NormalizedNode> void mergeDataToBuilder(
1252 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1253 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1254 // it is enough to process only config data because operational contains the same data
1255 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1256 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1260 public RestconfFuture<FormattableBody> operationsGET(final QueryParams params) {
1261 return operations.httpGET(params);
1265 public RestconfFuture<FormattableBody> operationsGET(final ApiPath apiPath, final QueryParams params) {
1266 return operations.httpGET(apiPath, params);
1269 public @NonNull RestconfFuture<InvokeResult> operationsPOST(final URI restconfURI, final ApiPath apiPath,
1270 final QueryParams params, final OperationInputBody body) {
1273 path = pathNormalizer.normalizeRpcPath(apiPath);
1274 } catch (RestconfDocumentedException e) {
1275 return RestconfFuture.failed(e);
1278 final InvokeParams invokeParams;
1280 invokeParams = InvokeParams.of(params);
1281 } catch (IllegalArgumentException e) {
1282 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
1283 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
1286 final ContainerNode data;
1288 data = body.toContainerNode(path);
1289 } catch (IOException e) {
1290 LOG.debug("Error reading input", e);
1291 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1292 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1295 final var type = path.rpc().argument();
1296 final var local = localRpcs.get(type);
1297 if (local != null) {
1298 return local.invoke(restconfURI, new OperationInput(path, data))
1299 .transform(output -> outputToInvokeResult(path, invokeParams, output));
1301 if (rpcService == null) {
1302 LOG.debug("RPC invocation is not available");
1303 return RestconfFuture.failed(new RestconfDocumentedException("RPC invocation is not available",
1304 ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED));
1307 final var ret = new SettableRestconfFuture<InvokeResult>();
1308 Futures.addCallback(rpcService.invokeRpc(type, data), new FutureCallback<DOMRpcResult>() {
1310 public void onSuccess(final DOMRpcResult response) {
1311 final var errors = response.errors();
1312 if (errors.isEmpty()) {
1313 ret.set(outputToInvokeResult(path, invokeParams, response.value()));
1315 LOG.debug("RPC invocation reported {}", response.errors());
1316 ret.setFailure(new RestconfDocumentedException("RPC implementation reported errors", null,
1317 response.errors()));
1322 public void onFailure(final Throwable cause) {
1323 LOG.debug("RPC invocation failed, cause");
1324 if (cause instanceof RestconfDocumentedException ex) {
1327 // TODO: YangNetconfErrorAware if we ever get into a broader invocation scope
1328 ret.setFailure(new RestconfDocumentedException(cause,
1329 new RestconfError(ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage())));
1332 }, MoreExecutors.directExecutor());
1336 private static @NonNull InvokeResult outputToInvokeResult(final @NonNull OperationPath path,
1337 final @NonNull InvokeParams params, final @Nullable ContainerNode value) {
1338 return value == null || value.isEmpty() ? InvokeResult.EMPTY
1339 : new InvokeResult(new OperationOutputBody(params, path, value));
1342 public @NonNull RestconfFuture<CharSource> resolveSource(final SourceIdentifier source,
1343 final Class<? extends SourceRepresentation> representation) {
1344 final var src = requireNonNull(source);
1345 if (YangTextSource.class.isAssignableFrom(representation)) {
1346 if (sourceProvider != null) {
1347 final var ret = new SettableRestconfFuture<CharSource>();
1348 Futures.addCallback(sourceProvider.getYangTexttSource(src), new FutureCallback<>() {
1350 public void onSuccess(final YangTextSource result) {
1355 public void onFailure(final Throwable cause) {
1356 ret.setFailure(cause instanceof RestconfDocumentedException e ? e
1357 : new RestconfDocumentedException(cause.getMessage(), ErrorType.RPC,
1358 ErrorTag.OPERATION_FAILED, cause));
1360 }, MoreExecutors.directExecutor());
1363 return exportSource(modelContext(), src, YangCharSource::new, YangCharSource::new);
1365 if (YinTextSource.class.isAssignableFrom(representation)) {
1366 return exportSource(modelContext(), src, YinCharSource.OfModule::new, YinCharSource.OfSubmodule::new);
1368 return RestconfFuture.failed(new RestconfDocumentedException(
1369 "Unsupported source representation " + representation.getName()));
1372 private static @NonNull RestconfFuture<CharSource> exportSource(final EffectiveModelContext modelContext,
1373 final SourceIdentifier source, final Function<ModuleEffectiveStatement, CharSource> moduleCtor,
1374 final BiFunction<ModuleEffectiveStatement, SubmoduleEffectiveStatement, CharSource> submoduleCtor) {
1375 // If the source identifies a module, things are easy
1376 final var name = source.name().getLocalName();
1377 final var optRevision = Optional.ofNullable(source.revision());
1378 final var optModule = modelContext.findModule(name, optRevision);
1379 if (optModule.isPresent()) {
1380 return RestconfFuture.of(moduleCtor.apply(optModule.orElseThrow().asEffectiveStatement()));
1383 // The source could be a submodule, which we need to hunt down
1384 for (var module : modelContext.getModules()) {
1385 for (var submodule : module.getSubmodules()) {
1386 if (name.equals(submodule.getName()) && optRevision.equals(submodule.getRevision())) {
1387 return RestconfFuture.of(submoduleCtor.apply(module.asEffectiveStatement(),
1388 submodule.asEffectiveStatement()));
1393 final var sb = new StringBuilder().append("Source ").append(source.name().getLocalName());
1394 optRevision.ifPresent(rev -> sb.append('@').append(rev));
1395 sb.append(" not found");
1396 return RestconfFuture.failed(new RestconfDocumentedException(sb.toString(),
1397 ErrorType.APPLICATION, ErrorTag.DATA_MISSING));
1400 public final @NonNull RestconfFuture<? extends DataPostResult> dataPOST(final ApiPath apiPath,
1401 final QueryParams params, final DataPostBody body) {
1402 if (apiPath.isEmpty()) {
1403 return dataCreatePOST(params, body.toResource());
1405 final InstanceReference path;
1407 path = pathNormalizer.normalizeDataOrActionPath(apiPath);
1408 } catch (RestconfDocumentedException e) {
1409 return RestconfFuture.failed(e);
1411 if (path instanceof Data dataPath) {
1412 try (var resourceBody = body.toResource()) {
1413 return dataCreatePOST(dataPath, params, resourceBody);
1416 if (path instanceof Action actionPath) {
1417 try (var inputBody = body.toOperationInput()) {
1418 return dataInvokePOST(actionPath, params, inputBody);
1421 // Note: this should never happen
1422 // FIXME: we should be able to eliminate this path with Java 21+ pattern matching
1423 return RestconfFuture.failed(new RestconfDocumentedException("Unhandled path " + path));
1426 public @NonNull RestconfFuture<CreateResourceResult> dataCreatePOST(final QueryParams params,
1427 final ChildBody body) {
1428 return dataCreatePOST(new DatabindPath.Data(databind), params, body);
1431 private @NonNull RestconfFuture<CreateResourceResult> dataCreatePOST(final DatabindPath.Data path,
1432 final QueryParams params, final ChildBody body) {
1433 final Insert insert;
1435 insert = Insert.of(path.databind(), params);
1436 } catch (IllegalArgumentException e) {
1437 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
1438 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
1441 final var payload = body.toPayload(path);
1442 return postData(concat(path.instance(), payload.prefix()), payload.body(), insert);
1445 private static YangInstanceIdentifier concat(final YangInstanceIdentifier parent, final List<PathArgument> args) {
1447 for (var arg : args) {
1448 ret = ret.node(arg);
1453 private @NonNull RestconfFuture<InvokeResult> dataInvokePOST(final @NonNull Action path,
1454 final @NonNull QueryParams params, final @NonNull OperationInputBody body) {
1455 final InvokeParams invokeParams;
1457 invokeParams = InvokeParams.of(params);
1458 } catch (IllegalArgumentException e) {
1459 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
1460 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
1463 final ContainerNode input;
1465 input = body.toContainerNode(path);
1466 } catch (IOException e) {
1467 LOG.debug("Error reading input", e);
1468 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1469 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1472 if (actionService == null) {
1473 return RestconfFuture.failed(new RestconfDocumentedException("DOMActionService is missing."));
1476 return dataInvokePOST(actionService, path, input)
1477 .transform(result -> outputToInvokeResult(path, invokeParams, result.getOutput().orElse(null)));
1481 * Invoke Action via ActionServiceHandler.
1483 * @param input input data
1484 * @param yangIId invocation context
1485 * @param schemaPath schema path of data
1486 * @param actionService action service to invoke action
1487 * @return {@link DOMActionResult}
1489 private static RestconfFuture<DOMActionResult> dataInvokePOST(final DOMActionService actionService,
1490 final Action path, final @NonNull ContainerNode input) {
1491 final var ret = new SettableRestconfFuture<DOMActionResult>();
1493 Futures.addCallback(actionService.invokeAction(
1494 path.inference().toSchemaInferenceStack().toSchemaNodeIdentifier(),
1495 DOMDataTreeIdentifier.of(LogicalDatastoreType.OPERATIONAL, path.instance()), input),
1496 new FutureCallback<DOMActionResult>() {
1498 public void onSuccess(final DOMActionResult result) {
1499 final var errors = result.getErrors();
1500 LOG.debug("InvokeAction Error Message {}", errors);
1501 if (errors.isEmpty()) {
1504 ret.setFailure(new RestconfDocumentedException("InvokeAction Error Message ", null, errors));
1509 public void onFailure(final Throwable cause) {
1510 if (cause instanceof DOMActionException) {
1511 ret.set(new SimpleDOMActionResult(List.of(RpcResultBuilder.newError(
1512 ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage()))));
1513 } else if (cause instanceof RestconfDocumentedException e) {
1515 } else if (cause instanceof CancellationException) {
1516 ret.setFailure(new RestconfDocumentedException("Action cancelled while executing",
1517 ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, cause));
1519 ret.setFailure(new RestconfDocumentedException("Invocation failed", cause));
1522 }, MoreExecutors.directExecutor());