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