summaryrefslogtreecommitdiffstats
path: root/infra/data-impl/src/main/java/io/fd/honeycomb/data/impl/ModificationDiff.java
blob: 710f8a0538d37374df9299c15f43cff4d8c0ecb9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
/*
 * Copyright (c) 2016 Cisco and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.fd.honeycomb.data.impl;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.collect.ImmutableMap;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
import org.opendaylight.yangtools.yang.data.api.schema.MixinNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;

/**
 * Recursively collects and provides all unique and non-null modifications (modified normalized nodes).
 */
final class ModificationDiff {

    private static final ModificationDiff EMPTY_DIFF = new ModificationDiff(Collections.emptyMap());
    private static final EnumSet LEAF_MODIFICATIONS = EnumSet.of(ModificationType.WRITE, ModificationType.DELETE);

    private final Map<YangInstanceIdentifier, NormalizedNodeUpdate> updates;

    private ModificationDiff(@Nonnull Map<YangInstanceIdentifier, NormalizedNodeUpdate> updates) {
        this.updates = updates;
    }

    /**
     * Get processed modifications.
     *
     * @return mapped modifications, where key is keyed {@link YangInstanceIdentifier}.
     */
    Map<YangInstanceIdentifier, NormalizedNodeUpdate> getUpdates() {
        return updates;
    }

    private ModificationDiff merge(final ModificationDiff other) {
        if (this == EMPTY_DIFF) {
            return other;
        }

        if (other == EMPTY_DIFF) {
            return this;
        }

        return new ModificationDiff(join(updates, other.updates));
    }

    private static Map<YangInstanceIdentifier, NormalizedNodeUpdate> join(Map<YangInstanceIdentifier, NormalizedNodeUpdate> first,
                                                                          Map<YangInstanceIdentifier, NormalizedNodeUpdate> second) {
        final Map<YangInstanceIdentifier, NormalizedNodeUpdate> merged = new HashMap<>();
        merged.putAll(first);
        merged.putAll(second);
        return merged;
    }

    private static ModificationDiff create(YangInstanceIdentifier id, DataTreeCandidateNode candidate) {
        return new ModificationDiff(ImmutableMap.of(id, NormalizedNodeUpdate.create(id, candidate)));
    }

    /**
     * Produce an aggregated diff from a candidate node recursively. MixinNodes are ignored as modifications and so
     * are complex nodes which direct leaves were not modified.
     */
    @Nonnull
    static ModificationDiff recursivelyFromCandidate(@Nonnull final YangInstanceIdentifier yangIid,
                                                     @Nonnull final DataTreeCandidateNode currentCandidate) {
        // recursively process child nodes for exact modifications
        return recursivelyChildrenFromCandidate(yangIid, currentCandidate)
                // also add modification on current level, if elligible
                .merge(isModification(currentCandidate)
                        ? ModificationDiff.create(yangIid, currentCandidate)
                        : EMPTY_DIFF);
    }

    /**
     * Check whether current node was modified. {@link MixinNode}s are ignored
     * and only nodes which direct leaves(or choices) are modified are considered a modification.
     */
    private static Boolean isModification(@Nonnull final DataTreeCandidateNode currentCandidate) {
        // Mixin nodes are not considered modifications
        if (isMixin(currentCandidate) && !isAugment(currentCandidate)) {
            return false;
        } else {
            return isCurrentModified(currentCandidate);
        }
    }

    private static Boolean isCurrentModified(final @Nonnull DataTreeCandidateNode currentCandidate) {
        // Check if there are any modified leaves and if so, consider current node as modified
        final Boolean directLeavesModified = currentCandidate.getChildNodes().stream()
                .filter(ModificationDiff::isLeaf)
                // For some reason, we get modifications on unmodified list keys TODO debug and report ODL bug
                // and that messes up our modifications collection here, so we need to skip
                .filter(ModificationDiff::isBeforeAndAfterDifferent)
                .filter(child -> LEAF_MODIFICATIONS.contains(child.getModificationType()))
                .findFirst()
                .isPresent();

        return directLeavesModified
                // Also check choices (choices do not exist in BA world and if anything within a choice was modified,
                // consider its parent as being modified)
                || currentCandidate.getChildNodes().stream()
                        .filter(ModificationDiff::isChoice)
                        // Recursively check each choice if there was any change to it
                        .filter(ModificationDiff::isCurrentModified)
                        .findFirst()
                        .isPresent();
    }

