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.PrettyPrintParam;
56 import org.opendaylight.restconf.api.query.WithDefaultsParam;
57 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
58 import org.opendaylight.restconf.common.errors.RestconfError;
59 import org.opendaylight.restconf.common.errors.RestconfFuture;
60 import org.opendaylight.restconf.common.errors.SettableRestconfFuture;
61 import org.opendaylight.restconf.common.patch.PatchContext;
62 import org.opendaylight.restconf.nb.rfc8040.Insert;
63 import org.opendaylight.restconf.nb.rfc8040.legacy.ErrorTags;
64 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
65 import org.opendaylight.restconf.nb.rfc8040.legacy.WriterParameters;
66 import org.opendaylight.restconf.server.api.ChildBody;
67 import org.opendaylight.restconf.server.api.ConfigurationMetadata;
68 import org.opendaylight.restconf.server.api.CreateResourceResult;
69 import org.opendaylight.restconf.server.api.DataGetParams;
70 import org.opendaylight.restconf.server.api.DataGetResult;
71 import org.opendaylight.restconf.server.api.DataPatchResult;
72 import org.opendaylight.restconf.server.api.DataPostBody;
73 import org.opendaylight.restconf.server.api.DataPostResult;
74 import org.opendaylight.restconf.server.api.DataPutResult;
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.InvokeResult;
84 import org.opendaylight.restconf.server.api.OperationInputBody;
85 import org.opendaylight.restconf.server.api.PatchBody;
86 import org.opendaylight.restconf.server.api.PatchStatusContext;
87 import org.opendaylight.restconf.server.api.PatchStatusEntity;
88 import org.opendaylight.restconf.server.api.ResourceBody;
89 import org.opendaylight.restconf.server.api.ServerRequest;
90 import org.opendaylight.restconf.server.spi.ApiPathCanonizer;
91 import org.opendaylight.restconf.server.spi.ApiPathNormalizer;
92 import org.opendaylight.restconf.server.spi.DefaultResourceContext;
93 import org.opendaylight.restconf.server.spi.HttpGetResource;
94 import org.opendaylight.restconf.server.spi.OperationInput;
95 import org.opendaylight.restconf.server.spi.OperationOutputBody;
96 import org.opendaylight.restconf.server.spi.OperationsResource;
97 import org.opendaylight.restconf.server.spi.RpcImplementation;
98 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.with.defaults.rev110601.WithDefaultsMode;
99 import org.opendaylight.yangtools.yang.common.Empty;
100 import org.opendaylight.yangtools.yang.common.ErrorTag;
101 import org.opendaylight.yangtools.yang.common.ErrorType;
102 import org.opendaylight.yangtools.yang.common.QName;
103 import org.opendaylight.yangtools.yang.common.QNameModule;
104 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
105 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
106 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
107 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
108 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
109 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
110 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
111 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
112 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
113 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
114 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
115 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
116 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
117 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
118 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
119 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
120 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
121 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
122 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
123 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
124 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
125 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
126 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
127 import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
128 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
129 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
130 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
131 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
132 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
133 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
134 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
135 import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
136 import org.opendaylight.yangtools.yang.model.api.source.SourceRepresentation;
137 import org.opendaylight.yangtools.yang.model.api.source.YangTextSource;
138 import org.opendaylight.yangtools.yang.model.api.source.YinTextSource;
139 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
140 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleEffectiveStatement;
141 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
142 import org.slf4j.Logger;
143 import org.slf4j.LoggerFactory;
146 * Baseline execution strategy for various RESTCONF operations.
148 * @see NetconfRestconfStrategy
149 * @see MdsalRestconfStrategy
151 // FIXME: it seems the first three operations deal with lifecycle of a transaction, while others invoke various
152 // operations. This should be handled through proper allocation indirection.
153 public abstract class RestconfStrategy {
155 public record StrategyAndPath(RestconfStrategy strategy, Data path) {
156 public StrategyAndPath {
157 requireNonNull(strategy);
158 requireNonNull(path);
163 * Result of a partial {@link ApiPath} lookup for the purposes of supporting {@code yang-ext:mount}-delimited mount
164 * points with possible nesting.
166 * @param strategy the strategy to use
167 * @param tail the {@link ApiPath} tail to use with the strategy
170 public record StrategyAndTail(RestconfStrategy strategy, ApiPath tail) {
171 public StrategyAndTail {
172 requireNonNull(strategy);
173 requireNonNull(tail);
177 private static final Logger LOG = LoggerFactory.getLogger(RestconfStrategy.class);
178 private static final @NonNull DataPutResult PUT_CREATED = new DataPutResult(true);
179 private static final @NonNull DataPutResult PUT_REPLACED = new DataPutResult(false);
180 private static final @NonNull DataPatchResult PATCH_EMPTY = new DataPatchResult();
182 private final @NonNull ImmutableMap<QName, RpcImplementation> localRpcs;
183 private final @NonNull ApiPathNormalizer pathNormalizer;
184 private final @NonNull DatabindContext databind;
185 private final YangTextSourceExtension sourceProvider;
186 private final DOMMountPointService mountPointService;
187 private final DOMActionService actionService;
188 private final DOMRpcService rpcService;
189 private final HttpGetResource operations;
191 RestconfStrategy(final DatabindContext databind, final ImmutableMap<QName, RpcImplementation> localRpcs,
192 final @Nullable DOMRpcService rpcService, final @Nullable DOMActionService actionService,
193 final @Nullable YangTextSourceExtension sourceProvider,
194 final @Nullable DOMMountPointService mountPointService) {
195 this.databind = requireNonNull(databind);
196 this.localRpcs = requireNonNull(localRpcs);
197 this.rpcService = rpcService;
198 this.actionService = actionService;
199 this.sourceProvider = sourceProvider;
200 this.mountPointService = mountPointService;
201 pathNormalizer = new ApiPathNormalizer(databind);
202 operations = new OperationsResource(pathNormalizer);
205 public final @NonNull StrategyAndPath resolveStrategyPath(final ApiPath path) {
206 final var andTail = resolveStrategy(path);
207 final var strategy = andTail.strategy();
208 return new StrategyAndPath(strategy, strategy.pathNormalizer.normalizeDataPath(andTail.tail()));
212 * Resolve any and all {@code yang-ext:mount} to the target {@link StrategyAndTail}.
214 * @param path {@link ApiPath} to resolve
215 * @return A strategy and the remaining path
216 * @throws NullPointerException if {@code path} is {@code null}
218 public final @NonNull StrategyAndTail resolveStrategy(final ApiPath path) {
219 var mount = path.indexOf("yang-ext", "mount");
221 return new StrategyAndTail(this, path);
223 if (mountPointService == null) {
224 throw new RestconfDocumentedException("Mount point service is not available",
225 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
227 final var mountPath = path.subPath(0, mount);
228 final var dataPath = pathNormalizer.normalizeDataPath(path.subPath(0, mount));
229 final var mountPoint = mountPointService.getMountPoint(dataPath.instance())
230 .orElseThrow(() -> new RestconfDocumentedException("Mount point '" + mountPath + "' does not exist",
231 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
233 return createStrategy(mountPath, mountPoint).resolveStrategy(path.subPath(mount + 1));
236 private static @NonNull RestconfStrategy createStrategy(final ApiPath mountPath, final DOMMountPoint mountPoint) {
237 final var mountSchemaService = mountPoint.getService(DOMSchemaService.class)
238 .orElseThrow(() -> new RestconfDocumentedException(
239 "Mount point '" + mountPath + "' does not expose DOMSchemaService",
240 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
241 final var mountModelContext = mountSchemaService.getGlobalContext();
242 if (mountModelContext == null) {
243 throw new RestconfDocumentedException("Mount point '" + mountPath + "' does not have any models",
244 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT);
246 final var mountDatabind = DatabindContext.ofModel(mountModelContext);
247 final var mountPointService = mountPoint.getService(DOMMountPointService.class).orElse(null);
248 final var rpcService = mountPoint.getService(DOMRpcService.class).orElse(null);
249 final var actionService = mountPoint.getService(DOMActionService.class).orElse(null);
250 final var sourceProvider = mountPoint.getService(DOMSchemaService.class)
251 .flatMap(schema -> Optional.ofNullable(schema.extension(YangTextSourceExtension.class)))
254 final var netconfService = mountPoint.getService(NetconfDataTreeService.class);
255 if (netconfService.isPresent()) {
256 return new NetconfRestconfStrategy(mountDatabind, netconfService.orElseThrow(), rpcService, actionService,
257 sourceProvider, mountPointService);
259 final var dataBroker = mountPoint.getService(DOMDataBroker.class);
260 if (dataBroker.isPresent()) {
261 return new MdsalRestconfStrategy(mountDatabind, dataBroker.orElseThrow(), ImmutableMap.of(), rpcService,
262 actionService, sourceProvider, mountPointService);
264 LOG.warn("Mount point {} does not expose a suitable access interface", mountPath);
265 throw new RestconfDocumentedException("Could not find a supported access interface in mount point",
266 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, mountPoint.getIdentifier());
269 public final @NonNull DatabindContext databind() {
273 public final @NonNull EffectiveModelContext modelContext() {
274 return databind.modelContext();
278 * Lock the entire datastore.
280 * @return A {@link RestconfTransaction}. This transaction needs to be either committed or canceled before doing
283 abstract RestconfTransaction prepareWriteExecution();
286 * Read data from the datastore.
288 * @param store the logical data store which should be modified
289 * @param path the data object path
290 * @return a ListenableFuture containing the result of the read
292 abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path);
295 * Check if data already exists in the configuration datastore.
297 * @param path the data object path
298 * @return a ListenableFuture containing the result of the check
300 // FIXME: this method should be hosted in RestconfTransaction
301 // FIXME: this method should only be needed in MdsalRestconfStrategy
302 abstract ListenableFuture<Boolean> exists(YangInstanceIdentifier path);
305 final @NonNull RestconfFuture<DataPatchResult> merge(final YangInstanceIdentifier path, final NormalizedNode data) {
306 final var ret = new SettableRestconfFuture<DataPatchResult>();
307 merge(ret, requireNonNull(path), requireNonNull(data));
311 private void merge(final @NonNull SettableRestconfFuture<DataPatchResult> future,
312 final @NonNull YangInstanceIdentifier path, final @NonNull NormalizedNode data) {
313 final var tx = prepareWriteExecution();
314 // FIXME: this method should be further specialized to eliminate this call -- it is only needed for MD-SAL
315 tx.ensureParentsByMerge(path);
316 tx.merge(path, data);
317 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
319 public void onSuccess(final CommitInfo result) {
320 // TODO: extract details once CommitInfo can communicate them
321 future.set(PATCH_EMPTY);
325 public void onFailure(final Throwable cause) {
326 future.setFailure(TransactionUtil.decodeException(cause, "MERGE", path, modelContext()));
328 }, MoreExecutors.directExecutor());
331 public @NonNull RestconfFuture<DataPutResult> dataPUT(final ServerRequest request, final ApiPath apiPath,
332 final ResourceBody body) {
335 path = pathNormalizer.normalizeDataPath(apiPath);
336 } catch (RestconfDocumentedException e) {
337 return RestconfFuture.failed(e);
342 insert = Insert.of(databind, request.queryParameters());
343 } catch (IllegalArgumentException e) {
344 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
345 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
347 final NormalizedNode data;
349 data = body.toNormalizedNode(path);
350 } catch (RestconfDocumentedException e) {
351 return RestconfFuture.failed(e);
353 return putData(path.instance(), data, insert);
357 * Check mount point and prepare variables for put data to DS.
359 * @param path path of data
361 * @param insert {@link Insert}
362 * @return A {@link DataPutResult}
364 public final @NonNull RestconfFuture<DataPutResult> putData(final YangInstanceIdentifier path,
365 final NormalizedNode data, final @Nullable Insert insert) {
366 final var exists = TransactionUtil.syncAccess(exists(path), path);
368 final ListenableFuture<? extends CommitInfo> commitFuture;
369 if (insert != null) {
370 final var parentPath = path.coerceParent();
371 checkListAndOrderedType(parentPath);
372 commitFuture = insertAndCommitPut(path, data, insert, parentPath);
374 commitFuture = replaceAndCommit(prepareWriteExecution(), path, data);
377 final var ret = new SettableRestconfFuture<DataPutResult>();
379 Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
381 public void onSuccess(final CommitInfo result) {
382 ret.set(exists ? PUT_REPLACED : PUT_CREATED);
386 public void onFailure(final Throwable cause) {
387 ret.setFailure(TransactionUtil.decodeException(cause, "PUT", path, modelContext()));
389 }, MoreExecutors.directExecutor());
394 private ListenableFuture<? extends CommitInfo> insertAndCommitPut(final YangInstanceIdentifier path,
395 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parentPath) {
396 final var tx = prepareWriteExecution();
398 return switch (insert.insert()) {
400 final var readData = tx.readList(parentPath);
401 if (readData == null || readData.isEmpty()) {
402 yield replaceAndCommit(tx, path, data);
404 tx.remove(parentPath);
405 tx.replace(path, data);
406 tx.replace(parentPath, readData);
409 case LAST -> replaceAndCommit(tx, path, data);
411 final var readData = tx.readList(parentPath);
412 if (readData == null || readData.isEmpty()) {
413 yield replaceAndCommit(tx, path, data);
415 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
419 final var readData = tx.readList(parentPath);
420 if (readData == null || readData.isEmpty()) {
421 yield replaceAndCommit(tx, path, data);
423 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
429 private void insertWithPointPut(final RestconfTransaction tx, final YangInstanceIdentifier path,
430 final NormalizedNode data, final @NonNull PathArgument pointArg, final NormalizedNodeContainer<?> readList,
431 final boolean before) {
432 tx.remove(path.getParent());
434 int lastItemPosition = 0;
435 for (var nodeChild : readList.body()) {
436 if (nodeChild.name().equals(pointArg)) {
445 int lastInsertedPosition = 0;
446 final var emptySubtree = fromInstanceId(modelContext(), path.getParent());
447 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
448 for (var nodeChild : readList.body()) {
449 if (lastInsertedPosition == lastItemPosition) {
450 tx.replace(path, data);
452 final var childPath = path.coerceParent().node(nodeChild.name());
453 tx.replace(childPath, nodeChild);
454 lastInsertedPosition++;
457 // In case we are inserting after last element
459 if (lastInsertedPosition == lastItemPosition) {
460 tx.replace(path, data);
465 private static ListenableFuture<? extends CommitInfo> replaceAndCommit(final RestconfTransaction tx,
466 final YangInstanceIdentifier path, final NormalizedNode data) {
467 tx.replace(path, data);
471 private DataSchemaNode checkListAndOrderedType(final YangInstanceIdentifier path) {
472 // FIXME: we have this available in InstanceIdentifierContext
473 final var dataSchemaNode = databind.schemaTree().findChild(path).orElseThrow().dataSchemaNode();
475 final String message;
476 if (dataSchemaNode instanceof ListSchemaNode listSchema) {
477 if (listSchema.isUserOrdered()) {
480 message = "Insert parameter can be used only with ordered-by user list.";
481 } else if (dataSchemaNode instanceof LeafListSchemaNode leafListSchema) {
482 if (leafListSchema.isUserOrdered()) {
483 return leafListSchema;
485 message = "Insert parameter can be used only with ordered-by user leaf-list.";
487 message = "Insert parameter can be used only with list or leaf-list";
489 throw new RestconfDocumentedException(message, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
493 * Check mount point and prepare variables for post data.
497 * @param insert {@link Insert}
498 * @return A {@link RestconfFuture}
500 public final @NonNull RestconfFuture<CreateResourceResult> postData(final YangInstanceIdentifier path,
501 final NormalizedNode data, final @Nullable Insert insert) {
502 final ListenableFuture<? extends CommitInfo> future;
503 if (insert != null) {
504 checkListAndOrderedType(path);
505 future = insertAndCommitPost(path, data, insert);
507 future = createAndCommit(prepareWriteExecution(), path, data);
510 final var ret = new SettableRestconfFuture<CreateResourceResult>();
511 Futures.addCallback(future, new FutureCallback<CommitInfo>() {
513 public void onSuccess(final CommitInfo result) {
514 ret.set(new CreateResourceResult(new ApiPathCanonizer(databind).dataToApiPath(
515 data instanceof MapNode mapData && !mapData.isEmpty()
516 ? path.node(mapData.body().iterator().next().name()) : path)));
520 public void onFailure(final Throwable cause) {
521 ret.setFailure(TransactionUtil.decodeException(cause, "POST", path, modelContext()));
524 }, MoreExecutors.directExecutor());
528 private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
529 final NormalizedNode data, final @NonNull Insert insert) {
530 final var tx = prepareWriteExecution();
532 return switch (insert.insert()) {
534 final var readData = tx.readList(path);
535 if (readData == null || readData.isEmpty()) {
536 tx.replace(path, data);
538 checkListDataDoesNotExist(path, data);
540 tx.replace(path, data);
541 tx.replace(path, readData);
545 case LAST -> createAndCommit(tx, path, data);
547 final var readData = tx.readList(path);
548 if (readData == null || readData.isEmpty()) {
549 tx.replace(path, data);
551 checkListDataDoesNotExist(path, data);
552 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
557 final var readData = tx.readList(path);
558 if (readData == null || readData.isEmpty()) {
559 tx.replace(path, data);
561 checkListDataDoesNotExist(path, data);
562 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
570 * Merge data into the configuration datastore, as outlined in
571 * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040 section 4.6.1</a>.
573 * @param apiPath Path to merge
574 * @param body Data to merge
575 * @return A {@link RestconfFuture}
576 * @throws NullPointerException if any argument is {@code null}
578 public final @NonNull RestconfFuture<DataPatchResult> dataPATCH(final ApiPath apiPath, final ResourceBody body) {
581 path = pathNormalizer.normalizeDataPath(apiPath);
582 } catch (RestconfDocumentedException e) {
583 return RestconfFuture.failed(e);
586 final NormalizedNode data;
588 data = body.toNormalizedNode(path);
589 } catch (RestconfDocumentedException e) {
590 return RestconfFuture.failed(e);
593 return merge(path.instance(), data);
596 public final @NonNull RestconfFuture<DataYangPatchResult> dataPATCH(final ApiPath apiPath, final PatchBody body) {
599 path = pathNormalizer.normalizeDataPath(apiPath);
600 } catch (RestconfDocumentedException e) {
601 return RestconfFuture.failed(e);
604 final PatchContext patch;
606 patch = body.toPatchContext(new DefaultResourceContext(path));
607 } catch (IOException e) {
608 LOG.debug("Error parsing YANG Patch input", e);
609 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
610 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
612 return patchData(patch);
616 * Process edit operations of one {@link PatchContext}.
618 * @param patch Patch context to be processed
619 * @return {@link PatchStatusContext}
622 public final @NonNull RestconfFuture<DataYangPatchResult> patchData(final PatchContext patch) {
623 final var editCollection = new ArrayList<PatchStatusEntity>();
624 final var tx = prepareWriteExecution();
626 boolean noError = true;
627 for (var patchEntity : patch.entities()) {
629 final var targetNode = patchEntity.getTargetNode();
630 final var editId = patchEntity.getEditId();
632 switch (patchEntity.getOperation()) {
635 tx.create(targetNode, patchEntity.getNode());
636 editCollection.add(new PatchStatusEntity(editId, true, null));
637 } catch (RestconfDocumentedException e) {
638 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
644 tx.delete(targetNode);
645 editCollection.add(new PatchStatusEntity(editId, true, null));
646 } catch (RestconfDocumentedException e) {
647 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
653 tx.ensureParentsByMerge(targetNode);
654 tx.merge(targetNode, patchEntity.getNode());
655 editCollection.add(new PatchStatusEntity(editId, true, null));
656 } catch (RestconfDocumentedException e) {
657 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
663 tx.replace(targetNode, patchEntity.getNode());
664 editCollection.add(new PatchStatusEntity(editId, true, null));
665 } catch (RestconfDocumentedException e) {
666 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
672 tx.remove(targetNode);
673 editCollection.add(new PatchStatusEntity(editId, true, null));
674 } catch (RestconfDocumentedException e) {
675 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
680 editCollection.add(new PatchStatusEntity(editId, false, List.of(
681 new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
682 "Not supported Yang Patch operation"))));
691 final var ret = new SettableRestconfFuture<DataYangPatchResult>();
695 ret.set(new DataYangPatchResult(
696 new PatchStatusContext(databind(), patch.patchId(), List.copyOf(editCollection), false, null)));
700 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
702 public void onSuccess(final CommitInfo result) {
703 ret.set(new DataYangPatchResult(
704 new PatchStatusContext(databind(), patch.patchId(), List.copyOf(editCollection), true, null)));
708 public void onFailure(final Throwable cause) {
709 // if errors occurred during transaction commit then patch failed and global errors are reported
710 ret.set(new DataYangPatchResult(
711 new PatchStatusContext(databind(), patch.patchId(), List.copyOf(editCollection), false,
712 TransactionUtil.decodeException(cause, "PATCH", null, modelContext()).getErrors())));
714 }, MoreExecutors.directExecutor());
719 private static void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
720 final NormalizedNode data, final PathArgument pointArg, final NormalizedNodeContainer<?> readList,
721 final boolean before) {
724 int lastItemPosition = 0;
725 for (var nodeChild : readList.body()) {
726 if (nodeChild.name().equals(pointArg)) {
735 int lastInsertedPosition = 0;
736 for (var nodeChild : readList.body()) {
737 if (lastInsertedPosition == lastItemPosition) {
738 tx.replace(path, data);
740 tx.replace(path.node(nodeChild.name()), nodeChild);
741 lastInsertedPosition++;
744 // In case we are inserting after last element
746 if (lastInsertedPosition == lastItemPosition) {
747 tx.replace(path, data);
752 private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
753 final YangInstanceIdentifier path, final NormalizedNode data) {
755 tx.create(path, data);
756 } catch (RestconfDocumentedException e) {
757 // close transaction if any and pass exception further
766 * Check if child items do NOT already exists in List at specified {@code path}.
768 * @param data Data to be checked
769 * @param path Path to be checked
770 * @throws RestconfDocumentedException if data already exists.
772 private void checkListDataDoesNotExist(final YangInstanceIdentifier path, final NormalizedNode data) {
773 if (data instanceof NormalizedNodeContainer<?> dataNode) {
774 for (final var node : dataNode.body()) {
775 checkItemDoesNotExists(exists(path.node(node.name())), path.node(node.name()));
778 throw new RestconfDocumentedException("Unexpected node type: " + data.getClass().getName());
783 * Check if items do NOT already exists at specified {@code path}.
785 * @param existsFuture if checked data exists
786 * @param path Path to be checked
787 * @throws RestconfDocumentedException if data already exists.
789 static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
790 final YangInstanceIdentifier path) {
791 if (TransactionUtil.syncAccess(existsFuture, path)) {
792 LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
793 throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
799 * Delete data from the configuration datastore. If the data does not exist, this operation will fail, as outlined
800 * in <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.7">RFC8040 section 4.7</a>
802 * @param apiPath Path to delete
803 * @return A {@link RestconfFuture}
804 * @throws NullPointerException if {@code apiPath} is {@code null}
807 @SuppressWarnings("checkstyle:abbreviationAsWordInName")
808 public final RestconfFuture<Empty> dataDELETE(final ServerRequest request, final ApiPath apiPath) {
811 path = pathNormalizer.normalizeDataPath(apiPath);
812 } catch (RestconfDocumentedException e) {
813 return RestconfFuture.failed(e);
816 // FIXME: reject empty YangInstanceIdentifier, as datastores may not be deleted
817 final var ret = new SettableRestconfFuture<Empty>();
818 delete(ret, request, path.instance());
823 abstract void delete(SettableRestconfFuture<Empty> future, ServerRequest request, YangInstanceIdentifier path);
825 public final @NonNull RestconfFuture<DataGetResult> dataGET(final ServerRequest request, final ApiPath apiPath) {
828 path = pathNormalizer.normalizeDataPath(apiPath);
829 } catch (RestconfDocumentedException e) {
830 return RestconfFuture.failed(e);
833 final DataGetParams getParams;
835 getParams = DataGetParams.of(request.queryParameters());
836 } catch (IllegalArgumentException e) {
837 return RestconfFuture.failed(new RestconfDocumentedException(e,
838 new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, "Invalid GET /data parameters", null,
841 return dataGET(request, path, getParams);
844 abstract @NonNull RestconfFuture<DataGetResult> dataGET(ServerRequest request, Data path, DataGetParams params);
846 static final @NonNull RestconfFuture<DataGetResult> completeDataGET(final PrettyPrintParam prettyPrint,
847 final Inference inference, final WriterParameters writerParams, final @Nullable NormalizedNode node,
848 final @Nullable ConfigurationMetadata metadata) {
850 return RestconfFuture.failed(new RestconfDocumentedException(
851 "Request could not be completed because the relevant data model content does not exist",
852 ErrorType.PROTOCOL, ErrorTag.DATA_MISSING));
855 final var payload = new NormalizedNodePayload(inference, node, writerParams, prettyPrint);
856 return RestconfFuture.of(metadata == null ? new DataGetResult(payload)
857 : new DataGetResult(payload, metadata.entityTag(), metadata.lastModified()));
861 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
862 * inside of object {@link RestconfStrategy} provided as a parameter.
864 * @param content type of data to read (config, state, all)
865 * @param path the path to read
866 * @param defaultsMode value of with-defaults parameter
867 * @return {@link NormalizedNode}
869 // FIXME: NETCONF-1155: this method should asynchronous
871 final @Nullable NormalizedNode readData(final @NonNull ContentParam content,
872 final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
873 return switch (content) {
875 // PREPARE STATE DATA NODE
876 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
877 // PREPARE CONFIG DATA NODE
878 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
880 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
881 : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
884 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
885 yield defaultsMode == null ? read
886 : prepareDataByParamWithDef(read, path, defaultsMode.mode());
888 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
892 private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
893 final YangInstanceIdentifier path) {
894 return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
897 final NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
898 final WithDefaultsMode defaultsMode) {
899 final boolean trim = switch (defaultsMode) {
901 case Explicit -> false;
902 case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
903 "Unsupported with-defaults value " + defaultsMode.getName());
906 // FIXME: we have this readily available in InstanceIdentifierContext
907 final var ctxNode = databind.schemaTree().findChild(path).orElseThrow();
908 if (readData instanceof ContainerNode container) {
909 final var builder = ImmutableNodes.newContainerBuilder().withNodeIdentifier(container.name());
910 buildCont(builder, container.body(), ctxNode, trim);
911 return builder.build();
912 } else if (readData instanceof MapEntryNode mapEntry) {
913 if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
914 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
917 final var builder = ImmutableNodes.newMapEntryBuilder().withNodeIdentifier(mapEntry.name());
918 buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
919 return builder.build();
921 throw new IllegalStateException("Unhandled data contract " + readData.contract());
925 private static void buildMapEntryBuilder(
926 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
927 final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
928 final boolean trim, final List<QName> keys) {
929 for (var child : children) {
930 final var childCtx = getChildContext(ctxNode, child);
932 if (child instanceof ContainerNode container) {
933 appendContainer(builder, container, childCtx, trim);
934 } else if (child instanceof MapNode map) {
935 appendMap(builder, map, childCtx, trim);
936 } else if (child instanceof LeafNode<?> leaf) {
937 appendLeaf(builder, leaf, childCtx, trim, keys);
939 // FIXME: we should never hit this, throw an ISE if this ever happens
940 LOG.debug("Ignoring unhandled child contract {}", child.contract());
945 private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
946 final DataSchemaContext ctxNode, final boolean trim) {
947 final var childBuilder = ImmutableNodes.newContainerBuilder().withNodeIdentifier(container.name());
948 buildCont(childBuilder, container.body(), ctxNode, trim);
949 builder.withChild(childBuilder.build());
952 private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
953 final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
954 if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
955 throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
958 // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
959 final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
961 // This is a combined check for when we need to emit the leaf.
963 // We always have to emit key leaf values
964 keys.contains(leafSchema.getQName())
965 // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
967 // When data is retrieved with a <with-defaults> parameter equal to
968 // 'trim', data nodes MUST NOT be reported if they contain the schema
969 // default value. Non-configuration data nodes containing the schema
970 // default value MUST NOT be reported.
972 || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
973 // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
974 // grasp what we are doing here... emit only if it matches default ???!!!
975 // FIXME: The WithDefaultsParam.EXPLICIT says:
977 // Data nodes set to the YANG default by the client are reported.
979 // and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
981 // If the "with-defaults" parameter is set to "explicit", then the
982 // server MUST adhere to the default-reporting behavior defined in
983 // Section 3.3 of [RFC6243].
985 // and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
987 // When data is retrieved with a <with-defaults> parameter equal to
988 // 'explicit', a data node that was set by a client to its schema
989 // default value MUST be reported. A conceptual data node that would be
990 // set by the server to the schema default value MUST NOT be reported.
991 // Non-configuration data nodes containing the schema default value MUST
994 // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
995 // This seems to disregard the 'trim = true' case semantics (see above).
996 // Combining the above, though, these checks are missing the 'non-config' check, which would
997 // distinguish, but barring that this check is superfluous and results in the wrong semantics.
998 // Without that input, this really should be covered by the previous case.
999 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
1000 builder.withChild(leaf);
1004 private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
1005 final DataSchemaContext childCtx, final boolean trim) {
1006 if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
1007 throw new IllegalStateException("Input " + map + " does not match " + childCtx);
1010 final var childBuilder = switch (map.ordering()) {
1011 case SYSTEM -> ImmutableNodes.newSystemMapBuilder();
1012 case USER -> ImmutableNodes.newUserMapBuilder();
1014 buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
1015 listSchema.getKeyDefinition());
1016 builder.withChild(childBuilder.build());
1019 private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
1020 final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
1021 final List<@NonNull QName> keys) {
1022 for (var entry : entries) {
1023 final var childCtx = getChildContext(ctxNode, entry);
1024 final var mapEntryBuilder = ImmutableNodes.newMapEntryBuilder().withNodeIdentifier(entry.name());
1025 buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
1026 builder.withChild(mapEntryBuilder.build());
1030 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
1031 final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
1032 for (var child : children) {
1033 final var childCtx = getChildContext(ctxNode, child);
1034 if (child instanceof ContainerNode container) {
1035 appendContainer(builder, container, childCtx, trim);
1036 } else if (child instanceof MapNode map) {
1037 appendMap(builder, map, childCtx, trim);
1038 } else if (child instanceof LeafNode<?> leaf) {
1039 appendLeaf(builder, leaf, childCtx, trim, List.of());
1044 private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
1045 final NormalizedNode child) {
1046 final var childId = child.name();
1047 final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
1049 if (childCtx == null) {
1050 throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
1055 static final NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
1056 final NormalizedNode configDataNode) {
1057 if (stateDataNode == null) {
1058 // No state, return config
1059 return configDataNode;
1061 if (configDataNode == null) {
1062 // No config, return state
1063 return stateDataNode;
1065 // merge config and state
1066 return mergeStateAndConfigData(stateDataNode, configDataNode);
1070 * Merge state and config data into a single NormalizedNode.
1072 * @param stateDataNode data node of state data
1073 * @param configDataNode data node of config data
1074 * @return {@link NormalizedNode}
1076 private static @NonNull NormalizedNode mergeStateAndConfigData(
1077 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
1078 validateNodeMerge(stateDataNode, configDataNode);
1079 // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
1080 if (configDataNode instanceof RpcDefinition) {
1081 return prepareRpcData(configDataNode, stateDataNode);
1083 return prepareData(configDataNode, stateDataNode);
1088 * Validates whether the two NormalizedNodes can be merged.
1090 * @param stateDataNode data node of state data
1091 * @param configDataNode data node of config data
1093 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
1094 final @NonNull NormalizedNode configDataNode) {
1095 final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
1096 final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
1097 if (!moduleOfStateData.equals(moduleOfConfigData)) {
1098 throw new RestconfDocumentedException("Unable to merge data from different modules.");
1103 * Prepare and map data for rpc.
1105 * @param configDataNode data node of config data
1106 * @param stateDataNode data node of state data
1107 * @return {@link NormalizedNode}
1109 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
1110 final @NonNull NormalizedNode stateDataNode) {
1111 final var mapEntryBuilder = ImmutableNodes.newMapEntryBuilder()
1112 .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
1115 mapRpcDataNode(configDataNode, mapEntryBuilder);
1117 mapRpcDataNode(stateDataNode, mapEntryBuilder);
1119 return ImmutableNodes.newSystemMapBuilder()
1120 .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
1121 .addChild(mapEntryBuilder.build())
1126 * Map node to map entry builder.
1128 * @param dataNode data node
1129 * @param mapEntryBuilder builder for mapping data
1131 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
1132 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
1133 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
1137 * Prepare and map all data from DS.
1139 * @param configDataNode data node of config data
1140 * @param stateDataNode data node of state data
1141 * @return {@link NormalizedNode}
1143 @SuppressWarnings("unchecked")
1144 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
1145 final @NonNull NormalizedNode stateDataNode) {
1146 if (configDataNode instanceof UserMapNode configMap) {
1147 final var builder = ImmutableNodes.newUserMapBuilder().withNodeIdentifier(configMap.name());
1148 mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
1149 return builder.build();
1150 } else if (configDataNode instanceof SystemMapNode configMap) {
1151 final var builder = ImmutableNodes.newSystemMapBuilder().withNodeIdentifier(configMap.name());
1152 mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
1153 return builder.build();
1154 } else if (configDataNode instanceof MapEntryNode configEntry) {
1155 final var builder = ImmutableNodes.newMapEntryBuilder().withNodeIdentifier(configEntry.name());
1156 mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
1157 return builder.build();
1158 } else if (configDataNode instanceof ContainerNode configContaienr) {
1159 final var builder = ImmutableNodes.newContainerBuilder().withNodeIdentifier(configContaienr.name());
1160 mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
1161 return builder.build();
1162 } else if (configDataNode instanceof ChoiceNode configChoice) {
1163 final var builder = ImmutableNodes.newChoiceBuilder().withNodeIdentifier(configChoice.name());
1164 mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
1165 return builder.build();
1166 } else if (configDataNode instanceof LeafNode configLeaf) {
1167 // config trumps oper
1169 } else if (configDataNode instanceof UserLeafSetNode) {
1170 final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
1171 final var builder = ImmutableNodes.<Object>newUserLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
1172 mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
1173 return builder.build();
1174 } else if (configDataNode instanceof SystemLeafSetNode) {
1175 final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
1176 final var builder = ImmutableNodes.<Object>newSystemLeafSetBuilder()
1177 .withNodeIdentifier(configLeafSet.name());
1178 mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
1179 return builder.build();
1180 } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
1181 // config trumps oper
1183 } else if (configDataNode instanceof UnkeyedListNode configList) {
1184 final var builder = ImmutableNodes.newUnkeyedListBuilder().withNodeIdentifier(configList.name());
1185 mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
1186 return builder.build();
1187 } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
1188 final var builder = ImmutableNodes.newUnkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
1189 mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
1190 return builder.build();
1192 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
1197 * Map value from container node to builder.
1199 * @param configData collection of config data nodes
1200 * @param stateData collection of state data nodes
1201 * @param builder builder
1203 private static <T extends NormalizedNode> void mapValueToBuilder(
1204 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
1205 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1206 final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1207 final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1209 // merge config and state data of children with different identifiers
1210 mapDataToBuilder(configMap, stateMap, builder);
1212 // merge config and state data of children with the same identifiers
1213 mergeDataToBuilder(configMap, stateMap, builder);
1217 * Map data with different identifiers to builder. Data with different identifiers can be just added
1218 * as childs to parent node.
1220 * @param configMap map of config data nodes
1221 * @param stateMap map of state data nodes
1222 * @param builder - builder
1224 private static <T extends NormalizedNode> void mapDataToBuilder(
1225 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1226 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1227 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
1228 y -> builder.addChild(y.getValue()));
1229 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
1230 y -> builder.addChild(y.getValue()));
1234 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
1235 * go one level down with {@code prepareData} method.
1237 * @param configMap immutable config data
1238 * @param stateMap immutable state data
1239 * @param builder - builder
1241 @SuppressWarnings("unchecked")
1242 private static <T extends NormalizedNode> void mergeDataToBuilder(
1243 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1244 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1245 // it is enough to process only config data because operational contains the same data
1246 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1247 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1251 public RestconfFuture<FormattableBody> operationsGET(final ServerRequest request) {
1252 return operations.httpGET(request);
1256 public RestconfFuture<FormattableBody> operationsGET(final ServerRequest request, final ApiPath apiPath) {
1257 return operations.httpGET(request, apiPath);
1260 public @NonNull RestconfFuture<InvokeResult> operationsPOST(final ServerRequest request, final URI restconfURI,
1261 final ApiPath apiPath, final OperationInputBody body) {
1264 path = pathNormalizer.normalizeRpcPath(apiPath);
1265 } catch (RestconfDocumentedException e) {
1266 return RestconfFuture.failed(e);
1269 final ContainerNode data;
1271 data = body.toContainerNode(path);
1272 } catch (IOException e) {
1273 LOG.debug("Error reading input", e);
1274 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1275 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1278 final var type = path.rpc().argument();
1279 final var local = localRpcs.get(type);
1280 if (local != null) {
1281 return local.invoke(restconfURI, new OperationInput(path, data))
1282 .transform(output -> outputToInvokeResult(path, output));
1284 if (rpcService == null) {
1285 LOG.debug("RPC invocation is not available");
1286 return RestconfFuture.failed(new RestconfDocumentedException("RPC invocation is not available",
1287 ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED));
1290 final var ret = new SettableRestconfFuture<InvokeResult>();
1291 Futures.addCallback(rpcService.invokeRpc(type, data), new FutureCallback<DOMRpcResult>() {
1293 public void onSuccess(final DOMRpcResult response) {
1294 final var errors = response.errors();
1295 if (errors.isEmpty()) {
1296 ret.set(outputToInvokeResult(path, response.value()));
1298 LOG.debug("RPC invocation reported {}", response.errors());
1299 ret.setFailure(new RestconfDocumentedException("RPC implementation reported errors", null,
1300 response.errors()));
1305 public void onFailure(final Throwable cause) {
1306 LOG.debug("RPC invocation failed, cause");
1307 if (cause instanceof RestconfDocumentedException ex) {
1310 // TODO: YangNetconfErrorAware if we ever get into a broader invocation scope
1311 ret.setFailure(new RestconfDocumentedException(cause,
1312 new RestconfError(ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage())));
1315 }, MoreExecutors.directExecutor());
1319 private static @NonNull InvokeResult outputToInvokeResult(final @NonNull OperationPath path,
1320 final @Nullable ContainerNode value) {
1321 return value == null || value.isEmpty() ? InvokeResult.EMPTY
1322 : new InvokeResult(new OperationOutputBody(path, value));
1325 public @NonNull RestconfFuture<CharSource> resolveSource(final SourceIdentifier source,
1326 final Class<? extends SourceRepresentation> representation) {
1327 final var src = requireNonNull(source);
1328 if (YangTextSource.class.isAssignableFrom(representation)) {
1329 if (sourceProvider != null) {
1330 final var ret = new SettableRestconfFuture<CharSource>();
1331 Futures.addCallback(sourceProvider.getYangTexttSource(src), new FutureCallback<>() {
1333 public void onSuccess(final YangTextSource result) {
1338 public void onFailure(final Throwable cause) {
1339 ret.setFailure(cause instanceof RestconfDocumentedException e ? e
1340 : new RestconfDocumentedException(cause.getMessage(), ErrorType.RPC,
1341 ErrorTag.OPERATION_FAILED, cause));
1343 }, MoreExecutors.directExecutor());
1346 return exportSource(modelContext(), src, YangCharSource::new, YangCharSource::new);
1348 if (YinTextSource.class.isAssignableFrom(representation)) {
1349 return exportSource(modelContext(), src, YinCharSource.OfModule::new, YinCharSource.OfSubmodule::new);
1351 return RestconfFuture.failed(new RestconfDocumentedException(
1352 "Unsupported source representation " + representation.getName()));
1355 private static @NonNull RestconfFuture<CharSource> exportSource(final EffectiveModelContext modelContext,
1356 final SourceIdentifier source, final Function<ModuleEffectiveStatement, CharSource> moduleCtor,
1357 final BiFunction<ModuleEffectiveStatement, SubmoduleEffectiveStatement, CharSource> submoduleCtor) {
1358 // If the source identifies a module, things are easy
1359 final var name = source.name().getLocalName();
1360 final var optRevision = Optional.ofNullable(source.revision());
1361 final var optModule = modelContext.findModule(name, optRevision);
1362 if (optModule.isPresent()) {
1363 return RestconfFuture.of(moduleCtor.apply(optModule.orElseThrow().asEffectiveStatement()));
1366 // The source could be a submodule, which we need to hunt down
1367 for (var module : modelContext.getModules()) {
1368 for (var submodule : module.getSubmodules()) {
1369 if (name.equals(submodule.getName()) && optRevision.equals(submodule.getRevision())) {
1370 return RestconfFuture.of(submoduleCtor.apply(module.asEffectiveStatement(),
1371 submodule.asEffectiveStatement()));
1376 final var sb = new StringBuilder().append("Source ").append(source.name().getLocalName());
1377 optRevision.ifPresent(rev -> sb.append('@').append(rev));
1378 sb.append(" not found");
1379 return RestconfFuture.failed(new RestconfDocumentedException(sb.toString(),
1380 ErrorType.APPLICATION, ErrorTag.DATA_MISSING));
1383 public final @NonNull RestconfFuture<? extends DataPostResult> dataPOST(final ServerRequest request,
1384 final ApiPath apiPath, final DataPostBody body) {
1385 if (apiPath.isEmpty()) {
1386 return dataCreatePOST(request, body.toResource());
1388 final InstanceReference path;
1390 path = pathNormalizer.normalizeDataOrActionPath(apiPath);
1391 } catch (RestconfDocumentedException e) {
1392 return RestconfFuture.failed(e);
1394 if (path instanceof Data dataPath) {
1395 try (var resourceBody = body.toResource()) {
1396 return dataCreatePOST(request, dataPath, resourceBody);
1399 if (path instanceof Action actionPath) {
1400 try (var inputBody = body.toOperationInput()) {
1401 return dataInvokePOST(actionPath, inputBody);
1404 // Note: this should never happen
1405 // FIXME: we should be able to eliminate this path with Java 21+ pattern matching
1406 return RestconfFuture.failed(new RestconfDocumentedException("Unhandled path " + path));
1409 public @NonNull RestconfFuture<CreateResourceResult> dataCreatePOST(final ServerRequest request,
1410 final ChildBody body) {
1411 return dataCreatePOST(request, new DatabindPath.Data(databind), body);
1414 private @NonNull RestconfFuture<CreateResourceResult> dataCreatePOST(final ServerRequest request,
1415 final DatabindPath.Data path, final ChildBody body) {
1416 final Insert insert;
1418 insert = Insert.of(path.databind(), request.queryParameters());
1419 } catch (IllegalArgumentException e) {
1420 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
1421 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
1424 final var payload = body.toPayload(path);
1425 return postData(concat(path.instance(), payload.prefix()), payload.body(), insert);
1428 private static YangInstanceIdentifier concat(final YangInstanceIdentifier parent, final List<PathArgument> args) {
1430 for (var arg : args) {
1431 ret = ret.node(arg);
1436 private @NonNull RestconfFuture<InvokeResult> dataInvokePOST(final @NonNull Action path,
1437 final @NonNull OperationInputBody body) {
1438 final ContainerNode input;
1440 input = body.toContainerNode(path);
1441 } catch (IOException e) {
1442 LOG.debug("Error reading input", e);
1443 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1444 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1447 if (actionService == null) {
1448 return RestconfFuture.failed(new RestconfDocumentedException("DOMActionService is missing."));
1451 return dataInvokePOST(actionService, path, input)
1452 .transform(result -> outputToInvokeResult(path, result.getOutput().orElse(null)));
1456 * Invoke Action via ActionServiceHandler.
1458 * @param input input data
1459 * @param yangIId invocation context
1460 * @param schemaPath schema path of data
1461 * @param actionService action service to invoke action
1462 * @return {@link DOMActionResult}
1464 private static RestconfFuture<DOMActionResult> dataInvokePOST(final DOMActionService actionService,
1465 final Action path, final @NonNull ContainerNode input) {
1466 final var ret = new SettableRestconfFuture<DOMActionResult>();
1468 Futures.addCallback(actionService.invokeAction(
1469 path.inference().toSchemaInferenceStack().toSchemaNodeIdentifier(),
1470 DOMDataTreeIdentifier.of(LogicalDatastoreType.OPERATIONAL, path.instance()), input),
1471 new FutureCallback<DOMActionResult>() {
1473 public void onSuccess(final DOMActionResult result) {
1474 final var errors = result.getErrors();
1475 LOG.debug("InvokeAction Error Message {}", errors);
1476 if (errors.isEmpty()) {
1479 ret.setFailure(new RestconfDocumentedException("InvokeAction Error Message ", null, errors));
1484 public void onFailure(final Throwable cause) {
1485 if (cause instanceof DOMActionException) {
1486 ret.set(new SimpleDOMActionResult(List.of(RpcResultBuilder.newError(
1487 ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage()))));
1488 } else if (cause instanceof RestconfDocumentedException e) {
1490 } else if (cause instanceof CancellationException) {
1491 ret.setFailure(new RestconfDocumentedException("Action cancelled while executing",
1492 ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, cause));
1494 ret.setFailure(new RestconfDocumentedException("Invocation failed", cause));
1497 }, MoreExecutors.directExecutor());