46992c260f55ce03bb2e9d0f0217f9362915c449
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / ChoiceNodeCodecContext.java
1 /*
2  * Copyright (c) 2014 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.mdsal.binding.dom.codec.impl;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11
12 import com.google.common.collect.ImmutableListMultimap;
13 import com.google.common.collect.ImmutableMap;
14 import com.google.common.collect.ImmutableMap.Builder;
15 import com.google.common.collect.ImmutableSet;
16 import com.google.common.collect.Iterables;
17 import com.google.common.collect.Lists;
18 import com.google.common.collect.MultimapBuilder.SetMultimapBuilder;
19 import com.google.common.collect.Multimaps;
20 import com.google.common.collect.SetMultimap;
21 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
22 import java.lang.reflect.Method;
23 import java.util.ArrayList;
24 import java.util.Comparator;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.LinkedList;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.Optional;
32 import java.util.Set;
33 import java.util.concurrent.ConcurrentHashMap;
34 import org.eclipse.jdt.annotation.NonNull;
35 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
36 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
37 import org.opendaylight.mdsal.binding.runtime.api.CaseRuntimeType;
38 import org.opendaylight.mdsal.binding.runtime.api.ChoiceRuntimeType;
39 import org.opendaylight.yangtools.yang.binding.DataContainer;
40 import org.opendaylight.yangtools.yang.binding.DataObject;
41 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
42 import org.opendaylight.yangtools.yang.binding.contract.Naming;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
45 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
47 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
48 import org.opendaylight.yangtools.yang.data.util.NormalizedNodeSchemaUtils;
49 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 /**
56  * This is a bit tricky. DataObject addressing does not take into account choice/case statements, and hence given:
57  *
58  * <pre>
59  *   <code>
60  *     container foo {
61  *       choice bar {
62  *         leaf baz;
63  *       }
64  *     }
65  *   </code>
66  * </pre>
67  * we will see {@code Baz extends ChildOf<Foo>}, which is how the users would address it in InstanceIdentifier terms.
68  * The implicit assumption being made is that {@code Baz} identifies a particular instantiation and hence provides
69  * unambiguous reference to an effective schema statement.
70  *
71  * <p>
72  * Unfortunately this does not quite work with groupings, as their generation has changed: we do not have interfaces
73  * that would capture grouping instantiations, hence we do not have a proper addressing point and users need to specify
74  * the interfaces generated in the grouping's definition. These can be very much ambiguous, as a {@code grouping} can be
75  * used in multiple modules independently within an {@code augment} targeting {@code choice}, as each instantiation is
76  * guaranteed to have a unique namespace -- but we do not have the appropriate instantiations of those nodes.
77  *
78  * <p>
79  * To address this issue we have a two-class lookup mechanism, which relies on the interface generated for the
80  * {@code case} statement to act as the namespace anchor bridging the nodes inside the grouping to the namespace in
81  * which they are instantiated.
82  *
83  * <p>
84  * Furthermore downstream code relies on historical mechanics, which would guess what the instantiation is, silently
85  * assuming the ambiguity is theoretical and does not occur in practice.
86  *
87  * <p>
88  * This leads to three classes of addressing, in order descending performance requirements.
89  * <ul>
90  *   <li>Direct DataObject, where we name an exact child</li>
91  *   <li>Case DataObject + Grouping DataObject</li>
92  *   <li>Grouping DataObject, which is ambiguous</li>
93  * </ul>
94  *
95  * {@link #byCaseChildClass} supports direct DataObject mapping and contains only unambiguous children, while
96  * {@link #byClass} supports indirect mapping and contains {@code case} sub-statements.
97  *
98  * {@link #ambiguousByCaseChildClass} contains ambiguous mappings, for which we end up issuing warnings. We track each
99  * ambiguous reference and issue warn once when they are encountered -- tracking warning information in
100  * {@link #ambiguousByCaseChildWarnings}.
101  */
102 final class ChoiceNodeCodecContext<D extends DataObject> extends DataContainerCodecContext<D, ChoiceRuntimeType> {
103     private static final Logger LOG = LoggerFactory.getLogger(ChoiceNodeCodecContext.class);
104
105     private final ImmutableMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangCaseChild;
106     private final ImmutableListMultimap<Class<?>, DataContainerCodecPrototype<?>> ambiguousByCaseChildClass;
107     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byCaseChildClass;
108     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byClass;
109     private final Set<Class<?>> ambiguousByCaseChildWarnings;
110
111     ChoiceNodeCodecContext(final DataContainerCodecPrototype<ChoiceRuntimeType> prototype) {
112         super(prototype);
113         final Map<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangCaseChildBuilder =
114             new HashMap<>();
115         final Map<Class<?>, DataContainerCodecPrototype<?>> byClassBuilder = new HashMap<>();
116         final SetMultimap<Class<?>, DataContainerCodecPrototype<?>> childToCase =
117             SetMultimapBuilder.hashKeys().hashSetValues().build();
118
119         // Load case statements valid in this choice and keep track of their names
120         final var choiceType = prototype.getType();
121         final var factory = prototype.getFactory();
122         final var localCases = new HashSet<JavaTypeName>();
123         for (var caseType : choiceType.validCaseChildren()) {
124             final var cazeDef = loadCase(factory, caseType);
125             localCases.add(caseType.getIdentifier());
126             byClassBuilder.put(cazeDef.getBindingClass(), cazeDef);
127
128             // Updates collection of case children
129             @SuppressWarnings("unchecked")
130             final Class<? extends DataObject> cazeCls = (Class<? extends DataObject>) cazeDef.getBindingClass();
131             for (final Class<? extends DataObject> cazeChild : getChildrenClasses(cazeCls)) {
132                 childToCase.put(cazeChild, cazeDef);
133             }
134             // Updates collection of YANG instance identifier to case
135             for (var stmt : cazeDef.getType().statement().effectiveSubstatements()) {
136                 if (stmt instanceof DataSchemaNode cazeChild) {
137                     if (cazeChild.isAugmenting()) {
138                         final AugmentationSchemaNode augment = NormalizedNodeSchemaUtils.findCorrespondingAugment(
139                             // FIXME: bad cast
140                             (DataSchemaNode) cazeDef.getType().statement(), cazeChild);
141                         if (augment != null) {
142                             byYangCaseChildBuilder.put(DataSchemaContextNode.augmentationIdentifierFrom(augment),
143                                 cazeDef);
144                             continue;
145                         }
146                     }
147                     byYangCaseChildBuilder.put(NodeIdentifier.create(cazeChild.getQName()), cazeDef);
148                 }
149             }
150         }
151         byYangCaseChild = ImmutableMap.copyOf(byYangCaseChildBuilder);
152
153         // Move unambiguous child->case mappings to byCaseChildClass, removing them from childToCase
154         final ImmutableListMultimap.Builder<Class<?>, DataContainerCodecPrototype<?>> ambiguousByCaseBuilder =
155                 ImmutableListMultimap.builder();
156         final Builder<Class<?>, DataContainerCodecPrototype<?>> unambiguousByCaseBuilder = ImmutableMap.builder();
157         for (Entry<Class<?>, Set<DataContainerCodecPrototype<?>>> e : Multimaps.asMap(childToCase).entrySet()) {
158             final Set<DataContainerCodecPrototype<?>> cases = e.getValue();
159             if (cases.size() != 1) {
160                 // Sort all possibilities by their FQCN to retain semi-predictable results
161                 final List<DataContainerCodecPrototype<?>> list = new ArrayList<>(e.getValue());
162                 list.sort(Comparator.comparing(proto -> proto.getBindingClass().getCanonicalName()));
163                 ambiguousByCaseBuilder.putAll(e.getKey(), list);
164             } else {
165                 unambiguousByCaseBuilder.put(e.getKey(), cases.iterator().next());
166             }
167         }
168         byCaseChildClass = unambiguousByCaseBuilder.build();
169
170         // Setup ambiguous tracking, if needed
171         ambiguousByCaseChildClass = ambiguousByCaseBuilder.build();
172         ambiguousByCaseChildWarnings = ambiguousByCaseChildClass.isEmpty() ? ImmutableSet.of()
173                 : ConcurrentHashMap.newKeySet();
174
175         /*
176          * Choice/Case mapping across groupings is compile-time unsafe and we therefore need to also track any
177          * CaseRuntimeTypes added to the choice in other contexts. This is necessary to discover when a case represents
178          * equivalent data in a different instantiation context.
179          *
180          * This is required due property of binding specification, that if choice is in grouping schema path location is
181          * lost, and users may use incorrect case class using copy builders.
182          */
183         final Map<Class<?>, DataContainerCodecPrototype<?>> bySubstitutionBuilder = new HashMap<>();
184         final var context = factory.getRuntimeContext();
185         for (var caseType : context.getTypes().allCaseChildren(choiceType)) {
186             final var caseName = caseType.getIdentifier();
187             if (!localCases.contains(caseName)) {
188                 // FIXME: do not rely on class loading here, the check we are performing should be possible on
189                 //        GeneratedType only -- or it can be provided by BindingRuntimeTypes -- i.e. rather than
190                 //        'allCaseChildren()' it would calculate additional mappings we can use off-the-bat.
191                 final Class<?> substitution = loadCase(context, caseType);
192
193                 search: for (final Entry<Class<?>, DataContainerCodecPrototype<?>> real : byClassBuilder.entrySet()) {
194                     if (isSubstitutionFor(substitution, real.getKey())) {
195                         bySubstitutionBuilder.put(substitution, real.getValue());
196                         break search;
197                     }
198                 }
199             }
200         }
201
202         byClassBuilder.putAll(bySubstitutionBuilder);
203         byClass = ImmutableMap.copyOf(byClassBuilder);
204     }
205
206     private static DataContainerCodecPrototype<CaseRuntimeType> loadCase(final CodecContextFactory factory,
207             final CaseRuntimeType caseType) {
208         return DataContainerCodecPrototype.from(loadCase(factory.getRuntimeContext(), caseType), caseType, factory);
209     }
210
211     private static Class<?> loadCase(final BindingRuntimeContext context, final CaseRuntimeType caseType) {
212         final var className = caseType.getIdentifier();
213         try {
214             return context.loadClass(className);
215         } catch (ClassNotFoundException e) {
216             throw new LinkageError("Failed to load class for " + className, e);
217         }
218     }
219
220     @Override
221     public WithStatus getSchema() {
222         // FIXME: Bad cast, we should be returning an EffectiveStatement perhaps?
223         return (WithStatus) getType().statement();
224     }
225
226     @SuppressWarnings("unchecked")
227     @Override
228     public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
229         final DataContainerCodecPrototype<?> child = byClass.get(childClass);
230         return (DataContainerCodecContext<C, ?>) childNonNull(child, childClass,
231             "Supplied class %s is not valid case in %s", childClass, bindingArg()).get();
232     }
233
234     @SuppressWarnings("unchecked")
235     @Override
236     public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
237             final Class<C> childClass) {
238         final DataContainerCodecPrototype<?> child = byClass.get(childClass);
239         if (child != null) {
240             return Optional.of((DataContainerCodecContext<C, ?>) child.get());
241         }
242         return Optional.empty();
243     }
244
245     Iterable<Class<?>> getCaseChildrenClasses() {
246         return Iterables.concat(byCaseChildClass.keySet(), ambiguousByCaseChildClass.keySet());
247     }
248
249     @Override
250     public NodeCodecContext yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
251         final DataContainerCodecPrototype<?> cazeProto;
252         if (arg instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
253             cazeProto = byYangCaseChild.get(new NodeIdentifier(arg.getNodeType()));
254         } else {
255             cazeProto = byYangCaseChild.get(arg);
256         }
257
258         return childNonNull(cazeProto, arg, "Argument %s is not valid child of %s", arg, getSchema()).get()
259                 .yangPathArgumentChild(arg);
260     }
261
262     @Override
263     @SuppressWarnings("unchecked")
264     @SuppressFBWarnings(value = "NP_NONNULL_RETURN_VIOLATION", justification = "See FIXME below")
265     public D deserialize(final NormalizedNode data) {
266         final ChoiceNode casted = checkDataArgument(ChoiceNode.class, data);
267         final NormalizedNode first = Iterables.getFirst(casted.body(), null);
268
269         if (first == null) {
270             // FIXME: this needs to be sorted out
271             return null;
272         }
273         final DataContainerCodecPrototype<?> caze = byYangCaseChild.get(first.getIdentifier());
274         return (D) caze.get().deserialize(data);
275     }
276
277     @Override
278     protected Object deserializeObject(final NormalizedNode normalizedNode) {
279         return deserialize(normalizedNode);
280     }
281
282     @Override
283     public PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
284         checkArgument(getDomPathArgument().equals(arg));
285         return null;
286     }
287
288     @Override
289     public YangInstanceIdentifier.PathArgument serializePathArgument(final PathArgument arg) {
290         // FIXME: check for null, since binding container is null.
291         return getDomPathArgument();
292     }
293
294     DataContainerCodecContext<?, ?> getCaseByChildClass(final @NonNull Class<? extends DataObject> type) {
295         DataContainerCodecPrototype<?> result = byCaseChildClass.get(type);
296         if (result == null) {
297             // We have not found an unambiguous result, try ambiguous ones
298             final List<DataContainerCodecPrototype<?>> inexact = ambiguousByCaseChildClass.get(type);
299             if (!inexact.isEmpty()) {
300                 result = inexact.get(0);
301                 // Issue a warning, but only once so as not to flood the logs
302                 if (ambiguousByCaseChildWarnings.add(type)) {
303                     LOG.warn("Ambiguous reference {} to child of {} resolved to {}, the first case in {} This mapping "
304                             + "is not guaranteed to be stable and is subject to variations based on runtime "
305                             + "circumstances. Please see the stack trace for hints about the source of ambiguity.",
306                             type, bindingArg(), result.getBindingClass(),
307                             Lists.transform(inexact, DataContainerCodecPrototype::getBindingClass), new Throwable());
308                 }
309             }
310         }
311
312         return childNonNull(result, type, "Class %s is not child of any cases for %s", type, bindingArg()).get();
313     }
314
315     /**
316      * Scans supplied class and returns an iterable of all data children classes.
317      *
318      * @param type
319      *            YANG Modeled Entity derived from DataContainer
320      * @return Iterable of all data children, which have YANG modeled entity
321      */
322     // FIXME: MDSAL-780: replace use of this method
323     @SuppressWarnings("unchecked")
324     private static Iterable<Class<? extends DataObject>> getChildrenClasses(final Class<? extends DataContainer> type) {
325         checkArgument(type != null, "Target type must not be null");
326         checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
327         List<Class<? extends DataObject>> ret = new LinkedList<>();
328         for (Method method : type.getMethods()) {
329             Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method, Naming.GETTER_PREFIX);
330             if (entity.isPresent()) {
331                 ret.add((Class<? extends DataObject>) entity.orElseThrow());
332             }
333         }
334         return ret;
335     }
336 }