e73a8c48e2c15da4f02811867b35c5c37aa88559
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / leafref / LeafRefValidatation.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.data.impl.leafref;
9
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;
20 import java.util.Map;
21 import java.util.Map.Entry;
22 import java.util.Optional;
23 import java.util.Set;
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;
48
49 // FIXME: 3.0.0: Rename to LeafRefValidation
50 public final class LeafRefValidatation {
51
52     private static final Logger LOG = LoggerFactory.getLogger(LeafRefValidatation.class);
53     private static final String FAILED = " -> FAILED";
54     private static final String SUCCESS = " -> OK";
55
56     private final Set<LeafRefContext> validatedLeafRefCtx = new HashSet<>();
57     private final List<String> errorsMessages = new ArrayList<>();
58     private final NormalizedNode<?, ?> root;
59
60     private LeafRefValidatation(final NormalizedNode<?, ?> root) {
61         this.root = root;
62     }
63
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());
69         }
70     }
71
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();
78
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);
85                 }
86             }
87         }
88
89         if (!errorsMessages.isEmpty()) {
90             final StringBuilder message = new StringBuilder();
91             int errCount = 0;
92             for (final String errorMessage : errorsMessages) {
93                 message.append(errorMessage);
94                 errCount++;
95             }
96             throw new LeafRefDataValidationFailedException(message.toString(), errCount);
97         }
98     }
99
100     private void validateNode(final DataTreeCandidateNode node, final LeafRefContext referencedByCtx,
101         final LeafRefContext referencingCtx, final YangInstanceIdentifier current) {
102
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);
108             return;
109         }
110
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);
116             return;
117         }
118
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);
124
125                 if (childReferencedByCtx != null || childReferencingCtx != null) {
126                     final YangInstanceIdentifier childYangInstanceIdentifier = current.node(childNode.getIdentifier());
127                     validateNode(childNode, childReferencedByCtx,childReferencingCtx, childYangInstanceIdentifier);
128                 }
129             }
130         }
131     }
132
133     private static LeafRefContext getReferencingCtxChild(final LeafRefContext referencingCtx,
134             final DataTreeCandidateNode childNode) {
135         if (referencingCtx == null) {
136             return null;
137         }
138
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;
145             }
146         }
147
148         return childReferencingCtx;
149     }
150
151     private static LeafRefContext getReferencedByCtxChild(final LeafRefContext referencedByCtx,
152             final DataTreeCandidateNode childNode) {
153         if (referencedByCtx == null) {
154             return null;
155         }
156
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;
163             }
164         }
165
166         return childReferencedByCtx;
167     }
168
169     private void validateNodeData(final NormalizedNode<?, ?> node, final LeafRefContext referencedByCtx,
170             final LeafRefContext referencingCtx, final ModificationType modificationType,
171             final YangInstanceIdentifier current) {
172
173         if (node instanceof LeafNode) {
174             final LeafNode<?> leaf = (LeafNode<?>) node;
175
176             if (referencedByCtx != null && referencedByCtx.isReferenced()) {
177                 validateLeafRefTargetNodeData(leaf, referencedByCtx, modificationType);
178             }
179             if (referencingCtx != null && referencingCtx.isReferencing()) {
180                 validateLeafRefNodeData(leaf, referencingCtx, modificationType, current);
181             }
182
183             return;
184         }
185
186         if (node instanceof LeafSetNode) {
187             if (referencedByCtx == null && referencingCtx == null) {
188                 return;
189             }
190
191             final LeafSetNode<?> leafSet = (LeafSetNode<?>) node;
192             for (final NormalizedNode<?, ?> leafSetEntry : leafSet.getValue()) {
193                 if (referencedByCtx != null && referencedByCtx.isReferenced()) {
194                     validateLeafRefTargetNodeData(leafSetEntry, referencedByCtx, modificationType);
195                 }
196                 if (referencingCtx != null && referencingCtx.isReferencing()) {
197                     validateLeafRefNodeData(leafSetEntry, referencingCtx, modificationType, current);
198                 }
199             }
200
201             return;
202         }
203
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();
208
209                 final LeafRefContext childReferencedByCtx;
210                 if (referencedByCtx != null) {
211                     childReferencedByCtx = findReferencedByCtxUnderChoice(referencedByCtx, qname);
212                 } else {
213                     childReferencedByCtx = null;
214                 }
215
216                 final LeafRefContext childReferencingCtx;
217                 if (referencingCtx != null) {
218                     childReferencingCtx = findReferencingCtxUnderChoice(referencingCtx, qname);
219                 } else {
220                     childReferencingCtx = null;
221                 }
222
223                 if (childReferencedByCtx != null || childReferencingCtx != null) {
224                     final YangInstanceIdentifier childYangInstanceIdentifier = current
225                             .node(dataContainerChild.getIdentifier());
226                     validateNodeData(dataContainerChild, childReferencedByCtx,
227                             childReferencingCtx, modificationType, childYangInstanceIdentifier);
228                 }
229             }
230         } else if (node instanceof DataContainerNode) {
231             final DataContainerNode<?> dataContainerNode = (DataContainerNode<?>) node;
232
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()));
237                     return;
238                 }
239
240                 final QName qname = child.getNodeType();
241                 final LeafRefContext childReferencedByCtx;
242                 if (referencedByCtx != null) {
243                     childReferencedByCtx = referencedByCtx.getReferencedChildByName(qname);
244                 } else {
245                     childReferencedByCtx = null;
246                 }
247
248                 final LeafRefContext childReferencingCtx;
249                 if (referencingCtx != null) {
250                     childReferencingCtx = referencingCtx.getReferencingChildByName(qname);
251                 } else {
252                     childReferencingCtx = null;
253                 }
254
255                 if (childReferencedByCtx != null || childReferencingCtx != null) {
256                     final YangInstanceIdentifier childYangInstanceIdentifier = current
257                             .node(child.getIdentifier());
258                     validateNodeData(child, childReferencedByCtx,
259                             childReferencingCtx, modificationType, childYangInstanceIdentifier);
260                 }
261             }
262         } else if (node instanceof MapNode) {
263             final MapNode map = (MapNode) node;
264
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()));
271                         return;
272                     }
273
274                     final QName qname = mapEntryNode.getNodeType();
275                     final LeafRefContext childReferencedByCtx;
276                     if (referencedByCtx != null) {
277                         childReferencedByCtx = referencedByCtx.getReferencedChildByName(qname);
278                     } else {
279                         childReferencedByCtx = null;
280                     }
281
282                     final LeafRefContext childReferencingCtx;
283                     if (referencingCtx != null) {
284                         childReferencingCtx = referencingCtx.getReferencingChildByName(qname);
285                     } else {
286                         childReferencingCtx = null;
287                     }
288
289                     if (childReferencedByCtx != null || childReferencingCtx != null) {
290                         validateNodeData(mapEntryNode, childReferencedByCtx, childReferencingCtx, modificationType,
291                                 mapEntryYangInstanceIdentifier.node(mapEntryNode.getIdentifier()));
292                     }
293                 }
294             }
295         }
296         // FIXME: check UnkeyedListNode case
297     }
298
299     private static LeafRefContext findReferencingCtxUnderChoice(
300             final LeafRefContext referencingCtx, final QName qname) {
301
302         for (final LeafRefContext child : referencingCtx.getReferencingChilds().values()) {
303             final LeafRefContext referencingChildByName = child.getReferencingChildByName(qname);
304             if (referencingChildByName != null) {
305                 return referencingChildByName;
306             }
307         }
308
309         return null;
310     }
311
312     private static LeafRefContext findReferencedByCtxUnderChoice(
313             final LeafRefContext referencedByCtx, final QName qname) {
314
315         for (final LeafRefContext child : referencedByCtx.getReferencedByChilds().values()) {
316             final LeafRefContext referencedByChildByName = child.getReferencedChildByName(qname);
317             if (referencedByChildByName != null) {
318                 return referencedByChildByName;
319             }
320         }
321
322         return null;
323     }
324
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());
330             return;
331         }
332
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()) {
338             return;
339         }
340
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);
346                     return;
347                 }
348
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(),
357                         FAILED));
358             });
359         });
360     }
361
362     private Set<Object> extractRootValues(final LeafRefContext context) {
363         return computeValues(root, createPath(context.getLeafRefNodePath()), null);
364     }
365
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()),
369             current);
370         if (values.contains(leaf.getValue())) {
371             LOG.debug("Operation [{}] validate data of LEAFREF node: name[{}] = value[{}] {}", modificationType,
372                 referencingCtx.getNodeName(), leaf.getValue(), SUCCESS);
373             return;
374         }
375
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()));
383     }
384
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);
389         return values;
390     }
391
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());
397             return;
398         }
399         if (node instanceof LeafSetNode<?>) {
400             for (final NormalizedNode<?, ?> entry : ((LeafSetNode<?>) node).getValue()) {
401                 values.add(entry.getValue());
402             }
403             return;
404         }
405
406         final QNameWithPredicate next = path.peek();
407         if (next == null) {
408             return;
409         }
410
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);
418             } else {
419                 for (final ChoiceNode choiceNode : getChoiceNodes(dataContainerNode)) {
420                     addValues(values, choiceNode, next.getQNamePredicates(), path, current);
421                 }
422             }
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));
427             }
428
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);
433                 } else {
434                     for (final ChoiceNode choiceNode : getChoiceNodes(mapEntryNode)) {
435                         addValues(values, choiceNode, next.getQNamePredicates(), path, current);
436                     }
437                 }
438             });
439         }
440     }
441
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(),
447                 current));
448         }
449
450         return mapEntry -> {
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())) {
454                     return false;
455                 }
456             }
457             return true;
458         };
459     }
460
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();
465         try {
466             addValues(values, node, nodePredicates, path, current);
467         } finally {
468             path.push(element);
469         }
470     }
471
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);
477             }
478         }
479         return choiceNodes;
480     }
481
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);
486             path.pollFirst();
487             return computeValues(parent, path, null);
488         }).orElse(ImmutableSet.of());
489     }
490
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);
499             } else {
500                 return currentNode;
501             }
502         }
503         return Optional.empty();
504     }
505
506     private static Deque<QNameWithPredicate> createPath(final LeafRefPath path) {
507         final Deque<QNameWithPredicate> ret = new ArrayDeque<>();
508         path.getPathTowardsRoot().forEach(ret::push);
509         return ret;
510     }
511 }