83cfcaca18e9d3e3ad403f5665a91843867edc3f
[controller.git] / opendaylight / md-sal / sal-dom-broker / src / main / java / org / opendaylight / controller / md / sal / dom / store / impl / tree / ListenerTree.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.tree;
9
10 import java.lang.ref.Reference;
11 import java.lang.ref.WeakReference;
12 import java.util.ArrayList;
13 import java.util.Collection;
14 import java.util.HashMap;
15 import java.util.Map;
16 import java.util.concurrent.locks.Lock;
17 import java.util.concurrent.locks.ReadWriteLock;
18 import java.util.concurrent.locks.ReentrantReadWriteLock;
19
20 import javax.annotation.concurrent.GuardedBy;
21
22 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
23 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
24 import org.opendaylight.controller.md.sal.dom.store.impl.DataChangeListenerRegistration;
25 import org.opendaylight.yangtools.concepts.AbstractListenerRegistration;
26 import org.opendaylight.yangtools.concepts.Identifiable;
27 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
28 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
29 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 import com.google.common.base.Optional;
34 import com.google.common.base.Preconditions;
35
36 public final class ListenerTree {
37     private static final Logger LOG = LoggerFactory.getLogger(ListenerTree.class);
38     private final ReadWriteLock rwLock = new ReentrantReadWriteLock(true);
39     private final Node rootNode = new Node(null, null);
40
41     private ListenerTree() {
42
43     }
44
45     public static ListenerTree create() {
46         return new ListenerTree();
47     }
48
49     /**
50      * Registers listener on this node.
51      *
52      * @param path Full path on which listener is registered.
53      * @param listener Listener
54      * @param scope Scope of triggering event.
55      * @return Listener registration
56      */
57     public <L extends AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>> DataChangeListenerRegistration<L> registerDataChangeListener(final InstanceIdentifier path,
58             final L listener, final DataChangeScope scope) {
59
60         // Take the write lock
61         rwLock.writeLock().lock();
62
63         try {
64             Node walkNode = rootNode;
65             for (final PathArgument arg : path.getPath()) {
66                 walkNode = walkNode.ensureChild(arg);
67             }
68
69             final Node node = walkNode;
70             DataChangeListenerRegistration<L> reg = new DataChangeListenerRegistrationImpl<L>(listener) {
71                 @Override
72                 public DataChangeScope getScope() {
73                     return scope;
74                 }
75
76                 @Override
77                 public InstanceIdentifier getPath() {
78                     return path;
79                 }
80
81                 @Override
82                 protected void removeRegistration() {
83                     /*
84                      * TODO: Here's an interesting problem. The way the datastore works, it
85                      *       enqueues requests towards the listener, so the listener will be
86                      *       notified at some point in the future. Now if the registration is
87                      *       closed, we will prevent any new events from being delivered, but
88                      *       we have no way to purge that queue.
89                      *
90                      *       While this does not directly violate the ListenerRegistration
91                      *       contract, it is probably not going to be liked by the users.
92                      */
93
94                     // Take the write lock
95                     ListenerTree.this.rwLock.writeLock().lock();
96                     try {
97                         node.removeListener(this);
98                     } finally {
99                         // Always release the lock
100                         ListenerTree.this.rwLock.writeLock().unlock();
101                     }
102                 }
103             };
104
105             node.addListener(reg);
106             return reg;
107         } finally {
108             // Always release the lock
109             rwLock.writeLock().unlock();
110         }
111     }
112
113     public Walker getWalker() {
114         /*
115          * TODO: The only current user of this method is local to the datastore.
116          *       Since this class represents a read-lock, losing a reference to
117          *       it is a _major_ problem, as the registration process will get
118          *       wedged, eventually grinding the system to a halt. Should an
119          *       external user exist, make the Walker a phantom reference, which
120          *       will cleanup the lock if not told to do so.
121          */
122         final Walker ret = new Walker(rwLock.readLock(), rootNode);
123         rwLock.readLock().lock();
124         return ret;
125     }
126
127     public static final class Walker implements AutoCloseable {
128         private final Lock lock;
129         private final Node node;
130
131         @GuardedBy("this")
132         private boolean valid = true;
133
134         private Walker(final Lock lock, final Node node) {
135             this.lock = Preconditions.checkNotNull(lock);
136             this.node = Preconditions.checkNotNull(node);
137         }
138
139         public Node getRootNode() {
140             return node;
141         }
142
143         @Override
144         public synchronized void close() {
145             if (valid) {
146                 lock.unlock();
147                 valid = false;
148             }
149         }
150     }
151
152     /**
153      * This is a single node within the listener tree. Note that the data returned from
154      * and instance of this class is guaranteed to have any relevance or consistency
155      * only as long as the {@link Walker} instance through which it is reached remains
156      * unclosed.
157      */
158     public static final class Node implements StoreTreeNode<Node>, Identifiable<PathArgument> {
159         private final Collection<DataChangeListenerRegistration<?>> listeners = new ArrayList<>();
160         private final Map<PathArgument, Node> children = new HashMap<>();
161         private final PathArgument identifier;
162         private final Reference<Node> parent;
163
164         private Node(final Node parent, final PathArgument identifier) {
165             this.parent = new WeakReference<>(parent);
166             this.identifier = identifier;
167         }
168
169         @Override
170         public PathArgument getIdentifier() {
171             return identifier;
172         }
173
174         @Override
175         public Optional<Node> getChild(final PathArgument child) {
176             return Optional.fromNullable(children.get(child));
177         }
178
179         /**
180          * Return the list of current listeners. This collection is guaranteed
181          * to be immutable only while the walker, through which this node is
182          * reachable remains unclosed.
183          *
184          * @return the list of current listeners
185          */
186         public Collection<DataChangeListenerRegistration<?>> getListeners() {
187             return listeners;
188         }
189
190         private Node ensureChild(final PathArgument child) {
191             Node potential = children.get(child);
192             if (potential == null) {
193                 potential = new Node(this, child);
194                 children.put(child, potential);
195             }
196             return potential;
197         }
198
199         private void addListener(final DataChangeListenerRegistration<?> listener) {
200             listeners.add(listener);
201             LOG.debug("Listener {} registered", listener);
202         }
203
204         private void removeListener(final DataChangeListenerRegistrationImpl<?> listener) {
205             listeners.remove(listener);
206             LOG.debug("Listener {} unregistered", listener);
207
208             // We have been called with the write-lock held, so we can perform some cleanup.
209             removeThisIfUnused();
210         }
211
212         private void removeThisIfUnused() {
213             final Node p = parent.get();
214             if (p != null && listeners.isEmpty() && children.isEmpty()) {
215                 p.removeChild(identifier);
216             }
217         }
218
219         private void removeChild(final PathArgument arg) {
220             children.remove(arg);
221             removeThisIfUnused();
222         }
223     }
224
225     private abstract static class DataChangeListenerRegistrationImpl<T extends AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>> extends AbstractListenerRegistration<T> //
226     implements DataChangeListenerRegistration<T> {
227         public DataChangeListenerRegistrationImpl(final T listener) {
228             super(listener);
229         }
230     }
231 }