52a7b06be46e728825533b2e1108251549d81ae8
[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 com.google.common.collect.Iterables;
19 import java.lang.invoke.MethodHandle;
20 import java.lang.invoke.MethodHandles;
21 import java.lang.invoke.MethodType;
22 import java.lang.invoke.VarHandle;
23 import java.lang.reflect.Method;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Map.Entry;
28 import java.util.Optional;
29 import org.eclipse.jdt.annotation.NonNull;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.opendaylight.mdsal.binding.dom.codec.api.IncorrectNestingException;
32 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
33 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
34 import org.opendaylight.mdsal.binding.model.api.Type;
35 import org.opendaylight.mdsal.binding.runtime.api.AugmentRuntimeType;
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 Iterable<AugmentRuntimeType> possibleAugmentations;
162         if (Augmentable.class.isAssignableFrom(bindingClass)) {
163             final var type = getType();
164             possibleAugmentations = Iterables.concat(type.augments(), type.mismatchedAugments());
165             generatedClass = CodecDataObjectGenerator.generateAugmentable(prototype.getFactory().getLoader(),
166                 bindingClass, tmpLeaves, tmpDataObjects, keyMethod);
167         } else {
168             possibleAugmentations = List.of();
169             generatedClass = CodecDataObjectGenerator.generate(prototype.getFactory().getLoader(), bindingClass,
170                 tmpLeaves, tmpDataObjects, keyMethod);
171         }
172
173         // Iterate over all possible augmentations, indexing them as needed
174         final Map<PathArgument, DataContainerCodecPrototype<?>> augByYang = new HashMap<>();
175         final Map<Class<?>, DataContainerCodecPrototype<?>> augByStream = new HashMap<>();
176         for (final AugmentRuntimeType augment : possibleAugmentations) {
177             final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment);
178             final PathArgument augYangArg = augProto.getYangArg();
179             if (augByYang.putIfAbsent(augYangArg, augProto) == null) {
180                 LOG.trace("Discovered new YANG mapping {} -> {} in {}", augYangArg, augProto, this);
181             }
182             final Class<?> augBindingClass = augProto.getBindingClass();
183             if (augByStream.putIfAbsent(augBindingClass, augProto) == null) {
184                 LOG.trace("Discovered new class mapping {} -> {} in {}", augBindingClass, augProto, this);
185             }
186         }
187         augmentationByYang = ImmutableMap.copyOf(augByYang);
188         augmentationByStream = ImmutableMap.copyOf(augByStream);
189
190         final MethodHandle ctor;
191         try {
192             ctor = MethodHandles.publicLookup().findConstructor(generatedClass, CONSTRUCTOR_TYPE);
193         } catch (NoSuchMethodException | IllegalAccessException e) {
194             throw new LinkageError("Failed to find contructor for class " + generatedClass, e);
195         }
196
197         proxyConstructor = ctor.asType(DATAOBJECT_TYPE);
198     }
199
200     @Override
201     public final WithStatus getSchema() {
202         // FIXME: Bad cast, we should be returning an EffectiveStatement perhaps?
203         return (WithStatus) getType().statement();
204     }
205
206     @Override
207     @SuppressWarnings("unchecked")
208     public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
209         return (DataContainerCodecContext<C, ?>) childNonNull(streamChildPrototype(childClass), childClass,
210             "Child %s is not valid child of %s", getBindingClass(), childClass).get();
211     }
212
213     private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
214         final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
215         if (childProto != null) {
216             return childProto;
217         }
218         if (Augmentation.class.isAssignableFrom(childClass)) {
219             return augmentationByClass(childClass);
220         }
221         return null;
222     }
223
224     @SuppressWarnings("unchecked")
225     @Override
226     public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
227             final Class<C> childClass) {
228         final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
229         if (childProto != null) {
230             return Optional.of((DataContainerCodecContext<C, ?>) childProto.get());
231         }
232         return Optional.empty();
233     }
234
235     @Override
236     public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
237             final List<YangInstanceIdentifier.PathArgument> builder) {
238
239         final Class<? extends DataObject> argType = arg.getType();
240         DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
241         if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
242             ctxProto = augmentationByClass(argType);
243         }
244         final DataContainerCodecContext<?, ?> context = childNonNull(ctxProto, argType,
245             "Class %s is not valid child of %s", argType, getBindingClass()).get();
246         if (context instanceof ChoiceNodeCodecContext) {
247             final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
248             choice.addYangPathArgument(arg, builder);
249
250             final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
251             final Class<? extends DataObject> type = arg.getType();
252             final DataContainerCodecContext<?, ?> caze;
253             if (caseType.isPresent()) {
254                 // Non-ambiguous addressing this should not pose any problems
255                 caze = choice.streamChild(caseType.get());
256             } else {
257                 caze = choice.getCaseByChildClass(type);
258             }
259
260             caze.addYangPathArgument(arg, builder);
261             return caze.bindingPathArgumentChild(arg, builder);
262         }
263         context.addYangPathArgument(arg, builder);
264         return context;
265     }
266
267     @Override
268     public NodeCodecContext yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
269         final NodeContextSupplier childSupplier;
270         if (arg instanceof NodeIdentifierWithPredicates) {
271             childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
272         } else if (arg instanceof AugmentationIdentifier) {
273             childSupplier = augmentationByYang.get(arg);
274         } else {
275             childSupplier = byYang.get(arg);
276         }
277
278         return childNonNull(childSupplier, arg, "Argument %s is not valid child of %s", arg, getSchema()).get();
279     }
280
281     protected final ValueNodeCodecContext getLeafChild(final String name) {
282         final ValueNodeCodecContext value = leafChild.get(name);
283         if (value == null) {
284             throw IncorrectNestingException.create("Leaf %s is not valid for %s", name, getBindingClass());
285         }
286         return value;
287     }
288
289     private DataContainerCodecPrototype<?> loadChildPrototype(final Class<? extends DataContainer> childClass) {
290         final var type = getType();
291         final var child = childNonNull(type.bindingChild(JavaTypeName.create(childClass)), childClass,
292             "Node %s does not have child named %s", type, childClass);
293
294         return DataContainerCodecPrototype.from(createBindingArg(childClass, child.statement()),
295             (CompositeRuntimeType) child, factory());
296     }
297
298     // FIXME: MDSAL-697: move this method into BindingRuntimeContext
299     //                   This method is only called from loadChildPrototype() and exists only to be overridden by
300     //                   CaseNodeCodecContext. Since we are providing childClass and our schema to BindingRuntimeContext
301     //                   and receiving childSchema from it via findChildSchemaDefinition, we should be able to receive
302     //                   the equivalent of Map.Entry<Item, DataSchemaNode>, along with the override we create here. One
303     //                   more input we may need to provide is our bindingClass().
304     @SuppressWarnings("unchecked")
305     Item<?> createBindingArg(final Class<?> childClass, final EffectiveStatement<?, ?> childSchema) {
306         return Item.of((Class<? extends DataObject>) childClass);
307     }
308
309     private @Nullable DataContainerCodecPrototype<?> augmentationByClass(final @NonNull Class<?> childClass) {
310         final DataContainerCodecPrototype<?> childProto = augmentationByStream.get(childClass);
311         return childProto != null ? childProto : mismatchedAugmentationByClass(childClass);
312     }
313
314     private @Nullable DataContainerCodecPrototype<?> mismatchedAugmentationByClass(final @NonNull Class<?> childClass) {
315         /*
316          * It is potentially mismatched valid augmentation - we look up equivalent augmentation using reflection
317          * and walk all stream child and compare augmentations classes if they are equivalent. When we find a match
318          * we'll cache it so we do not need to perform reflection operations again.
319          */
320         final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> local =
321                 (ImmutableMap<Class<?>, DataContainerCodecPrototype<?>>) MISMATCHED_AUGMENTED.getAcquire(this);
322         final DataContainerCodecPrototype<?> mismatched = local.get(childClass);
323         return mismatched != null ? mismatched : loadMismatchedAugmentation(local, childClass);
324
325     }
326
327     private @Nullable DataContainerCodecPrototype<?> loadMismatchedAugmentation(
328             final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> oldMismatched,
329             final @NonNull Class<?> childClass) {
330         @SuppressWarnings("rawtypes")
331         final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
332         // Do not bother with proposals which are not augmentations of our class, or do not match what the runtime
333         // context would load.
334         if (getBindingClass().equals(augTarget) && belongsToRuntimeContext(childClass)) {
335             for (final DataContainerCodecPrototype<?> realChild : augmentationByStream.values()) {
336                 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
337                         && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
338                     return cacheMismatched(oldMismatched, childClass, realChild);
339                 }
340             }
341         }
342         LOG.trace("Failed to resolve {} as a valid augmentation in {}", childClass, this);
343         return null;
344     }
345
346     private @NonNull DataContainerCodecPrototype<?> cacheMismatched(
347             final @NonNull ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> oldMismatched,
348             final @NonNull Class<?> childClass, final @NonNull DataContainerCodecPrototype<?> prototype) {
349
350         ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> expected = oldMismatched;
351         while (true) {
352             final Map<Class<?>, DataContainerCodecPrototype<?>> newMismatched =
353                     ImmutableMap.<Class<?>, DataContainerCodecPrototype<?>>builderWithExpectedSize(expected.size() + 1)
354                         .putAll(expected)
355                         .put(childClass, prototype)
356                         .build();
357
358             final var witness = (ImmutableMap<Class<?>, DataContainerCodecPrototype<?>>)
359                 MISMATCHED_AUGMENTED.compareAndExchangeRelease(this, expected, newMismatched);
360             if (witness == expected) {
361                 LOG.trace("Cached mismatched augmentation {} -> {} in {}", childClass, prototype, this);
362                 return prototype;
363             }
364
365             expected = witness;
366             final DataContainerCodecPrototype<?> existing = expected.get(childClass);
367             if (existing != null) {
368                 LOG.trace("Using raced mismatched augmentation {} -> {} in {}", childClass, existing, this);
369                 return existing;
370             }
371         }
372     }
373
374     private boolean belongsToRuntimeContext(final Class<?> cls) {
375         final BindingRuntimeContext ctx = factory().getRuntimeContext();
376         final Class<?> loaded;
377         try {
378             loaded = ctx.loadClass(Type.of(cls));
379         } catch (ClassNotFoundException e) {
380             LOG.debug("Proposed {} cannot be loaded in {}", cls, ctx, e);
381             return false;
382         }
383         return cls.equals(loaded);
384     }
385
386     private @NonNull DataContainerCodecPrototype<?> getAugmentationPrototype(final AugmentRuntimeType augment) {
387         final BindingRuntimeContext ctx = factory().getRuntimeContext();
388
389         final GeneratedType javaType = augment.javaType();
390         final Class<? extends Augmentation<?>> augClass;
391         try {
392             augClass = ctx.loadClass(javaType);
393         } catch (final ClassNotFoundException e) {
394             throw new IllegalStateException(
395                 "RuntimeContext references type " + javaType + " but failed to load its class", e);
396         }
397
398         // TODO: at some point we need the effective children
399         return DataContainerCodecPrototype.from(augClass, new AugmentationIdentifier(augment.statement()
400             .streamEffectiveSubstatements(SchemaTreeEffectiveStatement.class)
401             .map(SchemaTreeEffectiveStatement::getIdentifier)
402             .collect(ImmutableSet.toImmutableSet())), augment, factory());
403     }
404
405     @SuppressWarnings("checkstyle:illegalCatch")
406     protected final @NonNull D createBindingProxy(final DistinctNodeContainer<?, ?> node) {
407         try {
408             return (D) proxyConstructor.invokeExact(this, node);
409         } catch (final Throwable e) {
410             Throwables.throwIfUnchecked(e);
411             throw new IllegalStateException(e);
412         }
413     }
414
415     @SuppressWarnings("unchecked")
416     Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
417             final DistinctNodeContainer<PathArgument, NormalizedNode> data) {
418
419         @SuppressWarnings("rawtypes")
420         final Map map = new HashMap<>();
421
422         for (final NormalizedNode childValue : data.body()) {
423             if (childValue instanceof AugmentationNode) {
424                 final AugmentationNode augDomNode = (AugmentationNode) childValue;
425                 final DataContainerCodecPrototype<?> codecProto = augmentationByYang.get(augDomNode.getIdentifier());
426                 if (codecProto != null) {
427                     final DataContainerCodecContext<?, ?> codec = codecProto.get();
428                     map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
429                 }
430             }
431         }
432         for (final DataContainerCodecPrototype<?> value : augmentationByStream.values()) {
433             final var augClass = value.getBindingClass();
434             // Do not perform duplicate deserialization if we have already created the corresponding augmentation
435             // and validate whether the proposed augmentation is valid ion this instantiation context.
436             if (!map.containsKey(augClass) && getType().augments().contains(value.getType())) {
437                 final NormalizedNode augData = data.childByArg(value.getYangArg());
438                 if (augData != null) {
439                     // ... make sure we do not replace an e
440                     map.putIfAbsent(augClass, value.get().deserializeObject(augData));
441                 }
442             }
443         }
444         return map;
445     }
446
447     final @NonNull Class<? extends CodecDataObject<?>> generatedClass() {
448         return generatedClass;
449     }
450
451     @Override
452     public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
453         checkArgument(getDomPathArgument().equals(arg));
454         return bindingArg();
455     }
456
457     @Override
458     public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
459         checkArgument(bindingArg().equals(arg));
460         return getDomPathArgument();
461     }
462 }