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