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