Introduce restconf.server.{api,spi,mdsal}
[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     public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
618             final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
619         return switch (content) {
620             case ALL -> {
621                 // PREPARE STATE DATA NODE
622                 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
623                 // PREPARE CONFIG DATA NODE
624                 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
625
626                 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
627                     : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
628             }
629             case CONFIG -> {
630                 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
631                 yield defaultsMode == null ? read
632                     : prepareDataByParamWithDef(read, path, defaultsMode.mode());
633             }
634             case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
635         };
636     }
637
638     /**
639      * Read specific type of data from data store via transaction with specified subtrees that should only be read.
640      * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
641      *
642      * @param content  type of data to read (config, state, all)
643      * @param path     the parent path to read
644      * @param withDefa value of with-defaults parameter
645      * @param fields   paths to selected subtrees which should be read, relative to to the parent path
646      * @return {@link NormalizedNode}
647      */
648     public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
649             final @NonNull YangInstanceIdentifier path, final @Nullable WithDefaultsParam withDefa,
650             final @NonNull List<YangInstanceIdentifier> fields) {
651         return switch (content) {
652             case ALL -> {
653                 // PREPARE STATE DATA NODE
654                 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
655                 // PREPARE CONFIG DATA NODE
656                 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
657
658                 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, withDefa == null ? configDataNode
659                     : prepareDataByParamWithDef(configDataNode, path, withDefa.mode()));
660             }
661             case CONFIG -> {
662                 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
663                 yield withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa.mode());
664             }
665             case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
666         };
667     }
668
669     private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
670             final YangInstanceIdentifier path) {
671         return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
672     }
673
674     /**
675      * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
676      * specified subtrees that should only be read.
677      *
678      * @param store                 datastore type
679      * @param path                  parent path to selected fields
680      * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
681      *                              in {@link RestconfStrategy} if any
682      * @param fields                paths to selected subtrees which should be read, relative to to the parent path
683      * @return {@link NormalizedNode}
684      */
685     private @Nullable NormalizedNode readDataViaTransaction(final @NonNull LogicalDatastoreType store,
686             final @NonNull YangInstanceIdentifier path, final @NonNull List<YangInstanceIdentifier> fields) {
687         return TransactionUtil.syncAccess(read(store, path, fields), path).orElse(null);
688     }
689
690     private NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
691             final WithDefaultsMode defaultsMode) {
692         final boolean trim = switch (defaultsMode) {
693             case Trim -> true;
694             case Explicit -> false;
695             case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
696                 "Unsupported with-defaults value " + defaultsMode.getName());
697         };
698
699         // FIXME: we have this readily available in InstanceIdentifierContext
700         final var ctxNode = DataSchemaContextTree.from(modelContext).findChild(path).orElseThrow();
701         if (readData instanceof ContainerNode container) {
702             final var builder = Builders.containerBuilder().withNodeIdentifier(container.name());
703             buildCont(builder, container.body(), ctxNode, trim);
704             return builder.build();
705         } else if (readData instanceof MapEntryNode mapEntry) {
706             if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
707                 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
708             }
709
710             final var builder = Builders.mapEntryBuilder().withNodeIdentifier(mapEntry.name());
711             buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
712             return builder.build();
713         } else {
714             throw new IllegalStateException("Unhandled data contract " + readData.contract());
715         }
716     }
717
718     private static void buildMapEntryBuilder(
719             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
720             final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
721             final boolean trim, final List<QName> keys) {
722         for (var child : children) {
723             final var childCtx = getChildContext(ctxNode, child);
724
725             if (child instanceof ContainerNode container) {
726                 appendContainer(builder, container, childCtx, trim);
727             } else if (child instanceof MapNode map) {
728                 appendMap(builder, map, childCtx, trim);
729             } else if (child instanceof LeafNode<?> leaf) {
730                 appendLeaf(builder, leaf, childCtx, trim, keys);
731             } else {
732                 // FIXME: we should never hit this, throw an ISE if this ever happens
733                 LOG.debug("Ignoring unhandled child contract {}", child.contract());
734             }
735         }
736     }
737
738     private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
739             final DataSchemaContext ctxNode, final boolean trim) {
740         final var childBuilder = Builders.containerBuilder().withNodeIdentifier(container.name());
741         buildCont(childBuilder, container.body(), ctxNode, trim);
742         builder.withChild(childBuilder.build());
743     }
744
745     private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
746             final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
747         if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
748             throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
749         }
750
751         // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
752         final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
753
754         // This is a combined check for when we need to emit the leaf.
755         if (
756             // We always have to emit key leaf values
757             keys.contains(leafSchema.getQName())
758             // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
759             //
760             //            When data is retrieved with a <with-defaults> parameter equal to
761             //            'trim', data nodes MUST NOT be reported if they contain the schema
762             //            default value.  Non-configuration data nodes containing the schema
763             //            default value MUST NOT be reported.
764             //
765             || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
766             // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
767             // grasp what we are doing here... emit only if it matches default ???!!!
768             // FIXME: The WithDefaultsParam.EXPLICIT says:
769             //
770             //            Data nodes set to the YANG default by the client are reported.
771             //
772             //        and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
773             //
774             //            If the "with-defaults" parameter is set to "explicit", then the
775             //            server MUST adhere to the default-reporting behavior defined in
776             //            Section 3.3 of [RFC6243].
777             //
778             //        and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
779             //
780             //            When data is retrieved with a <with-defaults> parameter equal to
781             //            'explicit', a data node that was set by a client to its schema
782             //            default value MUST be reported.  A conceptual data node that would be
783             //            set by the server to the schema default value MUST NOT be reported.
784             //            Non-configuration data nodes containing the schema default value MUST
785             //            be reported.
786             //
787             // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
788             //            This seems to disregard the 'trim = true' case semantics (see above).
789             //            Combining the above, though, these checks are missing the 'non-config' check, which would
790             //            distinguish, but barring that this check is superfluous and results in the wrong semantics.
791             //            Without that input, this really should be  covered by the previous case.
792                 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
793             builder.withChild(leaf);
794         }
795     }
796
797     private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
798             final DataSchemaContext childCtx, final boolean trim) {
799         if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
800             throw new IllegalStateException("Input " + map + " does not match " + childCtx);
801         }
802
803         final var childBuilder = switch (map.ordering()) {
804             case SYSTEM -> Builders.mapBuilder();
805             case USER -> Builders.orderedMapBuilder();
806         };
807         buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
808             listSchema.getKeyDefinition());
809         builder.withChild(childBuilder.build());
810     }
811
812     private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
813             final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
814             final List<@NonNull QName> keys) {
815         for (var entry : entries) {
816             final var childCtx = getChildContext(ctxNode, entry);
817             final var mapEntryBuilder = Builders.mapEntryBuilder().withNodeIdentifier(entry.name());
818             buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
819             builder.withChild(mapEntryBuilder.build());
820         }
821     }
822
823     private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
824             final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
825         for (var child : children) {
826             final var childCtx = getChildContext(ctxNode, child);
827             if (child instanceof ContainerNode container) {
828                 appendContainer(builder, container, childCtx, trim);
829             } else if (child instanceof MapNode map) {
830                 appendMap(builder, map, childCtx, trim);
831             } else if (child instanceof LeafNode<?> leaf) {
832                 appendLeaf(builder, leaf, childCtx, trim, List.of());
833             }
834         }
835     }
836
837     private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
838             final NormalizedNode child) {
839         final var childId = child.name();
840         final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
841             : null;
842         if (childCtx == null) {
843             throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
844         }
845         return childCtx;
846     }
847
848     private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
849                                                                   final NormalizedNode configDataNode) {
850         // if no data exists
851         if (stateDataNode == null && configDataNode == null) {
852             return null;
853         }
854
855         // return config data
856         if (stateDataNode == null) {
857             return configDataNode;
858         }
859
860         // return state data
861         if (configDataNode == null) {
862             return stateDataNode;
863         }
864
865         // merge data from config and state
866         return mergeStateAndConfigData(stateDataNode, configDataNode);
867     }
868
869     /**
870      * Merge state and config data into a single NormalizedNode.
871      *
872      * @param stateDataNode  data node of state data
873      * @param configDataNode data node of config data
874      * @return {@link NormalizedNode}
875      */
876     private static @NonNull NormalizedNode mergeStateAndConfigData(
877             final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
878         validateNodeMerge(stateDataNode, configDataNode);
879         // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
880         if (configDataNode instanceof RpcDefinition) {
881             return prepareRpcData(configDataNode, stateDataNode);
882         } else {
883             return prepareData(configDataNode, stateDataNode);
884         }
885     }
886
887     /**
888      * Validates whether the two NormalizedNodes can be merged.
889      *
890      * @param stateDataNode  data node of state data
891      * @param configDataNode data node of config data
892      */
893     private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
894                                           final @NonNull NormalizedNode configDataNode) {
895         final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
896         final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
897         if (!moduleOfStateData.equals(moduleOfConfigData)) {
898             throw new RestconfDocumentedException("Unable to merge data from different modules.");
899         }
900     }
901
902     /**
903      * Prepare and map data for rpc.
904      *
905      * @param configDataNode data node of config data
906      * @param stateDataNode  data node of state data
907      * @return {@link NormalizedNode}
908      */
909     private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
910                                                           final @NonNull NormalizedNode stateDataNode) {
911         final var mapEntryBuilder = Builders.mapEntryBuilder()
912             .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
913
914         // MAP CONFIG DATA
915         mapRpcDataNode(configDataNode, mapEntryBuilder);
916         // MAP STATE DATA
917         mapRpcDataNode(stateDataNode, mapEntryBuilder);
918
919         return Builders.mapBuilder()
920             .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
921             .addChild(mapEntryBuilder.build())
922             .build();
923     }
924
925     /**
926      * Map node to map entry builder.
927      *
928      * @param dataNode        data node
929      * @param mapEntryBuilder builder for mapping data
930      */
931     private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
932             final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
933         ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
934     }
935
936     /**
937      * Prepare and map all data from DS.
938      *
939      * @param configDataNode data node of config data
940      * @param stateDataNode  data node of state data
941      * @return {@link NormalizedNode}
942      */
943     @SuppressWarnings("unchecked")
944     private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
945                                                        final @NonNull NormalizedNode stateDataNode) {
946         if (configDataNode instanceof UserMapNode configMap) {
947             final var builder = Builders.orderedMapBuilder().withNodeIdentifier(configMap.name());
948             mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
949             return builder.build();
950         } else if (configDataNode instanceof SystemMapNode configMap) {
951             final var builder = Builders.mapBuilder().withNodeIdentifier(configMap.name());
952             mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
953             return builder.build();
954         } else if (configDataNode instanceof MapEntryNode configEntry) {
955             final var builder = Builders.mapEntryBuilder().withNodeIdentifier(configEntry.name());
956             mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
957             return builder.build();
958         } else if (configDataNode instanceof ContainerNode configContaienr) {
959             final var builder = Builders.containerBuilder().withNodeIdentifier(configContaienr.name());
960             mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
961             return builder.build();
962         } else if (configDataNode instanceof ChoiceNode configChoice) {
963             final var builder = Builders.choiceBuilder().withNodeIdentifier(configChoice.name());
964             mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
965             return builder.build();
966         } else if (configDataNode instanceof LeafNode configLeaf) {
967             // config trumps oper
968             return configLeaf;
969         } else if (configDataNode instanceof UserLeafSetNode) {
970             final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
971             final var builder = Builders.<Object>orderedLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
972             mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
973             return builder.build();
974         } else if (configDataNode instanceof SystemLeafSetNode) {
975             final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
976             final var builder = Builders.<Object>leafSetBuilder().withNodeIdentifier(configLeafSet.name());
977             mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
978             return builder.build();
979         } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
980             // config trumps oper
981             return configEntry;
982         } else if (configDataNode instanceof UnkeyedListNode configList) {
983             final var builder = Builders.unkeyedListBuilder().withNodeIdentifier(configList.name());
984             mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
985             return builder.build();
986         } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
987             final var builder = Builders.unkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
988             mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
989             return builder.build();
990         } else {
991             throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
992         }
993     }
994
995     /**
996      * Map value from container node to builder.
997      *
998      * @param configData collection of config data nodes
999      * @param stateData  collection of state data nodes
1000      * @param builder    builder
1001      */
1002     private static <T extends NormalizedNode> void mapValueToBuilder(
1003             final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
1004             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1005         final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1006         final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1007
1008         // merge config and state data of children with different identifiers
1009         mapDataToBuilder(configMap, stateMap, builder);
1010
1011         // merge config and state data of children with the same identifiers
1012         mergeDataToBuilder(configMap, stateMap, builder);
1013     }
1014
1015     /**
1016      * Map data with different identifiers to builder. Data with different identifiers can be just added
1017      * as childs to parent node.
1018      *
1019      * @param configMap map of config data nodes
1020      * @param stateMap  map of state data nodes
1021      * @param builder   - builder
1022      */
1023     private static <T extends NormalizedNode> void mapDataToBuilder(
1024             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1025             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1026         configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
1027             y -> builder.addChild(y.getValue()));
1028         stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
1029             y -> builder.addChild(y.getValue()));
1030     }
1031
1032     /**
1033      * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
1034      * go one level down with {@code prepareData} method.
1035      *
1036      * @param configMap immutable config data
1037      * @param stateMap  immutable state data
1038      * @param builder   - builder
1039      */
1040     @SuppressWarnings("unchecked")
1041     private static <T extends NormalizedNode> void mergeDataToBuilder(
1042             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1043             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1044         // it is enough to process only config data because operational contains the same data
1045         configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1046             y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1047     }
1048
1049     public @NonNull RestconfFuture<OperationOutput> invokeRpc(final URI restconfURI, final QName type,
1050             final OperationInput input) {
1051         final var local = localRpcs.get(type);
1052         if (local != null) {
1053             return local.invoke(restconfURI, input);
1054         }
1055         if (rpcService == null) {
1056             LOG.debug("RPC invocation is not available");
1057             return RestconfFuture.failed(new RestconfDocumentedException("RPC invocation is not available",
1058                 ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED));
1059         }
1060
1061         final var ret = new SettableRestconfFuture<OperationOutput>();
1062         Futures.addCallback(rpcService.invokeRpc(requireNonNull(type), input.input()),
1063             new FutureCallback<DOMRpcResult>() {
1064                 @Override
1065                 public void onSuccess(final DOMRpcResult response) {
1066                     final var errors = response.errors();
1067                     if (errors.isEmpty()) {
1068                         ret.set(input.newOperationOutput(response.value()));
1069                     } else {
1070                         LOG.debug("RPC invocation reported {}", response.errors());
1071                         ret.setFailure(new RestconfDocumentedException("RPC implementation reported errors", null,
1072                             response.errors()));
1073                     }
1074                 }
1075
1076                 @Override
1077                 public void onFailure(final Throwable cause) {
1078                     LOG.debug("RPC invocation failed, cause");
1079                     if (cause instanceof RestconfDocumentedException ex) {
1080                         ret.setFailure(ex);
1081                     } else {
1082                         // TODO: YangNetconfErrorAware if we ever get into a broader invocation scope
1083                         ret.setFailure(new RestconfDocumentedException(cause,
1084                             new RestconfError(ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage())));
1085                     }
1086                 }
1087             }, MoreExecutors.directExecutor());
1088         return ret;
1089     }
1090 }