2 * Copyright (c) 2016 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
9 package org.opendaylight.controller.cluster.sharding;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import java.util.ArrayList;
14 import java.util.Collection;
15 import java.util.Collections;
16 import java.util.Iterator;
17 import java.util.LinkedList;
18 import java.util.List;
20 import java.util.concurrent.ConcurrentHashMap;
21 import java.util.stream.Collectors;
22 import javax.annotation.Nonnull;
23 import javax.annotation.Nullable;
24 import javax.annotation.concurrent.GuardedBy;
25 import org.opendaylight.controller.cluster.databroker.actors.dds.DataStoreClient;
26 import org.opendaylight.controller.cluster.datastore.AbstractDataStore;
27 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
28 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
29 import org.opendaylight.mdsal.dom.spi.AbstractDOMDataTreeChangeListenerRegistration;
30 import org.opendaylight.mdsal.dom.spi.AbstractRegistrationTree;
31 import org.opendaylight.mdsal.dom.spi.RegistrationTreeNode;
32 import org.opendaylight.mdsal.dom.spi.shard.ChildShardContext;
33 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTreeChangePublisher;
34 import org.opendaylight.yangtools.concepts.ListenerRegistration;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
39 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
40 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
42 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
43 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
44 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
45 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
46 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
47 import org.opendaylight.yangtools.yang.data.impl.schema.tree.SchemaValidationFailedException;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
51 public class DistributedShardChangePublisher
52 extends AbstractRegistrationTree<AbstractDOMDataTreeChangeListenerRegistration<?>>
53 implements DOMStoreTreeChangePublisher {
55 private static final Logger LOG = LoggerFactory.getLogger(DistributedShardChangePublisher.class);
57 private final AbstractDataStore distributedDataStore;
58 private final YangInstanceIdentifier shardPath;
60 private final Map<DOMDataTreeIdentifier, ChildShardContext> childShards;
63 private final DataTree dataTree;
65 public DistributedShardChangePublisher(final DataStoreClient client,
66 final AbstractDataStore distributedDataStore,
67 final DOMDataTreeIdentifier prefix,
68 final Map<DOMDataTreeIdentifier, ChildShardContext> childShards) {
69 this.distributedDataStore = distributedDataStore;
70 // TODO keeping the whole dataTree thats contained in subshards doesn't seem like a good idea
71 // maybe the whole listener logic would be better in the backend shards where we have direct access to the
72 // dataTree and wont have to cache it redundantly.
73 this.dataTree = InMemoryDataTreeFactory.getInstance().create(
74 TreeType.valueOf(prefix.getDatastoreType().name()), prefix.getRootIdentifier());
76 dataTree.setSchemaContext(distributedDataStore.getActorContext().getSchemaContext());
78 this.shardPath = prefix.getRootIdentifier();
79 this.childShards = childShards;
82 protected void registrationRemoved(final AbstractDOMDataTreeChangeListenerRegistration<?> registration) {
83 LOG.debug("Closing registration {}", registration);
87 public <L extends DOMDataTreeChangeListener> AbstractDOMDataTreeChangeListenerRegistration<L>
88 registerTreeChangeListener(final YangInstanceIdentifier path, final L listener) {
91 return setupListenerContext(path, listener);
97 private <L extends DOMDataTreeChangeListener> AbstractDOMDataTreeChangeListenerRegistration<L>
98 setupListenerContext(final YangInstanceIdentifier listenerPath, final L listener) {
99 // we need to register the listener registration path based on the shards root
100 // we have to strip the shard path from the listener path and then register
101 YangInstanceIdentifier strippedIdentifier = listenerPath;
102 if (!shardPath.isEmpty()) {
103 strippedIdentifier = YangInstanceIdentifier.create(stripShardPath(shardPath, listenerPath));
106 final DOMDataTreeListenerWithSubshards subshardListener =
107 new DOMDataTreeListenerWithSubshards(strippedIdentifier, listener);
108 final AbstractDOMDataTreeChangeListenerRegistration<L> reg =
109 setupContextWithoutSubshards(listenerPath, strippedIdentifier, subshardListener);
111 for (final ChildShardContext maybeAffected : childShards.values()) {
112 if (listenerPath.contains(maybeAffected.getPrefix().getRootIdentifier())) {
113 // consumer has initialDataChangeEvent subshard somewhere on lower level
114 // register to the notification manager with snapshot and forward child notifications to parent
115 LOG.debug("Adding new subshard{{}} to listener at {}", maybeAffected.getPrefix(), listenerPath);
116 subshardListener.addSubshard(maybeAffected);
117 } else if (maybeAffected.getPrefix().getRootIdentifier().contains(listenerPath)) {
118 // bind path is inside subshard
119 // TODO can this happen? seems like in ShardedDOMDataTree we are
120 // already registering to the lowest shard possible
121 throw new UnsupportedOperationException("Listener should be registered directly "
122 + "into initialDataChangeEvent subshard");
129 private <L extends DOMDataTreeChangeListener> AbstractDOMDataTreeChangeListenerRegistration<L>
130 setupContextWithoutSubshards(final YangInstanceIdentifier shardLookup,
131 final YangInstanceIdentifier listenerPath,
132 final DOMDataTreeListenerWithSubshards listener) {
134 LOG.debug("Registering root listener full path: {}, path inside shard: {}", shardLookup, listenerPath);
136 // register in the shard tree
137 final RegistrationTreeNode<AbstractDOMDataTreeChangeListenerRegistration<?>> node =
138 findNodeFor(listenerPath.getPathArguments());
140 // register listener in CDS
141 final ProxyRegistration proxyReg = new ProxyRegistration(distributedDataStore
142 .registerProxyListener(shardLookup, listenerPath, listener), listener);
144 @SuppressWarnings("unchecked")
145 final AbstractDOMDataTreeChangeListenerRegistration<L> registration =
146 new AbstractDOMDataTreeChangeListenerRegistration<L>((L) listener) {
148 protected void removeRegistration() {
150 DistributedShardChangePublisher.this.removeRegistration(node, this);
151 registrationRemoved(this);
155 addRegistration(node, registration);
160 private static Iterable<PathArgument> stripShardPath(final YangInstanceIdentifier shardPath,
161 final YangInstanceIdentifier listenerPath) {
162 if (shardPath.isEmpty()) {
163 return listenerPath.getPathArguments();
166 final List<PathArgument> listenerPathArgs = new ArrayList<>(listenerPath.getPathArguments());
167 final Iterator<PathArgument> shardIter = shardPath.getPathArguments().iterator();
168 final Iterator<PathArgument> listenerIter = listenerPathArgs.iterator();
170 while (shardIter.hasNext()) {
171 if (shardIter.next().equals(listenerIter.next())) {
172 listenerIter.remove();
178 return listenerPathArgs;
181 private static class ProxyRegistration implements ListenerRegistration<DOMDataTreeChangeListener> {
183 private final ListenerRegistration<org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener> proxy;
184 private final DOMDataTreeChangeListener listener;
186 private ProxyRegistration(
187 final ListenerRegistration<
188 org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener> proxy,
189 final DOMDataTreeChangeListener listener) {
191 this.listener = listener;
195 public DOMDataTreeChangeListener getInstance() {
200 public void close() {
205 synchronized DataTreeCandidate applyChanges(final YangInstanceIdentifier listenerPath,
206 final Collection<DataTreeCandidate> changes) throws DataValidationFailedException {
207 final DataTreeModification modification = dataTree.takeSnapshot().newModification();
208 for (final DataTreeCandidate change : changes) {
210 DataTreeCandidates.applyToModification(modification, change);
211 } catch (SchemaValidationFailedException e) {
212 LOG.error("Validation failed {}", e);
216 modification.ready();
218 final DataTreeCandidate candidate;
220 dataTree.validate(modification);
222 // strip nodes we dont need since this listener doesn't have to be registered at the root of the DataTree
223 candidate = dataTree.prepare(modification);
224 dataTree.commit(candidate);
227 DataTreeCandidateNode modifiedChild = candidate.getRootNode();
229 for (final PathArgument pathArgument : listenerPath.getPathArguments()) {
230 modifiedChild = modifiedChild.getModifiedChild(pathArgument);
233 if (modifiedChild == null) {
234 modifiedChild = new EmptyDataTreeCandidateNode(dataTree.getRootPath().getLastPathArgument());
237 return DataTreeCandidates.newDataTreeCandidate(dataTree.getRootPath(), modifiedChild);
241 private final class DOMDataTreeListenerWithSubshards implements DOMDataTreeChangeListener {
243 private final YangInstanceIdentifier listenerPath;
244 private final DOMDataTreeChangeListener delegate;
245 private final Map<YangInstanceIdentifier, ListenerRegistration<DOMDataTreeChangeListener>> registrations =
246 new ConcurrentHashMap<>();
249 private final Collection<DataTreeCandidate> stashedDataTreeCandidates = new LinkedList<>();
251 DOMDataTreeListenerWithSubshards(final YangInstanceIdentifier listenerPath,
252 final DOMDataTreeChangeListener delegate) {
253 this.listenerPath = Preconditions.checkNotNull(listenerPath);
254 this.delegate = Preconditions.checkNotNull(delegate);
258 public synchronized void onDataTreeChanged(@Nonnull final Collection<DataTreeCandidate> changes) {
259 LOG.debug("Received data changed {}", changes);
261 if (!stashedDataTreeCandidates.isEmpty()) {
262 LOG.debug("Adding stashed subshards' changes {}", stashedDataTreeCandidates);
263 changes.addAll(stashedDataTreeCandidates);
264 stashedDataTreeCandidates.clear();
268 applyChanges(listenerPath, changes);
269 } catch (final DataValidationFailedException e) {
270 // TODO should we fail here? What if stashed changes
271 // (changes from subshards) got ahead more than one generation
272 // from current shard. Than we can fail to apply this changes
273 // upon current data tree, but once we get respective changes
274 // from current shard, we can apply also changes from
277 // However, we can loose ability to notice and report some
278 // errors then. For example, we cannot detect potential lost
279 // changes from current shard.
280 LOG.error("Validation failed for modification built from changes {}, current data tree: {}",
281 changes, dataTree, e);
282 throw new RuntimeException("Notification validation failed", e);
285 delegate.onDataTreeChanged(changes);
288 synchronized void onDataTreeChanged(final YangInstanceIdentifier pathFromRoot,
289 final Collection<DataTreeCandidate> changes) {
290 final YangInstanceIdentifier changeId =
291 YangInstanceIdentifier.create(stripShardPath(dataTree.getRootPath(), pathFromRoot));
293 final List<DataTreeCandidate> newCandidates = changes.stream()
294 .map(candidate -> DataTreeCandidates.newDataTreeCandidate(changeId, candidate.getRootNode()))
295 .collect(Collectors.toList());
298 delegate.onDataTreeChanged(Collections.singleton(applyChanges(listenerPath, newCandidates)));
299 } catch (final DataValidationFailedException e) {
300 // We cannot apply changes from subshard to current data tree.
301 // Maybe changes from current shard haven't been applied to
302 // data tree yet. Postpone processing of these changes till we
303 // receive changes from current shard.
304 LOG.debug("Validation for modification built from subshard {} changes {} failed, current data tree {}.",
305 pathFromRoot, changes, dataTree, e);
306 stashedDataTreeCandidates.addAll(newCandidates);
310 void addSubshard(final ChildShardContext context) {
311 Preconditions.checkState(context.getShard() instanceof DOMStoreTreeChangePublisher,
312 "All subshards that are initialDataChangeEvent part of ListenerContext need to be listenable");
314 final DOMStoreTreeChangePublisher listenableShard = (DOMStoreTreeChangePublisher) context.getShard();
315 // since this is going into subshard we want to listen for ALL changes in the subshard
316 registrations.put(context.getPrefix().getRootIdentifier(),
317 listenableShard.registerTreeChangeListener(
318 context.getPrefix().getRootIdentifier(), changes -> onDataTreeChanged(
319 context.getPrefix().getRootIdentifier(), changes)));
323 for (final ListenerRegistration<DOMDataTreeChangeListener> registration : registrations.values()) {
324 registration.close();
326 registrations.clear();
330 private static final class EmptyDataTreeCandidateNode implements DataTreeCandidateNode {
332 private final PathArgument identifier;
334 EmptyDataTreeCandidateNode(final PathArgument identifier) {
335 this.identifier = Preconditions.checkNotNull(identifier, "Identifier should not be null");
340 public PathArgument getIdentifier() {
346 public Collection<DataTreeCandidateNode> getChildNodes() {
347 return Collections.emptySet();
352 public DataTreeCandidateNode getModifiedChild(final PathArgument identifier) {
358 public ModificationType getModificationType() {
359 return ModificationType.UNMODIFIED;
364 public Optional<NormalizedNode<?, ?>> getDataAfter() {
365 return Optional.absent();
370 public Optional<NormalizedNode<?, ?>> getDataBefore() {
371 return Optional.absent();