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.md.sal.dom.store.impl.tree.ListenerTree;
21 import org.opendaylight.mdsal.dom.spi.RegistrationTreeSnapshot;
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;
33 * Resolve Data Change Events based on modifications and listeners
36 * Computes data change events for all affected registered listeners in data tree.
39 public final class ResolveDataChangeEventsTask {
40 private static final Logger LOG = LoggerFactory.getLogger(ResolveDataChangeEventsTask.class);
42 private final DataTreeCandidate candidate;
43 private final ListenerTree listenerRoot;
45 private Multimap<DataChangeListenerRegistration<?>, DOMImmutableDataChangeEvent> collectedEvents;
47 private ResolveDataChangeEventsTask(final DataTreeCandidate candidate, final ListenerTree listenerTree) {
48 this.candidate = Preconditions.checkNotNull(candidate);
49 this.listenerRoot = Preconditions.checkNotNull(listenerTree);
53 * Resolves and submits notification tasks to the specified manager.
55 public synchronized void resolve(final NotificationManager<DataChangeListenerRegistration<?>,
56 DOMImmutableDataChangeEvent> manager) {
57 try (RegistrationTreeSnapshot<DataChangeListenerRegistration<?>> w = listenerRoot.takeSnapshot()) {
58 // Defensive: reset internal state
59 collectedEvents = ArrayListMultimap.create();
61 // Run through the tree
62 final ResolveDataChangeState s = ResolveDataChangeState.initial(candidate.getRootPath(), w.getRootNode());
63 resolveAnyChangeEvent(s, candidate.getRootNode());
66 * Convert to tasks, but be mindful of multiple values -- those indicate multiple
67 * wildcard matches, which need to be merged.
69 for (Entry<DataChangeListenerRegistration<?>, Collection<DOMImmutableDataChangeEvent>> e :
70 collectedEvents.asMap().entrySet()) {
71 final Collection<DOMImmutableDataChangeEvent> col = e.getValue();
72 final DOMImmutableDataChangeEvent event;
74 if (col.size() != 1) {
75 final Builder b = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE);
76 for (DOMImmutableDataChangeEvent i : col) {
81 LOG.trace("Merged events {} into event {}", col, event);
83 event = col.iterator().next();
86 manager.submitNotification(e.getKey(), event);
92 * Resolves data change event for supplied node.
95 * Path to current node in tree
97 * Collection of Listener registration nodes interested in
100 * Modification of current node
102 * - Original (before) state of current node
104 * - After state of current node
105 * @return True if the subtree changed, false otherwise
107 private boolean resolveAnyChangeEvent(final ResolveDataChangeState state, final DataTreeCandidateNode node) {
108 final Optional<NormalizedNode<?, ?>> maybeBefore = node.getDataBefore();
109 final Optional<NormalizedNode<?, ?>> maybeAfter = node.getDataAfter();
110 final ModificationType type = node.getModificationType();
112 if (type != ModificationType.UNMODIFIED && !maybeAfter.isPresent() && !maybeBefore.isPresent()) {
113 LOG.debug("Modification at {} has type {}, but no before- and after-data. Assuming unchanged.",
114 state.getPath(), type);
118 // no before and after state is present
121 case SUBTREE_MODIFIED:
122 return resolveSubtreeChangeEvent(state, node);
125 Preconditions.checkArgument(maybeAfter.isPresent(),
126 "Modification at {} has type {} but no after-data", state.getPath(), type);
127 if (!maybeBefore.isPresent()) {
128 @SuppressWarnings({ "unchecked", "rawtypes" })
129 final NormalizedNode<PathArgument, ?> afterNode = (NormalizedNode)maybeAfter.get();
130 resolveSameEventRecursivelly(state, afterNode, DOMImmutableDataChangeEvent.getCreateEventFactory());
134 return resolveReplacedEvent(state, maybeBefore.get(), maybeAfter.get());
137 Preconditions.checkArgument(maybeBefore.isPresent(),
138 "Modification at {} has type {} but no before-data", state.getPath(), type);
140 @SuppressWarnings({ "unchecked", "rawtypes" })
141 final NormalizedNode<PathArgument, ?> beforeNode = (NormalizedNode)maybeBefore.get();
142 resolveSameEventRecursivelly(state, beforeNode, DOMImmutableDataChangeEvent.getRemoveEventFactory());
150 throw new IllegalStateException(String.format("Unhandled node state %s at %s", type, state.getPath()));
153 private boolean resolveReplacedEvent(final ResolveDataChangeState state,
154 final NormalizedNode<?, ?> beforeData, final NormalizedNode<?, ?> afterData) {
156 if (beforeData instanceof NormalizedNodeContainer<?, ?, ?>) {
158 * Node is a container (contains a child) and we have interested
159 * listeners registered for it, that means we need to do
160 * resolution of changes on children level and can not
161 * shortcut resolution.
163 LOG.trace("Resolving subtree replace event for {} before {}, after {}", state.getPath(), beforeData,
165 @SuppressWarnings("unchecked")
166 NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> beforeCont =
167 (NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>>) beforeData;
168 @SuppressWarnings("unchecked")
169 NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> afterCont =
170 (NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>>) afterData;
171 return resolveNodeContainerReplaced(state, beforeCont, afterCont);
174 // Node is a Leaf type (does not contain child nodes)
175 // so normal equals method is sufficient for determining change.
176 if (beforeData.equals(afterData)) {
177 LOG.trace("Skipping equal leaf {}", state.getPath());
181 LOG.trace("Resolving leaf replace event for {} , before {}, after {}", state.getPath(), beforeData, afterData);
182 DOMImmutableDataChangeEvent event = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE)
183 .addUpdated(state.getPath(), beforeData, afterData).build();
184 state.addEvent(event);
185 state.collectEvents(beforeData, afterData, collectedEvents);
189 private boolean resolveNodeContainerReplaced(final ResolveDataChangeState state,
190 final NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> beforeCont,
191 final NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> afterCont) {
192 if (!state.needsProcessing()) {
193 LOG.trace("Not processing replaced container {}", state.getPath());
197 // We look at all children from before and compare it with after state.
198 boolean childChanged = false;
199 for (NormalizedNode<PathArgument, ?> beforeChild : beforeCont.getValue()) {
200 final PathArgument childId = beforeChild.getIdentifier();
202 if (resolveNodeContainerChildUpdated(state.child(childId), beforeChild, afterCont.getChild(childId))) {
207 for (NormalizedNode<PathArgument, ?> afterChild : afterCont.getValue()) {
208 final PathArgument childId = afterChild.getIdentifier();
211 * We have already iterated of the before-children, so have already
212 * emitted modify/delete events. This means the child has been
215 if (!beforeCont.getChild(childId).isPresent()) {
216 resolveSameEventRecursivelly(state.child(childId), afterChild,
217 DOMImmutableDataChangeEvent.getCreateEventFactory());
223 DOMImmutableDataChangeEvent event = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE)
224 .addUpdated(state.getPath(), beforeCont, afterCont).build();
225 state.addEvent(event);
228 state.collectEvents(beforeCont, afterCont, collectedEvents);
232 private boolean resolveNodeContainerChildUpdated(final ResolveDataChangeState state,
233 final NormalizedNode<PathArgument, ?> before, final Optional<NormalizedNode<PathArgument, ?>> after) {
234 if (after.isPresent()) {
235 // REPLACE or SUBTREE Modified
236 return resolveReplacedEvent(state, before, after.get());
239 // AFTER state is not present - child was deleted.
240 resolveSameEventRecursivelly(state, before, DOMImmutableDataChangeEvent.getRemoveEventFactory());
244 private void resolveSameEventRecursivelly(final ResolveDataChangeState state,
245 final NormalizedNode<PathArgument, ?> node, final SimpleEventFactory eventFactory) {
246 if (!state.needsProcessing()) {
247 LOG.trace("Skipping child {}", state.getPath());
251 // We have listeners for this node or it's children, so we will try
252 // to do additional processing
253 if (node instanceof NormalizedNodeContainer<?, ?, ?>) {
254 LOG.trace("Resolving subtree recursive event for {}, type {}", state.getPath(), eventFactory);
256 // Node has children, so we will try to resolve it's children
258 @SuppressWarnings("unchecked")
259 NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> container =
260 (NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>>) node;
261 for (NormalizedNode<PathArgument, ?> child : container.getValue()) {
262 final PathArgument childId = child.getIdentifier();
264 LOG.trace("Resolving event for child {}", childId);
265 resolveSameEventRecursivelly(state.child(childId), child, eventFactory);
269 final DOMImmutableDataChangeEvent event = eventFactory.create(state.getPath(), node);
270 LOG.trace("Adding event {} at path {}", event, state.getPath());
271 state.addEvent(event);
272 state.collectEvents(event.getOriginalSubtree(), event.getUpdatedSubtree(), collectedEvents);
275 private boolean resolveSubtreeChangeEvent(final ResolveDataChangeState state,
276 final DataTreeCandidateNode modification) {
277 final Optional<NormalizedNode<?, ?>> maybeBefore = modification.getDataBefore();
278 final Optional<NormalizedNode<?, ?>> maybeAfter = modification.getDataAfter();
280 Preconditions.checkArgument(maybeBefore.isPresent(), "Subtree change with before-data not present at path %s",
282 Preconditions.checkArgument(maybeAfter.isPresent(), "Subtree change with after-data not present at path %s",
285 if (!state.needsProcessing()) {
286 LOG.trace("Not processing modified subtree {}", state.getPath());
290 DataChangeScope scope = null;
291 for (DataTreeCandidateNode childMod : modification.getChildNodes()) {
292 final ResolveDataChangeState childState = state.child(childMod.getIdentifier());
294 switch (childMod.getModificationType()) {
299 if (resolveAnyChangeEvent(childState, childMod)) {
300 scope = DataChangeScope.ONE;
303 case SUBTREE_MODIFIED:
304 if (resolveSubtreeChangeEvent(childState, childMod) && scope == null) {
305 scope = DataChangeScope.SUBTREE;
316 final NormalizedNode<?, ?> before = maybeBefore.get();
317 final NormalizedNode<?, ?> after = maybeAfter.get();
320 DOMImmutableDataChangeEvent one = DOMImmutableDataChangeEvent.builder(scope)
321 .addUpdated(state.getPath(), before, after).build();
325 state.collectEvents(before, after, collectedEvents);
326 return scope != null;
329 public static ResolveDataChangeEventsTask create(final DataTreeCandidate candidate,
330 final ListenerTree listenerTree) {
331 return new ResolveDataChangeEventsTask(candidate, listenerTree);