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