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