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 NormalizedNode<?, ?> root;
56 private LeafRefValidatation(final NormalizedNode<?, ?> root) {
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());
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();
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);
85 if (!errorsMessages.isEmpty()) {
86 final StringBuilder message = new StringBuilder();
88 for (final String errorMessage : errorsMessages) {
89 message.append(errorMessage);
92 throw new LeafRefDataValidationFailedException(message.toString(), errCount);
96 private void validateNode(final DataTreeCandidateNode node, final LeafRefContext referencedByCtx,
97 final LeafRefContext referencingCtx, final YangInstanceIdentifier current) {
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);
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);
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);
121 if (childReferencedByCtx != null || childReferencingCtx != null) {
122 final YangInstanceIdentifier childYangInstanceIdentifier = current.node(childNode.getIdentifier());
123 validateNode(childNode, childReferencedByCtx,childReferencingCtx, childYangInstanceIdentifier);
129 private static LeafRefContext getReferencingCtxChild(final LeafRefContext referencingCtx,
130 final DataTreeCandidateNode childNode) {
131 if (referencingCtx == null) {
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;
144 return childReferencingCtx;
147 private static LeafRefContext getReferencedByCtxChild(final LeafRefContext referencedByCtx,
148 final DataTreeCandidateNode childNode) {
149 if (referencedByCtx == null) {
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;
162 return childReferencedByCtx;
165 private void validateNodeData(final NormalizedNode<?, ?> node, final LeafRefContext referencedByCtx,
166 final LeafRefContext referencingCtx, final ModificationType modificationType,
167 final YangInstanceIdentifier current) {
169 if (node instanceof LeafNode) {
170 final LeafNode<?> leaf = (LeafNode<?>) node;
172 if (referencedByCtx != null && referencedByCtx.isReferenced()) {
173 validateLeafRefTargetNodeData(leaf, referencedByCtx, modificationType);
175 if (referencingCtx != null && referencingCtx.isReferencing()) {
176 validateLeafRefNodeData(leaf, referencingCtx, modificationType, current);
182 if (node instanceof LeafSetNode) {
183 if (referencedByCtx == null && referencingCtx == null) {
187 final LeafSetNode<?> leafSet = (LeafSetNode<?>) node;
188 for (final NormalizedNode<?, ?> leafSetEntry : leafSet.getValue()) {
189 if (referencedByCtx != null && referencedByCtx.isReferenced()) {
190 validateLeafRefTargetNodeData(leafSetEntry, referencedByCtx, modificationType);
192 if (referencingCtx != null && referencingCtx.isReferencing()) {
193 validateLeafRefNodeData(leafSetEntry, referencingCtx, modificationType, current);
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();
205 final LeafRefContext childReferencedByCtx;
206 if (referencedByCtx != null) {
207 childReferencedByCtx = findReferencedByCtxUnderChoice(referencedByCtx, qname);
209 childReferencedByCtx = null;
212 final LeafRefContext childReferencingCtx;
213 if (referencingCtx != null) {
214 childReferencingCtx = findReferencingCtxUnderChoice(referencingCtx, qname);
216 childReferencingCtx = null;
219 if (childReferencedByCtx != null || childReferencingCtx != null) {
220 final YangInstanceIdentifier childYangInstanceIdentifier = current
221 .node(dataContainerChild.getIdentifier());
222 validateNodeData(dataContainerChild, childReferencedByCtx,
223 childReferencingCtx, modificationType, childYangInstanceIdentifier);
226 } else if (node instanceof DataContainerNode) {
227 final DataContainerNode<?> dataContainerNode = (DataContainerNode<?>) node;
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()));
236 final QName qname = child.getNodeType();
237 final LeafRefContext childReferencedByCtx;
238 if (referencedByCtx != null) {
239 childReferencedByCtx = referencedByCtx.getReferencedChildByName(qname);
241 childReferencedByCtx = null;
244 final LeafRefContext childReferencingCtx;
245 if (referencingCtx != null) {
246 childReferencingCtx = referencingCtx.getReferencingChildByName(qname);
248 childReferencingCtx = null;
251 if (childReferencedByCtx != null || childReferencingCtx != null) {
252 final YangInstanceIdentifier childYangInstanceIdentifier = current
253 .node(child.getIdentifier());
254 validateNodeData(child, childReferencedByCtx,
255 childReferencingCtx, modificationType, childYangInstanceIdentifier);
258 } else if (node instanceof MapNode) {
259 final MapNode map = (MapNode) node;
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()));
270 final QName qname = mapEntryNode.getNodeType();
271 final LeafRefContext childReferencedByCtx;
272 if (referencedByCtx != null) {
273 childReferencedByCtx = referencedByCtx.getReferencedChildByName(qname);
275 childReferencedByCtx = null;
278 final LeafRefContext childReferencingCtx;
279 if (referencingCtx != null) {
280 childReferencingCtx = referencingCtx.getReferencingChildByName(qname);
282 childReferencingCtx = null;
285 if (childReferencedByCtx != null || childReferencingCtx != null) {
286 validateNodeData(mapEntryNode, childReferencedByCtx, childReferencingCtx, modificationType,
287 mapEntryYangInstanceIdentifier.node(mapEntryNode.getIdentifier()));
292 // FIXME: check UnkeyedListNode case
295 private static LeafRefContext findReferencingCtxUnderChoice(
296 final LeafRefContext referencingCtx, final QName qname) {
298 for (final LeafRefContext child : referencingCtx.getReferencingChilds().values()) {
299 final LeafRefContext referencingChildByName = child.getReferencingChildByName(qname);
300 if (referencingChildByName != null) {
301 return referencingChildByName;
308 private static LeafRefContext findReferencedByCtxUnderChoice(
309 final LeafRefContext referencedByCtx, final QName qname) {
311 for (final LeafRefContext child : referencedByCtx.getReferencedByChilds().values()) {
312 final LeafRefContext referencedByChildByName = child.getReferencedChildByName(qname);
313 if (referencedByChildByName != null) {
314 return referencedByChildByName;
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());
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()) {
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);
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(),
358 private Set<Object> extractRootValues(final LeafRefContext context) {
359 return computeValues(root, context.getLeafRefNodePath().getPathFromRoot(), null);
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(),
366 if (values.contains(leaf.getValue())) {
367 LOG.debug("Operation [{}] validate data of LEAFREF node: name[{}] = value[{}] {}", modificationType,
368 referencingCtx.getNodeName(), leaf.getValue(), SUCCESS);
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()));
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);
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());
395 if (node instanceof LeafSetNode<?>) {
396 for (final NormalizedNode<?, ?> entry : ((LeafSetNode<?>) node).getValue()) {
397 values.add(entry.getValue());
402 final Iterator<QNameWithPredicate> iterator = path.iterator();
403 if (!iterator.hasNext()) {
406 final QNameWithPredicate qnameWithPredicate = iterator.next();
407 final QName qName = qnameWithPredicate.getQName();
408 final PathArgument pathArgument = new NodeIdentifier(qName);
410 if (node instanceof DataContainerNode) {
411 final DataContainerNode<?> dataContainerNode = (DataContainerNode<?>) node;
412 final Optional<DataContainerChild<? extends PathArgument, ?>> child = dataContainerNode
413 .getChild(pathArgument);
415 if (child.isPresent()) {
416 addValues(values, child.get(), nextLevel(path), current, qnameWithPredicate);
418 for (final ChoiceNode choiceNode : getChoiceNodes(dataContainerNode)) {
419 addValues(values, choiceNode, path, current, qnameWithPredicate);
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);
432 if (child.isPresent()) {
433 addValues(values, child.get(), nextLevel(path), current, qnameWithPredicate);
435 for (final ChoiceNode choiceNode : getChoiceNodes(mapEntryNode)) {
436 addValues(values, choiceNode, path, current, qnameWithPredicate);
441 final Map<QName, Set<?>> keyValues = new HashMap<>();
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);
450 keyValues.put(identifier, pathKeyExprValues);
453 for (final MapEntryNode mapEntryNode : map.getValue()) {
454 if (isMatchingPredicate(mapEntryNode, keyValues)) {
455 final Optional<DataContainerChild<? extends PathArgument, ?>> child = mapEntryNode
456 .getChild(pathArgument);
458 if (child.isPresent()) {
459 addValues(values, child.get(), nextLevel(path), current, qnameWithPredicate);
461 for (final ChoiceNode choiceNode : getChoiceNodes(mapEntryNode)) {
462 addValues(values, choiceNode, path, current, qnameWithPredicate);
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);
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())) {
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());
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);
512 return Optional.empty();
515 private static Iterable<QNameWithPredicate> nextLevel(final Iterable<QNameWithPredicate> path) {
516 return Iterables.skip(path, 1);