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