    /**
     * Process all non-leaf child nodes recursively, creating aggregated {@link ModificationDiff}.
     */
    private static ModificationDiff recursivelyChildrenFromCandidate(final @Nonnull YangInstanceIdentifier yangIid,
                                                                     final @Nonnull DataTreeCandidateNode currentCandidate) {
        // recursively process child nodes for specific modifications
        return currentCandidate.getChildNodes().stream()
                // not interested in modifications to leaves
                .filter(child -> !isLeaf(child))
                .map(candidate -> recursivelyFromCandidate(yangIid.node(candidate.getIdentifier()), candidate))
                .reduce(ModificationDiff::merge)
                .orElse(EMPTY_DIFF);
    }

    /**
     * Check whether candidate.before and candidate.after is different. If not return false.
     */
    private static boolean isBeforeAndAfterDifferent(@Nonnull final DataTreeCandidateNode candidateNode) {
        if (candidateNode.getDataBefore().isPresent()) {
            return !candidateNode.getDataBefore().get().equals(candidateNode.getDataAfter().orNull());
        }

        // considering not a modification if data after is also null
        return candidateNode.getDataAfter().isPresent();
    }

    /**
     * Check whether candidate node is for a leaf type node.
     */
    private static boolean isLeaf(final DataTreeCandidateNode candidateNode) {
        // orNull intentional, some candidate nodes have both data after and data before null
        return candidateNode.getDataAfter().orNull() instanceof LeafNode<?>
                || candidateNode.getDataBefore().orNull() instanceof LeafNode<?>;
    }

    /**
     * Check whether candidate node is for a Mixin type node.
     */
    private static boolean isMixin(final DataTreeCandidateNode candidateNode) {
        // orNull intentional, some candidate nodes have both data after and data before null
        return candidateNode.getDataAfter().orNull() instanceof MixinNode
                || candidateNode.getDataBefore().orNull() instanceof MixinNode;
    }

    /**
     * Check whether candidate node is for an Augmentation type node.
     */
    private static boolean isAugment(final DataTreeCandidateNode candidateNode) {
        // orNull intentional, some candidate nodes have both data after and data before null
        return candidateNode.getDataAfter().orNull() instanceof AugmentationNode
                || candidateNode.getDataBefore().orNull() instanceof AugmentationNode;
    }

    /**
     * Check whether candidate node is for a Choice type node.
     */
    private static boolean isChoice(final DataTreeCandidateNode candidateNode) {
        // orNull intentional, some candidate nodes have both data after and data before null
        return candidateNode.getDataAfter().orNull() instanceof ChoiceNode
                || candidateNode.getDataBefore().orNull() instanceof ChoiceNode;
    }

    @Override
    public String toString() {
        return "ModificationDiff{updates=" + updates + '}';
    }

    /**
     * Update to a normalized node identifiable by its {@link YangInstanceIdentifier}.
     */
    static final class NormalizedNodeUpdate {

        @Nonnull
        private final YangInstanceIdentifier id;
        @Nullable
        private final NormalizedNode<?, ?> dataBefore;
        @Nullable
        private final NormalizedNode<?, ?> dataAfter;

        private NormalizedNodeUpdate(@Nonnull final YangInstanceIdentifier id,
                                     @Nullable final NormalizedNode<?, ?> dataBefore,
                                     @Nullable final NormalizedNode<?, ?> dataAfter) {
            this.id = checkNotNull(id);
            this.dataAfter = dataAfter;
            this.dataBefore = dataBefore;
        }

        @Nullable
        public NormalizedNode<?, ?> getDataBefore() {
            return dataBefore;
        }

        @Nullable
        public NormalizedNode<?, ?> getDataAfter() {
            return dataAfter;
        }

        @Nonnull
        public YangInstanceIdentifier getId() {
            return id;
        }

        static NormalizedNodeUpdate create(@Nonnull final YangInstanceIdentifier id,
                                           @Nonnull final DataTreeCandidateNode candidate) {
            return create(id, candidate.getDataBefore().orNull(), candidate.getDataAfter().orNull());
        }

        static NormalizedNodeUpdate create(@Nonnull final YangInstanceIdentifier id,
                                           @Nullable final NormalizedNode<?, ?> dataBefore,
                                           @Nullable final NormalizedNode<?, ?> dataAfter) {
            checkArgument(!(dataBefore == null && dataAfter == null), "Both before and after data are null");
            return new NormalizedNodeUpdate(id, dataBefore, dataAfter);
        }

        @Override
        public boolean equals(final Object other) {
            if (this == other) {
                return true;
            }
            if (other == null || getClass() != other.getClass()) {
                return false;
            }

            final NormalizedNodeUpdate that = (NormalizedNodeUpdate) other;

            return id.equals(that.id);

        }

        @Override
        public int hashCode() {
            return id.hashCode();
        }

        @Override
        public String toString() {
            return "NormalizedNodeUpdate{" + "id=" + id
                    + ", dataBefore=" + dataBefore
                    + ", dataAfter=" + dataAfter
                    + '}';
        }
    }

}