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.tree.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.tree.api.DataTreeCandidate;
44 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidateNode;
45 import org.opendaylight.yangtools.yang.data.tree.api.ModificationType;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
49 public final class LeafRefValidation {
50 private static final Logger LOG = LoggerFactory.getLogger(LeafRefValidation.class);
51 private static final String FAILED = " -> FAILED";
52 private static final String SUCCESS = " -> OK";
54 private final Set<LeafRefContext> validatedLeafRefCtx = new HashSet<>();
55 private final List<String> errorsMessages = new ArrayList<>();
56 private final NormalizedNode root;
58 private LeafRefValidation(final NormalizedNode root) {
62 public static void validate(final DataTreeCandidate tree, final LeafRefContext rootLeafRefCtx)
63 throws LeafRefDataValidationFailedException {
64 final var root = tree.getRootNode().getDataAfter();
65 if (root.isPresent()) {
66 new LeafRefValidation(root.orElseThrow())
67 .validateChildren(rootLeafRefCtx, tree.getRootNode().getChildNodes());
71 private void validateChildren(final LeafRefContext rootLeafRefCtx, final Collection<DataTreeCandidateNode> children)
72 throws LeafRefDataValidationFailedException {
73 for (var dataTreeCandidateNode : children) {
74 if (dataTreeCandidateNode.getModificationType() != ModificationType.UNMODIFIED) {
75 final PathArgument identifier = dataTreeCandidateNode.getIdentifier();
76 final QName childQName = identifier.getNodeType();
78 final LeafRefContext referencedByCtx = rootLeafRefCtx.getReferencedChildByName(childQName);
79 final LeafRefContext referencingCtx = rootLeafRefCtx.getReferencingChildByName(childQName);
80 if (referencedByCtx != null || referencingCtx != null) {
81 validateNode(dataTreeCandidateNode, referencedByCtx, referencingCtx,
82 YangInstanceIdentifier.create(identifier));
87 if (!errorsMessages.isEmpty()) {
88 final StringBuilder message = new StringBuilder();
90 for (var errorMessage : errorsMessages) {
91 message.append(errorMessage);
94 throw new LeafRefDataValidationFailedException(message.toString(), errCount);
98 private void validateNode(final DataTreeCandidateNode node, final LeafRefContext referencedByCtx,
99 final LeafRefContext referencingCtx, final YangInstanceIdentifier current) {
101 if (node.getModificationType() == ModificationType.WRITE && node.getDataAfter().isPresent()) {
102 validateNodeData(node.getDataAfter().orElseThrow(), referencedByCtx, referencingCtx,
103 node.getModificationType(), current);
107 if (node.getModificationType() == ModificationType.DELETE && referencedByCtx != null) {
108 validateNodeData(node.getDataBefore().orElseThrow(), referencedByCtx, null, node.getModificationType(),
113 for (var childNode : node.getChildNodes()) {
114 if (childNode.getModificationType() != ModificationType.UNMODIFIED) {
115 final LeafRefContext childReferencedByCtx = getReferencedByCtxChild(referencedByCtx, childNode);
116 final LeafRefContext childReferencingCtx = getReferencingCtxChild(referencingCtx, childNode);
118 if (childReferencedByCtx != null || childReferencingCtx != null) {
119 validateNode(childNode, childReferencedByCtx,childReferencingCtx,
120 current.node(childNode.getIdentifier()));
126 private static LeafRefContext getReferencingCtxChild(final LeafRefContext referencingCtx,
127 final DataTreeCandidateNode childNode) {
128 if (referencingCtx == null) {
132 final QName childQName = childNode.getIdentifier().getNodeType();
133 LeafRefContext childReferencingCtx = referencingCtx.getReferencingChildByName(childQName);
134 if (childReferencingCtx == null) {
135 final NormalizedNode data = childNode.getDataAfter().orElseThrow();
136 if (data instanceof MapEntryNode || data instanceof UnkeyedListEntryNode) {
137 childReferencingCtx = referencingCtx;
141 return childReferencingCtx;
144 private static LeafRefContext getReferencedByCtxChild(final LeafRefContext referencedByCtx,
145 final DataTreeCandidateNode childNode) {
146 if (referencedByCtx == null) {
150 final QName childQName = childNode.getIdentifier().getNodeType();
151 LeafRefContext childReferencedByCtx = referencedByCtx.getReferencedChildByName(childQName);
152 if (childReferencedByCtx == null) {
153 final NormalizedNode data = childNode.getDataAfter().orElseThrow();
154 if (data instanceof MapEntryNode || data instanceof UnkeyedListEntryNode) {
155 childReferencedByCtx = referencedByCtx;
159 return childReferencedByCtx;
162 private void validateNodeData(final NormalizedNode node, final LeafRefContext referencedByCtx,
163 final LeafRefContext referencingCtx, final ModificationType modificationType,
164 final YangInstanceIdentifier current) {
165 if (node instanceof LeafNode) {
166 validateLeafNodeData((LeafNode<?>) node, referencedByCtx, referencingCtx, modificationType, current);
167 } else if (node instanceof LeafSetNode) {
168 validateLeafSetNodeData((LeafSetNode<?>) node, referencedByCtx, referencingCtx, modificationType, current);
169 } else if (node instanceof ChoiceNode) {
170 validateChoiceNodeData((ChoiceNode) node, referencedByCtx, referencingCtx, modificationType, current);
171 } else if (node instanceof DataContainerNode) {
172 validateDataContainerNodeData((DataContainerNode) node, referencedByCtx, referencingCtx, modificationType,
174 } else if (node instanceof MapNode) {
175 validateMapNodeData((MapNode) node, referencedByCtx, referencingCtx, modificationType, current);
177 // FIXME: check UnkeyedListNode case
180 private void validateLeafNodeData(final LeafNode<?> node, final LeafRefContext referencedByCtx,
181 final LeafRefContext referencingCtx, final ModificationType modificationType,
182 final YangInstanceIdentifier current) {
183 if (referencedByCtx != null && referencedByCtx.isReferenced()) {
184 validateLeafRefTargetNodeData(node, referencedByCtx, modificationType);
186 if (referencingCtx != null && referencingCtx.isReferencing()) {
187 validateLeafRefNodeData(node, referencingCtx, modificationType, current);
191 private void validateLeafSetNodeData(final LeafSetNode<?> node, final LeafRefContext referencedByCtx,
192 final LeafRefContext referencingCtx, final ModificationType modificationType,
193 final YangInstanceIdentifier current) {
194 if (referencedByCtx != null || referencingCtx != null) {
195 for (final NormalizedNode leafSetEntry : node.body()) {
196 if (referencedByCtx != null && referencedByCtx.isReferenced()) {
197 validateLeafRefTargetNodeData(leafSetEntry, referencedByCtx, modificationType);
199 if (referencingCtx != null && referencingCtx.isReferencing()) {
200 validateLeafRefNodeData(leafSetEntry, referencingCtx, modificationType, current);
206 private void validateChoiceNodeData(final ChoiceNode node, final LeafRefContext referencedByCtx,
207 final LeafRefContext referencingCtx, final ModificationType modificationType,
208 final YangInstanceIdentifier current) {
209 for (final DataContainerChild child : node.body()) {
210 final QName qname = child.getIdentifier().getNodeType();
211 final LeafRefContext childReferencedByCtx = referencedByCtx == null ? null
212 : findReferencedByCtxUnderChoice(referencedByCtx, qname);
213 final LeafRefContext childReferencingCtx = referencingCtx == null ? null
214 : findReferencingCtxUnderChoice(referencingCtx, qname);
215 if (childReferencedByCtx != null || childReferencingCtx != null) {
216 validateNodeData(child, childReferencedByCtx, childReferencingCtx, modificationType,
217 current.node(child.getIdentifier()));
222 private void validateDataContainerNodeData(final DataContainerNode node, final LeafRefContext referencedByCtx,
223 final LeafRefContext referencingCtx, final ModificationType modificationType,
224 final YangInstanceIdentifier current) {
225 for (final DataContainerChild child : node.body()) {
226 if (child instanceof AugmentationNode) {
227 validateNodeData(child, referencedByCtx, referencingCtx, modificationType, current.node(
228 child.getIdentifier()));
232 validateChildNodeData(child, referencedByCtx, referencingCtx, modificationType, current);
236 private void validateMapNodeData(final MapNode node, final LeafRefContext referencedByCtx,
237 final LeafRefContext referencingCtx, final ModificationType modificationType,
238 final YangInstanceIdentifier current) {
239 for (final MapEntryNode mapEntry : node.asMap().values()) {
240 final YangInstanceIdentifier mapEntryIdentifier = current.node(mapEntry.getIdentifier());
241 for (final DataContainerChild child : mapEntry.body()) {
242 if (child instanceof AugmentationNode) {
243 validateNodeData(child, referencedByCtx, referencingCtx, modificationType, current.node(
244 child.getIdentifier()));
248 validateChildNodeData(child, referencedByCtx, referencingCtx, modificationType, mapEntryIdentifier);
253 private void validateChildNodeData(final DataContainerChild child, final LeafRefContext referencedByCtx,
254 final LeafRefContext referencingCtx, final ModificationType modificationType,
255 final YangInstanceIdentifier current) {
256 final QName qname = child.getIdentifier().getNodeType();
257 final LeafRefContext childReferencedByCtx = referencedByCtx == null ? null
258 : referencedByCtx.getReferencedChildByName(qname);
259 final LeafRefContext childReferencingCtx = referencingCtx == null ? null
260 : referencingCtx.getReferencingChildByName(qname);
261 if (childReferencedByCtx != null || childReferencingCtx != null) {
262 validateNodeData(child, childReferencedByCtx, childReferencingCtx, modificationType, current.node(
263 child.getIdentifier()));
267 private static LeafRefContext findReferencingCtxUnderChoice(final LeafRefContext referencingCtx,
269 for (final LeafRefContext child : referencingCtx.getReferencingChilds().values()) {
270 final LeafRefContext referencingChildByName = child.getReferencingChildByName(qname);
271 if (referencingChildByName != null) {
272 return referencingChildByName;
278 private static LeafRefContext findReferencedByCtxUnderChoice(final LeafRefContext referencedByCtx,
280 for (final LeafRefContext child : referencedByCtx.getReferencedByChilds().values()) {
281 final LeafRefContext referencedByChildByName = child.getReferencedChildByName(qname);
282 if (referencedByChildByName != null) {
283 return referencedByChildByName;
289 private void validateLeafRefTargetNodeData(final NormalizedNode leaf, final LeafRefContext
290 referencedByCtx, final ModificationType modificationType) {
291 if (!validatedLeafRefCtx.add(referencedByCtx)) {
292 LOG.trace("Operation [{}] validate data of leafref TARGET node: name[{}] = value[{}] -> SKIP: Already "
293 + "validated", modificationType, referencedByCtx.getNodeName(), leaf.body());
297 LOG.trace("Operation [{}] validate data of leafref TARGET node: name[{}] = value[{}]", modificationType,
298 referencedByCtx.getNodeName(), leaf.body());
299 final Set<LeafRefContext> leafRefs = referencedByCtx.getAllReferencedByLeafRefCtxs().values().stream()
300 .filter(LeafRefContext::isReferencing).collect(Collectors.toSet());
301 if (leafRefs.isEmpty()) {
305 final Set<Object> leafRefTargetNodeValues = extractRootValues(referencedByCtx);
306 leafRefs.forEach(leafRefContext -> {
307 extractRootValues(leafRefContext).forEach(leafRefsValue -> {
308 if (leafRefTargetNodeValues.contains(leafRefsValue)) {
309 LOG.trace("Valid leafref value [{}] {}", leafRefsValue, SUCCESS);
313 LOG.debug("Invalid leafref value [{}] allowed values {} by validation of leafref TARGET node: {} path "
314 + "of invalid LEAFREF node: {} leafRef target path: {} {}", leafRefsValue,
315 leafRefTargetNodeValues, leaf.getIdentifier(), leafRefContext.getCurrentNodePath(),
316 leafRefContext.getAbsoluteLeafRefTargetPath(), FAILED);
317 errorsMessages.add(String.format("Invalid leafref value [%s] allowed values %s by validation of leafref"
318 + " TARGET node: %s path of invalid LEAFREF node: %s leafRef target path: %s %s", leafRefsValue,
319 leafRefTargetNodeValues, leaf.getIdentifier(), leafRefContext.getCurrentNodePath(),
320 leafRefContext.getAbsoluteLeafRefTargetPath(),
326 private Set<Object> extractRootValues(final LeafRefContext context) {
327 return computeValues(root, createPath(context.getLeafRefNodePath()), null);
330 private void validateLeafRefNodeData(final NormalizedNode leaf, final LeafRefContext referencingCtx,
331 final ModificationType modificationType, final YangInstanceIdentifier current) {
332 final Set<Object> values = computeValues(root, createPath(referencingCtx.getAbsoluteLeafRefTargetPath()),
334 if (values.contains(leaf.body())) {
335 LOG.debug("Operation [{}] validate data of LEAFREF node: name[{}] = value[{}] {}", modificationType,
336 referencingCtx.getNodeName(), leaf.body(), SUCCESS);
340 LOG.debug("Operation [{}] validate data of LEAFREF node: name[{}] = value[{}] {}", modificationType,
341 referencingCtx.getNodeName(), leaf.body(), FAILED);
342 LOG.debug("Invalid leafref value [{}] allowed values {} of LEAFREF node: {} leafRef target path: {}",
343 leaf.body(), values, leaf.getIdentifier(), referencingCtx.getAbsoluteLeafRefTargetPath());
344 errorsMessages.add(String.format("Invalid leafref value [%s] allowed values %s of LEAFREF node: %s leafRef "
345 + "target path: %s", leaf.body(), values, leaf.getIdentifier(),
346 referencingCtx.getAbsoluteLeafRefTargetPath()));
349 private Set<Object> computeValues(final NormalizedNode node, final Deque<QNameWithPredicate> path,
350 final YangInstanceIdentifier current) {
351 final HashSet<Object> values = new HashSet<>();
352 addValues(values, node, ImmutableList.of(), path, current);
356 private void addValues(final Set<Object> values, final NormalizedNode node,
357 final List<QNamePredicate> nodePredicates, final Deque<QNameWithPredicate> path,
358 final YangInstanceIdentifier current) {
359 if (node instanceof ValueNode) {
360 values.add(node.body());
363 if (node instanceof LeafSetNode<?>) {
364 for (final NormalizedNode entry : ((LeafSetNode<?>) node).body()) {
365 values.add(entry.body());
370 final QNameWithPredicate next = path.peek();
375 final PathArgument pathArgument = new NodeIdentifier(next.getQName());
376 if (node instanceof DataContainerNode) {
377 processChildNode(values, (DataContainerNode) node, pathArgument, next.getQNamePredicates(), path, current);
378 } else if (node instanceof MapNode) {
379 Stream<MapEntryNode> entries = ((MapNode) node).body().stream();
380 if (!nodePredicates.isEmpty() && current != null) {
381 entries = entries.filter(createMapEntryPredicate(nodePredicates, current));
384 entries.forEach(entry -> processChildNode(values, entry, pathArgument, next.getQNamePredicates(), path,
389 private void processChildNode(final Set<Object> values, final DataContainerNode parent,
390 final PathArgument arg, final List<QNamePredicate> nodePredicates, final Deque<QNameWithPredicate> path,
391 final YangInstanceIdentifier current) {
392 final DataContainerChild child = parent.childByArg(arg);
394 // FIXME: YANGTOOLS-901. We have SchemaContext nearby, hence we should be able to cache how to get
395 // to the leaf with with specified QName, without having to iterate through Choices/Augmentations.
396 // That perhaps means we should not have QNameWithPredicates, but NodeIdentifierWithPredicates as
397 // the path specification.
398 for (final DataContainerChild mixin : parent.body()) {
399 if (mixin instanceof AugmentationNode || mixin instanceof ChoiceNode) {
400 addValues(values, mixin, nodePredicates, path, current);
404 addNextValues(values, child, nodePredicates, path, current);
408 private Predicate<MapEntryNode> createMapEntryPredicate(final List<QNamePredicate> nodePredicates,
409 final YangInstanceIdentifier current) {
410 final Map<QName, Set<?>> keyValues = new HashMap<>();
411 for (QNamePredicate predicate : nodePredicates) {
412 keyValues.put(predicate.getIdentifier(), getPathKeyExpressionValues(predicate.getPathKeyExpression(),
417 for (final Entry<QName, Object> entryKeyValue : mapEntry.getIdentifier().entrySet()) {
418 final Set<?> allowedValues = keyValues.get(entryKeyValue.getKey());
419 if (allowedValues != null && !allowedValues.contains(entryKeyValue.getValue())) {
427 private void addNextValues(final Set<Object> values, final NormalizedNode node,
428 final List<QNamePredicate> nodePredicates, final Deque<QNameWithPredicate> path,
429 final YangInstanceIdentifier current) {
430 final QNameWithPredicate element = path.pop();
432 addValues(values, node, nodePredicates, path, current);
438 private Set<?> getPathKeyExpressionValues(final LeafRefPath predicatePathKeyExpression,
439 final YangInstanceIdentifier current) {
440 return findParentNode(Optional.of(root), current).map(parent -> {
441 final Deque<QNameWithPredicate> path = createPath(predicatePathKeyExpression);
443 return computeValues(parent, path, null);
444 }).orElse(ImmutableSet.of());
447 private static Optional<NormalizedNode> findParentNode(
448 final Optional<NormalizedNode> root, final YangInstanceIdentifier path) {
449 Optional<NormalizedNode> currentNode = root;
450 final Iterator<PathArgument> pathIterator = path.getPathArguments().iterator();
451 while (pathIterator.hasNext()) {
452 final PathArgument childPathArgument = pathIterator.next();
453 if (pathIterator.hasNext() && currentNode.isPresent()) {
454 currentNode = NormalizedNodes.getDirectChild(currentNode.orElseThrow(), childPathArgument);
459 return Optional.empty();
462 private static Deque<QNameWithPredicate> createPath(final LeafRefPath path) {
463 final Deque<QNameWithPredicate> ret = new ArrayDeque<>();
464 path.getPathTowardsRoot().forEach(ret::push);