Add CodecDataObjectAnalysis
[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
12 import com.google.common.annotations.Beta;
13 import com.google.common.base.Throwables;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.ImmutableSet;
16 import java.lang.invoke.MethodHandle;
17 import java.lang.invoke.MethodHandles;
18 import java.lang.invoke.VarHandle;
19 import java.lang.reflect.Method;
20 import java.util.HashMap;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Optional;
24 import org.eclipse.jdt.annotation.NonNull;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.opendaylight.mdsal.binding.dom.codec.api.IncorrectNestingException;
27 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
28 import org.opendaylight.mdsal.binding.model.api.Type;
29 import org.opendaylight.mdsal.binding.runtime.api.AugmentRuntimeType;
30 import org.opendaylight.mdsal.binding.runtime.api.AugmentableRuntimeType;
31 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
32 import org.opendaylight.mdsal.binding.runtime.api.CompositeRuntimeType;
33 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
34 import org.opendaylight.yangtools.yang.binding.Augmentation;
35 import org.opendaylight.yangtools.yang.binding.DataObject;
36 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
37 import org.opendaylight.yangtools.yang.common.QName;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
43 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.DistinctNodeContainer;
45 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
46 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
47 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 /**
52  * This class is an implementation detail. It is public only due to technical reasons and may change at any time.
53  */
54 @Beta
55 public abstract class DataObjectCodecContext<D extends DataObject, T extends CompositeRuntimeType>
56         extends DataContainerCodecContext<D, T> {
57     private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
58
59     private static final VarHandle MISMATCHED_AUGMENTED;
60
61     static {
62         try {
63             MISMATCHED_AUGMENTED = MethodHandles.lookup().findVarHandle(DataObjectCodecContext.class,
64                 "mismatchedAugmented", ImmutableMap.class);
65         } catch (NoSuchFieldException | IllegalAccessException e) {
66             throw new ExceptionInInitializerError(e);
67         }
68     }
69
70     private final ImmutableMap<String, ValueNodeCodecContext> leafChild;
71     private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
72     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
73     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
74     private final ImmutableMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> augmentationByYang;
75     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> augmentationByStream;
76     private final @NonNull Class<? extends CodecDataObject<?>> generatedClass;
77     private final MethodHandle proxyConstructor;
78
79     // Note this the content of this field depends only of invariants expressed as this class's fields or
80     // BindingRuntimeContext. It is only accessed via MISMATCHED_AUGMENTED above.
81     @SuppressWarnings("unused")
82     private volatile ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> mismatchedAugmented = ImmutableMap.of();
83
84     DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
85         this(prototype, CodecItemFactory.of());
86     }
87
88     DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype, final CodecItemFactory itemFactory) {
89         this(prototype, new CodecDataObjectAnalysis<>(prototype, itemFactory, null));
90     }
91
92     DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype, final Method keyMethod) {
93         this(prototype, new CodecDataObjectAnalysis<>(prototype, CodecItemFactory.of(), keyMethod));
94     }
95
96     private DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype,
97             final CodecDataObjectAnalysis<T> analysis) {
98         super(prototype);
99
100         // Inherit analysis stuff
101         leafChild = analysis.leafNodes;
102         proxyConstructor = analysis.proxyConstructor;
103         generatedClass = analysis.generatedClass;
104         byBindingArgClass = analysis.byBindingArgClass;
105         byStreamClass = analysis.byStreamClass;
106         byYang = analysis.byYang;
107
108         // Deal with augmentations, which are not something we analysis provides
109         final var augByYang = new HashMap<PathArgument, DataContainerCodecPrototype<?>>();
110         final var augByStream = new HashMap<Class<?>, DataContainerCodecPrototype<?>>();
111         for (var augment : analysis.possibleAugmentations) {
112             final var augProto = loadAugmentPrototype(augment);
113             if (augProto != null) {
114                 final var augYangArg = augProto.getYangArg();
115                 if (augByYang.putIfAbsent(augYangArg, augProto) == null) {
116                     LOG.trace("Discovered new YANG mapping {} -> {} in {}", augYangArg, augProto, this);
117                 }
118                 final var augBindingClass = augProto.getBindingClass();
119                 if (augByStream.putIfAbsent(augBindingClass, augProto) == null) {
120                     LOG.trace("Discovered new class mapping {} -> {} in {}", augBindingClass, augProto, this);
121                 }
122             }
123         }
124         augmentationByYang = ImmutableMap.copyOf(augByYang);
125         augmentationByStream = ImmutableMap.copyOf(augByStream);
126     }
127
128     @Override
129     public final WithStatus getSchema() {
130         // FIXME: Bad cast, we should be returning an EffectiveStatement perhaps?
131         return (WithStatus) getType().statement();
132     }
133
134     @Override
135     @SuppressWarnings("unchecked")
136     public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
137         return (DataContainerCodecContext<C, ?>) childNonNull(streamChildPrototype(childClass), childClass,
138             "Child %s is not valid child of %s", getBindingClass(), childClass).get();
139     }
140
141     private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
142         final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
143         if (childProto != null) {
144             return childProto;
145         }
146         if (Augmentation.class.isAssignableFrom(childClass)) {
147             return augmentationByClass(childClass);
148         }
149         return null;
150     }
151
152     @SuppressWarnings("unchecked")
153     @Override
154     public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
155             final Class<C> childClass) {
156         final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
157         if (childProto != null) {
158             return Optional.of((DataContainerCodecContext<C, ?>) childProto.get());
159         }
160         return Optional.empty();
161     }
162
163     @Override
164     public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
165             final List<YangInstanceIdentifier.PathArgument> builder) {
166
167         final Class<? extends DataObject> argType = arg.getType();
168         DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
169         if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
170             ctxProto = augmentationByClass(argType);
171         }
172         final DataContainerCodecContext<?, ?> context = childNonNull(ctxProto, argType,
173             "Class %s is not valid child of %s", argType, getBindingClass()).get();
174         if (context instanceof ChoiceNodeCodecContext<?> choice) {
175             choice.addYangPathArgument(arg, builder);
176
177             final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
178             final Class<? extends DataObject> type = arg.getType();
179             final DataContainerCodecContext<?, ?> caze;
180             if (caseType.isPresent()) {
181                 // Non-ambiguous addressing this should not pose any problems
182                 caze = choice.streamChild(caseType.orElseThrow());
183             } else {
184                 caze = choice.getCaseByChildClass(type);
185             }
186
187             caze.addYangPathArgument(arg, builder);
188             return caze.bindingPathArgumentChild(arg, builder);
189         }
190         context.addYangPathArgument(arg, builder);
191         return context;
192     }
193
194     @Override
195     public NodeCodecContext yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
196         final NodeContextSupplier childSupplier;
197         if (arg instanceof NodeIdentifierWithPredicates) {
198             childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
199         } else if (arg instanceof AugmentationIdentifier) {
200             childSupplier = augmentationByYang.get(arg);
201         } else {
202             childSupplier = byYang.get(arg);
203         }
204
205         return childNonNull(childSupplier, arg, "Argument %s is not valid child of %s", arg, getSchema()).get();
206     }
207
208     protected final ValueNodeCodecContext getLeafChild(final String name) {
209         final ValueNodeCodecContext value = leafChild.get(name);
210         if (value == null) {
211             throw new IncorrectNestingException("Leaf %s is not valid for %s", name, getBindingClass());
212         }
213         return value;
214     }
215
216     private @Nullable DataContainerCodecPrototype<?> augmentationByClass(final @NonNull Class<?> childClass) {
217         final DataContainerCodecPrototype<?> childProto = augmentationByStream.get(childClass);
218         return childProto != null ? childProto : mismatchedAugmentationByClass(childClass);
219     }
220
221     private @Nullable DataContainerCodecPrototype<?> mismatchedAugmentationByClass(final @NonNull Class<?> childClass) {
222         /*
223          * It is potentially mismatched valid augmentation - we look up equivalent augmentation using reflection
224          * and walk all stream child and compare augmentations classes if they are equivalent. When we find a match
225          * we'll cache it so we do not need to perform reflection operations again.
226          */
227         final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> local =
228                 (ImmutableMap<Class<?>, DataContainerCodecPrototype<?>>) MISMATCHED_AUGMENTED.getAcquire(this);
229         final DataContainerCodecPrototype<?> mismatched = local.get(childClass);
230         return mismatched != null ? mismatched : loadMismatchedAugmentation(local, childClass);
231
232     }
233
234     private @Nullable DataContainerCodecPrototype<?> loadMismatchedAugmentation(
235             final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> oldMismatched,
236             final @NonNull Class<?> childClass) {
237         @SuppressWarnings("rawtypes")
238         final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
239         // Do not bother with proposals which are not augmentations of our class, or do not match what the runtime
240         // context would load.
241         if (getBindingClass().equals(augTarget) && belongsToRuntimeContext(childClass)) {
242             for (final DataContainerCodecPrototype<?> realChild : augmentationByStream.values()) {
243                 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
244                         && isSubstitutionFor(childClass, realChild.getBindingClass())) {
245                     return cacheMismatched(oldMismatched, childClass, realChild);
246                 }
247             }
248         }
249         LOG.trace("Failed to resolve {} as a valid augmentation in {}", childClass, this);
250         return null;
251     }
252
253     private @NonNull DataContainerCodecPrototype<?> cacheMismatched(
254             final @NonNull ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> oldMismatched,
255             final @NonNull Class<?> childClass, final @NonNull DataContainerCodecPrototype<?> prototype) {
256
257         ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> expected = oldMismatched;
258         while (true) {
259             final Map<Class<?>, DataContainerCodecPrototype<?>> newMismatched =
260                     ImmutableMap.<Class<?>, DataContainerCodecPrototype<?>>builderWithExpectedSize(expected.size() + 1)
261                         .putAll(expected)
262                         .put(childClass, prototype)
263                         .build();
264
265             final var witness = (ImmutableMap<Class<?>, DataContainerCodecPrototype<?>>)
266                 MISMATCHED_AUGMENTED.compareAndExchangeRelease(this, expected, newMismatched);
267             if (witness == expected) {
268                 LOG.trace("Cached mismatched augmentation {} -> {} in {}", childClass, prototype, this);
269                 return prototype;
270             }
271
272             expected = witness;
273             final DataContainerCodecPrototype<?> existing = expected.get(childClass);
274             if (existing != null) {
275                 LOG.trace("Using raced mismatched augmentation {} -> {} in {}", childClass, existing, this);
276                 return existing;
277             }
278         }
279     }
280
281     private boolean belongsToRuntimeContext(final Class<?> cls) {
282         final BindingRuntimeContext ctx = factory().getRuntimeContext();
283         final Class<?> loaded;
284         try {
285             loaded = ctx.loadClass(Type.of(cls));
286         } catch (ClassNotFoundException e) {
287             LOG.debug("Proposed {} cannot be loaded in {}", cls, ctx, e);
288             return false;
289         }
290         return cls.equals(loaded);
291     }
292
293     private @Nullable DataContainerCodecPrototype<?> loadAugmentPrototype(final AugmentRuntimeType augment) {
294         // FIXME: in face of deviations this code should be looking at declared view, i.e. all possibilities at augment
295         //        declaration site
296         final var possibleChildren = augment.statement()
297             .streamEffectiveSubstatements(SchemaTreeEffectiveStatement.class)
298             .map(stmt -> (QName) stmt.argument())
299             .collect(ImmutableSet.toImmutableSet());
300         if (possibleChildren.isEmpty()) {
301             return null;
302         }
303
304         final var factory = factory();
305         final GeneratedType javaType = augment.javaType();
306         final Class<? extends Augmentation<?>> augClass;
307         try {
308             augClass = factory.getRuntimeContext().loadClass(javaType);
309         } catch (final ClassNotFoundException e) {
310             throw new IllegalStateException(
311                 "RuntimeContext references type " + javaType + " but failed to load its class", e);
312         }
313
314         return DataContainerCodecPrototype.from(augClass, new AugmentationIdentifier(possibleChildren), augment,
315             factory);
316     }
317
318     @SuppressWarnings("checkstyle:illegalCatch")
319     protected final @NonNull D createBindingProxy(final DistinctNodeContainer<?, ?> node) {
320         try {
321             return (D) proxyConstructor.invokeExact(this, node);
322         } catch (final Throwable e) {
323             Throwables.throwIfUnchecked(e);
324             throw new IllegalStateException(e);
325         }
326     }
327
328     @SuppressWarnings("unchecked")
329     Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
330             final DistinctNodeContainer<PathArgument, NormalizedNode> data) {
331
332         @SuppressWarnings("rawtypes")
333         final Map map = new HashMap<>();
334
335         for (final NormalizedNode childValue : data.body()) {
336             if (childValue instanceof AugmentationNode augDomNode) {
337                 final DataContainerCodecPrototype<?> codecProto = augmentationByYang.get(augDomNode.getIdentifier());
338                 if (codecProto != null) {
339                     final DataContainerCodecContext<?, ?> codec = codecProto.get();
340                     map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
341                 }
342             }
343         }
344         for (final DataContainerCodecPrototype<?> value : augmentationByStream.values()) {
345             final var augClass = value.getBindingClass();
346             // Do not perform duplicate deserialization if we have already created the corresponding augmentation
347             // and validate whether the proposed augmentation is valid ion this instantiation context.
348             if (!map.containsKey(augClass)
349                 && ((AugmentableRuntimeType) getType()).augments().contains(value.getType())) {
350                 final NormalizedNode augData = data.childByArg(value.getYangArg());
351                 if (augData != null) {
352                     // ... make sure we do not replace an e
353                     map.putIfAbsent(augClass, value.get().deserializeObject(augData));
354                 }
355             }
356         }
357         return map;
358     }
359
360     final @NonNull Class<? extends CodecDataObject<?>> generatedClass() {
361         return generatedClass;
362     }
363
364     @Override
365     public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
366         checkArgument(getDomPathArgument().equals(arg));
367         return bindingArg();
368     }
369
370     @Override
371     public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
372         checkArgument(bindingArg().equals(arg));
373         return getDomPathArgument();
374     }
375
376 }