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