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;
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.ImmutableSet;
16 import com.google.common.collect.ImmutableSetMultimap;
17 import com.google.common.io.CharSource;
18 import com.google.common.util.concurrent.FutureCallback;
19 import com.google.common.util.concurrent.Futures;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.MoreExecutors;
22 import java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Comparator;
27 import java.util.HashMap;
28 import java.util.List;
30 import java.util.Map.Entry;
31 import java.util.NoSuchElementException;
32 import java.util.Optional;
33 import java.util.concurrent.CancellationException;
34 import java.util.function.BiFunction;
35 import java.util.function.Function;
36 import java.util.stream.Collectors;
37 import org.eclipse.jdt.annotation.NonNull;
38 import org.eclipse.jdt.annotation.NonNullByDefault;
39 import org.eclipse.jdt.annotation.Nullable;
40 import org.opendaylight.mdsal.common.api.CommitInfo;
41 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
42 import org.opendaylight.mdsal.dom.api.DOMActionException;
43 import org.opendaylight.mdsal.dom.api.DOMActionResult;
44 import org.opendaylight.mdsal.dom.api.DOMActionService;
45 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
46 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
47 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
48 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
49 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
50 import org.opendaylight.mdsal.dom.api.DOMRpcService;
51 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
52 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
53 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
54 import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult;
55 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
56 import org.opendaylight.restconf.api.ApiPath;
57 import org.opendaylight.restconf.api.query.ContentParam;
58 import org.opendaylight.restconf.api.query.WithDefaultsParam;
59 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
60 import org.opendaylight.restconf.common.errors.RestconfError;
61 import org.opendaylight.restconf.common.errors.RestconfFuture;
62 import org.opendaylight.restconf.common.errors.SettableRestconfFuture;
63 import org.opendaylight.restconf.common.patch.PatchContext;
64 import org.opendaylight.restconf.common.patch.PatchStatusContext;
65 import org.opendaylight.restconf.common.patch.PatchStatusEntity;
66 import org.opendaylight.restconf.nb.rfc8040.Insert;
67 import org.opendaylight.restconf.nb.rfc8040.databind.ChildBody;
68 import org.opendaylight.restconf.nb.rfc8040.databind.DataPostBody;
69 import org.opendaylight.restconf.nb.rfc8040.databind.OperationInputBody;
70 import org.opendaylight.restconf.nb.rfc8040.databind.PatchBody;
71 import org.opendaylight.restconf.nb.rfc8040.databind.ResourceBody;
72 import org.opendaylight.restconf.nb.rfc8040.legacy.ErrorTags;
73 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
74 import org.opendaylight.restconf.nb.rfc8040.legacy.QueryParameters;
75 import org.opendaylight.restconf.nb.rfc8040.utils.parser.YangInstanceIdentifierSerializer;
76 import org.opendaylight.restconf.server.api.ConfigurationMetadata;
77 import org.opendaylight.restconf.server.api.DataGetParams;
78 import org.opendaylight.restconf.server.api.DataGetResult;
79 import org.opendaylight.restconf.server.api.DataPatchPath;
80 import org.opendaylight.restconf.server.api.DataPatchResult;
81 import org.opendaylight.restconf.server.api.DataPostPath;
82 import org.opendaylight.restconf.server.api.DataPostResult;
83 import org.opendaylight.restconf.server.api.DataPostResult.CreateResource;
84 import org.opendaylight.restconf.server.api.DataPostResult.InvokeOperation;
85 import org.opendaylight.restconf.server.api.DataPutPath;
86 import org.opendaylight.restconf.server.api.DataPutResult;
87 import org.opendaylight.restconf.server.api.DatabindContext;
88 import org.opendaylight.restconf.server.api.OperationsGetResult;
89 import org.opendaylight.restconf.server.api.OperationsPostPath;
90 import org.opendaylight.restconf.server.api.OperationsPostResult;
91 import org.opendaylight.restconf.server.spi.ApiPathNormalizer;
92 import org.opendaylight.restconf.server.spi.ApiPathNormalizer.DataPath;
93 import org.opendaylight.restconf.server.spi.ApiPathNormalizer.InstanceReference;
94 import org.opendaylight.restconf.server.spi.ApiPathNormalizer.OperationPath;
95 import org.opendaylight.restconf.server.spi.ApiPathNormalizer.OperationPath.Rpc;
96 import org.opendaylight.restconf.server.spi.OperationInput;
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.Revision;
105 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
106 import org.opendaylight.yangtools.yang.common.XMLNamespace;
107 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
108 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
109 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
110 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
111 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
112 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
113 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
114 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
115 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
116 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
117 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
118 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
119 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
120 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
121 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
122 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
123 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
124 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
125 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
126 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
127 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
128 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
129 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
130 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
131 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
132 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
133 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
134 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
135 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
136 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
137 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
138 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
139 import org.opendaylight.yangtools.yang.model.api.stmt.RpcEffectiveStatement;
140 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleEffectiveStatement;
141 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
142 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
143 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
144 import org.opendaylight.yangtools.yang.model.repo.api.YinTextSchemaSource;
145 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
146 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
147 import org.slf4j.Logger;
148 import org.slf4j.LoggerFactory;
151 * Baseline execution strategy for various RESTCONF operations.
153 * @see NetconfRestconfStrategy
154 * @see MdsalRestconfStrategy
156 // FIXME: it seems the first three operations deal with lifecycle of a transaction, while others invoke various
157 // operations. This should be handled through proper allocation indirection.
158 public abstract class RestconfStrategy {
160 public record StrategyAndPath(RestconfStrategy strategy, DataPath path) {
161 public StrategyAndPath {
162 requireNonNull(strategy);
163 requireNonNull(path);
168 * Result of a partial {@link ApiPath} lookup for the purposes of supporting {@code yang-ext:mount}-delimited mount
169 * points with possible nesting.
171 * @param strategy the strategy to use
172 * @param tail the {@link ApiPath} tail to use with the strategy
175 public record StrategyAndTail(RestconfStrategy strategy, ApiPath tail) {
176 public StrategyAndTail {
177 requireNonNull(strategy);
178 requireNonNull(tail);
182 private static final Logger LOG = LoggerFactory.getLogger(RestconfStrategy.class);
183 private static final @NonNull DataPutResult PUT_CREATED = new DataPutResult(true);
184 private static final @NonNull DataPutResult PUT_REPLACED = new DataPutResult(false);
185 private static final @NonNull DataPatchResult PATCH_EMPTY = new DataPatchResult();
187 private final @NonNull ImmutableMap<QName, RpcImplementation> localRpcs;
188 private final @NonNull ApiPathNormalizer pathNormalizer;
189 private final @NonNull DatabindContext databind;
190 private final DOMYangTextSourceProvider sourceProvider;
191 private final DOMMountPointService mountPointService;
192 private final DOMActionService actionService;
193 private final DOMRpcService rpcService;
195 RestconfStrategy(final DatabindContext databind, final ImmutableMap<QName, RpcImplementation> localRpcs,
196 final @Nullable DOMRpcService rpcService, final @Nullable DOMActionService actionService,
197 final DOMYangTextSourceProvider sourceProvider, final @Nullable DOMMountPointService mountPointService) {
198 this.databind = requireNonNull(databind);
199 this.localRpcs = requireNonNull(localRpcs);
200 this.rpcService = rpcService;
201 this.actionService = actionService;
202 this.sourceProvider = sourceProvider;
203 this.mountPointService = mountPointService;
204 pathNormalizer = new ApiPathNormalizer(databind);
207 public final @NonNull StrategyAndPath resolveStrategyPath(final ApiPath path) {
208 final var andTail = resolveStrategy(path);
209 final var strategy = andTail.strategy();
210 return new StrategyAndPath(strategy, strategy.pathNormalizer.normalizeDataPath(andTail.tail()));
214 * Resolve any and all {@code yang-ext:mount} to the target {@link StrategyAndTail}.
216 * @param path {@link ApiPath} to resolve
217 * @return A strategy and the remaining path
218 * @throws NullPointerException if {@code path} is {@code null}
220 public final @NonNull StrategyAndTail resolveStrategy(final ApiPath path) {
221 var mount = path.indexOf("yang-ext", "mount");
223 return new StrategyAndTail(this, path);
225 if (mountPointService == null) {
226 throw new RestconfDocumentedException("Mount point service is not available",
227 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
229 final var mountPath = path.subPath(0, mount);
230 final var dataPath = pathNormalizer.normalizeDataPath(path.subPath(0, mount));
231 final var mountPoint = mountPointService.getMountPoint(dataPath.instance())
232 .orElseThrow(() -> new RestconfDocumentedException("Mount point '" + mountPath + "' does not exist",
233 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
235 return createStrategy(mountPath, mountPoint).resolveStrategy(path.subPath(mount + 1));
238 private static @NonNull RestconfStrategy createStrategy(final ApiPath mountPath, final DOMMountPoint mountPoint) {
239 final var mountSchemaService = mountPoint.getService(DOMSchemaService.class)
240 .orElseThrow(() -> new RestconfDocumentedException(
241 "Mount point '" + mountPath + "' does not expose DOMSchemaService",
242 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
243 final var mountModelContext = mountSchemaService.getGlobalContext();
244 if (mountModelContext == null) {
245 throw new RestconfDocumentedException("Mount point '" + mountPath + "' does not have any models",
246 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT);
248 final var mountDatabind = DatabindContext.ofModel(mountModelContext);
249 final var mountPointService = mountPoint.getService(DOMMountPointService.class).orElse(null);
250 final var rpcService = mountPoint.getService(DOMRpcService.class).orElse(null);
251 final var actionService = mountPoint.getService(DOMActionService.class).orElse(null);
252 final var sourceProvider = mountPoint.getService(DOMSchemaService.class)
253 .flatMap(schema -> Optional.ofNullable(schema.getExtensions().getInstance(DOMYangTextSourceProvider.class)))
256 final var netconfService = mountPoint.getService(NetconfDataTreeService.class);
257 if (netconfService.isPresent()) {
258 return new NetconfRestconfStrategy(mountDatabind, netconfService.orElseThrow(), rpcService, actionService,
259 sourceProvider, mountPointService);
261 final var dataBroker = mountPoint.getService(DOMDataBroker.class);
262 if (dataBroker.isPresent()) {
263 return new MdsalRestconfStrategy(mountDatabind, dataBroker.orElseThrow(), rpcService, actionService,
264 sourceProvider, mountPointService);
266 LOG.warn("Mount point {} does not expose a suitable access interface", mountPath);
267 throw new RestconfDocumentedException("Could not find a supported access interface in mount point",
268 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, mountPoint.getIdentifier());
271 public final @NonNull DatabindContext databind() {
275 public final @NonNull EffectiveModelContext modelContext() {
276 return databind.modelContext();
280 * Lock the entire datastore.
282 * @return A {@link RestconfTransaction}. This transaction needs to be either committed or canceled before doing
285 abstract RestconfTransaction prepareWriteExecution();
288 * Read data from the datastore.
290 * @param store the logical data store which should be modified
291 * @param path the data object path
292 * @return a ListenableFuture containing the result of the read
294 abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path);
297 * Check if data already exists in the configuration datastore.
299 * @param path the data object path
300 * @return a ListenableFuture containing the result of the check
302 // FIXME: this method should be hosted in RestconfTransaction
303 // FIXME: this method should only be needed in MdsalRestconfStrategy
304 abstract ListenableFuture<Boolean> exists(YangInstanceIdentifier path);
307 final @NonNull RestconfFuture<DataPatchResult> merge(final YangInstanceIdentifier path, final NormalizedNode data) {
308 final var ret = new SettableRestconfFuture<DataPatchResult>();
309 merge(ret, requireNonNull(path), requireNonNull(data));
313 private void merge(final @NonNull SettableRestconfFuture<DataPatchResult> future,
314 final @NonNull YangInstanceIdentifier path, final @NonNull NormalizedNode data) {
315 final var tx = prepareWriteExecution();
316 // FIXME: this method should be further specialized to eliminate this call -- it is only needed for MD-SAL
317 tx.ensureParentsByMerge(path);
318 tx.merge(path, data);
319 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
321 public void onSuccess(final CommitInfo result) {
322 // TODO: extract details once CommitInfo can communicate them
323 future.set(PATCH_EMPTY);
327 public void onFailure(final Throwable cause) {
328 future.setFailure(TransactionUtil.decodeException(cause, "MERGE", path, modelContext()));
330 }, MoreExecutors.directExecutor());
333 public @NonNull RestconfFuture<DataPutResult> dataPUT(final ApiPath apiPath, final ResourceBody body,
334 final Map<String, String> queryParameters) {
337 path = pathNormalizer.normalizeDataPath(apiPath);
338 } catch (RestconfDocumentedException e) {
339 return RestconfFuture.failed(e);
344 insert = Insert.ofQueryParameters(databind, queryParameters);
345 } catch (IllegalArgumentException e) {
346 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
347 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
349 final NormalizedNode data;
351 data = body.toNormalizedNode(new DataPutPath(databind, path.inference(), path.instance()));
352 } catch (RestconfDocumentedException e) {
353 return RestconfFuture.failed(e);
355 return putData(path.instance(), data, insert);
359 * Check mount point and prepare variables for put data to DS.
361 * @param path path of data
363 * @param insert {@link Insert}
364 * @return A {@link DataPutResult}
366 public final @NonNull RestconfFuture<DataPutResult> putData(final YangInstanceIdentifier path,
367 final NormalizedNode data, final @Nullable Insert insert) {
368 final var exists = TransactionUtil.syncAccess(exists(path), path);
370 final ListenableFuture<? extends CommitInfo> commitFuture;
371 if (insert != null) {
372 final var parentPath = path.coerceParent();
373 checkListAndOrderedType(parentPath);
374 commitFuture = insertAndCommitPut(path, data, insert, parentPath);
376 commitFuture = replaceAndCommit(prepareWriteExecution(), path, data);
379 final var ret = new SettableRestconfFuture<DataPutResult>();
381 Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
383 public void onSuccess(final CommitInfo result) {
384 ret.set(exists ? PUT_REPLACED : PUT_CREATED);
388 public void onFailure(final Throwable cause) {
389 ret.setFailure(TransactionUtil.decodeException(cause, "PUT", path, modelContext()));
391 }, MoreExecutors.directExecutor());
396 private ListenableFuture<? extends CommitInfo> insertAndCommitPut(final YangInstanceIdentifier path,
397 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parentPath) {
398 final var tx = prepareWriteExecution();
400 return switch (insert.insert()) {
402 final var readData = tx.readList(parentPath);
403 if (readData == null || readData.isEmpty()) {
404 yield replaceAndCommit(tx, path, data);
406 tx.remove(parentPath);
407 tx.replace(path, data);
408 tx.replace(parentPath, readData);
411 case LAST -> replaceAndCommit(tx, path, data);
413 final var readData = tx.readList(parentPath);
414 if (readData == null || readData.isEmpty()) {
415 yield replaceAndCommit(tx, path, data);
417 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
421 final var readData = tx.readList(parentPath);
422 if (readData == null || readData.isEmpty()) {
423 yield replaceAndCommit(tx, path, data);
425 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
431 private void insertWithPointPut(final RestconfTransaction tx, final YangInstanceIdentifier path,
432 final NormalizedNode data, final @NonNull PathArgument pointArg, final NormalizedNodeContainer<?> readList,
433 final boolean before) {
434 tx.remove(path.getParent());
436 int lastItemPosition = 0;
437 for (var nodeChild : readList.body()) {
438 if (nodeChild.name().equals(pointArg)) {
447 int lastInsertedPosition = 0;
448 final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext(), path.getParent());
449 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
450 for (var nodeChild : readList.body()) {
451 if (lastInsertedPosition == lastItemPosition) {
452 tx.replace(path, data);
454 final var childPath = path.coerceParent().node(nodeChild.name());
455 tx.replace(childPath, nodeChild);
456 lastInsertedPosition++;
460 private static ListenableFuture<? extends CommitInfo> replaceAndCommit(final RestconfTransaction tx,
461 final YangInstanceIdentifier path, final NormalizedNode data) {
462 tx.replace(path, data);
466 private DataSchemaNode checkListAndOrderedType(final YangInstanceIdentifier path) {
467 // FIXME: we have this available in InstanceIdentifierContext
468 final var dataSchemaNode = databind.schemaTree().findChild(path).orElseThrow().dataSchemaNode();
470 final String message;
471 if (dataSchemaNode instanceof ListSchemaNode listSchema) {
472 if (listSchema.isUserOrdered()) {
475 message = "Insert parameter can be used only with ordered-by user list.";
476 } else if (dataSchemaNode instanceof LeafListSchemaNode leafListSchema) {
477 if (leafListSchema.isUserOrdered()) {
478 return leafListSchema;
480 message = "Insert parameter can be used only with ordered-by user leaf-list.";
482 message = "Insert parameter can be used only with list or leaf-list";
484 throw new RestconfDocumentedException(message, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
488 * Check mount point and prepare variables for post data.
492 * @param insert {@link Insert}
493 * @return A {@link RestconfFuture}
495 public final @NonNull RestconfFuture<CreateResource> postData(final YangInstanceIdentifier path,
496 final NormalizedNode data, final @Nullable Insert insert) {
497 final ListenableFuture<? extends CommitInfo> future;
498 if (insert != null) {
499 final var parentPath = path.coerceParent();
500 checkListAndOrderedType(parentPath);
501 future = insertAndCommitPost(path, data, insert, parentPath);
503 future = createAndCommit(prepareWriteExecution(), path, data);
506 final var ret = new SettableRestconfFuture<CreateResource>();
507 Futures.addCallback(future, new FutureCallback<CommitInfo>() {
509 public void onSuccess(final CommitInfo result) {
510 ret.set(new CreateResource(new YangInstanceIdentifierSerializer(databind).serializePath(
511 data instanceof MapNode mapData && !mapData.isEmpty()
512 ? path.node(mapData.body().iterator().next().name()) : path)));
516 public void onFailure(final Throwable cause) {
517 ret.setFailure(TransactionUtil.decodeException(cause, "POST", path, modelContext()));
520 }, MoreExecutors.directExecutor());
524 private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
525 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parent) {
526 final var grandParent = parent.coerceParent();
527 final var tx = prepareWriteExecution();
529 return switch (insert.insert()) {
531 final var readData = tx.readList(grandParent);
532 if (readData == null || readData.isEmpty()) {
533 tx.replace(path, data);
535 checkItemDoesNotExists(exists(path), path);
536 tx.remove(grandParent);
537 tx.replace(path, data);
538 tx.replace(grandParent, readData);
542 case LAST -> createAndCommit(tx, path, data);
544 final var readData = tx.readList(grandParent);
545 if (readData == null || readData.isEmpty()) {
546 tx.replace(path, data);
548 checkItemDoesNotExists(exists(path), path);
549 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, true);
554 final var readData = tx.readList(grandParent);
555 if (readData == null || readData.isEmpty()) {
556 tx.replace(path, data);
558 checkItemDoesNotExists(exists(path), path);
559 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, false);
567 * Merge data into the configuration datastore, as outlined in
568 * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040 section 4.6.1</a>.
570 * @param apiPath Path to merge
571 * @param body Data to merge
572 * @return A {@link RestconfFuture}
573 * @throws NullPointerException if any argument is {@code null}
575 public final @NonNull RestconfFuture<DataPatchResult> dataPATCH(final ApiPath apiPath, final ResourceBody body) {
578 path = pathNormalizer.normalizeDataPath(apiPath);
579 } catch (RestconfDocumentedException e) {
580 return RestconfFuture.failed(e);
583 final NormalizedNode data;
585 data = body.toNormalizedNode(new DataPutPath(databind, path.inference(), path.instance()));
586 } catch (RestconfDocumentedException e) {
587 return RestconfFuture.failed(e);
590 return merge(path.instance(), data);
593 public final @NonNull RestconfFuture<PatchStatusContext> dataPATCH(final ApiPath apiPath, final PatchBody body) {
596 path = pathNormalizer.normalizeDataPath(apiPath);
597 } catch (RestconfDocumentedException e) {
598 return RestconfFuture.failed(e);
601 final PatchContext patch;
603 patch = body.toPatchContext(new DataPatchPath(databind, path.instance()));
604 } catch (IOException e) {
605 LOG.debug("Error parsing YANG Patch input", e);
606 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
607 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
609 return patchData(patch);
613 * Process edit operations of one {@link PatchContext}.
615 * @param patch Patch context to be processed
616 * @return {@link PatchStatusContext}
618 public final @NonNull RestconfFuture<PatchStatusContext> patchData(final PatchContext patch) {
619 final var editCollection = new ArrayList<PatchStatusEntity>();
620 final var tx = prepareWriteExecution();
622 boolean noError = true;
623 for (var patchEntity : patch.entities()) {
625 final var targetNode = patchEntity.getTargetNode();
626 final var editId = patchEntity.getEditId();
628 switch (patchEntity.getOperation()) {
631 tx.create(targetNode, patchEntity.getNode());
632 editCollection.add(new PatchStatusEntity(editId, true, null));
633 } catch (RestconfDocumentedException e) {
634 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
640 tx.delete(targetNode);
641 editCollection.add(new PatchStatusEntity(editId, true, null));
642 } catch (RestconfDocumentedException e) {
643 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
649 tx.ensureParentsByMerge(targetNode);
650 tx.merge(targetNode, patchEntity.getNode());
651 editCollection.add(new PatchStatusEntity(editId, true, null));
652 } catch (RestconfDocumentedException e) {
653 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
659 tx.replace(targetNode, patchEntity.getNode());
660 editCollection.add(new PatchStatusEntity(editId, true, null));
661 } catch (RestconfDocumentedException e) {
662 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
668 tx.remove(targetNode);
669 editCollection.add(new PatchStatusEntity(editId, true, null));
670 } catch (RestconfDocumentedException e) {
671 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
676 editCollection.add(new PatchStatusEntity(editId, false, List.of(
677 new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
678 "Not supported Yang Patch operation"))));
687 final var ret = new SettableRestconfFuture<PatchStatusContext>();
691 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false, null));
695 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
697 public void onSuccess(final CommitInfo result) {
698 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), true,
703 public void onFailure(final Throwable cause) {
704 // if errors occurred during transaction commit then patch failed and global errors are reported
705 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false,
706 TransactionUtil.decodeException(cause, "PATCH", null, modelContext()).getErrors()));
708 }, MoreExecutors.directExecutor());
713 private void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
714 final NormalizedNode data, final PathArgument pointArg, final NormalizedNodeContainer<?> readList,
715 final YangInstanceIdentifier grandParentPath, final boolean before) {
716 tx.remove(grandParentPath);
718 int lastItemPosition = 0;
719 for (var nodeChild : readList.body()) {
720 if (nodeChild.name().equals(pointArg)) {
729 int lastInsertedPosition = 0;
730 final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext(), grandParentPath);
731 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
732 for (var nodeChild : readList.body()) {
733 if (lastInsertedPosition == lastItemPosition) {
734 tx.replace(path, data);
736 tx.replace(grandParentPath.node(nodeChild.name()), nodeChild);
737 lastInsertedPosition++;
741 private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
742 final YangInstanceIdentifier path, final NormalizedNode data) {
744 tx.create(path, data);
745 } catch (RestconfDocumentedException e) {
746 // close transaction if any and pass exception further
755 * Check if items do NOT already exists at specified {@code path}.
757 * @param existsFuture if checked data exists
758 * @param path Path to be checked
759 * @throws RestconfDocumentedException if data already exists.
761 static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
762 final YangInstanceIdentifier path) {
763 if (TransactionUtil.syncAccess(existsFuture, path)) {
764 LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
765 throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
771 * Delete data from the configuration datastore. If the data does not exist, this operation will fail, as outlined
772 * in <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.7">RFC8040 section 4.7</a>
774 * @param apiPath Path to delete
775 * @return A {@link RestconfFuture}
776 * @throws NullPointerException if {@code apiPath} is {@code null}
778 @SuppressWarnings("checkstyle:abbreviationAsWordInName")
779 public final @NonNull RestconfFuture<Empty> dataDELETE(final ApiPath apiPath) {
782 path = pathNormalizer.normalizeDataPath(apiPath);
783 } catch (RestconfDocumentedException e) {
784 return RestconfFuture.failed(e);
787 // FIXME: reject empty YangInstanceIdentifier, as datastores may not be deleted
788 final var ret = new SettableRestconfFuture<Empty>();
789 delete(ret, path.instance());
793 abstract void delete(@NonNull SettableRestconfFuture<Empty> future, @NonNull YangInstanceIdentifier path);
795 public final @NonNull RestconfFuture<DataGetResult> dataGET(final ApiPath apiPath,
796 final DataGetParams params) {
799 path = pathNormalizer.normalizeDataPath(apiPath);
800 } catch (RestconfDocumentedException e) {
801 return RestconfFuture.failed(e);
803 return dataGET(path, params);
806 abstract @NonNull RestconfFuture<DataGetResult> dataGET(DataPath path, DataGetParams params);
808 static final @NonNull RestconfFuture<DataGetResult> completeDataGET(final Inference inference,
809 final QueryParameters queryParams, final @Nullable NormalizedNode node,
810 final @Nullable ConfigurationMetadata metadata) {
812 return RestconfFuture.failed(new RestconfDocumentedException(
813 "Request could not be completed because the relevant data model content does not exist",
814 ErrorType.PROTOCOL, ErrorTag.DATA_MISSING));
817 final var payload = new NormalizedNodePayload(inference, node, queryParams);
818 return RestconfFuture.of(metadata == null ? new DataGetResult(payload)
819 : new DataGetResult(payload, metadata.entityTag(), metadata.lastModified()));
823 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
824 * inside of object {@link RestconfStrategy} provided as a parameter.
826 * @param content type of data to read (config, state, all)
827 * @param path the path to read
828 * @param defaultsMode value of with-defaults parameter
829 * @return {@link NormalizedNode}
831 // FIXME: NETCONF-1155: this method should asynchronous
832 public final @Nullable NormalizedNode readData(final @NonNull ContentParam content,
833 final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
834 return switch (content) {
836 // PREPARE STATE DATA NODE
837 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
838 // PREPARE CONFIG DATA NODE
839 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
841 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
842 : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
845 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
846 yield defaultsMode == null ? read
847 : prepareDataByParamWithDef(read, path, defaultsMode.mode());
849 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
853 private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
854 final YangInstanceIdentifier path) {
855 return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
858 final NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
859 final WithDefaultsMode defaultsMode) {
860 final boolean trim = switch (defaultsMode) {
862 case Explicit -> false;
863 case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
864 "Unsupported with-defaults value " + defaultsMode.getName());
867 // FIXME: we have this readily available in InstanceIdentifierContext
868 final var ctxNode = databind.schemaTree().findChild(path).orElseThrow();
869 if (readData instanceof ContainerNode container) {
870 final var builder = Builders.containerBuilder().withNodeIdentifier(container.name());
871 buildCont(builder, container.body(), ctxNode, trim);
872 return builder.build();
873 } else if (readData instanceof MapEntryNode mapEntry) {
874 if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
875 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
878 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(mapEntry.name());
879 buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
880 return builder.build();
882 throw new IllegalStateException("Unhandled data contract " + readData.contract());
886 private static void buildMapEntryBuilder(
887 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
888 final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
889 final boolean trim, final List<QName> keys) {
890 for (var child : children) {
891 final var childCtx = getChildContext(ctxNode, child);
893 if (child instanceof ContainerNode container) {
894 appendContainer(builder, container, childCtx, trim);
895 } else if (child instanceof MapNode map) {
896 appendMap(builder, map, childCtx, trim);
897 } else if (child instanceof LeafNode<?> leaf) {
898 appendLeaf(builder, leaf, childCtx, trim, keys);
900 // FIXME: we should never hit this, throw an ISE if this ever happens
901 LOG.debug("Ignoring unhandled child contract {}", child.contract());
906 private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
907 final DataSchemaContext ctxNode, final boolean trim) {
908 final var childBuilder = Builders.containerBuilder().withNodeIdentifier(container.name());
909 buildCont(childBuilder, container.body(), ctxNode, trim);
910 builder.withChild(childBuilder.build());
913 private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
914 final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
915 if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
916 throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
919 // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
920 final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
922 // This is a combined check for when we need to emit the leaf.
924 // We always have to emit key leaf values
925 keys.contains(leafSchema.getQName())
926 // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
928 // When data is retrieved with a <with-defaults> parameter equal to
929 // 'trim', data nodes MUST NOT be reported if they contain the schema
930 // default value. Non-configuration data nodes containing the schema
931 // default value MUST NOT be reported.
933 || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
934 // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
935 // grasp what we are doing here... emit only if it matches default ???!!!
936 // FIXME: The WithDefaultsParam.EXPLICIT says:
938 // Data nodes set to the YANG default by the client are reported.
940 // and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
942 // If the "with-defaults" parameter is set to "explicit", then the
943 // server MUST adhere to the default-reporting behavior defined in
944 // Section 3.3 of [RFC6243].
946 // and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
948 // When data is retrieved with a <with-defaults> parameter equal to
949 // 'explicit', a data node that was set by a client to its schema
950 // default value MUST be reported. A conceptual data node that would be
951 // set by the server to the schema default value MUST NOT be reported.
952 // Non-configuration data nodes containing the schema default value MUST
955 // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
956 // This seems to disregard the 'trim = true' case semantics (see above).
957 // Combining the above, though, these checks are missing the 'non-config' check, which would
958 // distinguish, but barring that this check is superfluous and results in the wrong semantics.
959 // Without that input, this really should be covered by the previous case.
960 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
961 builder.withChild(leaf);
965 private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
966 final DataSchemaContext childCtx, final boolean trim) {
967 if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
968 throw new IllegalStateException("Input " + map + " does not match " + childCtx);
971 final var childBuilder = switch (map.ordering()) {
972 case SYSTEM -> Builders.mapBuilder();
973 case USER -> Builders.orderedMapBuilder();
975 buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
976 listSchema.getKeyDefinition());
977 builder.withChild(childBuilder.build());
980 private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
981 final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
982 final List<@NonNull QName> keys) {
983 for (var entry : entries) {
984 final var childCtx = getChildContext(ctxNode, entry);
985 final var mapEntryBuilder = Builders.mapEntryBuilder().withNodeIdentifier(entry.name());
986 buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
987 builder.withChild(mapEntryBuilder.build());
991 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
992 final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
993 for (var child : children) {
994 final var childCtx = getChildContext(ctxNode, child);
995 if (child instanceof ContainerNode container) {
996 appendContainer(builder, container, childCtx, trim);
997 } else if (child instanceof MapNode map) {
998 appendMap(builder, map, childCtx, trim);
999 } else if (child instanceof LeafNode<?> leaf) {
1000 appendLeaf(builder, leaf, childCtx, trim, List.of());
1005 private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
1006 final NormalizedNode child) {
1007 final var childId = child.name();
1008 final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
1010 if (childCtx == null) {
1011 throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
1016 static final NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
1017 final NormalizedNode configDataNode) {
1018 // if no data exists
1019 if (stateDataNode == null && configDataNode == null) {
1023 // return config data
1024 if (stateDataNode == null) {
1025 return configDataNode;
1028 // return state data
1029 if (configDataNode == null) {
1030 return stateDataNode;
1033 // merge data from config and state
1034 return mergeStateAndConfigData(stateDataNode, configDataNode);
1038 * Merge state and config data into a single NormalizedNode.
1040 * @param stateDataNode data node of state data
1041 * @param configDataNode data node of config data
1042 * @return {@link NormalizedNode}
1044 private static @NonNull NormalizedNode mergeStateAndConfigData(
1045 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
1046 validateNodeMerge(stateDataNode, configDataNode);
1047 // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
1048 if (configDataNode instanceof RpcDefinition) {
1049 return prepareRpcData(configDataNode, stateDataNode);
1051 return prepareData(configDataNode, stateDataNode);
1056 * Validates whether the two NormalizedNodes can be merged.
1058 * @param stateDataNode data node of state data
1059 * @param configDataNode data node of config data
1061 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
1062 final @NonNull NormalizedNode configDataNode) {
1063 final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
1064 final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
1065 if (!moduleOfStateData.equals(moduleOfConfigData)) {
1066 throw new RestconfDocumentedException("Unable to merge data from different modules.");
1071 * Prepare and map data for rpc.
1073 * @param configDataNode data node of config data
1074 * @param stateDataNode data node of state data
1075 * @return {@link NormalizedNode}
1077 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
1078 final @NonNull NormalizedNode stateDataNode) {
1079 final var mapEntryBuilder = Builders.mapEntryBuilder()
1080 .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
1083 mapRpcDataNode(configDataNode, mapEntryBuilder);
1085 mapRpcDataNode(stateDataNode, mapEntryBuilder);
1087 return Builders.mapBuilder()
1088 .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
1089 .addChild(mapEntryBuilder.build())
1094 * Map node to map entry builder.
1096 * @param dataNode data node
1097 * @param mapEntryBuilder builder for mapping data
1099 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
1100 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
1101 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
1105 * Prepare and map all data from DS.
1107 * @param configDataNode data node of config data
1108 * @param stateDataNode data node of state data
1109 * @return {@link NormalizedNode}
1111 @SuppressWarnings("unchecked")
1112 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
1113 final @NonNull NormalizedNode stateDataNode) {
1114 if (configDataNode instanceof UserMapNode configMap) {
1115 final var builder = Builders.orderedMapBuilder().withNodeIdentifier(configMap.name());
1116 mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
1117 return builder.build();
1118 } else if (configDataNode instanceof SystemMapNode configMap) {
1119 final var builder = Builders.mapBuilder().withNodeIdentifier(configMap.name());
1120 mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
1121 return builder.build();
1122 } else if (configDataNode instanceof MapEntryNode configEntry) {
1123 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(configEntry.name());
1124 mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
1125 return builder.build();
1126 } else if (configDataNode instanceof ContainerNode configContaienr) {
1127 final var builder = Builders.containerBuilder().withNodeIdentifier(configContaienr.name());
1128 mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
1129 return builder.build();
1130 } else if (configDataNode instanceof ChoiceNode configChoice) {
1131 final var builder = Builders.choiceBuilder().withNodeIdentifier(configChoice.name());
1132 mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
1133 return builder.build();
1134 } else if (configDataNode instanceof LeafNode configLeaf) {
1135 // config trumps oper
1137 } else if (configDataNode instanceof UserLeafSetNode) {
1138 final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
1139 final var builder = Builders.<Object>orderedLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
1140 mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
1141 return builder.build();
1142 } else if (configDataNode instanceof SystemLeafSetNode) {
1143 final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
1144 final var builder = Builders.<Object>leafSetBuilder().withNodeIdentifier(configLeafSet.name());
1145 mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
1146 return builder.build();
1147 } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
1148 // config trumps oper
1150 } else if (configDataNode instanceof UnkeyedListNode configList) {
1151 final var builder = Builders.unkeyedListBuilder().withNodeIdentifier(configList.name());
1152 mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
1153 return builder.build();
1154 } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
1155 final var builder = Builders.unkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
1156 mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
1157 return builder.build();
1159 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
1164 * Map value from container node to builder.
1166 * @param configData collection of config data nodes
1167 * @param stateData collection of state data nodes
1168 * @param builder builder
1170 private static <T extends NormalizedNode> void mapValueToBuilder(
1171 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
1172 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1173 final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1174 final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1176 // merge config and state data of children with different identifiers
1177 mapDataToBuilder(configMap, stateMap, builder);
1179 // merge config and state data of children with the same identifiers
1180 mergeDataToBuilder(configMap, stateMap, builder);
1184 * Map data with different identifiers to builder. Data with different identifiers can be just added
1185 * as childs to parent node.
1187 * @param configMap map of config data nodes
1188 * @param stateMap map of state data nodes
1189 * @param builder - builder
1191 private static <T extends NormalizedNode> void mapDataToBuilder(
1192 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1193 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1194 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
1195 y -> builder.addChild(y.getValue()));
1196 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
1197 y -> builder.addChild(y.getValue()));
1201 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
1202 * go one level down with {@code prepareData} method.
1204 * @param configMap immutable config data
1205 * @param stateMap immutable state data
1206 * @param builder - builder
1208 @SuppressWarnings("unchecked")
1209 private static <T extends NormalizedNode> void mergeDataToBuilder(
1210 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1211 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1212 // it is enough to process only config data because operational contains the same data
1213 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1214 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1217 public @NonNull RestconfFuture<OperationsGetResult> operationsGET() {
1218 final var modelContext = modelContext();
1219 final var modules = modelContext.getModuleStatements();
1220 if (modules.isEmpty()) {
1221 // No modules, or defensive return empty content
1222 return RestconfFuture.of(new OperationsGetResult.Container(modelContext, ImmutableSetMultimap.of()));
1225 // RPC QNames by their XMLNamespace/Revision. This should be a Table, but Revision can be null, which wrecks us.
1226 final var table = new HashMap<XMLNamespace, Map<Revision, ImmutableSet<QName>>>();
1227 for (var entry : modules.entrySet()) {
1228 final var module = entry.getValue();
1229 final var rpcNames = module.streamEffectiveSubstatements(RpcEffectiveStatement.class)
1230 .map(RpcEffectiveStatement::argument)
1231 .collect(ImmutableSet.toImmutableSet());
1232 if (!rpcNames.isEmpty()) {
1233 final var namespace = entry.getKey();
1234 table.computeIfAbsent(namespace.getNamespace(), ignored -> new HashMap<>())
1235 .put(namespace.getRevision().orElse(null), rpcNames);
1239 // Now pick the latest revision for each namespace
1240 final var rpcs = ImmutableSetMultimap.<QNameModule, QName>builder();
1241 for (var entry : table.entrySet()) {
1242 entry.getValue().entrySet().stream()
1243 .sorted(Comparator.comparing(Entry::getKey, (first, second) -> Revision.compare(second, first)))
1245 .ifPresent(row -> rpcs.putAll(QNameModule.create(entry.getKey(), row.getKey()), row.getValue()));
1247 return RestconfFuture.of(new OperationsGetResult.Container(modelContext, rpcs.build()));
1250 public @NonNull RestconfFuture<OperationsGetResult> operationsGET(final ApiPath apiPath) {
1251 if (apiPath.steps().isEmpty()) {
1252 return operationsGET();
1257 rpc = pathNormalizer.normalizeRpcPath(apiPath);
1258 } catch (RestconfDocumentedException e) {
1259 return RestconfFuture.failed(e);
1262 return RestconfFuture.of(
1263 new OperationsGetResult.Leaf(rpc.inference().getEffectiveModelContext(), rpc.rpc().argument()));
1266 public @NonNull RestconfFuture<OperationsPostResult> operationsPOST(final URI restconfURI, final ApiPath apiPath,
1267 final OperationInputBody body) {
1268 final OperationPath.Rpc path;
1270 path = pathNormalizer.normalizeRpcPath(apiPath);
1271 } catch (RestconfDocumentedException e) {
1272 return RestconfFuture.failed(e);
1275 final var postPath = new OperationsPostPath(databind, path.inference());
1276 final ContainerNode data;
1278 data = body.toContainerNode(postPath);
1279 } catch (IOException e) {
1280 LOG.debug("Error reading input", e);
1281 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1282 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1285 final var type = path.rpc().argument();
1286 final var local = localRpcs.get(type);
1287 if (local != null) {
1288 return local.invoke(restconfURI, new OperationInput(databind, postPath.operation(), data));
1290 if (rpcService == null) {
1291 LOG.debug("RPC invocation is not available");
1292 return RestconfFuture.failed(new RestconfDocumentedException("RPC invocation is not available",
1293 ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED));
1296 final var ret = new SettableRestconfFuture<OperationsPostResult>();
1297 Futures.addCallback(rpcService.invokeRpc(type, data), new FutureCallback<DOMRpcResult>() {
1299 public void onSuccess(final DOMRpcResult response) {
1300 final var errors = response.errors();
1301 if (errors.isEmpty()) {
1302 ret.set(new OperationsPostResult(databind, postPath.operation(), response.value()));
1304 LOG.debug("RPC invocation reported {}", response.errors());
1305 ret.setFailure(new RestconfDocumentedException("RPC implementation reported errors", null,
1306 response.errors()));
1311 public void onFailure(final Throwable cause) {
1312 LOG.debug("RPC invocation failed, cause");
1313 if (cause instanceof RestconfDocumentedException ex) {
1316 // TODO: YangNetconfErrorAware if we ever get into a broader invocation scope
1317 ret.setFailure(new RestconfDocumentedException(cause,
1318 new RestconfError(ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage())));
1321 }, MoreExecutors.directExecutor());
1325 public @NonNull RestconfFuture<CharSource> resolveSource(final SourceIdentifier source,
1326 final Class<? extends SchemaSourceRepresentation> representation) {
1327 final var src = requireNonNull(source);
1328 if (YangTextSchemaSource.class.isAssignableFrom(representation)) {
1329 if (sourceProvider != null) {
1330 final var ret = new SettableRestconfFuture<CharSource>();
1331 Futures.addCallback(sourceProvider.getSource(src), new FutureCallback<YangTextSchemaSource>() {
1333 public void onSuccess(final YangTextSchemaSource 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 (YinTextSchemaSource.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 ApiPath apiPath,
1384 final DataPostBody body, final Map<String, String> queryParameters) {
1385 if (apiPath.steps().isEmpty()) {
1386 return dataCreatePOST(body.toResource(), queryParameters);
1388 final InstanceReference path;
1390 path = pathNormalizer.normalizeDataOrActionPath(apiPath);
1391 } catch (RestconfDocumentedException e) {
1392 return RestconfFuture.failed(e);
1394 if (path instanceof DataPath dataPath) {
1395 try (var resourceBody = body.toResource()) {
1396 return dataCreatePOST(new DataPostPath(databind, dataPath.inference(), dataPath.instance()),
1397 resourceBody, queryParameters);
1400 if (path instanceof OperationPath.Action actionPath) {
1401 try (var inputBody = body.toOperationInput()) {
1402 return dataInvokePOST(actionPath, inputBody);
1405 // Note: this should never happen
1406 // FIXME: we should be able to eliminate this path with Java 21+ pattern matching
1407 return RestconfFuture.failed(new RestconfDocumentedException("Unhandled path " + path));
1410 public @NonNull RestconfFuture<CreateResource> dataCreatePOST(final ChildBody body,
1411 final Map<String, String> queryParameters) {
1412 return dataCreatePOST(new DataPostPath(databind,
1413 SchemaInferenceStack.of(databind.modelContext()).toInference(), YangInstanceIdentifier.of()), body,
1417 private @NonNull RestconfFuture<CreateResource> dataCreatePOST(final DataPostPath path, final ChildBody body,
1418 final Map<String, String> queryParameters) {
1419 final Insert insert;
1421 insert = Insert.ofQueryParameters(path.databind(), queryParameters);
1422 } catch (IllegalArgumentException e) {
1423 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
1424 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
1427 final var payload = body.toPayload(path);
1428 return postData(concat(path.instance(), payload.prefix()), payload.body(), insert);
1431 private static YangInstanceIdentifier concat(final YangInstanceIdentifier parent, final List<PathArgument> args) {
1433 for (var arg : args) {
1434 ret = ret.node(arg);
1439 private @NonNull RestconfFuture<InvokeOperation> dataInvokePOST(final OperationPath.Action path,
1440 final OperationInputBody body) {
1441 final var inference = path.inference();
1442 final ContainerNode input;
1444 input = body.toContainerNode(new OperationsPostPath(databind, inference));
1445 } catch (IOException e) {
1446 LOG.debug("Error reading input", e);
1447 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1448 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1451 if (actionService == null) {
1452 return RestconfFuture.failed(new RestconfDocumentedException("DOMActionService is missing."));
1455 final var future = dataInvokePOST(actionService, path, input);
1456 return future.transform(result -> result.getOutput()
1457 .flatMap(output -> output.isEmpty() ? Optional.empty()
1458 : Optional.of(new InvokeOperation(new NormalizedNodePayload(inference, output))))
1459 .orElse(InvokeOperation.EMPTY));
1463 * Invoke Action via ActionServiceHandler.
1465 * @param input input data
1466 * @param yangIId invocation context
1467 * @param schemaPath schema path of data
1468 * @param actionService action service to invoke action
1469 * @return {@link DOMActionResult}
1471 private static RestconfFuture<DOMActionResult> dataInvokePOST(final DOMActionService actionService,
1472 final OperationPath.Action path, final @NonNull ContainerNode input) {
1473 final var ret = new SettableRestconfFuture<DOMActionResult>();
1475 Futures.addCallback(actionService.invokeAction(
1476 path.inference().toSchemaInferenceStack().toSchemaNodeIdentifier(),
1477 new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, path.instance()), input),
1478 new FutureCallback<DOMActionResult>() {
1480 public void onSuccess(final DOMActionResult result) {
1481 final var errors = result.getErrors();
1482 LOG.debug("InvokeAction Error Message {}", errors);
1483 if (errors.isEmpty()) {
1486 ret.setFailure(new RestconfDocumentedException("InvokeAction Error Message ", null, errors));
1491 public void onFailure(final Throwable cause) {
1492 if (cause instanceof DOMActionException) {
1493 ret.set(new SimpleDOMActionResult(List.of(RpcResultBuilder.newError(
1494 ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage()))));
1495 } else if (cause instanceof RestconfDocumentedException e) {
1497 } else if (cause instanceof CancellationException) {
1498 ret.setFailure(new RestconfDocumentedException("Action cancelled while executing",
1499 ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, cause));
1501 ret.setFailure(new RestconfDocumentedException("Invocation failed", cause));
1504 }, MoreExecutors.directExecutor());