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