2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.data.impl.leafref;
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;
19 import java.util.Map.Entry;
20 import java.util.Optional;
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;
45 // FIXME: 3.0.0: Rename to LeafRefValidation
46 public final class LeafRefValidatation {
48 private static final Logger LOG = LoggerFactory.getLogger(LeafRefValidatation.class);
49 private static final String FAILED = " -> FAILED";
50 private static final String SUCCESS = " -> OK";
52 private final Set<LeafRefContext> validatedLeafRefCtx = new HashSet<>();
53 private final List<String> errorsMessages = new ArrayList<>();
54 private final DataTreeCandidate tree;
56 private LeafRefValidatation(final DataTreeCandidate tree) {
60 public static void validate(final DataTreeCandidate tree, final LeafRefContext rootLeafRefCtx)
61 throws LeafRefDataValidationFailedException {
62 new LeafRefValidatation(tree).validate0(rootLeafRefCtx);
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();
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);
81 if (!errorsMessages.isEmpty()) {
82 final StringBuilder message = new StringBuilder();
84 for (final String errorMessage : errorsMessages) {
85 message.append(errorMessage);
88 throw new LeafRefDataValidationFailedException(message.toString(), errCount);
92 private void validateNode(final DataTreeCandidateNode node, final LeafRefContext referencedByCtx,
93 final LeafRefContext referencingCtx, final YangInstanceIdentifier current) {
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);
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);
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);
117 if (childReferencedByCtx != null || childReferencingCtx != null) {
118 final YangInstanceIdentifier childYangInstanceIdentifier = current.node(childNode.getIdentifier());
119 validateNode(childNode, childReferencedByCtx,childReferencingCtx, childYangInstanceIdentifier);
125 private static LeafRefContext getReferencingCtxChild(final LeafRefContext referencingCtx,
126 final DataTreeCandidateNode childNode) {
127 if (referencingCtx == null) {
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;
140 return childReferencingCtx;
143 private static LeafRefContext getReferencedByCtxChild(final LeafRefContext referencedByCtx,
144 final DataTreeCandidateNode childNode) {
145 if (referencedByCtx == null) {
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;
158 return childReferencedByCtx;
161 private void validateNodeData(final NormalizedNode<?, ?> node, final LeafRefContext referencedByCtx,
162 final LeafRefContext referencingCtx, final ModificationType modificationType,
163 final YangInstanceIdentifier current) {
165 if (node instanceof LeafNode) {
166 final LeafNode<?> leaf = (LeafNode<?>) node;
168 if (referencedByCtx != null && referencedByCtx.isReferenced()) {
169 validateLeafRefTargetNodeData(leaf, referencedByCtx, modificationType);
171 if (referencingCtx != null && referencingCtx.isReferencing()) {
172 validateLeafRefNodeData(leaf, referencingCtx, modificationType, current);
178 if (node instanceof LeafSetNode) {
179 if (referencedByCtx == null && referencingCtx == null) {
183 final LeafSetNode<?> leafSet = (LeafSetNode<?>) node;
184 for (final NormalizedNode<?, ?> leafSetEntry : leafSet.getValue()) {
185 if (referencedByCtx != null && referencedByCtx.isReferenced()) {
186 validateLeafRefTargetNodeData(leafSetEntry, referencedByCtx, modificationType);
188 if (referencingCtx != null && referencingCtx.isReferencing()) {
189 validateLeafRefNodeData(leafSetEntry, referencingCtx, modificationType, current);
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();
201 final LeafRefContext childReferencedByCtx;
202 if (referencedByCtx != null) {
203 childReferencedByCtx = findReferencedByCtxUnderChoice(referencedByCtx, qname);
205 childReferencedByCtx = null;
208 final LeafRefContext childReferencingCtx;
209 if (referencingCtx != null) {
210 childReferencingCtx = findReferencingCtxUnderChoice(referencingCtx, qname);
212 childReferencingCtx = null;
215 if (childReferencedByCtx != null || childReferencingCtx != null) {
216 final YangInstanceIdentifier childYangInstanceIdentifier = current
217 .node(dataContainerChild.getIdentifier());
218 validateNodeData(dataContainerChild, childReferencedByCtx,
219 childReferencingCtx, modificationType, childYangInstanceIdentifier);
222 } else if (node instanceof DataContainerNode) {
223 final DataContainerNode<?> dataContainerNode = (DataContainerNode<?>) node;
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()));
232 final QName qname = child.getNodeType();
233 final LeafRefContext childReferencedByCtx;
234 if (referencedByCtx != null) {
235 childReferencedByCtx = referencedByCtx.getReferencedChildByName(qname);
237 childReferencedByCtx = null;
240 final LeafRefContext childReferencingCtx;
241 if (referencingCtx != null) {
242 childReferencingCtx = referencingCtx.getReferencingChildByName(qname);
244 childReferencingCtx = null;
247 if (childReferencedByCtx != null || childReferencingCtx != null) {
248 final YangInstanceIdentifier childYangInstanceIdentifier = current
249 .node(child.getIdentifier());
250 validateNodeData(child, childReferencedByCtx,
251 childReferencingCtx, modificationType, childYangInstanceIdentifier);
254 } else if (node instanceof MapNode) {
255 final MapNode map = (MapNode) node;
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()));
266 final QName qname = mapEntryNode.getNodeType();
267 final LeafRefContext childReferencedByCtx;
268 if (referencedByCtx != null) {
269 childReferencedByCtx = referencedByCtx.getReferencedChildByName(qname);
271 childReferencedByCtx = null;
274 final LeafRefContext childReferencingCtx;
275 if (referencingCtx != null) {
276 childReferencingCtx = referencingCtx.getReferencingChildByName(qname);
278 childReferencingCtx = null;
281 if (childReferencedByCtx != null || childReferencingCtx != null) {
282 validateNodeData(mapEntryNode, childReferencedByCtx, childReferencingCtx, modificationType,
283 mapEntryYangInstanceIdentifier.node(mapEntryNode.getIdentifier()));
288 // FIXME: check UnkeyedListNode case
291 private static LeafRefContext findReferencingCtxUnderChoice(
292 final LeafRefContext referencingCtx, final QName qname) {
294 for (final LeafRefContext child : referencingCtx.getReferencingChilds().values()) {
295 final LeafRefContext referencingChildByName = child.getReferencingChildByName(qname);
296 if (referencingChildByName != null) {
297 return referencingChildByName;
304 private static LeafRefContext findReferencedByCtxUnderChoice(
305 final LeafRefContext referencedByCtx, final QName qname) {
307 for (final LeafRefContext child : referencedByCtx.getReferencedByChilds().values()) {
308 final LeafRefContext referencedByChildByName = child.getReferencedChildByName(qname);
309 if (referencedByChildByName != null) {
310 return referencedByChildByName;
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());
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()) {
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);
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(),
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());
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);
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()));
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);
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());
394 if (node instanceof LeafSetNode<?>) {
395 for (final NormalizedNode<?, ?> entry : ((LeafSetNode<?>) node).getValue()) {
396 values.add(entry.getValue());
401 final Iterator<QNameWithPredicate> iterator = path.iterator();
402 if (!iterator.hasNext()) {
405 final QNameWithPredicate qnameWithPredicate = iterator.next();
406 final QName qName = qnameWithPredicate.getQName();
407 final PathArgument pathArgument = new NodeIdentifier(qName);
409 if (node instanceof DataContainerNode) {
410 final DataContainerNode<?> dataContainerNode = (DataContainerNode<?>) node;
411 final Optional<DataContainerChild<? extends PathArgument, ?>> child = dataContainerNode
412 .getChild(pathArgument);
414 if (child.isPresent()) {
415 addValues(values, child.get(), nextLevel(path), current, qnameWithPredicate);
417 for (final ChoiceNode choiceNode : getChoiceNodes(dataContainerNode)) {
418 addValues(values, choiceNode, path, current, qnameWithPredicate);
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);
431 if (child.isPresent()) {
432 addValues(values, child.get(), nextLevel(path), current, qnameWithPredicate);
434 for (final ChoiceNode choiceNode : getChoiceNodes(mapEntryNode)) {
435 addValues(values, choiceNode, path, current, qnameWithPredicate);
440 final Map<QName, Set<?>> keyValues = new HashMap<>();
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);
449 keyValues.put(identifier, pathKeyExprValues);
452 for (final MapEntryNode mapEntryNode : map.getValue()) {
453 if (isMatchingPredicate(mapEntryNode, keyValues)) {
454 final Optional<DataContainerChild<? extends PathArgument, ?>> child = mapEntryNode
455 .getChild(pathArgument);
457 if (child.isPresent()) {
458 addValues(values, child.get(), nextLevel(path), current, qnameWithPredicate);
460 for (final ChoiceNode choiceNode : getChoiceNodes(mapEntryNode)) {
461 addValues(values, choiceNode, path, current, qnameWithPredicate);
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);
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())) {
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());
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);
511 return Optional.empty();
514 private static Iterable<QNameWithPredicate> nextLevel(final Iterable<QNameWithPredicate> path) {
515 return Iterables.skip(path, 1);