Do not validate non-existent roots
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / leafref / LeafRefValidatation.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. 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.yangtools.yang.data.impl.leafref;
9
10 import com.google.common.collect.ImmutableSet;
11 import com.google.common.collect.Iterables;
12 import java.util.ArrayList;
13 import java.util.Collection;
14 import java.util.HashMap;
15 import java.util.HashSet;
16 import java.util.Iterator;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.Map.Entry;
20 import java.util.Optional;
21 import java.util.Set;
22 import java.util.stream.Collectors;
23 import org.opendaylight.yangtools.yang.common.QName;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
27 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
28 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
30 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
37 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.ValueNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
40 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 // FIXME: 3.0.0: Rename to LeafRefValidation
46 public final class LeafRefValidatation {
47
48     private static final Logger LOG = LoggerFactory.getLogger(LeafRefValidatation.class);
49     private static final String FAILED = " -> FAILED";
50     private static final String SUCCESS = " -> OK";
51
52     private final Set<LeafRefContext> validatedLeafRefCtx = new HashSet<>();
53     private final List<String> errorsMessages = new ArrayList<>();
54     private final NormalizedNode<?, ?> root;
55
56     private LeafRefValidatation(final NormalizedNode<?, ?> root) {
57         this.root = root;
58     }
59
60     public static void validate(final DataTreeCandidate tree, final LeafRefContext rootLeafRefCtx)
61             throws LeafRefDataValidationFailedException {
62         final Optional<NormalizedNode<?, ?>> root = tree.getRootNode().getDataAfter();
63         if (root.isPresent()) {
64             new LeafRefValidatation(root.get()).validateChildren(rootLeafRefCtx, tree.getRootNode().getChildNodes());
65         }
66     }
67
68     private void validateChildren(final LeafRefContext rootLeafRefCtx, final Collection<DataTreeCandidateNode> children)
69             throws LeafRefDataValidationFailedException {
70         for (final DataTreeCandidateNode dataTreeCandidateNode : children) {
71             if (dataTreeCandidateNode.getModificationType() != ModificationType.UNMODIFIED) {
72                 final PathArgument identifier = dataTreeCandidateNode.getIdentifier();
73                 final QName childQName = identifier.getNodeType();
74
75                 final LeafRefContext referencedByCtx = rootLeafRefCtx.getReferencedChildByName(childQName);
76                 final LeafRefContext referencingCtx = rootLeafRefCtx.getReferencingChildByName(childQName);
77                 if (referencedByCtx != null || referencingCtx != null) {
78                     final YangInstanceIdentifier yangInstanceIdentifier = YangInstanceIdentifier
79                             .create(dataTreeCandidateNode.getIdentifier());
80                     validateNode(dataTreeCandidateNode, referencedByCtx, referencingCtx, yangInstanceIdentifier);
81                 }
82             }
83         }
84
85         if (!errorsMessages.isEmpty()) {
86             final StringBuilder message = new StringBuilder();
87             int errCount = 0;
88             for (final String errorMessage : errorsMessages) {
89                 message.append(errorMessage);
90                 errCount++;
91             }
92             throw new LeafRefDataValidationFailedException(message.toString(), errCount);
93         }
94     }
95
96     private void validateNode(final DataTreeCandidateNode node, final LeafRefContext referencedByCtx,
97         final LeafRefContext referencingCtx, final YangInstanceIdentifier current) {
98
99         if (node.getModificationType() == ModificationType.WRITE && node.getDataAfter().isPresent()) {
100             final Optional<NormalizedNode<?, ?>> dataAfter = node.getDataAfter();
101             final NormalizedNode<?, ?> normalizedNode = dataAfter.get();
102             validateNodeData(normalizedNode, referencedByCtx, referencingCtx,
103                     node.getModificationType(), current);
104             return;
105         }
106
107         if (node.getModificationType() == ModificationType.DELETE && referencedByCtx != null) {
108             final Optional<NormalizedNode<?, ?>> dataBefor = node.getDataBefore();
109             final NormalizedNode<?, ?> normalizedNode = dataBefor.get();
110             validateNodeData(normalizedNode, referencedByCtx, null,
111                     node.getModificationType(), current);
112             return;
113         }
114
115         final Collection<DataTreeCandidateNode> childNodes = node.getChildNodes();
116         for (final DataTreeCandidateNode childNode : childNodes) {
117             if (childNode.getModificationType() != ModificationType.UNMODIFIED) {
118                 final LeafRefContext childReferencedByCtx = getReferencedByCtxChild(referencedByCtx, childNode);
119                 final LeafRefContext childReferencingCtx = getReferencingCtxChild(referencingCtx, childNode);
120
121                 if (childReferencedByCtx != null || childReferencingCtx != null) {
122                     final YangInstanceIdentifier childYangInstanceIdentifier = current.node(childNode.getIdentifier());
123                     validateNode(childNode, childReferencedByCtx,childReferencingCtx, childYangInstanceIdentifier);
124                 }
125             }
126         }
127     }
128
129     private static LeafRefContext getReferencingCtxChild(final LeafRefContext referencingCtx,
130             final DataTreeCandidateNode childNode) {
131         if (referencingCtx == null) {
132             return null;
133         }
134
135         final QName childQName = childNode.getIdentifier().getNodeType();
136         LeafRefContext childReferencingCtx = referencingCtx.getReferencingChildByName(childQName);
137         if (childReferencingCtx == null) {
138             final NormalizedNode<?, ?> data = childNode.getDataAfter().get();
139             if (data instanceof MapEntryNode || data instanceof UnkeyedListEntryNode) {
140                 childReferencingCtx = referencingCtx;
141             }
142         }
143
144         return childReferencingCtx;
145     }
146
147     private static LeafRefContext getReferencedByCtxChild(final LeafRefContext referencedByCtx,
148             final DataTreeCandidateNode childNode) {
149         if (referencedByCtx == null) {
150             return null;
151         }
152
153         final QName childQName = childNode.getIdentifier().getNodeType();
154         LeafRefContext childReferencedByCtx = referencedByCtx.getReferencedChildByName(childQName);
155         if (childReferencedByCtx == null) {
156             final NormalizedNode<?, ?> data = childNode.getDataAfter().get();
157             if (data instanceof MapEntryNode || data instanceof UnkeyedListEntryNode) {
158                 childReferencedByCtx = referencedByCtx;
159             }
160         }
161
162         return childReferencedByCtx;
163     }
164
165     private void validateNodeData(final NormalizedNode<?, ?> node, final LeafRefContext referencedByCtx,
166             final LeafRefContext referencingCtx, final ModificationType modificationType,
167             final YangInstanceIdentifier current) {
168
169         if (node instanceof LeafNode) {
170             final LeafNode<?> leaf = (LeafNode<?>) node;
171
172             if (referencedByCtx != null && referencedByCtx.isReferenced()) {
173                 validateLeafRefTargetNodeData(leaf, referencedByCtx, modificationType);
174             }
175             if (referencingCtx != null && referencingCtx.isReferencing()) {
176                 validateLeafRefNodeData(leaf, referencingCtx, modificationType, current);
177             }
178
179             return;
180         }
181
182         if (node instanceof LeafSetNode) {
183             if (referencedByCtx == null && referencingCtx == null) {
184                 return;
185             }
186
187             final LeafSetNode<?> leafSet = (LeafSetNode<?>) node;
188             for (final NormalizedNode<?, ?> leafSetEntry : leafSet.getValue()) {
189                 if (referencedByCtx != null && referencedByCtx.isReferenced()) {
190                     validateLeafRefTargetNodeData(leafSetEntry, referencedByCtx, modificationType);
191                 }
192                 if (referencingCtx != null && referencingCtx.isReferencing()) {
193                     validateLeafRefNodeData(leafSetEntry, referencingCtx, modificationType, current);
194                 }
195             }
196
197             return;
198         }
199
200         if (node instanceof ChoiceNode) {
201             final ChoiceNode choice = (ChoiceNode) node;
202             for (final DataContainerChild<? extends PathArgument, ?> dataContainerChild : choice.getValue()) {
203                 final QName qname = dataContainerChild.getNodeType();
204
205                 final LeafRefContext childReferencedByCtx;
206                 if (referencedByCtx != null) {
207                     childReferencedByCtx = findReferencedByCtxUnderChoice(referencedByCtx, qname);
208                 } else {
209                     childReferencedByCtx = null;
210                 }
211
212                 final LeafRefContext childReferencingCtx;
213                 if (referencingCtx != null) {
214                     childReferencingCtx = findReferencingCtxUnderChoice(referencingCtx, qname);
215                 } else {
216                     childReferencingCtx = null;
217                 }
218
219                 if (childReferencedByCtx != null || childReferencingCtx != null) {
220                     final YangInstanceIdentifier childYangInstanceIdentifier = current
221                             .node(dataContainerChild.getIdentifier());
222                     validateNodeData(dataContainerChild, childReferencedByCtx,
223                             childReferencingCtx, modificationType, childYangInstanceIdentifier);
224                 }
225             }
226         } else if (node instanceof DataContainerNode) {
227             final DataContainerNode<?> dataContainerNode = (DataContainerNode<?>) node;
228
229             for (final DataContainerChild<? extends PathArgument, ?> child : dataContainerNode.getValue()) {
230                 if (child instanceof AugmentationNode) {
231                     validateNodeData(child, referencedByCtx, referencingCtx, modificationType, current
232                         .node(child.getIdentifier()));
233                     return;
234                 }
235
236                 final QName qname = child.getNodeType();
237                 final LeafRefContext childReferencedByCtx;
238                 if (referencedByCtx != null) {
239                     childReferencedByCtx = referencedByCtx.getReferencedChildByName(qname);
240                 } else {
241                     childReferencedByCtx = null;
242                 }
243
244                 final LeafRefContext childReferencingCtx;
245                 if (referencingCtx != null) {
246                     childReferencingCtx = referencingCtx.getReferencingChildByName(qname);
247                 } else {
248                     childReferencingCtx = null;
249                 }
250
251                 if (childReferencedByCtx != null || childReferencingCtx != null) {
252                     final YangInstanceIdentifier childYangInstanceIdentifier = current
253                             .node(child.getIdentifier());
254                     validateNodeData(child, childReferencedByCtx,
255                             childReferencingCtx, modificationType, childYangInstanceIdentifier);
256                 }
257             }
258         } else if (node instanceof MapNode) {
259             final MapNode map = (MapNode) node;
260
261             for (final MapEntryNode mapEntry : map.getValue()) {
262                 final YangInstanceIdentifier mapEntryYangInstanceIdentifier = current.node(mapEntry.getIdentifier());
263                 for (final DataContainerChild<? extends PathArgument, ?> mapEntryNode : mapEntry.getValue()) {
264                     if (mapEntryNode instanceof AugmentationNode) {
265                         validateNodeData(mapEntryNode, referencedByCtx, referencingCtx, modificationType, current
266                             .node(mapEntryNode.getIdentifier()));
267                         return;
268                     }
269
270                     final QName qname = mapEntryNode.getNodeType();
271                     final LeafRefContext childReferencedByCtx;
272                     if (referencedByCtx != null) {
273                         childReferencedByCtx = referencedByCtx.getReferencedChildByName(qname);
274                     } else {
275                         childReferencedByCtx = null;
276                     }
277
278                     final LeafRefContext childReferencingCtx;
279                     if (referencingCtx != null) {
280                         childReferencingCtx = referencingCtx.getReferencingChildByName(qname);
281                     } else {
282                         childReferencingCtx = null;
283                     }
284
285                     if (childReferencedByCtx != null || childReferencingCtx != null) {
286                         validateNodeData(mapEntryNode, childReferencedByCtx, childReferencingCtx, modificationType,
287                                 mapEntryYangInstanceIdentifier.node(mapEntryNode.getIdentifier()));
288                     }
289                 }
290             }
291         }
292         // FIXME: check UnkeyedListNode case
293     }
294
295     private static LeafRefContext findReferencingCtxUnderChoice(
296             final LeafRefContext referencingCtx, final QName qname) {
297
298         for (final LeafRefContext child : referencingCtx.getReferencingChilds().values()) {
299             final LeafRefContext referencingChildByName = child.getReferencingChildByName(qname);
300             if (referencingChildByName != null) {
301                 return referencingChildByName;
302             }
303         }
304
305         return null;
306     }
307
308     private static LeafRefContext findReferencedByCtxUnderChoice(
309             final LeafRefContext referencedByCtx, final QName qname) {
310
311         for (final LeafRefContext child : referencedByCtx.getReferencedByChilds().values()) {
312             final LeafRefContext referencedByChildByName = child.getReferencedChildByName(qname);
313             if (referencedByChildByName != null) {
314                 return referencedByChildByName;
315             }
316         }
317
318         return null;
319     }
320
321     private void validateLeafRefTargetNodeData(final NormalizedNode<?, ?> leaf, final LeafRefContext
322             referencedByCtx, final ModificationType modificationType) {
323         if (!validatedLeafRefCtx.add(referencedByCtx)) {
324             LOG.trace("Operation [{}] validate data of leafref TARGET node: name[{}] = value[{}] -> SKIP: Already "
325                     + "validated", modificationType, referencedByCtx.getNodeName(), leaf.getValue());
326             return;
327         }
328
329         LOG.trace("Operation [{}] validate data of leafref TARGET node: name[{}] = value[{}]", modificationType,
330             referencedByCtx.getNodeName(), leaf.getValue());
331         final Set<LeafRefContext> leafRefs = referencedByCtx.getAllReferencedByLeafRefCtxs().values().stream()
332                 .filter(LeafRefContext::isReferencing).collect(Collectors.toSet());
333         if (leafRefs.isEmpty()) {
334             return;
335         }
336
337         final Set<Object> leafRefTargetNodeValues = extractRootValues(referencedByCtx);
338         leafRefs.forEach(leafRefContext -> {
339             extractRootValues(leafRefContext).forEach(leafRefsValue -> {
340                 if (leafRefTargetNodeValues.contains(leafRefsValue)) {
341                     LOG.trace("Valid leafref value [{}] {}", leafRefsValue, SUCCESS);
342                     return;
343                 }
344
345                 LOG.debug("Invalid leafref value [{}] allowed values {} by validation of leafref TARGET node: {} path "
346                         + "of invalid LEAFREF node: {} leafRef target path: {} {}", leafRefsValue,
347                         leafRefTargetNodeValues, leaf.getNodeType(), leafRefContext.getCurrentNodePath(),
348                         leafRefContext.getAbsoluteLeafRefTargetPath(), FAILED);
349                 errorsMessages.add(String.format("Invalid leafref value [%s] allowed values %s by validation of leafref"
350                         + " TARGET node: %s path of invalid LEAFREF node: %s leafRef target path: %s %s", leafRefsValue,
351                         leafRefTargetNodeValues, leaf.getNodeType(), leafRefContext.getCurrentNodePath(),
352                         leafRefContext.getAbsoluteLeafRefTargetPath(),
353                         FAILED));
354             });
355         });
356     }
357
358     private Set<Object> extractRootValues(final LeafRefContext context) {
359         return computeValues(root, context.getLeafRefNodePath().getPathFromRoot(), null);
360     }
361
362     private void validateLeafRefNodeData(final NormalizedNode<?, ?> leaf, final LeafRefContext referencingCtx,
363             final ModificationType modificationType, final YangInstanceIdentifier current) {
364         final Set<Object> values = computeValues(root, referencingCtx.getAbsoluteLeafRefTargetPath().getPathFromRoot(),
365             current);
366         if (values.contains(leaf.getValue())) {
367             LOG.debug("Operation [{}] validate data of LEAFREF node: name[{}] = value[{}] {}", modificationType,
368                 referencingCtx.getNodeName(), leaf.getValue(), SUCCESS);
369             return;
370         }
371
372         LOG.debug("Operation [{}] validate data of LEAFREF node: name[{}] = value[{}] {}", modificationType,
373             referencingCtx.getNodeName(), leaf.getValue(), FAILED);
374         LOG.debug("Invalid leafref value [{}] allowed values {} of LEAFREF node: {} leafRef target path: {}",
375             leaf.getValue(), values, leaf.getNodeType(), referencingCtx.getAbsoluteLeafRefTargetPath());
376         errorsMessages.add(String.format("Invalid leafref value [%s] allowed values %s of LEAFREF node: %s leafRef "
377                 + "target path: %s", leaf.getValue(), values, leaf.getNodeType(),
378                 referencingCtx.getAbsoluteLeafRefTargetPath()));
379     }
380
381     private Set<Object> computeValues(final NormalizedNode<?, ?> node, final Iterable<QNameWithPredicate> path,
382             final YangInstanceIdentifier current) {
383         final HashSet<Object> values = new HashSet<>();
384         addValues(values, node, path, current, QNameWithPredicate.ROOT);
385         return values;
386     }
387
388     private void addValues(final Set<Object> values, final NormalizedNode<?, ?> node,
389             final Iterable<QNameWithPredicate> path, final YangInstanceIdentifier current,
390             final QNameWithPredicate previousQName) {
391         if (node instanceof ValueNode) {
392             values.add(node.getValue());
393             return;
394         }
395         if (node instanceof LeafSetNode<?>) {
396             for (final NormalizedNode<?, ?> entry : ((LeafSetNode<?>) node).getValue()) {
397                 values.add(entry.getValue());
398             }
399             return;
400         }
401
402         final Iterator<QNameWithPredicate> iterator = path.iterator();
403         if (!iterator.hasNext()) {
404             return;
405         }
406         final QNameWithPredicate qnameWithPredicate = iterator.next();
407         final QName qName = qnameWithPredicate.getQName();
408         final PathArgument pathArgument = new NodeIdentifier(qName);
409
410         if (node instanceof DataContainerNode) {
411             final DataContainerNode<?> dataContainerNode = (DataContainerNode<?>) node;
412             final Optional<DataContainerChild<? extends PathArgument, ?>> child = dataContainerNode
413                     .getChild(pathArgument);
414
415             if (child.isPresent()) {
416                 addValues(values, child.get(), nextLevel(path), current, qnameWithPredicate);
417             } else {
418                 for (final ChoiceNode choiceNode : getChoiceNodes(dataContainerNode)) {
419                     addValues(values, choiceNode, path, current, qnameWithPredicate);
420                 }
421             }
422
423         } else if (node instanceof MapNode) {
424             final MapNode map = (MapNode) node;
425             final List<QNamePredicate> qNamePredicates = previousQName.getQNamePredicates();
426             if (qNamePredicates.isEmpty() || current == null) {
427                 final Iterable<MapEntryNode> value = map.getValue();
428                 for (final MapEntryNode mapEntryNode : value) {
429                     final Optional<DataContainerChild<? extends PathArgument, ?>> child = mapEntryNode
430                             .getChild(pathArgument);
431
432                     if (child.isPresent()) {
433                         addValues(values, child.get(), nextLevel(path), current, qnameWithPredicate);
434                     } else {
435                         for (final ChoiceNode choiceNode : getChoiceNodes(mapEntryNode)) {
436                             addValues(values, choiceNode, path, current, qnameWithPredicate);
437                         }
438                     }
439                 }
440             } else {
441                 final Map<QName, Set<?>> keyValues = new HashMap<>();
442
443                 final Iterator<QNamePredicate> predicates = qNamePredicates.iterator();
444                 while (predicates.hasNext()) {
445                     final QNamePredicate predicate = predicates.next();
446                     final QName identifier = predicate.getIdentifier();
447                     final LeafRefPath predicatePathKeyExpression = predicate.getPathKeyExpression();
448                     final Set<?> pathKeyExprValues = getPathKeyExpressionValues(predicatePathKeyExpression, current);
449
450                     keyValues.put(identifier, pathKeyExprValues);
451                 }
452
453                 for (final MapEntryNode mapEntryNode : map.getValue()) {
454                     if (isMatchingPredicate(mapEntryNode, keyValues)) {
455                         final Optional<DataContainerChild<? extends PathArgument, ?>> child = mapEntryNode
456                                 .getChild(pathArgument);
457
458                         if (child.isPresent()) {
459                             addValues(values, child.get(), nextLevel(path), current, qnameWithPredicate);
460                         } else {
461                             for (final ChoiceNode choiceNode : getChoiceNodes(mapEntryNode)) {
462                                 addValues(values, choiceNode,  path, current, qnameWithPredicate);
463                             }
464                         }
465                     }
466                 }
467             }
468         }
469     }
470
471     private static Iterable<ChoiceNode> getChoiceNodes(final DataContainerNode<?> dataContainerNode) {
472         final List<ChoiceNode> choiceNodes = new ArrayList<>();
473         for (final DataContainerChild<? extends PathArgument, ?> child : dataContainerNode.getValue()) {
474             if (child instanceof ChoiceNode) {
475                 choiceNodes.add((ChoiceNode) child);
476             }
477         }
478         return choiceNodes;
479     }
480
481     private static boolean isMatchingPredicate(final MapEntryNode mapEntryNode,
482             final Map<QName, Set<?>> allowedKeyValues) {
483         for (final Entry<QName, Object> entryKeyValue : mapEntryNode.getIdentifier().getKeyValues().entrySet()) {
484             final Set<?> allowedValues = allowedKeyValues.get(entryKeyValue.getKey());
485             if (allowedValues != null && !allowedValues.contains(entryKeyValue.getValue())) {
486                 return false;
487             }
488         }
489
490         return true;
491     }
492
493     private Set<?> getPathKeyExpressionValues(final LeafRefPath predicatePathKeyExpression,
494             final YangInstanceIdentifier current) {
495         return findParentNode(Optional.of(root), current)
496                 .map(parent -> computeValues(parent, nextLevel(predicatePathKeyExpression.getPathFromRoot()), null))
497                 .orElse(ImmutableSet.of());
498     }
499
500     private static Optional<NormalizedNode<?, ?>> findParentNode(
501             final Optional<NormalizedNode<?, ?>> root, final YangInstanceIdentifier path) {
502         Optional<NormalizedNode<?, ?>> currentNode = root;
503         final Iterator<PathArgument> pathIterator = path.getPathArguments().iterator();
504         while (pathIterator.hasNext()) {
505             final PathArgument childPathArgument = pathIterator.next();
506             if (pathIterator.hasNext() && currentNode.isPresent()) {
507                 currentNode = NormalizedNodes.getDirectChild(currentNode.get(), childPathArgument);
508             } else {
509                 return currentNode;
510             }
511         }
512         return Optional.empty();
513     }
514
515     private static Iterable<QNameWithPredicate> nextLevel(final Iterable<QNameWithPredicate> path) {
516         return Iterables.skip(path, 1);
517     }
518 }