2 * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.restconf.nb.rfc8040.rests.transactions;
10 import static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
12 import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.fromInstanceId;
14 import com.google.common.annotations.VisibleForTesting;
15 import com.google.common.collect.ImmutableMap;
16 import com.google.common.collect.ImmutableSet;
17 import com.google.common.collect.ImmutableSetMultimap;
18 import com.google.common.io.CharSource;
19 import com.google.common.util.concurrent.FutureCallback;
20 import com.google.common.util.concurrent.Futures;
21 import com.google.common.util.concurrent.ListenableFuture;
22 import com.google.common.util.concurrent.MoreExecutors;
23 import java.io.IOException;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.Comparator;
28 import java.util.HashMap;
29 import java.util.List;
31 import java.util.Map.Entry;
32 import java.util.NoSuchElementException;
33 import java.util.Optional;
34 import java.util.concurrent.CancellationException;
35 import java.util.function.BiFunction;
36 import java.util.function.Function;
37 import java.util.stream.Collectors;
38 import org.eclipse.jdt.annotation.NonNull;
39 import org.eclipse.jdt.annotation.NonNullByDefault;
40 import org.eclipse.jdt.annotation.Nullable;
41 import org.opendaylight.mdsal.common.api.CommitInfo;
42 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
43 import org.opendaylight.mdsal.dom.api.DOMActionException;
44 import org.opendaylight.mdsal.dom.api.DOMActionResult;
45 import org.opendaylight.mdsal.dom.api.DOMActionService;
46 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
47 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
48 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
49 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
50 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
51 import org.opendaylight.mdsal.dom.api.DOMRpcService;
52 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
53 import org.opendaylight.mdsal.dom.api.DOMSchemaService.YangTextSourceExtension;
54 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
55 import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult;
56 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
57 import org.opendaylight.restconf.api.ApiPath;
58 import org.opendaylight.restconf.api.query.ContentParam;
59 import org.opendaylight.restconf.api.query.WithDefaultsParam;
60 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
61 import org.opendaylight.restconf.common.errors.RestconfError;
62 import org.opendaylight.restconf.common.errors.RestconfFuture;
63 import org.opendaylight.restconf.common.errors.SettableRestconfFuture;
64 import org.opendaylight.restconf.common.patch.PatchContext;
65 import org.opendaylight.restconf.common.patch.PatchStatusContext;
66 import org.opendaylight.restconf.common.patch.PatchStatusEntity;
67 import org.opendaylight.restconf.nb.rfc8040.Insert;
68 import org.opendaylight.restconf.nb.rfc8040.legacy.ErrorTags;
69 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
70 import org.opendaylight.restconf.nb.rfc8040.legacy.QueryParameters;
71 import org.opendaylight.restconf.server.api.ChildBody;
72 import org.opendaylight.restconf.server.api.ConfigurationMetadata;
73 import org.opendaylight.restconf.server.api.DataGetParams;
74 import org.opendaylight.restconf.server.api.DataGetResult;
75 import org.opendaylight.restconf.server.api.DataPatchPath;
76 import org.opendaylight.restconf.server.api.DataPatchResult;
77 import org.opendaylight.restconf.server.api.DataPostBody;
78 import org.opendaylight.restconf.server.api.DataPostPath;
79 import org.opendaylight.restconf.server.api.DataPostResult;
80 import org.opendaylight.restconf.server.api.DataPostResult.CreateResource;
81 import org.opendaylight.restconf.server.api.DataPostResult.InvokeOperation;
82 import org.opendaylight.restconf.server.api.DataPutResult;
83 import org.opendaylight.restconf.server.api.DataYangPatchResult;
84 import org.opendaylight.restconf.server.api.DatabindContext;
85 import org.opendaylight.restconf.server.api.DatabindPath.Action;
86 import org.opendaylight.restconf.server.api.DatabindPath.Data;
87 import org.opendaylight.restconf.server.api.DatabindPath.InstanceReference;
88 import org.opendaylight.restconf.server.api.DatabindPath.Rpc;
89 import org.opendaylight.restconf.server.api.OperationInputBody;
90 import org.opendaylight.restconf.server.api.OperationsGetResult;
91 import org.opendaylight.restconf.server.api.OperationsPostPath;
92 import org.opendaylight.restconf.server.api.OperationsPostResult;
93 import org.opendaylight.restconf.server.api.PatchBody;
94 import org.opendaylight.restconf.server.api.ResourceBody;
95 import org.opendaylight.restconf.server.spi.ApiPathNormalizer;
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.spi.node.ImmutableNodes;
130 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
131 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
132 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
133 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
134 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
135 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
136 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
137 import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
138 import org.opendaylight.yangtools.yang.model.api.source.SourceRepresentation;
139 import org.opendaylight.yangtools.yang.model.api.source.YangTextSource;
140 import org.opendaylight.yangtools.yang.model.api.source.YinTextSource;
141 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
142 import org.opendaylight.yangtools.yang.model.api.stmt.RpcEffectiveStatement;
143 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleEffectiveStatement;
144 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
145 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
146 import org.slf4j.Logger;
147 import org.slf4j.LoggerFactory;
150 * Baseline execution strategy for various RESTCONF operations.
152 * @see NetconfRestconfStrategy
153 * @see MdsalRestconfStrategy
155 // FIXME: it seems the first three operations deal with lifecycle of a transaction, while others invoke various
156 // operations. This should be handled through proper allocation indirection.
157 public abstract class RestconfStrategy {
159 public record StrategyAndPath(RestconfStrategy strategy, Data path) {
160 public StrategyAndPath {
161 requireNonNull(strategy);
162 requireNonNull(path);
167 * Result of a partial {@link ApiPath} lookup for the purposes of supporting {@code yang-ext:mount}-delimited mount
168 * points with possible nesting.
170 * @param strategy the strategy to use
171 * @param tail the {@link ApiPath} tail to use with the strategy
174 public record StrategyAndTail(RestconfStrategy strategy, ApiPath tail) {
175 public StrategyAndTail {
176 requireNonNull(strategy);
177 requireNonNull(tail);
181 private static final Logger LOG = LoggerFactory.getLogger(RestconfStrategy.class);
182 private static final @NonNull DataPutResult PUT_CREATED = new DataPutResult(true);
183 private static final @NonNull DataPutResult PUT_REPLACED = new DataPutResult(false);
184 private static final @NonNull DataPatchResult PATCH_EMPTY = new DataPatchResult();
186 private final @NonNull ImmutableMap<QName, RpcImplementation> localRpcs;
187 private final @NonNull ApiPathNormalizer pathNormalizer;
188 private final @NonNull DatabindContext databind;
189 private final YangTextSourceExtension sourceProvider;
190 private final DOMMountPointService mountPointService;
191 private final DOMActionService actionService;
192 private final DOMRpcService rpcService;
194 RestconfStrategy(final DatabindContext databind, final ImmutableMap<QName, RpcImplementation> localRpcs,
195 final @Nullable DOMRpcService rpcService, final @Nullable DOMActionService actionService,
196 final YangTextSourceExtension sourceProvider, final @Nullable DOMMountPointService mountPointService) {
197 this.databind = requireNonNull(databind);
198 this.localRpcs = requireNonNull(localRpcs);
199 this.rpcService = rpcService;
200 this.actionService = actionService;
201 this.sourceProvider = sourceProvider;
202 this.mountPointService = mountPointService;
203 pathNormalizer = new ApiPathNormalizer(databind);
206 public final @NonNull StrategyAndPath resolveStrategyPath(final ApiPath path) {
207 final var andTail = resolveStrategy(path);
208 final var strategy = andTail.strategy();
209 return new StrategyAndPath(strategy, strategy.pathNormalizer.normalizeDataPath(andTail.tail()));
213 * Resolve any and all {@code yang-ext:mount} to the target {@link StrategyAndTail}.
215 * @param path {@link ApiPath} to resolve
216 * @return A strategy and the remaining path
217 * @throws NullPointerException if {@code path} is {@code null}
219 public final @NonNull StrategyAndTail resolveStrategy(final ApiPath path) {
220 var mount = path.indexOf("yang-ext", "mount");
222 return new StrategyAndTail(this, path);
224 if (mountPointService == null) {
225 throw new RestconfDocumentedException("Mount point service is not available",
226 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
228 final var mountPath = path.subPath(0, mount);
229 final var dataPath = pathNormalizer.normalizeDataPath(path.subPath(0, mount));
230 final var mountPoint = mountPointService.getMountPoint(dataPath.instance())
231 .orElseThrow(() -> new RestconfDocumentedException("Mount point '" + mountPath + "' does not exist",
232 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
234 return createStrategy(mountPath, mountPoint).resolveStrategy(path.subPath(mount + 1));
237 private static @NonNull RestconfStrategy createStrategy(final ApiPath mountPath, final DOMMountPoint mountPoint) {
238 final var mountSchemaService = mountPoint.getService(DOMSchemaService.class)
239 .orElseThrow(() -> new RestconfDocumentedException(
240 "Mount point '" + mountPath + "' does not expose DOMSchemaService",
241 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
242 final var mountModelContext = mountSchemaService.getGlobalContext();
243 if (mountModelContext == null) {
244 throw new RestconfDocumentedException("Mount point '" + mountPath + "' does not have any models",
245 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT);
247 final var mountDatabind = DatabindContext.ofModel(mountModelContext);
248 final var mountPointService = mountPoint.getService(DOMMountPointService.class).orElse(null);
249 final var rpcService = mountPoint.getService(DOMRpcService.class).orElse(null);
250 final var actionService = mountPoint.getService(DOMActionService.class).orElse(null);
251 final var sourceProvider = mountPoint.getService(DOMSchemaService.class)
252 .flatMap(schema -> Optional.ofNullable(schema.extension(YangTextSourceExtension.class)))
255 final var netconfService = mountPoint.getService(NetconfDataTreeService.class);
256 if (netconfService.isPresent()) {
257 return new NetconfRestconfStrategy(mountDatabind, netconfService.orElseThrow(), rpcService, actionService,
258 sourceProvider, mountPointService);
260 final var dataBroker = mountPoint.getService(DOMDataBroker.class);
261 if (dataBroker.isPresent()) {
262 return new MdsalRestconfStrategy(mountDatabind, dataBroker.orElseThrow(), rpcService, actionService,
263 sourceProvider, mountPointService);
265 LOG.warn("Mount point {} does not expose a suitable access interface", mountPath);
266 throw new RestconfDocumentedException("Could not find a supported access interface in mount point",
267 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, mountPoint.getIdentifier());
270 public final @NonNull DatabindContext databind() {
274 public final @NonNull EffectiveModelContext modelContext() {
275 return databind.modelContext();
279 * Lock the entire datastore.
281 * @return A {@link RestconfTransaction}. This transaction needs to be either committed or canceled before doing
284 abstract RestconfTransaction prepareWriteExecution();
287 * Read data from the datastore.
289 * @param store the logical data store which should be modified
290 * @param path the data object path
291 * @return a ListenableFuture containing the result of the read
293 abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path);
296 * Check if data already exists in the configuration datastore.
298 * @param path the data object path
299 * @return a ListenableFuture containing the result of the check
301 // FIXME: this method should be hosted in RestconfTransaction
302 // FIXME: this method should only be needed in MdsalRestconfStrategy
303 abstract ListenableFuture<Boolean> exists(YangInstanceIdentifier path);
306 final @NonNull RestconfFuture<DataPatchResult> merge(final YangInstanceIdentifier path, final NormalizedNode data) {
307 final var ret = new SettableRestconfFuture<DataPatchResult>();
308 merge(ret, requireNonNull(path), requireNonNull(data));
312 private void merge(final @NonNull SettableRestconfFuture<DataPatchResult> future,
313 final @NonNull YangInstanceIdentifier path, final @NonNull NormalizedNode data) {
314 final var tx = prepareWriteExecution();
315 // FIXME: this method should be further specialized to eliminate this call -- it is only needed for MD-SAL
316 tx.ensureParentsByMerge(path);
317 tx.merge(path, data);
318 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
320 public void onSuccess(final CommitInfo result) {
321 // TODO: extract details once CommitInfo can communicate them
322 future.set(PATCH_EMPTY);
326 public void onFailure(final Throwable cause) {
327 future.setFailure(TransactionUtil.decodeException(cause, "MERGE", path, modelContext()));
329 }, MoreExecutors.directExecutor());
332 public @NonNull RestconfFuture<DataPutResult> dataPUT(final ApiPath apiPath, final ResourceBody body,
333 final Map<String, String> queryParameters) {
336 path = pathNormalizer.normalizeDataPath(apiPath);
337 } catch (RestconfDocumentedException e) {
338 return RestconfFuture.failed(e);
343 insert = Insert.ofQueryParameters(databind, queryParameters);
344 } catch (IllegalArgumentException e) {
345 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
346 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
348 final NormalizedNode data;
350 data = body.toNormalizedNode(path);
351 } catch (RestconfDocumentedException e) {
352 return RestconfFuture.failed(e);
354 return putData(path.instance(), data, insert);
358 * Check mount point and prepare variables for put data to DS.
360 * @param path path of data
362 * @param insert {@link Insert}
363 * @return A {@link DataPutResult}
365 public final @NonNull RestconfFuture<DataPutResult> putData(final YangInstanceIdentifier path,
366 final NormalizedNode data, final @Nullable Insert insert) {
367 final var exists = TransactionUtil.syncAccess(exists(path), path);
369 final ListenableFuture<? extends CommitInfo> commitFuture;
370 if (insert != null) {
371 final var parentPath = path.coerceParent();
372 checkListAndOrderedType(parentPath);
373 commitFuture = insertAndCommitPut(path, data, insert, parentPath);
375 commitFuture = replaceAndCommit(prepareWriteExecution(), path, data);
378 final var ret = new SettableRestconfFuture<DataPutResult>();
380 Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
382 public void onSuccess(final CommitInfo result) {
383 ret.set(exists ? PUT_REPLACED : PUT_CREATED);
387 public void onFailure(final Throwable cause) {
388 ret.setFailure(TransactionUtil.decodeException(cause, "PUT", path, modelContext()));
390 }, MoreExecutors.directExecutor());
395 private ListenableFuture<? extends CommitInfo> insertAndCommitPut(final YangInstanceIdentifier path,
396 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parentPath) {
397 final var tx = prepareWriteExecution();
399 return switch (insert.insert()) {
401 final var readData = tx.readList(parentPath);
402 if (readData == null || readData.isEmpty()) {
403 yield replaceAndCommit(tx, path, data);
405 tx.remove(parentPath);
406 tx.replace(path, data);
407 tx.replace(parentPath, readData);
410 case LAST -> replaceAndCommit(tx, path, data);
412 final var readData = tx.readList(parentPath);
413 if (readData == null || readData.isEmpty()) {
414 yield replaceAndCommit(tx, path, data);
416 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
420 final var readData = tx.readList(parentPath);
421 if (readData == null || readData.isEmpty()) {
422 yield replaceAndCommit(tx, path, data);
424 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
430 private void insertWithPointPut(final RestconfTransaction tx, final YangInstanceIdentifier path,
431 final NormalizedNode data, final @NonNull PathArgument pointArg, final NormalizedNodeContainer<?> readList,
432 final boolean before) {
433 tx.remove(path.getParent());
435 int lastItemPosition = 0;
436 for (var nodeChild : readList.body()) {
437 if (nodeChild.name().equals(pointArg)) {
446 int lastInsertedPosition = 0;
447 final var emptySubtree = fromInstanceId(modelContext(), path.getParent());
448 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
449 for (var nodeChild : readList.body()) {
450 if (lastInsertedPosition == lastItemPosition) {
451 tx.replace(path, data);
453 final var childPath = path.coerceParent().node(nodeChild.name());
454 tx.replace(childPath, nodeChild);
455 lastInsertedPosition++;
458 // In case we are inserting after last element
460 if (lastInsertedPosition == lastItemPosition) {
461 tx.replace(path, data);
466 private static ListenableFuture<? extends CommitInfo> replaceAndCommit(final RestconfTransaction tx,
467 final YangInstanceIdentifier path, final NormalizedNode data) {
468 tx.replace(path, data);
472 private DataSchemaNode checkListAndOrderedType(final YangInstanceIdentifier path) {
473 // FIXME: we have this available in InstanceIdentifierContext
474 final var dataSchemaNode = databind.schemaTree().findChild(path).orElseThrow().dataSchemaNode();
476 final String message;
477 if (dataSchemaNode instanceof ListSchemaNode listSchema) {
478 if (listSchema.isUserOrdered()) {
481 message = "Insert parameter can be used only with ordered-by user list.";
482 } else if (dataSchemaNode instanceof LeafListSchemaNode leafListSchema) {
483 if (leafListSchema.isUserOrdered()) {
484 return leafListSchema;
486 message = "Insert parameter can be used only with ordered-by user leaf-list.";
488 message = "Insert parameter can be used only with list or leaf-list";
490 throw new RestconfDocumentedException(message, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
494 * Check mount point and prepare variables for post data.
498 * @param insert {@link Insert}
499 * @return A {@link RestconfFuture}
501 public final @NonNull RestconfFuture<CreateResource> postData(final YangInstanceIdentifier path,
502 final NormalizedNode data, final @Nullable Insert insert) {
503 final ListenableFuture<? extends CommitInfo> future;
504 if (insert != null) {
505 checkListAndOrderedType(path);
506 future = insertAndCommitPost(path, data, insert);
508 future = createAndCommit(prepareWriteExecution(), path, data);
511 final var ret = new SettableRestconfFuture<CreateResource>();
512 Futures.addCallback(future, new FutureCallback<CommitInfo>() {
514 public void onSuccess(final CommitInfo result) {
515 ret.set(new CreateResource(new ApiPathNormalizer(databind).canonicalize(
516 data instanceof MapNode mapData && !mapData.isEmpty()
517 ? path.node(mapData.body().iterator().next().name()) : path).toString()));
521 public void onFailure(final Throwable cause) {
522 ret.setFailure(TransactionUtil.decodeException(cause, "POST", path, modelContext()));
525 }, MoreExecutors.directExecutor());
529 private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
530 final NormalizedNode data, final @NonNull Insert insert) {
531 final var tx = prepareWriteExecution();
533 return switch (insert.insert()) {
535 final var readData = tx.readList(path);
536 if (readData == null || readData.isEmpty()) {
537 tx.replace(path, data);
539 checkListDataDoesNotExist(path, data);
541 tx.replace(path, data);
542 tx.replace(path, readData);
546 case LAST -> createAndCommit(tx, path, data);
548 final var readData = tx.readList(path);
549 if (readData == null || readData.isEmpty()) {
550 tx.replace(path, data);
552 checkListDataDoesNotExist(path, data);
553 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
558 final var readData = tx.readList(path);
559 if (readData == null || readData.isEmpty()) {
560 tx.replace(path, data);
562 checkListDataDoesNotExist(path, data);
563 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
571 * Merge data into the configuration datastore, as outlined in
572 * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040 section 4.6.1</a>.
574 * @param apiPath Path to merge
575 * @param body Data to merge
576 * @return A {@link RestconfFuture}
577 * @throws NullPointerException if any argument is {@code null}
579 public final @NonNull RestconfFuture<DataPatchResult> dataPATCH(final ApiPath apiPath, final ResourceBody body) {
582 path = pathNormalizer.normalizeDataPath(apiPath);
583 } catch (RestconfDocumentedException e) {
584 return RestconfFuture.failed(e);
587 final NormalizedNode data;
589 data = body.toNormalizedNode(path);
590 } catch (RestconfDocumentedException e) {
591 return RestconfFuture.failed(e);
594 return merge(path.instance(), data);
597 public final @NonNull RestconfFuture<DataYangPatchResult> dataPATCH(final ApiPath apiPath, final PatchBody body) {
600 path = pathNormalizer.normalizeDataPath(apiPath);
601 } catch (RestconfDocumentedException e) {
602 return RestconfFuture.failed(e);
605 final PatchContext patch;
607 patch = body.toPatchContext(new DataPatchPath(databind, path.instance()));
608 } catch (IOException e) {
609 LOG.debug("Error parsing YANG Patch input", e);
610 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
611 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
613 return patchData(patch);
617 * Process edit operations of one {@link PatchContext}.
619 * @param patch Patch context to be processed
620 * @return {@link PatchStatusContext}
622 public final @NonNull RestconfFuture<DataYangPatchResult> patchData(final PatchContext patch) {
623 final var editCollection = new ArrayList<PatchStatusEntity>();
624 final var tx = prepareWriteExecution();
626 boolean noError = true;
627 for (var patchEntity : patch.entities()) {
629 final var targetNode = patchEntity.getTargetNode();
630 final var editId = patchEntity.getEditId();
632 switch (patchEntity.getOperation()) {
635 tx.create(targetNode, patchEntity.getNode());
636 editCollection.add(new PatchStatusEntity(editId, true, null));
637 } catch (RestconfDocumentedException e) {
638 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
644 tx.delete(targetNode);
645 editCollection.add(new PatchStatusEntity(editId, true, null));
646 } catch (RestconfDocumentedException e) {
647 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
653 tx.ensureParentsByMerge(targetNode);
654 tx.merge(targetNode, patchEntity.getNode());
655 editCollection.add(new PatchStatusEntity(editId, true, null));
656 } catch (RestconfDocumentedException e) {
657 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
663 tx.replace(targetNode, patchEntity.getNode());
664 editCollection.add(new PatchStatusEntity(editId, true, null));
665 } catch (RestconfDocumentedException e) {
666 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
672 tx.remove(targetNode);
673 editCollection.add(new PatchStatusEntity(editId, true, null));
674 } catch (RestconfDocumentedException e) {
675 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
680 editCollection.add(new PatchStatusEntity(editId, false, List.of(
681 new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
682 "Not supported Yang Patch operation"))));
691 final var ret = new SettableRestconfFuture<DataYangPatchResult>();
695 ret.set(new DataYangPatchResult(
696 new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false, null)));
700 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
702 public void onSuccess(final CommitInfo result) {
703 ret.set(new DataYangPatchResult(
704 new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), true, null)));
708 public void onFailure(final Throwable cause) {
709 // if errors occurred during transaction commit then patch failed and global errors are reported
710 ret.set(new DataYangPatchResult(
711 new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false,
712 TransactionUtil.decodeException(cause, "PATCH", null, modelContext()).getErrors())));
714 }, MoreExecutors.directExecutor());
719 private void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
720 final NormalizedNode data, final PathArgument pointArg, final NormalizedNodeContainer<?> readList,
721 final boolean before) {
724 int lastItemPosition = 0;
725 for (var nodeChild : readList.body()) {
726 if (nodeChild.name().equals(pointArg)) {
735 int lastInsertedPosition = 0;
736 for (var nodeChild : readList.body()) {
737 if (lastInsertedPosition == lastItemPosition) {
738 tx.replace(path, data);
740 tx.replace(path.node(nodeChild.name()), nodeChild);
741 lastInsertedPosition++;
744 // In case we are inserting after last element
746 if (lastInsertedPosition == lastItemPosition) {
747 tx.replace(path, data);
752 private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
753 final YangInstanceIdentifier path, final NormalizedNode data) {
755 tx.create(path, data);
756 } catch (RestconfDocumentedException e) {
757 // close transaction if any and pass exception further
766 * Check if child items do NOT already exists in List at specified {@code path}.
768 * @param data Data to be checked
769 * @param path Path to be checked
770 * @throws RestconfDocumentedException if data already exists.
772 private void checkListDataDoesNotExist(final YangInstanceIdentifier path, final NormalizedNode data) {
773 if (data instanceof NormalizedNodeContainer<?> dataNode) {
774 for (final var node : dataNode.body()) {
775 checkItemDoesNotExists(exists(path.node(node.name())), path.node(node.name()));
778 throw new RestconfDocumentedException("Unexpected node type: " + data.getClass().getName());
783 * Check if items do NOT already exists at specified {@code path}.
785 * @param existsFuture if checked data exists
786 * @param path Path to be checked
787 * @throws RestconfDocumentedException if data already exists.
789 static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
790 final YangInstanceIdentifier path) {
791 if (TransactionUtil.syncAccess(existsFuture, path)) {
792 LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
793 throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
799 * Delete data from the configuration datastore. If the data does not exist, this operation will fail, as outlined
800 * in <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.7">RFC8040 section 4.7</a>
802 * @param apiPath Path to delete
803 * @return A {@link RestconfFuture}
804 * @throws NullPointerException if {@code apiPath} is {@code null}
806 @SuppressWarnings("checkstyle:abbreviationAsWordInName")
807 public final @NonNull RestconfFuture<Empty> dataDELETE(final ApiPath apiPath) {
810 path = pathNormalizer.normalizeDataPath(apiPath);
811 } catch (RestconfDocumentedException e) {
812 return RestconfFuture.failed(e);
815 // FIXME: reject empty YangInstanceIdentifier, as datastores may not be deleted
816 final var ret = new SettableRestconfFuture<Empty>();
817 delete(ret, path.instance());
821 abstract void delete(@NonNull SettableRestconfFuture<Empty> future, @NonNull YangInstanceIdentifier path);
823 public final @NonNull RestconfFuture<DataGetResult> dataGET(final ApiPath apiPath,
824 final DataGetParams params) {
827 path = pathNormalizer.normalizeDataPath(apiPath);
828 } catch (RestconfDocumentedException e) {
829 return RestconfFuture.failed(e);
831 return dataGET(path, params);
834 abstract @NonNull RestconfFuture<DataGetResult> dataGET(Data path, DataGetParams params);
836 static final @NonNull RestconfFuture<DataGetResult> completeDataGET(final Inference inference,
837 final QueryParameters queryParams, final @Nullable NormalizedNode node,
838 final @Nullable ConfigurationMetadata metadata) {
840 return RestconfFuture.failed(new RestconfDocumentedException(
841 "Request could not be completed because the relevant data model content does not exist",
842 ErrorType.PROTOCOL, ErrorTag.DATA_MISSING));
845 final var payload = new NormalizedNodePayload(inference, node, queryParams);
846 return RestconfFuture.of(metadata == null ? new DataGetResult(payload)
847 : new DataGetResult(payload, metadata.entityTag(), metadata.lastModified()));
851 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
852 * inside of object {@link RestconfStrategy} provided as a parameter.
854 * @param content type of data to read (config, state, all)
855 * @param path the path to read
856 * @param defaultsMode value of with-defaults parameter
857 * @return {@link NormalizedNode}
859 // FIXME: NETCONF-1155: this method should asynchronous
861 final @Nullable NormalizedNode readData(final @NonNull ContentParam content,
862 final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
863 return switch (content) {
865 // PREPARE STATE DATA NODE
866 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
867 // PREPARE CONFIG DATA NODE
868 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
870 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
871 : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
874 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
875 yield defaultsMode == null ? read
876 : prepareDataByParamWithDef(read, path, defaultsMode.mode());
878 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
882 private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
883 final YangInstanceIdentifier path) {
884 return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
887 final NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
888 final WithDefaultsMode defaultsMode) {
889 final boolean trim = switch (defaultsMode) {
891 case Explicit -> false;
892 case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
893 "Unsupported with-defaults value " + defaultsMode.getName());
896 // FIXME: we have this readily available in InstanceIdentifierContext
897 final var ctxNode = databind.schemaTree().findChild(path).orElseThrow();
898 if (readData instanceof ContainerNode container) {
899 final var builder = ImmutableNodes.newContainerBuilder().withNodeIdentifier(container.name());
900 buildCont(builder, container.body(), ctxNode, trim);
901 return builder.build();
902 } else if (readData instanceof MapEntryNode mapEntry) {
903 if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
904 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
907 final var builder = ImmutableNodes.newMapEntryBuilder().withNodeIdentifier(mapEntry.name());
908 buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
909 return builder.build();
911 throw new IllegalStateException("Unhandled data contract " + readData.contract());
915 private static void buildMapEntryBuilder(
916 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
917 final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
918 final boolean trim, final List<QName> keys) {
919 for (var child : children) {
920 final var childCtx = getChildContext(ctxNode, child);
922 if (child instanceof ContainerNode container) {
923 appendContainer(builder, container, childCtx, trim);
924 } else if (child instanceof MapNode map) {
925 appendMap(builder, map, childCtx, trim);
926 } else if (child instanceof LeafNode<?> leaf) {
927 appendLeaf(builder, leaf, childCtx, trim, keys);
929 // FIXME: we should never hit this, throw an ISE if this ever happens
930 LOG.debug("Ignoring unhandled child contract {}", child.contract());
935 private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
936 final DataSchemaContext ctxNode, final boolean trim) {
937 final var childBuilder = ImmutableNodes.newContainerBuilder().withNodeIdentifier(container.name());
938 buildCont(childBuilder, container.body(), ctxNode, trim);
939 builder.withChild(childBuilder.build());
942 private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
943 final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
944 if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
945 throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
948 // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
949 final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
951 // This is a combined check for when we need to emit the leaf.
953 // We always have to emit key leaf values
954 keys.contains(leafSchema.getQName())
955 // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
957 // When data is retrieved with a <with-defaults> parameter equal to
958 // 'trim', data nodes MUST NOT be reported if they contain the schema
959 // default value. Non-configuration data nodes containing the schema
960 // default value MUST NOT be reported.
962 || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
963 // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
964 // grasp what we are doing here... emit only if it matches default ???!!!
965 // FIXME: The WithDefaultsParam.EXPLICIT says:
967 // Data nodes set to the YANG default by the client are reported.
969 // and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
971 // If the "with-defaults" parameter is set to "explicit", then the
972 // server MUST adhere to the default-reporting behavior defined in
973 // Section 3.3 of [RFC6243].
975 // and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
977 // When data is retrieved with a <with-defaults> parameter equal to
978 // 'explicit', a data node that was set by a client to its schema
979 // default value MUST be reported. A conceptual data node that would be
980 // set by the server to the schema default value MUST NOT be reported.
981 // Non-configuration data nodes containing the schema default value MUST
984 // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
985 // This seems to disregard the 'trim = true' case semantics (see above).
986 // Combining the above, though, these checks are missing the 'non-config' check, which would
987 // distinguish, but barring that this check is superfluous and results in the wrong semantics.
988 // Without that input, this really should be covered by the previous case.
989 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
990 builder.withChild(leaf);
994 private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
995 final DataSchemaContext childCtx, final boolean trim) {
996 if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
997 throw new IllegalStateException("Input " + map + " does not match " + childCtx);
1000 final var childBuilder = switch (map.ordering()) {
1001 case SYSTEM -> ImmutableNodes.newSystemMapBuilder();
1002 case USER -> ImmutableNodes.newUserMapBuilder();
1004 buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
1005 listSchema.getKeyDefinition());
1006 builder.withChild(childBuilder.build());
1009 private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
1010 final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
1011 final List<@NonNull QName> keys) {
1012 for (var entry : entries) {
1013 final var childCtx = getChildContext(ctxNode, entry);
1014 final var mapEntryBuilder = ImmutableNodes.newMapEntryBuilder().withNodeIdentifier(entry.name());
1015 buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
1016 builder.withChild(mapEntryBuilder.build());
1020 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
1021 final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
1022 for (var child : children) {
1023 final var childCtx = getChildContext(ctxNode, child);
1024 if (child instanceof ContainerNode container) {
1025 appendContainer(builder, container, childCtx, trim);
1026 } else if (child instanceof MapNode map) {
1027 appendMap(builder, map, childCtx, trim);
1028 } else if (child instanceof LeafNode<?> leaf) {
1029 appendLeaf(builder, leaf, childCtx, trim, List.of());
1034 private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
1035 final NormalizedNode child) {
1036 final var childId = child.name();
1037 final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
1039 if (childCtx == null) {
1040 throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
1045 static final NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
1046 final NormalizedNode configDataNode) {
1047 if (stateDataNode == null) {
1048 // No state, return config
1049 return configDataNode;
1051 if (configDataNode == null) {
1052 // No config, return state
1053 return stateDataNode;
1055 // merge config and state
1056 return mergeStateAndConfigData(stateDataNode, configDataNode);
1060 * Merge state and config data into a single NormalizedNode.
1062 * @param stateDataNode data node of state data
1063 * @param configDataNode data node of config data
1064 * @return {@link NormalizedNode}
1066 private static @NonNull NormalizedNode mergeStateAndConfigData(
1067 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
1068 validateNodeMerge(stateDataNode, configDataNode);
1069 // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
1070 if (configDataNode instanceof RpcDefinition) {
1071 return prepareRpcData(configDataNode, stateDataNode);
1073 return prepareData(configDataNode, stateDataNode);
1078 * Validates whether the two NormalizedNodes can be merged.
1080 * @param stateDataNode data node of state data
1081 * @param configDataNode data node of config data
1083 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
1084 final @NonNull NormalizedNode configDataNode) {
1085 final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
1086 final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
1087 if (!moduleOfStateData.equals(moduleOfConfigData)) {
1088 throw new RestconfDocumentedException("Unable to merge data from different modules.");
1093 * Prepare and map data for rpc.
1095 * @param configDataNode data node of config data
1096 * @param stateDataNode data node of state data
1097 * @return {@link NormalizedNode}
1099 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
1100 final @NonNull NormalizedNode stateDataNode) {
1101 final var mapEntryBuilder = ImmutableNodes.newMapEntryBuilder()
1102 .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
1105 mapRpcDataNode(configDataNode, mapEntryBuilder);
1107 mapRpcDataNode(stateDataNode, mapEntryBuilder);
1109 return ImmutableNodes.newSystemMapBuilder()
1110 .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
1111 .addChild(mapEntryBuilder.build())
1116 * Map node to map entry builder.
1118 * @param dataNode data node
1119 * @param mapEntryBuilder builder for mapping data
1121 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
1122 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
1123 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
1127 * Prepare and map all data from DS.
1129 * @param configDataNode data node of config data
1130 * @param stateDataNode data node of state data
1131 * @return {@link NormalizedNode}
1133 @SuppressWarnings("unchecked")
1134 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
1135 final @NonNull NormalizedNode stateDataNode) {
1136 if (configDataNode instanceof UserMapNode configMap) {
1137 final var builder = ImmutableNodes.newUserMapBuilder().withNodeIdentifier(configMap.name());
1138 mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
1139 return builder.build();
1140 } else if (configDataNode instanceof SystemMapNode configMap) {
1141 final var builder = ImmutableNodes.newSystemMapBuilder().withNodeIdentifier(configMap.name());
1142 mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
1143 return builder.build();
1144 } else if (configDataNode instanceof MapEntryNode configEntry) {
1145 final var builder = ImmutableNodes.newMapEntryBuilder().withNodeIdentifier(configEntry.name());
1146 mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
1147 return builder.build();
1148 } else if (configDataNode instanceof ContainerNode configContaienr) {
1149 final var builder = ImmutableNodes.newContainerBuilder().withNodeIdentifier(configContaienr.name());
1150 mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
1151 return builder.build();
1152 } else if (configDataNode instanceof ChoiceNode configChoice) {
1153 final var builder = ImmutableNodes.newChoiceBuilder().withNodeIdentifier(configChoice.name());
1154 mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
1155 return builder.build();
1156 } else if (configDataNode instanceof LeafNode configLeaf) {
1157 // config trumps oper
1159 } else if (configDataNode instanceof UserLeafSetNode) {
1160 final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
1161 final var builder = ImmutableNodes.<Object>newUserLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
1162 mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
1163 return builder.build();
1164 } else if (configDataNode instanceof SystemLeafSetNode) {
1165 final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
1166 final var builder = ImmutableNodes.<Object>newSystemLeafSetBuilder()
1167 .withNodeIdentifier(configLeafSet.name());
1168 mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
1169 return builder.build();
1170 } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
1171 // config trumps oper
1173 } else if (configDataNode instanceof UnkeyedListNode configList) {
1174 final var builder = ImmutableNodes.newUnkeyedListBuilder().withNodeIdentifier(configList.name());
1175 mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
1176 return builder.build();
1177 } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
1178 final var builder = ImmutableNodes.newUnkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
1179 mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
1180 return builder.build();
1182 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
1187 * Map value from container node to builder.
1189 * @param configData collection of config data nodes
1190 * @param stateData collection of state data nodes
1191 * @param builder builder
1193 private static <T extends NormalizedNode> void mapValueToBuilder(
1194 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
1195 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1196 final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1197 final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1199 // merge config and state data of children with different identifiers
1200 mapDataToBuilder(configMap, stateMap, builder);
1202 // merge config and state data of children with the same identifiers
1203 mergeDataToBuilder(configMap, stateMap, builder);
1207 * Map data with different identifiers to builder. Data with different identifiers can be just added
1208 * as childs to parent node.
1210 * @param configMap map of config data nodes
1211 * @param stateMap map of state data nodes
1212 * @param builder - builder
1214 private static <T extends NormalizedNode> void mapDataToBuilder(
1215 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1216 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1217 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
1218 y -> builder.addChild(y.getValue()));
1219 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
1220 y -> builder.addChild(y.getValue()));
1224 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
1225 * go one level down with {@code prepareData} method.
1227 * @param configMap immutable config data
1228 * @param stateMap immutable state data
1229 * @param builder - builder
1231 @SuppressWarnings("unchecked")
1232 private static <T extends NormalizedNode> void mergeDataToBuilder(
1233 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1234 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1235 // it is enough to process only config data because operational contains the same data
1236 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1237 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1240 public @NonNull RestconfFuture<OperationsGetResult> operationsGET() {
1241 final var modelContext = modelContext();
1242 final var modules = modelContext.getModuleStatements();
1243 if (modules.isEmpty()) {
1244 // No modules, or defensive return empty content
1245 return RestconfFuture.of(new OperationsGetResult.Container(modelContext, ImmutableSetMultimap.of()));
1248 // RPC QNames by their XMLNamespace/Revision. This should be a Table, but Revision can be null, which wrecks us.
1249 final var table = new HashMap<XMLNamespace, Map<Revision, ImmutableSet<QName>>>();
1250 for (var entry : modules.entrySet()) {
1251 final var module = entry.getValue();
1252 final var rpcNames = module.streamEffectiveSubstatements(RpcEffectiveStatement.class)
1253 .map(RpcEffectiveStatement::argument)
1254 .collect(ImmutableSet.toImmutableSet());
1255 if (!rpcNames.isEmpty()) {
1256 final var namespace = entry.getKey();
1257 table.computeIfAbsent(namespace.namespace(), ignored -> new HashMap<>())
1258 .put(namespace.revision(), rpcNames);
1262 // Now pick the latest revision for each namespace
1263 final var rpcs = ImmutableSetMultimap.<QNameModule, QName>builder();
1264 for (var entry : table.entrySet()) {
1265 entry.getValue().entrySet().stream()
1266 .sorted(Comparator.comparing(Entry::getKey, (first, second) -> Revision.compare(second, first)))
1268 .ifPresent(row -> rpcs.putAll(QNameModule.of(entry.getKey(), row.getKey()), row.getValue()));
1270 return RestconfFuture.of(new OperationsGetResult.Container(modelContext, rpcs.build()));
1273 public @NonNull RestconfFuture<OperationsGetResult> operationsGET(final ApiPath apiPath) {
1274 if (apiPath.steps().isEmpty()) {
1275 return operationsGET();
1280 rpc = pathNormalizer.normalizeRpcPath(apiPath);
1281 } catch (RestconfDocumentedException e) {
1282 return RestconfFuture.failed(e);
1285 return RestconfFuture.of(new OperationsGetResult.Leaf(rpc.inference().modelContext(), rpc.rpc().argument()));
1288 public @NonNull RestconfFuture<OperationsPostResult> operationsPOST(final URI restconfURI, final ApiPath apiPath,
1289 final OperationInputBody body) {
1292 path = pathNormalizer.normalizeRpcPath(apiPath);
1293 } catch (RestconfDocumentedException e) {
1294 return RestconfFuture.failed(e);
1297 final var postPath = new OperationsPostPath(databind, path.inference());
1298 final ContainerNode data;
1300 data = body.toContainerNode(postPath);
1301 } catch (IOException e) {
1302 LOG.debug("Error reading input", e);
1303 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1304 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1307 final var type = path.rpc().argument();
1308 final var local = localRpcs.get(type);
1309 if (local != null) {
1310 return local.invoke(restconfURI, new OperationInput(databind, postPath.operation(), data));
1312 if (rpcService == null) {
1313 LOG.debug("RPC invocation is not available");
1314 return RestconfFuture.failed(new RestconfDocumentedException("RPC invocation is not available",
1315 ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED));
1318 final var ret = new SettableRestconfFuture<OperationsPostResult>();
1319 Futures.addCallback(rpcService.invokeRpc(type, data), new FutureCallback<DOMRpcResult>() {
1321 public void onSuccess(final DOMRpcResult response) {
1322 final var errors = response.errors();
1323 if (errors.isEmpty()) {
1324 ret.set(new OperationsPostResult(databind, postPath.operation(), response.value()));
1326 LOG.debug("RPC invocation reported {}", response.errors());
1327 ret.setFailure(new RestconfDocumentedException("RPC implementation reported errors", null,
1328 response.errors()));
1333 public void onFailure(final Throwable cause) {
1334 LOG.debug("RPC invocation failed, cause");
1335 if (cause instanceof RestconfDocumentedException ex) {
1338 // TODO: YangNetconfErrorAware if we ever get into a broader invocation scope
1339 ret.setFailure(new RestconfDocumentedException(cause,
1340 new RestconfError(ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage())));
1343 }, MoreExecutors.directExecutor());
1347 public @NonNull RestconfFuture<CharSource> resolveSource(final SourceIdentifier source,
1348 final Class<? extends SourceRepresentation> representation) {
1349 final var src = requireNonNull(source);
1350 if (YangTextSource.class.isAssignableFrom(representation)) {
1351 if (sourceProvider != null) {
1352 final var ret = new SettableRestconfFuture<CharSource>();
1353 Futures.addCallback(sourceProvider.getYangTexttSource(src), new FutureCallback<>() {
1355 public void onSuccess(final YangTextSource result) {
1360 public void onFailure(final Throwable cause) {
1361 ret.setFailure(cause instanceof RestconfDocumentedException e ? e
1362 : new RestconfDocumentedException(cause.getMessage(), ErrorType.RPC,
1363 ErrorTag.OPERATION_FAILED, cause));
1365 }, MoreExecutors.directExecutor());
1368 return exportSource(modelContext(), src, YangCharSource::new, YangCharSource::new);
1370 if (YinTextSource.class.isAssignableFrom(representation)) {
1371 return exportSource(modelContext(), src, YinCharSource.OfModule::new, YinCharSource.OfSubmodule::new);
1373 return RestconfFuture.failed(new RestconfDocumentedException(
1374 "Unsupported source representation " + representation.getName()));
1377 private static @NonNull RestconfFuture<CharSource> exportSource(final EffectiveModelContext modelContext,
1378 final SourceIdentifier source, final Function<ModuleEffectiveStatement, CharSource> moduleCtor,
1379 final BiFunction<ModuleEffectiveStatement, SubmoduleEffectiveStatement, CharSource> submoduleCtor) {
1380 // If the source identifies a module, things are easy
1381 final var name = source.name().getLocalName();
1382 final var optRevision = Optional.ofNullable(source.revision());
1383 final var optModule = modelContext.findModule(name, optRevision);
1384 if (optModule.isPresent()) {
1385 return RestconfFuture.of(moduleCtor.apply(optModule.orElseThrow().asEffectiveStatement()));
1388 // The source could be a submodule, which we need to hunt down
1389 for (var module : modelContext.getModules()) {
1390 for (var submodule : module.getSubmodules()) {
1391 if (name.equals(submodule.getName()) && optRevision.equals(submodule.getRevision())) {
1392 return RestconfFuture.of(submoduleCtor.apply(module.asEffectiveStatement(),
1393 submodule.asEffectiveStatement()));
1398 final var sb = new StringBuilder().append("Source ").append(source.name().getLocalName());
1399 optRevision.ifPresent(rev -> sb.append('@').append(rev));
1400 sb.append(" not found");
1401 return RestconfFuture.failed(new RestconfDocumentedException(sb.toString(),
1402 ErrorType.APPLICATION, ErrorTag.DATA_MISSING));
1405 public final @NonNull RestconfFuture<? extends DataPostResult> dataPOST(final ApiPath apiPath,
1406 final DataPostBody body, final Map<String, String> queryParameters) {
1407 if (apiPath.steps().isEmpty()) {
1408 return dataCreatePOST(body.toResource(), queryParameters);
1410 final InstanceReference path;
1412 path = pathNormalizer.normalizeDataOrActionPath(apiPath);
1413 } catch (RestconfDocumentedException e) {
1414 return RestconfFuture.failed(e);
1416 if (path instanceof Data dataPath) {
1417 try (var resourceBody = body.toResource()) {
1418 return dataCreatePOST(new DataPostPath(databind, dataPath.inference(), dataPath.instance()),
1419 resourceBody, queryParameters);
1422 if (path instanceof Action actionPath) {
1423 try (var inputBody = body.toOperationInput()) {
1424 return dataInvokePOST(actionPath, inputBody);
1427 // Note: this should never happen
1428 // FIXME: we should be able to eliminate this path with Java 21+ pattern matching
1429 return RestconfFuture.failed(new RestconfDocumentedException("Unhandled path " + path));
1432 public @NonNull RestconfFuture<CreateResource> dataCreatePOST(final ChildBody body,
1433 final Map<String, String> queryParameters) {
1434 return dataCreatePOST(new DataPostPath(databind,
1435 SchemaInferenceStack.of(databind.modelContext()).toInference(), YangInstanceIdentifier.of()), body,
1439 private @NonNull RestconfFuture<CreateResource> dataCreatePOST(final DataPostPath path, final ChildBody body,
1440 final Map<String, String> queryParameters) {
1441 final Insert insert;
1443 insert = Insert.ofQueryParameters(path.databind(), queryParameters);
1444 } catch (IllegalArgumentException e) {
1445 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
1446 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
1449 final var payload = body.toPayload(path);
1450 return postData(concat(path.instance(), payload.prefix()), payload.body(), insert);
1453 private static YangInstanceIdentifier concat(final YangInstanceIdentifier parent, final List<PathArgument> args) {
1455 for (var arg : args) {
1456 ret = ret.node(arg);
1461 private @NonNull RestconfFuture<InvokeOperation> dataInvokePOST(final Action path, final OperationInputBody body) {
1462 final var inference = path.inference();
1463 final ContainerNode input;
1465 input = body.toContainerNode(new OperationsPostPath(databind, inference));
1466 } catch (IOException e) {
1467 LOG.debug("Error reading input", e);
1468 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1469 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1472 if (actionService == null) {
1473 return RestconfFuture.failed(new RestconfDocumentedException("DOMActionService is missing."));
1476 final var future = dataInvokePOST(actionService, path, input);
1477 return future.transform(result -> result.getOutput()
1478 .flatMap(output -> output.isEmpty() ? Optional.empty()
1479 : Optional.of(new InvokeOperation(new NormalizedNodePayload(inference, output))))
1480 .orElse(InvokeOperation.EMPTY));
1484 * Invoke Action via ActionServiceHandler.
1486 * @param input input data
1487 * @param yangIId invocation context
1488 * @param schemaPath schema path of data
1489 * @param actionService action service to invoke action
1490 * @return {@link DOMActionResult}
1492 private static RestconfFuture<DOMActionResult> dataInvokePOST(final DOMActionService actionService,
1493 final Action path, final @NonNull ContainerNode input) {
1494 final var ret = new SettableRestconfFuture<DOMActionResult>();
1496 Futures.addCallback(actionService.invokeAction(
1497 path.inference().toSchemaInferenceStack().toSchemaNodeIdentifier(),
1498 DOMDataTreeIdentifier.of(LogicalDatastoreType.OPERATIONAL, path.instance()), input),
1499 new FutureCallback<DOMActionResult>() {
1501 public void onSuccess(final DOMActionResult result) {
1502 final var errors = result.getErrors();
1503 LOG.debug("InvokeAction Error Message {}", errors);
1504 if (errors.isEmpty()) {
1507 ret.setFailure(new RestconfDocumentedException("InvokeAction Error Message ", null, errors));
1512 public void onFailure(final Throwable cause) {
1513 if (cause instanceof DOMActionException) {
1514 ret.set(new SimpleDOMActionResult(List.of(RpcResultBuilder.newError(
1515 ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage()))));
1516 } else if (cause instanceof RestconfDocumentedException e) {
1518 } else if (cause instanceof CancellationException) {
1519 ret.setFailure(new RestconfDocumentedException("Action cancelled while executing",
1520 ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, cause));
1522 ret.setFailure(new RestconfDocumentedException("Invocation failed", cause));
1525 }, MoreExecutors.directExecutor());