2 * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.restconf.nb.rfc8040.rests.transactions;
10 import static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.ImmutableSet;
16 import com.google.common.collect.ImmutableSetMultimap;
17 import com.google.common.io.CharSource;
18 import com.google.common.util.concurrent.FutureCallback;
19 import com.google.common.util.concurrent.Futures;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.MoreExecutors;
22 import java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Comparator;
27 import java.util.HashMap;
28 import java.util.List;
30 import java.util.Map.Entry;
31 import java.util.NoSuchElementException;
32 import java.util.Optional;
33 import java.util.concurrent.CancellationException;
34 import java.util.function.BiFunction;
35 import java.util.function.Function;
36 import java.util.stream.Collectors;
37 import org.eclipse.jdt.annotation.NonNull;
38 import org.eclipse.jdt.annotation.NonNullByDefault;
39 import org.eclipse.jdt.annotation.Nullable;
40 import org.opendaylight.mdsal.common.api.CommitInfo;
41 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
42 import org.opendaylight.mdsal.dom.api.DOMActionException;
43 import org.opendaylight.mdsal.dom.api.DOMActionResult;
44 import org.opendaylight.mdsal.dom.api.DOMActionService;
45 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
46 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
47 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
48 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
49 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
50 import org.opendaylight.mdsal.dom.api.DOMRpcService;
51 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
52 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
53 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
54 import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult;
55 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
56 import org.opendaylight.restconf.api.ApiPath;
57 import org.opendaylight.restconf.api.query.ContentParam;
58 import org.opendaylight.restconf.api.query.WithDefaultsParam;
59 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
60 import org.opendaylight.restconf.common.errors.RestconfError;
61 import org.opendaylight.restconf.common.errors.RestconfFuture;
62 import org.opendaylight.restconf.common.errors.SettableRestconfFuture;
63 import org.opendaylight.restconf.common.patch.PatchContext;
64 import org.opendaylight.restconf.common.patch.PatchStatusContext;
65 import org.opendaylight.restconf.common.patch.PatchStatusEntity;
66 import org.opendaylight.restconf.nb.rfc8040.Insert;
67 import org.opendaylight.restconf.nb.rfc8040.databind.ChildBody;
68 import org.opendaylight.restconf.nb.rfc8040.databind.DataPostBody;
69 import org.opendaylight.restconf.nb.rfc8040.databind.OperationInputBody;
70 import org.opendaylight.restconf.nb.rfc8040.databind.PatchBody;
71 import org.opendaylight.restconf.nb.rfc8040.databind.ResourceBody;
72 import org.opendaylight.restconf.nb.rfc8040.legacy.ErrorTags;
73 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
74 import org.opendaylight.restconf.nb.rfc8040.legacy.QueryParameters;
75 import org.opendaylight.restconf.nb.rfc8040.utils.parser.YangInstanceIdentifierSerializer;
76 import org.opendaylight.restconf.server.api.ConfigurationMetadata;
77 import org.opendaylight.restconf.server.api.DataGetParams;
78 import org.opendaylight.restconf.server.api.DataGetResult;
79 import org.opendaylight.restconf.server.api.DataPatchPath;
80 import org.opendaylight.restconf.server.api.DataPostPath;
81 import org.opendaylight.restconf.server.api.DataPostResult;
82 import org.opendaylight.restconf.server.api.DataPostResult.CreateResource;
83 import org.opendaylight.restconf.server.api.DataPostResult.InvokeOperation;
84 import org.opendaylight.restconf.server.api.DataPutPath;
85 import org.opendaylight.restconf.server.api.DataPutResult;
86 import org.opendaylight.restconf.server.api.DatabindContext;
87 import org.opendaylight.restconf.server.api.OperationsGetResult;
88 import org.opendaylight.restconf.server.api.OperationsPostPath;
89 import org.opendaylight.restconf.server.api.OperationsPostResult;
90 import org.opendaylight.restconf.server.spi.ApiPathNormalizer;
91 import org.opendaylight.restconf.server.spi.ApiPathNormalizer.DataPath;
92 import org.opendaylight.restconf.server.spi.ApiPathNormalizer.InstanceReference;
93 import org.opendaylight.restconf.server.spi.ApiPathNormalizer.OperationPath;
94 import org.opendaylight.restconf.server.spi.ApiPathNormalizer.OperationPath.Rpc;
95 import org.opendaylight.restconf.server.spi.OperationInput;
96 import org.opendaylight.restconf.server.spi.RpcImplementation;
97 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.with.defaults.rev110601.WithDefaultsMode;
98 import org.opendaylight.yangtools.yang.common.Empty;
99 import org.opendaylight.yangtools.yang.common.ErrorTag;
100 import org.opendaylight.yangtools.yang.common.ErrorType;
101 import org.opendaylight.yangtools.yang.common.QName;
102 import org.opendaylight.yangtools.yang.common.QNameModule;
103 import org.opendaylight.yangtools.yang.common.Revision;
104 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
105 import org.opendaylight.yangtools.yang.common.XMLNamespace;
106 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
107 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
108 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
109 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
110 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
111 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
112 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
113 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
114 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
115 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
116 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
117 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
118 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
119 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
120 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
121 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
122 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
123 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
124 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
125 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
126 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
127 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
128 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
129 import org.opendaylight.yangtools.yang.data.impl.schema.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.stmt.ModuleEffectiveStatement;
138 import org.opendaylight.yangtools.yang.model.api.stmt.RpcEffectiveStatement;
139 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleEffectiveStatement;
140 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
141 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
142 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
143 import org.opendaylight.yangtools.yang.model.repo.api.YinTextSchemaSource;
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, DataPath 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);
183 private final @NonNull ImmutableMap<QName, RpcImplementation> localRpcs;
184 private final @NonNull ApiPathNormalizer pathNormalizer;
185 private final @NonNull DatabindContext databind;
186 private final DOMYangTextSourceProvider sourceProvider;
187 private final DOMMountPointService mountPointService;
188 private final DOMActionService actionService;
189 private final DOMRpcService rpcService;
191 RestconfStrategy(final DatabindContext databind, final ImmutableMap<QName, RpcImplementation> localRpcs,
192 final @Nullable DOMRpcService rpcService, final @Nullable DOMActionService actionService,
193 final DOMYangTextSourceProvider sourceProvider, final @Nullable DOMMountPointService mountPointService) {
194 this.databind = requireNonNull(databind);
195 this.localRpcs = requireNonNull(localRpcs);
196 this.rpcService = rpcService;
197 this.actionService = actionService;
198 this.sourceProvider = sourceProvider;
199 this.mountPointService = mountPointService;
200 pathNormalizer = new ApiPathNormalizer(databind);
203 public final @NonNull StrategyAndPath resolveStrategyPath(final ApiPath path) {
204 final var andTail = resolveStrategy(path);
205 final var strategy = andTail.strategy();
206 return new StrategyAndPath(strategy, strategy.pathNormalizer.normalizeDataPath(andTail.tail()));
210 * Resolve any and all {@code yang-ext:mount} to the target {@link StrategyAndTail}.
212 * @param path {@link ApiPath} to resolve
213 * @return A strategy and the remaining path
214 * @throws NullPointerException if {@code path} is {@code null}
216 public final @NonNull StrategyAndTail resolveStrategy(final ApiPath path) {
217 var mount = path.indexOf("yang-ext", "mount");
219 return new StrategyAndTail(this, path);
221 if (mountPointService == null) {
222 throw new RestconfDocumentedException("Mount point service is not available",
223 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
225 final var mountPath = path.subPath(0, mount);
226 final var dataPath = pathNormalizer.normalizeDataPath(path.subPath(0, mount));
227 final var mountPoint = mountPointService.getMountPoint(dataPath.instance())
228 .orElseThrow(() -> new RestconfDocumentedException("Mount point '" + mountPath + "' does not exist",
229 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
231 return createStrategy(mountPath, mountPoint).resolveStrategy(path.subPath(mount + 1));
234 private static @NonNull RestconfStrategy createStrategy(final ApiPath mountPath, final DOMMountPoint mountPoint) {
235 final var mountSchemaService = mountPoint.getService(DOMSchemaService.class)
236 .orElseThrow(() -> new RestconfDocumentedException(
237 "Mount point '" + mountPath + "' does not expose DOMSchemaService",
238 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
239 final var mountModelContext = mountSchemaService.getGlobalContext();
240 if (mountModelContext == null) {
241 throw new RestconfDocumentedException("Mount point '" + mountPath + "' does not have any models",
242 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT);
244 final var mountDatabind = DatabindContext.ofModel(mountModelContext);
245 final var mountPointService = mountPoint.getService(DOMMountPointService.class).orElse(null);
246 final var rpcService = mountPoint.getService(DOMRpcService.class).orElse(null);
247 final var actionService = mountPoint.getService(DOMActionService.class).orElse(null);
248 final var sourceProvider = mountPoint.getService(DOMSchemaService.class)
249 .flatMap(schema -> Optional.ofNullable(schema.getExtensions().getInstance(DOMYangTextSourceProvider.class)))
252 final var netconfService = mountPoint.getService(NetconfDataTreeService.class);
253 if (netconfService.isPresent()) {
254 return new NetconfRestconfStrategy(mountDatabind, netconfService.orElseThrow(), rpcService, actionService,
255 sourceProvider, mountPointService);
257 final var dataBroker = mountPoint.getService(DOMDataBroker.class);
258 if (dataBroker.isPresent()) {
259 return new MdsalRestconfStrategy(mountDatabind, dataBroker.orElseThrow(), rpcService, actionService,
260 sourceProvider, mountPointService);
262 LOG.warn("Mount point {} does not expose a suitable access interface", mountPath);
263 throw new RestconfDocumentedException("Could not find a supported access interface in mount point",
264 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, mountPoint.getIdentifier());
267 public final @NonNull DatabindContext databind() {
271 public final @NonNull EffectiveModelContext modelContext() {
272 return databind.modelContext();
276 * Lock the entire datastore.
278 * @return A {@link RestconfTransaction}. This transaction needs to be either committed or canceled before doing
281 abstract RestconfTransaction prepareWriteExecution();
284 * Read data from the datastore.
286 * @param store the logical data store which should be modified
287 * @param path the data object path
288 * @return a ListenableFuture containing the result of the read
290 abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path);
293 * Check if data already exists in the configuration datastore.
295 * @param path the data object path
296 * @return a ListenableFuture containing the result of the check
298 // FIXME: this method should be hosted in RestconfTransaction
299 // FIXME: this method should only be needed in MdsalRestconfStrategy
300 abstract ListenableFuture<Boolean> exists(YangInstanceIdentifier path);
303 final @NonNull RestconfFuture<Empty> merge(final YangInstanceIdentifier path, final NormalizedNode data) {
304 final var ret = new SettableRestconfFuture<Empty>();
305 merge(ret, requireNonNull(path), requireNonNull(data));
309 private void merge(final @NonNull SettableRestconfFuture<Empty> future, final @NonNull YangInstanceIdentifier path,
310 final @NonNull NormalizedNode data) {
311 final var tx = prepareWriteExecution();
312 // FIXME: this method should be further specialized to eliminate this call -- it is only needed for MD-SAL
313 tx.ensureParentsByMerge(path);
314 tx.merge(path, data);
315 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
317 public void onSuccess(final CommitInfo result) {
318 future.set(Empty.value());
322 public void onFailure(final Throwable cause) {
323 future.setFailure(TransactionUtil.decodeException(cause, "MERGE", path, modelContext()));
325 }, MoreExecutors.directExecutor());
328 public @NonNull RestconfFuture<DataPutResult> dataPUT(final ApiPath apiPath, final ResourceBody body,
329 final Map<String, String> queryParameters) {
332 path = pathNormalizer.normalizeDataPath(apiPath);
333 } catch (RestconfDocumentedException e) {
334 return RestconfFuture.failed(e);
339 insert = Insert.ofQueryParameters(databind, queryParameters);
340 } catch (IllegalArgumentException e) {
341 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
342 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
344 final NormalizedNode data;
346 data = body.toNormalizedNode(new DataPutPath(databind, path.inference(), path.instance()));
347 } catch (RestconfDocumentedException e) {
348 return RestconfFuture.failed(e);
350 return putData(path.instance(), data, insert);
354 * Check mount point and prepare variables for put data to DS.
356 * @param path path of data
358 * @param insert {@link Insert}
359 * @return A {@link DataPutResult}
361 public final @NonNull RestconfFuture<DataPutResult> putData(final YangInstanceIdentifier path,
362 final NormalizedNode data, final @Nullable Insert insert) {
363 final var exists = TransactionUtil.syncAccess(exists(path), path);
365 final ListenableFuture<? extends CommitInfo> commitFuture;
366 if (insert != null) {
367 final var parentPath = path.coerceParent();
368 checkListAndOrderedType(parentPath);
369 commitFuture = insertAndCommitPut(path, data, insert, parentPath);
371 commitFuture = replaceAndCommit(prepareWriteExecution(), path, data);
374 final var ret = new SettableRestconfFuture<DataPutResult>();
376 Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
378 public void onSuccess(final CommitInfo result) {
379 ret.set(exists ? DataPutResult.REPLACED : DataPutResult.CREATED);
383 public void onFailure(final Throwable cause) {
384 ret.setFailure(TransactionUtil.decodeException(cause, "PUT", path, modelContext()));
386 }, MoreExecutors.directExecutor());
391 private ListenableFuture<? extends CommitInfo> insertAndCommitPut(final YangInstanceIdentifier path,
392 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parentPath) {
393 final var tx = prepareWriteExecution();
395 return switch (insert.insert()) {
397 final var readData = tx.readList(parentPath);
398 if (readData == null || readData.isEmpty()) {
399 yield replaceAndCommit(tx, path, data);
401 tx.remove(parentPath);
402 tx.replace(path, data);
403 tx.replace(parentPath, readData);
406 case LAST -> replaceAndCommit(tx, path, data);
408 final var readData = tx.readList(parentPath);
409 if (readData == null || readData.isEmpty()) {
410 yield replaceAndCommit(tx, path, data);
412 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
416 final var readData = tx.readList(parentPath);
417 if (readData == null || readData.isEmpty()) {
418 yield replaceAndCommit(tx, path, data);
420 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
426 private void insertWithPointPut(final RestconfTransaction tx, final YangInstanceIdentifier path,
427 final NormalizedNode data, final @NonNull PathArgument pointArg, final NormalizedNodeContainer<?> readList,
428 final boolean before) {
429 tx.remove(path.getParent());
431 int lastItemPosition = 0;
432 for (var nodeChild : readList.body()) {
433 if (nodeChild.name().equals(pointArg)) {
442 int lastInsertedPosition = 0;
443 final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext(), path.getParent());
444 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
445 for (var nodeChild : readList.body()) {
446 if (lastInsertedPosition == lastItemPosition) {
447 tx.replace(path, data);
449 final var childPath = path.coerceParent().node(nodeChild.name());
450 tx.replace(childPath, nodeChild);
451 lastInsertedPosition++;
455 private static ListenableFuture<? extends CommitInfo> replaceAndCommit(final RestconfTransaction tx,
456 final YangInstanceIdentifier path, final NormalizedNode data) {
457 tx.replace(path, data);
461 private DataSchemaNode checkListAndOrderedType(final YangInstanceIdentifier path) {
462 // FIXME: we have this available in InstanceIdentifierContext
463 final var dataSchemaNode = databind.schemaTree().findChild(path).orElseThrow().dataSchemaNode();
465 final String message;
466 if (dataSchemaNode instanceof ListSchemaNode listSchema) {
467 if (listSchema.isUserOrdered()) {
470 message = "Insert parameter can be used only with ordered-by user list.";
471 } else if (dataSchemaNode instanceof LeafListSchemaNode leafListSchema) {
472 if (leafListSchema.isUserOrdered()) {
473 return leafListSchema;
475 message = "Insert parameter can be used only with ordered-by user leaf-list.";
477 message = "Insert parameter can be used only with list or leaf-list";
479 throw new RestconfDocumentedException(message, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
483 * Check mount point and prepare variables for post data.
487 * @param insert {@link Insert}
488 * @return A {@link RestconfFuture}
490 public final @NonNull RestconfFuture<CreateResource> postData(final YangInstanceIdentifier path,
491 final NormalizedNode data, final @Nullable Insert insert) {
492 final ListenableFuture<? extends CommitInfo> future;
493 if (insert != null) {
494 final var parentPath = path.coerceParent();
495 checkListAndOrderedType(parentPath);
496 future = insertAndCommitPost(path, data, insert, parentPath);
498 future = createAndCommit(prepareWriteExecution(), path, data);
501 final var ret = new SettableRestconfFuture<CreateResource>();
502 Futures.addCallback(future, new FutureCallback<CommitInfo>() {
504 public void onSuccess(final CommitInfo result) {
505 ret.set(new CreateResource(new YangInstanceIdentifierSerializer(databind).serializePath(
506 data instanceof MapNode mapData && !mapData.isEmpty()
507 ? path.node(mapData.body().iterator().next().name()) : path)));
511 public void onFailure(final Throwable cause) {
512 ret.setFailure(TransactionUtil.decodeException(cause, "POST", path, modelContext()));
515 }, MoreExecutors.directExecutor());
519 private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
520 final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parent) {
521 final var grandParent = parent.coerceParent();
522 final var tx = prepareWriteExecution();
524 return switch (insert.insert()) {
526 final var readData = tx.readList(grandParent);
527 if (readData == null || readData.isEmpty()) {
528 tx.replace(path, data);
530 checkItemDoesNotExists(exists(path), path);
531 tx.remove(grandParent);
532 tx.replace(path, data);
533 tx.replace(grandParent, readData);
537 case LAST -> createAndCommit(tx, path, data);
539 final var readData = tx.readList(grandParent);
540 if (readData == null || readData.isEmpty()) {
541 tx.replace(path, data);
543 checkItemDoesNotExists(exists(path), path);
544 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, true);
549 final var readData = tx.readList(grandParent);
550 if (readData == null || readData.isEmpty()) {
551 tx.replace(path, data);
553 checkItemDoesNotExists(exists(path), path);
554 insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, false);
562 * Merge data into the configuration datastore, as outlined in
563 * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040 section 4.6.1</a>.
565 * @param apiPath Path to merge
566 * @param body Data to merge
567 * @return A {@link RestconfFuture}
568 * @throws NullPointerException if any argument is {@code null}
570 public final @NonNull RestconfFuture<Empty> dataPATCH(final ApiPath apiPath, final ResourceBody body) {
573 path = pathNormalizer.normalizeDataPath(apiPath);
574 } catch (RestconfDocumentedException e) {
575 return RestconfFuture.failed(e);
578 final NormalizedNode data;
580 data = body.toNormalizedNode(new DataPutPath(databind, path.inference(), path.instance()));
581 } catch (RestconfDocumentedException e) {
582 return RestconfFuture.failed(e);
585 return merge(path.instance(), data);
588 public final @NonNull RestconfFuture<PatchStatusContext> dataPATCH(final ApiPath apiPath, final PatchBody body) {
591 path = pathNormalizer.normalizeDataPath(apiPath);
592 } catch (RestconfDocumentedException e) {
593 return RestconfFuture.failed(e);
596 final PatchContext patch;
598 patch = body.toPatchContext(new DataPatchPath(databind, path.instance()));
599 } catch (IOException e) {
600 LOG.debug("Error parsing YANG Patch input", e);
601 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
602 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
604 return patchData(patch);
608 * Process edit operations of one {@link PatchContext}.
610 * @param patch Patch context to be processed
611 * @return {@link PatchStatusContext}
613 public final @NonNull RestconfFuture<PatchStatusContext> patchData(final PatchContext patch) {
614 final var editCollection = new ArrayList<PatchStatusEntity>();
615 final var tx = prepareWriteExecution();
617 boolean noError = true;
618 for (var patchEntity : patch.entities()) {
620 final var targetNode = patchEntity.getTargetNode();
621 final var editId = patchEntity.getEditId();
623 switch (patchEntity.getOperation()) {
626 tx.create(targetNode, patchEntity.getNode());
627 editCollection.add(new PatchStatusEntity(editId, true, null));
628 } catch (RestconfDocumentedException e) {
629 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
635 tx.delete(targetNode);
636 editCollection.add(new PatchStatusEntity(editId, true, null));
637 } catch (RestconfDocumentedException e) {
638 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
644 tx.ensureParentsByMerge(targetNode);
645 tx.merge(targetNode, patchEntity.getNode());
646 editCollection.add(new PatchStatusEntity(editId, true, null));
647 } catch (RestconfDocumentedException e) {
648 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
654 tx.replace(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.remove(targetNode);
664 editCollection.add(new PatchStatusEntity(editId, true, null));
665 } catch (RestconfDocumentedException e) {
666 editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
671 editCollection.add(new PatchStatusEntity(editId, false, List.of(
672 new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
673 "Not supported Yang Patch operation"))));
682 final var ret = new SettableRestconfFuture<PatchStatusContext>();
686 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false, null));
690 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
692 public void onSuccess(final CommitInfo result) {
693 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), true,
698 public void onFailure(final Throwable cause) {
699 // if errors occurred during transaction commit then patch failed and global errors are reported
700 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false,
701 TransactionUtil.decodeException(cause, "PATCH", null, modelContext()).getErrors()));
703 }, MoreExecutors.directExecutor());
708 private void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
709 final NormalizedNode data, final PathArgument pointArg, final NormalizedNodeContainer<?> readList,
710 final YangInstanceIdentifier grandParentPath, final boolean before) {
711 tx.remove(grandParentPath);
713 int lastItemPosition = 0;
714 for (var nodeChild : readList.body()) {
715 if (nodeChild.name().equals(pointArg)) {
724 int lastInsertedPosition = 0;
725 final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext(), grandParentPath);
726 tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
727 for (var nodeChild : readList.body()) {
728 if (lastInsertedPosition == lastItemPosition) {
729 tx.replace(path, data);
731 tx.replace(grandParentPath.node(nodeChild.name()), nodeChild);
732 lastInsertedPosition++;
736 private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
737 final YangInstanceIdentifier path, final NormalizedNode data) {
739 tx.create(path, data);
740 } catch (RestconfDocumentedException e) {
741 // close transaction if any and pass exception further
750 * Check if items do NOT already exists at specified {@code path}.
752 * @param existsFuture if checked data exists
753 * @param path Path to be checked
754 * @throws RestconfDocumentedException if data already exists.
756 static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
757 final YangInstanceIdentifier path) {
758 if (TransactionUtil.syncAccess(existsFuture, path)) {
759 LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
760 throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
766 * Delete data from the configuration datastore. If the data does not exist, this operation will fail, as outlined
767 * in <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.7">RFC8040 section 4.7</a>
769 * @param apiPath Path to delete
770 * @return A {@link RestconfFuture}
771 * @throws NullPointerException if {@code apiPath} is {@code null}
773 @SuppressWarnings("checkstyle:abbreviationAsWordInName")
774 public final @NonNull RestconfFuture<Empty> dataDELETE(final ApiPath apiPath) {
777 path = pathNormalizer.normalizeDataPath(apiPath);
778 } catch (RestconfDocumentedException e) {
779 return RestconfFuture.failed(e);
782 // FIXME: reject empty YangInstanceIdentifier, as datastores may not be deleted
783 final var ret = new SettableRestconfFuture<Empty>();
784 delete(ret, path.instance());
788 abstract void delete(@NonNull SettableRestconfFuture<Empty> future, @NonNull YangInstanceIdentifier path);
790 public final @NonNull RestconfFuture<DataGetResult> dataGET(final ApiPath apiPath,
791 final DataGetParams params) {
794 path = pathNormalizer.normalizeDataPath(apiPath);
795 } catch (RestconfDocumentedException e) {
796 return RestconfFuture.failed(e);
798 return dataGET(path, params);
801 abstract @NonNull RestconfFuture<DataGetResult> dataGET(DataPath path, DataGetParams params);
803 static final @NonNull RestconfFuture<DataGetResult> completeDataGET(final Inference inference,
804 final QueryParameters queryParams, final @Nullable NormalizedNode node,
805 final @Nullable ConfigurationMetadata metadata) {
807 return RestconfFuture.failed(new RestconfDocumentedException(
808 "Request could not be completed because the relevant data model content does not exist",
809 ErrorType.PROTOCOL, ErrorTag.DATA_MISSING));
812 final var payload = new NormalizedNodePayload(inference, node, queryParams);
813 return RestconfFuture.of(metadata == null ? new DataGetResult(payload)
814 : new DataGetResult(payload, metadata.entityTag(), metadata.lastModified()));
818 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
819 * inside of object {@link RestconfStrategy} provided as a parameter.
821 * @param content type of data to read (config, state, all)
822 * @param path the path to read
823 * @param defaultsMode value of with-defaults parameter
824 * @return {@link NormalizedNode}
826 // FIXME: NETCONF-1155: this method should asynchronous
827 public final @Nullable NormalizedNode readData(final @NonNull ContentParam content,
828 final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
829 return switch (content) {
831 // PREPARE STATE DATA NODE
832 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
833 // PREPARE CONFIG DATA NODE
834 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
836 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
837 : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
840 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
841 yield defaultsMode == null ? read
842 : prepareDataByParamWithDef(read, path, defaultsMode.mode());
844 case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
848 private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
849 final YangInstanceIdentifier path) {
850 return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
853 final NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
854 final WithDefaultsMode defaultsMode) {
855 final boolean trim = switch (defaultsMode) {
857 case Explicit -> false;
858 case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
859 "Unsupported with-defaults value " + defaultsMode.getName());
862 // FIXME: we have this readily available in InstanceIdentifierContext
863 final var ctxNode = databind.schemaTree().findChild(path).orElseThrow();
864 if (readData instanceof ContainerNode container) {
865 final var builder = Builders.containerBuilder().withNodeIdentifier(container.name());
866 buildCont(builder, container.body(), ctxNode, trim);
867 return builder.build();
868 } else if (readData instanceof MapEntryNode mapEntry) {
869 if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
870 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
873 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(mapEntry.name());
874 buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
875 return builder.build();
877 throw new IllegalStateException("Unhandled data contract " + readData.contract());
881 private static void buildMapEntryBuilder(
882 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
883 final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
884 final boolean trim, final List<QName> keys) {
885 for (var child : children) {
886 final var childCtx = getChildContext(ctxNode, child);
888 if (child instanceof ContainerNode container) {
889 appendContainer(builder, container, childCtx, trim);
890 } else if (child instanceof MapNode map) {
891 appendMap(builder, map, childCtx, trim);
892 } else if (child instanceof LeafNode<?> leaf) {
893 appendLeaf(builder, leaf, childCtx, trim, keys);
895 // FIXME: we should never hit this, throw an ISE if this ever happens
896 LOG.debug("Ignoring unhandled child contract {}", child.contract());
901 private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
902 final DataSchemaContext ctxNode, final boolean trim) {
903 final var childBuilder = Builders.containerBuilder().withNodeIdentifier(container.name());
904 buildCont(childBuilder, container.body(), ctxNode, trim);
905 builder.withChild(childBuilder.build());
908 private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
909 final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
910 if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
911 throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
914 // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
915 final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
917 // This is a combined check for when we need to emit the leaf.
919 // We always have to emit key leaf values
920 keys.contains(leafSchema.getQName())
921 // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
923 // When data is retrieved with a <with-defaults> parameter equal to
924 // 'trim', data nodes MUST NOT be reported if they contain the schema
925 // default value. Non-configuration data nodes containing the schema
926 // default value MUST NOT be reported.
928 || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
929 // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
930 // grasp what we are doing here... emit only if it matches default ???!!!
931 // FIXME: The WithDefaultsParam.EXPLICIT says:
933 // Data nodes set to the YANG default by the client are reported.
935 // and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
937 // If the "with-defaults" parameter is set to "explicit", then the
938 // server MUST adhere to the default-reporting behavior defined in
939 // Section 3.3 of [RFC6243].
941 // and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
943 // When data is retrieved with a <with-defaults> parameter equal to
944 // 'explicit', a data node that was set by a client to its schema
945 // default value MUST be reported. A conceptual data node that would be
946 // set by the server to the schema default value MUST NOT be reported.
947 // Non-configuration data nodes containing the schema default value MUST
950 // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
951 // This seems to disregard the 'trim = true' case semantics (see above).
952 // Combining the above, though, these checks are missing the 'non-config' check, which would
953 // distinguish, but barring that this check is superfluous and results in the wrong semantics.
954 // Without that input, this really should be covered by the previous case.
955 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
956 builder.withChild(leaf);
960 private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
961 final DataSchemaContext childCtx, final boolean trim) {
962 if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
963 throw new IllegalStateException("Input " + map + " does not match " + childCtx);
966 final var childBuilder = switch (map.ordering()) {
967 case SYSTEM -> Builders.mapBuilder();
968 case USER -> Builders.orderedMapBuilder();
970 buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
971 listSchema.getKeyDefinition());
972 builder.withChild(childBuilder.build());
975 private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
976 final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
977 final List<@NonNull QName> keys) {
978 for (var entry : entries) {
979 final var childCtx = getChildContext(ctxNode, entry);
980 final var mapEntryBuilder = Builders.mapEntryBuilder().withNodeIdentifier(entry.name());
981 buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
982 builder.withChild(mapEntryBuilder.build());
986 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
987 final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
988 for (var child : children) {
989 final var childCtx = getChildContext(ctxNode, child);
990 if (child instanceof ContainerNode container) {
991 appendContainer(builder, container, childCtx, trim);
992 } else if (child instanceof MapNode map) {
993 appendMap(builder, map, childCtx, trim);
994 } else if (child instanceof LeafNode<?> leaf) {
995 appendLeaf(builder, leaf, childCtx, trim, List.of());
1000 private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
1001 final NormalizedNode child) {
1002 final var childId = child.name();
1003 final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
1005 if (childCtx == null) {
1006 throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
1011 static final NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
1012 final NormalizedNode configDataNode) {
1013 // if no data exists
1014 if (stateDataNode == null && configDataNode == null) {
1018 // return config data
1019 if (stateDataNode == null) {
1020 return configDataNode;
1023 // return state data
1024 if (configDataNode == null) {
1025 return stateDataNode;
1028 // merge data from config and state
1029 return mergeStateAndConfigData(stateDataNode, configDataNode);
1033 * Merge state and config data into a single NormalizedNode.
1035 * @param stateDataNode data node of state data
1036 * @param configDataNode data node of config data
1037 * @return {@link NormalizedNode}
1039 private static @NonNull NormalizedNode mergeStateAndConfigData(
1040 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
1041 validateNodeMerge(stateDataNode, configDataNode);
1042 // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
1043 if (configDataNode instanceof RpcDefinition) {
1044 return prepareRpcData(configDataNode, stateDataNode);
1046 return prepareData(configDataNode, stateDataNode);
1051 * Validates whether the two NormalizedNodes can be merged.
1053 * @param stateDataNode data node of state data
1054 * @param configDataNode data node of config data
1056 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
1057 final @NonNull NormalizedNode configDataNode) {
1058 final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
1059 final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
1060 if (!moduleOfStateData.equals(moduleOfConfigData)) {
1061 throw new RestconfDocumentedException("Unable to merge data from different modules.");
1066 * Prepare and map data for rpc.
1068 * @param configDataNode data node of config data
1069 * @param stateDataNode data node of state data
1070 * @return {@link NormalizedNode}
1072 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
1073 final @NonNull NormalizedNode stateDataNode) {
1074 final var mapEntryBuilder = Builders.mapEntryBuilder()
1075 .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
1078 mapRpcDataNode(configDataNode, mapEntryBuilder);
1080 mapRpcDataNode(stateDataNode, mapEntryBuilder);
1082 return Builders.mapBuilder()
1083 .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
1084 .addChild(mapEntryBuilder.build())
1089 * Map node to map entry builder.
1091 * @param dataNode data node
1092 * @param mapEntryBuilder builder for mapping data
1094 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
1095 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
1096 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
1100 * Prepare and map all data from DS.
1102 * @param configDataNode data node of config data
1103 * @param stateDataNode data node of state data
1104 * @return {@link NormalizedNode}
1106 @SuppressWarnings("unchecked")
1107 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
1108 final @NonNull NormalizedNode stateDataNode) {
1109 if (configDataNode instanceof UserMapNode configMap) {
1110 final var builder = Builders.orderedMapBuilder().withNodeIdentifier(configMap.name());
1111 mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
1112 return builder.build();
1113 } else if (configDataNode instanceof SystemMapNode configMap) {
1114 final var builder = Builders.mapBuilder().withNodeIdentifier(configMap.name());
1115 mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
1116 return builder.build();
1117 } else if (configDataNode instanceof MapEntryNode configEntry) {
1118 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(configEntry.name());
1119 mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
1120 return builder.build();
1121 } else if (configDataNode instanceof ContainerNode configContaienr) {
1122 final var builder = Builders.containerBuilder().withNodeIdentifier(configContaienr.name());
1123 mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
1124 return builder.build();
1125 } else if (configDataNode instanceof ChoiceNode configChoice) {
1126 final var builder = Builders.choiceBuilder().withNodeIdentifier(configChoice.name());
1127 mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
1128 return builder.build();
1129 } else if (configDataNode instanceof LeafNode configLeaf) {
1130 // config trumps oper
1132 } else if (configDataNode instanceof UserLeafSetNode) {
1133 final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
1134 final var builder = Builders.<Object>orderedLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
1135 mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
1136 return builder.build();
1137 } else if (configDataNode instanceof SystemLeafSetNode) {
1138 final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
1139 final var builder = Builders.<Object>leafSetBuilder().withNodeIdentifier(configLeafSet.name());
1140 mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
1141 return builder.build();
1142 } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
1143 // config trumps oper
1145 } else if (configDataNode instanceof UnkeyedListNode configList) {
1146 final var builder = Builders.unkeyedListBuilder().withNodeIdentifier(configList.name());
1147 mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
1148 return builder.build();
1149 } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
1150 final var builder = Builders.unkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
1151 mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
1152 return builder.build();
1154 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
1159 * Map value from container node to builder.
1161 * @param configData collection of config data nodes
1162 * @param stateData collection of state data nodes
1163 * @param builder builder
1165 private static <T extends NormalizedNode> void mapValueToBuilder(
1166 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
1167 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1168 final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1169 final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1171 // merge config and state data of children with different identifiers
1172 mapDataToBuilder(configMap, stateMap, builder);
1174 // merge config and state data of children with the same identifiers
1175 mergeDataToBuilder(configMap, stateMap, builder);
1179 * Map data with different identifiers to builder. Data with different identifiers can be just added
1180 * as childs to parent node.
1182 * @param configMap map of config data nodes
1183 * @param stateMap map of state data nodes
1184 * @param builder - builder
1186 private static <T extends NormalizedNode> void mapDataToBuilder(
1187 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1188 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1189 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
1190 y -> builder.addChild(y.getValue()));
1191 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
1192 y -> builder.addChild(y.getValue()));
1196 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
1197 * go one level down with {@code prepareData} method.
1199 * @param configMap immutable config data
1200 * @param stateMap immutable state data
1201 * @param builder - builder
1203 @SuppressWarnings("unchecked")
1204 private static <T extends NormalizedNode> void mergeDataToBuilder(
1205 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1206 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1207 // it is enough to process only config data because operational contains the same data
1208 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1209 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1212 public @NonNull RestconfFuture<OperationsGetResult> operationsGET() {
1213 final var modelContext = modelContext();
1214 final var modules = modelContext.getModuleStatements();
1215 if (modules.isEmpty()) {
1216 // No modules, or defensive return empty content
1217 return RestconfFuture.of(new OperationsGetResult.Container(modelContext, ImmutableSetMultimap.of()));
1220 // RPC QNames by their XMLNamespace/Revision. This should be a Table, but Revision can be null, which wrecks us.
1221 final var table = new HashMap<XMLNamespace, Map<Revision, ImmutableSet<QName>>>();
1222 for (var entry : modules.entrySet()) {
1223 final var module = entry.getValue();
1224 final var rpcNames = module.streamEffectiveSubstatements(RpcEffectiveStatement.class)
1225 .map(RpcEffectiveStatement::argument)
1226 .collect(ImmutableSet.toImmutableSet());
1227 if (!rpcNames.isEmpty()) {
1228 final var namespace = entry.getKey();
1229 table.computeIfAbsent(namespace.getNamespace(), ignored -> new HashMap<>())
1230 .put(namespace.getRevision().orElse(null), rpcNames);
1234 // Now pick the latest revision for each namespace
1235 final var rpcs = ImmutableSetMultimap.<QNameModule, QName>builder();
1236 for (var entry : table.entrySet()) {
1237 entry.getValue().entrySet().stream()
1238 .sorted(Comparator.comparing(Entry::getKey, (first, second) -> Revision.compare(second, first)))
1240 .ifPresent(row -> rpcs.putAll(QNameModule.create(entry.getKey(), row.getKey()), row.getValue()));
1242 return RestconfFuture.of(new OperationsGetResult.Container(modelContext, rpcs.build()));
1245 public @NonNull RestconfFuture<OperationsGetResult> operationsGET(final ApiPath apiPath) {
1246 if (apiPath.steps().isEmpty()) {
1247 return operationsGET();
1252 rpc = pathNormalizer.normalizeRpcPath(apiPath);
1253 } catch (RestconfDocumentedException e) {
1254 return RestconfFuture.failed(e);
1257 return RestconfFuture.of(
1258 new OperationsGetResult.Leaf(rpc.inference().getEffectiveModelContext(), rpc.rpc().argument()));
1261 public @NonNull RestconfFuture<OperationsPostResult> operationsPOST(final URI restconfURI, final ApiPath apiPath,
1262 final OperationInputBody body) {
1263 final OperationPath.Rpc path;
1265 path = pathNormalizer.normalizeRpcPath(apiPath);
1266 } catch (RestconfDocumentedException e) {
1267 return RestconfFuture.failed(e);
1270 final var postPath = new OperationsPostPath(databind, path.inference());
1271 final ContainerNode data;
1273 data = body.toContainerNode(postPath);
1274 } catch (IOException e) {
1275 LOG.debug("Error reading input", e);
1276 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1277 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1280 final var type = path.rpc().argument();
1281 final var local = localRpcs.get(type);
1282 if (local != null) {
1283 return local.invoke(restconfURI, new OperationInput(databind, postPath.operation(), data));
1285 if (rpcService == null) {
1286 LOG.debug("RPC invocation is not available");
1287 return RestconfFuture.failed(new RestconfDocumentedException("RPC invocation is not available",
1288 ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED));
1291 final var ret = new SettableRestconfFuture<OperationsPostResult>();
1292 Futures.addCallback(rpcService.invokeRpc(type, data), new FutureCallback<DOMRpcResult>() {
1294 public void onSuccess(final DOMRpcResult response) {
1295 final var errors = response.errors();
1296 if (errors.isEmpty()) {
1297 ret.set(new OperationsPostResult(databind, postPath.operation(), response.value()));
1299 LOG.debug("RPC invocation reported {}", response.errors());
1300 ret.setFailure(new RestconfDocumentedException("RPC implementation reported errors", null,
1301 response.errors()));
1306 public void onFailure(final Throwable cause) {
1307 LOG.debug("RPC invocation failed, cause");
1308 if (cause instanceof RestconfDocumentedException ex) {
1311 // TODO: YangNetconfErrorAware if we ever get into a broader invocation scope
1312 ret.setFailure(new RestconfDocumentedException(cause,
1313 new RestconfError(ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage())));
1316 }, MoreExecutors.directExecutor());
1320 public @NonNull RestconfFuture<CharSource> resolveSource(final SourceIdentifier source,
1321 final Class<? extends SchemaSourceRepresentation> representation) {
1322 final var src = requireNonNull(source);
1323 if (YangTextSchemaSource.class.isAssignableFrom(representation)) {
1324 if (sourceProvider != null) {
1325 final var ret = new SettableRestconfFuture<CharSource>();
1326 Futures.addCallback(sourceProvider.getSource(src), new FutureCallback<YangTextSchemaSource>() {
1328 public void onSuccess(final YangTextSchemaSource result) {
1333 public void onFailure(final Throwable cause) {
1334 ret.setFailure(cause instanceof RestconfDocumentedException e ? e
1335 : new RestconfDocumentedException(cause.getMessage(), ErrorType.RPC,
1336 ErrorTag.OPERATION_FAILED, cause));
1338 }, MoreExecutors.directExecutor());
1341 return exportSource(modelContext(), src, YangCharSource::new, YangCharSource::new);
1343 if (YinTextSchemaSource.class.isAssignableFrom(representation)) {
1344 return exportSource(modelContext(), src, YinCharSource.OfModule::new, YinCharSource.OfSubmodule::new);
1346 return RestconfFuture.failed(new RestconfDocumentedException(
1347 "Unsupported source representation " + representation.getName()));
1350 private static @NonNull RestconfFuture<CharSource> exportSource(final EffectiveModelContext modelContext,
1351 final SourceIdentifier source, final Function<ModuleEffectiveStatement, CharSource> moduleCtor,
1352 final BiFunction<ModuleEffectiveStatement, SubmoduleEffectiveStatement, CharSource> submoduleCtor) {
1353 // If the source identifies a module, things are easy
1354 final var name = source.name().getLocalName();
1355 final var optRevision = Optional.ofNullable(source.revision());
1356 final var optModule = modelContext.findModule(name, optRevision);
1357 if (optModule.isPresent()) {
1358 return RestconfFuture.of(moduleCtor.apply(optModule.orElseThrow().asEffectiveStatement()));
1361 // The source could be a submodule, which we need to hunt down
1362 for (var module : modelContext.getModules()) {
1363 for (var submodule : module.getSubmodules()) {
1364 if (name.equals(submodule.getName()) && optRevision.equals(submodule.getRevision())) {
1365 return RestconfFuture.of(submoduleCtor.apply(module.asEffectiveStatement(),
1366 submodule.asEffectiveStatement()));
1371 final var sb = new StringBuilder().append("Source ").append(source.name().getLocalName());
1372 optRevision.ifPresent(rev -> sb.append('@').append(rev));
1373 sb.append(" not found");
1374 return RestconfFuture.failed(new RestconfDocumentedException(sb.toString(),
1375 ErrorType.APPLICATION, ErrorTag.DATA_MISSING));
1378 public final @NonNull RestconfFuture<? extends DataPostResult> dataPOST(final ApiPath apiPath,
1379 final DataPostBody body, final Map<String, String> queryParameters) {
1380 if (apiPath.steps().isEmpty()) {
1381 return dataCreatePOST(body.toResource(), queryParameters);
1383 final InstanceReference path;
1385 path = pathNormalizer.normalizeDataOrActionPath(apiPath);
1386 } catch (RestconfDocumentedException e) {
1387 return RestconfFuture.failed(e);
1389 if (path instanceof DataPath dataPath) {
1390 try (var resourceBody = body.toResource()) {
1391 return dataCreatePOST(new DataPostPath(databind, dataPath.inference(), dataPath.instance()),
1392 resourceBody, queryParameters);
1395 if (path instanceof OperationPath.Action actionPath) {
1396 try (var inputBody = body.toOperationInput()) {
1397 return dataInvokePOST(actionPath, inputBody);
1400 // Note: this should never happen
1401 // FIXME: we should be able to eliminate this path with Java 21+ pattern matching
1402 return RestconfFuture.failed(new RestconfDocumentedException("Unhandled path " + path));
1405 public @NonNull RestconfFuture<CreateResource> dataCreatePOST(final ChildBody body,
1406 final Map<String, String> queryParameters) {
1407 return dataCreatePOST(new DataPostPath(databind,
1408 SchemaInferenceStack.of(databind.modelContext()).toInference(), YangInstanceIdentifier.of()), body,
1412 private @NonNull RestconfFuture<CreateResource> dataCreatePOST(final DataPostPath path, final ChildBody body,
1413 final Map<String, String> queryParameters) {
1414 final Insert insert;
1416 insert = Insert.ofQueryParameters(path.databind(), queryParameters);
1417 } catch (IllegalArgumentException e) {
1418 return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
1419 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
1422 final var payload = body.toPayload(path);
1423 return postData(concat(path.instance(), payload.prefix()), payload.body(), insert);
1426 private static YangInstanceIdentifier concat(final YangInstanceIdentifier parent, final List<PathArgument> args) {
1428 for (var arg : args) {
1429 ret = ret.node(arg);
1434 private @NonNull RestconfFuture<InvokeOperation> dataInvokePOST(final OperationPath.Action path,
1435 final OperationInputBody body) {
1436 final var inference = path.inference();
1437 final ContainerNode input;
1439 input = body.toContainerNode(new OperationsPostPath(databind, inference));
1440 } catch (IOException e) {
1441 LOG.debug("Error reading input", e);
1442 return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1443 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1446 if (actionService == null) {
1447 return RestconfFuture.failed(new RestconfDocumentedException("DOMActionService is missing."));
1450 final var future = dataInvokePOST(actionService, path, input);
1451 return future.transform(result -> result.getOutput()
1452 .flatMap(output -> output.isEmpty() ? Optional.empty()
1453 : Optional.of(new InvokeOperation(new NormalizedNodePayload(inference, output))))
1454 .orElse(InvokeOperation.EMPTY));
1458 * Invoke Action via ActionServiceHandler.
1460 * @param input input data
1461 * @param yangIId invocation context
1462 * @param schemaPath schema path of data
1463 * @param actionService action service to invoke action
1464 * @return {@link DOMActionResult}
1466 private static RestconfFuture<DOMActionResult> dataInvokePOST(final DOMActionService actionService,
1467 final OperationPath.Action path, final @NonNull ContainerNode input) {
1468 final var ret = new SettableRestconfFuture<DOMActionResult>();
1470 Futures.addCallback(actionService.invokeAction(
1471 path.inference().toSchemaInferenceStack().toSchemaNodeIdentifier(),
1472 new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, path.instance()), input),
1473 new FutureCallback<DOMActionResult>() {
1475 public void onSuccess(final DOMActionResult result) {
1476 final var errors = result.getErrors();
1477 LOG.debug("InvokeAction Error Message {}", errors);
1478 if (errors.isEmpty()) {
1481 ret.setFailure(new RestconfDocumentedException("InvokeAction Error Message ", null, errors));
1486 public void onFailure(final Throwable cause) {
1487 if (cause instanceof DOMActionException) {
1488 ret.set(new SimpleDOMActionResult(List.of(RpcResultBuilder.newError(
1489 ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage()))));
1490 } else if (cause instanceof RestconfDocumentedException e) {
1492 } else if (cause instanceof CancellationException) {
1493 ret.setFailure(new RestconfDocumentedException("Action cancelled while executing",
1494 ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, cause));
1496 ret.setFailure(new RestconfDocumentedException("Invocation failed", cause));
1499 }, MoreExecutors.directExecutor());