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 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 Optional<NormalizedNode<?, ?>> root = tree.getRootNode().getDataAfter();
65 if (root.isPresent()) {
66 new LeafRefValidation(root.get()).validateChildren(rootLeafRefCtx, tree.getRootNode().getChildNodes());
70 private void validateChildren(final LeafRefContext rootLeafRefCtx, final Collection<DataTreeCandidateNode> children)
71 throws LeafRefDataValidationFailedException {
72 for (final DataTreeCandidateNode dataTreeCandidateNode : children) {
73 if (dataTreeCandidateNode.getModificationType() != ModificationType.UNMODIFIED) {
74 final PathArgument identifier = dataTreeCandidateNode.getIdentifier();
75 final QName childQName = identifier.getNodeType();
77 final LeafRefContext referencedByCtx = rootLeafRefCtx.getReferencedChildByName(childQName);
78 final LeafRefContext referencingCtx = rootLeafRefCtx.getReferencingChildByName(childQName);
79 if (referencedByCtx != null || referencingCtx != null) {
80 validateNode(dataTreeCandidateNode, referencedByCtx, referencingCtx,
81 YangInstanceIdentifier.create(identifier));
86 if (!errorsMessages.isEmpty()) {
87 final StringBuilder message = new StringBuilder();
89 for (final String errorMessage : errorsMessages) {
90 message.append(errorMessage);
93 throw new LeafRefDataValidationFailedException(message.toString(), errCount);
97 private void validateNode(final DataTreeCandidateNode node, final LeafRefContext referencedByCtx,
98 final LeafRefContext referencingCtx, final YangInstanceIdentifier current) {
100 if (node.getModificationType() == ModificationType.WRITE && node.getDataAfter().isPresent()) {
101 validateNodeData(node.getDataAfter().get(), referencedByCtx, referencingCtx, node.getModificationType(),
106 if (node.getModificationType() == ModificationType.DELETE && referencedByCtx != null) {
107 validateNodeData(node.getDataBefore().get(), referencedByCtx, null, node.getModificationType(), current);
111 for (final DataTreeCandidateNode childNode : node.getChildNodes()) {
112 if (childNode.getModificationType() != ModificationType.UNMODIFIED) {
113 final LeafRefContext childReferencedByCtx = getReferencedByCtxChild(referencedByCtx, childNode);
114 final LeafRefContext childReferencingCtx = getReferencingCtxChild(referencingCtx, childNode);
116 if (childReferencedByCtx != null || childReferencingCtx != null) {
117 validateNode(childNode, childReferencedByCtx,childReferencingCtx,
118 current.node(childNode.getIdentifier()));
124 private static LeafRefContext getReferencingCtxChild(final LeafRefContext referencingCtx,
125 final DataTreeCandidateNode childNode) {
126 if (referencingCtx == null) {
130 final QName childQName = childNode.getIdentifier().getNodeType();
131 LeafRefContext childReferencingCtx = referencingCtx.getReferencingChildByName(childQName);
132 if (childReferencingCtx == null) {
133 final NormalizedNode<?, ?> data = childNode.getDataAfter().get();
134 if (data instanceof MapEntryNode || data instanceof UnkeyedListEntryNode) {
135 childReferencingCtx = referencingCtx;
139 return childReferencingCtx;
142 private static LeafRefContext getReferencedByCtxChild(final LeafRefContext referencedByCtx,
143 final DataTreeCandidateNode childNode) {
144 if (referencedByCtx == null) {
148 final QName childQName = childNode.getIdentifier().getNodeType();
149 LeafRefContext childReferencedByCtx = referencedByCtx.getReferencedChildByName(childQName);
150 if (childReferencedByCtx == null) {
151 final NormalizedNode<?, ?> data = childNode.getDataAfter().get();
152 if (data instanceof MapEntryNode || data instanceof UnkeyedListEntryNode) {
153 childReferencedByCtx = referencedByCtx;
157 return childReferencedByCtx;
160 private void validateNodeData(final NormalizedNode<?, ?> node, final LeafRefContext referencedByCtx,
161 final LeafRefContext referencingCtx, final ModificationType modificationType,
162 final YangInstanceIdentifier current) {
163 if (node instanceof LeafNode) {
164 validateLeafNodeData((LeafNode<?>) node, referencedByCtx, referencingCtx, modificationType, current);
165 } else if (node instanceof LeafSetNode) {
166 validateLeafSetNodeData((LeafSetNode<?>) node, referencedByCtx, referencingCtx, modificationType, current);
167 } else if (node instanceof ChoiceNode) {
168 validateChoiceNodeData((ChoiceNode) node, referencedByCtx, referencingCtx, modificationType, current);
169 } else if (node instanceof DataContainerNode) {
170 validateDataContainerNodeData((DataContainerNode<?>) node, referencedByCtx, referencingCtx,
171 modificationType, current);
172 } else if (node instanceof MapNode) {
173 validateMapNodeData((MapNode) node, referencedByCtx, referencingCtx, modificationType, current);
175 // FIXME: check UnkeyedListNode case
178 private void validateLeafNodeData(final LeafNode<?> node, final LeafRefContext referencedByCtx,
179 final LeafRefContext referencingCtx, final ModificationType modificationType,
180 final YangInstanceIdentifier current) {
181 if (referencedByCtx != null && referencedByCtx.isReferenced()) {
182 validateLeafRefTargetNodeData(node, referencedByCtx, modificationType);
184 if (referencingCtx != null && referencingCtx.isReferencing()) {
185 validateLeafRefNodeData(node, referencingCtx, modificationType, current);
189 private void validateLeafSetNodeData(final LeafSetNode<?> node, final LeafRefContext referencedByCtx,
190 final LeafRefContext referencingCtx, final ModificationType modificationType,
191 final YangInstanceIdentifier current) {
192 if (referencedByCtx != null || referencingCtx != null) {
193 for (final NormalizedNode<?, ?> leafSetEntry : node.getValue()) {
194 if (referencedByCtx != null && referencedByCtx.isReferenced()) {
195 validateLeafRefTargetNodeData(leafSetEntry, referencedByCtx, modificationType);
197 if (referencingCtx != null && referencingCtx.isReferencing()) {
198 validateLeafRefNodeData(leafSetEntry, referencingCtx, modificationType, current);
204 private void validateChoiceNodeData(final ChoiceNode node, final LeafRefContext referencedByCtx,
205 final LeafRefContext referencingCtx, final ModificationType modificationType,
206 final YangInstanceIdentifier current) {
207 for (final DataContainerChild<?, ?> child : node.getValue()) {
208 final QName qname = child.getNodeType();
209 final LeafRefContext childReferencedByCtx = referencedByCtx == null ? null
210 : findReferencedByCtxUnderChoice(referencedByCtx, qname);
211 final LeafRefContext childReferencingCtx = referencingCtx == null ? null
212 : findReferencingCtxUnderChoice(referencingCtx, qname);
213 if (childReferencedByCtx != null || childReferencingCtx != null) {
214 validateNodeData(child, childReferencedByCtx, childReferencingCtx, modificationType,
215 current.node(child.getIdentifier()));
220 private void validateDataContainerNodeData(final DataContainerNode<?> node, final LeafRefContext referencedByCtx,
221 final LeafRefContext referencingCtx, final ModificationType modificationType,
222 final YangInstanceIdentifier current) {
223 for (final DataContainerChild<?, ?> child : node.getValue()) {
224 if (child instanceof AugmentationNode) {
225 validateNodeData(child, referencedByCtx, referencingCtx, modificationType, current.node(
226 child.getIdentifier()));
230 validateChildNodeData(child, referencedByCtx, referencingCtx, modificationType, current);
234 private void validateMapNodeData(final MapNode node, final LeafRefContext referencedByCtx,
235 final LeafRefContext referencingCtx, final ModificationType modificationType,
236 final YangInstanceIdentifier current) {
237 for (final MapEntryNode mapEntry : node.getValue()) {
238 final YangInstanceIdentifier mapEntryIdentifier = current.node(mapEntry.getIdentifier());
239 for (final DataContainerChild<?, ?> child : mapEntry.getValue()) {
240 if (child instanceof AugmentationNode) {
241 validateNodeData(child, referencedByCtx, referencingCtx, modificationType, current.node(
242 child.getIdentifier()));
246 validateChildNodeData(child, referencedByCtx, referencingCtx, modificationType, mapEntryIdentifier);
251 private void validateChildNodeData(final DataContainerChild<?, ?> child, final LeafRefContext referencedByCtx,
252 final LeafRefContext referencingCtx, final ModificationType modificationType,
253 final YangInstanceIdentifier current) {
254 final QName qname = child.getNodeType();
255 final LeafRefContext childReferencedByCtx = referencedByCtx == null ? null
256 : referencedByCtx.getReferencedChildByName(qname);
257 final LeafRefContext childReferencingCtx = referencingCtx == null ? null
258 : referencingCtx.getReferencingChildByName(qname);
259 if (childReferencedByCtx != null || childReferencingCtx != null) {
260 validateNodeData(child, childReferencedByCtx, childReferencingCtx, modificationType, current.node(
261 child.getIdentifier()));
265 private static LeafRefContext findReferencingCtxUnderChoice(final LeafRefContext referencingCtx,
267 for (final LeafRefContext child : referencingCtx.getReferencingChilds().values()) {
268 final LeafRefContext referencingChildByName = child.getReferencingChildByName(qname);
269 if (referencingChildByName != null) {
270 return referencingChildByName;
276 private static LeafRefContext findReferencedByCtxUnderChoice(final LeafRefContext referencedByCtx,
278 for (final LeafRefContext child : referencedByCtx.getReferencedByChilds().values()) {
279 final LeafRefContext referencedByChildByName = child.getReferencedChildByName(qname);
280 if (referencedByChildByName != null) {
281 return referencedByChildByName;
287 private void validateLeafRefTargetNodeData(final NormalizedNode<?, ?> leaf, final LeafRefContext
288 referencedByCtx, final ModificationType modificationType) {
289 if (!validatedLeafRefCtx.add(referencedByCtx)) {
290 LOG.trace("Operation [{}] validate data of leafref TARGET node: name[{}] = value[{}] -> SKIP: Already "
291 + "validated", modificationType, referencedByCtx.getNodeName(), leaf.getValue());
295 LOG.trace("Operation [{}] validate data of leafref TARGET node: name[{}] = value[{}]", modificationType,
296 referencedByCtx.getNodeName(), leaf.getValue());
297 final Set<LeafRefContext> leafRefs = referencedByCtx.getAllReferencedByLeafRefCtxs().values().stream()
298 .filter(LeafRefContext::isReferencing).collect(Collectors.toSet());
299 if (leafRefs.isEmpty()) {
303 final Set<Object> leafRefTargetNodeValues = extractRootValues(referencedByCtx);
304 leafRefs.forEach(leafRefContext -> {
305 extractRootValues(leafRefContext).forEach(leafRefsValue -> {
306 if (leafRefTargetNodeValues.contains(leafRefsValue)) {
307 LOG.trace("Valid leafref value [{}] {}", leafRefsValue, SUCCESS);
311 LOG.debug("Invalid leafref value [{}] allowed values {} by validation of leafref TARGET node: {} path "
312 + "of invalid LEAFREF node: {} leafRef target path: {} {}", leafRefsValue,
313 leafRefTargetNodeValues, leaf.getNodeType(), leafRefContext.getCurrentNodePath(),
314 leafRefContext.getAbsoluteLeafRefTargetPath(), FAILED);
315 errorsMessages.add(String.format("Invalid leafref value [%s] allowed values %s by validation of leafref"
316 + " TARGET node: %s path of invalid LEAFREF node: %s leafRef target path: %s %s", leafRefsValue,
317 leafRefTargetNodeValues, leaf.getNodeType(), leafRefContext.getCurrentNodePath(),
318 leafRefContext.getAbsoluteLeafRefTargetPath(),
324 private Set<Object> extractRootValues(final LeafRefContext context) {
325 return computeValues(root, createPath(context.getLeafRefNodePath()), null);
328 private void validateLeafRefNodeData(final NormalizedNode<?, ?> leaf, final LeafRefContext referencingCtx,
329 final ModificationType modificationType, final YangInstanceIdentifier current) {
330 final Set<Object> values = computeValues(root, createPath(referencingCtx.getAbsoluteLeafRefTargetPath()),
332 if (values.contains(leaf.getValue())) {
333 LOG.debug("Operation [{}] validate data of LEAFREF node: name[{}] = value[{}] {}", modificationType,
334 referencingCtx.getNodeName(), leaf.getValue(), SUCCESS);
338 LOG.debug("Operation [{}] validate data of LEAFREF node: name[{}] = value[{}] {}", modificationType,
339 referencingCtx.getNodeName(), leaf.getValue(), FAILED);
340 LOG.debug("Invalid leafref value [{}] allowed values {} of LEAFREF node: {} leafRef target path: {}",
341 leaf.getValue(), values, leaf.getNodeType(), referencingCtx.getAbsoluteLeafRefTargetPath());
342 errorsMessages.add(String.format("Invalid leafref value [%s] allowed values %s of LEAFREF node: %s leafRef "
343 + "target path: %s", leaf.getValue(), values, leaf.getNodeType(),
344 referencingCtx.getAbsoluteLeafRefTargetPath()));
347 private Set<Object> computeValues(final NormalizedNode<?, ?> node, final Deque<QNameWithPredicate> path,
348 final YangInstanceIdentifier current) {
349 final HashSet<Object> values = new HashSet<>();
350 addValues(values, node, ImmutableList.of(), path, current);
354 private void addValues(final Set<Object> values, final NormalizedNode<?, ?> node,
355 final List<QNamePredicate> nodePredicates, final Deque<QNameWithPredicate> path,
356 final YangInstanceIdentifier current) {
357 if (node instanceof ValueNode) {
358 values.add(node.getValue());
361 if (node instanceof LeafSetNode<?>) {
362 for (final NormalizedNode<?, ?> entry : ((LeafSetNode<?>) node).getValue()) {
363 values.add(entry.getValue());
368 final QNameWithPredicate next = path.peek();
373 final PathArgument pathArgument = new NodeIdentifier(next.getQName());
374 if (node instanceof DataContainerNode) {
375 processChildNode(values, (DataContainerNode<?>) node, pathArgument, next.getQNamePredicates(), path,
377 } else if (node instanceof MapNode) {
378 Stream<MapEntryNode> entries = ((MapNode) node).getValue().stream();
379 if (!nodePredicates.isEmpty() && current != null) {
380 entries = entries.filter(createMapEntryPredicate(nodePredicates, current));
383 entries.forEach(entry -> processChildNode(values, entry, pathArgument, next.getQNamePredicates(), path,
388 private void processChildNode(final Set<Object> values, final DataContainerNode<?> parent,
389 final PathArgument arg, final List<QNamePredicate> nodePredicates, final Deque<QNameWithPredicate> path,
390 final YangInstanceIdentifier current) {
391 final Optional<DataContainerChild<?, ?>> child = parent.getChild(arg);
392 if (!child.isPresent()) {
393 for (final DataContainerChild<?, ?> choice : parent.getValue()) {
394 if (choice instanceof ChoiceNode) {
395 addValues(values, choice, nodePredicates, path, current);
399 addNextValues(values, child.get(), nodePredicates, path, current);
403 private Predicate<MapEntryNode> createMapEntryPredicate(final List<QNamePredicate> nodePredicates,
404 final YangInstanceIdentifier current) {
405 final Map<QName, Set<?>> keyValues = new HashMap<>();
406 for (QNamePredicate predicate : nodePredicates) {
407 keyValues.put(predicate.getIdentifier(), getPathKeyExpressionValues(predicate.getPathKeyExpression(),
412 for (final Entry<QName, Object> entryKeyValue : mapEntry.getIdentifier().getKeyValues().entrySet()) {
413 final Set<?> allowedValues = keyValues.get(entryKeyValue.getKey());
414 if (allowedValues != null && !allowedValues.contains(entryKeyValue.getValue())) {
422 private void addNextValues(final Set<Object> values, final NormalizedNode<?, ?> node,
423 final List<QNamePredicate> nodePredicates, final Deque<QNameWithPredicate> path,
424 final YangInstanceIdentifier current) {
425 final QNameWithPredicate element = path.pop();
427 addValues(values, node, nodePredicates, path, current);
433 private Set<?> getPathKeyExpressionValues(final LeafRefPath predicatePathKeyExpression,
434 final YangInstanceIdentifier current) {
435 return findParentNode(Optional.of(root), current).map(parent -> {
436 final Deque<QNameWithPredicate> path = createPath(predicatePathKeyExpression);
438 return computeValues(parent, path, null);
439 }).orElse(ImmutableSet.of());
442 private static Optional<NormalizedNode<?, ?>> findParentNode(
443 final Optional<NormalizedNode<?, ?>> root, final YangInstanceIdentifier path) {
444 Optional<NormalizedNode<?, ?>> currentNode = root;
445 final Iterator<PathArgument> pathIterator = path.getPathArguments().iterator();
446 while (pathIterator.hasNext()) {
447 final PathArgument childPathArgument = pathIterator.next();
448 if (pathIterator.hasNext() && currentNode.isPresent()) {
449 currentNode = NormalizedNodes.getDirectChild(currentNode.get(), childPathArgument);
454 return Optional.empty();
457 private static Deque<QNameWithPredicate> createPath(final LeafRefPath path) {
458 final Deque<QNameWithPredicate> ret = new ArrayDeque<>();
459 path.getPathTowardsRoot().forEach(ret::push);