2 * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.restconf.nb.rfc8040.rests.transactions;
10 import static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.ImmutableSet;
16 import com.google.common.collect.ImmutableSetMultimap;
17 import com.google.common.io.CharSource;
18 import com.google.common.util.concurrent.FutureCallback;
19 import com.google.common.util.concurrent.Futures;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.MoreExecutors;
22 import java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Comparator;
27 import java.util.HashMap;
28 import java.util.List;
30 import java.util.Map.Entry;
31 import java.util.NoSuchElementException;
32 import java.util.Optional;
33 import java.util.concurrent.CancellationException;
34 import java.util.function.BiFunction;
35 import java.util.function.Function;
36 import java.util.stream.Collectors;
37 import org.eclipse.jdt.annotation.NonNull;
38 import org.eclipse.jdt.annotation.NonNullByDefault;
39 import org.eclipse.jdt.annotation.Nullable;
40 import org.opendaylight.mdsal.common.api.CommitInfo;
41 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
42 import org.opendaylight.mdsal.dom.api.DOMActionException;
43 import org.opendaylight.mdsal.dom.api.DOMActionResult;
44 import org.opendaylight.mdsal.dom.api.DOMActionService;
45 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
46 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
47 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
48 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
49 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
50 import org.opendaylight.mdsal.dom.api.DOMRpcService;
51 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
52 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
53 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
54 import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult;
55 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
56 import org.opendaylight.restconf.api.ApiPath;
57 import org.opendaylight.restconf.api.query.ContentParam;
58 import org.opendaylight.restconf.api.query.WithDefaultsParam;
59 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
60 import org.opendaylight.restconf.common.errors.RestconfError;
61 import org.opendaylight.restconf.common.errors.RestconfFuture;
62 import org.opendaylight.restconf.common.errors.SettableRestconfFuture;
63 import org.opendaylight.restconf.common.patch.PatchContext;
64 import org.opendaylight.restconf.common.patch.PatchStatusContext;
65 import org.opendaylight.restconf.common.patch.PatchStatusEntity;
66 import org.opendaylight.restconf.nb.rfc8040.Insert;
67 import org.opendaylight.restconf.nb.rfc8040.databind.ChildBody;
68 import org.opendaylight.restconf.nb.rfc8040.databind.DataPostBody;
69 import org.opendaylight.restconf.nb.rfc8040.databind.OperationInputBody;
70 import org.opendaylight.restconf.nb.rfc8040.databind.PatchBody;
71 import org.opendaylight.restconf.nb.rfc8040.databind.ResourceBody;
72 import org.opendaylight.restconf.nb.rfc8040.legacy.ErrorTags;
73 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
74 import org.opendaylight.restconf.nb.rfc8040.legacy.QueryParameters;
75 import org.opendaylight.restconf.nb.rfc8040.utils.parser.YangInstanceIdentifierSerializer;
76 import org.opendaylight.restconf.server.api.DataGetParams;
77 import org.opendaylight.restconf.server.api.DataPatchPath;
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.DataPutPath;
83 import org.opendaylight.restconf.server.api.DataPutResult;
84 import org.opendaylight.restconf.server.api.DatabindContext;
85 import org.opendaylight.restconf.server.api.OperationsGetResult;
86 import org.opendaylight.restconf.server.api.OperationsPostPath;
87 import org.opendaylight.restconf.server.api.OperationsPostResult;
88 import org.opendaylight.restconf.server.spi.ApiPathNormalizer;
89 import org.opendaylight.restconf.server.spi.ApiPathNormalizer.DataPath;
90 import org.opendaylight.restconf.server.spi.ApiPathNormalizer.InstanceReference;
91 import org.opendaylight.restconf.server.spi.ApiPathNormalizer.OperationPath;
92 import org.opendaylight.restconf.server.spi.ApiPathNormalizer.OperationPath.Rpc;
93 import org.opendaylight.restconf.server.spi.OperationInput;
94 import org.opendaylight.restconf.server.spi.RpcImplementation;
95 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.with.defaults.rev110601.WithDefaultsMode;
96 import org.opendaylight.yangtools.yang.common.Empty;
97 import org.opendaylight.yangtools.yang.common.ErrorTag;
98 import org.opendaylight.yangtools.yang.common.ErrorType;
99 import org.opendaylight.yangtools.yang.common.QName;
100 import org.opendaylight.yangtools.yang.common.QNameModule;
101 import org.opendaylight.yangtools.yang.common.Revision;
102 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
103 import org.opendaylight.yangtools.yang.common.XMLNamespace;
104 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
105 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
106 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
107 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
108 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
109 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
110 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
111 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
112 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
113 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
114 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
115 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
116 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
117 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
118 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
119 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
120 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
121 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
122 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
123 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
124 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
125 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
126 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
127 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
128 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
129 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
130 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
131 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
132 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
133 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
134 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
135 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
136 import org.opendaylight.yangtools.yang.model.api.stmt.RpcEffectiveStatement;
137 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleEffectiveStatement;
138 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
139 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
140 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
141 import org.opendaylight.yangtools.yang.model.repo.api.YinTextSchemaSource;
142 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
143 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
144 import org.slf4j.Logger;
145 import org.slf4j.LoggerFactory;
148 * Baseline execution strategy for various RESTCONF operations.
150 * @see NetconfRestconfStrategy
151 * @see MdsalRestconfStrategy
153 // FIXME: it seems the first three operations deal with lifecycle of a transaction, while others invoke various
154 // operations. This should be handled through proper allocation indirection.
155 public abstract class RestconfStrategy {
157 public record StrategyAndPath(RestconfStrategy strategy, DataPath path) {
158 public StrategyAndPath {
159 requireNonNull(strategy);
160 requireNonNull(path);
165 * Result of a partial {@link ApiPath} lookup for the purposes of supporting {@code yang-ext:mount}-delimited mount
166 * points with possible nesting.
168 * @param strategy the strategy to use
169 * @param tail the {@link ApiPath} tail to use with the strategy
172 public record StrategyAndTail(RestconfStrategy strategy, ApiPath tail) {
173 public StrategyAndTail {
174 requireNonNull(strategy);
175 requireNonNull(tail);
179 private static final Logger LOG = LoggerFactory.getLogger(RestconfStrategy.class);
181 private final @NonNull ImmutableMap<QName, RpcImplementation> localRpcs;
182 private final @NonNull ApiPathNormalizer pathNormalizer;
183 private final @NonNull DatabindContext databind;
184 private final DOMYangTextSourceProvider sourceProvider;
185 private final DOMMountPointService mountPointService;
186 private final DOMActionService actionService;
187 private final DOMRpcService rpcService;
189 RestconfStrategy(final DatabindContext databind, final ImmutableMap<QName, RpcImplementation> localRpcs,
190 final @Nullable DOMRpcService rpcService, final @Nullable DOMActionService actionService,
191 final DOMYangTextSourceProvider sourceProvider, final @Nullable DOMMountPointService mountPointService) {
192 this.databind = requireNonNull(databind);
193 this.localRpcs = requireNonNull(localRpcs);
194 this.rpcService = rpcService;
195 this.actionService = actionService;
196 this.sourceProvider = sourceProvider;
197 this.mountPointService = mountPointService;
198 pathNormalizer = new ApiPathNormalizer(databind);
201 public final @NonNull StrategyAndPath resolveStrategyPath(final ApiPath path) {
202 final var andTail = resolveStrategy(path);
203 final var strategy = andTail.strategy();
204 return new StrategyAndPath(strategy, strategy.pathNormalizer.normalizeDataPath(andTail.tail()));
208 * Resolve any and all {@code yang-ext:mount} to the target {@link StrategyAndTail}.
210 * @param path {@link ApiPath} to resolve
211 * @return A strategy and the remaining path
212 * @throws NullPointerException if {@code path} is {@code null}
214 public final @NonNull StrategyAndTail resolveStrategy(final ApiPath path) {
215 var mount = path.indexOf("yang-ext", "mount");
217 return new StrategyAndTail(this, path);
219 if (mountPointService == null) {
220 throw new RestconfDocumentedException("Mount point service is not available",
221 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
223 final var mountPath = path.subPath(0, mount);
224 final var dataPath = pathNormalizer.normalizeDataPath(path.subPath(0, mount));
225 final var mountPoint = mountPointService.getMountPoint(dataPath.instance())
226 .orElseThrow(() -> new RestconfDocumentedException("Mount point '" + mountPath + "' does not exist",
227 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
229 return createStrategy(mountPath, mountPoint).resolveStrategy(path.subPath(mount + 1));
232 private static @NonNull RestconfStrategy createStrategy(final ApiPath mountPath, final DOMMountPoint mountPoint) {
233 final var mountSchemaService = mountPoint.getService(DOMSchemaService.class)
234 .orElseThrow(() -> new RestconfDocumentedException(
235 "Mount point '" + mountPath + "' does not expose DOMSchemaService",
236 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
237 final var mountModelContext = mountSchemaService.getGlobalContext();
238 if (mountModelContext == null) {
239 throw new RestconfDocumentedException("Mount point '" + mountPath + "' does not have any models",
240 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT);
242 final var mountDatabind = DatabindContext.ofModel(mountModelContext);
243 final var mountPointService = mountPoint.getService(DOMMountPointService.class).orElse(null);
244 final var rpcService = mountPoint.getService(DOMRpcService.class).orElse(null);
245 final var actionService = mountPoint.getService(DOMActionService.class).orElse(null);
246 final var sourceProvider = mountPoint.getService(DOMSchemaService.class)
247 .flatMap(schema -> Optional.ofNullable(schema.getExtensions().getInstance(DOMYangTextSourceProvider.class)))
250 final var netconfService = mountPoint.getService(NetconfDataTreeService.class);
251 if (netconfService.isPresent()) {
252 return new NetconfRestconfStrategy(mountDatabind, netconfService.orElseThrow(), rpcService, actionService,
253 sourceProvider, mountPointService);
255 final var dataBroker = mountPoint.getService(DOMDataBroker.class);
256 if (dataBroker.isPresent()) {
257 return new MdsalRestconfStrategy(mountDatabind, dataBroker.orElseThrow(), rpcService, actionService,
258 sourceProvider, mountPointService);
260 LOG.warn("Mount point {} does not expose a suitable access interface", mountPath);
261 throw new RestconfDocumentedException("Could not find a supported access interface in mount point",
262 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, mountPoint.getIdentifier());
265 public final @NonNull DatabindContext databind() {
269 public final @NonNull EffectiveModelContext modelContext() {
270 return databind.modelContext();
274 * Lock the entire datastore.
276 * @return A {@link RestconfTransaction}. This transaction needs to be either committed or canceled before doing
279 abstract RestconfTransaction prepareWriteExecution();
282 * Read data from the datastore.
284 * @param store the logical data store which should be modified
285 * @param path the data object path
286 * @return a ListenableFuture containing the result of the read
288 abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path);
291 * Check if data already exists in the configuration datastore.
293 * @param path the data object path
294 * @return a ListenableFuture containing the result of the check
296 // FIXME: this method should be hosted in RestconfTransaction
297 // FIXME: this method should only be needed in MdsalRestconfStrategy
298 abstract ListenableFuture<Boolean> exists(YangInstanceIdentifier path);
301 final @NonNull RestconfFuture<Empty> merge(final YangInstanceIdentifier path, final NormalizedNode data) {
302 final var ret = new SettableRestconfFuture<Empty>();
303 merge(ret, requireNonNull(path), requireNonNull(data));
307 private void merge(final @NonNull SettableRestconfFuture<Empty> future, final @NonNull YangInstanceIdentifier path,
308 final @NonNull NormalizedNode data) {
309 final var tx = prepareWriteExecution();
310 // FIXME: this method should be further specialized to eliminate this call -- it is only needed for MD-SAL
311 tx.ensureParentsByMerge(path);
312 tx.merge(path, data);
313 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
315 public void onSuccess(final CommitInfo result) {
316 future.set(Empty.value());
320 public void onFailure(final Throwable cause) {
321 future.setFailure(TransactionUtil.decodeException(cause, "MERGE", path, modelContext()));
323 }, MoreExecutors.directExecutor());
326 public @NonNull RestconfFuture<DataPutResult> dataPUT(final ApiPath apiPath, final ResourceBody body,
327 final Map<String, String> queryParameters) {
330 path = pathNormalizer.normalizeDataPath(apiPath);
331 } catch (RestconfDocumentedException e) {
332 return RestconfFuture.failed(e);
337 insert = Insert.ofQueryParameters(databind, queryParameters);
338 } catch (IllegalArgumentException e) {
339 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
340 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
342 final NormalizedNode data;
344 data = body.toNormalizedNode(new DataPutPath(databind, path.inference(), path.instance()));
345 } catch (RestconfDocumentedException e) {
346 return RestconfFuture.failed(e);
348 return putData(path.instance(), data, insert);
352 * Check mount point and prepare variables for put data to DS.
354 * @param path path of data
356 * @param insert {@link Insert}
357 * @return A {@link DataPutResult}
359 public final @NonNull RestconfFuture<DataPutResult> putData(final YangInstanceIdentifier path,
360 final NormalizedNode data, final @Nullable Insert insert) {
361 final var exists = TransactionUtil.syncAccess(exists(path), path);
363 final ListenableFuture<? extends CommitInfo> commitFuture;
364 if (insert != null) {
365 final var parentPath = path.coerceParent();
366 checkListAndOrderedType(parentPath);
367 commitFuture = insertAndCommitPut(path, data, insert, parentPath);
369 commitFuture = replaceAndCommit(prepareWriteExecution(), path, data);
372 final var ret = new SettableRestconfFuture<DataPutResult>();
374 Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
376 public void onSuccess(final CommitInfo result) {
377 ret.set(exists ? DataPutResult.REPLACED : DataPutResult.CREATED);
381 public void onFailure(final Throwable cause) {
382 ret.setFailure(TransactionUtil.decodeException(cause, "PUT", path, modelContext()));
384 }, MoreExecutors.directExecutor());
389 private ListenableFuture<? extends CommitInfo> insertAndCommitPut(final YangInstanceIdentifier path,
390 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parentPath) {
391 final var tx = prepareWriteExecution();
393 return switch (insert.insert()) {
395 final var readData = tx.readList(parentPath);
396 if (readData == null || readData.isEmpty()) {
397 yield replaceAndCommit(tx, path, data);
399 tx.remove(parentPath);
400 tx.replace(path, data);
401 tx.replace(parentPath, readData);
404 case LAST -> replaceAndCommit(tx, path, data);
406 final var readData = tx.readList(parentPath);
407 if (readData == null || readData.isEmpty()) {
408 yield replaceAndCommit(tx, path, data);
410 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
414 final var readData = tx.readList(parentPath);
415 if (readData == null || readData.isEmpty()) {
416 yield replaceAndCommit(tx, path, data);
418 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
424 private void insertWithPointPut(final RestconfTransaction tx, final YangInstanceIdentifier path,
425 final NormalizedNode data, final @NonNull PathArgument pointArg, final NormalizedNodeContainer<?> readList,
426 final boolean before) {
427 tx.remove(path.getParent());
429 int lastItemPosition = 0;
430 for (var nodeChild : readList.body()) {
431 if (nodeChild.name().equals(pointArg)) {
440 int lastInsertedPosition = 0;
441 final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext(), path.getParent());
442 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
443 for (var nodeChild : readList.body()) {
444 if (lastInsertedPosition == lastItemPosition) {
445 tx.replace(path, data);
447 final var childPath = path.coerceParent().node(nodeChild.name());
448 tx.replace(childPath, nodeChild);
449 lastInsertedPosition++;
453 private static ListenableFuture<? extends CommitInfo> replaceAndCommit(final RestconfTransaction tx,
454 final YangInstanceIdentifier path, final NormalizedNode data) {
455 tx.replace(path, data);
459 private DataSchemaNode checkListAndOrderedType(final YangInstanceIdentifier path) {
460 // FIXME: we have this available in InstanceIdentifierContext
461 final var dataSchemaNode = databind.schemaTree().findChild(path).orElseThrow().dataSchemaNode();
463 final String message;
464 if (dataSchemaNode instanceof ListSchemaNode listSchema) {
465 if (listSchema.isUserOrdered()) {
468 message = "Insert parameter can be used only with ordered-by user list.";
469 } else if (dataSchemaNode instanceof LeafListSchemaNode leafListSchema) {
470 if (leafListSchema.isUserOrdered()) {
471 return leafListSchema;
473 message = "Insert parameter can be used only with ordered-by user leaf-list.";
475 message = "Insert parameter can be used only with list or leaf-list";
477 throw new RestconfDocumentedException(message, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
481 * Check mount point and prepare variables for post data.
485 * @param insert {@link Insert}
486 * @return A {@link RestconfFuture}
488 public final @NonNull RestconfFuture<CreateResource> postData(final YangInstanceIdentifier path,
489 final NormalizedNode data, final @Nullable Insert insert) {
490 final ListenableFuture<? extends CommitInfo> future;
491 if (insert != null) {
492 final var parentPath = path.coerceParent();
493 checkListAndOrderedType(parentPath);
494 future = insertAndCommitPost(path, data, insert, parentPath);
496 future = createAndCommit(prepareWriteExecution(), path, data);
499 final var ret = new SettableRestconfFuture<CreateResource>();
500 Futures.addCallback(future, new FutureCallback<CommitInfo>() {
502 public void onSuccess(final CommitInfo result) {
503 ret.set(new CreateResource(new YangInstanceIdentifierSerializer(databind).serializePath(
504 data instanceof MapNode mapData && !mapData.isEmpty()
505 ? path.node(mapData.body().iterator().next().name()) : path)));
509 public void onFailure(final Throwable cause) {
510 ret.setFailure(TransactionUtil.decodeException(cause, "POST", path, modelContext()));
513 }, MoreExecutors.directExecutor());
517 private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
518 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parent) {
519 final var grandParent = parent.coerceParent();
520 final var tx = prepareWriteExecution();
522 return switch (insert.insert()) {
524 final var readData = tx.readList(grandParent);
525 if (readData == null || readData.isEmpty()) {
526 tx.replace(path, data);
528 checkItemDoesNotExists(exists(path), path);
529 tx.remove(grandParent);
530 tx.replace(path, data);
531 tx.replace(grandParent, readData);
535 case LAST -> createAndCommit(tx, path, data);
537 final var readData = tx.readList(grandParent);
538 if (readData == null || readData.isEmpty()) {
539 tx.replace(path, data);
541 checkItemDoesNotExists(exists(path), path);
542 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, true);
547 final var readData = tx.readList(grandParent);
548 if (readData == null || readData.isEmpty()) {
549 tx.replace(path, data);
551 checkItemDoesNotExists(exists(path), path);
552 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, false);
560 * Merge data into the configuration datastore, as outlined in
561 * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040 section 4.6.1</a>.
563 * @param apiPath Path to merge
564 * @param body Data to merge
565 * @return A {@link RestconfFuture}
566 * @throws NullPointerException if any argument is {@code null}
568 public final @NonNull RestconfFuture<Empty> dataPATCH(final ApiPath apiPath, final ResourceBody body) {
571 path = pathNormalizer.normalizeDataPath(apiPath);
572 } catch (RestconfDocumentedException e) {
573 return RestconfFuture.failed(e);
576 final NormalizedNode data;
578 data = body.toNormalizedNode(new DataPutPath(databind, path.inference(), path.instance()));
579 } catch (RestconfDocumentedException e) {
580 return RestconfFuture.failed(e);
583 return merge(path.instance(), data);
586 public final @NonNull RestconfFuture<PatchStatusContext> dataPATCH(final ApiPath apiPath, final PatchBody body) {
589 path = pathNormalizer.normalizeDataPath(apiPath);
590 } catch (RestconfDocumentedException e) {
591 return RestconfFuture.failed(e);
594 final PatchContext patch;
596 patch = body.toPatchContext(new DataPatchPath(databind, path.instance()));
597 } catch (IOException e) {
598 LOG.debug("Error parsing YANG Patch input", e);
599 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
600 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
602 return patchData(patch);
606 * Process edit operations of one {@link PatchContext}.
608 * @param patch Patch context to be processed
609 * @return {@link PatchStatusContext}
611 public final @NonNull RestconfFuture<PatchStatusContext> patchData(final PatchContext patch) {
612 final var editCollection = new ArrayList<PatchStatusEntity>();
613 final var tx = prepareWriteExecution();
615 boolean noError = true;
616 for (var patchEntity : patch.entities()) {
618 final var targetNode = patchEntity.getTargetNode();
619 final var editId = patchEntity.getEditId();
621 switch (patchEntity.getOperation()) {
624 tx.create(targetNode, patchEntity.getNode());
625 editCollection.add(new PatchStatusEntity(editId, true, null));
626 } catch (RestconfDocumentedException e) {
627 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
633 tx.delete(targetNode);
634 editCollection.add(new PatchStatusEntity(editId, true, null));
635 } catch (RestconfDocumentedException e) {
636 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
642 tx.ensureParentsByMerge(targetNode);
643 tx.merge(targetNode, patchEntity.getNode());
644 editCollection.add(new PatchStatusEntity(editId, true, null));
645 } catch (RestconfDocumentedException e) {
646 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
652 tx.replace(targetNode, patchEntity.getNode());
653 editCollection.add(new PatchStatusEntity(editId, true, null));
654 } catch (RestconfDocumentedException e) {
655 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
661 tx.remove(targetNode);
662 editCollection.add(new PatchStatusEntity(editId, true, null));
663 } catch (RestconfDocumentedException e) {
664 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
669 editCollection.add(new PatchStatusEntity(editId, false, List.of(
670 new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
671 "Not supported Yang Patch operation"))));
680 final var ret = new SettableRestconfFuture<PatchStatusContext>();
684 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false, null));
688 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
690 public void onSuccess(final CommitInfo result) {
691 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), true,
696 public void onFailure(final Throwable cause) {
697 // if errors occurred during transaction commit then patch failed and global errors are reported
698 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false,
699 TransactionUtil.decodeException(cause, "PATCH", null, modelContext()).getErrors()));
701 }, MoreExecutors.directExecutor());
706 private void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
707 final NormalizedNode data, final PathArgument pointArg, final NormalizedNodeContainer<?> readList,
708 final YangInstanceIdentifier grandParentPath, final boolean before) {
709 tx.remove(grandParentPath);
711 int lastItemPosition = 0;
712 for (var nodeChild : readList.body()) {
713 if (nodeChild.name().equals(pointArg)) {
722 int lastInsertedPosition = 0;
723 final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext(), grandParentPath);
724 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
725 for (var nodeChild : readList.body()) {
726 if (lastInsertedPosition == lastItemPosition) {
727 tx.replace(path, data);
729 tx.replace(grandParentPath.node(nodeChild.name()), nodeChild);
730 lastInsertedPosition++;
734 private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
735 final YangInstanceIdentifier path, final NormalizedNode data) {
737 tx.create(path, data);
738 } catch (RestconfDocumentedException e) {
739 // close transaction if any and pass exception further
748 * Check if items do NOT already exists at specified {@code path}.
750 * @param existsFuture if checked data exists
751 * @param path Path to be checked
752 * @throws RestconfDocumentedException if data already exists.
754 static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
755 final YangInstanceIdentifier path) {
756 if (TransactionUtil.syncAccess(existsFuture, path)) {
757 LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
758 throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
764 * Delete data from the configuration datastore. If the data does not exist, this operation will fail, as outlined
765 * in <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.7">RFC8040 section 4.7</a>
767 * @param apiPath Path to delete
768 * @return A {@link RestconfFuture}
769 * @throws NullPointerException if {@code apiPath} is {@code null}
771 @SuppressWarnings("checkstyle:abbreviationAsWordInName")
772 public final @NonNull RestconfFuture<Empty> dataDELETE(final ApiPath apiPath) {
775 path = pathNormalizer.normalizeDataPath(apiPath);
776 } catch (RestconfDocumentedException e) {
777 return RestconfFuture.failed(e);
780 // FIXME: reject empty YangInstanceIdentifier, as datastores may not be deleted
781 final var ret = new SettableRestconfFuture<Empty>();
782 delete(ret, path.instance());
786 abstract void delete(@NonNull SettableRestconfFuture<Empty> future, @NonNull YangInstanceIdentifier path);
788 public final @NonNull RestconfFuture<NormalizedNodePayload> dataGET(final ApiPath apiPath,
789 final DataGetParams params) {
792 path = pathNormalizer.normalizeDataPath(apiPath);
793 } catch (RestconfDocumentedException e) {
794 return RestconfFuture.failed(e);
796 return dataGET(path, params);
799 abstract @NonNull RestconfFuture<NormalizedNodePayload> dataGET(DataPath path, DataGetParams params);
801 static final @NonNull RestconfFuture<NormalizedNodePayload> completeDataGET(final Inference inference,
802 final QueryParameters queryParams, final NormalizedNode node) {
804 return RestconfFuture.failed(new RestconfDocumentedException(
805 "Request could not be completed because the relevant data model content does not exist",
806 ErrorType.PROTOCOL, ErrorTag.DATA_MISSING));
809 return RestconfFuture.of(new NormalizedNodePayload(inference, node, queryParams));
813 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
814 * inside of object {@link RestconfStrategy} provided as a parameter.
816 * @param content type of data to read (config, state, all)
817 * @param path the path to read
818 * @param defaultsMode value of with-defaults parameter
819 * @return {@link NormalizedNode}
821 // FIXME: NETCONF-1155: this method should asynchronous
822 public final @Nullable NormalizedNode readData(final @NonNull ContentParam content,
823 final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
824 return switch (content) {
826 // PREPARE STATE DATA NODE
827 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
828 // PREPARE CONFIG DATA NODE
829 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
831 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
832 : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
835 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
836 yield defaultsMode == null ? read
837 : prepareDataByParamWithDef(read, path, defaultsMode.mode());
839 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
843 private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
844 final YangInstanceIdentifier path) {
845 return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
848 final NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
849 final WithDefaultsMode defaultsMode) {
850 final boolean trim = switch (defaultsMode) {
852 case Explicit -> false;
853 case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
854 "Unsupported with-defaults value " + defaultsMode.getName());
857 // FIXME: we have this readily available in InstanceIdentifierContext
858 final var ctxNode = databind.schemaTree().findChild(path).orElseThrow();
859 if (readData instanceof ContainerNode container) {
860 final var builder = Builders.containerBuilder().withNodeIdentifier(container.name());
861 buildCont(builder, container.body(), ctxNode, trim);
862 return builder.build();
863 } else if (readData instanceof MapEntryNode mapEntry) {
864 if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
865 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
868 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(mapEntry.name());
869 buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
870 return builder.build();
872 throw new IllegalStateException("Unhandled data contract " + readData.contract());
876 private static void buildMapEntryBuilder(
877 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
878 final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
879 final boolean trim, final List<QName> keys) {
880 for (var child : children) {
881 final var childCtx = getChildContext(ctxNode, child);
883 if (child instanceof ContainerNode container) {
884 appendContainer(builder, container, childCtx, trim);
885 } else if (child instanceof MapNode map) {
886 appendMap(builder, map, childCtx, trim);
887 } else if (child instanceof LeafNode<?> leaf) {
888 appendLeaf(builder, leaf, childCtx, trim, keys);
890 // FIXME: we should never hit this, throw an ISE if this ever happens
891 LOG.debug("Ignoring unhandled child contract {}", child.contract());
896 private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
897 final DataSchemaContext ctxNode, final boolean trim) {
898 final var childBuilder = Builders.containerBuilder().withNodeIdentifier(container.name());
899 buildCont(childBuilder, container.body(), ctxNode, trim);
900 builder.withChild(childBuilder.build());
903 private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
904 final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
905 if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
906 throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
909 // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
910 final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
912 // This is a combined check for when we need to emit the leaf.
914 // We always have to emit key leaf values
915 keys.contains(leafSchema.getQName())
916 // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
918 // When data is retrieved with a <with-defaults> parameter equal to
919 // 'trim', data nodes MUST NOT be reported if they contain the schema
920 // default value. Non-configuration data nodes containing the schema
921 // default value MUST NOT be reported.
923 || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
924 // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
925 // grasp what we are doing here... emit only if it matches default ???!!!
926 // FIXME: The WithDefaultsParam.EXPLICIT says:
928 // Data nodes set to the YANG default by the client are reported.
930 // and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
932 // If the "with-defaults" parameter is set to "explicit", then the
933 // server MUST adhere to the default-reporting behavior defined in
934 // Section 3.3 of [RFC6243].
936 // and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
938 // When data is retrieved with a <with-defaults> parameter equal to
939 // 'explicit', a data node that was set by a client to its schema
940 // default value MUST be reported. A conceptual data node that would be
941 // set by the server to the schema default value MUST NOT be reported.
942 // Non-configuration data nodes containing the schema default value MUST
945 // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
946 // This seems to disregard the 'trim = true' case semantics (see above).
947 // Combining the above, though, these checks are missing the 'non-config' check, which would
948 // distinguish, but barring that this check is superfluous and results in the wrong semantics.
949 // Without that input, this really should be covered by the previous case.
950 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
951 builder.withChild(leaf);
955 private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
956 final DataSchemaContext childCtx, final boolean trim) {
957 if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
958 throw new IllegalStateException("Input " + map + " does not match " + childCtx);
961 final var childBuilder = switch (map.ordering()) {
962 case SYSTEM -> Builders.mapBuilder();
963 case USER -> Builders.orderedMapBuilder();
965 buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
966 listSchema.getKeyDefinition());
967 builder.withChild(childBuilder.build());
970 private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
971 final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
972 final List<@NonNull QName> keys) {
973 for (var entry : entries) {
974 final var childCtx = getChildContext(ctxNode, entry);
975 final var mapEntryBuilder = Builders.mapEntryBuilder().withNodeIdentifier(entry.name());
976 buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
977 builder.withChild(mapEntryBuilder.build());
981 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
982 final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
983 for (var child : children) {
984 final var childCtx = getChildContext(ctxNode, child);
985 if (child instanceof ContainerNode container) {
986 appendContainer(builder, container, childCtx, trim);
987 } else if (child instanceof MapNode map) {
988 appendMap(builder, map, childCtx, trim);
989 } else if (child instanceof LeafNode<?> leaf) {
990 appendLeaf(builder, leaf, childCtx, trim, List.of());
995 private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
996 final NormalizedNode child) {
997 final var childId = child.name();
998 final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
1000 if (childCtx == null) {
1001 throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
1006 static final NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
1007 final NormalizedNode configDataNode) {
1008 // if no data exists
1009 if (stateDataNode == null && configDataNode == null) {
1013 // return config data
1014 if (stateDataNode == null) {
1015 return configDataNode;
1018 // return state data
1019 if (configDataNode == null) {
1020 return stateDataNode;
1023 // merge data from config and state
1024 return mergeStateAndConfigData(stateDataNode, configDataNode);
1028 * Merge state and config data into a single NormalizedNode.
1030 * @param stateDataNode data node of state data
1031 * @param configDataNode data node of config data
1032 * @return {@link NormalizedNode}
1034 private static @NonNull NormalizedNode mergeStateAndConfigData(
1035 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
1036 validateNodeMerge(stateDataNode, configDataNode);
1037 // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
1038 if (configDataNode instanceof RpcDefinition) {
1039 return prepareRpcData(configDataNode, stateDataNode);
1041 return prepareData(configDataNode, stateDataNode);
1046 * Validates whether the two NormalizedNodes can be merged.
1048 * @param stateDataNode data node of state data
1049 * @param configDataNode data node of config data
1051 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
1052 final @NonNull NormalizedNode configDataNode) {
1053 final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
1054 final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
1055 if (!moduleOfStateData.equals(moduleOfConfigData)) {
1056 throw new RestconfDocumentedException("Unable to merge data from different modules.");
1061 * Prepare and map data for rpc.
1063 * @param configDataNode data node of config data
1064 * @param stateDataNode data node of state data
1065 * @return {@link NormalizedNode}
1067 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
1068 final @NonNull NormalizedNode stateDataNode) {
1069 final var mapEntryBuilder = Builders.mapEntryBuilder()
1070 .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
1073 mapRpcDataNode(configDataNode, mapEntryBuilder);
1075 mapRpcDataNode(stateDataNode, mapEntryBuilder);
1077 return Builders.mapBuilder()
1078 .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
1079 .addChild(mapEntryBuilder.build())
1084 * Map node to map entry builder.
1086 * @param dataNode data node
1087 * @param mapEntryBuilder builder for mapping data
1089 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
1090 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
1091 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
1095 * Prepare and map all data from DS.
1097 * @param configDataNode data node of config data
1098 * @param stateDataNode data node of state data
1099 * @return {@link NormalizedNode}
1101 @SuppressWarnings("unchecked")
1102 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
1103 final @NonNull NormalizedNode stateDataNode) {
1104 if (configDataNode instanceof UserMapNode configMap) {
1105 final var builder = Builders.orderedMapBuilder().withNodeIdentifier(configMap.name());
1106 mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
1107 return builder.build();
1108 } else if (configDataNode instanceof SystemMapNode configMap) {
1109 final var builder = Builders.mapBuilder().withNodeIdentifier(configMap.name());
1110 mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
1111 return builder.build();
1112 } else if (configDataNode instanceof MapEntryNode configEntry) {
1113 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(configEntry.name());
1114 mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
1115 return builder.build();
1116 } else if (configDataNode instanceof ContainerNode configContaienr) {
1117 final var builder = Builders.containerBuilder().withNodeIdentifier(configContaienr.name());
1118 mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
1119 return builder.build();
1120 } else if (configDataNode instanceof ChoiceNode configChoice) {
1121 final var builder = Builders.choiceBuilder().withNodeIdentifier(configChoice.name());
1122 mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
1123 return builder.build();
1124 } else if (configDataNode instanceof LeafNode configLeaf) {
1125 // config trumps oper
1127 } else if (configDataNode instanceof UserLeafSetNode) {
1128 final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
1129 final var builder = Builders.<Object>orderedLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
1130 mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
1131 return builder.build();
1132 } else if (configDataNode instanceof SystemLeafSetNode) {
1133 final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
1134 final var builder = Builders.<Object>leafSetBuilder().withNodeIdentifier(configLeafSet.name());
1135 mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
1136 return builder.build();
1137 } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
1138 // config trumps oper
1140 } else if (configDataNode instanceof UnkeyedListNode configList) {
1141 final var builder = Builders.unkeyedListBuilder().withNodeIdentifier(configList.name());
1142 mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
1143 return builder.build();
1144 } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
1145 final var builder = Builders.unkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
1146 mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
1147 return builder.build();
1149 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
1154 * Map value from container node to builder.
1156 * @param configData collection of config data nodes
1157 * @param stateData collection of state data nodes
1158 * @param builder builder
1160 private static <T extends NormalizedNode> void mapValueToBuilder(
1161 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
1162 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1163 final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1164 final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1166 // merge config and state data of children with different identifiers
1167 mapDataToBuilder(configMap, stateMap, builder);
1169 // merge config and state data of children with the same identifiers
1170 mergeDataToBuilder(configMap, stateMap, builder);
1174 * Map data with different identifiers to builder. Data with different identifiers can be just added
1175 * as childs to parent node.
1177 * @param configMap map of config data nodes
1178 * @param stateMap map of state data nodes
1179 * @param builder - builder
1181 private static <T extends NormalizedNode> void mapDataToBuilder(
1182 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1183 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1184 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
1185 y -> builder.addChild(y.getValue()));
1186 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
1187 y -> builder.addChild(y.getValue()));
1191 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
1192 * go one level down with {@code prepareData} method.
1194 * @param configMap immutable config data
1195 * @param stateMap immutable state data
1196 * @param builder - builder
1198 @SuppressWarnings("unchecked")
1199 private static <T extends NormalizedNode> void mergeDataToBuilder(
1200 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1201 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1202 // it is enough to process only config data because operational contains the same data
1203 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1204 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1207 public @NonNull RestconfFuture<OperationsGetResult> operationsGET() {
1208 final var modelContext = modelContext();
1209 final var modules = modelContext.getModuleStatements();
1210 if (modules.isEmpty()) {
1211 // No modules, or defensive return empty content
1212 return RestconfFuture.of(new OperationsGetResult.Container(modelContext, ImmutableSetMultimap.of()));
1215 // RPC QNames by their XMLNamespace/Revision. This should be a Table, but Revision can be null, which wrecks us.
1216 final var table = new HashMap<XMLNamespace, Map<Revision, ImmutableSet<QName>>>();
1217 for (var entry : modules.entrySet()) {
1218 final var module = entry.getValue();
1219 final var rpcNames = module.streamEffectiveSubstatements(RpcEffectiveStatement.class)
1220 .map(RpcEffectiveStatement::argument)
1221 .collect(ImmutableSet.toImmutableSet());
1222 if (!rpcNames.isEmpty()) {
1223 final var namespace = entry.getKey();
1224 table.computeIfAbsent(namespace.getNamespace(), ignored -> new HashMap<>())
1225 .put(namespace.getRevision().orElse(null), rpcNames);
1229 // Now pick the latest revision for each namespace
1230 final var rpcs = ImmutableSetMultimap.<QNameModule, QName>builder();
1231 for (var entry : table.entrySet()) {
1232 entry.getValue().entrySet().stream()
1233 .sorted(Comparator.comparing(Entry::getKey, (first, second) -> Revision.compare(second, first)))
1235 .ifPresent(row -> rpcs.putAll(QNameModule.create(entry.getKey(), row.getKey()), row.getValue()));
1237 return RestconfFuture.of(new OperationsGetResult.Container(modelContext, rpcs.build()));
1240 public @NonNull RestconfFuture<OperationsGetResult> operationsGET(final ApiPath apiPath) {
1241 if (apiPath.steps().isEmpty()) {
1242 return operationsGET();
1247 rpc = pathNormalizer.normalizeRpcPath(apiPath);
1248 } catch (RestconfDocumentedException e) {
1249 return RestconfFuture.failed(e);
1252 return RestconfFuture.of(
1253 new OperationsGetResult.Leaf(rpc.inference().getEffectiveModelContext(), rpc.rpc().argument()));
1256 public @NonNull RestconfFuture<OperationsPostResult> operationsPOST(final URI restconfURI, final ApiPath apiPath,
1257 final OperationInputBody body) {
1258 final OperationPath.Rpc path;
1260 path = pathNormalizer.normalizeRpcPath(apiPath);
1261 } catch (RestconfDocumentedException e) {
1262 return RestconfFuture.failed(e);
1265 final var postPath = new OperationsPostPath(databind, path.inference());
1266 final ContainerNode data;
1268 data = body.toContainerNode(postPath);
1269 } catch (IOException e) {
1270 LOG.debug("Error reading input", e);
1271 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1272 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1275 final var type = path.rpc().argument();
1276 final var local = localRpcs.get(type);
1277 if (local != null) {
1278 return local.invoke(restconfURI, new OperationInput(databind, postPath.operation(), data));
1280 if (rpcService == null) {
1281 LOG.debug("RPC invocation is not available");
1282 return RestconfFuture.failed(new RestconfDocumentedException("RPC invocation is not available",
1283 ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED));
1286 final var ret = new SettableRestconfFuture<OperationsPostResult>();
1287 Futures.addCallback(rpcService.invokeRpc(type, data), new FutureCallback<DOMRpcResult>() {
1289 public void onSuccess(final DOMRpcResult response) {
1290 final var errors = response.errors();
1291 if (errors.isEmpty()) {
1292 ret.set(new OperationsPostResult(databind, postPath.operation(), response.value()));
1294 LOG.debug("RPC invocation reported {}", response.errors());
1295 ret.setFailure(new RestconfDocumentedException("RPC implementation reported errors", null,
1296 response.errors()));
1301 public void onFailure(final Throwable cause) {
1302 LOG.debug("RPC invocation failed, cause");
1303 if (cause instanceof RestconfDocumentedException ex) {
1306 // TODO: YangNetconfErrorAware if we ever get into a broader invocation scope
1307 ret.setFailure(new RestconfDocumentedException(cause,
1308 new RestconfError(ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage())));
1311 }, MoreExecutors.directExecutor());
1315 public @NonNull RestconfFuture<CharSource> resolveSource(final SourceIdentifier source,
1316 final Class<? extends SchemaSourceRepresentation> representation) {
1317 final var src = requireNonNull(source);
1318 if (YangTextSchemaSource.class.isAssignableFrom(representation)) {
1319 if (sourceProvider != null) {
1320 final var ret = new SettableRestconfFuture<CharSource>();
1321 Futures.addCallback(sourceProvider.getSource(src), new FutureCallback<YangTextSchemaSource>() {
1323 public void onSuccess(final YangTextSchemaSource result) {
1328 public void onFailure(final Throwable cause) {
1329 ret.setFailure(cause instanceof RestconfDocumentedException e ? e
1330 : new RestconfDocumentedException(cause.getMessage(), ErrorType.RPC,
1331 ErrorTag.OPERATION_FAILED, cause));
1333 }, MoreExecutors.directExecutor());
1336 return exportSource(modelContext(), src, YangCharSource::new, YangCharSource::new);
1338 if (YinTextSchemaSource.class.isAssignableFrom(representation)) {
1339 return exportSource(modelContext(), src, YinCharSource.OfModule::new, YinCharSource.OfSubmodule::new);
1341 return RestconfFuture.failed(new RestconfDocumentedException(
1342 "Unsupported source representation " + representation.getName()));
1345 private static @NonNull RestconfFuture<CharSource> exportSource(final EffectiveModelContext modelContext,
1346 final SourceIdentifier source, final Function<ModuleEffectiveStatement, CharSource> moduleCtor,
1347 final BiFunction<ModuleEffectiveStatement, SubmoduleEffectiveStatement, CharSource> submoduleCtor) {
1348 // If the source identifies a module, things are easy
1349 final var name = source.name().getLocalName();
1350 final var optRevision = Optional.ofNullable(source.revision());
1351 final var optModule = modelContext.findModule(name, optRevision);
1352 if (optModule.isPresent()) {
1353 return RestconfFuture.of(moduleCtor.apply(optModule.orElseThrow().asEffectiveStatement()));
1356 // The source could be a submodule, which we need to hunt down
1357 for (var module : modelContext.getModules()) {
1358 for (var submodule : module.getSubmodules()) {
1359 if (name.equals(submodule.getName()) && optRevision.equals(submodule.getRevision())) {
1360 return RestconfFuture.of(submoduleCtor.apply(module.asEffectiveStatement(),
1361 submodule.asEffectiveStatement()));
1366 final var sb = new StringBuilder().append("Source ").append(source.name().getLocalName());
1367 optRevision.ifPresent(rev -> sb.append('@').append(rev));
1368 sb.append(" not found");
1369 return RestconfFuture.failed(new RestconfDocumentedException(sb.toString(),
1370 ErrorType.APPLICATION, ErrorTag.DATA_MISSING));
1373 public final @NonNull RestconfFuture<? extends DataPostResult> dataPOST(final ApiPath apiPath,
1374 final DataPostBody body, final Map<String, String> queryParameters) {
1375 if (apiPath.steps().isEmpty()) {
1376 return dataCreatePOST(body.toResource(), queryParameters);
1378 final InstanceReference path;
1380 path = pathNormalizer.normalizeDataOrActionPath(apiPath);
1381 } catch (RestconfDocumentedException e) {
1382 return RestconfFuture.failed(e);
1384 if (path instanceof DataPath dataPath) {
1385 try (var resourceBody = body.toResource()) {
1386 return dataCreatePOST(new DataPostPath(databind, dataPath.inference(), dataPath.instance()),
1387 resourceBody, queryParameters);
1390 if (path instanceof OperationPath.Action actionPath) {
1391 try (var inputBody = body.toOperationInput()) {
1392 return dataInvokePOST(actionPath, inputBody);
1395 // Note: this should never happen
1396 // FIXME: we should be able to eliminate this path with Java 21+ pattern matching
1397 return RestconfFuture.failed(new RestconfDocumentedException("Unhandled path " + path));
1400 public @NonNull RestconfFuture<CreateResource> dataCreatePOST(final ChildBody body,
1401 final Map<String, String> queryParameters) {
1402 return dataCreatePOST(new DataPostPath(databind,
1403 SchemaInferenceStack.of(databind.modelContext()).toInference(), YangInstanceIdentifier.of()), body,
1407 private @NonNull RestconfFuture<CreateResource> dataCreatePOST(final DataPostPath path, final ChildBody body,
1408 final Map<String, String> queryParameters) {
1409 final Insert insert;
1411 insert = Insert.ofQueryParameters(path.databind(), queryParameters);
1412 } catch (IllegalArgumentException e) {
1413 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
1414 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
1417 final var payload = body.toPayload(path);
1418 return postData(concat(path.instance(), payload.prefix()), payload.body(), insert);
1421 private static YangInstanceIdentifier concat(final YangInstanceIdentifier parent, final List<PathArgument> args) {
1423 for (var arg : args) {
1424 ret = ret.node(arg);
1429 private @NonNull RestconfFuture<InvokeOperation> dataInvokePOST(final OperationPath.Action path,
1430 final OperationInputBody body) {
1431 final var inference = path.inference();
1432 final ContainerNode input;
1434 input = body.toContainerNode(new OperationsPostPath(databind, inference));
1435 } catch (IOException e) {
1436 LOG.debug("Error reading input", e);
1437 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1438 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1441 if (actionService == null) {
1442 return RestconfFuture.failed(new RestconfDocumentedException("DOMActionService is missing."));
1445 final var future = dataInvokePOST(actionService, path, input);
1446 return future.transform(result -> result.getOutput()
1447 .flatMap(output -> output.isEmpty() ? Optional.empty()
1448 : Optional.of(new InvokeOperation(new NormalizedNodePayload(inference, output))))
1449 .orElse(InvokeOperation.EMPTY));
1453 * Invoke Action via ActionServiceHandler.
1455 * @param input input data
1456 * @param yangIId invocation context
1457 * @param schemaPath schema path of data
1458 * @param actionService action service to invoke action
1459 * @return {@link DOMActionResult}
1461 private static RestconfFuture<DOMActionResult> dataInvokePOST(final DOMActionService actionService,
1462 final OperationPath.Action path, final @NonNull ContainerNode input) {
1463 final var ret = new SettableRestconfFuture<DOMActionResult>();
1465 Futures.addCallback(actionService.invokeAction(
1466 path.inference().toSchemaInferenceStack().toSchemaNodeIdentifier(),
1467 new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, path.instance()), input),
1468 new FutureCallback<DOMActionResult>() {
1470 public void onSuccess(final DOMActionResult result) {
1471 final var errors = result.getErrors();
1472 LOG.debug("InvokeAction Error Message {}", errors);
1473 if (errors.isEmpty()) {
1476 ret.setFailure(new RestconfDocumentedException("InvokeAction Error Message ", null, errors));
1481 public void onFailure(final Throwable cause) {
1482 if (cause instanceof DOMActionException) {
1483 ret.set(new SimpleDOMActionResult(List.of(RpcResultBuilder.newError(
1484 ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage()))));
1485 } else if (cause instanceof RestconfDocumentedException e) {
1487 } else if (cause instanceof CancellationException) {
1488 ret.setFailure(new RestconfDocumentedException("Action cancelled while executing",
1489 ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, cause));
1491 ret.setFailure(new RestconfDocumentedException("Invocation failed", cause));
1494 }, MoreExecutors.directExecutor());