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.ImmutableList;
11 import com.google.common.collect.ImmutableSet;
12 import java.util.ArrayDeque;
13 import java.util.ArrayList;
14 import java.util.Collection;
15 import java.util.Deque;
16 import java.util.HashMap;
17 import java.util.HashSet;
18 import java.util.Iterator;
19 import java.util.List;
21 import java.util.Map.Entry;
22 import java.util.Optional;
24 import java.util.function.Predicate;
25 import java.util.stream.Collectors;
26 import java.util.stream.Stream;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
31 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
34 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
41 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.ValueNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
44 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
49 // FIXME: 3.0.0: Rename to LeafRefValidation
50 public final class LeafRefValidatation {
52 private static final Logger LOG = LoggerFactory.getLogger(LeafRefValidatation.class);
53 private static final String FAILED = " -> FAILED";
54 private static final String SUCCESS = " -> OK";
56 private final Set<LeafRefContext> validatedLeafRefCtx = new HashSet<>();
57 private final List<String> errorsMessages = new ArrayList<>();
58 private final NormalizedNode<?, ?> root;
60 private LeafRefValidatation(final NormalizedNode<?, ?> root) {
64 public static void validate(final DataTreeCandidate tree, final LeafRefContext rootLeafRefCtx)
65 throws LeafRefDataValidationFailedException {
66 final Optional<NormalizedNode<?, ?>> root = tree.getRootNode().getDataAfter();
67 if (root.isPresent()) {
68 new LeafRefValidatation(root.get()).validateChildren(rootLeafRefCtx, tree.getRootNode().getChildNodes());
72 private void validateChildren(final LeafRefContext rootLeafRefCtx, final Collection<DataTreeCandidateNode> children)
73 throws LeafRefDataValidationFailedException {
74 for (final DataTreeCandidateNode dataTreeCandidateNode : children) {
75 if (dataTreeCandidateNode.getModificationType() != ModificationType.UNMODIFIED) {
76 final PathArgument identifier = dataTreeCandidateNode.getIdentifier();
77 final QName childQName = identifier.getNodeType();
79 final LeafRefContext referencedByCtx = rootLeafRefCtx.getReferencedChildByName(childQName);
80 final LeafRefContext referencingCtx = rootLeafRefCtx.getReferencingChildByName(childQName);
81 if (referencedByCtx != null || referencingCtx != null) {
82 final YangInstanceIdentifier yangInstanceIdentifier = YangInstanceIdentifier
83 .create(dataTreeCandidateNode.getIdentifier());
84 validateNode(dataTreeCandidateNode, referencedByCtx, referencingCtx, yangInstanceIdentifier);
89 if (!errorsMessages.isEmpty()) {
90 final StringBuilder message = new StringBuilder();
92 for (final String errorMessage : errorsMessages) {
93 message.append(errorMessage);
96 throw new LeafRefDataValidationFailedException(message.toString(), errCount);
100 private void validateNode(final DataTreeCandidateNode node, final LeafRefContext referencedByCtx,
101 final LeafRefContext referencingCtx, final YangInstanceIdentifier current) {
103 if (node.getModificationType() == ModificationType.WRITE && node.getDataAfter().isPresent()) {
104 final Optional<NormalizedNode<?, ?>> dataAfter = node.getDataAfter();
105 final NormalizedNode<?, ?> normalizedNode = dataAfter.get();
106 validateNodeData(normalizedNode, referencedByCtx, referencingCtx,
107 node.getModificationType(), current);
111 if (node.getModificationType() == ModificationType.DELETE && referencedByCtx != null) {
112 final Optional<NormalizedNode<?, ?>> dataBefor = node.getDataBefore();
113 final NormalizedNode<?, ?> normalizedNode = dataBefor.get();
114 validateNodeData(normalizedNode, referencedByCtx, null,
115 node.getModificationType(), current);
119 final Collection<DataTreeCandidateNode> childNodes = node.getChildNodes();
120 for (final DataTreeCandidateNode childNode : childNodes) {
121 if (childNode.getModificationType() != ModificationType.UNMODIFIED) {
122 final LeafRefContext childReferencedByCtx = getReferencedByCtxChild(referencedByCtx, childNode);
123 final LeafRefContext childReferencingCtx = getReferencingCtxChild(referencingCtx, childNode);
125 if (childReferencedByCtx != null || childReferencingCtx != null) {
126 final YangInstanceIdentifier childYangInstanceIdentifier = current.node(childNode.getIdentifier());
127 validateNode(childNode, childReferencedByCtx,childReferencingCtx, childYangInstanceIdentifier);
133 private static LeafRefContext getReferencingCtxChild(final LeafRefContext referencingCtx,
134 final DataTreeCandidateNode childNode) {
135 if (referencingCtx == null) {
139 final QName childQName = childNode.getIdentifier().getNodeType();
140 LeafRefContext childReferencingCtx = referencingCtx.getReferencingChildByName(childQName);
141 if (childReferencingCtx == null) {
142 final NormalizedNode<?, ?> data = childNode.getDataAfter().get();
143 if (data instanceof MapEntryNode || data instanceof UnkeyedListEntryNode) {
144 childReferencingCtx = referencingCtx;
148 return childReferencingCtx;
151 private static LeafRefContext getReferencedByCtxChild(final LeafRefContext referencedByCtx,
152 final DataTreeCandidateNode childNode) {
153 if (referencedByCtx == null) {
157 final QName childQName = childNode.getIdentifier().getNodeType();
158 LeafRefContext childReferencedByCtx = referencedByCtx.getReferencedChildByName(childQName);
159 if (childReferencedByCtx == null) {
160 final NormalizedNode<?, ?> data = childNode.getDataAfter().get();
161 if (data instanceof MapEntryNode || data instanceof UnkeyedListEntryNode) {
162 childReferencedByCtx = referencedByCtx;
166 return childReferencedByCtx;
169 private void validateNodeData(final NormalizedNode<?, ?> node, final LeafRefContext referencedByCtx,
170 final LeafRefContext referencingCtx, final ModificationType modificationType,
171 final YangInstanceIdentifier current) {
173 if (node instanceof LeafNode) {
174 final LeafNode<?> leaf = (LeafNode<?>) node;
176 if (referencedByCtx != null && referencedByCtx.isReferenced()) {
177 validateLeafRefTargetNodeData(leaf, referencedByCtx, modificationType);
179 if (referencingCtx != null && referencingCtx.isReferencing()) {
180 validateLeafRefNodeData(leaf, referencingCtx, modificationType, current);
186 if (node instanceof LeafSetNode) {
187 if (referencedByCtx == null && referencingCtx == null) {
191 final LeafSetNode<?> leafSet = (LeafSetNode<?>) node;
192 for (final NormalizedNode<?, ?> leafSetEntry : leafSet.getValue()) {
193 if (referencedByCtx != null && referencedByCtx.isReferenced()) {
194 validateLeafRefTargetNodeData(leafSetEntry, referencedByCtx, modificationType);
196 if (referencingCtx != null && referencingCtx.isReferencing()) {
197 validateLeafRefNodeData(leafSetEntry, referencingCtx, modificationType, current);
204 if (node instanceof ChoiceNode) {
205 final ChoiceNode choice = (ChoiceNode) node;
206 for (final DataContainerChild<? extends PathArgument, ?> dataContainerChild : choice.getValue()) {
207 final QName qname = dataContainerChild.getNodeType();
209 final LeafRefContext childReferencedByCtx;
210 if (referencedByCtx != null) {
211 childReferencedByCtx = findReferencedByCtxUnderChoice(referencedByCtx, qname);
213 childReferencedByCtx = null;
216 final LeafRefContext childReferencingCtx;
217 if (referencingCtx != null) {
218 childReferencingCtx = findReferencingCtxUnderChoice(referencingCtx, qname);
220 childReferencingCtx = null;
223 if (childReferencedByCtx != null || childReferencingCtx != null) {
224 final YangInstanceIdentifier childYangInstanceIdentifier = current
225 .node(dataContainerChild.getIdentifier());
226 validateNodeData(dataContainerChild, childReferencedByCtx,
227 childReferencingCtx, modificationType, childYangInstanceIdentifier);
230 } else if (node instanceof DataContainerNode) {
231 final DataContainerNode<?> dataContainerNode = (DataContainerNode<?>) node;
233 for (final DataContainerChild<? extends PathArgument, ?> child : dataContainerNode.getValue()) {
234 if (child instanceof AugmentationNode) {
235 validateNodeData(child, referencedByCtx, referencingCtx, modificationType, current
236 .node(child.getIdentifier()));
240 final QName qname = child.getNodeType();
241 final LeafRefContext childReferencedByCtx;
242 if (referencedByCtx != null) {
243 childReferencedByCtx = referencedByCtx.getReferencedChildByName(qname);
245 childReferencedByCtx = null;
248 final LeafRefContext childReferencingCtx;
249 if (referencingCtx != null) {
250 childReferencingCtx = referencingCtx.getReferencingChildByName(qname);
252 childReferencingCtx = null;
255 if (childReferencedByCtx != null || childReferencingCtx != null) {
256 final YangInstanceIdentifier childYangInstanceIdentifier = current
257 .node(child.getIdentifier());
258 validateNodeData(child, childReferencedByCtx,
259 childReferencingCtx, modificationType, childYangInstanceIdentifier);
262 } else if (node instanceof MapNode) {
263 final MapNode map = (MapNode) node;
265 for (final MapEntryNode mapEntry : map.getValue()) {
266 final YangInstanceIdentifier mapEntryYangInstanceIdentifier = current.node(mapEntry.getIdentifier());
267 for (final DataContainerChild<? extends PathArgument, ?> mapEntryNode : mapEntry.getValue()) {
268 if (mapEntryNode instanceof AugmentationNode) {
269 validateNodeData(mapEntryNode, referencedByCtx, referencingCtx, modificationType, current
270 .node(mapEntryNode.getIdentifier()));
274 final QName qname = mapEntryNode.getNodeType();
275 final LeafRefContext childReferencedByCtx;
276 if (referencedByCtx != null) {
277 childReferencedByCtx = referencedByCtx.getReferencedChildByName(qname);
279 childReferencedByCtx = null;
282 final LeafRefContext childReferencingCtx;
283 if (referencingCtx != null) {
284 childReferencingCtx = referencingCtx.getReferencingChildByName(qname);
286 childReferencingCtx = null;
289 if (childReferencedByCtx != null || childReferencingCtx != null) {
290 validateNodeData(mapEntryNode, childReferencedByCtx, childReferencingCtx, modificationType,
291 mapEntryYangInstanceIdentifier.node(mapEntryNode.getIdentifier()));
296 // FIXME: check UnkeyedListNode case
299 private static LeafRefContext findReferencingCtxUnderChoice(
300 final LeafRefContext referencingCtx, final QName qname) {
302 for (final LeafRefContext child : referencingCtx.getReferencingChilds().values()) {
303 final LeafRefContext referencingChildByName = child.getReferencingChildByName(qname);
304 if (referencingChildByName != null) {
305 return referencingChildByName;
312 private static LeafRefContext findReferencedByCtxUnderChoice(
313 final LeafRefContext referencedByCtx, final QName qname) {
315 for (final LeafRefContext child : referencedByCtx.getReferencedByChilds().values()) {
316 final LeafRefContext referencedByChildByName = child.getReferencedChildByName(qname);
317 if (referencedByChildByName != null) {
318 return referencedByChildByName;
325 private void validateLeafRefTargetNodeData(final NormalizedNode<?, ?> leaf, final LeafRefContext
326 referencedByCtx, final ModificationType modificationType) {
327 if (!validatedLeafRefCtx.add(referencedByCtx)) {
328 LOG.trace("Operation [{}] validate data of leafref TARGET node: name[{}] = value[{}] -> SKIP: Already "
329 + "validated", modificationType, referencedByCtx.getNodeName(), leaf.getValue());
333 LOG.trace("Operation [{}] validate data of leafref TARGET node: name[{}] = value[{}]", modificationType,
334 referencedByCtx.getNodeName(), leaf.getValue());
335 final Set<LeafRefContext> leafRefs = referencedByCtx.getAllReferencedByLeafRefCtxs().values().stream()
336 .filter(LeafRefContext::isReferencing).collect(Collectors.toSet());
337 if (leafRefs.isEmpty()) {
341 final Set<Object> leafRefTargetNodeValues = extractRootValues(referencedByCtx);
342 leafRefs.forEach(leafRefContext -> {
343 extractRootValues(leafRefContext).forEach(leafRefsValue -> {
344 if (leafRefTargetNodeValues.contains(leafRefsValue)) {
345 LOG.trace("Valid leafref value [{}] {}", leafRefsValue, SUCCESS);
349 LOG.debug("Invalid leafref value [{}] allowed values {} by validation of leafref TARGET node: {} path "
350 + "of invalid LEAFREF node: {} leafRef target path: {} {}", leafRefsValue,
351 leafRefTargetNodeValues, leaf.getNodeType(), leafRefContext.getCurrentNodePath(),
352 leafRefContext.getAbsoluteLeafRefTargetPath(), FAILED);
353 errorsMessages.add(String.format("Invalid leafref value [%s] allowed values %s by validation of leafref"
354 + " TARGET node: %s path of invalid LEAFREF node: %s leafRef target path: %s %s", leafRefsValue,
355 leafRefTargetNodeValues, leaf.getNodeType(), leafRefContext.getCurrentNodePath(),
356 leafRefContext.getAbsoluteLeafRefTargetPath(),
362 private Set<Object> extractRootValues(final LeafRefContext context) {
363 return computeValues(root, createPath(context.getLeafRefNodePath()), null);
366 private void validateLeafRefNodeData(final NormalizedNode<?, ?> leaf, final LeafRefContext referencingCtx,
367 final ModificationType modificationType, final YangInstanceIdentifier current) {
368 final Set<Object> values = computeValues(root, createPath(referencingCtx.getAbsoluteLeafRefTargetPath()),
370 if (values.contains(leaf.getValue())) {
371 LOG.debug("Operation [{}] validate data of LEAFREF node: name[{}] = value[{}] {}", modificationType,
372 referencingCtx.getNodeName(), leaf.getValue(), SUCCESS);
376 LOG.debug("Operation [{}] validate data of LEAFREF node: name[{}] = value[{}] {}", modificationType,
377 referencingCtx.getNodeName(), leaf.getValue(), FAILED);
378 LOG.debug("Invalid leafref value [{}] allowed values {} of LEAFREF node: {} leafRef target path: {}",
379 leaf.getValue(), values, leaf.getNodeType(), referencingCtx.getAbsoluteLeafRefTargetPath());
380 errorsMessages.add(String.format("Invalid leafref value [%s] allowed values %s of LEAFREF node: %s leafRef "
381 + "target path: %s", leaf.getValue(), values, leaf.getNodeType(),
382 referencingCtx.getAbsoluteLeafRefTargetPath()));
385 private Set<Object> computeValues(final NormalizedNode<?, ?> node, final Deque<QNameWithPredicate> path,
386 final YangInstanceIdentifier current) {
387 final HashSet<Object> values = new HashSet<>();
388 addValues(values, node, ImmutableList.of(), path, current);
392 private void addValues(final Set<Object> values, final NormalizedNode<?, ?> node,
393 final List<QNamePredicate> nodePredicates, final Deque<QNameWithPredicate> path,
394 final YangInstanceIdentifier current) {
395 if (node instanceof ValueNode) {
396 values.add(node.getValue());
399 if (node instanceof LeafSetNode<?>) {
400 for (final NormalizedNode<?, ?> entry : ((LeafSetNode<?>) node).getValue()) {
401 values.add(entry.getValue());
406 final QNameWithPredicate next = path.peek();
411 final QName qname = next.getQName();
412 final PathArgument pathArgument = new NodeIdentifier(qname);
413 if (node instanceof DataContainerNode) {
414 final DataContainerNode<?> dataContainerNode = (DataContainerNode<?>) node;
415 final Optional<DataContainerChild<?, ?>> child = dataContainerNode.getChild(pathArgument);
416 if (child.isPresent()) {
417 addNextValues(values, child.get(), next.getQNamePredicates(), path, current);
419 for (final ChoiceNode choiceNode : getChoiceNodes(dataContainerNode)) {
420 addValues(values, choiceNode, next.getQNamePredicates(), path, current);
423 } else if (node instanceof MapNode) {
424 Stream<MapEntryNode> entries = ((MapNode) node).getValue().stream();
425 if (!nodePredicates.isEmpty() && current != null) {
426 entries = entries.filter(createMapEntryPredicate(nodePredicates, current));
429 entries.forEach(mapEntryNode -> {
430 final Optional<DataContainerChild<?, ?>> child = mapEntryNode.getChild(pathArgument);
431 if (child.isPresent()) {
432 addNextValues(values, child.get(), next.getQNamePredicates(), path, current);
434 for (final ChoiceNode choiceNode : getChoiceNodes(mapEntryNode)) {
435 addValues(values, choiceNode, next.getQNamePredicates(), path, current);
442 private Predicate<MapEntryNode> createMapEntryPredicate(final List<QNamePredicate> nodePredicates,
443 final YangInstanceIdentifier current) {
444 final Map<QName, Set<?>> keyValues = new HashMap<>();
445 for (QNamePredicate predicate : nodePredicates) {
446 keyValues.put(predicate.getIdentifier(), getPathKeyExpressionValues(predicate.getPathKeyExpression(),
451 for (final Entry<QName, Object> entryKeyValue : mapEntry.getIdentifier().getKeyValues().entrySet()) {
452 final Set<?> allowedValues = keyValues.get(entryKeyValue.getKey());
453 if (allowedValues != null && !allowedValues.contains(entryKeyValue.getValue())) {
461 private void addNextValues(final Set<Object> values, final NormalizedNode<?, ?> node,
462 final List<QNamePredicate> nodePredicates, final Deque<QNameWithPredicate> path,
463 final YangInstanceIdentifier current) {
464 final QNameWithPredicate element = path.pop();
466 addValues(values, node, nodePredicates, path, current);
472 private static Iterable<ChoiceNode> getChoiceNodes(final DataContainerNode<?> dataContainerNode) {
473 final List<ChoiceNode> choiceNodes = new ArrayList<>();
474 for (final DataContainerChild<? extends PathArgument, ?> child : dataContainerNode.getValue()) {
475 if (child instanceof ChoiceNode) {
476 choiceNodes.add((ChoiceNode) child);
482 private Set<?> getPathKeyExpressionValues(final LeafRefPath predicatePathKeyExpression,
483 final YangInstanceIdentifier current) {
484 return findParentNode(Optional.of(root), current).map(parent -> {
485 final Deque<QNameWithPredicate> path = createPath(predicatePathKeyExpression);
487 return computeValues(parent, path, null);
488 }).orElse(ImmutableSet.of());
491 private static Optional<NormalizedNode<?, ?>> findParentNode(
492 final Optional<NormalizedNode<?, ?>> root, final YangInstanceIdentifier path) {
493 Optional<NormalizedNode<?, ?>> currentNode = root;
494 final Iterator<PathArgument> pathIterator = path.getPathArguments().iterator();
495 while (pathIterator.hasNext()) {
496 final PathArgument childPathArgument = pathIterator.next();
497 if (pathIterator.hasNext() && currentNode.isPresent()) {
498 currentNode = NormalizedNodes.getDirectChild(currentNode.get(), childPathArgument);
503 return Optional.empty();
506 private static Deque<QNameWithPredicate> createPath(final LeafRefPath path) {
507 final Deque<QNameWithPredicate> ret = new ArrayDeque<>();
508 path.getPathTowardsRoot().forEach(ret::push);