Disconnect PatchStatusContext from InstanceIdentifierContext
[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     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     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     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     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.entities()) {
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         final var patchId = patch.patchId();
488         if (noError) {
489             try {
490                 TransactionUtil.syncCommit(tx.commit(), "PATCH", null);
491             } catch (RestconfDocumentedException e) {
492                 // if errors occurred during transaction commit then patch failed and global errors are reported
493                 return new PatchStatusContext(context, patchId, List.copyOf(editCollection), false, e.getErrors());
494             }
495
496             return new PatchStatusContext(context, patchId, List.copyOf(editCollection), true, null);
497         } else {
498             tx.cancel();
499             return new PatchStatusContext(context, patchId, List.copyOf(editCollection), false, null);
500         }
501     }
502
503     private static void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
504             final NormalizedNode data, final PointParam point, final NormalizedNodeContainer<?> readList,
505             final YangInstanceIdentifier grandParentPath, final boolean before, final EffectiveModelContext context) {
506         tx.remove(grandParentPath);
507         final var pointArg = YangInstanceIdentifierDeserializer.create(context, point.value()).path
508             .getLastPathArgument();
509         int lastItemPosition = 0;
510         for (var nodeChild : readList.body()) {
511             if (nodeChild.name().equals(pointArg)) {
512                 break;
513             }
514             lastItemPosition++;
515         }
516         if (!before) {
517             lastItemPosition++;
518         }
519         int lastInsertedPosition = 0;
520         final var emptySubtree = ImmutableNodes.fromInstanceId(context, grandParentPath);
521         tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
522         for (var nodeChild : readList.body()) {
523             if (lastInsertedPosition == lastItemPosition) {
524                 tx.replace(path, data, context);
525             }
526             final YangInstanceIdentifier childPath = grandParentPath.node(nodeChild.name());
527             tx.replace(childPath, nodeChild, context);
528             lastInsertedPosition++;
529         }
530     }
531
532     private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
533             final YangInstanceIdentifier path, final NormalizedNode data, final EffectiveModelContext context) {
534         try {
535             tx.create(path, data, context);
536         } catch (RestconfDocumentedException e) {
537             // close transaction if any and pass exception further
538             tx.cancel();
539             throw e;
540         }
541
542         return tx.commit();
543     }
544
545     /**
546      * Check if items do NOT already exists at specified {@code path}.
547      *
548      * @param existsFuture if checked data exists
549      * @param path         Path to be checked
550      * @throws RestconfDocumentedException if data already exists.
551      */
552     static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
553             final YangInstanceIdentifier path) {
554         if (TransactionUtil.syncAccess(existsFuture, path)) {
555             LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
556             throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
557                 path);
558         }
559     }
560
561     /**
562      * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
563      * inside of object {@link RestconfStrategy} provided as a parameter.
564      *
565      * @param content        type of data to read (config, state, all)
566      * @param path           the path to read
567      * @param defaultsMode   value of with-defaults parameter
568      * @param ctx            schema context
569      * @return {@link NormalizedNode}
570      */
571     public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
572             final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode,
573             final EffectiveModelContext ctx) {
574         return switch (content) {
575             case ALL -> {
576                 // PREPARE STATE DATA NODE
577                 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
578                 // PREPARE CONFIG DATA NODE
579                 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
580
581                 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
582                     : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode(), ctx));
583             }
584             case CONFIG -> {
585                 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
586                 yield defaultsMode == null ? read : prepareDataByParamWithDef(read, path, defaultsMode.mode(), ctx);
587             }
588             case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
589         };
590     }
591
592     /**
593      * Read specific type of data from data store via transaction with specified subtrees that should only be read.
594      * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
595      *
596      * @param content        type of data to read (config, state, all)
597      * @param path           the parent path to read
598      * @param withDefa       value of with-defaults parameter
599      * @param ctx            schema context
600      * @param fields         paths to selected subtrees which should be read, relative to to the parent path
601      * @return {@link NormalizedNode}
602      */
603     public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
604             final @NonNull YangInstanceIdentifier path, final @Nullable WithDefaultsParam withDefa,
605             final @NonNull EffectiveModelContext ctx, final @NonNull List<YangInstanceIdentifier> fields) {
606         return switch (content) {
607             case ALL -> {
608                 // PREPARE STATE DATA NODE
609                 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
610                 // PREPARE CONFIG DATA NODE
611                 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
612
613                 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, withDefa == null ? configDataNode
614                     : prepareDataByParamWithDef(configDataNode, path, withDefa.mode(), ctx));
615             }
616             case CONFIG -> {
617                 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
618                 yield withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa.mode(), ctx);
619             }
620             case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
621         };
622     }
623
624     private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
625             final YangInstanceIdentifier path) {
626         return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
627     }
628
629     /**
630      * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
631      * specified subtrees that should only be read.
632      *
633      * @param store                 datastore type
634      * @param path                  parent path to selected fields
635      * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
636      *                              in {@link RestconfStrategy} if any
637      * @param fields                paths to selected subtrees which should be read, relative to to the parent path
638      * @return {@link NormalizedNode}
639      */
640     private @Nullable NormalizedNode readDataViaTransaction(final @NonNull LogicalDatastoreType store,
641             final @NonNull YangInstanceIdentifier path, final @NonNull List<YangInstanceIdentifier> fields) {
642         return TransactionUtil.syncAccess(read(store, path, fields), path).orElse(null);
643     }
644
645     private static NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData,
646             final YangInstanceIdentifier path, final WithDefaultsMode defaultsMode, final EffectiveModelContext ctx) {
647         final boolean trim = switch (defaultsMode) {
648             case Trim -> true;
649             case Explicit -> false;
650             case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
651                 "Unsupported with-defaults value " + defaultsMode.getName());
652         };
653
654         final var ctxNode = DataSchemaContextTree.from(ctx).findChild(path).orElseThrow();
655         if (readData instanceof ContainerNode container) {
656             final var builder = Builders.containerBuilder().withNodeIdentifier(container.name());
657             buildCont(builder, container.body(), ctxNode, trim);
658             return builder.build();
659         } else if (readData instanceof MapEntryNode mapEntry) {
660             if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
661                 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
662             }
663
664             final var builder = Builders.mapEntryBuilder().withNodeIdentifier(mapEntry.name());
665             buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
666             return builder.build();
667         } else {
668             throw new IllegalStateException("Unhandled data contract " + readData.contract());
669         }
670     }
671
672     private static void buildMapEntryBuilder(
673             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
674             final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
675             final boolean trim, final List<QName> keys) {
676         for (var child : children) {
677             final var childCtx = getChildContext(ctxNode, child);
678
679             if (child instanceof ContainerNode container) {
680                 appendContainer(builder, container, childCtx, trim);
681             } else if (child instanceof MapNode map) {
682                 appendMap(builder, map, childCtx, trim);
683             } else if (child instanceof LeafNode<?> leaf) {
684                 appendLeaf(builder, leaf, childCtx, trim, keys);
685             } else {
686                 // FIXME: we should never hit this, throw an ISE if this ever happens
687                 LOG.debug("Ignoring unhandled child contract {}", child.contract());
688             }
689         }
690     }
691
692     private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
693             final DataSchemaContext ctxNode, final boolean trim) {
694         final var childBuilder = Builders.containerBuilder().withNodeIdentifier(container.name());
695         buildCont(childBuilder, container.body(), ctxNode, trim);
696         builder.withChild(childBuilder.build());
697     }
698
699     private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
700             final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
701         if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
702             throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
703         }
704
705         // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
706         final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
707
708         // This is a combined check for when we need to emit the leaf.
709         if (
710             // We always have to emit key leaf values
711             keys.contains(leafSchema.getQName())
712             // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
713             //
714             //            When data is retrieved with a <with-defaults> parameter equal to
715             //            'trim', data nodes MUST NOT be reported if they contain the schema
716             //            default value.  Non-configuration data nodes containing the schema
717             //            default value MUST NOT be reported.
718             //
719             || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
720             // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
721             // grasp what we are doing here... emit only if it matches default ???!!!
722             // FIXME: The WithDefaultsParam.EXPLICIT says:
723             //
724             //            Data nodes set to the YANG default by the client are reported.
725             //
726             //        and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
727             //
728             //            If the "with-defaults" parameter is set to "explicit", then the
729             //            server MUST adhere to the default-reporting behavior defined in
730             //            Section 3.3 of [RFC6243].
731             //
732             //        and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
733             //
734             //            When data is retrieved with a <with-defaults> parameter equal to
735             //            'explicit', a data node that was set by a client to its schema
736             //            default value MUST be reported.  A conceptual data node that would be
737             //            set by the server to the schema default value MUST NOT be reported.
738             //            Non-configuration data nodes containing the schema default value MUST
739             //            be reported.
740             //
741             // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
742             //            This seems to disregard the 'trim = true' case semantics (see above).
743             //            Combining the above, though, these checks are missing the 'non-config' check, which would
744             //            distinguish, but barring that this check is superfluous and results in the wrong semantics.
745             //            Without that input, this really should be  covered by the previous case.
746                 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
747             builder.withChild(leaf);
748         }
749     }
750
751     private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
752             final DataSchemaContext childCtx, final boolean trim) {
753         if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
754             throw new IllegalStateException("Input " + map + " does not match " + childCtx);
755         }
756
757         final var childBuilder = switch (map.ordering()) {
758             case SYSTEM -> Builders.mapBuilder();
759             case USER -> Builders.orderedMapBuilder();
760         };
761         buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
762             listSchema.getKeyDefinition());
763         builder.withChild(childBuilder.build());
764     }
765
766     private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
767             final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
768             final List<@NonNull QName> keys) {
769         for (var entry : entries) {
770             final var childCtx = getChildContext(ctxNode, entry);
771             final var mapEntryBuilder = Builders.mapEntryBuilder().withNodeIdentifier(entry.name());
772             buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
773             builder.withChild(mapEntryBuilder.build());
774         }
775     }
776
777     private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
778             final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
779         for (var child : children) {
780             final var childCtx = getChildContext(ctxNode, child);
781             if (child instanceof ContainerNode container) {
782                 appendContainer(builder, container, childCtx, trim);
783             } else if (child instanceof MapNode map) {
784                 appendMap(builder, map, childCtx, trim);
785             } else if (child instanceof LeafNode<?> leaf) {
786                 appendLeaf(builder, leaf, childCtx, trim, List.of());
787             }
788         }
789     }
790
791     private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
792             final NormalizedNode child) {
793         final var childId = child.name();
794         final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
795             : null;
796         if (childCtx == null) {
797             throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
798         }
799         return childCtx;
800     }
801
802     private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
803                                                                   final NormalizedNode configDataNode) {
804         // if no data exists
805         if (stateDataNode == null && configDataNode == null) {
806             return null;
807         }
808
809         // return config data
810         if (stateDataNode == null) {
811             return configDataNode;
812         }
813
814         // return state data
815         if (configDataNode == null) {
816             return stateDataNode;
817         }
818
819         // merge data from config and state
820         return mergeStateAndConfigData(stateDataNode, configDataNode);
821     }
822
823     /**
824      * Merge state and config data into a single NormalizedNode.
825      *
826      * @param stateDataNode  data node of state data
827      * @param configDataNode data node of config data
828      * @return {@link NormalizedNode}
829      */
830     private static @NonNull NormalizedNode mergeStateAndConfigData(
831             final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
832         validateNodeMerge(stateDataNode, configDataNode);
833         // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
834         if (configDataNode instanceof RpcDefinition) {
835             return prepareRpcData(configDataNode, stateDataNode);
836         } else {
837             return prepareData(configDataNode, stateDataNode);
838         }
839     }
840
841     /**
842      * Validates whether the two NormalizedNodes can be merged.
843      *
844      * @param stateDataNode  data node of state data
845      * @param configDataNode data node of config data
846      */
847     private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
848                                           final @NonNull NormalizedNode configDataNode) {
849         final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
850         final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
851         if (!moduleOfStateData.equals(moduleOfConfigData)) {
852             throw new RestconfDocumentedException("Unable to merge data from different modules.");
853         }
854     }
855
856     /**
857      * Prepare and map data for rpc.
858      *
859      * @param configDataNode data node of config data
860      * @param stateDataNode  data node of state data
861      * @return {@link NormalizedNode}
862      */
863     private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
864                                                           final @NonNull NormalizedNode stateDataNode) {
865         final var mapEntryBuilder = Builders.mapEntryBuilder()
866             .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
867
868         // MAP CONFIG DATA
869         mapRpcDataNode(configDataNode, mapEntryBuilder);
870         // MAP STATE DATA
871         mapRpcDataNode(stateDataNode, mapEntryBuilder);
872
873         return Builders.mapBuilder()
874             .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
875             .addChild(mapEntryBuilder.build())
876             .build();
877     }
878
879     /**
880      * Map node to map entry builder.
881      *
882      * @param dataNode        data node
883      * @param mapEntryBuilder builder for mapping data
884      */
885     private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
886             final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
887         ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
888     }
889
890     /**
891      * Prepare and map all data from DS.
892      *
893      * @param configDataNode data node of config data
894      * @param stateDataNode  data node of state data
895      * @return {@link NormalizedNode}
896      */
897     @SuppressWarnings("unchecked")
898     private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
899                                                        final @NonNull NormalizedNode stateDataNode) {
900         if (configDataNode instanceof UserMapNode configMap) {
901             final var builder = Builders.orderedMapBuilder().withNodeIdentifier(configMap.name());
902             mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
903             return builder.build();
904         } else if (configDataNode instanceof SystemMapNode configMap) {
905             final var builder = Builders.mapBuilder().withNodeIdentifier(configMap.name());
906             mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
907             return builder.build();
908         } else if (configDataNode instanceof MapEntryNode configEntry) {
909             final var builder = Builders.mapEntryBuilder().withNodeIdentifier(configEntry.name());
910             mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
911             return builder.build();
912         } else if (configDataNode instanceof ContainerNode configContaienr) {
913             final var builder = Builders.containerBuilder().withNodeIdentifier(configContaienr.name());
914             mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
915             return builder.build();
916         } else if (configDataNode instanceof ChoiceNode configChoice) {
917             final var builder = Builders.choiceBuilder().withNodeIdentifier(configChoice.name());
918             mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
919             return builder.build();
920         } else if (configDataNode instanceof LeafNode configLeaf) {
921             // config trumps oper
922             return configLeaf;
923         } else if (configDataNode instanceof UserLeafSetNode) {
924             final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
925             final var builder = Builders.<Object>orderedLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
926             mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
927             return builder.build();
928         } else if (configDataNode instanceof SystemLeafSetNode) {
929             final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
930             final var builder = Builders.<Object>leafSetBuilder().withNodeIdentifier(configLeafSet.name());
931             mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
932             return builder.build();
933         } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
934             // config trumps oper
935             return configEntry;
936         } else if (configDataNode instanceof UnkeyedListNode configList) {
937             final var builder = Builders.unkeyedListBuilder().withNodeIdentifier(configList.name());
938             mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
939             return builder.build();
940         } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
941             final var builder = Builders.unkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
942             mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
943             return builder.build();
944         } else {
945             throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
946         }
947     }
948
949     /**
950      * Map value from container node to builder.
951      *
952      * @param configData collection of config data nodes
953      * @param stateData  collection of state data nodes
954      * @param builder    builder
955      */
956     private static <T extends NormalizedNode> void mapValueToBuilder(
957             final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
958             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
959         final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
960         final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
961
962         // merge config and state data of children with different identifiers
963         mapDataToBuilder(configMap, stateMap, builder);
964
965         // merge config and state data of children with the same identifiers
966         mergeDataToBuilder(configMap, stateMap, builder);
967     }
968
969     /**
970      * Map data with different identifiers to builder. Data with different identifiers can be just added
971      * as childs to parent node.
972      *
973      * @param configMap map of config data nodes
974      * @param stateMap  map of state data nodes
975      * @param builder   - builder
976      */
977     private static <T extends NormalizedNode> void mapDataToBuilder(
978             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
979             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
980         configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
981             y -> builder.addChild(y.getValue()));
982         stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
983             y -> builder.addChild(y.getValue()));
984     }
985
986     /**
987      * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
988      * go one level down with {@code prepareData} method.
989      *
990      * @param configMap immutable config data
991      * @param stateMap  immutable state data
992      * @param builder   - builder
993      */
994     @SuppressWarnings("unchecked")
995     private static <T extends NormalizedNode> void mergeDataToBuilder(
996             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
997             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
998         // it is enough to process only config data because operational contains the same data
999         configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1000             y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1001     }
1002
1003 }