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.collect.ImmutableMap;
14 import com.google.common.collect.ImmutableSet;
15 import com.google.common.collect.ImmutableSetMultimap;
16 import com.google.common.io.CharSource;
17 import com.google.common.util.concurrent.FutureCallback;
18 import com.google.common.util.concurrent.Futures;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import com.google.common.util.concurrent.MoreExecutors;
21 import java.io.IOException;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Comparator;
26 import java.util.HashMap;
27 import java.util.List;
29 import java.util.Map.Entry;
30 import java.util.NoSuchElementException;
31 import java.util.Optional;
32 import java.util.concurrent.CancellationException;
33 import java.util.function.BiFunction;
34 import java.util.function.Function;
35 import java.util.stream.Collectors;
36 import org.eclipse.jdt.annotation.NonNull;
37 import org.eclipse.jdt.annotation.NonNullByDefault;
38 import org.eclipse.jdt.annotation.Nullable;
39 import org.opendaylight.mdsal.common.api.CommitInfo;
40 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
41 import org.opendaylight.mdsal.dom.api.DOMActionException;
42 import org.opendaylight.mdsal.dom.api.DOMActionResult;
43 import org.opendaylight.mdsal.dom.api.DOMActionService;
44 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
45 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
46 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
47 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
48 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
49 import org.opendaylight.mdsal.dom.api.DOMRpcService;
50 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
51 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
52 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
53 import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult;
54 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
55 import org.opendaylight.restconf.api.ApiPath;
56 import org.opendaylight.restconf.api.query.ContentParam;
57 import org.opendaylight.restconf.api.query.WithDefaultsParam;
58 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
59 import org.opendaylight.restconf.common.errors.RestconfError;
60 import org.opendaylight.restconf.common.errors.RestconfFuture;
61 import org.opendaylight.restconf.common.errors.SettableRestconfFuture;
62 import org.opendaylight.restconf.common.patch.PatchContext;
63 import org.opendaylight.restconf.common.patch.PatchStatusContext;
64 import org.opendaylight.restconf.common.patch.PatchStatusEntity;
65 import org.opendaylight.restconf.nb.rfc8040.Insert;
66 import org.opendaylight.restconf.nb.rfc8040.databind.ChildBody;
67 import org.opendaylight.restconf.nb.rfc8040.databind.DataPostBody;
68 import org.opendaylight.restconf.nb.rfc8040.databind.OperationInputBody;
69 import org.opendaylight.restconf.nb.rfc8040.databind.ResourceBody;
70 import org.opendaylight.restconf.nb.rfc8040.legacy.ErrorTags;
71 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
72 import org.opendaylight.restconf.nb.rfc8040.legacy.QueryParameters;
73 import org.opendaylight.restconf.nb.rfc8040.utils.parser.YangInstanceIdentifierSerializer;
74 import org.opendaylight.restconf.server.api.DataGetParams;
75 import org.opendaylight.restconf.server.api.DataPostPath;
76 import org.opendaylight.restconf.server.api.DataPostResult;
77 import org.opendaylight.restconf.server.api.DataPostResult.CreateResource;
78 import org.opendaylight.restconf.server.api.DataPostResult.InvokeOperation;
79 import org.opendaylight.restconf.server.api.DataPutPath;
80 import org.opendaylight.restconf.server.api.DataPutResult;
81 import org.opendaylight.restconf.server.api.DatabindContext;
82 import org.opendaylight.restconf.server.api.OperationsGetResult;
83 import org.opendaylight.restconf.server.api.OperationsPostPath;
84 import org.opendaylight.restconf.server.api.OperationsPostResult;
85 import org.opendaylight.restconf.server.spi.ApiPathNormalizer;
86 import org.opendaylight.restconf.server.spi.ApiPathNormalizer.DataPath;
87 import org.opendaylight.restconf.server.spi.ApiPathNormalizer.OperationPath;
88 import org.opendaylight.restconf.server.spi.ApiPathNormalizer.OperationPath.Rpc;
89 import org.opendaylight.restconf.server.spi.OperationInput;
90 import org.opendaylight.restconf.server.spi.RpcImplementation;
91 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.with.defaults.rev110601.WithDefaultsMode;
92 import org.opendaylight.yangtools.yang.common.Empty;
93 import org.opendaylight.yangtools.yang.common.ErrorTag;
94 import org.opendaylight.yangtools.yang.common.ErrorType;
95 import org.opendaylight.yangtools.yang.common.QName;
96 import org.opendaylight.yangtools.yang.common.QNameModule;
97 import org.opendaylight.yangtools.yang.common.Revision;
98 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
99 import org.opendaylight.yangtools.yang.common.XMLNamespace;
100 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
101 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
102 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
103 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
104 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
105 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
106 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
107 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
108 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
109 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
110 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
111 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
112 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
113 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
114 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
115 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
116 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
117 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
118 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
119 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
120 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
121 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
122 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
123 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
124 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
125 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
126 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
127 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
128 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
129 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
130 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
131 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
132 import org.opendaylight.yangtools.yang.model.api.stmt.RpcEffectiveStatement;
133 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleEffectiveStatement;
134 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
135 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
136 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
137 import org.opendaylight.yangtools.yang.model.repo.api.YinTextSchemaSource;
138 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
139 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
140 import org.slf4j.Logger;
141 import org.slf4j.LoggerFactory;
144 * Baseline execution strategy for various RESTCONF operations.
146 * @see NetconfRestconfStrategy
147 * @see MdsalRestconfStrategy
149 // FIXME: it seems the first three operations deal with lifecycle of a transaction, while others invoke various
150 // operations. This should be handled through proper allocation indirection.
151 public abstract class RestconfStrategy {
153 public record StrategyAndPath(RestconfStrategy strategy, DataPath path) {
154 public StrategyAndPath {
155 requireNonNull(strategy);
156 requireNonNull(path);
161 * Result of a partial {@link ApiPath} lookup for the purposes of supporting {@code yang-ext:mount}-delimited mount
162 * points with possible nesting.
164 * @param strategy the strategy to use
165 * @param tail the {@link ApiPath} tail to use with the strategy
168 public record StrategyAndTail(RestconfStrategy strategy, ApiPath tail) {
169 public StrategyAndTail {
170 requireNonNull(strategy);
171 requireNonNull(tail);
175 private static final Logger LOG = LoggerFactory.getLogger(RestconfStrategy.class);
177 private final @NonNull ImmutableMap<QName, RpcImplementation> localRpcs;
178 private final @NonNull ApiPathNormalizer pathNormalizer;
179 private final @NonNull DatabindContext databind;
180 private final DOMYangTextSourceProvider sourceProvider;
181 private final DOMMountPointService mountPointService;
182 private final DOMActionService actionService;
183 private final DOMRpcService rpcService;
185 RestconfStrategy(final DatabindContext databind, final ImmutableMap<QName, RpcImplementation> localRpcs,
186 final @Nullable DOMRpcService rpcService, final @Nullable DOMActionService actionService,
187 final DOMYangTextSourceProvider sourceProvider, final @Nullable DOMMountPointService mountPointService) {
188 this.databind = requireNonNull(databind);
189 this.localRpcs = requireNonNull(localRpcs);
190 this.rpcService = rpcService;
191 this.actionService = actionService;
192 this.sourceProvider = sourceProvider;
193 this.mountPointService = mountPointService;
194 pathNormalizer = new ApiPathNormalizer(databind);
197 public final @NonNull StrategyAndPath resolveStrategyPath(final ApiPath path) {
198 final var andTail = resolveStrategy(path);
199 final var strategy = andTail.strategy();
200 return new StrategyAndPath(strategy, strategy.pathNormalizer.normalizeDataPath(andTail.tail()));
204 * Resolve any and all {@code yang-ext:mount} to the target {@link StrategyAndTail}.
206 * @param path {@link ApiPath} to resolve
207 * @return A strategy and the remaining path
208 * @throws NullPointerException if {@code path} is {@code null}
210 public final @NonNull StrategyAndTail resolveStrategy(final ApiPath path) {
211 var mount = path.indexOf("yang-ext", "mount");
213 return new StrategyAndTail(this, path);
215 if (mountPointService == null) {
216 throw new RestconfDocumentedException("Mount point service is not available",
217 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
219 final var mountPath = path.subPath(0, mount);
220 final var dataPath = pathNormalizer.normalizeDataPath(path.subPath(0, mount));
221 final var mountPoint = mountPointService.getMountPoint(dataPath.instance())
222 .orElseThrow(() -> new RestconfDocumentedException("Mount point '" + mountPath + "' does not exist",
223 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
225 return createStrategy(mountPath, mountPoint).resolveStrategy(path.subPath(mount + 1));
228 private static @NonNull RestconfStrategy createStrategy(final ApiPath mountPath, final DOMMountPoint mountPoint) {
229 final var mountSchemaService = mountPoint.getService(DOMSchemaService.class)
230 .orElseThrow(() -> new RestconfDocumentedException(
231 "Mount point '" + mountPath + "' does not expose DOMSchemaService",
232 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
233 final var mountModelContext = mountSchemaService.getGlobalContext();
234 if (mountModelContext == null) {
235 throw new RestconfDocumentedException("Mount point '" + mountPath + "' does not have any models",
236 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT);
238 final var mountDatabind = DatabindContext.ofModel(mountModelContext);
239 final var mountPointService = mountPoint.getService(DOMMountPointService.class).orElse(null);
240 final var rpcService = mountPoint.getService(DOMRpcService.class).orElse(null);
241 final var actionService = mountPoint.getService(DOMActionService.class).orElse(null);
242 final var sourceProvider = mountPoint.getService(DOMSchemaService.class)
243 .flatMap(schema -> Optional.ofNullable(schema.getExtensions().getInstance(DOMYangTextSourceProvider.class)))
246 final var netconfService = mountPoint.getService(NetconfDataTreeService.class);
247 if (netconfService.isPresent()) {
248 return new NetconfRestconfStrategy(mountDatabind, netconfService.orElseThrow(), rpcService, actionService,
249 sourceProvider, mountPointService);
251 final var dataBroker = mountPoint.getService(DOMDataBroker.class);
252 if (dataBroker.isPresent()) {
253 return new MdsalRestconfStrategy(mountDatabind, dataBroker.orElseThrow(), rpcService, actionService,
254 sourceProvider, mountPointService);
256 LOG.warn("Mount point {} does not expose a suitable access interface", mountPath);
257 throw new RestconfDocumentedException("Could not find a supported access interface in mount point",
258 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, mountPoint.getIdentifier());
261 public final @NonNull DatabindContext databind() {
265 public final @NonNull EffectiveModelContext modelContext() {
266 return databind.modelContext();
270 * Lock the entire datastore.
272 * @return A {@link RestconfTransaction}. This transaction needs to be either committed or canceled before doing
275 abstract RestconfTransaction prepareWriteExecution();
278 * Read data from the datastore.
280 * @param store the logical data store which should be modified
281 * @param path the data object path
282 * @return a ListenableFuture containing the result of the read
284 abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path);
287 * Check if data already exists in the configuration datastore.
289 * @param path the data object path
290 * @return a ListenableFuture containing the result of the check
292 // FIXME: this method should be hosted in RestconfTransaction
293 // FIXME: this method should only be needed in MdsalRestconfStrategy
294 abstract ListenableFuture<Boolean> exists(YangInstanceIdentifier path);
297 * Delete data from the configuration datastore. If the data does not exist, this operation will fail, as outlined
298 * in <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.7">RFC8040 section 4.7</a>
300 * @param path Path to delete
301 * @return A {@link RestconfFuture}
302 * @throws NullPointerException if {@code path} is {@code null}
304 public final @NonNull RestconfFuture<Empty> delete(final YangInstanceIdentifier path) {
305 final var ret = new SettableRestconfFuture<Empty>();
306 delete(ret, requireNonNull(path));
310 abstract void delete(@NonNull SettableRestconfFuture<Empty> future, @NonNull YangInstanceIdentifier path);
313 * Merge data into the configuration datastore, as outlined in
314 * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040 section 4.6.1</a>.
316 * @param path Path to merge
317 * @param data Data to merge
318 * @return A {@link RestconfFuture}
319 * @throws NullPointerException if any argument is {@code null}
321 public final @NonNull RestconfFuture<Empty> merge(final YangInstanceIdentifier path, final NormalizedNode data) {
322 final var ret = new SettableRestconfFuture<Empty>();
323 merge(ret, requireNonNull(path), requireNonNull(data));
327 private void merge(final @NonNull SettableRestconfFuture<Empty> future, final @NonNull YangInstanceIdentifier path,
328 final @NonNull NormalizedNode data) {
329 final var tx = prepareWriteExecution();
330 // FIXME: this method should be further specialized to eliminate this call -- it is only needed for MD-SAL
331 tx.ensureParentsByMerge(path);
332 tx.merge(path, data);
333 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
335 public void onSuccess(final CommitInfo result) {
336 future.set(Empty.value());
340 public void onFailure(final Throwable cause) {
341 future.setFailure(TransactionUtil.decodeException(cause, "MERGE", path, modelContext()));
343 }, MoreExecutors.directExecutor());
346 public @NonNull RestconfFuture<DataPutResult> dataPUT(final ApiPath apiPath, final ResourceBody body,
347 final Map<String, String> queryParameters) {
348 final var path = pathNormalizer.normalizeDataPath(apiPath);
352 insert = Insert.ofQueryParameters(databind, queryParameters);
353 } catch (IllegalArgumentException e) {
354 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
355 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
357 final NormalizedNode data;
359 data = body.toNormalizedNode(new DataPutPath(databind, path.inference(), path.instance()));
360 } catch (RestconfDocumentedException e) {
361 return RestconfFuture.failed(e);
363 return putData(path.instance(), data, insert);
367 * Check mount point and prepare variables for put data to DS.
369 * @param path path of data
371 * @param insert {@link Insert}
372 * @return A {@link DataPutResult}
374 public final @NonNull RestconfFuture<DataPutResult> putData(final YangInstanceIdentifier path,
375 final NormalizedNode data, final @Nullable Insert insert) {
376 final var exists = TransactionUtil.syncAccess(exists(path), path);
378 final ListenableFuture<? extends CommitInfo> commitFuture;
379 if (insert != null) {
380 final var parentPath = path.coerceParent();
381 checkListAndOrderedType(parentPath);
382 commitFuture = insertAndCommitPut(path, data, insert, parentPath);
384 commitFuture = replaceAndCommit(prepareWriteExecution(), path, data);
387 final var ret = new SettableRestconfFuture<DataPutResult>();
389 Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
391 public void onSuccess(final CommitInfo result) {
392 ret.set(exists ? DataPutResult.REPLACED : DataPutResult.CREATED);
396 public void onFailure(final Throwable cause) {
397 ret.setFailure(TransactionUtil.decodeException(cause, "PUT", path, modelContext()));
399 }, MoreExecutors.directExecutor());
404 private ListenableFuture<? extends CommitInfo> insertAndCommitPut(final YangInstanceIdentifier path,
405 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parentPath) {
406 final var tx = prepareWriteExecution();
408 return switch (insert.insert()) {
410 final var readData = tx.readList(parentPath);
411 if (readData == null || readData.isEmpty()) {
412 yield replaceAndCommit(tx, path, data);
414 tx.remove(parentPath);
415 tx.replace(path, data);
416 tx.replace(parentPath, readData);
419 case LAST -> replaceAndCommit(tx, path, data);
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, true);
429 final var readData = tx.readList(parentPath);
430 if (readData == null || readData.isEmpty()) {
431 yield replaceAndCommit(tx, path, data);
433 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
439 private void insertWithPointPut(final RestconfTransaction tx, final YangInstanceIdentifier path,
440 final NormalizedNode data, final @NonNull PathArgument pointArg, final NormalizedNodeContainer<?> readList,
441 final boolean before) {
442 tx.remove(path.getParent());
444 int lastItemPosition = 0;
445 for (var nodeChild : readList.body()) {
446 if (nodeChild.name().equals(pointArg)) {
455 int lastInsertedPosition = 0;
456 final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext(), path.getParent());
457 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
458 for (var nodeChild : readList.body()) {
459 if (lastInsertedPosition == lastItemPosition) {
460 tx.replace(path, data);
462 final var childPath = path.coerceParent().node(nodeChild.name());
463 tx.replace(childPath, nodeChild);
464 lastInsertedPosition++;
468 private static ListenableFuture<? extends CommitInfo> replaceAndCommit(final RestconfTransaction tx,
469 final YangInstanceIdentifier path, final NormalizedNode data) {
470 tx.replace(path, data);
474 private DataSchemaNode checkListAndOrderedType(final YangInstanceIdentifier path) {
475 // FIXME: we have this available in InstanceIdentifierContext
476 final var dataSchemaNode = databind.schemaTree().findChild(path).orElseThrow().dataSchemaNode();
478 final String message;
479 if (dataSchemaNode instanceof ListSchemaNode listSchema) {
480 if (listSchema.isUserOrdered()) {
483 message = "Insert parameter can be used only with ordered-by user list.";
484 } else if (dataSchemaNode instanceof LeafListSchemaNode leafListSchema) {
485 if (leafListSchema.isUserOrdered()) {
486 return leafListSchema;
488 message = "Insert parameter can be used only with ordered-by user leaf-list.";
490 message = "Insert parameter can be used only with list or leaf-list";
492 throw new RestconfDocumentedException(message, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
496 * Check mount point and prepare variables for post data.
500 * @param insert {@link Insert}
501 * @return A {@link RestconfFuture}
503 public final @NonNull RestconfFuture<CreateResource> postData(final YangInstanceIdentifier path,
504 final NormalizedNode data, final @Nullable Insert insert) {
505 final ListenableFuture<? extends CommitInfo> future;
506 if (insert != null) {
507 final var parentPath = path.coerceParent();
508 checkListAndOrderedType(parentPath);
509 future = insertAndCommitPost(path, data, insert, parentPath);
511 future = createAndCommit(prepareWriteExecution(), path, data);
514 final var ret = new SettableRestconfFuture<CreateResource>();
515 Futures.addCallback(future, new FutureCallback<CommitInfo>() {
517 public void onSuccess(final CommitInfo result) {
518 ret.set(new CreateResource(new YangInstanceIdentifierSerializer(databind).serializePath(
519 data instanceof MapNode mapData && !mapData.isEmpty()
520 ? path.node(mapData.body().iterator().next().name()) : path)));
524 public void onFailure(final Throwable cause) {
525 ret.setFailure(TransactionUtil.decodeException(cause, "POST", path, modelContext()));
528 }, MoreExecutors.directExecutor());
532 private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
533 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parent) {
534 final var grandParent = parent.coerceParent();
535 final var tx = prepareWriteExecution();
537 return switch (insert.insert()) {
539 final var readData = tx.readList(grandParent);
540 if (readData == null || readData.isEmpty()) {
541 tx.replace(path, data);
543 checkItemDoesNotExists(exists(path), path);
544 tx.remove(grandParent);
545 tx.replace(path, data);
546 tx.replace(grandParent, readData);
550 case LAST -> createAndCommit(tx, path, data);
552 final var readData = tx.readList(grandParent);
553 if (readData == null || readData.isEmpty()) {
554 tx.replace(path, data);
556 checkItemDoesNotExists(exists(path), path);
557 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, true);
562 final var readData = tx.readList(grandParent);
563 if (readData == null || readData.isEmpty()) {
564 tx.replace(path, data);
566 checkItemDoesNotExists(exists(path), path);
567 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, false);
575 * Process edit operations of one {@link PatchContext}.
577 * @param patch Patch context to be processed
578 * @return {@link PatchStatusContext}
580 public final @NonNull RestconfFuture<PatchStatusContext> patchData(final PatchContext patch) {
581 final var editCollection = new ArrayList<PatchStatusEntity>();
582 final var tx = prepareWriteExecution();
584 boolean noError = true;
585 for (var patchEntity : patch.entities()) {
587 final var targetNode = patchEntity.getTargetNode();
588 final var editId = patchEntity.getEditId();
590 switch (patchEntity.getOperation()) {
593 tx.create(targetNode, patchEntity.getNode());
594 editCollection.add(new PatchStatusEntity(editId, true, null));
595 } catch (RestconfDocumentedException e) {
596 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
602 tx.delete(targetNode);
603 editCollection.add(new PatchStatusEntity(editId, true, null));
604 } catch (RestconfDocumentedException e) {
605 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
611 tx.ensureParentsByMerge(targetNode);
612 tx.merge(targetNode, patchEntity.getNode());
613 editCollection.add(new PatchStatusEntity(editId, true, null));
614 } catch (RestconfDocumentedException e) {
615 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
621 tx.replace(targetNode, patchEntity.getNode());
622 editCollection.add(new PatchStatusEntity(editId, true, null));
623 } catch (RestconfDocumentedException e) {
624 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
630 tx.remove(targetNode);
631 editCollection.add(new PatchStatusEntity(editId, true, null));
632 } catch (RestconfDocumentedException e) {
633 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
638 editCollection.add(new PatchStatusEntity(editId, false, List.of(
639 new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
640 "Not supported Yang Patch operation"))));
649 final var ret = new SettableRestconfFuture<PatchStatusContext>();
653 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false, null));
657 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
659 public void onSuccess(final CommitInfo result) {
660 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), true,
665 public void onFailure(final Throwable cause) {
666 // if errors occurred during transaction commit then patch failed and global errors are reported
667 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false,
668 TransactionUtil.decodeException(cause, "PATCH", null, modelContext()).getErrors()));
670 }, MoreExecutors.directExecutor());
675 private void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
676 final NormalizedNode data, final PathArgument pointArg, final NormalizedNodeContainer<?> readList,
677 final YangInstanceIdentifier grandParentPath, final boolean before) {
678 tx.remove(grandParentPath);
680 int lastItemPosition = 0;
681 for (var nodeChild : readList.body()) {
682 if (nodeChild.name().equals(pointArg)) {
691 int lastInsertedPosition = 0;
692 final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext(), grandParentPath);
693 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
694 for (var nodeChild : readList.body()) {
695 if (lastInsertedPosition == lastItemPosition) {
696 tx.replace(path, data);
698 tx.replace(grandParentPath.node(nodeChild.name()), nodeChild);
699 lastInsertedPosition++;
703 private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
704 final YangInstanceIdentifier path, final NormalizedNode data) {
706 tx.create(path, data);
707 } catch (RestconfDocumentedException e) {
708 // close transaction if any and pass exception further
717 * Check if items do NOT already exists at specified {@code path}.
719 * @param existsFuture if checked data exists
720 * @param path Path to be checked
721 * @throws RestconfDocumentedException if data already exists.
723 static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
724 final YangInstanceIdentifier path) {
725 if (TransactionUtil.syncAccess(existsFuture, path)) {
726 LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
727 throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
732 public final @NonNull RestconfFuture<NormalizedNodePayload> dataGET(final ApiPath apiPath,
733 final DataGetParams params) {
734 return dataGET(pathNormalizer.normalizeDataPath(apiPath), params);
737 abstract @NonNull RestconfFuture<NormalizedNodePayload> dataGET(DataPath path, DataGetParams params);
739 static final @NonNull RestconfFuture<NormalizedNodePayload> completeDataGET(final Inference inference,
740 final QueryParameters queryParams, final NormalizedNode node) {
742 return RestconfFuture.failed(new RestconfDocumentedException(
743 "Request could not be completed because the relevant data model content does not exist",
744 ErrorType.PROTOCOL, ErrorTag.DATA_MISSING));
747 return RestconfFuture.of(new NormalizedNodePayload(inference, node, queryParams));
751 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
752 * inside of object {@link RestconfStrategy} provided as a parameter.
754 * @param content type of data to read (config, state, all)
755 * @param path the path to read
756 * @param defaultsMode value of with-defaults parameter
757 * @return {@link NormalizedNode}
759 // FIXME: NETCONF-1155: this method should asynchronous
760 public final @Nullable NormalizedNode readData(final @NonNull ContentParam content,
761 final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
762 return switch (content) {
764 // PREPARE STATE DATA NODE
765 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
766 // PREPARE CONFIG DATA NODE
767 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
769 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
770 : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
773 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
774 yield defaultsMode == null ? read
775 : prepareDataByParamWithDef(read, path, defaultsMode.mode());
777 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
781 private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
782 final YangInstanceIdentifier path) {
783 return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
786 final NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
787 final WithDefaultsMode defaultsMode) {
788 final boolean trim = switch (defaultsMode) {
790 case Explicit -> false;
791 case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
792 "Unsupported with-defaults value " + defaultsMode.getName());
795 // FIXME: we have this readily available in InstanceIdentifierContext
796 final var ctxNode = databind.schemaTree().findChild(path).orElseThrow();
797 if (readData instanceof ContainerNode container) {
798 final var builder = Builders.containerBuilder().withNodeIdentifier(container.name());
799 buildCont(builder, container.body(), ctxNode, trim);
800 return builder.build();
801 } else if (readData instanceof MapEntryNode mapEntry) {
802 if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
803 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
806 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(mapEntry.name());
807 buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
808 return builder.build();
810 throw new IllegalStateException("Unhandled data contract " + readData.contract());
814 private static void buildMapEntryBuilder(
815 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
816 final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
817 final boolean trim, final List<QName> keys) {
818 for (var child : children) {
819 final var childCtx = getChildContext(ctxNode, child);
821 if (child instanceof ContainerNode container) {
822 appendContainer(builder, container, childCtx, trim);
823 } else if (child instanceof MapNode map) {
824 appendMap(builder, map, childCtx, trim);
825 } else if (child instanceof LeafNode<?> leaf) {
826 appendLeaf(builder, leaf, childCtx, trim, keys);
828 // FIXME: we should never hit this, throw an ISE if this ever happens
829 LOG.debug("Ignoring unhandled child contract {}", child.contract());
834 private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
835 final DataSchemaContext ctxNode, final boolean trim) {
836 final var childBuilder = Builders.containerBuilder().withNodeIdentifier(container.name());
837 buildCont(childBuilder, container.body(), ctxNode, trim);
838 builder.withChild(childBuilder.build());
841 private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
842 final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
843 if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
844 throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
847 // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
848 final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
850 // This is a combined check for when we need to emit the leaf.
852 // We always have to emit key leaf values
853 keys.contains(leafSchema.getQName())
854 // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
856 // When data is retrieved with a <with-defaults> parameter equal to
857 // 'trim', data nodes MUST NOT be reported if they contain the schema
858 // default value. Non-configuration data nodes containing the schema
859 // default value MUST NOT be reported.
861 || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
862 // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
863 // grasp what we are doing here... emit only if it matches default ???!!!
864 // FIXME: The WithDefaultsParam.EXPLICIT says:
866 // Data nodes set to the YANG default by the client are reported.
868 // and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
870 // If the "with-defaults" parameter is set to "explicit", then the
871 // server MUST adhere to the default-reporting behavior defined in
872 // Section 3.3 of [RFC6243].
874 // and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
876 // When data is retrieved with a <with-defaults> parameter equal to
877 // 'explicit', a data node that was set by a client to its schema
878 // default value MUST be reported. A conceptual data node that would be
879 // set by the server to the schema default value MUST NOT be reported.
880 // Non-configuration data nodes containing the schema default value MUST
883 // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
884 // This seems to disregard the 'trim = true' case semantics (see above).
885 // Combining the above, though, these checks are missing the 'non-config' check, which would
886 // distinguish, but barring that this check is superfluous and results in the wrong semantics.
887 // Without that input, this really should be covered by the previous case.
888 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
889 builder.withChild(leaf);
893 private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
894 final DataSchemaContext childCtx, final boolean trim) {
895 if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
896 throw new IllegalStateException("Input " + map + " does not match " + childCtx);
899 final var childBuilder = switch (map.ordering()) {
900 case SYSTEM -> Builders.mapBuilder();
901 case USER -> Builders.orderedMapBuilder();
903 buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
904 listSchema.getKeyDefinition());
905 builder.withChild(childBuilder.build());
908 private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
909 final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
910 final List<@NonNull QName> keys) {
911 for (var entry : entries) {
912 final var childCtx = getChildContext(ctxNode, entry);
913 final var mapEntryBuilder = Builders.mapEntryBuilder().withNodeIdentifier(entry.name());
914 buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
915 builder.withChild(mapEntryBuilder.build());
919 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
920 final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
921 for (var child : children) {
922 final var childCtx = getChildContext(ctxNode, child);
923 if (child instanceof ContainerNode container) {
924 appendContainer(builder, container, childCtx, trim);
925 } else if (child instanceof MapNode map) {
926 appendMap(builder, map, childCtx, trim);
927 } else if (child instanceof LeafNode<?> leaf) {
928 appendLeaf(builder, leaf, childCtx, trim, List.of());
933 private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
934 final NormalizedNode child) {
935 final var childId = child.name();
936 final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
938 if (childCtx == null) {
939 throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
944 static final NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
945 final NormalizedNode configDataNode) {
947 if (stateDataNode == null && configDataNode == null) {
951 // return config data
952 if (stateDataNode == null) {
953 return configDataNode;
957 if (configDataNode == null) {
958 return stateDataNode;
961 // merge data from config and state
962 return mergeStateAndConfigData(stateDataNode, configDataNode);
966 * Merge state and config data into a single NormalizedNode.
968 * @param stateDataNode data node of state data
969 * @param configDataNode data node of config data
970 * @return {@link NormalizedNode}
972 private static @NonNull NormalizedNode mergeStateAndConfigData(
973 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
974 validateNodeMerge(stateDataNode, configDataNode);
975 // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
976 if (configDataNode instanceof RpcDefinition) {
977 return prepareRpcData(configDataNode, stateDataNode);
979 return prepareData(configDataNode, stateDataNode);
984 * Validates whether the two NormalizedNodes can be merged.
986 * @param stateDataNode data node of state data
987 * @param configDataNode data node of config data
989 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
990 final @NonNull NormalizedNode configDataNode) {
991 final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
992 final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
993 if (!moduleOfStateData.equals(moduleOfConfigData)) {
994 throw new RestconfDocumentedException("Unable to merge data from different modules.");
999 * Prepare and map data for rpc.
1001 * @param configDataNode data node of config data
1002 * @param stateDataNode data node of state data
1003 * @return {@link NormalizedNode}
1005 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
1006 final @NonNull NormalizedNode stateDataNode) {
1007 final var mapEntryBuilder = Builders.mapEntryBuilder()
1008 .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
1011 mapRpcDataNode(configDataNode, mapEntryBuilder);
1013 mapRpcDataNode(stateDataNode, mapEntryBuilder);
1015 return Builders.mapBuilder()
1016 .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
1017 .addChild(mapEntryBuilder.build())
1022 * Map node to map entry builder.
1024 * @param dataNode data node
1025 * @param mapEntryBuilder builder for mapping data
1027 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
1028 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
1029 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
1033 * Prepare and map all data from DS.
1035 * @param configDataNode data node of config data
1036 * @param stateDataNode data node of state data
1037 * @return {@link NormalizedNode}
1039 @SuppressWarnings("unchecked")
1040 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
1041 final @NonNull NormalizedNode stateDataNode) {
1042 if (configDataNode instanceof UserMapNode configMap) {
1043 final var builder = Builders.orderedMapBuilder().withNodeIdentifier(configMap.name());
1044 mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
1045 return builder.build();
1046 } else if (configDataNode instanceof SystemMapNode configMap) {
1047 final var builder = Builders.mapBuilder().withNodeIdentifier(configMap.name());
1048 mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
1049 return builder.build();
1050 } else if (configDataNode instanceof MapEntryNode configEntry) {
1051 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(configEntry.name());
1052 mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
1053 return builder.build();
1054 } else if (configDataNode instanceof ContainerNode configContaienr) {
1055 final var builder = Builders.containerBuilder().withNodeIdentifier(configContaienr.name());
1056 mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
1057 return builder.build();
1058 } else if (configDataNode instanceof ChoiceNode configChoice) {
1059 final var builder = Builders.choiceBuilder().withNodeIdentifier(configChoice.name());
1060 mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
1061 return builder.build();
1062 } else if (configDataNode instanceof LeafNode configLeaf) {
1063 // config trumps oper
1065 } else if (configDataNode instanceof UserLeafSetNode) {
1066 final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
1067 final var builder = Builders.<Object>orderedLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
1068 mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
1069 return builder.build();
1070 } else if (configDataNode instanceof SystemLeafSetNode) {
1071 final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
1072 final var builder = Builders.<Object>leafSetBuilder().withNodeIdentifier(configLeafSet.name());
1073 mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
1074 return builder.build();
1075 } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
1076 // config trumps oper
1078 } else if (configDataNode instanceof UnkeyedListNode configList) {
1079 final var builder = Builders.unkeyedListBuilder().withNodeIdentifier(configList.name());
1080 mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
1081 return builder.build();
1082 } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
1083 final var builder = Builders.unkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
1084 mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
1085 return builder.build();
1087 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
1092 * Map value from container node to builder.
1094 * @param configData collection of config data nodes
1095 * @param stateData collection of state data nodes
1096 * @param builder builder
1098 private static <T extends NormalizedNode> void mapValueToBuilder(
1099 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
1100 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1101 final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1102 final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1104 // merge config and state data of children with different identifiers
1105 mapDataToBuilder(configMap, stateMap, builder);
1107 // merge config and state data of children with the same identifiers
1108 mergeDataToBuilder(configMap, stateMap, builder);
1112 * Map data with different identifiers to builder. Data with different identifiers can be just added
1113 * as childs to parent node.
1115 * @param configMap map of config data nodes
1116 * @param stateMap map of state data nodes
1117 * @param builder - builder
1119 private static <T extends NormalizedNode> void mapDataToBuilder(
1120 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1121 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1122 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
1123 y -> builder.addChild(y.getValue()));
1124 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
1125 y -> builder.addChild(y.getValue()));
1129 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
1130 * go one level down with {@code prepareData} method.
1132 * @param configMap immutable config data
1133 * @param stateMap immutable state data
1134 * @param builder - builder
1136 @SuppressWarnings("unchecked")
1137 private static <T extends NormalizedNode> void mergeDataToBuilder(
1138 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1139 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1140 // it is enough to process only config data because operational contains the same data
1141 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1142 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1145 public @NonNull RestconfFuture<OperationsGetResult> operationsGET() {
1146 final var modelContext = modelContext();
1147 final var modules = modelContext.getModuleStatements();
1148 if (modules.isEmpty()) {
1149 // No modules, or defensive return empty content
1150 return RestconfFuture.of(new OperationsGetResult.Container(modelContext, ImmutableSetMultimap.of()));
1153 // RPC QNames by their XMLNamespace/Revision. This should be a Table, but Revision can be null, which wrecks us.
1154 final var table = new HashMap<XMLNamespace, Map<Revision, ImmutableSet<QName>>>();
1155 for (var entry : modules.entrySet()) {
1156 final var module = entry.getValue();
1157 final var rpcNames = module.streamEffectiveSubstatements(RpcEffectiveStatement.class)
1158 .map(RpcEffectiveStatement::argument)
1159 .collect(ImmutableSet.toImmutableSet());
1160 if (!rpcNames.isEmpty()) {
1161 final var namespace = entry.getKey();
1162 table.computeIfAbsent(namespace.getNamespace(), ignored -> new HashMap<>())
1163 .put(namespace.getRevision().orElse(null), rpcNames);
1167 // Now pick the latest revision for each namespace
1168 final var rpcs = ImmutableSetMultimap.<QNameModule, QName>builder();
1169 for (var entry : table.entrySet()) {
1170 entry.getValue().entrySet().stream()
1171 .sorted(Comparator.comparing(Entry::getKey, (first, second) -> Revision.compare(second, first)))
1173 .ifPresent(row -> rpcs.putAll(QNameModule.create(entry.getKey(), row.getKey()), row.getValue()));
1175 return RestconfFuture.of(new OperationsGetResult.Container(modelContext, rpcs.build()));
1178 public @NonNull RestconfFuture<OperationsGetResult> operationsGET(final ApiPath apiPath) {
1179 if (apiPath.steps().isEmpty()) {
1180 return operationsGET();
1185 rpc = pathNormalizer.normalizeRpcPath(apiPath);
1186 } catch (RestconfDocumentedException e) {
1187 return RestconfFuture.failed(e);
1190 return RestconfFuture.of(
1191 new OperationsGetResult.Leaf(rpc.inference().getEffectiveModelContext(), rpc.rpc().argument()));
1194 public @NonNull RestconfFuture<OperationsPostResult> operationsPOST(final URI restconfURI, final ApiPath apiPath,
1195 final OperationInputBody body) {
1196 final OperationPath.Rpc path;
1198 path = pathNormalizer.normalizeRpcPath(apiPath);
1199 } catch (RestconfDocumentedException e) {
1200 return RestconfFuture.failed(e);
1203 final var postPath = new OperationsPostPath(databind, path.inference());
1204 final ContainerNode data;
1206 data = body.toContainerNode(postPath);
1207 } catch (IOException e) {
1208 LOG.debug("Error reading input", e);
1209 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1210 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1213 final var type = path.rpc().argument();
1214 final var local = localRpcs.get(type);
1215 if (local != null) {
1216 return local.invoke(restconfURI, new OperationInput(databind, postPath.operation(), data));
1218 if (rpcService == null) {
1219 LOG.debug("RPC invocation is not available");
1220 return RestconfFuture.failed(new RestconfDocumentedException("RPC invocation is not available",
1221 ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED));
1224 final var ret = new SettableRestconfFuture<OperationsPostResult>();
1225 Futures.addCallback(rpcService.invokeRpc(type, data), new FutureCallback<DOMRpcResult>() {
1227 public void onSuccess(final DOMRpcResult response) {
1228 final var errors = response.errors();
1229 if (errors.isEmpty()) {
1230 ret.set(new OperationsPostResult(databind, postPath.operation(), response.value()));
1232 LOG.debug("RPC invocation reported {}", response.errors());
1233 ret.setFailure(new RestconfDocumentedException("RPC implementation reported errors", null,
1234 response.errors()));
1239 public void onFailure(final Throwable cause) {
1240 LOG.debug("RPC invocation failed, cause");
1241 if (cause instanceof RestconfDocumentedException ex) {
1244 // TODO: YangNetconfErrorAware if we ever get into a broader invocation scope
1245 ret.setFailure(new RestconfDocumentedException(cause,
1246 new RestconfError(ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage())));
1249 }, MoreExecutors.directExecutor());
1253 public @NonNull RestconfFuture<CharSource> resolveSource(final SourceIdentifier source,
1254 final Class<? extends SchemaSourceRepresentation> representation) {
1255 final var src = requireNonNull(source);
1256 if (YangTextSchemaSource.class.isAssignableFrom(representation)) {
1257 if (sourceProvider != null) {
1258 final var ret = new SettableRestconfFuture<CharSource>();
1259 Futures.addCallback(sourceProvider.getSource(src), new FutureCallback<YangTextSchemaSource>() {
1261 public void onSuccess(final YangTextSchemaSource result) {
1266 public void onFailure(final Throwable cause) {
1267 ret.setFailure(cause instanceof RestconfDocumentedException e ? e
1268 : new RestconfDocumentedException(cause.getMessage(), ErrorType.RPC,
1269 ErrorTag.OPERATION_FAILED, cause));
1271 }, MoreExecutors.directExecutor());
1274 return exportSource(modelContext(), src, YangCharSource::new, YangCharSource::new);
1276 if (YinTextSchemaSource.class.isAssignableFrom(representation)) {
1277 return exportSource(modelContext(), src, YinCharSource.OfModule::new, YinCharSource.OfSubmodule::new);
1279 return RestconfFuture.failed(new RestconfDocumentedException(
1280 "Unsupported source representation " + representation.getName()));
1283 private static @NonNull RestconfFuture<CharSource> exportSource(final EffectiveModelContext modelContext,
1284 final SourceIdentifier source, final Function<ModuleEffectiveStatement, CharSource> moduleCtor,
1285 final BiFunction<ModuleEffectiveStatement, SubmoduleEffectiveStatement, CharSource> submoduleCtor) {
1286 // If the source identifies a module, things are easy
1287 final var name = source.name().getLocalName();
1288 final var optRevision = Optional.ofNullable(source.revision());
1289 final var optModule = modelContext.findModule(name, optRevision);
1290 if (optModule.isPresent()) {
1291 return RestconfFuture.of(moduleCtor.apply(optModule.orElseThrow().asEffectiveStatement()));
1294 // The source could be a submodule, which we need to hunt down
1295 for (var module : modelContext.getModules()) {
1296 for (var submodule : module.getSubmodules()) {
1297 if (name.equals(submodule.getName()) && optRevision.equals(submodule.getRevision())) {
1298 return RestconfFuture.of(submoduleCtor.apply(module.asEffectiveStatement(),
1299 submodule.asEffectiveStatement()));
1304 final var sb = new StringBuilder().append("Source ").append(source.name().getLocalName());
1305 optRevision.ifPresent(rev -> sb.append('@').append(rev));
1306 sb.append(" not found");
1307 return RestconfFuture.failed(new RestconfDocumentedException(sb.toString(),
1308 ErrorType.APPLICATION, ErrorTag.DATA_MISSING));
1311 public final @NonNull RestconfFuture<? extends DataPostResult> dataPOST(final ApiPath apiPath,
1312 final DataPostBody body, final Map<String, String> queryParameters) {
1313 if (apiPath.steps().isEmpty()) {
1314 return dataCreatePOST(body.toResource(), queryParameters);
1316 final var path = pathNormalizer.normalizeDataOrActionPath(apiPath);
1317 if (path instanceof DataPath dataPath) {
1318 try (var resourceBody = body.toResource()) {
1319 return dataCreatePOST(new DataPostPath(databind, dataPath.inference(), dataPath.instance()),
1320 resourceBody, queryParameters);
1323 if (path instanceof OperationPath.Action actionPath) {
1324 try (var inputBody = body.toOperationInput()) {
1325 return dataInvokePOST(actionPath, inputBody);
1328 // Note: this should never happen
1329 // FIXME: we should be able to eliminate this path with Java 21+ pattern matching
1330 return RestconfFuture.failed(new RestconfDocumentedException("Unhandled path " + path));
1333 public @NonNull RestconfFuture<CreateResource> dataCreatePOST(final ChildBody body,
1334 final Map<String, String> queryParameters) {
1335 return dataCreatePOST(new DataPostPath(databind,
1336 SchemaInferenceStack.of(databind.modelContext()).toInference(), YangInstanceIdentifier.of()), body,
1340 private @NonNull RestconfFuture<CreateResource> dataCreatePOST(final DataPostPath path, final ChildBody body,
1341 final Map<String, String> queryParameters) {
1342 final Insert insert;
1344 insert = Insert.ofQueryParameters(path.databind(), queryParameters);
1345 } catch (IllegalArgumentException e) {
1346 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
1347 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
1350 final var payload = body.toPayload(path);
1351 return postData(concat(path.instance(), payload.prefix()), payload.body(), insert);
1354 private static YangInstanceIdentifier concat(final YangInstanceIdentifier parent, final List<PathArgument> args) {
1356 for (var arg : args) {
1357 ret = ret.node(arg);
1362 private @NonNull RestconfFuture<InvokeOperation> dataInvokePOST(final OperationPath.Action path,
1363 final OperationInputBody body) {
1364 final var inference = path.inference();
1365 final ContainerNode input;
1367 input = body.toContainerNode(new OperationsPostPath(databind, inference));
1368 } catch (IOException e) {
1369 LOG.debug("Error reading input", e);
1370 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1371 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1374 if (actionService == null) {
1375 return RestconfFuture.failed(new RestconfDocumentedException("DOMActionService is missing."));
1378 final var future = dataInvokePOST(actionService, path, input);
1379 return future.transform(result -> result.getOutput()
1380 .flatMap(output -> output.isEmpty() ? Optional.empty()
1381 : Optional.of(new InvokeOperation(new NormalizedNodePayload(inference, output))))
1382 .orElse(InvokeOperation.EMPTY));
1386 * Invoke Action via ActionServiceHandler.
1388 * @param input input data
1389 * @param yangIId invocation context
1390 * @param schemaPath schema path of data
1391 * @param actionService action service to invoke action
1392 * @return {@link DOMActionResult}
1394 private static RestconfFuture<DOMActionResult> dataInvokePOST(final DOMActionService actionService,
1395 final OperationPath.Action path, final @NonNull ContainerNode input) {
1396 final var ret = new SettableRestconfFuture<DOMActionResult>();
1398 Futures.addCallback(actionService.invokeAction(
1399 path.inference().toSchemaInferenceStack().toSchemaNodeIdentifier(),
1400 new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, path.instance()), input),
1401 new FutureCallback<DOMActionResult>() {
1403 public void onSuccess(final DOMActionResult result) {
1404 final var errors = result.getErrors();
1405 LOG.debug("InvokeAction Error Message {}", errors);
1406 if (errors.isEmpty()) {
1409 ret.setFailure(new RestconfDocumentedException("InvokeAction Error Message ", null, errors));
1414 public void onFailure(final Throwable cause) {
1415 if (cause instanceof DOMActionException) {
1416 ret.set(new SimpleDOMActionResult(List.of(RpcResultBuilder.newError(
1417 ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage()))));
1418 } else if (cause instanceof RestconfDocumentedException e) {
1420 } else if (cause instanceof CancellationException) {
1421 ret.setFailure(new RestconfDocumentedException("Action cancelled while executing",
1422 ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, cause));
1424 ret.setFailure(new RestconfDocumentedException("Invocation failed", cause));
1427 }, MoreExecutors.directExecutor());