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