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.server.api.ChildBody;
64 import org.opendaylight.restconf.server.api.ConfigurationMetadata;
65 import org.opendaylight.restconf.server.api.CreateResourceResult;
66 import org.opendaylight.restconf.server.api.DataGetParams;
67 import org.opendaylight.restconf.server.api.DataGetResult;
68 import org.opendaylight.restconf.server.api.DataPatchResult;
69 import org.opendaylight.restconf.server.api.DataPostBody;
70 import org.opendaylight.restconf.server.api.DataPostResult;
71 import org.opendaylight.restconf.server.api.DataPutResult;
72 import org.opendaylight.restconf.server.api.DataYangPatchResult;
73 import org.opendaylight.restconf.server.api.DatabindContext;
74 import org.opendaylight.restconf.server.api.DatabindPath;
75 import org.opendaylight.restconf.server.api.DatabindPath.Action;
76 import org.opendaylight.restconf.server.api.DatabindPath.Data;
77 import org.opendaylight.restconf.server.api.DatabindPath.InstanceReference;
78 import org.opendaylight.restconf.server.api.DatabindPath.OperationPath;
79 import org.opendaylight.restconf.server.api.DatabindPath.Rpc;
80 import org.opendaylight.restconf.server.api.InvokeResult;
81 import org.opendaylight.restconf.server.api.OperationInputBody;
82 import org.opendaylight.restconf.server.api.PatchBody;
83 import org.opendaylight.restconf.server.api.PatchStatusContext;
84 import org.opendaylight.restconf.server.api.PatchStatusEntity;
85 import org.opendaylight.restconf.server.api.ResourceBody;
86 import org.opendaylight.restconf.server.api.ServerRequest;
87 import org.opendaylight.restconf.server.spi.ApiPathCanonizer;
88 import org.opendaylight.restconf.server.spi.ApiPathNormalizer;
89 import org.opendaylight.restconf.server.spi.DefaultResourceContext;
90 import org.opendaylight.restconf.server.spi.HttpGetResource;
91 import org.opendaylight.restconf.server.spi.NormalizedFormattableBody;
92 import org.opendaylight.restconf.server.spi.NormalizedNodeWriterFactory;
93 import org.opendaylight.restconf.server.spi.OperationInput;
94 import org.opendaylight.restconf.server.spi.OperationOutputBody;
95 import org.opendaylight.restconf.server.spi.OperationsResource;
96 import org.opendaylight.restconf.server.spi.RpcImplementation;
97 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.with.defaults.rev110601.WithDefaultsMode;
98 import org.opendaylight.yangtools.yang.common.Empty;
99 import org.opendaylight.yangtools.yang.common.ErrorTag;
100 import org.opendaylight.yangtools.yang.common.ErrorType;
101 import org.opendaylight.yangtools.yang.common.QName;
102 import org.opendaylight.yangtools.yang.common.QNameModule;
103 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
104 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
105 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
106 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
107 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
108 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
109 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
110 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
111 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
112 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
113 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
114 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
115 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
116 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
117 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
118 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
119 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
120 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
121 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
122 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
123 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
124 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
125 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
126 import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
127 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
128 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
129 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
130 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
131 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
132 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
133 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
134 import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
135 import org.opendaylight.yangtools.yang.model.api.source.SourceRepresentation;
136 import org.opendaylight.yangtools.yang.model.api.source.YangTextSource;
137 import org.opendaylight.yangtools.yang.model.api.source.YinTextSource;
138 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
139 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleEffectiveStatement;
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 HttpGetResource operations;
189 RestconfStrategy(final DatabindContext databind, final ImmutableMap<QName, RpcImplementation> localRpcs,
190 final @Nullable DOMRpcService rpcService, final @Nullable DOMActionService actionService,
191 final @Nullable YangTextSourceExtension sourceProvider,
192 final @Nullable DOMMountPointService mountPointService) {
193 this.databind = requireNonNull(databind);
194 this.localRpcs = requireNonNull(localRpcs);
195 this.rpcService = rpcService;
196 this.actionService = actionService;
197 this.sourceProvider = sourceProvider;
198 this.mountPointService = mountPointService;
199 pathNormalizer = new ApiPathNormalizer(databind);
200 operations = new OperationsResource(pathNormalizer);
203 public final @NonNull StrategyAndPath resolveStrategyPath(final ApiPath path) {
204 final var andTail = resolveStrategy(path);
205 final var strategy = andTail.strategy();
206 return new StrategyAndPath(strategy, strategy.pathNormalizer.normalizeDataPath(andTail.tail()));
210 * Resolve any and all {@code yang-ext:mount} to the target {@link StrategyAndTail}.
212 * @param path {@link ApiPath} to resolve
213 * @return A strategy and the remaining path
214 * @throws NullPointerException if {@code path} is {@code null}
216 public final @NonNull StrategyAndTail resolveStrategy(final ApiPath path) {
217 var mount = path.indexOf("yang-ext", "mount");
219 return new StrategyAndTail(this, path);
221 if (mountPointService == null) {
222 throw new RestconfDocumentedException("Mount point service is not available",
223 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
225 final var mountPath = path.subPath(0, mount);
226 final var dataPath = pathNormalizer.normalizeDataPath(path.subPath(0, mount));
227 final var mountPoint = mountPointService.getMountPoint(dataPath.instance())
228 .orElseThrow(() -> new RestconfDocumentedException("Mount point '" + mountPath + "' does not exist",
229 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
231 return createStrategy(mountPath, mountPoint).resolveStrategy(path.subPath(mount + 1));
234 private static @NonNull RestconfStrategy createStrategy(final ApiPath mountPath, final DOMMountPoint mountPoint) {
235 final var mountSchemaService = mountPoint.getService(DOMSchemaService.class)
236 .orElseThrow(() -> new RestconfDocumentedException(
237 "Mount point '" + mountPath + "' does not expose DOMSchemaService",
238 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
239 final var mountModelContext = mountSchemaService.getGlobalContext();
240 if (mountModelContext == null) {
241 throw new RestconfDocumentedException("Mount point '" + mountPath + "' does not have any models",
242 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT);
244 final var mountDatabind = DatabindContext.ofModel(mountModelContext);
245 final var mountPointService = mountPoint.getService(DOMMountPointService.class).orElse(null);
246 final var rpcService = mountPoint.getService(DOMRpcService.class).orElse(null);
247 final var actionService = mountPoint.getService(DOMActionService.class).orElse(null);
248 final var sourceProvider = mountPoint.getService(DOMSchemaService.class)
249 .flatMap(schema -> Optional.ofNullable(schema.extension(YangTextSourceExtension.class)))
252 final var netconfService = mountPoint.getService(NetconfDataTreeService.class);
253 if (netconfService.isPresent()) {
254 return new NetconfRestconfStrategy(mountDatabind, netconfService.orElseThrow(), rpcService, actionService,
255 sourceProvider, mountPointService);
257 final var dataBroker = mountPoint.getService(DOMDataBroker.class);
258 if (dataBroker.isPresent()) {
259 return new MdsalRestconfStrategy(mountDatabind, dataBroker.orElseThrow(), ImmutableMap.of(), rpcService,
260 actionService, sourceProvider, mountPointService);
262 LOG.warn("Mount point {} does not expose a suitable access interface", mountPath);
263 throw new RestconfDocumentedException("Could not find a supported access interface in mount point",
264 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, mountPoint.getIdentifier());
267 public final @NonNull DatabindContext databind() {
271 public final @NonNull EffectiveModelContext modelContext() {
272 return databind.modelContext();
276 * Lock the entire datastore.
278 * @return A {@link RestconfTransaction}. This transaction needs to be either committed or canceled before doing
281 abstract RestconfTransaction prepareWriteExecution();
284 * Read data from the datastore.
286 * @param store the logical data store which should be modified
287 * @param path the data object path
288 * @return a ListenableFuture containing the result of the read
290 abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path);
293 * Check if data already exists in the configuration datastore.
295 * @param path the data object path
296 * @return a ListenableFuture containing the result of the check
298 // FIXME: this method should be hosted in RestconfTransaction
299 // FIXME: this method should only be needed in MdsalRestconfStrategy
300 abstract ListenableFuture<Boolean> exists(YangInstanceIdentifier path);
303 final @NonNull RestconfFuture<DataPatchResult> merge(final YangInstanceIdentifier path, final NormalizedNode data) {
304 final var ret = new SettableRestconfFuture<DataPatchResult>();
305 merge(ret, requireNonNull(path), requireNonNull(data));
309 private void merge(final @NonNull SettableRestconfFuture<DataPatchResult> future,
310 final @NonNull YangInstanceIdentifier path, final @NonNull NormalizedNode data) {
311 final var tx = prepareWriteExecution();
312 // FIXME: this method should be further specialized to eliminate this call -- it is only needed for MD-SAL
313 tx.ensureParentsByMerge(path);
314 tx.merge(path, data);
315 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
317 public void onSuccess(final CommitInfo result) {
318 // TODO: extract details once CommitInfo can communicate them
319 future.set(PATCH_EMPTY);
323 public void onFailure(final Throwable cause) {
324 future.setFailure(TransactionUtil.decodeException(cause, "MERGE", path, modelContext()));
326 }, MoreExecutors.directExecutor());
329 public @NonNull RestconfFuture<DataPutResult> dataPUT(final ServerRequest request, final ApiPath apiPath,
330 final ResourceBody body) {
333 path = pathNormalizer.normalizeDataPath(apiPath);
334 } catch (RestconfDocumentedException e) {
335 return RestconfFuture.failed(e);
340 insert = Insert.of(databind, request.queryParameters());
341 } catch (IllegalArgumentException e) {
342 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
343 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
345 final NormalizedNode data;
347 data = body.toNormalizedNode(path);
348 } catch (RestconfDocumentedException e) {
349 return RestconfFuture.failed(e);
351 return putData(path.instance(), data, insert);
355 * Check mount point and prepare variables for put data to DS.
357 * @param path path of data
359 * @param insert {@link Insert}
360 * @return A {@link DataPutResult}
362 public final @NonNull RestconfFuture<DataPutResult> putData(final YangInstanceIdentifier path,
363 final NormalizedNode data, final @Nullable Insert insert) {
364 final var exists = TransactionUtil.syncAccess(exists(path), path);
366 final ListenableFuture<? extends CommitInfo> commitFuture;
367 if (insert != null) {
368 final var parentPath = path.coerceParent();
369 checkListAndOrderedType(parentPath);
370 commitFuture = insertAndCommitPut(path, data, insert, parentPath);
372 commitFuture = replaceAndCommit(prepareWriteExecution(), path, data);
375 final var ret = new SettableRestconfFuture<DataPutResult>();
377 Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
379 public void onSuccess(final CommitInfo result) {
380 ret.set(exists ? PUT_REPLACED : PUT_CREATED);
384 public void onFailure(final Throwable cause) {
385 ret.setFailure(TransactionUtil.decodeException(cause, "PUT", path, modelContext()));
387 }, MoreExecutors.directExecutor());
392 private ListenableFuture<? extends CommitInfo> insertAndCommitPut(final YangInstanceIdentifier path,
393 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parentPath) {
394 final var tx = prepareWriteExecution();
396 return switch (insert.insert()) {
398 final var readData = tx.readList(parentPath);
399 if (readData == null || readData.isEmpty()) {
400 yield replaceAndCommit(tx, path, data);
402 tx.remove(parentPath);
403 tx.replace(path, data);
404 tx.replace(parentPath, readData);
407 case LAST -> replaceAndCommit(tx, path, data);
409 final var readData = tx.readList(parentPath);
410 if (readData == null || readData.isEmpty()) {
411 yield replaceAndCommit(tx, path, data);
413 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
417 final var readData = tx.readList(parentPath);
418 if (readData == null || readData.isEmpty()) {
419 yield replaceAndCommit(tx, path, data);
421 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
427 private void insertWithPointPut(final RestconfTransaction tx, final YangInstanceIdentifier path,
428 final NormalizedNode data, final @NonNull PathArgument pointArg, final NormalizedNodeContainer<?> readList,
429 final boolean before) {
430 tx.remove(path.getParent());
432 int lastItemPosition = 0;
433 for (var nodeChild : readList.body()) {
434 if (nodeChild.name().equals(pointArg)) {
443 int lastInsertedPosition = 0;
444 final var emptySubtree = fromInstanceId(modelContext(), path.getParent());
445 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
446 for (var nodeChild : readList.body()) {
447 if (lastInsertedPosition == lastItemPosition) {
448 tx.replace(path, data);
450 final var childPath = path.coerceParent().node(nodeChild.name());
451 tx.replace(childPath, nodeChild);
452 lastInsertedPosition++;
455 // In case we are inserting after last element
457 if (lastInsertedPosition == lastItemPosition) {
458 tx.replace(path, data);
463 private static ListenableFuture<? extends CommitInfo> replaceAndCommit(final RestconfTransaction tx,
464 final YangInstanceIdentifier path, final NormalizedNode data) {
465 tx.replace(path, data);
469 private DataSchemaNode checkListAndOrderedType(final YangInstanceIdentifier path) {
470 // FIXME: we have this available in InstanceIdentifierContext
471 final var dataSchemaNode = databind.schemaTree().findChild(path).orElseThrow().dataSchemaNode();
473 final String message;
474 if (dataSchemaNode instanceof ListSchemaNode listSchema) {
475 if (listSchema.isUserOrdered()) {
478 message = "Insert parameter can be used only with ordered-by user list.";
479 } else if (dataSchemaNode instanceof LeafListSchemaNode leafListSchema) {
480 if (leafListSchema.isUserOrdered()) {
481 return leafListSchema;
483 message = "Insert parameter can be used only with ordered-by user leaf-list.";
485 message = "Insert parameter can be used only with list or leaf-list";
487 throw new RestconfDocumentedException(message, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
491 * Check mount point and prepare variables for post data.
495 * @param insert {@link Insert}
496 * @return A {@link RestconfFuture}
498 public final @NonNull RestconfFuture<CreateResourceResult> postData(final YangInstanceIdentifier path,
499 final NormalizedNode data, final @Nullable Insert insert) {
500 final ListenableFuture<? extends CommitInfo> future;
501 if (insert != null) {
502 checkListAndOrderedType(path);
503 future = insertAndCommitPost(path, data, insert);
505 future = createAndCommit(prepareWriteExecution(), path, data);
508 final var ret = new SettableRestconfFuture<CreateResourceResult>();
509 Futures.addCallback(future, new FutureCallback<CommitInfo>() {
511 public void onSuccess(final CommitInfo result) {
512 ret.set(new CreateResourceResult(new ApiPathCanonizer(databind).dataToApiPath(
513 data instanceof MapNode mapData && !mapData.isEmpty()
514 ? path.node(mapData.body().iterator().next().name()) : path)));
518 public void onFailure(final Throwable cause) {
519 ret.setFailure(TransactionUtil.decodeException(cause, "POST", path, modelContext()));
522 }, MoreExecutors.directExecutor());
526 private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
527 final NormalizedNode data, final @NonNull Insert insert) {
528 final var tx = prepareWriteExecution();
530 return switch (insert.insert()) {
532 final var readData = tx.readList(path);
533 if (readData == null || readData.isEmpty()) {
534 tx.replace(path, data);
536 checkListDataDoesNotExist(path, data);
538 tx.replace(path, data);
539 tx.replace(path, readData);
543 case LAST -> createAndCommit(tx, path, data);
545 final var readData = tx.readList(path);
546 if (readData == null || readData.isEmpty()) {
547 tx.replace(path, data);
549 checkListDataDoesNotExist(path, data);
550 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
555 final var readData = tx.readList(path);
556 if (readData == null || readData.isEmpty()) {
557 tx.replace(path, data);
559 checkListDataDoesNotExist(path, data);
560 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
568 * Merge data into the configuration datastore, as outlined in
569 * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040 section 4.6.1</a>.
571 * @param apiPath Path to merge
572 * @param body Data to merge
573 * @return A {@link RestconfFuture}
574 * @throws NullPointerException if any argument is {@code null}
576 public final @NonNull RestconfFuture<DataPatchResult> dataPATCH(final ApiPath apiPath, final ResourceBody body) {
579 path = pathNormalizer.normalizeDataPath(apiPath);
580 } catch (RestconfDocumentedException e) {
581 return RestconfFuture.failed(e);
584 final NormalizedNode data;
586 data = body.toNormalizedNode(path);
587 } catch (RestconfDocumentedException e) {
588 return RestconfFuture.failed(e);
591 return merge(path.instance(), data);
594 public final @NonNull RestconfFuture<DataYangPatchResult> dataPATCH(final ApiPath apiPath, final PatchBody body) {
597 path = pathNormalizer.normalizeDataPath(apiPath);
598 } catch (RestconfDocumentedException e) {
599 return RestconfFuture.failed(e);
602 final PatchContext patch;
604 patch = body.toPatchContext(new DefaultResourceContext(path));
605 } catch (IOException e) {
606 LOG.debug("Error parsing YANG Patch input", e);
607 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
608 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
610 return patchData(patch);
614 * Process edit operations of one {@link PatchContext}.
616 * @param patch Patch context to be processed
617 * @return {@link PatchStatusContext}
620 public final @NonNull RestconfFuture<DataYangPatchResult> patchData(final PatchContext patch) {
621 final var editCollection = new ArrayList<PatchStatusEntity>();
622 final var tx = prepareWriteExecution();
624 boolean noError = true;
625 for (var patchEntity : patch.entities()) {
627 final var targetNode = patchEntity.getTargetNode();
628 final var editId = patchEntity.getEditId();
630 switch (patchEntity.getOperation()) {
633 tx.create(targetNode, patchEntity.getNode());
634 editCollection.add(new PatchStatusEntity(editId, true, null));
635 } catch (RestconfDocumentedException e) {
636 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
642 tx.delete(targetNode);
643 editCollection.add(new PatchStatusEntity(editId, true, null));
644 } catch (RestconfDocumentedException e) {
645 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
651 tx.ensureParentsByMerge(targetNode);
652 tx.merge(targetNode, patchEntity.getNode());
653 editCollection.add(new PatchStatusEntity(editId, true, null));
654 } catch (RestconfDocumentedException e) {
655 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
661 tx.replace(targetNode, patchEntity.getNode());
662 editCollection.add(new PatchStatusEntity(editId, true, null));
663 } catch (RestconfDocumentedException e) {
664 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
670 tx.remove(targetNode);
671 editCollection.add(new PatchStatusEntity(editId, true, null));
672 } catch (RestconfDocumentedException e) {
673 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
678 editCollection.add(new PatchStatusEntity(editId, false, List.of(
679 new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
680 "Not supported Yang Patch operation"))));
689 final var ret = new SettableRestconfFuture<DataYangPatchResult>();
693 ret.set(new DataYangPatchResult(
694 new PatchStatusContext(databind(), patch.patchId(), List.copyOf(editCollection), false, null)));
698 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
700 public void onSuccess(final CommitInfo result) {
701 ret.set(new DataYangPatchResult(
702 new PatchStatusContext(databind(), patch.patchId(), List.copyOf(editCollection), true, null)));
706 public void onFailure(final Throwable cause) {
707 // if errors occurred during transaction commit then patch failed and global errors are reported
708 ret.set(new DataYangPatchResult(
709 new PatchStatusContext(databind(), patch.patchId(), List.copyOf(editCollection), false,
710 TransactionUtil.decodeException(cause, "PATCH", null, modelContext()).getErrors())));
712 }, MoreExecutors.directExecutor());
717 private static void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
718 final NormalizedNode data, final PathArgument pointArg, final NormalizedNodeContainer<?> readList,
719 final boolean before) {
722 int lastItemPosition = 0;
723 for (var nodeChild : readList.body()) {
724 if (nodeChild.name().equals(pointArg)) {
733 int lastInsertedPosition = 0;
734 for (var nodeChild : readList.body()) {
735 if (lastInsertedPosition == lastItemPosition) {
736 tx.replace(path, data);
738 tx.replace(path.node(nodeChild.name()), nodeChild);
739 lastInsertedPosition++;
742 // In case we are inserting after last element
744 if (lastInsertedPosition == lastItemPosition) {
745 tx.replace(path, data);
750 private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
751 final YangInstanceIdentifier path, final NormalizedNode data) {
753 tx.create(path, data);
754 } catch (RestconfDocumentedException e) {
755 // close transaction if any and pass exception further
764 * Check if child items do NOT already exists in List at specified {@code path}.
766 * @param data Data to be checked
767 * @param path Path to be checked
768 * @throws RestconfDocumentedException if data already exists.
770 private void checkListDataDoesNotExist(final YangInstanceIdentifier path, final NormalizedNode data) {
771 if (data instanceof NormalizedNodeContainer<?> dataNode) {
772 for (final var node : dataNode.body()) {
773 checkItemDoesNotExists(exists(path.node(node.name())), path.node(node.name()));
776 throw new RestconfDocumentedException("Unexpected node type: " + data.getClass().getName());
781 * Check if items do NOT already exists at specified {@code path}.
783 * @param existsFuture if checked data exists
784 * @param path Path to be checked
785 * @throws RestconfDocumentedException if data already exists.
787 static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
788 final YangInstanceIdentifier path) {
789 if (TransactionUtil.syncAccess(existsFuture, path)) {
790 LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
791 throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
797 * Delete data from the configuration datastore. If the data does not exist, this operation will fail, as outlined
798 * in <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.7">RFC8040 section 4.7</a>
800 * @param apiPath Path to delete
801 * @return A {@link RestconfFuture}
802 * @throws NullPointerException if {@code apiPath} is {@code null}
805 @SuppressWarnings("checkstyle:abbreviationAsWordInName")
806 public final RestconfFuture<Empty> dataDELETE(final ServerRequest request, final ApiPath apiPath) {
809 path = pathNormalizer.normalizeDataPath(apiPath);
810 } catch (RestconfDocumentedException e) {
811 return RestconfFuture.failed(e);
814 // FIXME: reject empty YangInstanceIdentifier, as datastores may not be deleted
815 final var ret = new SettableRestconfFuture<Empty>();
816 delete(ret, request, path.instance());
821 abstract void delete(SettableRestconfFuture<Empty> future, ServerRequest request, YangInstanceIdentifier path);
823 public final @NonNull RestconfFuture<DataGetResult> dataGET(final ServerRequest request, final ApiPath apiPath) {
826 path = pathNormalizer.normalizeDataPath(apiPath);
827 } catch (RestconfDocumentedException e) {
828 return RestconfFuture.failed(e);
831 final DataGetParams getParams;
833 getParams = DataGetParams.of(request.queryParameters());
834 } catch (IllegalArgumentException e) {
835 return RestconfFuture.failed(new RestconfDocumentedException(e,
836 new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, "Invalid GET /data parameters", null,
839 return dataGET(request, path, getParams);
842 abstract @NonNull RestconfFuture<DataGetResult> dataGET(ServerRequest request, Data path, DataGetParams params);
845 static final RestconfFuture<DataGetResult> completeDataGET(final @Nullable NormalizedNode node, final Data path,
846 final NormalizedNodeWriterFactory writerFactory, final @Nullable ConfigurationMetadata metadata) {
849 return RestconfFuture.failed(new RestconfDocumentedException(
850 "Request could not be completed because the relevant data model content does not exist",
851 ErrorType.PROTOCOL, ErrorTag.DATA_MISSING));
854 final var body = NormalizedFormattableBody.of(path, node, writerFactory);
855 return RestconfFuture.of(metadata == null ? new DataGetResult(body)
856 : new DataGetResult(body, metadata.entityTag(), metadata.lastModified()));
860 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
861 * inside of object {@link RestconfStrategy} provided as a parameter.
863 * @param content type of data to read (config, state, all)
864 * @param path the path to read
865 * @param defaultsMode value of with-defaults parameter
866 * @return {@link NormalizedNode}
868 // FIXME: NETCONF-1155: this method should asynchronous
870 final @Nullable NormalizedNode readData(final @NonNull ContentParam content,
871 final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
872 return switch (content) {
874 // PREPARE STATE DATA NODE
875 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
876 // PREPARE CONFIG DATA NODE
877 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
879 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
880 : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
883 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
884 yield defaultsMode == null ? read
885 : prepareDataByParamWithDef(read, path, defaultsMode.mode());
887 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
891 private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
892 final YangInstanceIdentifier path) {
893 return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
896 final NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
897 final WithDefaultsMode defaultsMode) {
898 final boolean trim = switch (defaultsMode) {
900 case Explicit -> false;
901 case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
902 "Unsupported with-defaults value " + defaultsMode.getName());
905 // FIXME: we have this readily available in InstanceIdentifierContext
906 final var ctxNode = databind.schemaTree().findChild(path).orElseThrow();
907 if (readData instanceof ContainerNode container) {
908 final var builder = ImmutableNodes.newContainerBuilder().withNodeIdentifier(container.name());
909 buildCont(builder, container.body(), ctxNode, trim);
910 return builder.build();
911 } else if (readData instanceof MapEntryNode mapEntry) {
912 if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
913 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
916 final var builder = ImmutableNodes.newMapEntryBuilder().withNodeIdentifier(mapEntry.name());
917 buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
918 return builder.build();
920 throw new IllegalStateException("Unhandled data contract " + readData.contract());
924 private static void buildMapEntryBuilder(
925 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
926 final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
927 final boolean trim, final List<QName> keys) {
928 for (var child : children) {
929 final var childCtx = getChildContext(ctxNode, child);
931 if (child instanceof ContainerNode container) {
932 appendContainer(builder, container, childCtx, trim);
933 } else if (child instanceof MapNode map) {
934 appendMap(builder, map, childCtx, trim);
935 } else if (child instanceof LeafNode<?> leaf) {
936 appendLeaf(builder, leaf, childCtx, trim, keys);
938 // FIXME: we should never hit this, throw an ISE if this ever happens
939 LOG.debug("Ignoring unhandled child contract {}", child.contract());
944 private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
945 final DataSchemaContext ctxNode, final boolean trim) {
946 final var childBuilder = ImmutableNodes.newContainerBuilder().withNodeIdentifier(container.name());
947 buildCont(childBuilder, container.body(), ctxNode, trim);
948 builder.withChild(childBuilder.build());
951 private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
952 final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
953 if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
954 throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
957 // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
958 final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
960 // This is a combined check for when we need to emit the leaf.
962 // We always have to emit key leaf values
963 keys.contains(leafSchema.getQName())
964 // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
966 // When data is retrieved with a <with-defaults> parameter equal to
967 // 'trim', data nodes MUST NOT be reported if they contain the schema
968 // default value. Non-configuration data nodes containing the schema
969 // default value MUST NOT be reported.
971 || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
972 // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
973 // grasp what we are doing here... emit only if it matches default ???!!!
974 // FIXME: The WithDefaultsParam.EXPLICIT says:
976 // Data nodes set to the YANG default by the client are reported.
978 // and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
980 // If the "with-defaults" parameter is set to "explicit", then the
981 // server MUST adhere to the default-reporting behavior defined in
982 // Section 3.3 of [RFC6243].
984 // and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
986 // When data is retrieved with a <with-defaults> parameter equal to
987 // 'explicit', a data node that was set by a client to its schema
988 // default value MUST be reported. A conceptual data node that would be
989 // set by the server to the schema default value MUST NOT be reported.
990 // Non-configuration data nodes containing the schema default value MUST
993 // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
994 // This seems to disregard the 'trim = true' case semantics (see above).
995 // Combining the above, though, these checks are missing the 'non-config' check, which would
996 // distinguish, but barring that this check is superfluous and results in the wrong semantics.
997 // Without that input, this really should be covered by the previous case.
998 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
999 builder.withChild(leaf);
1003 private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
1004 final DataSchemaContext childCtx, final boolean trim) {
1005 if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
1006 throw new IllegalStateException("Input " + map + " does not match " + childCtx);
1009 final var childBuilder = switch (map.ordering()) {
1010 case SYSTEM -> ImmutableNodes.newSystemMapBuilder();
1011 case USER -> ImmutableNodes.newUserMapBuilder();
1013 buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
1014 listSchema.getKeyDefinition());
1015 builder.withChild(childBuilder.build());
1018 private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
1019 final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
1020 final List<@NonNull QName> keys) {
1021 for (var entry : entries) {
1022 final var childCtx = getChildContext(ctxNode, entry);
1023 final var mapEntryBuilder = ImmutableNodes.newMapEntryBuilder().withNodeIdentifier(entry.name());
1024 buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
1025 builder.withChild(mapEntryBuilder.build());
1029 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
1030 final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
1031 for (var child : children) {
1032 final var childCtx = getChildContext(ctxNode, child);
1033 if (child instanceof ContainerNode container) {
1034 appendContainer(builder, container, childCtx, trim);
1035 } else if (child instanceof MapNode map) {
1036 appendMap(builder, map, childCtx, trim);
1037 } else if (child instanceof LeafNode<?> leaf) {
1038 appendLeaf(builder, leaf, childCtx, trim, List.of());
1043 private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
1044 final NormalizedNode child) {
1045 final var childId = child.name();
1046 final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
1048 if (childCtx == null) {
1049 throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
1054 static final NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
1055 final NormalizedNode configDataNode) {
1056 if (stateDataNode == null) {
1057 // No state, return config
1058 return configDataNode;
1060 if (configDataNode == null) {
1061 // No config, return state
1062 return stateDataNode;
1064 // merge config and state
1065 return mergeStateAndConfigData(stateDataNode, configDataNode);
1069 * Merge state and config data into a single NormalizedNode.
1071 * @param stateDataNode data node of state data
1072 * @param configDataNode data node of config data
1073 * @return {@link NormalizedNode}
1075 private static @NonNull NormalizedNode mergeStateAndConfigData(
1076 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
1077 validateNodeMerge(stateDataNode, configDataNode);
1078 // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
1079 if (configDataNode instanceof RpcDefinition) {
1080 return prepareRpcData(configDataNode, stateDataNode);
1082 return prepareData(configDataNode, stateDataNode);
1087 * Validates whether the two NormalizedNodes can be merged.
1089 * @param stateDataNode data node of state data
1090 * @param configDataNode data node of config data
1092 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
1093 final @NonNull NormalizedNode configDataNode) {
1094 final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
1095 final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
1096 if (!moduleOfStateData.equals(moduleOfConfigData)) {
1097 throw new RestconfDocumentedException("Unable to merge data from different modules.");
1102 * Prepare and map data for rpc.
1104 * @param configDataNode data node of config data
1105 * @param stateDataNode data node of state data
1106 * @return {@link NormalizedNode}
1108 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
1109 final @NonNull NormalizedNode stateDataNode) {
1110 final var mapEntryBuilder = ImmutableNodes.newMapEntryBuilder()
1111 .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
1114 mapRpcDataNode(configDataNode, mapEntryBuilder);
1116 mapRpcDataNode(stateDataNode, mapEntryBuilder);
1118 return ImmutableNodes.newSystemMapBuilder()
1119 .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
1120 .addChild(mapEntryBuilder.build())
1125 * Map node to map entry builder.
1127 * @param dataNode data node
1128 * @param mapEntryBuilder builder for mapping data
1130 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
1131 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
1132 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
1136 * Prepare and map all data from DS.
1138 * @param configDataNode data node of config data
1139 * @param stateDataNode data node of state data
1140 * @return {@link NormalizedNode}
1142 @SuppressWarnings("unchecked")
1143 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
1144 final @NonNull NormalizedNode stateDataNode) {
1145 if (configDataNode instanceof UserMapNode configMap) {
1146 final var builder = ImmutableNodes.newUserMapBuilder().withNodeIdentifier(configMap.name());
1147 mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
1148 return builder.build();
1149 } else if (configDataNode instanceof SystemMapNode configMap) {
1150 final var builder = ImmutableNodes.newSystemMapBuilder().withNodeIdentifier(configMap.name());
1151 mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
1152 return builder.build();
1153 } else if (configDataNode instanceof MapEntryNode configEntry) {
1154 final var builder = ImmutableNodes.newMapEntryBuilder().withNodeIdentifier(configEntry.name());
1155 mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
1156 return builder.build();
1157 } else if (configDataNode instanceof ContainerNode configContaienr) {
1158 final var builder = ImmutableNodes.newContainerBuilder().withNodeIdentifier(configContaienr.name());
1159 mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
1160 return builder.build();
1161 } else if (configDataNode instanceof ChoiceNode configChoice) {
1162 final var builder = ImmutableNodes.newChoiceBuilder().withNodeIdentifier(configChoice.name());
1163 mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
1164 return builder.build();
1165 } else if (configDataNode instanceof LeafNode configLeaf) {
1166 // config trumps oper
1168 } else if (configDataNode instanceof UserLeafSetNode) {
1169 final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
1170 final var builder = ImmutableNodes.<Object>newUserLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
1171 mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
1172 return builder.build();
1173 } else if (configDataNode instanceof SystemLeafSetNode) {
1174 final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
1175 final var builder = ImmutableNodes.<Object>newSystemLeafSetBuilder()
1176 .withNodeIdentifier(configLeafSet.name());
1177 mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
1178 return builder.build();
1179 } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
1180 // config trumps oper
1182 } else if (configDataNode instanceof UnkeyedListNode configList) {
1183 final var builder = ImmutableNodes.newUnkeyedListBuilder().withNodeIdentifier(configList.name());
1184 mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
1185 return builder.build();
1186 } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
1187 final var builder = ImmutableNodes.newUnkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
1188 mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
1189 return builder.build();
1191 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
1196 * Map value from container node to builder.
1198 * @param configData collection of config data nodes
1199 * @param stateData collection of state data nodes
1200 * @param builder builder
1202 private static <T extends NormalizedNode> void mapValueToBuilder(
1203 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
1204 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1205 final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1206 final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1208 // merge config and state data of children with different identifiers
1209 mapDataToBuilder(configMap, stateMap, builder);
1211 // merge config and state data of children with the same identifiers
1212 mergeDataToBuilder(configMap, stateMap, builder);
1216 * Map data with different identifiers to builder. Data with different identifiers can be just added
1217 * as childs to parent node.
1219 * @param configMap map of config data nodes
1220 * @param stateMap map of state data nodes
1221 * @param builder - builder
1223 private static <T extends NormalizedNode> void mapDataToBuilder(
1224 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1225 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1226 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
1227 y -> builder.addChild(y.getValue()));
1228 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
1229 y -> builder.addChild(y.getValue()));
1233 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
1234 * go one level down with {@code prepareData} method.
1236 * @param configMap immutable config data
1237 * @param stateMap immutable state data
1238 * @param builder - builder
1240 @SuppressWarnings("unchecked")
1241 private static <T extends NormalizedNode> void mergeDataToBuilder(
1242 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1243 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1244 // it is enough to process only config data because operational contains the same data
1245 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1246 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1250 public RestconfFuture<FormattableBody> operationsGET(final ServerRequest request) {
1251 return operations.httpGET(request);
1255 public RestconfFuture<FormattableBody> operationsGET(final ServerRequest request, final ApiPath apiPath) {
1256 return operations.httpGET(request, apiPath);
1259 public @NonNull RestconfFuture<InvokeResult> operationsPOST(final ServerRequest request, final URI restconfURI,
1260 final ApiPath apiPath, final OperationInputBody body) {
1263 path = pathNormalizer.normalizeRpcPath(apiPath);
1264 } catch (RestconfDocumentedException e) {
1265 return RestconfFuture.failed(e);
1268 final ContainerNode data;
1270 data = body.toContainerNode(path);
1271 } catch (IOException e) {
1272 LOG.debug("Error reading input", e);
1273 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1274 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1277 final var type = path.rpc().argument();
1278 final var local = localRpcs.get(type);
1279 if (local != null) {
1280 return local.invoke(restconfURI, new OperationInput(path, data))
1281 .transform(output -> outputToInvokeResult(path, output));
1283 if (rpcService == null) {
1284 LOG.debug("RPC invocation is not available");
1285 return RestconfFuture.failed(new RestconfDocumentedException("RPC invocation is not available",
1286 ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED));
1289 final var ret = new SettableRestconfFuture<InvokeResult>();
1290 Futures.addCallback(rpcService.invokeRpc(type, data), new FutureCallback<DOMRpcResult>() {
1292 public void onSuccess(final DOMRpcResult response) {
1293 final var errors = response.errors();
1294 if (errors.isEmpty()) {
1295 ret.set(outputToInvokeResult(path, response.value()));
1297 LOG.debug("RPC invocation reported {}", response.errors());
1298 ret.setFailure(new RestconfDocumentedException("RPC implementation reported errors", null,
1299 response.errors()));
1304 public void onFailure(final Throwable cause) {
1305 LOG.debug("RPC invocation failed, cause");
1306 if (cause instanceof RestconfDocumentedException ex) {
1309 // TODO: YangNetconfErrorAware if we ever get into a broader invocation scope
1310 ret.setFailure(new RestconfDocumentedException(cause,
1311 new RestconfError(ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage())));
1314 }, MoreExecutors.directExecutor());
1318 private static @NonNull InvokeResult outputToInvokeResult(final @NonNull OperationPath path,
1319 final @Nullable ContainerNode value) {
1320 return value == null || value.isEmpty() ? InvokeResult.EMPTY
1321 : new InvokeResult(new OperationOutputBody(path, value));
1324 public @NonNull RestconfFuture<CharSource> resolveSource(final SourceIdentifier source,
1325 final Class<? extends SourceRepresentation> representation) {
1326 final var src = requireNonNull(source);
1327 if (YangTextSource.class.isAssignableFrom(representation)) {
1328 if (sourceProvider != null) {
1329 final var ret = new SettableRestconfFuture<CharSource>();
1330 Futures.addCallback(sourceProvider.getYangTexttSource(src), new FutureCallback<>() {
1332 public void onSuccess(final YangTextSource result) {
1337 public void onFailure(final Throwable cause) {
1338 ret.setFailure(cause instanceof RestconfDocumentedException e ? e
1339 : new RestconfDocumentedException(cause.getMessage(), ErrorType.RPC,
1340 ErrorTag.OPERATION_FAILED, cause));
1342 }, MoreExecutors.directExecutor());
1345 return exportSource(modelContext(), src, YangCharSource::new, YangCharSource::new);
1347 if (YinTextSource.class.isAssignableFrom(representation)) {
1348 return exportSource(modelContext(), src, YinCharSource.OfModule::new, YinCharSource.OfSubmodule::new);
1350 return RestconfFuture.failed(new RestconfDocumentedException(
1351 "Unsupported source representation " + representation.getName()));
1354 private static @NonNull RestconfFuture<CharSource> exportSource(final EffectiveModelContext modelContext,
1355 final SourceIdentifier source, final Function<ModuleEffectiveStatement, CharSource> moduleCtor,
1356 final BiFunction<ModuleEffectiveStatement, SubmoduleEffectiveStatement, CharSource> submoduleCtor) {
1357 // If the source identifies a module, things are easy
1358 final var name = source.name().getLocalName();
1359 final var optRevision = Optional.ofNullable(source.revision());
1360 final var optModule = modelContext.findModule(name, optRevision);
1361 if (optModule.isPresent()) {
1362 return RestconfFuture.of(moduleCtor.apply(optModule.orElseThrow().asEffectiveStatement()));
1365 // The source could be a submodule, which we need to hunt down
1366 for (var module : modelContext.getModules()) {
1367 for (var submodule : module.getSubmodules()) {
1368 if (name.equals(submodule.getName()) && optRevision.equals(submodule.getRevision())) {
1369 return RestconfFuture.of(submoduleCtor.apply(module.asEffectiveStatement(),
1370 submodule.asEffectiveStatement()));
1375 final var sb = new StringBuilder().append("Source ").append(source.name().getLocalName());
1376 optRevision.ifPresent(rev -> sb.append('@').append(rev));
1377 sb.append(" not found");
1378 return RestconfFuture.failed(new RestconfDocumentedException(sb.toString(),
1379 ErrorType.APPLICATION, ErrorTag.DATA_MISSING));
1382 public final @NonNull RestconfFuture<? extends DataPostResult> dataPOST(final ServerRequest request,
1383 final ApiPath apiPath, final DataPostBody body) {
1384 if (apiPath.isEmpty()) {
1385 return dataCreatePOST(request, body.toResource());
1387 final InstanceReference path;
1389 path = pathNormalizer.normalizeDataOrActionPath(apiPath);
1390 } catch (RestconfDocumentedException e) {
1391 return RestconfFuture.failed(e);
1393 if (path instanceof Data dataPath) {
1394 try (var resourceBody = body.toResource()) {
1395 return dataCreatePOST(request, dataPath, resourceBody);
1398 if (path instanceof Action actionPath) {
1399 try (var inputBody = body.toOperationInput()) {
1400 return dataInvokePOST(actionPath, inputBody);
1403 // Note: this should never happen
1404 // FIXME: we should be able to eliminate this path with Java 21+ pattern matching
1405 return RestconfFuture.failed(new RestconfDocumentedException("Unhandled path " + path));
1408 public @NonNull RestconfFuture<CreateResourceResult> dataCreatePOST(final ServerRequest request,
1409 final ChildBody body) {
1410 return dataCreatePOST(request, new DatabindPath.Data(databind), body);
1413 private @NonNull RestconfFuture<CreateResourceResult> dataCreatePOST(final ServerRequest request,
1414 final DatabindPath.Data path, final ChildBody body) {
1415 final Insert insert;
1417 insert = Insert.of(path.databind(), request.queryParameters());
1418 } catch (IllegalArgumentException e) {
1419 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
1420 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
1423 final var payload = body.toPayload(path);
1424 return postData(concat(path.instance(), payload.prefix()), payload.body(), insert);
1427 private static YangInstanceIdentifier concat(final YangInstanceIdentifier parent, final List<PathArgument> args) {
1429 for (var arg : args) {
1430 ret = ret.node(arg);
1435 private @NonNull RestconfFuture<InvokeResult> dataInvokePOST(final @NonNull Action path,
1436 final @NonNull OperationInputBody body) {
1437 final ContainerNode input;
1439 input = body.toContainerNode(path);
1440 } catch (IOException e) {
1441 LOG.debug("Error reading input", e);
1442 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1443 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1446 if (actionService == null) {
1447 return RestconfFuture.failed(new RestconfDocumentedException("DOMActionService is missing."));
1450 return dataInvokePOST(actionService, path, input)
1451 .transform(result -> outputToInvokeResult(path, result.getOutput().orElse(null)));
1455 * Invoke Action via ActionServiceHandler.
1457 * @param input input data
1458 * @param yangIId invocation context
1459 * @param schemaPath schema path of data
1460 * @param actionService action service to invoke action
1461 * @return {@link DOMActionResult}
1463 private static RestconfFuture<DOMActionResult> dataInvokePOST(final DOMActionService actionService,
1464 final Action path, final @NonNull ContainerNode input) {
1465 final var ret = new SettableRestconfFuture<DOMActionResult>();
1467 Futures.addCallback(actionService.invokeAction(
1468 path.inference().toSchemaInferenceStack().toSchemaNodeIdentifier(),
1469 DOMDataTreeIdentifier.of(LogicalDatastoreType.OPERATIONAL, path.instance()), input),
1470 new FutureCallback<DOMActionResult>() {
1472 public void onSuccess(final DOMActionResult result) {
1473 final var errors = result.getErrors();
1474 LOG.debug("InvokeAction Error Message {}", errors);
1475 if (errors.isEmpty()) {
1478 ret.setFailure(new RestconfDocumentedException("InvokeAction Error Message ", null, errors));
1483 public void onFailure(final Throwable cause) {
1484 if (cause instanceof DOMActionException) {
1485 ret.set(new SimpleDOMActionResult(List.of(RpcResultBuilder.newError(
1486 ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage()))));
1487 } else if (cause instanceof RestconfDocumentedException e) {
1489 } else if (cause instanceof CancellationException) {
1490 ret.setFailure(new RestconfDocumentedException("Action cancelled while executing",
1491 ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, cause));
1493 ret.setFailure(new RestconfDocumentedException("Invocation failed", cause));
1496 }, MoreExecutors.directExecutor());