2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.md.sal.dom.store.impl;
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;
34 * Resolve Data Change Events based on modifications and listeners
37 * Computes data change events for all affected registered listeners in data tree.
40 public final class ResolveDataChangeEventsTask {
41 private static final Logger LOG = LoggerFactory.getLogger(ResolveDataChangeEventsTask.class);
43 private final DataTreeCandidate candidate;
44 private final ListenerTree listenerRoot;
46 private Multimap<DataChangeListenerRegistration<?>, DOMImmutableDataChangeEvent> collectedEvents;
48 private ResolveDataChangeEventsTask(final DataTreeCandidate candidate, final ListenerTree listenerTree) {
49 this.candidate = Preconditions.checkNotNull(candidate);
50 this.listenerRoot = Preconditions.checkNotNull(listenerTree);
54 * Resolves and submits notification tasks to the specified manager.
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();
62 // Run through the tree
63 final ResolveDataChangeState s = ResolveDataChangeState.initial(candidate.getRootPath(), w.getRootNode());
64 resolveAnyChangeEvent(s, candidate.getRootNode());
67 * Convert to tasks, but be mindful of multiple values -- those indicate multiple
68 * wildcard matches, which need to be merged.
70 for (Entry<DataChangeListenerRegistration<?>, Collection<DOMImmutableDataChangeEvent>> e :
71 collectedEvents.asMap().entrySet()) {
72 final Collection<DOMImmutableDataChangeEvent> col = e.getValue();
73 final DOMImmutableDataChangeEvent event;
75 if (col.size() != 1) {
76 final Builder b = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE);
77 for (DOMImmutableDataChangeEvent i : col) {
82 LOG.trace("Merged events {} into event {}", col, event);
84 event = col.iterator().next();
87 manager.submitNotification(e.getKey(), event);
93 * Resolves data change event for supplied node.
96 * Path to current node in tree
98 * Collection of Listener registration nodes interested in
100 * @param modification
101 * Modification of current node
103 * - Original (before) state of current node
105 * - After state of current node
106 * @return True if the subtree changed, false otherwise
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();
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);
119 // no before and after state is present
122 case SUBTREE_MODIFIED:
123 return resolveSubtreeChangeEvent(state, node);
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());
135 return resolveReplacedEvent(state, maybeBefore.get(), maybeAfter.get());
138 Preconditions.checkArgument(maybeBefore.isPresent(),
139 "Modification at {} has type {} but no before-data", state.getPath(), type);
141 @SuppressWarnings({ "unchecked", "rawtypes" })
142 final NormalizedNode<PathArgument, ?> beforeNode = (NormalizedNode)maybeBefore.get();
143 resolveSameEventRecursivelly(state, beforeNode, DOMImmutableDataChangeEvent.getRemoveEventFactory());
151 throw new IllegalStateException(String.format("Unhandled node state %s at %s", type, state.getPath()));
154 private boolean resolveReplacedEvent(final ResolveDataChangeState state,
155 final NormalizedNode<?, ?> beforeData, final NormalizedNode<?, ?> afterData) {
157 if (beforeData instanceof NormalizedNodeContainer<?, ?, ?>) {
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.
164 LOG.trace("Resolving subtree replace event for {} before {}, after {}", state.getPath(), beforeData,
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);
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());
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);
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());
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();
203 if (resolveNodeContainerChildUpdated(state.child(childId), beforeChild, afterCont.getChild(childId))) {
208 for (NormalizedNode<PathArgument, ?> afterChild : afterCont.getValue()) {
209 final PathArgument childId = afterChild.getIdentifier();
212 * We have already iterated of the before-children, so have already
213 * emitted modify/delete events. This means the child has been
216 if (!beforeCont.getChild(childId).isPresent()) {
217 resolveSameEventRecursivelly(state.child(childId), afterChild,
218 DOMImmutableDataChangeEvent.getCreateEventFactory());
224 DOMImmutableDataChangeEvent event = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE)
225 .addUpdated(state.getPath(), beforeCont, afterCont).build();
226 state.addEvent(event);
229 state.collectEvents(beforeCont, afterCont, collectedEvents);
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());
240 // AFTER state is not present - child was deleted.
241 resolveSameEventRecursivelly(state, before, DOMImmutableDataChangeEvent.getRemoveEventFactory());
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());
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);
257 // Node has children, so we will try to resolve it's children
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();
265 LOG.trace("Resolving event for child {}", childId);
266 resolveSameEventRecursivelly(state.child(childId), child, eventFactory);
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);
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();
281 Preconditions.checkArgument(maybeBefore.isPresent(), "Subtree change with before-data not present at path %s",
283 Preconditions.checkArgument(maybeAfter.isPresent(), "Subtree change with after-data not present at path %s",
286 if (!state.needsProcessing()) {
287 LOG.trace("Not processing modified subtree {}", state.getPath());
291 DataChangeScope scope = null;
292 for (DataTreeCandidateNode childMod : modification.getChildNodes()) {
293 final ResolveDataChangeState childState = state.child(childMod.getIdentifier());
295 switch (childMod.getModificationType()) {
300 if (resolveAnyChangeEvent(childState, childMod)) {
301 scope = DataChangeScope.ONE;
304 case SUBTREE_MODIFIED:
305 if (resolveSubtreeChangeEvent(childState, childMod) && scope == null) {
306 scope = DataChangeScope.SUBTREE;
317 final NormalizedNode<?, ?> before = maybeBefore.get();
318 final NormalizedNode<?, ?> after = maybeAfter.get();
321 DOMImmutableDataChangeEvent one = DOMImmutableDataChangeEvent.builder(scope)
322 .addUpdated(state.getPath(), before, after).build();
326 state.collectEvents(before, after, collectedEvents);
327 return scope != null;
330 public static ResolveDataChangeEventsTask create(final DataTreeCandidate candidate,
331 final ListenerTree listenerTree) {
332 return new ResolveDataChangeEventsTask(candidate, listenerTree);