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