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.collect.ImmutableSet;
17 import com.google.common.collect.ImmutableSetMultimap;
18 import com.google.common.io.CharSource;
19 import com.google.common.util.concurrent.FutureCallback;
20 import com.google.common.util.concurrent.Futures;
21 import com.google.common.util.concurrent.ListenableFuture;
22 import com.google.common.util.concurrent.MoreExecutors;
23 import java.io.IOException;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.Comparator;
28 import java.util.HashMap;
29 import java.util.List;
31 import java.util.Map.Entry;
32 import java.util.NoSuchElementException;
33 import java.util.Optional;
34 import java.util.concurrent.CancellationException;
35 import java.util.function.BiFunction;
36 import java.util.function.Function;
37 import java.util.stream.Collectors;
38 import org.eclipse.jdt.annotation.NonNull;
39 import org.eclipse.jdt.annotation.NonNullByDefault;
40 import org.eclipse.jdt.annotation.Nullable;
41 import org.opendaylight.mdsal.common.api.CommitInfo;
42 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
43 import org.opendaylight.mdsal.dom.api.DOMActionException;
44 import org.opendaylight.mdsal.dom.api.DOMActionResult;
45 import org.opendaylight.mdsal.dom.api.DOMActionService;
46 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
47 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
48 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
49 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
50 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
51 import org.opendaylight.mdsal.dom.api.DOMRpcService;
52 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
53 import org.opendaylight.mdsal.dom.api.DOMSchemaService.YangTextSourceExtension;
54 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
55 import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult;
56 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
57 import org.opendaylight.restconf.api.ApiPath;
58 import org.opendaylight.restconf.api.query.ContentParam;
59 import org.opendaylight.restconf.api.query.WithDefaultsParam;
60 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
61 import org.opendaylight.restconf.common.errors.RestconfError;
62 import org.opendaylight.restconf.common.errors.RestconfFuture;
63 import org.opendaylight.restconf.common.errors.SettableRestconfFuture;
64 import org.opendaylight.restconf.common.patch.PatchContext;
65 import org.opendaylight.restconf.common.patch.PatchStatusContext;
66 import org.opendaylight.restconf.common.patch.PatchStatusEntity;
67 import org.opendaylight.restconf.nb.rfc8040.Insert;
68 import org.opendaylight.restconf.nb.rfc8040.legacy.ErrorTags;
69 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
70 import org.opendaylight.restconf.nb.rfc8040.legacy.QueryParameters;
71 import org.opendaylight.restconf.server.api.ChildBody;
72 import org.opendaylight.restconf.server.api.ConfigurationMetadata;
73 import org.opendaylight.restconf.server.api.DataGetParams;
74 import org.opendaylight.restconf.server.api.DataGetResult;
75 import org.opendaylight.restconf.server.api.DataPatchResult;
76 import org.opendaylight.restconf.server.api.DataPostBody;
77 import org.opendaylight.restconf.server.api.DataPostResult;
78 import org.opendaylight.restconf.server.api.DataPostResult.CreateResource;
79 import org.opendaylight.restconf.server.api.DataPostResult.InvokeOperation;
80 import org.opendaylight.restconf.server.api.DataPutResult;
81 import org.opendaylight.restconf.server.api.DataYangPatchResult;
82 import org.opendaylight.restconf.server.api.DatabindContext;
83 import org.opendaylight.restconf.server.api.DatabindPath;
84 import org.opendaylight.restconf.server.api.DatabindPath.Action;
85 import org.opendaylight.restconf.server.api.DatabindPath.Data;
86 import org.opendaylight.restconf.server.api.DatabindPath.InstanceReference;
87 import org.opendaylight.restconf.server.api.DatabindPath.Rpc;
88 import org.opendaylight.restconf.server.api.OperationInputBody;
89 import org.opendaylight.restconf.server.api.OperationsGetResult;
90 import org.opendaylight.restconf.server.api.OperationsPostResult;
91 import org.opendaylight.restconf.server.api.PatchBody;
92 import org.opendaylight.restconf.server.api.ResourceBody;
93 import org.opendaylight.restconf.server.spi.ApiPathCanonizer;
94 import org.opendaylight.restconf.server.spi.ApiPathNormalizer;
95 import org.opendaylight.restconf.server.spi.OperationInput;
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.Revision;
104 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
105 import org.opendaylight.yangtools.yang.common.XMLNamespace;
106 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
107 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
108 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
109 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
110 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
111 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
112 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
113 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
114 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
115 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
116 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
117 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
118 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
119 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
120 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
121 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
122 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
123 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
124 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
125 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
126 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
127 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
128 import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
129 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
130 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
131 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
132 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
133 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
134 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
135 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
136 import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
137 import org.opendaylight.yangtools.yang.model.api.source.SourceRepresentation;
138 import org.opendaylight.yangtools.yang.model.api.source.YangTextSource;
139 import org.opendaylight.yangtools.yang.model.api.source.YinTextSource;
140 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
141 import org.opendaylight.yangtools.yang.model.api.stmt.RpcEffectiveStatement;
142 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleEffectiveStatement;
143 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
144 import org.slf4j.Logger;
145 import org.slf4j.LoggerFactory;
148 * Baseline execution strategy for various RESTCONF operations.
150 * @see NetconfRestconfStrategy
151 * @see MdsalRestconfStrategy
153 // FIXME: it seems the first three operations deal with lifecycle of a transaction, while others invoke various
154 // operations. This should be handled through proper allocation indirection.
155 public abstract class RestconfStrategy {
157 public record StrategyAndPath(RestconfStrategy strategy, Data path) {
158 public StrategyAndPath {
159 requireNonNull(strategy);
160 requireNonNull(path);
165 * Result of a partial {@link ApiPath} lookup for the purposes of supporting {@code yang-ext:mount}-delimited mount
166 * points with possible nesting.
168 * @param strategy the strategy to use
169 * @param tail the {@link ApiPath} tail to use with the strategy
172 public record StrategyAndTail(RestconfStrategy strategy, ApiPath tail) {
173 public StrategyAndTail {
174 requireNonNull(strategy);
175 requireNonNull(tail);
179 private static final Logger LOG = LoggerFactory.getLogger(RestconfStrategy.class);
180 private static final @NonNull DataPutResult PUT_CREATED = new DataPutResult(true);
181 private static final @NonNull DataPutResult PUT_REPLACED = new DataPutResult(false);
182 private static final @NonNull DataPatchResult PATCH_EMPTY = new DataPatchResult();
184 private final @NonNull ImmutableMap<QName, RpcImplementation> localRpcs;
185 private final @NonNull ApiPathNormalizer pathNormalizer;
186 private final @NonNull DatabindContext databind;
187 private final YangTextSourceExtension sourceProvider;
188 private final DOMMountPointService mountPointService;
189 private final DOMActionService actionService;
190 private final DOMRpcService rpcService;
192 RestconfStrategy(final DatabindContext databind, final ImmutableMap<QName, RpcImplementation> localRpcs,
193 final @Nullable DOMRpcService rpcService, final @Nullable DOMActionService actionService,
194 final YangTextSourceExtension sourceProvider, 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);
204 public final @NonNull StrategyAndPath resolveStrategyPath(final ApiPath path) {
205 final var andTail = resolveStrategy(path);
206 final var strategy = andTail.strategy();
207 return new StrategyAndPath(strategy, strategy.pathNormalizer.normalizeDataPath(andTail.tail()));
211 * Resolve any and all {@code yang-ext:mount} to the target {@link StrategyAndTail}.
213 * @param path {@link ApiPath} to resolve
214 * @return A strategy and the remaining path
215 * @throws NullPointerException if {@code path} is {@code null}
217 public final @NonNull StrategyAndTail resolveStrategy(final ApiPath path) {
218 var mount = path.indexOf("yang-ext", "mount");
220 return new StrategyAndTail(this, path);
222 if (mountPointService == null) {
223 throw new RestconfDocumentedException("Mount point service is not available",
224 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
226 final var mountPath = path.subPath(0, mount);
227 final var dataPath = pathNormalizer.normalizeDataPath(path.subPath(0, mount));
228 final var mountPoint = mountPointService.getMountPoint(dataPath.instance())
229 .orElseThrow(() -> new RestconfDocumentedException("Mount point '" + mountPath + "' does not exist",
230 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
232 return createStrategy(mountPath, mountPoint).resolveStrategy(path.subPath(mount + 1));
235 private static @NonNull RestconfStrategy createStrategy(final ApiPath mountPath, final DOMMountPoint mountPoint) {
236 final var mountSchemaService = mountPoint.getService(DOMSchemaService.class)
237 .orElseThrow(() -> new RestconfDocumentedException(
238 "Mount point '" + mountPath + "' does not expose DOMSchemaService",
239 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
240 final var mountModelContext = mountSchemaService.getGlobalContext();
241 if (mountModelContext == null) {
242 throw new RestconfDocumentedException("Mount point '" + mountPath + "' does not have any models",
243 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT);
245 final var mountDatabind = DatabindContext.ofModel(mountModelContext);
246 final var mountPointService = mountPoint.getService(DOMMountPointService.class).orElse(null);
247 final var rpcService = mountPoint.getService(DOMRpcService.class).orElse(null);
248 final var actionService = mountPoint.getService(DOMActionService.class).orElse(null);
249 final var sourceProvider = mountPoint.getService(DOMSchemaService.class)
250 .flatMap(schema -> Optional.ofNullable(schema.extension(YangTextSourceExtension.class)))
253 final var netconfService = mountPoint.getService(NetconfDataTreeService.class);
254 if (netconfService.isPresent()) {
255 return new NetconfRestconfStrategy(mountDatabind, netconfService.orElseThrow(), rpcService, actionService,
256 sourceProvider, mountPointService);
258 final var dataBroker = mountPoint.getService(DOMDataBroker.class);
259 if (dataBroker.isPresent()) {
260 return new MdsalRestconfStrategy(mountDatabind, dataBroker.orElseThrow(), rpcService, actionService,
261 sourceProvider, mountPointService);
263 LOG.warn("Mount point {} does not expose a suitable access interface", mountPath);
264 throw new RestconfDocumentedException("Could not find a supported access interface in mount point",
265 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, mountPoint.getIdentifier());
268 public final @NonNull DatabindContext databind() {
272 public final @NonNull EffectiveModelContext modelContext() {
273 return databind.modelContext();
277 * Lock the entire datastore.
279 * @return A {@link RestconfTransaction}. This transaction needs to be either committed or canceled before doing
282 abstract RestconfTransaction prepareWriteExecution();
285 * Read data from the datastore.
287 * @param store the logical data store which should be modified
288 * @param path the data object path
289 * @return a ListenableFuture containing the result of the read
291 abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path);
294 * Check if data already exists in the configuration datastore.
296 * @param path the data object path
297 * @return a ListenableFuture containing the result of the check
299 // FIXME: this method should be hosted in RestconfTransaction
300 // FIXME: this method should only be needed in MdsalRestconfStrategy
301 abstract ListenableFuture<Boolean> exists(YangInstanceIdentifier path);
304 final @NonNull RestconfFuture<DataPatchResult> merge(final YangInstanceIdentifier path, final NormalizedNode data) {
305 final var ret = new SettableRestconfFuture<DataPatchResult>();
306 merge(ret, requireNonNull(path), requireNonNull(data));
310 private void merge(final @NonNull SettableRestconfFuture<DataPatchResult> future,
311 final @NonNull YangInstanceIdentifier path, final @NonNull NormalizedNode data) {
312 final var tx = prepareWriteExecution();
313 // FIXME: this method should be further specialized to eliminate this call -- it is only needed for MD-SAL
314 tx.ensureParentsByMerge(path);
315 tx.merge(path, data);
316 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
318 public void onSuccess(final CommitInfo result) {
319 // TODO: extract details once CommitInfo can communicate them
320 future.set(PATCH_EMPTY);
324 public void onFailure(final Throwable cause) {
325 future.setFailure(TransactionUtil.decodeException(cause, "MERGE", path, modelContext()));
327 }, MoreExecutors.directExecutor());
330 public @NonNull RestconfFuture<DataPutResult> dataPUT(final ApiPath apiPath, final ResourceBody body,
331 final Map<String, String> queryParameters) {
334 path = pathNormalizer.normalizeDataPath(apiPath);
335 } catch (RestconfDocumentedException e) {
336 return RestconfFuture.failed(e);
341 insert = Insert.ofQueryParameters(databind, queryParameters);
342 } catch (IllegalArgumentException e) {
343 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
344 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
346 final NormalizedNode data;
348 data = body.toNormalizedNode(path);
349 } catch (RestconfDocumentedException e) {
350 return RestconfFuture.failed(e);
352 return putData(path.instance(), data, insert);
356 * Check mount point and prepare variables for put data to DS.
358 * @param path path of data
360 * @param insert {@link Insert}
361 * @return A {@link DataPutResult}
363 public final @NonNull RestconfFuture<DataPutResult> putData(final YangInstanceIdentifier path,
364 final NormalizedNode data, final @Nullable Insert insert) {
365 final var exists = TransactionUtil.syncAccess(exists(path), path);
367 final ListenableFuture<? extends CommitInfo> commitFuture;
368 if (insert != null) {
369 final var parentPath = path.coerceParent();
370 checkListAndOrderedType(parentPath);
371 commitFuture = insertAndCommitPut(path, data, insert, parentPath);
373 commitFuture = replaceAndCommit(prepareWriteExecution(), path, data);
376 final var ret = new SettableRestconfFuture<DataPutResult>();
378 Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
380 public void onSuccess(final CommitInfo result) {
381 ret.set(exists ? PUT_REPLACED : PUT_CREATED);
385 public void onFailure(final Throwable cause) {
386 ret.setFailure(TransactionUtil.decodeException(cause, "PUT", path, modelContext()));
388 }, MoreExecutors.directExecutor());
393 private ListenableFuture<? extends CommitInfo> insertAndCommitPut(final YangInstanceIdentifier path,
394 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parentPath) {
395 final var tx = prepareWriteExecution();
397 return switch (insert.insert()) {
399 final var readData = tx.readList(parentPath);
400 if (readData == null || readData.isEmpty()) {
401 yield replaceAndCommit(tx, path, data);
403 tx.remove(parentPath);
404 tx.replace(path, data);
405 tx.replace(parentPath, readData);
408 case LAST -> replaceAndCommit(tx, path, data);
410 final var readData = tx.readList(parentPath);
411 if (readData == null || readData.isEmpty()) {
412 yield replaceAndCommit(tx, path, data);
414 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
418 final var readData = tx.readList(parentPath);
419 if (readData == null || readData.isEmpty()) {
420 yield replaceAndCommit(tx, path, data);
422 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
428 private void insertWithPointPut(final RestconfTransaction tx, final YangInstanceIdentifier path,
429 final NormalizedNode data, final @NonNull PathArgument pointArg, final NormalizedNodeContainer<?> readList,
430 final boolean before) {
431 tx.remove(path.getParent());
433 int lastItemPosition = 0;
434 for (var nodeChild : readList.body()) {
435 if (nodeChild.name().equals(pointArg)) {
444 int lastInsertedPosition = 0;
445 final var emptySubtree = fromInstanceId(modelContext(), path.getParent());
446 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
447 for (var nodeChild : readList.body()) {
448 if (lastInsertedPosition == lastItemPosition) {
449 tx.replace(path, data);
451 final var childPath = path.coerceParent().node(nodeChild.name());
452 tx.replace(childPath, nodeChild);
453 lastInsertedPosition++;
456 // In case we are inserting after last element
458 if (lastInsertedPosition == lastItemPosition) {
459 tx.replace(path, data);
464 private static ListenableFuture<? extends CommitInfo> replaceAndCommit(final RestconfTransaction tx,
465 final YangInstanceIdentifier path, final NormalizedNode data) {
466 tx.replace(path, data);
470 private DataSchemaNode checkListAndOrderedType(final YangInstanceIdentifier path) {
471 // FIXME: we have this available in InstanceIdentifierContext
472 final var dataSchemaNode = databind.schemaTree().findChild(path).orElseThrow().dataSchemaNode();
474 final String message;
475 if (dataSchemaNode instanceof ListSchemaNode listSchema) {
476 if (listSchema.isUserOrdered()) {
479 message = "Insert parameter can be used only with ordered-by user list.";
480 } else if (dataSchemaNode instanceof LeafListSchemaNode leafListSchema) {
481 if (leafListSchema.isUserOrdered()) {
482 return leafListSchema;
484 message = "Insert parameter can be used only with ordered-by user leaf-list.";
486 message = "Insert parameter can be used only with list or leaf-list";
488 throw new RestconfDocumentedException(message, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
492 * Check mount point and prepare variables for post data.
496 * @param insert {@link Insert}
497 * @return A {@link RestconfFuture}
499 public final @NonNull RestconfFuture<CreateResource> postData(final YangInstanceIdentifier path,
500 final NormalizedNode data, final @Nullable Insert insert) {
501 final ListenableFuture<? extends CommitInfo> future;
502 if (insert != null) {
503 checkListAndOrderedType(path);
504 future = insertAndCommitPost(path, data, insert);
506 future = createAndCommit(prepareWriteExecution(), path, data);
509 final var ret = new SettableRestconfFuture<CreateResource>();
510 Futures.addCallback(future, new FutureCallback<CommitInfo>() {
512 public void onSuccess(final CommitInfo result) {
513 ret.set(new CreateResource(new ApiPathCanonizer(databind).dataToApiPath(
514 data instanceof MapNode mapData && !mapData.isEmpty()
515 ? path.node(mapData.body().iterator().next().name()) : path).toString()));
519 public void onFailure(final Throwable cause) {
520 ret.setFailure(TransactionUtil.decodeException(cause, "POST", path, modelContext()));
523 }, MoreExecutors.directExecutor());
527 private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
528 final NormalizedNode data, final @NonNull Insert insert) {
529 final var tx = prepareWriteExecution();
531 return switch (insert.insert()) {
533 final var readData = tx.readList(path);
534 if (readData == null || readData.isEmpty()) {
535 tx.replace(path, data);
537 checkListDataDoesNotExist(path, data);
539 tx.replace(path, data);
540 tx.replace(path, readData);
544 case LAST -> createAndCommit(tx, path, data);
546 final var readData = tx.readList(path);
547 if (readData == null || readData.isEmpty()) {
548 tx.replace(path, data);
550 checkListDataDoesNotExist(path, data);
551 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
556 final var readData = tx.readList(path);
557 if (readData == null || readData.isEmpty()) {
558 tx.replace(path, data);
560 checkListDataDoesNotExist(path, data);
561 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
569 * Merge data into the configuration datastore, as outlined in
570 * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040 section 4.6.1</a>.
572 * @param apiPath Path to merge
573 * @param body Data to merge
574 * @return A {@link RestconfFuture}
575 * @throws NullPointerException if any argument is {@code null}
577 public final @NonNull RestconfFuture<DataPatchResult> dataPATCH(final ApiPath apiPath, final ResourceBody body) {
580 path = pathNormalizer.normalizeDataPath(apiPath);
581 } catch (RestconfDocumentedException e) {
582 return RestconfFuture.failed(e);
585 final NormalizedNode data;
587 data = body.toNormalizedNode(path);
588 } catch (RestconfDocumentedException e) {
589 return RestconfFuture.failed(e);
592 return merge(path.instance(), data);
595 public final @NonNull RestconfFuture<DataYangPatchResult> dataPATCH(final ApiPath apiPath, final PatchBody body) {
598 path = pathNormalizer.normalizeDataPath(apiPath);
599 } catch (RestconfDocumentedException e) {
600 return RestconfFuture.failed(e);
603 final PatchContext patch;
605 patch = body.toPatchContext(path);
606 } catch (IOException e) {
607 LOG.debug("Error parsing YANG Patch input", e);
608 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
609 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
611 return patchData(patch);
615 * Process edit operations of one {@link PatchContext}.
617 * @param patch Patch context to be processed
618 * @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(modelContext(), 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(modelContext(), 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(modelContext(), patch.patchId(), List.copyOf(editCollection), false,
710 TransactionUtil.decodeException(cause, "PATCH", null, modelContext()).getErrors())));
712 }, MoreExecutors.directExecutor());
717 private 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}
804 @SuppressWarnings("checkstyle:abbreviationAsWordInName")
805 public final @NonNull RestconfFuture<Empty> dataDELETE(final ApiPath apiPath) {
808 path = pathNormalizer.normalizeDataPath(apiPath);
809 } catch (RestconfDocumentedException e) {
810 return RestconfFuture.failed(e);
813 // FIXME: reject empty YangInstanceIdentifier, as datastores may not be deleted
814 final var ret = new SettableRestconfFuture<Empty>();
815 delete(ret, path.instance());
819 abstract void delete(@NonNull SettableRestconfFuture<Empty> future, @NonNull YangInstanceIdentifier path);
821 public final @NonNull RestconfFuture<DataGetResult> dataGET(final ApiPath apiPath,
822 final DataGetParams params) {
825 path = pathNormalizer.normalizeDataPath(apiPath);
826 } catch (RestconfDocumentedException e) {
827 return RestconfFuture.failed(e);
829 return dataGET(path, params);
832 abstract @NonNull RestconfFuture<DataGetResult> dataGET(Data path, DataGetParams params);
834 static final @NonNull RestconfFuture<DataGetResult> completeDataGET(final Inference inference,
835 final QueryParameters queryParams, final @Nullable NormalizedNode node,
836 final @Nullable ConfigurationMetadata metadata) {
838 return RestconfFuture.failed(new RestconfDocumentedException(
839 "Request could not be completed because the relevant data model content does not exist",
840 ErrorType.PROTOCOL, ErrorTag.DATA_MISSING));
843 final var payload = new NormalizedNodePayload(inference, node, queryParams);
844 return RestconfFuture.of(metadata == null ? new DataGetResult(payload)
845 : new DataGetResult(payload, metadata.entityTag(), metadata.lastModified()));
849 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
850 * inside of object {@link RestconfStrategy} provided as a parameter.
852 * @param content type of data to read (config, state, all)
853 * @param path the path to read
854 * @param defaultsMode value of with-defaults parameter
855 * @return {@link NormalizedNode}
857 // FIXME: NETCONF-1155: this method should asynchronous
859 final @Nullable NormalizedNode readData(final @NonNull ContentParam content,
860 final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
861 return switch (content) {
863 // PREPARE STATE DATA NODE
864 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
865 // PREPARE CONFIG DATA NODE
866 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
868 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
869 : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
872 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
873 yield defaultsMode == null ? read
874 : prepareDataByParamWithDef(read, path, defaultsMode.mode());
876 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
880 private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
881 final YangInstanceIdentifier path) {
882 return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
885 final NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
886 final WithDefaultsMode defaultsMode) {
887 final boolean trim = switch (defaultsMode) {
889 case Explicit -> false;
890 case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
891 "Unsupported with-defaults value " + defaultsMode.getName());
894 // FIXME: we have this readily available in InstanceIdentifierContext
895 final var ctxNode = databind.schemaTree().findChild(path).orElseThrow();
896 if (readData instanceof ContainerNode container) {
897 final var builder = ImmutableNodes.newContainerBuilder().withNodeIdentifier(container.name());
898 buildCont(builder, container.body(), ctxNode, trim);
899 return builder.build();
900 } else if (readData instanceof MapEntryNode mapEntry) {
901 if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
902 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
905 final var builder = ImmutableNodes.newMapEntryBuilder().withNodeIdentifier(mapEntry.name());
906 buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
907 return builder.build();
909 throw new IllegalStateException("Unhandled data contract " + readData.contract());
913 private static void buildMapEntryBuilder(
914 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
915 final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
916 final boolean trim, final List<QName> keys) {
917 for (var child : children) {
918 final var childCtx = getChildContext(ctxNode, child);
920 if (child instanceof ContainerNode container) {
921 appendContainer(builder, container, childCtx, trim);
922 } else if (child instanceof MapNode map) {
923 appendMap(builder, map, childCtx, trim);
924 } else if (child instanceof LeafNode<?> leaf) {
925 appendLeaf(builder, leaf, childCtx, trim, keys);
927 // FIXME: we should never hit this, throw an ISE if this ever happens
928 LOG.debug("Ignoring unhandled child contract {}", child.contract());
933 private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
934 final DataSchemaContext ctxNode, final boolean trim) {
935 final var childBuilder = ImmutableNodes.newContainerBuilder().withNodeIdentifier(container.name());
936 buildCont(childBuilder, container.body(), ctxNode, trim);
937 builder.withChild(childBuilder.build());
940 private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
941 final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
942 if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
943 throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
946 // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
947 final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
949 // This is a combined check for when we need to emit the leaf.
951 // We always have to emit key leaf values
952 keys.contains(leafSchema.getQName())
953 // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
955 // When data is retrieved with a <with-defaults> parameter equal to
956 // 'trim', data nodes MUST NOT be reported if they contain the schema
957 // default value. Non-configuration data nodes containing the schema
958 // default value MUST NOT be reported.
960 || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
961 // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
962 // grasp what we are doing here... emit only if it matches default ???!!!
963 // FIXME: The WithDefaultsParam.EXPLICIT says:
965 // Data nodes set to the YANG default by the client are reported.
967 // and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
969 // If the "with-defaults" parameter is set to "explicit", then the
970 // server MUST adhere to the default-reporting behavior defined in
971 // Section 3.3 of [RFC6243].
973 // and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
975 // When data is retrieved with a <with-defaults> parameter equal to
976 // 'explicit', a data node that was set by a client to its schema
977 // default value MUST be reported. A conceptual data node that would be
978 // set by the server to the schema default value MUST NOT be reported.
979 // Non-configuration data nodes containing the schema default value MUST
982 // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
983 // This seems to disregard the 'trim = true' case semantics (see above).
984 // Combining the above, though, these checks are missing the 'non-config' check, which would
985 // distinguish, but barring that this check is superfluous and results in the wrong semantics.
986 // Without that input, this really should be covered by the previous case.
987 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
988 builder.withChild(leaf);
992 private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
993 final DataSchemaContext childCtx, final boolean trim) {
994 if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
995 throw new IllegalStateException("Input " + map + " does not match " + childCtx);
998 final var childBuilder = switch (map.ordering()) {
999 case SYSTEM -> ImmutableNodes.newSystemMapBuilder();
1000 case USER -> ImmutableNodes.newUserMapBuilder();
1002 buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
1003 listSchema.getKeyDefinition());
1004 builder.withChild(childBuilder.build());
1007 private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
1008 final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
1009 final List<@NonNull QName> keys) {
1010 for (var entry : entries) {
1011 final var childCtx = getChildContext(ctxNode, entry);
1012 final var mapEntryBuilder = ImmutableNodes.newMapEntryBuilder().withNodeIdentifier(entry.name());
1013 buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
1014 builder.withChild(mapEntryBuilder.build());
1018 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
1019 final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
1020 for (var child : children) {
1021 final var childCtx = getChildContext(ctxNode, child);
1022 if (child instanceof ContainerNode container) {
1023 appendContainer(builder, container, childCtx, trim);
1024 } else if (child instanceof MapNode map) {
1025 appendMap(builder, map, childCtx, trim);
1026 } else if (child instanceof LeafNode<?> leaf) {
1027 appendLeaf(builder, leaf, childCtx, trim, List.of());
1032 private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
1033 final NormalizedNode child) {
1034 final var childId = child.name();
1035 final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
1037 if (childCtx == null) {
1038 throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
1043 static final NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
1044 final NormalizedNode configDataNode) {
1045 if (stateDataNode == null) {
1046 // No state, return config
1047 return configDataNode;
1049 if (configDataNode == null) {
1050 // No config, return state
1051 return stateDataNode;
1053 // merge config and state
1054 return mergeStateAndConfigData(stateDataNode, configDataNode);
1058 * Merge state and config data into a single NormalizedNode.
1060 * @param stateDataNode data node of state data
1061 * @param configDataNode data node of config data
1062 * @return {@link NormalizedNode}
1064 private static @NonNull NormalizedNode mergeStateAndConfigData(
1065 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
1066 validateNodeMerge(stateDataNode, configDataNode);
1067 // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
1068 if (configDataNode instanceof RpcDefinition) {
1069 return prepareRpcData(configDataNode, stateDataNode);
1071 return prepareData(configDataNode, stateDataNode);
1076 * Validates whether the two NormalizedNodes can be merged.
1078 * @param stateDataNode data node of state data
1079 * @param configDataNode data node of config data
1081 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
1082 final @NonNull NormalizedNode configDataNode) {
1083 final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
1084 final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
1085 if (!moduleOfStateData.equals(moduleOfConfigData)) {
1086 throw new RestconfDocumentedException("Unable to merge data from different modules.");
1091 * Prepare and map data for rpc.
1093 * @param configDataNode data node of config data
1094 * @param stateDataNode data node of state data
1095 * @return {@link NormalizedNode}
1097 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
1098 final @NonNull NormalizedNode stateDataNode) {
1099 final var mapEntryBuilder = ImmutableNodes.newMapEntryBuilder()
1100 .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
1103 mapRpcDataNode(configDataNode, mapEntryBuilder);
1105 mapRpcDataNode(stateDataNode, mapEntryBuilder);
1107 return ImmutableNodes.newSystemMapBuilder()
1108 .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
1109 .addChild(mapEntryBuilder.build())
1114 * Map node to map entry builder.
1116 * @param dataNode data node
1117 * @param mapEntryBuilder builder for mapping data
1119 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
1120 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
1121 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
1125 * Prepare and map all data from DS.
1127 * @param configDataNode data node of config data
1128 * @param stateDataNode data node of state data
1129 * @return {@link NormalizedNode}
1131 @SuppressWarnings("unchecked")
1132 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
1133 final @NonNull NormalizedNode stateDataNode) {
1134 if (configDataNode instanceof UserMapNode configMap) {
1135 final var builder = ImmutableNodes.newUserMapBuilder().withNodeIdentifier(configMap.name());
1136 mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
1137 return builder.build();
1138 } else if (configDataNode instanceof SystemMapNode configMap) {
1139 final var builder = ImmutableNodes.newSystemMapBuilder().withNodeIdentifier(configMap.name());
1140 mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
1141 return builder.build();
1142 } else if (configDataNode instanceof MapEntryNode configEntry) {
1143 final var builder = ImmutableNodes.newMapEntryBuilder().withNodeIdentifier(configEntry.name());
1144 mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
1145 return builder.build();
1146 } else if (configDataNode instanceof ContainerNode configContaienr) {
1147 final var builder = ImmutableNodes.newContainerBuilder().withNodeIdentifier(configContaienr.name());
1148 mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
1149 return builder.build();
1150 } else if (configDataNode instanceof ChoiceNode configChoice) {
1151 final var builder = ImmutableNodes.newChoiceBuilder().withNodeIdentifier(configChoice.name());
1152 mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
1153 return builder.build();
1154 } else if (configDataNode instanceof LeafNode configLeaf) {
1155 // config trumps oper
1157 } else if (configDataNode instanceof UserLeafSetNode) {
1158 final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
1159 final var builder = ImmutableNodes.<Object>newUserLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
1160 mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
1161 return builder.build();
1162 } else if (configDataNode instanceof SystemLeafSetNode) {
1163 final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
1164 final var builder = ImmutableNodes.<Object>newSystemLeafSetBuilder()
1165 .withNodeIdentifier(configLeafSet.name());
1166 mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
1167 return builder.build();
1168 } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
1169 // config trumps oper
1171 } else if (configDataNode instanceof UnkeyedListNode configList) {
1172 final var builder = ImmutableNodes.newUnkeyedListBuilder().withNodeIdentifier(configList.name());
1173 mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
1174 return builder.build();
1175 } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
1176 final var builder = ImmutableNodes.newUnkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
1177 mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
1178 return builder.build();
1180 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
1185 * Map value from container node to builder.
1187 * @param configData collection of config data nodes
1188 * @param stateData collection of state data nodes
1189 * @param builder builder
1191 private static <T extends NormalizedNode> void mapValueToBuilder(
1192 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
1193 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1194 final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1195 final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1197 // merge config and state data of children with different identifiers
1198 mapDataToBuilder(configMap, stateMap, builder);
1200 // merge config and state data of children with the same identifiers
1201 mergeDataToBuilder(configMap, stateMap, builder);
1205 * Map data with different identifiers to builder. Data with different identifiers can be just added
1206 * as childs to parent node.
1208 * @param configMap map of config data nodes
1209 * @param stateMap map of state data nodes
1210 * @param builder - builder
1212 private static <T extends NormalizedNode> void mapDataToBuilder(
1213 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1214 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1215 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
1216 y -> builder.addChild(y.getValue()));
1217 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
1218 y -> builder.addChild(y.getValue()));
1222 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
1223 * go one level down with {@code prepareData} method.
1225 * @param configMap immutable config data
1226 * @param stateMap immutable state data
1227 * @param builder - builder
1229 @SuppressWarnings("unchecked")
1230 private static <T extends NormalizedNode> void mergeDataToBuilder(
1231 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1232 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1233 // it is enough to process only config data because operational contains the same data
1234 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1235 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1238 public @NonNull RestconfFuture<OperationsGetResult> operationsGET() {
1239 final var modelContext = modelContext();
1240 final var modules = modelContext.getModuleStatements();
1241 if (modules.isEmpty()) {
1242 // No modules, or defensive return empty content
1243 return RestconfFuture.of(new OperationsGetResult.Container(modelContext, ImmutableSetMultimap.of()));
1246 // RPC QNames by their XMLNamespace/Revision. This should be a Table, but Revision can be null, which wrecks us.
1247 final var table = new HashMap<XMLNamespace, Map<Revision, ImmutableSet<QName>>>();
1248 for (var entry : modules.entrySet()) {
1249 final var module = entry.getValue();
1250 final var rpcNames = module.streamEffectiveSubstatements(RpcEffectiveStatement.class)
1251 .map(RpcEffectiveStatement::argument)
1252 .collect(ImmutableSet.toImmutableSet());
1253 if (!rpcNames.isEmpty()) {
1254 final var namespace = entry.getKey();
1255 table.computeIfAbsent(namespace.namespace(), ignored -> new HashMap<>())
1256 .put(namespace.revision(), rpcNames);
1260 // Now pick the latest revision for each namespace
1261 final var rpcs = ImmutableSetMultimap.<QNameModule, QName>builder();
1262 for (var entry : table.entrySet()) {
1263 entry.getValue().entrySet().stream()
1264 .sorted(Comparator.comparing(Entry::getKey, (first, second) -> Revision.compare(second, first)))
1266 .ifPresent(row -> rpcs.putAll(QNameModule.of(entry.getKey(), row.getKey()), row.getValue()));
1268 return RestconfFuture.of(new OperationsGetResult.Container(modelContext, rpcs.build()));
1271 public @NonNull RestconfFuture<OperationsGetResult> operationsGET(final ApiPath apiPath) {
1272 if (apiPath.steps().isEmpty()) {
1273 return operationsGET();
1278 rpc = pathNormalizer.normalizeRpcPath(apiPath);
1279 } catch (RestconfDocumentedException e) {
1280 return RestconfFuture.failed(e);
1283 return RestconfFuture.of(new OperationsGetResult.Leaf(rpc.inference().modelContext(), rpc.rpc().argument()));
1286 public @NonNull RestconfFuture<OperationsPostResult> operationsPOST(final URI restconfURI, final ApiPath apiPath,
1287 final OperationInputBody body) {
1290 path = pathNormalizer.normalizeRpcPath(apiPath);
1291 } catch (RestconfDocumentedException e) {
1292 return RestconfFuture.failed(e);
1295 final ContainerNode data;
1297 data = body.toContainerNode(path);
1298 } catch (IOException e) {
1299 LOG.debug("Error reading input", e);
1300 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1301 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1304 final var type = path.rpc().argument();
1305 final var local = localRpcs.get(type);
1306 if (local != null) {
1307 return local.invoke(restconfURI, new OperationInput(path, data));
1309 if (rpcService == null) {
1310 LOG.debug("RPC invocation is not available");
1311 return RestconfFuture.failed(new RestconfDocumentedException("RPC invocation is not available",
1312 ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED));
1315 final var ret = new SettableRestconfFuture<OperationsPostResult>();
1316 Futures.addCallback(rpcService.invokeRpc(type, data), new FutureCallback<DOMRpcResult>() {
1318 public void onSuccess(final DOMRpcResult response) {
1319 final var errors = response.errors();
1320 if (errors.isEmpty()) {
1321 ret.set(new OperationsPostResult(path, response.value()));
1323 LOG.debug("RPC invocation reported {}", response.errors());
1324 ret.setFailure(new RestconfDocumentedException("RPC implementation reported errors", null,
1325 response.errors()));
1330 public void onFailure(final Throwable cause) {
1331 LOG.debug("RPC invocation failed, cause");
1332 if (cause instanceof RestconfDocumentedException ex) {
1335 // TODO: YangNetconfErrorAware if we ever get into a broader invocation scope
1336 ret.setFailure(new RestconfDocumentedException(cause,
1337 new RestconfError(ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage())));
1340 }, MoreExecutors.directExecutor());
1344 public @NonNull RestconfFuture<CharSource> resolveSource(final SourceIdentifier source,
1345 final Class<? extends SourceRepresentation> representation) {
1346 final var src = requireNonNull(source);
1347 if (YangTextSource.class.isAssignableFrom(representation)) {
1348 if (sourceProvider != null) {
1349 final var ret = new SettableRestconfFuture<CharSource>();
1350 Futures.addCallback(sourceProvider.getYangTexttSource(src), new FutureCallback<>() {
1352 public void onSuccess(final YangTextSource result) {
1357 public void onFailure(final Throwable cause) {
1358 ret.setFailure(cause instanceof RestconfDocumentedException e ? e
1359 : new RestconfDocumentedException(cause.getMessage(), ErrorType.RPC,
1360 ErrorTag.OPERATION_FAILED, cause));
1362 }, MoreExecutors.directExecutor());
1365 return exportSource(modelContext(), src, YangCharSource::new, YangCharSource::new);
1367 if (YinTextSource.class.isAssignableFrom(representation)) {
1368 return exportSource(modelContext(), src, YinCharSource.OfModule::new, YinCharSource.OfSubmodule::new);
1370 return RestconfFuture.failed(new RestconfDocumentedException(
1371 "Unsupported source representation " + representation.getName()));
1374 private static @NonNull RestconfFuture<CharSource> exportSource(final EffectiveModelContext modelContext,
1375 final SourceIdentifier source, final Function<ModuleEffectiveStatement, CharSource> moduleCtor,
1376 final BiFunction<ModuleEffectiveStatement, SubmoduleEffectiveStatement, CharSource> submoduleCtor) {
1377 // If the source identifies a module, things are easy
1378 final var name = source.name().getLocalName();
1379 final var optRevision = Optional.ofNullable(source.revision());
1380 final var optModule = modelContext.findModule(name, optRevision);
1381 if (optModule.isPresent()) {
1382 return RestconfFuture.of(moduleCtor.apply(optModule.orElseThrow().asEffectiveStatement()));
1385 // The source could be a submodule, which we need to hunt down
1386 for (var module : modelContext.getModules()) {
1387 for (var submodule : module.getSubmodules()) {
1388 if (name.equals(submodule.getName()) && optRevision.equals(submodule.getRevision())) {
1389 return RestconfFuture.of(submoduleCtor.apply(module.asEffectiveStatement(),
1390 submodule.asEffectiveStatement()));
1395 final var sb = new StringBuilder().append("Source ").append(source.name().getLocalName());
1396 optRevision.ifPresent(rev -> sb.append('@').append(rev));
1397 sb.append(" not found");
1398 return RestconfFuture.failed(new RestconfDocumentedException(sb.toString(),
1399 ErrorType.APPLICATION, ErrorTag.DATA_MISSING));
1402 public final @NonNull RestconfFuture<? extends DataPostResult> dataPOST(final ApiPath apiPath,
1403 final DataPostBody body, final Map<String, String> queryParameters) {
1404 if (apiPath.steps().isEmpty()) {
1405 return dataCreatePOST(body.toResource(), queryParameters);
1407 final InstanceReference path;
1409 path = pathNormalizer.normalizeDataOrActionPath(apiPath);
1410 } catch (RestconfDocumentedException e) {
1411 return RestconfFuture.failed(e);
1413 if (path instanceof Data dataPath) {
1414 try (var resourceBody = body.toResource()) {
1415 return dataCreatePOST(dataPath, resourceBody, queryParameters);
1418 if (path instanceof Action actionPath) {
1419 try (var inputBody = body.toOperationInput()) {
1420 return dataInvokePOST(actionPath, inputBody);
1423 // Note: this should never happen
1424 // FIXME: we should be able to eliminate this path with Java 21+ pattern matching
1425 return RestconfFuture.failed(new RestconfDocumentedException("Unhandled path " + path));
1428 public @NonNull RestconfFuture<CreateResource> dataCreatePOST(final ChildBody body,
1429 final Map<String, String> queryParameters) {
1430 return dataCreatePOST(new DatabindPath.Data(databind), body, queryParameters);
1433 private @NonNull RestconfFuture<CreateResource> dataCreatePOST(final DatabindPath.Data path, final ChildBody body,
1434 final Map<String, String> queryParameters) {
1435 final Insert insert;
1437 insert = Insert.ofQueryParameters(path.databind(), queryParameters);
1438 } catch (IllegalArgumentException e) {
1439 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
1440 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
1443 final var payload = body.toPayload(path);
1444 return postData(concat(path.instance(), payload.prefix()), payload.body(), insert);
1447 private static YangInstanceIdentifier concat(final YangInstanceIdentifier parent, final List<PathArgument> args) {
1449 for (var arg : args) {
1450 ret = ret.node(arg);
1455 private @NonNull RestconfFuture<InvokeOperation> dataInvokePOST(final Action path, final OperationInputBody body) {
1456 final ContainerNode input;
1458 input = body.toContainerNode(path);
1459 } catch (IOException e) {
1460 LOG.debug("Error reading input", e);
1461 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1462 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1465 if (actionService == null) {
1466 return RestconfFuture.failed(new RestconfDocumentedException("DOMActionService is missing."));
1469 final var future = dataInvokePOST(actionService, path, input);
1470 return future.transform(result -> result.getOutput()
1471 .flatMap(output -> output.isEmpty() ? Optional.empty()
1472 : Optional.of(new InvokeOperation(new NormalizedNodePayload(path.inference(), output))))
1473 .orElse(InvokeOperation.EMPTY));
1477 * Invoke Action via ActionServiceHandler.
1479 * @param input input data
1480 * @param yangIId invocation context
1481 * @param schemaPath schema path of data
1482 * @param actionService action service to invoke action
1483 * @return {@link DOMActionResult}
1485 private static RestconfFuture<DOMActionResult> dataInvokePOST(final DOMActionService actionService,
1486 final Action path, final @NonNull ContainerNode input) {
1487 final var ret = new SettableRestconfFuture<DOMActionResult>();
1489 Futures.addCallback(actionService.invokeAction(
1490 path.inference().toSchemaInferenceStack().toSchemaNodeIdentifier(),
1491 DOMDataTreeIdentifier.of(LogicalDatastoreType.OPERATIONAL, path.instance()), input),
1492 new FutureCallback<DOMActionResult>() {
1494 public void onSuccess(final DOMActionResult result) {
1495 final var errors = result.getErrors();
1496 LOG.debug("InvokeAction Error Message {}", errors);
1497 if (errors.isEmpty()) {
1500 ret.setFailure(new RestconfDocumentedException("InvokeAction Error Message ", null, errors));
1505 public void onFailure(final Throwable cause) {
1506 if (cause instanceof DOMActionException) {
1507 ret.set(new SimpleDOMActionResult(List.of(RpcResultBuilder.newError(
1508 ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage()))));
1509 } else if (cause instanceof RestconfDocumentedException e) {
1511 } else if (cause instanceof CancellationException) {
1512 ret.setFailure(new RestconfDocumentedException("Action cancelled while executing",
1513 ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, cause));
1515 ret.setFailure(new RestconfDocumentedException("Invocation failed", cause));
1518 }, MoreExecutors.directExecutor());