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