57ab7c906ece3620e00d1c69d0fc09224df80d92
[mdsal.git] / binding / mdsal-binding-dom-adapter / src / main / java / org / opendaylight / mdsal / binding / dom / adapter / AbstractDataObjectModification.java
1 /*
2  * Copyright (c) 2023 PANTHEON.tech, s.r.o. 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.adapter;
9
10 import static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
12 import static org.opendaylight.yangtools.yang.data.tree.api.ModificationType.UNMODIFIED;
13
14 import com.google.common.base.MoreObjects;
15 import com.google.common.base.MoreObjects.ToStringHelper;
16 import com.google.common.base.VerifyException;
17 import com.google.common.collect.ArrayListMultimap;
18 import com.google.common.collect.ImmutableList;
19 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
20 import java.lang.invoke.MethodHandles;
21 import java.lang.invoke.VarHandle;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.List;
25 import java.util.stream.Collectors;
26 import java.util.stream.Stream;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.opendaylight.mdsal.binding.api.DataObjectModification;
30 import org.opendaylight.mdsal.binding.dom.codec.api.BindingAugmentationCodecTreeNode;
31 import org.opendaylight.mdsal.binding.dom.codec.api.BindingDataObjectCodecTreeNode;
32 import org.opendaylight.mdsal.binding.dom.codec.api.CommonDataObjectCodecTreeNode;
33 import org.opendaylight.yangtools.yang.binding.Augmentation;
34 import org.opendaylight.yangtools.yang.binding.ChildOf;
35 import org.opendaylight.yangtools.yang.binding.ChoiceIn;
36 import org.opendaylight.yangtools.yang.binding.DataObject;
37 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
38 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
39 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
40 import org.opendaylight.yangtools.yang.binding.Key;
41 import org.opendaylight.yangtools.yang.binding.KeyAware;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
44 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidateNode;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 /**
49  * Lazily translated {@link DataObjectModification} based on {@link DataTreeCandidateNode}.
50  * {@link AbstractDataObjectModification} represents Data tree change event, but whole tree is not translated or
51  * resolved eagerly, but only child nodes which are directly accessed by user of data object modification.
52  *
53  * <p>
54  * This class is further specialized as {@link LazyAugmentationModification} and {@link LazyDataObjectModification}, as
55  * both use different serialization methods.
56  *
57  * @param <T> Type of Binding {@link DataObject}
58  * @param <N> Type of underlying {@link CommonDataObjectCodecTreeNode}
59  */
60 abstract sealed class AbstractDataObjectModification<T extends DataObject, N extends CommonDataObjectCodecTreeNode<T>>
61         implements DataObjectModification<T>
62         permits LazyAugmentationModification, LazyDataObjectModification {
63     private static final Logger LOG = LoggerFactory.getLogger(AbstractDataObjectModification.class);
64     private static final @NonNull Object NULL_DATA_OBJECT = new Object();
65     private static final VarHandle MODIFICATION_TYPE;
66     private static final VarHandle MODIFIED_CHILDREN;
67     private static final VarHandle DATA_BEFORE;
68     private static final VarHandle DATA_AFTER;
69
70     static {
71         final var lookup = MethodHandles.lookup();
72
73         try {
74             MODIFICATION_TYPE = lookup.findVarHandle(AbstractDataObjectModification.class, "modificationType",
75                 ModificationType.class);
76             MODIFIED_CHILDREN = lookup.findVarHandle(AbstractDataObjectModification.class, "modifiedChildren",
77                 ImmutableList.class);
78             DATA_BEFORE = lookup.findVarHandle(AbstractDataObjectModification.class, "dataBefore", Object.class);
79             DATA_AFTER = lookup.findVarHandle(AbstractDataObjectModification.class, "dataAfter", Object.class);
80         } catch (NoSuchFieldException | IllegalAccessException e) {
81             throw new ExceptionInInitializerError(e);
82         }
83     }
84
85     final @NonNull DataTreeCandidateNode domData;
86     final @NonNull PathArgument identifier;
87     final @NonNull N codec;
88
89     @SuppressWarnings("unused")
90     @SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "https://github.com/spotbugs/spotbugs/issues/2749")
91     private volatile ImmutableList<AbstractDataObjectModification<?, ?>> modifiedChildren;
92     @SuppressWarnings("unused")
93     @SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "https://github.com/spotbugs/spotbugs/issues/2749")
94     private volatile ModificationType modificationType;
95     @SuppressWarnings("unused")
96     @SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "https://github.com/spotbugs/spotbugs/issues/2749")
97     private volatile Object dataBefore;
98     @SuppressWarnings("unused")
99     @SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "https://github.com/spotbugs/spotbugs/issues/2749")
100     private volatile Object dataAfter;
101
102     AbstractDataObjectModification(final DataTreeCandidateNode domData, final N codec, final PathArgument identifier) {
103         this.domData = requireNonNull(domData);
104         this.identifier = requireNonNull(identifier);
105         this.codec = requireNonNull(codec);
106     }
107
108     static @Nullable AbstractDataObjectModification<?, ?> from(final CommonDataObjectCodecTreeNode<?> codec,
109             final @NonNull DataTreeCandidateNode current) {
110         if (codec instanceof BindingDataObjectCodecTreeNode<?> childDataObjectCodec) {
111             return new LazyDataObjectModification<>(childDataObjectCodec, current);
112         } else if (codec instanceof BindingAugmentationCodecTreeNode<?> childAugmentationCodec) {
113             return LazyAugmentationModification.forParent(childAugmentationCodec, current);
114         } else {
115             throw new VerifyException("Unhandled codec " + codec);
116         }
117     }
118
119     @Override
120     public final Class<T> getDataType() {
121         return codec.getBindingClass();
122     }
123
124     @Override
125     public final PathArgument getIdentifier() {
126         return identifier;
127     }
128
129     @Override
130     public final ModificationType getModificationType() {
131         final var local = (ModificationType) MODIFICATION_TYPE.getAcquire(this);
132         return local != null ? local : loadModificationType();
133     }
134
135     private @NonNull ModificationType loadModificationType() {
136         final var domModificationType = domModificationType();
137         final var computed = switch (domModificationType) {
138             case APPEARED, WRITE -> ModificationType.WRITE;
139             case DISAPPEARED, DELETE -> ModificationType.DELETE;
140             case SUBTREE_MODIFIED -> resolveSubtreeModificationType();
141             default ->
142                 // TODO: Should we lie about modification type instead of exception?
143                 throw new IllegalStateException("Unsupported DOM Modification type " + domModificationType);
144         };
145
146         MODIFICATION_TYPE.setRelease(this, computed);
147         return computed;
148     }
149
150     @Override
151     public final T getDataBefore() {
152         final var local = DATA_BEFORE.getAcquire(this);
153         return local != null ? unmask(local) : loadDataBefore();
154     }
155
156     private @Nullable T loadDataBefore() {
157         final var computed = deserializeNullable(domData.dataBefore());
158         final var witness = DATA_BEFORE.compareAndExchangeRelease(this, null, mask(computed));
159         return witness == null ? computed : unmask(witness);
160     }
161
162     @Override
163     public final T getDataAfter() {
164         final var local = DATA_AFTER.getAcquire(this);
165         return local != null ? unmask(local) : loadDataAfter();
166     }
167
168     private @Nullable T loadDataAfter() {
169         final var computed = deserializeNullable(domData.dataAfter());
170         final var witness = DATA_AFTER.compareAndExchangeRelease(this, null, mask(computed));
171         return witness == null ? computed : unmask(witness);
172     }
173
174     private static <T extends DataObject> @NonNull Object mask(final @Nullable T obj) {
175         return obj != null ? obj : NULL_DATA_OBJECT;
176     }
177
178     @SuppressWarnings("unchecked")
179     private @Nullable T unmask(final @NonNull Object obj) {
180         return obj == NULL_DATA_OBJECT ? null : (T) verifyNotNull(obj);
181     }
182
183     private @Nullable T deserializeNullable(final @Nullable NormalizedNode normalized) {
184         return normalized == null ? null : deserialize(normalized);
185     }
186
187     abstract @Nullable T deserialize(@NonNull NormalizedNode normalized);
188
189     @Override
190     public final DataObjectModification<?> getModifiedChild(final PathArgument arg) {
191         final var domArgumentList = new ArrayList<YangInstanceIdentifier.PathArgument>();
192         final var childCodec = codec.bindingPathArgumentChild(arg, domArgumentList);
193         final var toEnter = domArgumentList.iterator();
194
195         // Careful now: we need to validated the first item against subclass
196         var current = toEnter.hasNext() ? firstModifiedChild(toEnter.next()) : domData;
197         // ... and for everything else we can just go wild
198         while (toEnter.hasNext() && current != null) {
199             current = current.modifiedChild(toEnter.next());
200         }
201
202         if (current == null || current.modificationType() == UNMODIFIED) {
203             return null;
204         }
205         return from(childCodec, current);
206     }
207
208     abstract @Nullable DataTreeCandidateNode firstModifiedChild(YangInstanceIdentifier.PathArgument arg);
209
210     @Override
211     public final ImmutableList<AbstractDataObjectModification<?, ?>> getModifiedChildren() {
212         final var local = (ImmutableList<AbstractDataObjectModification<?, ?>>) MODIFIED_CHILDREN.getAcquire(this);
213         return local != null ? local : loadModifiedChilden();
214     }
215
216     @Override
217     public final <C extends ChildOf<? super T>> List<DataObjectModification<C>> getModifiedChildren(
218             final Class<C> childType) {
219         return streamModifiedChildren(childType).collect(Collectors.toList());
220     }
221
222     @Override
223     public final <H extends ChoiceIn<? super T> & DataObject, C extends ChildOf<? super H>>
224             List<DataObjectModification<C>> getModifiedChildren(final Class<H> caseType, final Class<C> childType) {
225         return streamModifiedChildren(childType)
226             .filter(child -> caseType.equals(child.identifier.getCaseType().orElse(null)))
227             .collect(Collectors.toList());
228     }
229
230     @SuppressWarnings("unchecked")
231     private @NonNull ImmutableList<AbstractDataObjectModification<?, ?>> loadModifiedChilden() {
232         final var builder = ImmutableList.<AbstractDataObjectModification<?, ?>>builder();
233         populateList(builder, codec, domData, domChildNodes());
234         final var computed = builder.build();
235         // Non-trivial return: use CAS to ensure we reuse concurrent loads
236         final var witness = MODIFIED_CHILDREN.compareAndExchangeRelease(this, null, computed);
237         return witness == null ? computed : (ImmutableList<AbstractDataObjectModification<?, ?>>) witness;
238     }
239
240     @SuppressWarnings("unchecked")
241     private <C extends DataObject> Stream<LazyDataObjectModification<C>> streamModifiedChildren(
242             final Class<C> childType) {
243         return getModifiedChildren().stream()
244             .filter(child -> childType.isAssignableFrom(child.getDataType()))
245             .map(child -> (LazyDataObjectModification<C>) child);
246     }
247
248     @Override
249     @SuppressWarnings("unchecked")
250     public final <C extends KeyAware<K> & ChildOf<? super T>, K extends Key<C>> DataObjectModification<C>
251             getModifiedChildListItem(final Class<C> listItem, final K listKey) {
252         return (DataObjectModification<C>) getModifiedChild(IdentifiableItem.of(listItem, listKey));
253     }
254
255     @Override
256     @SuppressWarnings("unchecked")
257     public final <H extends ChoiceIn<? super T> & DataObject, C extends KeyAware<K> & ChildOf<? super H>,
258             K extends Key<C>> DataObjectModification<C> getModifiedChildListItem(final Class<H> caseType,
259                     final Class<C> listItem, final K listKey) {
260         return (DataObjectModification<C>) getModifiedChild(IdentifiableItem.of(caseType, listItem, listKey));
261     }
262
263     @Override
264     @SuppressWarnings("unchecked")
265     public final <C extends ChildOf<? super T>> DataObjectModification<C> getModifiedChildContainer(
266             final Class<C> child) {
267         return (DataObjectModification<C>) getModifiedChild(Item.of(child));
268     }
269
270     @Override
271     @SuppressWarnings("unchecked")
272     public final <H extends ChoiceIn<? super T> & DataObject, C extends ChildOf<? super H>> DataObjectModification<C>
273             getModifiedChildContainer(final Class<H> caseType, final Class<C> child) {
274         return (DataObjectModification<C>) getModifiedChild(Item.of(caseType, child));
275     }
276
277     @Override
278     @SuppressWarnings("unchecked")
279     public final <C extends Augmentation<T> & DataObject> DataObjectModification<C> getModifiedAugmentation(
280             final Class<C> augmentation) {
281         return (DataObjectModification<C>) getModifiedChild(Item.of(augmentation));
282     }
283
284     @Override
285     public final String toString() {
286         return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
287     }
288
289     ToStringHelper addToStringAttributes(final ToStringHelper helper) {
290         return helper.add("identifier", identifier).add("domData", domData);
291     }
292
293     abstract @NonNull Collection<DataTreeCandidateNode> domChildNodes();
294
295     abstract org.opendaylight.yangtools.yang.data.tree.api.@NonNull ModificationType domModificationType();
296
297     private @NonNull ModificationType resolveSubtreeModificationType() {
298         return switch (codec.getChildAddressabilitySummary()) {
299             case ADDRESSABLE ->
300                 // All children are addressable, it is safe to report SUBTREE_MODIFIED
301                 ModificationType.SUBTREE_MODIFIED;
302             case UNADDRESSABLE ->
303                 // All children are non-addressable, report WRITE
304                 ModificationType.WRITE;
305             case MIXED -> {
306                 // This case is not completely trivial, as we may have NOT_ADDRESSABLE nodes underneath us. If that
307                 // is the case, we need to turn this modification into a WRITE operation, so that the user is able
308                 // to observe those nodes being introduced. This is not efficient, but unfortunately unavoidable,
309                 // as we cannot accurately represent such changes.
310                 for (var child : domChildNodes()) {
311                     if (BindingStructuralType.recursiveFrom(child) == BindingStructuralType.NOT_ADDRESSABLE) {
312                         // We have a non-addressable child, turn this modification into a write
313                         yield ModificationType.WRITE;
314                     }
315                 }
316
317                 // No unaddressable children found, proceed in addressed mode
318                 yield ModificationType.SUBTREE_MODIFIED;
319             }
320         };
321     }
322
323     private static void populateList(final ImmutableList.Builder<AbstractDataObjectModification<?, ?>> result,
324             final CommonDataObjectCodecTreeNode<?> parentCodec, final DataTreeCandidateNode parent,
325             final Collection<DataTreeCandidateNode> children) {
326         final var augmentChildren =
327             ArrayListMultimap.<BindingAugmentationCodecTreeNode<?>, DataTreeCandidateNode>create();
328
329         for (var domChildNode : parent.childNodes()) {
330             if (domChildNode.modificationType() != UNMODIFIED) {
331                 final var type = BindingStructuralType.from(domChildNode);
332                 if (type != BindingStructuralType.NOT_ADDRESSABLE) {
333                     /*
334                      * Even if type is UNKNOWN, from perspective of BindingStructuralType we try to load codec for it.
335                      * We will use that type to further specify debug log.
336                      */
337                     try {
338                         final var childCodec = parentCodec.yangPathArgumentChild(domChildNode.name());
339                         if (childCodec instanceof BindingDataObjectCodecTreeNode<?> childDataObjectCodec) {
340                             populateList(result, type, childDataObjectCodec, domChildNode);
341                         } else if (childCodec instanceof BindingAugmentationCodecTreeNode<?> childAugmentationCodec) {
342                             // Defer creation once we have collected all modified children
343                             augmentChildren.put(childAugmentationCodec, domChildNode);
344                         } else {
345                             throw new VerifyException("Unhandled codec %s for type %s".formatted(childCodec, type));
346                         }
347                     } catch (final IllegalArgumentException e) {
348                         if (type == BindingStructuralType.UNKNOWN) {
349                             LOG.debug("Unable to deserialize unknown DOM node {}", domChildNode, e);
350                         } else {
351                             LOG.debug("Binding representation for DOM node {} was not found", domChildNode, e);
352                         }
353                     }
354                 }
355             }
356         }
357
358         for (var entry : augmentChildren.asMap().entrySet()) {
359             final var modification = LazyAugmentationModification.forModifications(entry.getKey(), parent,
360                 entry.getValue());
361             if (modification != null) {
362                 result.add(modification);
363             }
364         }
365     }
366
367     private static void populateList(final ImmutableList.Builder<AbstractDataObjectModification<?, ?>> result,
368             final BindingStructuralType type, final BindingDataObjectCodecTreeNode<?> childCodec,
369             final DataTreeCandidateNode domChildNode) {
370         switch (type) {
371             case INVISIBLE_LIST:
372                 // We use parent codec intentionally.
373                 populateListWithSingleCodec(result, childCodec, domChildNode.childNodes());
374                 break;
375             case INVISIBLE_CONTAINER:
376                 populateList(result, childCodec, domChildNode, domChildNode.childNodes());
377                 break;
378             case UNKNOWN:
379             case VISIBLE_CONTAINER:
380                 result.add(new LazyDataObjectModification<>(childCodec, domChildNode));
381                 break;
382             default:
383         }
384     }
385
386     private static void populateListWithSingleCodec(
387             final ImmutableList.Builder<AbstractDataObjectModification<?, ?>> result,
388             final BindingDataObjectCodecTreeNode<?> codec, final Collection<DataTreeCandidateNode> childNodes) {
389         for (var child : childNodes) {
390             if (child.modificationType() != UNMODIFIED) {
391                 result.add(new LazyDataObjectModification<>(codec, child));
392             }
393         }
394     }
395 }