Cleanup: Remove passing around of DataPersistenceProvider
[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.spi.RegistrationTreeSnapshot;
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.md.sal.dom.store.impl.tree.ListenerTree;
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 RegistrationTreeSnapshot<DataChangeListenerRegistration<?>> w = listenerRoot.takeSnapshot()) {
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         final Optional<NormalizedNode<?, ?>> maybeBefore = node.getDataBefore();
105         final Optional<NormalizedNode<?, ?>> maybeAfter = node.getDataAfter();
106         final ModificationType type = node.getModificationType();
107
108         if (type != ModificationType.UNMODIFIED && !maybeAfter.isPresent() && !maybeBefore.isPresent()) {
109             LOG.debug("Modification at {} has type {}, but no before- and after-data. Assuming unchanged.",
110                     state.getPath(), type);
111             return false;
112         }
113
114         // no before and after state is present
115
116         switch (type) {
117         case SUBTREE_MODIFIED:
118             return resolveSubtreeChangeEvent(state, node);
119         case MERGE:
120         case WRITE:
121             Preconditions.checkArgument(maybeAfter.isPresent(),
122                     "Modification at {} has type {} but no after-data", state.getPath(), type);
123             if (!maybeBefore.isPresent()) {
124                 @SuppressWarnings({ "unchecked", "rawtypes" })
125                 final NormalizedNode<PathArgument, ?> afterNode = (NormalizedNode)maybeAfter.get();
126                 resolveSameEventRecursivelly(state, afterNode, DOMImmutableDataChangeEvent.getCreateEventFactory());
127                 return true;
128             }
129
130             return resolveReplacedEvent(state, maybeBefore.get(), maybeAfter.get());
131         case DELETE:
132             Preconditions.checkArgument(maybeBefore.isPresent(),
133                     "Modification at {} has type {} but no before-data", state.getPath(), type);
134
135             @SuppressWarnings({ "unchecked", "rawtypes" })
136             final NormalizedNode<PathArgument, ?> beforeNode = (NormalizedNode)maybeBefore.get();
137             resolveSameEventRecursivelly(state, beforeNode, DOMImmutableDataChangeEvent.getRemoveEventFactory());
138             return true;
139         case UNMODIFIED:
140             return false;
141         }
142
143         throw new IllegalStateException(String.format("Unhandled node state %s at %s", type, state.getPath()));
144     }
145
146     private boolean resolveReplacedEvent(final ResolveDataChangeState state,
147             final NormalizedNode<?, ?> beforeData, final NormalizedNode<?, ?> afterData) {
148
149         if (beforeData instanceof NormalizedNodeContainer<?, ?, ?>) {
150             /*
151              * Node is a container (contains a child) and we have interested
152              * listeners registered for it, that means we need to do
153              * resolution of changes on children level and can not
154              * shortcut resolution.
155              */
156             LOG.trace("Resolving subtree replace event for {} before {}, after {}", state.getPath(), beforeData, afterData);
157             @SuppressWarnings("unchecked")
158             NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> beforeCont = (NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>>) beforeData;
159             @SuppressWarnings("unchecked")
160             NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> afterCont = (NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>>) afterData;
161             return resolveNodeContainerReplaced(state, beforeCont, afterCont);
162         }
163
164         // Node is a Leaf type (does not contain child nodes)
165         // so normal equals method is sufficient for determining change.
166         if (beforeData.equals(afterData)) {
167             LOG.trace("Skipping equal leaf {}", state.getPath());
168             return false;
169         }
170
171         LOG.trace("Resolving leaf replace event for {} , before {}, after {}", state.getPath(), beforeData, afterData);
172         DOMImmutableDataChangeEvent event = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE).addUpdated(state.getPath(), beforeData, afterData).build();
173         state.addEvent(event);
174         state.collectEvents(beforeData, afterData, collectedEvents);
175         return true;
176     }
177
178     private boolean resolveNodeContainerReplaced(final ResolveDataChangeState state,
179             final NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> beforeCont,
180                     final NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> afterCont) {
181         if (!state.needsProcessing()) {
182             LOG.trace("Not processing replaced container {}", state.getPath());
183             return true;
184         }
185
186         // We look at all children from before and compare it with after state.
187         boolean childChanged = false;
188         for (NormalizedNode<PathArgument, ?> beforeChild : beforeCont.getValue()) {
189             final PathArgument childId = beforeChild.getIdentifier();
190
191             if (resolveNodeContainerChildUpdated(state.child(childId), beforeChild, afterCont.getChild(childId))) {
192                 childChanged = true;
193             }
194         }
195
196         for (NormalizedNode<PathArgument, ?> afterChild : afterCont.getValue()) {
197             final PathArgument childId = afterChild.getIdentifier();
198
199             /*
200              * We have already iterated of the before-children, so have already
201              * emitted modify/delete events. This means the child has been
202              * created.
203              */
204             if (!beforeCont.getChild(childId).isPresent()) {
205                 resolveSameEventRecursivelly(state.child(childId), afterChild, DOMImmutableDataChangeEvent.getCreateEventFactory());
206                 childChanged = true;
207             }
208         }
209
210         if (childChanged) {
211             DOMImmutableDataChangeEvent event = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE)
212                     .addUpdated(state.getPath(), beforeCont, afterCont).build();
213             state.addEvent(event);
214         }
215
216         state.collectEvents(beforeCont, afterCont, collectedEvents);
217         return childChanged;
218     }
219
220     private boolean resolveNodeContainerChildUpdated(final ResolveDataChangeState state,
221             final NormalizedNode<PathArgument, ?> before, final Optional<NormalizedNode<PathArgument, ?>> after) {
222         if (after.isPresent()) {
223             // REPLACE or SUBTREE Modified
224             return resolveReplacedEvent(state, before, after.get());
225         }
226
227         // AFTER state is not present - child was deleted.
228         resolveSameEventRecursivelly(state, before, DOMImmutableDataChangeEvent.getRemoveEventFactory());
229         return true;
230     }
231
232     private void resolveSameEventRecursivelly(final ResolveDataChangeState state,
233             final NormalizedNode<PathArgument, ?> node, final SimpleEventFactory eventFactory) {
234         if (!state.needsProcessing()) {
235             LOG.trace("Skipping child {}", state.getPath());
236             return;
237         }
238
239         // We have listeners for this node or it's children, so we will try
240         // to do additional processing
241         if (node instanceof NormalizedNodeContainer<?, ?, ?>) {
242             LOG.trace("Resolving subtree recursive event for {}, type {}", state.getPath(), eventFactory);
243
244             // Node has children, so we will try to resolve it's children
245             // changes.
246             @SuppressWarnings("unchecked")
247             NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> container = (NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>>) node;
248             for (NormalizedNode<PathArgument, ?> child : container.getValue()) {
249                 final PathArgument childId = child.getIdentifier();
250
251                 LOG.trace("Resolving event for child {}", childId);
252                 resolveSameEventRecursivelly(state.child(childId), child, eventFactory);
253             }
254         }
255
256         final DOMImmutableDataChangeEvent event = eventFactory.create(state.getPath(), node);
257         LOG.trace("Adding event {} at path {}", event, state.getPath());
258         state.addEvent(event);
259         state.collectEvents(event.getOriginalSubtree(), event.getUpdatedSubtree(), collectedEvents);
260     }
261
262     private boolean resolveSubtreeChangeEvent(final ResolveDataChangeState state, final DataTreeCandidateNode modification) {
263         final Optional<NormalizedNode<?, ?>> maybeBefore = modification.getDataBefore();
264         final Optional<NormalizedNode<?, ?>> maybeAfter = modification.getDataAfter();
265
266         Preconditions.checkArgument(maybeBefore.isPresent(), "Subtree change with before-data not present at path %s", state.getPath());
267         Preconditions.checkArgument(maybeAfter.isPresent(), "Subtree change with after-data not present at path %s", state.getPath());
268
269         if (!state.needsProcessing()) {
270             LOG.trace("Not processing modified subtree {}", state.getPath());
271             return true;
272         }
273
274         DataChangeScope scope = null;
275         for (DataTreeCandidateNode childMod : modification.getChildNodes()) {
276             final ResolveDataChangeState childState = state.child(childMod.getIdentifier());
277
278             switch (childMod.getModificationType()) {
279             case WRITE:
280             case MERGE:
281             case DELETE:
282                 if (resolveAnyChangeEvent(childState, childMod)) {
283                     scope = DataChangeScope.ONE;
284                 }
285                 break;
286             case SUBTREE_MODIFIED:
287                 if (resolveSubtreeChangeEvent(childState, childMod) && scope == null) {
288                     scope = DataChangeScope.SUBTREE;
289                 }
290                 break;
291             case UNMODIFIED:
292                 // no-op
293                 break;
294             }
295         }
296
297         final NormalizedNode<?, ?> before = maybeBefore.get();
298         final NormalizedNode<?, ?> after = maybeAfter.get();
299
300         if (scope != null) {
301             DOMImmutableDataChangeEvent one = DOMImmutableDataChangeEvent.builder(scope).addUpdated(state.getPath(), before, after).build();
302             state.addEvent(one);
303         }
304
305         state.collectEvents(before, after, collectedEvents);
306         return scope != null;
307     }
308
309     public static ResolveDataChangeEventsTask create(final DataTreeCandidate candidate, final ListenerTree listenerTree) {
310         return new ResolveDataChangeEventsTask(candidate, listenerTree);
311     }
312 }