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