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.Iterables;
11 import java.util.ArrayList;
12 import java.util.Collection;
13 import java.util.HashMap;
14 import java.util.HashSet;
15 import java.util.Iterator;
16 import java.util.List;
18 import java.util.Map.Entry;
19 import java.util.Optional;
21 import org.opendaylight.yangtools.yang.common.QName;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
25 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
27 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
28 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
34 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.ValueNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
37 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
39 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
43 public final class LeafRefValidatation {
45 private static final Logger LOG = LoggerFactory.getLogger(LeafRefValidatation.class);
46 private static final String FAILED = " -> FAILED";
47 private static final String SUCCESS = " -> OK";
49 private final Set<LeafRefContext> validatedLeafRefCtx = new HashSet<>();
50 private final List<String> errorsMessages = new ArrayList<>();
51 private final DataTreeCandidate tree;
53 private LeafRefValidatation(final DataTreeCandidate tree) {
57 public static void validate(final DataTreeCandidate tree, final LeafRefContext rootLeafRefCtx)
58 throws LeafRefDataValidationFailedException {
59 new LeafRefValidatation(tree).validate0(rootLeafRefCtx);
62 private void validate0(final LeafRefContext rootLeafRefCtx) throws LeafRefDataValidationFailedException {
63 for (final DataTreeCandidateNode dataTreeCandidateNode : tree.getRootNode().getChildNodes()) {
64 if (dataTreeCandidateNode.getModificationType() != ModificationType.UNMODIFIED) {
65 final PathArgument identifier = dataTreeCandidateNode.getIdentifier();
66 final QName childQName = identifier.getNodeType();
68 final LeafRefContext referencedByCtx = rootLeafRefCtx.getReferencedChildByName(childQName);
69 final LeafRefContext referencingCtx = rootLeafRefCtx.getReferencingChildByName(childQName);
70 if (referencedByCtx != null || referencingCtx != null) {
71 final YangInstanceIdentifier yangInstanceIdentifier = YangInstanceIdentifier
72 .create(dataTreeCandidateNode.getIdentifier());
73 validateNode(dataTreeCandidateNode, referencedByCtx, referencingCtx, yangInstanceIdentifier);
78 if (!errorsMessages.isEmpty()) {
79 final StringBuilder message = new StringBuilder();
81 for (final String errorMessage : errorsMessages) {
82 message.append(errorMessage);
85 throw new LeafRefDataValidationFailedException(message.toString(), errCount);
89 private void validateNode(final DataTreeCandidateNode node, final LeafRefContext referencedByCtx,
90 final LeafRefContext referencingCtx, final YangInstanceIdentifier current) {
92 if (node.getModificationType() == ModificationType.WRITE && node.getDataAfter().isPresent()) {
93 final Optional<NormalizedNode<?, ?>> dataAfter = node.getDataAfter();
94 final NormalizedNode<?, ?> normalizedNode = dataAfter.get();
95 validateNodeData(normalizedNode, referencedByCtx, referencingCtx,
96 node.getModificationType(), current);
100 if (node.getModificationType() == ModificationType.DELETE && referencedByCtx != null) {
101 final Optional<NormalizedNode<?, ?>> dataBefor = node.getDataBefore();
102 final NormalizedNode<?, ?> normalizedNode = dataBefor.get();
103 validateNodeData(normalizedNode, referencedByCtx, null,
104 node.getModificationType(), current);
108 final Collection<DataTreeCandidateNode> childNodes = node.getChildNodes();
109 for (final DataTreeCandidateNode childNode : childNodes) {
110 if (childNode.getModificationType() != ModificationType.UNMODIFIED) {
111 final LeafRefContext childReferencedByCtx = getReferencedByCtxChild(referencedByCtx, childNode);
112 final LeafRefContext childReferencingCtx = getReferencingCtxChild(referencingCtx, childNode);
114 if (childReferencedByCtx != null || childReferencingCtx != null) {
115 final YangInstanceIdentifier childYangInstanceIdentifier = current.node(childNode.getIdentifier());
116 validateNode(childNode, childReferencedByCtx,childReferencingCtx, childYangInstanceIdentifier);
122 private static LeafRefContext getReferencingCtxChild(final LeafRefContext referencingCtx,
123 final DataTreeCandidateNode childNode) {
124 if (referencingCtx == null) {
128 final QName childQName = childNode.getIdentifier().getNodeType();
129 LeafRefContext childReferencingCtx = referencingCtx.getReferencingChildByName(childQName);
130 if (childReferencingCtx == null) {
131 final NormalizedNode<?, ?> data = childNode.getDataAfter().get();
132 if (data instanceof MapEntryNode || data instanceof UnkeyedListEntryNode) {
133 childReferencingCtx = referencingCtx;
137 return childReferencingCtx;
140 private static LeafRefContext getReferencedByCtxChild(final LeafRefContext referencedByCtx,
141 final DataTreeCandidateNode childNode) {
142 if (referencedByCtx == null) {
146 final QName childQName = childNode.getIdentifier().getNodeType();
147 LeafRefContext childReferencedByCtx = referencedByCtx.getReferencedChildByName(childQName);
148 if (childReferencedByCtx == null) {
149 final NormalizedNode<?, ?> data = childNode.getDataAfter().get();
150 if (data instanceof MapEntryNode || data instanceof UnkeyedListEntryNode) {
151 childReferencedByCtx = referencedByCtx;
155 return childReferencedByCtx;
158 private void validateNodeData(final NormalizedNode<?, ?> node, final LeafRefContext referencedByCtx,
159 final LeafRefContext referencingCtx, final ModificationType modificationType,
160 final YangInstanceIdentifier current) {
162 if (node instanceof LeafNode) {
163 final LeafNode<?> leaf = (LeafNode<?>) node;
165 if (referencedByCtx != null && referencedByCtx.isReferenced()) {
166 validateLeafRefTargetNodeData(leaf, referencedByCtx, modificationType);
168 if (referencingCtx != null && referencingCtx.isReferencing()) {
169 validateLeafRefNodeData(leaf, referencingCtx, modificationType, current);
175 if (node instanceof LeafSetNode) {
176 if (referencedByCtx == null && referencingCtx == null) {
180 final LeafSetNode<?> leafSet = (LeafSetNode<?>) node;
181 for (final NormalizedNode<?, ?> leafSetEntry : leafSet.getValue()) {
182 if (referencedByCtx != null && referencedByCtx.isReferenced()) {
183 validateLeafRefTargetNodeData(leafSetEntry, referencedByCtx, modificationType);
185 if (referencingCtx != null && referencingCtx.isReferencing()) {
186 validateLeafRefNodeData(leafSetEntry, referencingCtx, modificationType, current);
193 if (node instanceof ChoiceNode) {
194 final ChoiceNode choice = (ChoiceNode) node;
195 for (final DataContainerChild<? extends PathArgument, ?> dataContainerChild : choice.getValue()) {
196 final QName qname = dataContainerChild.getNodeType();
198 final LeafRefContext childReferencedByCtx;
199 if (referencedByCtx != null) {
200 childReferencedByCtx = findReferencedByCtxUnderChoice(referencedByCtx, qname);
202 childReferencedByCtx = null;
205 final LeafRefContext childReferencingCtx;
206 if (referencingCtx != null) {
207 childReferencingCtx = findReferencingCtxUnderChoice(referencingCtx, qname);
209 childReferencingCtx = null;
212 if (childReferencedByCtx != null || childReferencingCtx != null) {
213 final YangInstanceIdentifier childYangInstanceIdentifier = current
214 .node(dataContainerChild.getIdentifier());
215 validateNodeData(dataContainerChild, childReferencedByCtx,
216 childReferencingCtx, modificationType, childYangInstanceIdentifier);
219 } else if (node instanceof DataContainerNode) {
220 final DataContainerNode<?> dataContainerNode = (DataContainerNode<?>) node;
222 for (final DataContainerChild<? extends PathArgument, ?> child : dataContainerNode.getValue()) {
223 final QName qname = child.getNodeType();
225 final LeafRefContext childReferencedByCtx;
226 if (referencedByCtx != null) {
227 childReferencedByCtx = referencedByCtx.getReferencedChildByName(qname);
229 childReferencedByCtx = null;
232 final LeafRefContext childReferencingCtx;
233 if (referencingCtx != null) {
234 childReferencingCtx = referencingCtx.getReferencingChildByName(qname);
236 childReferencingCtx = null;
239 if (childReferencedByCtx != null || childReferencingCtx != null) {
240 final YangInstanceIdentifier childYangInstanceIdentifier = current
241 .node(child.getIdentifier());
242 validateNodeData(child, childReferencedByCtx,
243 childReferencingCtx, modificationType, childYangInstanceIdentifier);
246 } else if (node instanceof MapNode) {
247 final MapNode map = (MapNode) node;
249 for (final MapEntryNode mapEntry : map.getValue()) {
250 final YangInstanceIdentifier mapEntryYangInstanceIdentifier = current.node(mapEntry.getIdentifier());
251 for (final DataContainerChild<? extends PathArgument, ?> mapEntryNode : mapEntry.getValue()) {
252 final QName qname = mapEntryNode.getNodeType();
254 final LeafRefContext childReferencedByCtx;
255 if (referencedByCtx != null) {
256 childReferencedByCtx = referencedByCtx.getReferencedChildByName(qname);
258 childReferencedByCtx = null;
261 final LeafRefContext childReferencingCtx;
262 if (referencingCtx != null) {
263 childReferencingCtx = referencingCtx.getReferencingChildByName(qname);
265 childReferencingCtx = null;
268 if (childReferencedByCtx != null || childReferencingCtx != null) {
269 validateNodeData(mapEntryNode, childReferencedByCtx, childReferencingCtx, modificationType,
270 mapEntryYangInstanceIdentifier.node(mapEntryNode.getIdentifier()));
275 // FIXME if (node instance of UnkeyedListNode ...
278 private static LeafRefContext findReferencingCtxUnderChoice(
279 final LeafRefContext referencingCtx, final QName qname) {
281 for (final LeafRefContext child : referencingCtx.getReferencingChilds().values()) {
282 final LeafRefContext referencingChildByName = child.getReferencingChildByName(qname);
283 if (referencingChildByName != null) {
284 return referencingChildByName;
291 private static LeafRefContext findReferencedByCtxUnderChoice(
292 final LeafRefContext referencedByCtx, final QName qname) {
294 for (final LeafRefContext child : referencedByCtx.getReferencedByChilds().values()) {
295 final LeafRefContext referencedByChildByName = child.getReferencedChildByName(qname);
296 if (referencedByChildByName != null) {
297 return referencedByChildByName;
304 private void validateLeafRefTargetNodeData(final NormalizedNode<?, ?> leaf, final LeafRefContext
305 referencedByCtx, final ModificationType modificationType) {
306 final Map<LeafRefContext, Set<?>> leafRefsValues = new HashMap<>();
307 if (validatedLeafRefCtx.contains(referencedByCtx)) {
308 leafRefTargetNodeDataLog(leaf, referencedByCtx, modificationType, leafRefsValues, null);
312 final Map<QName, LeafRefContext> allReferencedByLeafRefCtxs = referencedByCtx.getAllReferencedByLeafRefCtxs();
313 for (final LeafRefContext leafRefContext : allReferencedByLeafRefCtxs.values()) {
314 if (leafRefContext.isReferencing()) {
315 final Set<Object> values = new HashSet<>();
317 final SchemaPath leafRefNodeSchemaPath = leafRefContext.getCurrentNodePath();
318 final LeafRefPath leafRefNodePath = LeafRefUtils.schemaPathToLeafRefPath(leafRefNodeSchemaPath,
319 leafRefContext.getLeafRefContextModule());
320 final Iterable<QNameWithPredicate> pathFromRoot = leafRefNodePath.getPathFromRoot();
321 addValues(values, tree.getRootNode().getDataAfter(), pathFromRoot, null, QNameWithPredicate.ROOT);
322 leafRefsValues.put(leafRefContext, values);
326 if (!leafRefsValues.isEmpty()) {
327 final Set<Object> leafRefTargetNodeValues = new HashSet<>();
328 final SchemaPath nodeSchemaPath = referencedByCtx.getCurrentNodePath();
329 final LeafRefPath nodePath = LeafRefUtils.schemaPathToLeafRefPath(nodeSchemaPath, referencedByCtx
330 .getLeafRefContextModule());
331 addValues(leafRefTargetNodeValues, tree.getRootNode().getDataAfter(), nodePath.getPathFromRoot(), null,
332 QNameWithPredicate.ROOT);
333 leafRefTargetNodeDataLog(leaf, referencedByCtx, modificationType, leafRefsValues,
334 leafRefTargetNodeValues);
336 leafRefTargetNodeDataLog(leaf, referencedByCtx, modificationType, null, null);
338 validatedLeafRefCtx.add(referencedByCtx);
341 private void leafRefTargetNodeDataLog(final NormalizedNode<?, ?> leaf, final LeafRefContext referencedByCtx,
342 final ModificationType modificationType, final Map<LeafRefContext, Set<?>> leafRefsValues,
343 final Set<Object> leafRefTargetNodeValues) {
345 if (leafRefsValues != null && !leafRefsValues.isEmpty()) {
346 final Set<Entry<LeafRefContext, Set<?>>> entrySet = leafRefsValues.entrySet();
347 LOG.debug("Operation [{}] validate data of leafref TARGET node: name[{}] = value[{}]",
348 modificationType, referencedByCtx.getNodeName(), leaf.getValue());
349 for (final Entry<LeafRefContext, Set<?>> entry : entrySet) {
350 final LeafRefContext leafRefContext = entry.getKey();
351 final Set<?> leafRefValuesSet = entry.getValue();
352 for (final Object leafRefsValue : leafRefValuesSet) {
353 if (leafRefTargetNodeValues != null && !leafRefTargetNodeValues.contains(leafRefsValue)) {
354 LOG.debug("Invalid leafref value [{}] allowed values {} by validation of leafref TARGET node: "
355 + "{} path of invalid LEAFREF node: {} leafRef target path: {} {}", leafRefsValue,
356 leafRefTargetNodeValues, leaf.getNodeType(), leafRefContext.getCurrentNodePath(),
357 leafRefContext.getAbsoluteLeafRefTargetPath(), FAILED);
358 errorsMessages.add(String.format("Invalid leafref value [%s] allowed values %s by validation "
359 + "of leafref TARGET node: %s path of invalid LEAFREF node: %s leafRef target "
360 + "path: %s %s", leafRefsValue, leafRefTargetNodeValues, leaf.getNodeType(),
361 leafRefContext.getCurrentNodePath(), leafRefContext.getAbsoluteLeafRefTargetPath(),
364 LOG.debug("Valid leafref value [{}] {}", leafRefsValue, SUCCESS);
368 } else if (leafRefsValues != null) {
369 LOG.debug("Operation [{}] validate data of leafref TARGET node: name[{}] = value[{}] "
370 + "-> SKIP: Already validated", modificationType, referencedByCtx.getNodeName(), leaf.getValue());
374 private void validateLeafRefNodeData(final NormalizedNode<?, ?> leaf, final LeafRefContext referencingCtx,
375 final ModificationType modificationType, final YangInstanceIdentifier current) {
376 final HashSet<Object> values = new HashSet<>();
377 final LeafRefPath targetPath = referencingCtx.getAbsoluteLeafRefTargetPath();
378 final Iterable<QNameWithPredicate> pathFromRoot = targetPath.getPathFromRoot();
380 addValues(values, tree.getRootNode().getDataAfter(), pathFromRoot, current, QNameWithPredicate.ROOT);
382 if (!values.contains(leaf.getValue())) {
383 LOG.debug("Operation [{}] validate data of LEAFREF node: name[{}] = value[{}] {}",
384 modificationType, referencingCtx.getNodeName(), leaf.getValue(), FAILED);
385 LOG.debug("Invalid leafref value [{}] allowed values {} of LEAFREF node: {} leafRef target path: {}",
386 leaf.getValue(), values, leaf.getNodeType(), referencingCtx.getAbsoluteLeafRefTargetPath());
387 errorsMessages.add(String.format("Invalid leafref value [%s] allowed values %s of LEAFREF node: %s "
388 + "leafRef target path: %s", leaf.getValue(), values, leaf.getNodeType(), referencingCtx
389 .getAbsoluteLeafRefTargetPath()));
391 LOG.debug("Operation [{}] validate data of LEAFREF node: name[{}] = value[{}] {}", modificationType,
392 referencingCtx.getNodeName(), leaf.getValue(), SUCCESS);
396 private void addValues(final Set<Object> values, final Optional<? extends NormalizedNode<?, ?>> optDataNode,
397 final Iterable<QNameWithPredicate> path, final YangInstanceIdentifier current,
398 final QNameWithPredicate previousQName) {
400 if (!optDataNode.isPresent()) {
403 final NormalizedNode<?, ?> node = optDataNode.get();
404 if (node instanceof ValueNode) {
405 values.add(node.getValue());
408 if (node instanceof LeafSetNode<?>) {
409 for (final NormalizedNode<?, ?> entry : ((LeafSetNode<?>) node).getValue()) {
410 values.add(entry.getValue());
415 final Iterator<QNameWithPredicate> iterator = path.iterator();
416 if (!iterator.hasNext()) {
419 final QNameWithPredicate qnameWithPredicate = iterator.next();
420 final QName qName = qnameWithPredicate.getQName();
421 final PathArgument pathArgument = new NodeIdentifier(qName);
423 if (node instanceof DataContainerNode) {
424 final DataContainerNode<?> dataContainerNode = (DataContainerNode<?>) node;
425 final Optional<DataContainerChild<? extends PathArgument, ?>> child = dataContainerNode
426 .getChild(pathArgument);
428 if (child.isPresent()) {
429 addValues(values, child, nextLevel(path), current, qnameWithPredicate);
431 for (final ChoiceNode choiceNode : getChoiceNodes(dataContainerNode)) {
432 addValues(values, Optional.of(choiceNode), path, current,
437 } else if (node instanceof MapNode) {
438 final MapNode map = (MapNode) node;
439 final List<QNamePredicate> qNamePredicates = previousQName.getQNamePredicates();
440 if (qNamePredicates.isEmpty() || current == null) {
441 final Iterable<MapEntryNode> value = map.getValue();
442 for (final MapEntryNode mapEntryNode : value) {
443 final Optional<DataContainerChild<? extends PathArgument, ?>> child = mapEntryNode
444 .getChild(pathArgument);
446 if (child.isPresent()) {
447 addValues(values, child, nextLevel(path), current, qnameWithPredicate);
449 for (final ChoiceNode choiceNode : getChoiceNodes(mapEntryNode)) {
450 addValues(values, Optional.of(choiceNode), path, current, qnameWithPredicate);
455 final Map<QName, Set<?>> keyValues = new HashMap<>();
457 final Iterator<QNamePredicate> predicates = qNamePredicates.iterator();
458 while (predicates.hasNext()) {
459 final QNamePredicate predicate = predicates.next();
460 final QName identifier = predicate.getIdentifier();
461 final LeafRefPath predicatePathKeyExpression = predicate
462 .getPathKeyExpression();
464 final Set<?> pathKeyExprValues = getPathKeyExpressionValues(
465 predicatePathKeyExpression, current);
467 keyValues.put(identifier, pathKeyExprValues);
470 for (final MapEntryNode mapEntryNode : map.getValue()) {
471 if (isMatchingPredicate(mapEntryNode, keyValues)) {
472 final Optional<DataContainerChild<? extends PathArgument, ?>> child = mapEntryNode
473 .getChild(pathArgument);
475 if (child.isPresent()) {
476 addValues(values, child, nextLevel(path), current, qnameWithPredicate);
478 for (final ChoiceNode choiceNode : getChoiceNodes(mapEntryNode)) {
479 addValues(values, Optional.of(choiceNode), path, current, qnameWithPredicate);
488 private static Iterable<ChoiceNode> getChoiceNodes(final DataContainerNode<?> dataContainerNode) {
489 final List<ChoiceNode> choiceNodes = new ArrayList<>();
490 for (final DataContainerChild<? extends PathArgument, ?> child : dataContainerNode.getValue()) {
491 if (child instanceof ChoiceNode) {
492 choiceNodes.add((ChoiceNode) child);
498 private static boolean isMatchingPredicate(final MapEntryNode mapEntryNode,
499 final Map<QName, Set<?>> allowedKeyValues) {
500 for (final Entry<QName, Object> entryKeyValue : mapEntryNode.getIdentifier().getKeyValues().entrySet()) {
501 final Set<?> allowedValues = allowedKeyValues.get(entryKeyValue.getKey());
502 if (allowedValues != null && !allowedValues.contains(entryKeyValue.getValue())) {
510 private Set<?> getPathKeyExpressionValues(final LeafRefPath predicatePathKeyExpression,
511 final YangInstanceIdentifier current) {
513 final Optional<NormalizedNode<?, ?>> parent = findParentNode(tree.getRootNode().getDataAfter(), current);
514 final Iterable<QNameWithPredicate> predicatePathExpr = predicatePathKeyExpression.getPathFromRoot();
515 final Iterable<QNameWithPredicate> predicatePath = nextLevel(predicatePathExpr);
517 final Set<Object> values = new HashSet<>();
518 // FIXME: this null check does not look right
519 if (parent != null) {
520 addValues(values, parent, predicatePath, null, QNameWithPredicate.ROOT);
526 private static Optional<NormalizedNode<?, ?>> findParentNode(
527 final Optional<NormalizedNode<?, ?>> root, final YangInstanceIdentifier path) {
528 Optional<NormalizedNode<?, ?>> currentNode = root;
529 final Iterator<PathArgument> pathIterator = path.getPathArguments().iterator();
530 while (pathIterator.hasNext()) {
531 final PathArgument childPathArgument = pathIterator.next();
532 if (pathIterator.hasNext() && currentNode.isPresent()) {
533 currentNode = NormalizedNodes.getDirectChild(currentNode.get(), childPathArgument);
538 return Optional.empty();
541 private static Iterable<QNameWithPredicate> nextLevel(final Iterable<QNameWithPredicate> path) {
542 return Iterables.skip(path, 1);