Eliminate (ReadData)TransactionUtil
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / transactions / RestconfStrategy.java
1 /*
2  * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.restconf.nb.rfc8040.rests.transactions;
9
10 import static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import com.google.common.util.concurrent.MoreExecutors;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.NoSuchElementException;
22 import java.util.Optional;
23 import java.util.function.Function;
24 import java.util.stream.Collectors;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.opendaylight.mdsal.common.api.CommitInfo;
28 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
29 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
30 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
31 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
32 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
33 import org.opendaylight.restconf.api.query.ContentParam;
34 import org.opendaylight.restconf.api.query.PointParam;
35 import org.opendaylight.restconf.api.query.WithDefaultsParam;
36 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
37 import org.opendaylight.restconf.common.errors.RestconfError;
38 import org.opendaylight.restconf.common.errors.RestconfFuture;
39 import org.opendaylight.restconf.common.errors.SettableRestconfFuture;
40 import org.opendaylight.restconf.common.patch.PatchContext;
41 import org.opendaylight.restconf.common.patch.PatchStatusContext;
42 import org.opendaylight.restconf.common.patch.PatchStatusEntity;
43 import org.opendaylight.restconf.nb.rfc8040.Insert;
44 import org.opendaylight.restconf.nb.rfc8040.utils.parser.YangInstanceIdentifierDeserializer;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.with.defaults.rev110601.WithDefaultsMode;
46 import org.opendaylight.yangtools.yang.common.Empty;
47 import org.opendaylight.yangtools.yang.common.ErrorTag;
48 import org.opendaylight.yangtools.yang.common.ErrorType;
49 import org.opendaylight.yangtools.yang.common.QName;
50 import org.opendaylight.yangtools.yang.common.QNameModule;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
55 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
58 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
64 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
71 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
72 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
73 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
74 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
75 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
76 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
77 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
79 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
80 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
85
86 /**
87  * Baseline execution strategy for various RESTCONF operations.
88  *
89  * @see NetconfRestconfStrategy
90  * @see MdsalRestconfStrategy
91  */
92 // FIXME: it seems the first three operations deal with lifecycle of a transaction, while others invoke various
93 //        operations. This should be handled through proper allocation indirection.
94 public abstract class RestconfStrategy {
95     /**
96      * Result of a {@code PUT} request as defined in
97      * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.5">RFC8040 section 4.5</a>. The definition makes it
98      * clear that the logical operation is {@code create-or-replace}.
99      */
100     public enum CreateOrReplaceResult {
101         /**
102          * A new resource has been created.
103          */
104         CREATED,
105         /*
106          * An existing resources has been replaced.
107          */
108         REPLACED;
109     }
110
111     private static final Logger LOG = LoggerFactory.getLogger(RestconfStrategy.class);
112
113     RestconfStrategy() {
114         // Hidden on purpose
115     }
116
117     /**
118      * Look up the appropriate strategy for a particular mount point.
119      *
120      * @param mountPoint Target mount point
121      * @return A strategy, or null if the mount point does not expose a supported interface
122      * @throws NullPointerException if {@code mountPoint} is null
123      */
124     public static Optional<RestconfStrategy> forMountPoint(final DOMMountPoint mountPoint) {
125         final Optional<RestconfStrategy> netconf = mountPoint.getService(NetconfDataTreeService.class)
126             .map(NetconfRestconfStrategy::new);
127         if (netconf.isPresent()) {
128             return netconf;
129         }
130
131         return mountPoint.getService(DOMDataBroker.class).map(MdsalRestconfStrategy::new);
132     }
133
134     /**
135      * Lock the entire datastore.
136      *
137      * @return A {@link RestconfTransaction}. This transaction needs to be either committed or canceled before doing
138      *         anything else.
139      */
140     public abstract RestconfTransaction prepareWriteExecution();
141
142     /**
143      * Read data from the datastore.
144      *
145      * @param store the logical data store which should be modified
146      * @param path the data object path
147      * @return a ListenableFuture containing the result of the read
148      */
149     public abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store,
150         YangInstanceIdentifier path);
151
152     /**
153      * Read data selected using fields from the datastore.
154      *
155      * @param store the logical data store which should be modified
156      * @param path the parent data object path
157      * @param fields paths to selected fields relative to parent path
158      * @return a ListenableFuture containing the result of the read
159      */
160     public abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store,
161             YangInstanceIdentifier path, List<YangInstanceIdentifier> fields);
162
163     /**
164      * Check if data already exists in the configuration datastore.
165      *
166      * @param path the data object path
167      * @return a ListenableFuture containing the result of the check
168      */
169     // FIXME: this method should be hosted in RestconfTransaction
170     // FIXME: this method should only be needed in MdsalRestconfStrategy
171     abstract ListenableFuture<Boolean> exists(YangInstanceIdentifier path);
172
173     /**
174      * Delete data from the configuration datastore. If the data does not exist, this operation will fail, as outlined
175      * in <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.7">RFC8040 section 4.7</a>
176      *
177      * @param path Path to delete
178      * @return A {@link RestconfFuture}
179      * @throws NullPointerException if {@code path} is {@code null}
180      */
181     public final @NonNull RestconfFuture<Empty> delete(final YangInstanceIdentifier path) {
182         final var ret = new SettableRestconfFuture<Empty>();
183         delete(ret, requireNonNull(path));
184         return ret;
185     }
186
187     protected abstract void delete(@NonNull SettableRestconfFuture<Empty> future, @NonNull YangInstanceIdentifier path);
188
189     /**
190      * Merge data into the configuration datastore, as outlined in
191      * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040 section 4.6.1</a>.
192      *
193      * @param path Path to merge
194      * @param data Data to merge
195      * @param context Corresponding EffectiveModelContext
196      * @return A {@link RestconfFuture}
197      * @throws NullPointerException if any argument is {@code null}
198      */
199     public final @NonNull RestconfFuture<Empty> merge(final YangInstanceIdentifier path, final NormalizedNode data,
200             final EffectiveModelContext context) {
201         final var ret = new SettableRestconfFuture<Empty>();
202         merge(ret, requireNonNull(path), requireNonNull(data), requireNonNull(context));
203         return ret;
204     }
205
206     private void merge(final @NonNull SettableRestconfFuture<Empty> future,
207             final @NonNull YangInstanceIdentifier path, final @NonNull NormalizedNode data,
208             final @NonNull EffectiveModelContext context) {
209         final var tx = prepareWriteExecution();
210         // FIXME: this method should be further specialized to eliminate this call -- it is only needed for MD-SAL
211         tx.ensureParentsByMerge(path, context);
212         tx.merge(path, data);
213         Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
214             @Override
215             public void onSuccess(final CommitInfo result) {
216                 future.set(Empty.value());
217             }
218
219             @Override
220             public void onFailure(final Throwable cause) {
221                 future.setFailure(TransactionUtil.decodeException(cause, "MERGE", path));
222             }
223         }, MoreExecutors.directExecutor());
224     }
225
226     /**
227      * Check mount point and prepare variables for put data to DS.
228      *
229      * @param path    path of data
230      * @param data    data
231      * @param context reference to {@link EffectiveModelContext}
232      * @param insert  {@link Insert}
233      * @return A {@link CreateOrReplaceResult}
234      */
235     public @NonNull CreateOrReplaceResult putData(final YangInstanceIdentifier path, final NormalizedNode data,
236             final EffectiveModelContext context, final @Nullable Insert insert) {
237         final var exists = TransactionUtil.syncAccess(exists(path), path);
238
239         final ListenableFuture<? extends CommitInfo> commitFuture;
240         if (insert != null) {
241             final var parentPath = path.coerceParent();
242             checkListAndOrderedType(context, parentPath);
243             commitFuture = insertAndCommitPut(path, data, insert, parentPath, context);
244         } else {
245             commitFuture = replaceAndCommit(prepareWriteExecution(), path, data, context);
246         }
247
248         TransactionUtil.syncCommit(commitFuture, "PUT", path);
249         return exists ? CreateOrReplaceResult.REPLACED : CreateOrReplaceResult.CREATED;
250     }
251
252     private ListenableFuture<? extends CommitInfo> insertAndCommitPut(final YangInstanceIdentifier path,
253             final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parentPath,
254             final EffectiveModelContext context) {
255         final var tx = prepareWriteExecution();
256
257         return switch (insert.insert()) {
258             case FIRST -> {
259                 final var readData = tx.readList(parentPath);
260                 if (readData == null || readData.isEmpty()) {
261                     yield replaceAndCommit(tx, path, data, context);
262                 }
263                 tx.remove(parentPath);
264                 tx.replace(path, data, context);
265                 tx.replace(parentPath, readData, context);
266                 yield tx.commit();
267             }
268             case LAST -> replaceAndCommit(tx, path, data, context);
269             case BEFORE -> {
270                 final var readData = tx.readList(parentPath);
271                 if (readData == null || readData.isEmpty()) {
272                     yield replaceAndCommit(tx, path, data, context);
273                 }
274                 insertWithPointPut(tx, path, data, verifyNotNull(insert.point()), readData, true, context);
275                 yield tx.commit();
276             }
277             case AFTER -> {
278                 final var readData = tx.readList(parentPath);
279                 if (readData == null || readData.isEmpty()) {
280                     yield replaceAndCommit(tx, path, data, context);
281                 }
282                 insertWithPointPut(tx, path, data, verifyNotNull(insert.point()), readData, false, context);
283                 yield tx.commit();
284             }
285         };
286     }
287
288     private static void insertWithPointPut(final RestconfTransaction tx, final YangInstanceIdentifier path,
289             final NormalizedNode data, final @NonNull PointParam point, final NormalizedNodeContainer<?> readList,
290             final boolean before, final EffectiveModelContext context) {
291         tx.remove(path.getParent());
292         final var pointArg = YangInstanceIdentifierDeserializer.create(context, point.value()).path
293             .getLastPathArgument();
294         int lastItemPosition = 0;
295         for (var nodeChild : readList.body()) {
296             if (nodeChild.name().equals(pointArg)) {
297                 break;
298             }
299             lastItemPosition++;
300         }
301         if (!before) {
302             lastItemPosition++;
303         }
304         int lastInsertedPosition = 0;
305         final var emptySubtree = ImmutableNodes.fromInstanceId(context, path.getParent());
306         tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
307         for (var nodeChild : readList.body()) {
308             if (lastInsertedPosition == lastItemPosition) {
309                 tx.replace(path, data, context);
310             }
311             final var childPath = path.coerceParent().node(nodeChild.name());
312             tx.replace(childPath, nodeChild, context);
313             lastInsertedPosition++;
314         }
315     }
316
317     private static ListenableFuture<? extends CommitInfo> replaceAndCommit(final RestconfTransaction tx,
318             final YangInstanceIdentifier path, final NormalizedNode data, final EffectiveModelContext context) {
319         tx.replace(path, data, context);
320         return tx.commit();
321     }
322
323     private static DataSchemaNode checkListAndOrderedType(final EffectiveModelContext ctx,
324             final YangInstanceIdentifier path) {
325         final var dataSchemaNode = DataSchemaContextTree.from(ctx).findChild(path).orElseThrow().dataSchemaNode();
326
327         final String message;
328         if (dataSchemaNode instanceof ListSchemaNode listSchema) {
329             if (listSchema.isUserOrdered()) {
330                 return listSchema;
331             }
332             message = "Insert parameter can be used only with ordered-by user list.";
333         } else if (dataSchemaNode instanceof LeafListSchemaNode leafListSchema) {
334             if (leafListSchema.isUserOrdered()) {
335                 return leafListSchema;
336             }
337             message = "Insert parameter can be used only with ordered-by user leaf-list.";
338         } else {
339             message = "Insert parameter can be used only with list or leaf-list";
340         }
341         throw new RestconfDocumentedException(message, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
342     }
343
344     /**
345      * Check mount point and prepare variables for post data.
346      *
347      * @param path    path
348      * @param data    data
349      * @param context reference to actual {@link EffectiveModelContext}
350      * @param insert  {@link Insert}
351      */
352     public final void postData(final YangInstanceIdentifier path, final NormalizedNode data,
353             final EffectiveModelContext context, final @Nullable Insert insert) {
354         final ListenableFuture<? extends CommitInfo> future;
355         if (insert != null) {
356             final var parentPath = path.coerceParent();
357             checkListAndOrderedType(context, parentPath);
358             future = insertAndCommitPost(path, data, insert, parentPath, context);
359         } else {
360             future = createAndCommit(prepareWriteExecution(), path, data, context);
361         }
362         TransactionUtil.syncCommit(future, "POST", path);
363     }
364
365     private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
366             final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parent,
367             final EffectiveModelContext context) {
368         final var grandParent = parent.coerceParent();
369         final var tx = prepareWriteExecution();
370
371         return switch (insert.insert()) {
372             case FIRST -> {
373                 final var readData = tx.readList(grandParent);
374                 if (readData == null || readData.isEmpty()) {
375                     tx.replace(path, data, context);
376                 } else {
377                     checkItemDoesNotExists(exists(path), path);
378                     tx.remove(grandParent);
379                     tx.replace(path, data, context);
380                     tx.replace(grandParent, readData, context);
381                 }
382                 yield tx.commit();
383             }
384             case LAST -> createAndCommit(tx, path, data, context);
385             case BEFORE -> {
386                 final var readData = tx.readList(grandParent);
387                 if (readData == null || readData.isEmpty()) {
388                     tx.replace(path, data, context);
389                 } else {
390                     checkItemDoesNotExists(exists(path), path);
391                     insertWithPointPost(tx, path, data, verifyNotNull(insert.point()), readData, grandParent, true,
392                         context);
393                 }
394                 yield tx.commit();
395             }
396             case AFTER -> {
397                 final var readData = tx.readList(grandParent);
398                 if (readData == null || readData.isEmpty()) {
399                     tx.replace(path, data, context);
400                 } else {
401                     checkItemDoesNotExists(exists(path), path);
402                     insertWithPointPost(tx, path, data, verifyNotNull(insert.point()), readData, grandParent, false,
403                         context);
404                 }
405                 yield tx.commit();
406             }
407         };
408     }
409
410     /**
411      * Process edit operations of one {@link PatchContext}.
412      *
413      * @param patch    Patch context to be processed
414      * @param context  Global schema context
415      * @return {@link PatchStatusContext}
416      */
417     public final @NonNull PatchStatusContext patchData(final PatchContext patch, final EffectiveModelContext context) {
418         final var editCollection = new ArrayList<PatchStatusEntity>();
419         final var tx = prepareWriteExecution();
420
421         boolean noError = true;
422         for (var patchEntity : patch.getData()) {
423             if (noError) {
424                 final var targetNode = patchEntity.getTargetNode();
425                 final var editId = patchEntity.getEditId();
426
427                 switch (patchEntity.getOperation()) {
428                     case Create:
429                         try {
430                             tx.create(targetNode, patchEntity.getNode(), context);
431                             editCollection.add(new PatchStatusEntity(editId, true, null));
432                         } catch (RestconfDocumentedException e) {
433                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
434                             noError = false;
435                         }
436                         break;
437                     case Delete:
438                         try {
439                             tx.delete(targetNode);
440                             editCollection.add(new PatchStatusEntity(editId, true, null));
441                         } catch (RestconfDocumentedException e) {
442                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
443                             noError = false;
444                         }
445                         break;
446                     case Merge:
447                         try {
448                             tx.ensureParentsByMerge(targetNode, context);
449                             tx.merge(targetNode, patchEntity.getNode());
450                             editCollection.add(new PatchStatusEntity(editId, true, null));
451                         } catch (RestconfDocumentedException e) {
452                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
453                             noError = false;
454                         }
455                         break;
456                     case Replace:
457                         try {
458                             tx.replace(targetNode, patchEntity.getNode(), context);
459                             editCollection.add(new PatchStatusEntity(editId, true, null));
460                         } catch (RestconfDocumentedException e) {
461                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
462                             noError = false;
463                         }
464                         break;
465                     case Remove:
466                         try {
467                             tx.remove(targetNode);
468                             editCollection.add(new PatchStatusEntity(editId, true, null));
469                         } catch (RestconfDocumentedException e) {
470                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
471                             noError = false;
472                         }
473                         break;
474                     default:
475                         editCollection.add(new PatchStatusEntity(editId, false, List.of(
476                             new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
477                                 "Not supported Yang Patch operation"))));
478                         noError = false;
479                         break;
480                 }
481             } else {
482                 break;
483             }
484         }
485
486         // if no errors then submit transaction, otherwise cancel
487         if (noError) {
488             try {
489                 TransactionUtil.syncCommit(tx.commit(), "PATCH", null);
490             } catch (RestconfDocumentedException e) {
491                 // if errors occurred during transaction commit then patch failed and global errors are reported
492                 return new PatchStatusContext(patch.getPatchId(), List.copyOf(editCollection), false, e.getErrors());
493             }
494
495             return new PatchStatusContext(patch.getPatchId(), List.copyOf(editCollection), true, null);
496         } else {
497             tx.cancel();
498             return new PatchStatusContext(patch.getPatchId(), List.copyOf(editCollection), false, null);
499         }
500     }
501
502     private static void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
503             final NormalizedNode data, final PointParam point, final NormalizedNodeContainer<?> readList,
504             final YangInstanceIdentifier grandParentPath, final boolean before, final EffectiveModelContext context) {
505         tx.remove(grandParentPath);
506         final var pointArg = YangInstanceIdentifierDeserializer.create(context, point.value()).path
507             .getLastPathArgument();
508         int lastItemPosition = 0;
509         for (var nodeChild : readList.body()) {
510             if (nodeChild.name().equals(pointArg)) {
511                 break;
512             }
513             lastItemPosition++;
514         }
515         if (!before) {
516             lastItemPosition++;
517         }
518         int lastInsertedPosition = 0;
519         final var emptySubtree = ImmutableNodes.fromInstanceId(context, grandParentPath);
520         tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
521         for (var nodeChild : readList.body()) {
522             if (lastInsertedPosition == lastItemPosition) {
523                 tx.replace(path, data, context);
524             }
525             final YangInstanceIdentifier childPath = grandParentPath.node(nodeChild.name());
526             tx.replace(childPath, nodeChild, context);
527             lastInsertedPosition++;
528         }
529     }
530
531     private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
532             final YangInstanceIdentifier path, final NormalizedNode data, final EffectiveModelContext context) {
533         try {
534             tx.create(path, data, context);
535         } catch (RestconfDocumentedException e) {
536             // close transaction if any and pass exception further
537             tx.cancel();
538             throw e;
539         }
540
541         return tx.commit();
542     }
543
544     /**
545      * Check if items do NOT already exists at specified {@code path}.
546      *
547      * @param existsFuture if checked data exists
548      * @param path         Path to be checked
549      * @throws RestconfDocumentedException if data already exists.
550      */
551     static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
552             final YangInstanceIdentifier path) {
553         if (TransactionUtil.syncAccess(existsFuture, path)) {
554             LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
555             throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
556                 path);
557         }
558     }
559
560     /**
561      * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
562      * inside of object {@link RestconfStrategy} provided as a parameter.
563      *
564      * @param content        type of data to read (config, state, all)
565      * @param path           the path to read
566      * @param defaultsMode   value of with-defaults parameter
567      * @param ctx            schema context
568      * @return {@link NormalizedNode}
569      */
570     public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
571             final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode,
572             final EffectiveModelContext ctx) {
573         return switch (content) {
574             case ALL -> {
575                 // PREPARE STATE DATA NODE
576                 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
577                 // PREPARE CONFIG DATA NODE
578                 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
579
580                 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
581                     : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode(), ctx));
582             }
583             case CONFIG -> {
584                 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
585                 yield defaultsMode == null ? read : prepareDataByParamWithDef(read, path, defaultsMode.mode(), ctx);
586             }
587             case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
588         };
589     }
590
591     /**
592      * Read specific type of data from data store via transaction with specified subtrees that should only be read.
593      * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
594      *
595      * @param content        type of data to read (config, state, all)
596      * @param path           the parent path to read
597      * @param withDefa       value of with-defaults parameter
598      * @param ctx            schema context
599      * @param fields         paths to selected subtrees which should be read, relative to to the parent path
600      * @return {@link NormalizedNode}
601      */
602     public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
603             final @NonNull YangInstanceIdentifier path, final @Nullable WithDefaultsParam withDefa,
604             final @NonNull EffectiveModelContext ctx, final @NonNull List<YangInstanceIdentifier> fields) {
605         return switch (content) {
606             case ALL -> {
607                 // PREPARE STATE DATA NODE
608                 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
609                 // PREPARE CONFIG DATA NODE
610                 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
611
612                 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, withDefa == null ? configDataNode
613                     : prepareDataByParamWithDef(configDataNode, path, withDefa.mode(), ctx));
614             }
615             case CONFIG -> {
616                 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
617                 yield withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa.mode(), ctx);
618             }
619             case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
620         };
621     }
622
623     private static NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData,
624             final YangInstanceIdentifier path, final WithDefaultsMode defaultsMode, final EffectiveModelContext ctx) {
625         final boolean trim = switch (defaultsMode) {
626             case Trim -> true;
627             case Explicit -> false;
628             case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
629                 "Unsupported with-defaults value " + defaultsMode.getName());
630         };
631
632         final var ctxNode = DataSchemaContextTree.from(ctx).findChild(path).orElseThrow();
633         if (readData instanceof ContainerNode container) {
634             final var builder = Builders.containerBuilder().withNodeIdentifier(container.name());
635             buildCont(builder, container.body(), ctxNode, trim);
636             return builder.build();
637         } else if (readData instanceof MapEntryNode mapEntry) {
638             if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
639                 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
640             }
641
642             final var builder = Builders.mapEntryBuilder().withNodeIdentifier(mapEntry.name());
643             buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
644             return builder.build();
645         } else {
646             throw new IllegalStateException("Unhandled data contract " + readData.contract());
647         }
648     }
649
650     private static void buildMapEntryBuilder(
651             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
652             final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
653             final boolean trim, final List<QName> keys) {
654         for (var child : children) {
655             final var childCtx = getChildContext(ctxNode, child);
656
657             if (child instanceof ContainerNode container) {
658                 appendContainer(builder, container, childCtx, trim);
659             } else if (child instanceof MapNode map) {
660                 appendMap(builder, map, childCtx, trim);
661             } else if (child instanceof LeafNode<?> leaf) {
662                 appendLeaf(builder, leaf, childCtx, trim, keys);
663             } else {
664                 // FIXME: we should never hit this, throw an ISE if this ever happens
665                 LOG.debug("Ignoring unhandled child contract {}", child.contract());
666             }
667         }
668     }
669
670     private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
671             final DataSchemaContext ctxNode, final boolean trim) {
672         final var childBuilder = Builders.containerBuilder().withNodeIdentifier(container.name());
673         buildCont(childBuilder, container.body(), ctxNode, trim);
674         builder.withChild(childBuilder.build());
675     }
676
677     private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
678             final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
679         if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
680             throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
681         }
682
683         // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
684         final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
685
686         // This is a combined check for when we need to emit the leaf.
687         if (
688             // We always have to emit key leaf values
689             keys.contains(leafSchema.getQName())
690             // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
691             //
692             //            When data is retrieved with a <with-defaults> parameter equal to
693             //            'trim', data nodes MUST NOT be reported if they contain the schema
694             //            default value.  Non-configuration data nodes containing the schema
695             //            default value MUST NOT be reported.
696             //
697             || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
698             // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
699             // grasp what we are doing here... emit only if it matches default ???!!!
700             // FIXME: The WithDefaultsParam.EXPLICIT says:
701             //
702             //            Data nodes set to the YANG default by the client are reported.
703             //
704             //        and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
705             //
706             //            If the "with-defaults" parameter is set to "explicit", then the
707             //            server MUST adhere to the default-reporting behavior defined in
708             //            Section 3.3 of [RFC6243].
709             //
710             //        and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
711             //
712             //            When data is retrieved with a <with-defaults> parameter equal to
713             //            'explicit', a data node that was set by a client to its schema
714             //            default value MUST be reported.  A conceptual data node that would be
715             //            set by the server to the schema default value MUST NOT be reported.
716             //            Non-configuration data nodes containing the schema default value MUST
717             //            be reported.
718             //
719             // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
720             //            This seems to disregard the 'trim = true' case semantics (see above).
721             //            Combining the above, though, these checks are missing the 'non-config' check, which would
722             //            distinguish, but barring that this check is superfluous and results in the wrong semantics.
723             //            Without that input, this really should be  covered by the previous case.
724                 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
725             builder.withChild(leaf);
726         }
727     }
728
729     private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
730             final DataSchemaContext childCtx, final boolean trim) {
731         if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
732             throw new IllegalStateException("Input " + map + " does not match " + childCtx);
733         }
734
735         final var childBuilder = switch (map.ordering()) {
736             case SYSTEM -> Builders.mapBuilder();
737             case USER -> Builders.orderedMapBuilder();
738         };
739         buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
740             listSchema.getKeyDefinition());
741         builder.withChild(childBuilder.build());
742     }
743
744     private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
745             final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
746             final List<@NonNull QName> keys) {
747         for (var entry : entries) {
748             final var childCtx = getChildContext(ctxNode, entry);
749             final var mapEntryBuilder = Builders.mapEntryBuilder().withNodeIdentifier(entry.name());
750             buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
751             builder.withChild(mapEntryBuilder.build());
752         }
753     }
754
755     private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
756             final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
757         for (var child : children) {
758             final var childCtx = getChildContext(ctxNode, child);
759             if (child instanceof ContainerNode container) {
760                 appendContainer(builder, container, childCtx, trim);
761             } else if (child instanceof MapNode map) {
762                 appendMap(builder, map, childCtx, trim);
763             } else if (child instanceof LeafNode<?> leaf) {
764                 appendLeaf(builder, leaf, childCtx, trim, List.of());
765             }
766         }
767     }
768
769     private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
770             final NormalizedNode child) {
771         final var childId = child.name();
772         final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
773             : null;
774         if (childCtx == null) {
775             throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
776         }
777         return childCtx;
778     }
779
780     private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
781             final YangInstanceIdentifier path) {
782         return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
783     }
784
785     /**
786      * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
787      * specified subtrees that should only be read.
788      *
789      * @param store                 datastore type
790      * @param path                  parent path to selected fields
791      * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
792      *                              in {@link RestconfStrategy} if any
793      * @param fields                paths to selected subtrees which should be read, relative to to the parent path
794      * @return {@link NormalizedNode}
795      */
796     private @Nullable NormalizedNode readDataViaTransaction(final @NonNull LogicalDatastoreType store,
797             final @NonNull YangInstanceIdentifier path, final @NonNull List<YangInstanceIdentifier> fields) {
798         return TransactionUtil.syncAccess(read(store, path, fields), path).orElse(null);
799     }
800
801     private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
802                                                                   final NormalizedNode configDataNode) {
803         // if no data exists
804         if (stateDataNode == null && configDataNode == null) {
805             return null;
806         }
807
808         // return config data
809         if (stateDataNode == null) {
810             return configDataNode;
811         }
812
813         // return state data
814         if (configDataNode == null) {
815             return stateDataNode;
816         }
817
818         // merge data from config and state
819         return mergeStateAndConfigData(stateDataNode, configDataNode);
820     }
821
822     /**
823      * Merge state and config data into a single NormalizedNode.
824      *
825      * @param stateDataNode  data node of state data
826      * @param configDataNode data node of config data
827      * @return {@link NormalizedNode}
828      */
829     private static @NonNull NormalizedNode mergeStateAndConfigData(
830             final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
831         validateNodeMerge(stateDataNode, configDataNode);
832         // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
833         if (configDataNode instanceof RpcDefinition) {
834             return prepareRpcData(configDataNode, stateDataNode);
835         } else {
836             return prepareData(configDataNode, stateDataNode);
837         }
838     }
839
840     /**
841      * Validates whether the two NormalizedNodes can be merged.
842      *
843      * @param stateDataNode  data node of state data
844      * @param configDataNode data node of config data
845      */
846     private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
847                                           final @NonNull NormalizedNode configDataNode) {
848         final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
849         final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
850         if (!moduleOfStateData.equals(moduleOfConfigData)) {
851             throw new RestconfDocumentedException("Unable to merge data from different modules.");
852         }
853     }
854
855     /**
856      * Prepare and map data for rpc.
857      *
858      * @param configDataNode data node of config data
859      * @param stateDataNode  data node of state data
860      * @return {@link NormalizedNode}
861      */
862     private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
863                                                           final @NonNull NormalizedNode stateDataNode) {
864         final var mapEntryBuilder = Builders.mapEntryBuilder()
865             .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
866
867         // MAP CONFIG DATA
868         mapRpcDataNode(configDataNode, mapEntryBuilder);
869         // MAP STATE DATA
870         mapRpcDataNode(stateDataNode, mapEntryBuilder);
871
872         return Builders.mapBuilder()
873             .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
874             .addChild(mapEntryBuilder.build())
875             .build();
876     }
877
878     /**
879      * Map node to map entry builder.
880      *
881      * @param dataNode        data node
882      * @param mapEntryBuilder builder for mapping data
883      */
884     private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
885             final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
886         ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
887     }
888
889     /**
890      * Prepare and map all data from DS.
891      *
892      * @param configDataNode data node of config data
893      * @param stateDataNode  data node of state data
894      * @return {@link NormalizedNode}
895      */
896     @SuppressWarnings("unchecked")
897     private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
898                                                        final @NonNull NormalizedNode stateDataNode) {
899         if (configDataNode instanceof UserMapNode configMap) {
900             final var builder = Builders.orderedMapBuilder().withNodeIdentifier(configMap.name());
901             mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
902             return builder.build();
903         } else if (configDataNode instanceof SystemMapNode configMap) {
904             final var builder = Builders.mapBuilder().withNodeIdentifier(configMap.name());
905             mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
906             return builder.build();
907         } else if (configDataNode instanceof MapEntryNode configEntry) {
908             final var builder = Builders.mapEntryBuilder().withNodeIdentifier(configEntry.name());
909             mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
910             return builder.build();
911         } else if (configDataNode instanceof ContainerNode configContaienr) {
912             final var builder = Builders.containerBuilder().withNodeIdentifier(configContaienr.name());
913             mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
914             return builder.build();
915         } else if (configDataNode instanceof ChoiceNode configChoice) {
916             final var builder = Builders.choiceBuilder().withNodeIdentifier(configChoice.name());
917             mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
918             return builder.build();
919         } else if (configDataNode instanceof LeafNode configLeaf) {
920             // config trumps oper
921             return configLeaf;
922         } else if (configDataNode instanceof UserLeafSetNode) {
923             final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
924             final var builder = Builders.<Object>orderedLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
925             mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
926             return builder.build();
927         } else if (configDataNode instanceof SystemLeafSetNode) {
928             final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
929             final var builder = Builders.<Object>leafSetBuilder().withNodeIdentifier(configLeafSet.name());
930             mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
931             return builder.build();
932         } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
933             // config trumps oper
934             return configEntry;
935         } else if (configDataNode instanceof UnkeyedListNode configList) {
936             final var builder = Builders.unkeyedListBuilder().withNodeIdentifier(configList.name());
937             mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
938             return builder.build();
939         } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
940             final var builder = Builders.unkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
941             mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
942             return builder.build();
943         } else {
944             throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
945         }
946     }
947
948     /**
949      * Map value from container node to builder.
950      *
951      * @param configData collection of config data nodes
952      * @param stateData  collection of state data nodes
953      * @param builder    builder
954      */
955     private static <T extends NormalizedNode> void mapValueToBuilder(
956             final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
957             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
958         final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
959         final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
960
961         // merge config and state data of children with different identifiers
962         mapDataToBuilder(configMap, stateMap, builder);
963
964         // merge config and state data of children with the same identifiers
965         mergeDataToBuilder(configMap, stateMap, builder);
966     }
967
968     /**
969      * Map data with different identifiers to builder. Data with different identifiers can be just added
970      * as childs to parent node.
971      *
972      * @param configMap map of config data nodes
973      * @param stateMap  map of state data nodes
974      * @param builder   - builder
975      */
976     private static <T extends NormalizedNode> void mapDataToBuilder(
977             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
978             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
979         configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
980             y -> builder.addChild(y.getValue()));
981         stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
982             y -> builder.addChild(y.getValue()));
983     }
984
985     /**
986      * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
987      * go one level down with {@code prepareData} method.
988      *
989      * @param configMap immutable config data
990      * @param stateMap  immutable state data
991      * @param builder   - builder
992      */
993     @SuppressWarnings("unchecked")
994     private static <T extends NormalizedNode> void mergeDataToBuilder(
995             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
996             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
997         // it is enough to process only config data because operational contains the same data
998         configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
999             y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1000     }
1001
1002 }