2 * Copyright (c) 2023 PANTHEON.tech, s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.dom.adapter;
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;
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 java.lang.invoke.MethodHandles;
20 import java.lang.invoke.VarHandle;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.List;
24 import java.util.stream.Collectors;
25 import java.util.stream.Stream;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.opendaylight.mdsal.binding.api.DataObjectModification;
29 import org.opendaylight.mdsal.binding.dom.codec.api.BindingAugmentationCodecTreeNode;
30 import org.opendaylight.mdsal.binding.dom.codec.api.BindingDataObjectCodecTreeNode;
31 import org.opendaylight.mdsal.binding.dom.codec.api.CommonDataObjectCodecTreeNode;
32 import org.opendaylight.yangtools.yang.binding.Augmentation;
33 import org.opendaylight.yangtools.yang.binding.ChildOf;
34 import org.opendaylight.yangtools.yang.binding.ChoiceIn;
35 import org.opendaylight.yangtools.yang.binding.DataObject;
36 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
37 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
38 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
39 import org.opendaylight.yangtools.yang.binding.Key;
40 import org.opendaylight.yangtools.yang.binding.KeyAware;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
43 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidateNode;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
48 * Lazily translated {@link DataObjectModification} based on {@link DataTreeCandidateNode}.
49 * {@link AbstractDataObjectModification} represents Data tree change event, but whole tree is not translated or
50 * resolved eagerly, but only child nodes which are directly accessed by user of data object modification.
53 * This class is further specialized as {@link LazyAugmentationModification} and {@link LazyDataObjectModification}, as
54 * both use different serialization methods.
56 * @param <T> Type of Binding {@link DataObject}
57 * @param <N> Type of underlying {@link CommonDataObjectCodecTreeNode}
59 abstract sealed class AbstractDataObjectModification<T extends DataObject, N extends CommonDataObjectCodecTreeNode<T>>
60 implements DataObjectModification<T>
61 permits LazyAugmentationModification, LazyDataObjectModification {
62 private static final Logger LOG = LoggerFactory.getLogger(AbstractDataObjectModification.class);
63 private static final @NonNull Object NULL_DATA_OBJECT = new Object();
64 private static final VarHandle MODIFICATION_TYPE;
65 private static final VarHandle MODIFIED_CHILDREN;
66 private static final VarHandle DATA_BEFORE;
67 private static final VarHandle DATA_AFTER;
70 final var lookup = MethodHandles.lookup();
73 MODIFICATION_TYPE = lookup.findVarHandle(AbstractDataObjectModification.class, "modificationType",
74 ModificationType.class);
75 MODIFIED_CHILDREN = lookup.findVarHandle(AbstractDataObjectModification.class, "modifiedChildren",
77 DATA_BEFORE = lookup.findVarHandle(AbstractDataObjectModification.class, "dataBefore", Object.class);
78 DATA_AFTER = lookup.findVarHandle(AbstractDataObjectModification.class, "dataAfter", Object.class);
79 } catch (NoSuchFieldException | IllegalAccessException e) {
80 throw new ExceptionInInitializerError(e);
84 final @NonNull DataTreeCandidateNode domData;
85 final @NonNull PathArgument identifier;
86 final @NonNull N codec;
88 @SuppressWarnings("unused")
89 private volatile ImmutableList<AbstractDataObjectModification<?, ?>> modifiedChildren;
90 @SuppressWarnings("unused")
91 private volatile ModificationType modificationType;
92 @SuppressWarnings("unused")
93 private volatile Object dataBefore;
94 @SuppressWarnings("unused")
95 private volatile Object dataAfter;
97 AbstractDataObjectModification(final DataTreeCandidateNode domData, final N codec, final PathArgument identifier) {
98 this.domData = requireNonNull(domData);
99 this.identifier = requireNonNull(identifier);
100 this.codec = requireNonNull(codec);
103 static @Nullable AbstractDataObjectModification<?, ?> from(final CommonDataObjectCodecTreeNode<?> codec,
104 final @NonNull DataTreeCandidateNode current) {
105 if (codec instanceof BindingDataObjectCodecTreeNode<?> childDataObjectCodec) {
106 return new LazyDataObjectModification<>(childDataObjectCodec, current);
107 } else if (codec instanceof BindingAugmentationCodecTreeNode<?> childAugmentationCodec) {
108 return LazyAugmentationModification.forParent(childAugmentationCodec, current);
110 throw new VerifyException("Unhandled codec " + codec);
115 public final Class<T> getDataType() {
116 return codec.getBindingClass();
120 public final PathArgument getIdentifier() {
125 public final ModificationType getModificationType() {
126 final var local = (ModificationType) MODIFICATION_TYPE.getAcquire(this);
127 return local != null ? local : loadModificationType();
130 private @NonNull ModificationType loadModificationType() {
131 final var domModificationType = domModificationType();
132 final var computed = switch (domModificationType) {
133 case APPEARED, WRITE -> ModificationType.WRITE;
134 case DISAPPEARED, DELETE -> ModificationType.DELETE;
135 case SUBTREE_MODIFIED -> resolveSubtreeModificationType();
137 // TODO: Should we lie about modification type instead of exception?
138 throw new IllegalStateException("Unsupported DOM Modification type " + domModificationType);
141 MODIFICATION_TYPE.setRelease(this, computed);
146 public final T getDataBefore() {
147 final var local = DATA_BEFORE.getAcquire(this);
148 return local != null ? unmask(local) : loadDataBefore();
151 private @Nullable T loadDataBefore() {
152 final var computed = deserializeNullable(domData.dataBefore());
153 final var witness = DATA_BEFORE.compareAndExchangeRelease(this, null, mask(computed));
154 return witness == null ? computed : unmask(witness);
158 public final T getDataAfter() {
159 final var local = DATA_AFTER.getAcquire(this);
160 return local != null ? unmask(local) : loadDataAfter();
163 private @Nullable T loadDataAfter() {
164 final var computed = deserializeNullable(domData.dataAfter());
165 final var witness = DATA_AFTER.compareAndExchangeRelease(this, null, mask(computed));
166 return witness == null ? computed : unmask(witness);
169 private static <T extends DataObject> @NonNull Object mask(final @Nullable T obj) {
170 return obj != null ? obj : NULL_DATA_OBJECT;
173 @SuppressWarnings("unchecked")
174 private @Nullable T unmask(final @NonNull Object obj) {
175 return obj == NULL_DATA_OBJECT ? null : (T) verifyNotNull(obj);
178 private @Nullable T deserializeNullable(final @Nullable NormalizedNode normalized) {
179 return normalized == null ? null : deserialize(normalized);
182 abstract @Nullable T deserialize(@NonNull NormalizedNode normalized);
185 public final DataObjectModification<?> getModifiedChild(final PathArgument arg) {
186 final var domArgumentList = new ArrayList<YangInstanceIdentifier.PathArgument>();
187 final var childCodec = codec.bindingPathArgumentChild(arg, domArgumentList);
188 final var toEnter = domArgumentList.iterator();
190 // Careful now: we need to validated the first item against subclass
191 var current = toEnter.hasNext() ? firstModifiedChild(toEnter.next()) : domData;
192 // ... and for everything else we can just go wild
193 while (toEnter.hasNext() && current != null) {
194 current = current.modifiedChild(toEnter.next());
197 if (current == null || current.modificationType() == UNMODIFIED) {
200 return from(childCodec, current);
203 abstract @Nullable DataTreeCandidateNode firstModifiedChild(YangInstanceIdentifier.PathArgument arg);
206 public final ImmutableList<AbstractDataObjectModification<?, ?>> getModifiedChildren() {
207 final var local = (ImmutableList<AbstractDataObjectModification<?, ?>>) MODIFIED_CHILDREN.getAcquire(this);
208 return local != null ? local : loadModifiedChilden();
212 public final <C extends ChildOf<? super T>> List<DataObjectModification<C>> getModifiedChildren(
213 final Class<C> childType) {
214 return streamModifiedChildren(childType).collect(Collectors.toList());
218 public final <H extends ChoiceIn<? super T> & DataObject, C extends ChildOf<? super H>>
219 List<DataObjectModification<C>> getModifiedChildren(final Class<H> caseType, final Class<C> childType) {
220 return streamModifiedChildren(childType)
221 .filter(child -> caseType.equals(child.identifier.getCaseType().orElse(null)))
222 .collect(Collectors.toList());
225 @SuppressWarnings("unchecked")
226 private @NonNull ImmutableList<AbstractDataObjectModification<?, ?>> loadModifiedChilden() {
227 final var builder = ImmutableList.<AbstractDataObjectModification<?, ?>>builder();
228 populateList(builder, codec, domData, domChildNodes());
229 final var computed = builder.build();
230 // Non-trivial return: use CAS to ensure we reuse concurrent loads
231 final var witness = MODIFIED_CHILDREN.compareAndExchangeRelease(this, null, computed);
232 return witness == null ? computed : (ImmutableList<AbstractDataObjectModification<?, ?>>) witness;
235 @SuppressWarnings("unchecked")
236 private <C extends DataObject> Stream<LazyDataObjectModification<C>> streamModifiedChildren(
237 final Class<C> childType) {
238 return getModifiedChildren().stream()
239 .filter(child -> childType.isAssignableFrom(child.getDataType()))
240 .map(child -> (LazyDataObjectModification<C>) child);
244 @SuppressWarnings("unchecked")
245 public final <C extends KeyAware<K> & ChildOf<? super T>, K extends Key<C>> DataObjectModification<C>
246 getModifiedChildListItem(final Class<C> listItem, final K listKey) {
247 return (DataObjectModification<C>) getModifiedChild(IdentifiableItem.of(listItem, listKey));
251 @SuppressWarnings("unchecked")
252 public final <H extends ChoiceIn<? super T> & DataObject, C extends KeyAware<K> & ChildOf<? super H>,
253 K extends Key<C>> DataObjectModification<C> getModifiedChildListItem(final Class<H> caseType,
254 final Class<C> listItem, final K listKey) {
255 return (DataObjectModification<C>) getModifiedChild(IdentifiableItem.of(caseType, listItem, listKey));
259 @SuppressWarnings("unchecked")
260 public final <C extends ChildOf<? super T>> DataObjectModification<C> getModifiedChildContainer(
261 final Class<C> child) {
262 return (DataObjectModification<C>) getModifiedChild(Item.of(child));
266 @SuppressWarnings("unchecked")
267 public final <H extends ChoiceIn<? super T> & DataObject, C extends ChildOf<? super H>> DataObjectModification<C>
268 getModifiedChildContainer(final Class<H> caseType, final Class<C> child) {
269 return (DataObjectModification<C>) getModifiedChild(Item.of(caseType, child));
273 @SuppressWarnings("unchecked")
274 public final <C extends Augmentation<T> & DataObject> DataObjectModification<C> getModifiedAugmentation(
275 final Class<C> augmentation) {
276 return (DataObjectModification<C>) getModifiedChild(Item.of(augmentation));
280 public final String toString() {
281 return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
284 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
285 return helper.add("identifier", identifier).add("domData", domData);
288 abstract @NonNull Collection<DataTreeCandidateNode> domChildNodes();
290 abstract org.opendaylight.yangtools.yang.data.tree.api.@NonNull ModificationType domModificationType();
292 private @NonNull ModificationType resolveSubtreeModificationType() {
293 return switch (codec.getChildAddressabilitySummary()) {
295 // All children are addressable, it is safe to report SUBTREE_MODIFIED
296 ModificationType.SUBTREE_MODIFIED;
297 case UNADDRESSABLE ->
298 // All children are non-addressable, report WRITE
299 ModificationType.WRITE;
301 // This case is not completely trivial, as we may have NOT_ADDRESSABLE nodes underneath us. If that
302 // is the case, we need to turn this modification into a WRITE operation, so that the user is able
303 // to observe those nodes being introduced. This is not efficient, but unfortunately unavoidable,
304 // as we cannot accurately represent such changes.
305 for (var child : domChildNodes()) {
306 if (BindingStructuralType.recursiveFrom(child) == BindingStructuralType.NOT_ADDRESSABLE) {
307 // We have a non-addressable child, turn this modification into a write
308 yield ModificationType.WRITE;
312 // No unaddressable children found, proceed in addressed mode
313 yield ModificationType.SUBTREE_MODIFIED;
318 private static void populateList(final ImmutableList.Builder<AbstractDataObjectModification<?, ?>> result,
319 final CommonDataObjectCodecTreeNode<?> parentCodec, final DataTreeCandidateNode parent,
320 final Collection<DataTreeCandidateNode> children) {
321 final var augmentChildren =
322 ArrayListMultimap.<BindingAugmentationCodecTreeNode<?>, DataTreeCandidateNode>create();
324 for (var domChildNode : parent.childNodes()) {
325 if (domChildNode.modificationType() != UNMODIFIED) {
326 final var type = BindingStructuralType.from(domChildNode);
327 if (type != BindingStructuralType.NOT_ADDRESSABLE) {
329 * Even if type is UNKNOWN, from perspective of BindingStructuralType we try to load codec for it.
330 * We will use that type to further specify debug log.
333 final var childCodec = parentCodec.yangPathArgumentChild(domChildNode.name());
334 if (childCodec instanceof BindingDataObjectCodecTreeNode<?> childDataObjectCodec) {
335 populateList(result, type, childDataObjectCodec, domChildNode);
336 } else if (childCodec instanceof BindingAugmentationCodecTreeNode<?> childAugmentationCodec) {
337 // Defer creation once we have collected all modified children
338 augmentChildren.put(childAugmentationCodec, domChildNode);
340 throw new VerifyException("Unhandled codec %s for type %s".formatted(childCodec, type));
342 } catch (final IllegalArgumentException e) {
343 if (type == BindingStructuralType.UNKNOWN) {
344 LOG.debug("Unable to deserialize unknown DOM node {}", domChildNode, e);
346 LOG.debug("Binding representation for DOM node {} was not found", domChildNode, e);
353 for (var entry : augmentChildren.asMap().entrySet()) {
354 final var modification = LazyAugmentationModification.forModifications(entry.getKey(), parent,
356 if (modification != null) {
357 result.add(modification);
362 private static void populateList(final ImmutableList.Builder<AbstractDataObjectModification<?, ?>> result,
363 final BindingStructuralType type, final BindingDataObjectCodecTreeNode<?> childCodec,
364 final DataTreeCandidateNode domChildNode) {
367 // We use parent codec intentionally.
368 populateListWithSingleCodec(result, childCodec, domChildNode.childNodes());
370 case INVISIBLE_CONTAINER:
371 populateList(result, childCodec, domChildNode, domChildNode.childNodes());
374 case VISIBLE_CONTAINER:
375 result.add(new LazyDataObjectModification<>(childCodec, domChildNode));
381 private static void populateListWithSingleCodec(
382 final ImmutableList.Builder<AbstractDataObjectModification<?, ?>> result,
383 final BindingDataObjectCodecTreeNode<?> codec, final Collection<DataTreeCandidateNode> childNodes) {
384 for (var child : childNodes) {
385 if (child.modificationType() != UNMODIFIED) {
386 result.add(new LazyDataObjectModification<>(codec, child));