Allow odl-pretty-print to be configured to true
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / transactions / MdsalRestconfStrategy.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 java.util.Objects.requireNonNull;
11 import static org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION;
12
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import com.google.common.util.concurrent.MoreExecutors;
18 import java.util.ArrayList;
19 import java.util.HashSet;
20 import java.util.List;
21 import java.util.Optional;
22 import java.util.Set;
23 import org.eclipse.jdt.annotation.NonNull;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.opendaylight.mdsal.common.api.CommitInfo;
26 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
27 import org.opendaylight.mdsal.dom.api.DOMActionService;
28 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
29 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
30 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
31 import org.opendaylight.mdsal.dom.api.DOMRpcService;
32 import org.opendaylight.mdsal.dom.api.DOMSchemaService.YangTextSourceExtension;
33 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
34 import org.opendaylight.restconf.api.query.FieldsParam;
35 import org.opendaylight.restconf.api.query.FieldsParam.NodeSelector;
36 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
37 import org.opendaylight.restconf.common.errors.RestconfFuture;
38 import org.opendaylight.restconf.common.errors.SettableRestconfFuture;
39 import org.opendaylight.restconf.nb.rfc8040.jersey.providers.ParameterAwareNormalizedNodeWriter;
40 import org.opendaylight.restconf.nb.rfc8040.legacy.WriterParameters;
41 import org.opendaylight.restconf.server.api.DataGetParams;
42 import org.opendaylight.restconf.server.api.DataGetResult;
43 import org.opendaylight.restconf.server.api.DatabindContext;
44 import org.opendaylight.restconf.server.api.DatabindPath.Data;
45 import org.opendaylight.restconf.server.spi.RpcImplementation;
46 import org.opendaylight.yangtools.yang.common.Empty;
47 import org.opendaylight.yangtools.yang.common.ErrorTag;
48 import org.opendaylight.yangtools.yang.common.ErrorType;
49 import org.opendaylight.yangtools.yang.common.QName;
50 import org.opendaylight.yangtools.yang.common.QNameModule;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
52 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
53 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
54 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext.PathMixin;
55 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
56
57 /**
58  * Implementation of RESTCONF operations using {@link DOMTransactionChain} and related concepts.
59  *
60  * @see DOMTransactionChain
61  * @see DOMDataTreeReadWriteTransaction
62  */
63 public final class MdsalRestconfStrategy extends RestconfStrategy {
64     private final DOMDataBroker dataBroker;
65
66     public MdsalRestconfStrategy(final DatabindContext databind, final DOMDataBroker dataBroker,
67             final ImmutableMap<QName, RpcImplementation> localRpcs, final @Nullable DOMRpcService rpcService,
68             final @Nullable DOMActionService actionService, final @Nullable YangTextSourceExtension sourceProvider,
69             final @Nullable DOMMountPointService mountPointService) {
70         super(databind, localRpcs, rpcService, actionService, sourceProvider, mountPointService);
71         this.dataBroker = requireNonNull(dataBroker);
72     }
73
74     @Override
75     RestconfTransaction prepareWriteExecution() {
76         return new MdsalRestconfTransaction(modelContext(), dataBroker);
77     }
78
79     @Override
80     void delete(final SettableRestconfFuture<Empty> future, final YangInstanceIdentifier path) {
81         final var tx = dataBroker.newReadWriteTransaction();
82         tx.exists(CONFIGURATION, path).addCallback(new FutureCallback<>() {
83             @Override
84             public void onSuccess(final Boolean result) {
85                 if (!result) {
86                     cancelTx(new RestconfDocumentedException("Data does not exist", ErrorType.PROTOCOL,
87                         ErrorTag.DATA_MISSING, path));
88                     return;
89                 }
90
91                 tx.delete(CONFIGURATION, path);
92                 tx.commit().addCallback(new FutureCallback<CommitInfo>() {
93                     @Override
94                     public void onSuccess(final CommitInfo result) {
95                         future.set(Empty.value());
96                     }
97
98                     @Override
99                     public void onFailure(final Throwable cause) {
100                         future.setFailure(new RestconfDocumentedException("Transaction to delete " + path + " failed",
101                             cause));
102                     }
103                 }, MoreExecutors.directExecutor());
104             }
105
106             @Override
107             public void onFailure(final Throwable cause) {
108                 cancelTx(new RestconfDocumentedException("Failed to access " + path, cause));
109             }
110
111             private void cancelTx(final RestconfDocumentedException ex) {
112                 tx.cancel();
113                 future.setFailure(ex);
114             }
115         }, MoreExecutors.directExecutor());
116     }
117
118     @Override
119     RestconfFuture<DataGetResult> dataGET(final Data path, final DataGetParams params) {
120         final var inference = path.inference();
121         final var fields = params.fields();
122         return completeDataGET(inference,
123             fields == null ? WriterParameters.of(params.prettyPrint(), params.depth())
124                 : new WriterParameters(params.prettyPrint(), params.depth(),
125                     translateFieldsParam(inference.modelContext(), path.schema(), fields)),
126             readData(params.content(), path.instance(), params.withDefaults()), null);
127     }
128
129     @Override
130     ListenableFuture<Optional<NormalizedNode>> read(final LogicalDatastoreType store,
131             final YangInstanceIdentifier path) {
132         try (var tx = dataBroker.newReadOnlyTransaction()) {
133             return tx.read(store, path);
134         }
135     }
136
137     @Override
138     ListenableFuture<Boolean> exists(final YangInstanceIdentifier path) {
139         try (var tx = dataBroker.newReadOnlyTransaction()) {
140             return tx.exists(LogicalDatastoreType.CONFIGURATION, path);
141         }
142     }
143
144     /**
145      * Translate a {@link FieldsParam} to a complete list of child nodes organized into levels, suitable for use with
146      * {@link ParameterAwareNormalizedNodeWriter}.
147      *
148      * <p>
149      * Fields parser that stores set of {@link QName}s in each level. Because of this fact, from the output it is only
150      * possible to assume on what depth the selected element is placed. Identifiers of intermediary mixin nodes are also
151      * flatten to the same level as identifiers of data nodes.<br>
152      * Example: field 'a(/b/c);d/e' ('e' is place under choice node 'x') is parsed into following levels:<br>
153      * <pre>
154      * level 0: ['a', 'd']
155      * level 1: ['b', 'x', 'e']
156      * level 2: ['c']
157      * </pre>
158      *
159      * @param modelContext EffectiveModelContext
160      * @param startNode {@link DataSchemaContext} of the API request path
161      * @param input input value of fields parameter
162      * @return {@link List} of levels; each level contains set of {@link QName}
163      */
164     @VisibleForTesting
165     public static @NonNull List<Set<QName>> translateFieldsParam(final @NonNull EffectiveModelContext modelContext,
166             final DataSchemaContext startNode, final @NonNull FieldsParam input) {
167         final var parsed = new ArrayList<Set<QName>>();
168         processSelectors(parsed, modelContext, startNode.dataSchemaNode().getQName().getModule(), startNode,
169             input.nodeSelectors(), 0);
170         return parsed;
171     }
172
173     private static void processSelectors(final List<Set<QName>> parsed, final EffectiveModelContext context,
174             final QNameModule startNamespace, final DataSchemaContext startNode, final List<NodeSelector> selectors,
175             final int index) {
176         final Set<QName> startLevel;
177         if (parsed.size() <= index) {
178             startLevel = new HashSet<>();
179             parsed.add(startLevel);
180         } else {
181             startLevel = parsed.get(index);
182         }
183         for (var selector : selectors) {
184             var node = startNode;
185             var namespace = startNamespace;
186             var level = startLevel;
187             var levelIndex = index;
188
189             // Note: path is guaranteed to have at least one step
190             final var it = selector.path().iterator();
191             while (true) {
192                 // FIXME: The layout of this loop is rather weird, which is due to how prepareQNameLevel() operates. We
193                 //        need to call it only when we know there is another identifier coming, otherwise we would end
194                 //        up with empty levels sneaking into the mix.
195                 //
196                 //        Dealing with that weirdness requires understanding what the expected end results are and a
197                 //        larger rewrite of the algorithms involved.
198                 final var step = it.next();
199                 final var module = step.module();
200                 if (module != null) {
201                     // FIXME: this is not defensive enough, as we can fail to find the module
202                     namespace = context.findModules(module).iterator().next().getQNameModule();
203                 }
204
205                 // add parsed identifier to results for current level
206                 node = addChildToResult(node, step.identifier().bindTo(namespace), level);
207                 if (!it.hasNext()) {
208                     break;
209                 }
210
211                 // go one level down
212                 level = prepareQNameLevel(parsed, level);
213                 levelIndex++;
214             }
215
216             final var subs = selector.subSelectors();
217             if (!subs.isEmpty()) {
218                 processSelectors(parsed, context, namespace, node, subs, levelIndex + 1);
219             }
220         }
221     }
222
223     /**
224      * Preparation of the identifiers level that is used as storage for parsed identifiers. If the current level exist
225      * at the index that doesn't equal to the last index of already parsed identifiers, a new level of identifiers
226      * is allocated and pushed to input parsed identifiers.
227      *
228      * @param parsedIdentifiers Already parsed list of identifiers grouped to multiple levels.
229      * @param currentLevel Current level of identifiers (set).
230      * @return Existing or new level of identifiers.
231      */
232     private static Set<QName> prepareQNameLevel(final List<Set<QName>> parsedIdentifiers,
233             final Set<QName> currentLevel) {
234         final var existingLevel = parsedIdentifiers.stream()
235                 .filter(qNameSet -> qNameSet.equals(currentLevel))
236                 .findAny();
237         if (existingLevel.isPresent()) {
238             final int index = parsedIdentifiers.indexOf(existingLevel.orElseThrow());
239             if (index == parsedIdentifiers.size() - 1) {
240                 final var nextLevel = new HashSet<QName>();
241                 parsedIdentifiers.add(nextLevel);
242                 return nextLevel;
243             }
244
245             return parsedIdentifiers.get(index + 1);
246         }
247
248         final var nextLevel = new HashSet<QName>();
249         parsedIdentifiers.add(nextLevel);
250         return nextLevel;
251     }
252
253     /**
254      * Add parsed child of current node to result for current level.
255      *
256      * @param currentNode current node
257      * @param childQName parsed identifier of child node
258      * @param level current nodes level
259      * @return {@link DataSchemaContextNode}
260      */
261     private static DataSchemaContext addChildToResult(final DataSchemaContext currentNode, final QName childQName,
262             final Set<QName> level) {
263         // resolve parent node
264         final var parentNode = resolveMixinNode(currentNode, level, currentNode.dataSchemaNode().getQName());
265         if (parentNode == null) {
266             throw new RestconfDocumentedException(
267                     "Not-mixin node missing in " + currentNode.getPathStep().getNodeType().getLocalName(),
268                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
269         }
270
271         // resolve child node
272         final DataSchemaContext childNode = resolveMixinNode(childByQName(parentNode, childQName), level, childQName);
273         if (childNode == null) {
274             throw new RestconfDocumentedException(
275                     "Child " + childQName.getLocalName() + " node missing in "
276                             + currentNode.getPathStep().getNodeType().getLocalName(),
277                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
278         }
279
280         // add final childNode node to level nodes
281         level.add(childNode.dataSchemaNode().getQName());
282         return childNode;
283     }
284
285     private static @Nullable DataSchemaContext childByQName(final DataSchemaContext parent, final QName qname) {
286         return parent instanceof DataSchemaContext.Composite composite ? composite.childByQName(qname) : null;
287     }
288
289     /**
290      * Resolve mixin node by searching for inner nodes until not mixin node or null is found.
291      * All nodes expect of not mixin node are added to current level nodes.
292      *
293      * @param node          initial mixin or not-mixin node
294      * @param level         current nodes level
295      * @param qualifiedName qname of initial node
296      * @return {@link DataSchemaContextNode}
297      */
298     private static @Nullable DataSchemaContext resolveMixinNode(final @Nullable DataSchemaContext node,
299             final @NonNull Set<QName> level, final @NonNull QName qualifiedName) {
300         DataSchemaContext currentNode = node;
301         while (currentNode instanceof PathMixin currentMixin) {
302             level.add(qualifiedName);
303             currentNode = currentMixin.childByQName(qualifiedName);
304         }
305
306         return currentNode;
307     }
308
309 }