Ignore empty augmentations at runtime
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / DataObjectCodecContext.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 import static com.google.common.base.Verify.verify;
12
13 import com.google.common.annotations.Beta;
14 import com.google.common.base.Throwables;
15 import com.google.common.collect.ImmutableMap;
16 import com.google.common.collect.ImmutableMap.Builder;
17 import com.google.common.collect.ImmutableSet;
18 import java.lang.invoke.MethodHandle;
19 import java.lang.invoke.MethodHandles;
20 import java.lang.invoke.MethodType;
21 import java.lang.invoke.VarHandle;
22 import java.lang.reflect.Method;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Map.Entry;
27 import java.util.Optional;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.opendaylight.mdsal.binding.dom.codec.api.IncorrectNestingException;
31 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
32 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
33 import org.opendaylight.mdsal.binding.model.api.Type;
34 import org.opendaylight.mdsal.binding.runtime.api.AugmentRuntimeType;
35 import org.opendaylight.mdsal.binding.runtime.api.AugmentableRuntimeType;
36 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
37 import org.opendaylight.mdsal.binding.runtime.api.ChoiceRuntimeType;
38 import org.opendaylight.mdsal.binding.runtime.api.CompositeRuntimeType;
39 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
40 import org.opendaylight.yangtools.yang.binding.Augmentable;
41 import org.opendaylight.yangtools.yang.binding.Augmentation;
42 import org.opendaylight.yangtools.yang.binding.DataContainer;
43 import org.opendaylight.yangtools.yang.binding.DataObject;
44 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
45 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
46 import org.opendaylight.yangtools.yang.binding.OpaqueObject;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
52 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.DistinctNodeContainer;
54 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
55 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
56 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
57 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60
61 /**
62  * This class is an implementation detail. It is public only due to technical reasons and may change at any time.
63  */
64 @Beta
65 public abstract class DataObjectCodecContext<D extends DataObject, T extends CompositeRuntimeType>
66         extends DataContainerCodecContext<D, T> {
67     private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
68     private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class,
69         DataObjectCodecContext.class, DistinctNodeContainer.class);
70     private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class,
71         DataObjectCodecContext.class, DistinctNodeContainer.class);
72     private static final VarHandle MISMATCHED_AUGMENTED;
73
74     static {
75         try {
76             MISMATCHED_AUGMENTED = MethodHandles.lookup().findVarHandle(DataObjectCodecContext.class,
77                 "mismatchedAugmented", ImmutableMap.class);
78         } catch (NoSuchFieldException | IllegalAccessException e) {
79             throw new ExceptionInInitializerError(e);
80         }
81     }
82
83     private final ImmutableMap<String, ValueNodeCodecContext> leafChild;
84     private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
85     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
86     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
87     private final ImmutableMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> augmentationByYang;
88     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> augmentationByStream;
89     private final @NonNull Class<? extends CodecDataObject<?>> generatedClass;
90     private final MethodHandle proxyConstructor;
91
92     // Note this the content of this field depends only of invariants expressed as this class's fields or
93     // BindingRuntimeContext. It is only accessed via MISMATCHED_AUGMENTED above.
94     @SuppressWarnings("unused")
95     private volatile ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> mismatchedAugmented = ImmutableMap.of();
96
97     DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
98         this(prototype, null);
99     }
100
101     DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype, final Method keyMethod) {
102         super(prototype);
103
104         final Class<D> bindingClass = getBindingClass();
105
106         final ImmutableMap<Method, ValueNodeCodecContext> tmpLeaves = factory().getLeafNodes(bindingClass,
107             getType().statement());
108         final Map<Class<? extends DataContainer>, Method> clsToMethod =
109             BindingReflections.getChildrenClassToMethod(bindingClass);
110
111         final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
112         final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
113         final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
114
115         // Adds leaves to mapping
116         final Builder<String, ValueNodeCodecContext> leafChildBuilder =
117                 ImmutableMap.builderWithExpectedSize(tmpLeaves.size());
118         for (final ValueNodeCodecContext leaf : tmpLeaves.values()) {
119             leafChildBuilder.put(leaf.getSchema().getQName().getLocalName(), leaf);
120             byYangBuilder.put(leaf.getDomPathArgument(), leaf);
121         }
122         this.leafChild = leafChildBuilder.build();
123
124         final Map<Method, Class<?>> tmpDataObjects = new HashMap<>();
125         for (final Entry<Class<? extends DataContainer>, Method> childDataObj : clsToMethod.entrySet()) {
126             final Method method = childDataObj.getValue();
127             verify(!method.isDefault(), "Unexpected default method %s in %s", method, bindingClass);
128
129             final Class<? extends DataContainer> retClass = childDataObj.getKey();
130             if (OpaqueObject.class.isAssignableFrom(retClass)) {
131                 // Filter OpaqueObjects, they are not containers
132                 continue;
133             }
134
135             final DataContainerCodecPrototype<?> childProto = loadChildPrototype(retClass);
136             final Class<?> childClass = childProto.getBindingClass();
137             tmpDataObjects.put(method, childClass);
138             byStreamClassBuilder.put(childClass, childProto);
139             byYangBuilder.put(childProto.getYangArg(), childProto);
140
141             // FIXME: It really feels like we should be specializing DataContainerCodecPrototype so as to ditch
142             //        createInstance() and then we could do an instanceof check instead.
143             if (childProto.getType() instanceof ChoiceRuntimeType) {
144                 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
145                 for (final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
146                     byBindingArgClassBuilder.put(cazeChild, childProto);
147                 }
148             }
149         }
150
151         this.byYang = ImmutableMap.copyOf(byYangBuilder);
152         this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
153
154         // Slight footprint optimization: we do not want to copy byStreamClass, as that would force its entrySet view
155         // to be instantiated. Furthermore the two maps can easily end up being equal -- hence we can reuse
156         // byStreamClass for the purposes of both.
157         byBindingArgClassBuilder.putAll(byStreamClassBuilder);
158         this.byBindingArgClass = byStreamClassBuilder.equals(byBindingArgClassBuilder) ? this.byStreamClass
159                 : ImmutableMap.copyOf(byBindingArgClassBuilder);
160
161         final List<AugmentRuntimeType> possibleAugmentations;
162         if (Augmentable.class.isAssignableFrom(bindingClass)) {
163             // Verify we have the appropriate backing runtimeType
164             final var type = getType();
165             verify(type instanceof AugmentableRuntimeType, "Unexpected type %s backing augmenable %s", type,
166                 bindingClass);
167             possibleAugmentations = ((AugmentableRuntimeType) type).augments();
168             generatedClass = CodecDataObjectGenerator.generateAugmentable(prototype.getFactory().getLoader(),
169                 bindingClass, tmpLeaves, tmpDataObjects, keyMethod);
170         } else {
171             possibleAugmentations = List.of();
172             generatedClass = CodecDataObjectGenerator.generate(prototype.getFactory().getLoader(), bindingClass,
173                 tmpLeaves, tmpDataObjects, keyMethod);
174         }
175
176         // Iterate over all possible augmentations, indexing them as needed
177         final Map<PathArgument, DataContainerCodecPrototype<?>> augByYang = new HashMap<>();
178         final Map<Class<?>, DataContainerCodecPrototype<?>> augByStream = new HashMap<>();
179         for (final AugmentRuntimeType augment : possibleAugmentations) {
180             final DataContainerCodecPrototype<?> augProto = loadAugmentPrototype(augment);
181             if (augProto != null) {
182                 final PathArgument augYangArg = augProto.getYangArg();
183                 if (augByYang.putIfAbsent(augYangArg, augProto) == null) {
184                     LOG.trace("Discovered new YANG mapping {} -> {} in {}", augYangArg, augProto, this);
185                 }
186                 final Class<?> augBindingClass = augProto.getBindingClass();
187                 if (augByStream.putIfAbsent(augBindingClass, augProto) == null) {
188                     LOG.trace("Discovered new class mapping {} -> {} in {}", augBindingClass, augProto, this);
189                 }
190             }
191         }
192         augmentationByYang = ImmutableMap.copyOf(augByYang);
193         augmentationByStream = ImmutableMap.copyOf(augByStream);
194
195         final MethodHandle ctor;
196         try {
197             ctor = MethodHandles.publicLookup().findConstructor(generatedClass, CONSTRUCTOR_TYPE);
198         } catch (NoSuchMethodException | IllegalAccessException e) {
199             throw new LinkageError("Failed to find contructor for class " + generatedClass, e);
200         }
201
202         proxyConstructor = ctor.asType(DATAOBJECT_TYPE);
203     }
204
205     @Override
206     public final WithStatus getSchema() {
207         // FIXME: Bad cast, we should be returning an EffectiveStatement perhaps?
208         return (WithStatus) getType().statement();
209     }
210
211     @Override
212     @SuppressWarnings("unchecked")
213     public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
214         return (DataContainerCodecContext<C, ?>) childNonNull(streamChildPrototype(childClass), childClass,
215             "Child %s is not valid child of %s", getBindingClass(), childClass).get();
216     }
217
218     private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
219         final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
220         if (childProto != null) {
221             return childProto;
222         }
223         if (Augmentation.class.isAssignableFrom(childClass)) {
224             return augmentationByClass(childClass);
225         }
226         return null;
227     }
228
229     @SuppressWarnings("unchecked")
230     @Override
231     public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
232             final Class<C> childClass) {
233         final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
234         if (childProto != null) {
235             return Optional.of((DataContainerCodecContext<C, ?>) childProto.get());
236         }
237         return Optional.empty();
238     }
239
240     @Override
241     public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
242             final List<YangInstanceIdentifier.PathArgument> builder) {
243
244         final Class<? extends DataObject> argType = arg.getType();
245         DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
246         if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
247             ctxProto = augmentationByClass(argType);
248         }
249         final DataContainerCodecContext<?, ?> context = childNonNull(ctxProto, argType,
250             "Class %s is not valid child of %s", argType, getBindingClass()).get();
251         if (context instanceof ChoiceNodeCodecContext) {
252             final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
253             choice.addYangPathArgument(arg, builder);
254
255             final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
256             final Class<? extends DataObject> type = arg.getType();
257             final DataContainerCodecContext<?, ?> caze;
258             if (caseType.isPresent()) {
259                 // Non-ambiguous addressing this should not pose any problems
260                 caze = choice.streamChild(caseType.get());
261             } else {
262                 caze = choice.getCaseByChildClass(type);
263             }
264
265             caze.addYangPathArgument(arg, builder);
266             return caze.bindingPathArgumentChild(arg, builder);
267         }
268         context.addYangPathArgument(arg, builder);
269         return context;
270     }
271
272     @Override
273     public NodeCodecContext yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
274         final NodeContextSupplier childSupplier;
275         if (arg instanceof NodeIdentifierWithPredicates) {
276             childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
277         } else if (arg instanceof AugmentationIdentifier) {
278             childSupplier = augmentationByYang.get(arg);
279         } else {
280             childSupplier = byYang.get(arg);
281         }
282
283         return childNonNull(childSupplier, arg, "Argument %s is not valid child of %s", arg, getSchema()).get();
284     }
285
286     protected final ValueNodeCodecContext getLeafChild(final String name) {
287         final ValueNodeCodecContext value = leafChild.get(name);
288         if (value == null) {
289             throw IncorrectNestingException.create("Leaf %s is not valid for %s", name, getBindingClass());
290         }
291         return value;
292     }
293
294     private DataContainerCodecPrototype<?> loadChildPrototype(final Class<? extends DataContainer> childClass) {
295         final var type = getType();
296         final var child = childNonNull(type.bindingChild(JavaTypeName.create(childClass)), childClass,
297             "Node %s does not have child named %s", type, childClass);
298
299         return DataContainerCodecPrototype.from(createBindingArg(childClass, child.statement()),
300             (CompositeRuntimeType) child, factory());
301     }
302
303     // FIXME: MDSAL-697: move this method into BindingRuntimeContext
304     //                   This method is only called from loadChildPrototype() and exists only to be overridden by
305     //                   CaseNodeCodecContext. Since we are providing childClass and our schema to BindingRuntimeContext
306     //                   and receiving childSchema from it via findChildSchemaDefinition, we should be able to receive
307     //                   the equivalent of Map.Entry<Item, DataSchemaNode>, along with the override we create here. One
308     //                   more input we may need to provide is our bindingClass().
309     @SuppressWarnings("unchecked")
310     Item<?> createBindingArg(final Class<?> childClass, final EffectiveStatement<?, ?> childSchema) {
311         return Item.of((Class<? extends DataObject>) childClass);
312     }
313
314     private @Nullable DataContainerCodecPrototype<?> augmentationByClass(final @NonNull Class<?> childClass) {
315         final DataContainerCodecPrototype<?> childProto = augmentationByStream.get(childClass);
316         return childProto != null ? childProto : mismatchedAugmentationByClass(childClass);
317     }
318
319     private @Nullable DataContainerCodecPrototype<?> mismatchedAugmentationByClass(final @NonNull Class<?> childClass) {
320         /*
321          * It is potentially mismatched valid augmentation - we look up equivalent augmentation using reflection
322          * and walk all stream child and compare augmentations classes if they are equivalent. When we find a match
323          * we'll cache it so we do not need to perform reflection operations again.
324          */
325         final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> local =
326                 (ImmutableMap<Class<?>, DataContainerCodecPrototype<?>>) MISMATCHED_AUGMENTED.getAcquire(this);
327         final DataContainerCodecPrototype<?> mismatched = local.get(childClass);
328         return mismatched != null ? mismatched : loadMismatchedAugmentation(local, childClass);
329
330     }
331
332     private @Nullable DataContainerCodecPrototype<?> loadMismatchedAugmentation(
333             final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> oldMismatched,
334             final @NonNull Class<?> childClass) {
335         @SuppressWarnings("rawtypes")
336         final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
337         // Do not bother with proposals which are not augmentations of our class, or do not match what the runtime
338         // context would load.
339         if (getBindingClass().equals(augTarget) && belongsToRuntimeContext(childClass)) {
340             for (final DataContainerCodecPrototype<?> realChild : augmentationByStream.values()) {
341                 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
342                         && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
343                     return cacheMismatched(oldMismatched, childClass, realChild);
344                 }
345             }
346         }
347         LOG.trace("Failed to resolve {} as a valid augmentation in {}", childClass, this);
348         return null;
349     }
350
351     private @NonNull DataContainerCodecPrototype<?> cacheMismatched(
352             final @NonNull ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> oldMismatched,
353             final @NonNull Class<?> childClass, final @NonNull DataContainerCodecPrototype<?> prototype) {
354
355         ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> expected = oldMismatched;
356         while (true) {
357             final Map<Class<?>, DataContainerCodecPrototype<?>> newMismatched =
358                     ImmutableMap.<Class<?>, DataContainerCodecPrototype<?>>builderWithExpectedSize(expected.size() + 1)
359                         .putAll(expected)
360                         .put(childClass, prototype)
361                         .build();
362
363             final var witness = (ImmutableMap<Class<?>, DataContainerCodecPrototype<?>>)
364                 MISMATCHED_AUGMENTED.compareAndExchangeRelease(this, expected, newMismatched);
365             if (witness == expected) {
366                 LOG.trace("Cached mismatched augmentation {} -> {} in {}", childClass, prototype, this);
367                 return prototype;
368             }
369
370             expected = witness;
371             final DataContainerCodecPrototype<?> existing = expected.get(childClass);
372             if (existing != null) {
373                 LOG.trace("Using raced mismatched augmentation {} -> {} in {}", childClass, existing, this);
374                 return existing;
375             }
376         }
377     }
378
379     private boolean belongsToRuntimeContext(final Class<?> cls) {
380         final BindingRuntimeContext ctx = factory().getRuntimeContext();
381         final Class<?> loaded;
382         try {
383             loaded = ctx.loadClass(Type.of(cls));
384         } catch (ClassNotFoundException e) {
385             LOG.debug("Proposed {} cannot be loaded in {}", cls, ctx, e);
386             return false;
387         }
388         return cls.equals(loaded);
389     }
390
391     private @Nullable DataContainerCodecPrototype<?> loadAugmentPrototype(final AugmentRuntimeType augment) {
392         // FIXME: in face of deviations this code should be looking at declared view, i.e. all possibilities at augment
393         //        declaration site
394         final var possibleChildren = augment.statement()
395             .streamEffectiveSubstatements(SchemaTreeEffectiveStatement.class)
396             .map(SchemaTreeEffectiveStatement::getIdentifier)
397             .collect(ImmutableSet.toImmutableSet());
398         if (possibleChildren.isEmpty()) {
399             return null;
400         }
401
402         final var factory = factory();
403         final GeneratedType javaType = augment.javaType();
404         final Class<? extends Augmentation<?>> augClass;
405         try {
406             augClass = factory.getRuntimeContext().loadClass(javaType);
407         } catch (final ClassNotFoundException e) {
408             throw new IllegalStateException(
409                 "RuntimeContext references type " + javaType + " but failed to load its class", e);
410         }
411
412         return DataContainerCodecPrototype.from(augClass, new AugmentationIdentifier(possibleChildren), augment,
413             factory);
414     }
415
416     @SuppressWarnings("checkstyle:illegalCatch")
417     protected final @NonNull D createBindingProxy(final DistinctNodeContainer<?, ?> node) {
418         try {
419             return (D) proxyConstructor.invokeExact(this, node);
420         } catch (final Throwable e) {
421             Throwables.throwIfUnchecked(e);
422             throw new IllegalStateException(e);
423         }
424     }
425
426     @SuppressWarnings("unchecked")
427     Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
428             final DistinctNodeContainer<PathArgument, NormalizedNode> data) {
429
430         @SuppressWarnings("rawtypes")
431         final Map map = new HashMap<>();
432
433         for (final NormalizedNode childValue : data.body()) {
434             if (childValue instanceof AugmentationNode) {
435                 final AugmentationNode augDomNode = (AugmentationNode) childValue;
436                 final DataContainerCodecPrototype<?> codecProto = augmentationByYang.get(augDomNode.getIdentifier());
437                 if (codecProto != null) {
438                     final DataContainerCodecContext<?, ?> codec = codecProto.get();
439                     map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
440                 }
441             }
442         }
443         for (final DataContainerCodecPrototype<?> value : augmentationByStream.values()) {
444             final var augClass = value.getBindingClass();
445             // Do not perform duplicate deserialization if we have already created the corresponding augmentation
446             // and validate whether the proposed augmentation is valid ion this instantiation context.
447             if (!map.containsKey(augClass)
448                 && ((AugmentableRuntimeType) getType()).augments().contains(value.getType())) {
449                 final NormalizedNode augData = data.childByArg(value.getYangArg());
450                 if (augData != null) {
451                     // ... make sure we do not replace an e
452                     map.putIfAbsent(augClass, value.get().deserializeObject(augData));
453                 }
454             }
455         }
456         return map;
457     }
458
459     final @NonNull Class<? extends CodecDataObject<?>> generatedClass() {
460         return generatedClass;
461     }
462
463     @Override
464     public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
465         checkArgument(getDomPathArgument().equals(arg));
466         return bindingArg();
467     }
468
469     @Override
470     public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
471         checkArgument(bindingArg().equals(arg));
472         return getDomPathArgument();
473     }
474 }