Add sal-dom-compat
[controller.git] / opendaylight / md-sal / sal-inmemory-datastore / src / main / java / org / opendaylight / controller / md / sal / dom / store / impl / ResolveDataChangeEventsTask.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.controller.md.sal.dom.store.impl;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ArrayListMultimap;
13 import com.google.common.collect.Multimap;
14 import java.util.Collection;
15 import java.util.Map.Entry;
16 import java.util.Optional;
17 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
18 import org.opendaylight.controller.md.sal.dom.store.impl.DOMImmutableDataChangeEvent.Builder;
19 import org.opendaylight.controller.md.sal.dom.store.impl.DOMImmutableDataChangeEvent.SimpleEventFactory;
20 import org.opendaylight.controller.sal.core.compat.DataChangeListenerRegistration;
21 import org.opendaylight.controller.sal.core.compat.ListenerTree;
22 import org.opendaylight.mdsal.dom.spi.RegistrationTreeSnapshot;
23 import org.opendaylight.yangtools.util.concurrent.NotificationManager;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
25 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
28 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 /**
34  * Resolve Data Change Events based on modifications and listeners
35  *
36  * <p>
37  * Computes data change events for all affected registered listeners in data tree.
38  */
39 @Beta
40 public final class ResolveDataChangeEventsTask {
41     private static final Logger LOG = LoggerFactory.getLogger(ResolveDataChangeEventsTask.class);
42
43     private final DataTreeCandidate candidate;
44     private final ListenerTree listenerRoot;
45
46     private Multimap<DataChangeListenerRegistration<?>, DOMImmutableDataChangeEvent> collectedEvents;
47
48     private ResolveDataChangeEventsTask(final DataTreeCandidate candidate, final ListenerTree listenerTree) {
49         this.candidate = Preconditions.checkNotNull(candidate);
50         this.listenerRoot = Preconditions.checkNotNull(listenerTree);
51     }
52
53     /**
54      * Resolves and submits notification tasks to the specified manager.
55      */
56     public synchronized void resolve(final NotificationManager<DataChangeListenerRegistration<?>,
57             DOMImmutableDataChangeEvent> manager) {
58         try (RegistrationTreeSnapshot<DataChangeListenerRegistration<?>> w = listenerRoot.takeSnapshot()) {
59             // Defensive: reset internal state
60             collectedEvents = ArrayListMultimap.create();
61
62             // Run through the tree
63             final ResolveDataChangeState s = ResolveDataChangeState.initial(candidate.getRootPath(), w.getRootNode());
64             resolveAnyChangeEvent(s, candidate.getRootNode());
65
66             /*
67              * Convert to tasks, but be mindful of multiple values -- those indicate multiple
68              * wildcard matches, which need to be merged.
69              */
70             for (Entry<DataChangeListenerRegistration<?>, Collection<DOMImmutableDataChangeEvent>> e :
71                     collectedEvents.asMap().entrySet()) {
72                 final Collection<DOMImmutableDataChangeEvent> col = e.getValue();
73                 final DOMImmutableDataChangeEvent event;
74
75                 if (col.size() != 1) {
76                     final Builder b = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE);
77                     for (DOMImmutableDataChangeEvent i : col) {
78                         b.merge(i);
79                     }
80
81                     event = b.build();
82                     LOG.trace("Merged events {} into event {}", col, event);
83                 } else {
84                     event = col.iterator().next();
85                 }
86
87                 manager.submitNotification(e.getKey(), event);
88             }
89         }
90     }
91
92     /**
93      * Resolves data change event for supplied node.
94      *
95      * @param path
96      *            Path to current node in tree
97      * @param listeners
98      *            Collection of Listener registration nodes interested in
99      *            subtree
100      * @param modification
101      *            Modification of current node
102      * @param before
103      *            - Original (before) state of current node
104      * @param after
105      *            - After state of current node
106      * @return True if the subtree changed, false otherwise
107      */
108     private boolean resolveAnyChangeEvent(final ResolveDataChangeState state, final DataTreeCandidateNode node) {
109         final Optional<NormalizedNode<?, ?>> maybeBefore = node.getDataBefore();
110         final Optional<NormalizedNode<?, ?>> maybeAfter = node.getDataAfter();
111         final ModificationType type = node.getModificationType();
112
113         if (type != ModificationType.UNMODIFIED && !maybeAfter.isPresent() && !maybeBefore.isPresent()) {
114             LOG.debug("Modification at {} has type {}, but no before- and after-data. Assuming unchanged.",
115                     state.getPath(), type);
116             return false;
117         }
118
119         // no before and after state is present
120
121         switch (type) {
122             case SUBTREE_MODIFIED:
123                 return resolveSubtreeChangeEvent(state, node);
124             case APPEARED:
125             case WRITE:
126                 Preconditions.checkArgument(maybeAfter.isPresent(),
127                         "Modification at {} has type {} but no after-data", state.getPath(), type);
128                 if (!maybeBefore.isPresent()) {
129                     @SuppressWarnings({ "unchecked", "rawtypes" })
130                     final NormalizedNode<PathArgument, ?> afterNode = (NormalizedNode)maybeAfter.get();
131                     resolveSameEventRecursivelly(state, afterNode, DOMImmutableDataChangeEvent.getCreateEventFactory());
132                     return true;
133                 }
134
135                 return resolveReplacedEvent(state, maybeBefore.get(), maybeAfter.get());
136             case DISAPPEARED:
137             case DELETE:
138                 Preconditions.checkArgument(maybeBefore.isPresent(),
139                         "Modification at {} has type {} but no before-data", state.getPath(), type);
140
141                 @SuppressWarnings({ "unchecked", "rawtypes" })
142                 final NormalizedNode<PathArgument, ?> beforeNode = (NormalizedNode)maybeBefore.get();
143                 resolveSameEventRecursivelly(state, beforeNode, DOMImmutableDataChangeEvent.getRemoveEventFactory());
144                 return true;
145             case UNMODIFIED:
146                 return false;
147             default:
148                 break;
149         }
150
151         throw new IllegalStateException(String.format("Unhandled node state %s at %s", type, state.getPath()));
152     }
153
154     private boolean resolveReplacedEvent(final ResolveDataChangeState state,
155             final NormalizedNode<?, ?> beforeData, final NormalizedNode<?, ?> afterData) {
156
157         if (beforeData instanceof NormalizedNodeContainer<?, ?, ?>) {
158             /*
159              * Node is a container (contains a child) and we have interested
160              * listeners registered for it, that means we need to do
161              * resolution of changes on children level and can not
162              * shortcut resolution.
163              */
164             LOG.trace("Resolving subtree replace event for {} before {}, after {}", state.getPath(), beforeData,
165                     afterData);
166             @SuppressWarnings("unchecked")
167             NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> beforeCont =
168                 (NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>>) beforeData;
169             @SuppressWarnings("unchecked")
170             NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> afterCont =
171                 (NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>>) afterData;
172             return resolveNodeContainerReplaced(state, beforeCont, afterCont);
173         }
174
175         // Node is a Leaf type (does not contain child nodes)
176         // so normal equals method is sufficient for determining change.
177         if (beforeData.equals(afterData)) {
178             LOG.trace("Skipping equal leaf {}", state.getPath());
179             return false;
180         }
181
182         LOG.trace("Resolving leaf replace event for {} , before {}, after {}", state.getPath(), beforeData, afterData);
183         DOMImmutableDataChangeEvent event = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE)
184                 .addUpdated(state.getPath(), beforeData, afterData).build();
185         state.addEvent(event);
186         state.collectEvents(beforeData, afterData, collectedEvents);
187         return true;
188     }
189
190     private boolean resolveNodeContainerReplaced(final ResolveDataChangeState state,
191             final NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> beforeCont,
192                     final NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> afterCont) {
193         if (!state.needsProcessing()) {
194             LOG.trace("Not processing replaced container {}", state.getPath());
195             return true;
196         }
197
198         // We look at all children from before and compare it with after state.
199         boolean childChanged = false;
200         for (NormalizedNode<PathArgument, ?> beforeChild : beforeCont.getValue()) {
201             final PathArgument childId = beforeChild.getIdentifier();
202
203             if (resolveNodeContainerChildUpdated(state.child(childId), beforeChild, afterCont.getChild(childId))) {
204                 childChanged = true;
205             }
206         }
207
208         for (NormalizedNode<PathArgument, ?> afterChild : afterCont.getValue()) {
209             final PathArgument childId = afterChild.getIdentifier();
210
211             /*
212              * We have already iterated of the before-children, so have already
213              * emitted modify/delete events. This means the child has been
214              * created.
215              */
216             if (!beforeCont.getChild(childId).isPresent()) {
217                 resolveSameEventRecursivelly(state.child(childId), afterChild,
218                         DOMImmutableDataChangeEvent.getCreateEventFactory());
219                 childChanged = true;
220             }
221         }
222
223         if (childChanged) {
224             DOMImmutableDataChangeEvent event = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE)
225                     .addUpdated(state.getPath(), beforeCont, afterCont).build();
226             state.addEvent(event);
227         }
228
229         state.collectEvents(beforeCont, afterCont, collectedEvents);
230         return childChanged;
231     }
232
233     private boolean resolveNodeContainerChildUpdated(final ResolveDataChangeState state,
234             final NormalizedNode<PathArgument, ?> before, final Optional<NormalizedNode<PathArgument, ?>> after) {
235         if (after.isPresent()) {
236             // REPLACE or SUBTREE Modified
237             return resolveReplacedEvent(state, before, after.get());
238         }
239
240         // AFTER state is not present - child was deleted.
241         resolveSameEventRecursivelly(state, before, DOMImmutableDataChangeEvent.getRemoveEventFactory());
242         return true;
243     }
244
245     private void resolveSameEventRecursivelly(final ResolveDataChangeState state,
246             final NormalizedNode<PathArgument, ?> node, final SimpleEventFactory eventFactory) {
247         if (!state.needsProcessing()) {
248             LOG.trace("Skipping child {}", state.getPath());
249             return;
250         }
251
252         // We have listeners for this node or it's children, so we will try
253         // to do additional processing
254         if (node instanceof NormalizedNodeContainer<?, ?, ?>) {
255             LOG.trace("Resolving subtree recursive event for {}, type {}", state.getPath(), eventFactory);
256
257             // Node has children, so we will try to resolve it's children
258             // changes.
259             @SuppressWarnings("unchecked")
260             NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> container =
261                 (NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>>) node;
262             for (NormalizedNode<PathArgument, ?> child : container.getValue()) {
263                 final PathArgument childId = child.getIdentifier();
264
265                 LOG.trace("Resolving event for child {}", childId);
266                 resolveSameEventRecursivelly(state.child(childId), child, eventFactory);
267             }
268         }
269
270         final DOMImmutableDataChangeEvent event = eventFactory.create(state.getPath(), node);
271         LOG.trace("Adding event {} at path {}", event, state.getPath());
272         state.addEvent(event);
273         state.collectEvents(event.getOriginalSubtree(), event.getUpdatedSubtree(), collectedEvents);
274     }
275
276     private boolean resolveSubtreeChangeEvent(final ResolveDataChangeState state,
277             final DataTreeCandidateNode modification) {
278         final Optional<NormalizedNode<?, ?>> maybeBefore = modification.getDataBefore();
279         final Optional<NormalizedNode<?, ?>> maybeAfter = modification.getDataAfter();
280
281         Preconditions.checkArgument(maybeBefore.isPresent(), "Subtree change with before-data not present at path %s",
282                 state.getPath());
283         Preconditions.checkArgument(maybeAfter.isPresent(), "Subtree change with after-data not present at path %s",
284                 state.getPath());
285
286         if (!state.needsProcessing()) {
287             LOG.trace("Not processing modified subtree {}", state.getPath());
288             return true;
289         }
290
291         DataChangeScope scope = null;
292         for (DataTreeCandidateNode childMod : modification.getChildNodes()) {
293             final ResolveDataChangeState childState = state.child(childMod.getIdentifier());
294
295             switch (childMod.getModificationType()) {
296                 case APPEARED:
297                 case DELETE:
298                 case DISAPPEARED:
299                 case WRITE:
300                     if (resolveAnyChangeEvent(childState, childMod)) {
301                         scope = DataChangeScope.ONE;
302                     }
303                     break;
304                 case SUBTREE_MODIFIED:
305                     if (resolveSubtreeChangeEvent(childState, childMod) && scope == null) {
306                         scope = DataChangeScope.SUBTREE;
307                     }
308                     break;
309                 case UNMODIFIED:
310                     // no-op
311                     break;
312                 default:
313                     break;
314             }
315         }
316
317         final NormalizedNode<?, ?> before = maybeBefore.get();
318         final NormalizedNode<?, ?> after = maybeAfter.get();
319
320         if (scope != null) {
321             DOMImmutableDataChangeEvent one = DOMImmutableDataChangeEvent.builder(scope)
322                     .addUpdated(state.getPath(), before, after).build();
323             state.addEvent(one);
324         }
325
326         state.collectEvents(before, after, collectedEvents);
327         return scope != null;
328     }
329
330     public static ResolveDataChangeEventsTask create(final DataTreeCandidate candidate,
331             final ListenerTree listenerTree) {
332         return new ResolveDataChangeEventsTask(candidate, listenerTree);
333     }
334 }