Bug 3135 - Fixed support for InterestListener
[controller.git] / opendaylight / md-sal / sal-dom-broker / src / main / java / org / opendaylight / controller / md / sal / dom / broker / impl / DOMNotificationRouter.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.broker.impl;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.base.Predicate;
12 import com.google.common.collect.ImmutableList;
13 import com.google.common.collect.ImmutableMultimap;
14 import com.google.common.collect.ImmutableMultimap.Builder;
15 import com.google.common.collect.Multimap;
16 import com.google.common.collect.Multimaps;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.lmax.disruptor.EventHandler;
20 import com.lmax.disruptor.InsufficientCapacityException;
21 import com.lmax.disruptor.PhasedBackoffWaitStrategy;
22 import com.lmax.disruptor.WaitStrategy;
23 import com.lmax.disruptor.dsl.Disruptor;
24 import com.lmax.disruptor.dsl.ProducerType;
25 import java.util.Arrays;
26 import java.util.Collection;
27 import java.util.List;
28 import java.util.Set;
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.Executors;
31 import java.util.concurrent.TimeUnit;
32 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
33 import org.opendaylight.controller.md.sal.dom.api.DOMNotificationListener;
34 import org.opendaylight.controller.md.sal.dom.api.DOMNotificationPublishService;
35 import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService;
36 import org.opendaylight.controller.md.sal.dom.spi.DOMNotificationSubscriptionListener;
37 import org.opendaylight.controller.md.sal.dom.spi.DOMNotificationSubscriptionListenerRegistry;
38 import org.opendaylight.yangtools.concepts.AbstractListenerRegistration;
39 import org.opendaylight.yangtools.concepts.ListenerRegistration;
40 import org.opendaylight.yangtools.util.ListenerRegistry;
41 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 /**
46  * Joint implementation of {@link DOMNotificationPublishService} and {@link DOMNotificationService}. Provides
47  * routing of notifications from publishers to subscribers.
48  *
49  * Internal implementation works by allocating a two-handler Disruptor. The first handler delivers notifications
50  * to subscribed listeners and the second one notifies whoever may be listening on the returned future. Registration
51  * state tracking is performed by a simple immutable multimap -- when a registration or unregistration occurs we
52  * re-generate the entire map from scratch and set it atomically. While registrations/unregistrations synchronize
53  * on this instance, notifications do not take any locks here.
54  *
55  * The fully-blocking {@link #publish(long, DOMNotification, Collection)} and non-blocking {@link #offerNotification(DOMNotification)}
56  * are realized using the Disruptor's native operations. The bounded-blocking {@link #offerNotification(DOMNotification, long, TimeUnit)}
57  * is realized by arming a background wakeup interrupt.
58  */
59 public final class DOMNotificationRouter implements AutoCloseable, DOMNotificationPublishService,
60         DOMNotificationService, DOMNotificationSubscriptionListenerRegistry {
61
62     private static final Logger LOG = LoggerFactory.getLogger(DOMNotificationRouter.class);
63     private static final ListenableFuture<Void> NO_LISTENERS = Futures.immediateFuture(null);
64     private static final WaitStrategy DEFAULT_STRATEGY = PhasedBackoffWaitStrategy.withLock(1L, 30L, TimeUnit.MILLISECONDS);
65     private static final EventHandler<DOMNotificationRouterEvent> DISPATCH_NOTIFICATIONS = new EventHandler<DOMNotificationRouterEvent>() {
66         @Override
67         public void onEvent(final DOMNotificationRouterEvent event, final long sequence, final boolean endOfBatch) throws Exception {
68             event.deliverNotification();
69
70         }
71     };
72     private static final EventHandler<DOMNotificationRouterEvent> NOTIFY_FUTURE = new EventHandler<DOMNotificationRouterEvent>() {
73         @Override
74         public void onEvent(final DOMNotificationRouterEvent event, final long sequence, final boolean endOfBatch) {
75             event.setFuture();
76         }
77     };
78
79     private final Disruptor<DOMNotificationRouterEvent> disruptor;
80     private final ExecutorService executor;
81     private volatile Multimap<SchemaPath, ListenerRegistration<? extends DOMNotificationListener>> listeners = ImmutableMultimap.of();
82     private final ListenerRegistry<DOMNotificationSubscriptionListener> subscriptionListeners = ListenerRegistry.create();
83
84     private DOMNotificationRouter(final ExecutorService executor, final Disruptor<DOMNotificationRouterEvent> disruptor) {
85         this.executor = Preconditions.checkNotNull(executor);
86         this.disruptor = Preconditions.checkNotNull(disruptor);
87     }
88
89     @SuppressWarnings("unchecked")
90     public static DOMNotificationRouter create(final int queueDepth) {
91         final ExecutorService executor = Executors.newCachedThreadPool();
92         final Disruptor<DOMNotificationRouterEvent> disruptor = new Disruptor<>(DOMNotificationRouterEvent.FACTORY, queueDepth, executor, ProducerType.MULTI, DEFAULT_STRATEGY);
93
94         disruptor.handleEventsWith(DISPATCH_NOTIFICATIONS);
95         disruptor.after(DISPATCH_NOTIFICATIONS).handleEventsWith(NOTIFY_FUTURE);
96         disruptor.start();
97
98         return new DOMNotificationRouter(executor, disruptor);
99     }
100
101     @Override
102     public synchronized <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(final T listener, final Collection<SchemaPath> types) {
103         final ListenerRegistration<T> reg = new AbstractListenerRegistration<T>(listener) {
104             @Override
105             protected void removeRegistration() {
106                 final ListenerRegistration<T> me = this;
107
108                 synchronized (DOMNotificationRouter.this) {
109                     replaceListeners(ImmutableMultimap.copyOf(Multimaps.filterValues(listeners, new Predicate<ListenerRegistration<? extends DOMNotificationListener>>() {
110                         @Override
111                         public boolean apply(final ListenerRegistration<? extends DOMNotificationListener> input) {
112                             return input != me;
113                         }
114                     })));
115                 }
116             }
117         };
118
119         if (!types.isEmpty()) {
120             final Builder<SchemaPath, ListenerRegistration<? extends DOMNotificationListener>> b = ImmutableMultimap.builder();
121             b.putAll(listeners);
122
123             for (final SchemaPath t : types) {
124                 b.put(t, reg);
125             }
126
127             replaceListeners(b.build());
128         }
129
130         return reg;
131     }
132
133     @Override
134     public <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(final T listener, final SchemaPath... types) {
135         return registerNotificationListener(listener, Arrays.asList(types));
136     }
137
138     /**
139      * Swaps registered listeners and triggers notification update
140      *
141      * @param newListeners
142      */
143     private void replaceListeners(
144             final Multimap<SchemaPath, ListenerRegistration<? extends DOMNotificationListener>> newListeners) {
145         listeners = newListeners;
146         notifyListenerTypesChanged(newListeners.keySet());
147     }
148
149     private void notifyListenerTypesChanged(final Set<SchemaPath> typesAfter) {
150         final List<ListenerRegistration<DOMNotificationSubscriptionListener>> listenersAfter =ImmutableList.copyOf(subscriptionListeners.getListeners());
151         executor.submit(new Runnable() {
152
153             @Override
154             public void run() {
155                 for (final ListenerRegistration<DOMNotificationSubscriptionListener> subListener : listenersAfter) {
156                     try {
157                         subListener.getInstance().onSubscriptionChanged(typesAfter);
158                     } catch (final Exception e) {
159                         LOG.warn("Uncaught exception during invoking listener {}", subListener.getInstance(), e);
160                     }
161                 }
162             }
163         });
164     }
165
166     @Override
167     public <L extends DOMNotificationSubscriptionListener> ListenerRegistration<L> registerSubscriptionListener(
168             final L listener) {
169         final Set<SchemaPath> initialTypes = listeners.keySet();
170         executor.submit(new Runnable() {
171
172             @Override
173             public void run() {
174                 listener.onSubscriptionChanged(initialTypes);
175             }
176         });
177         return subscriptionListeners.registerWithType(listener);
178     }
179
180     private ListenableFuture<Void> publish(final long seq, final DOMNotification notification, final Collection<ListenerRegistration<? extends DOMNotificationListener>> subscribers) {
181         final DOMNotificationRouterEvent event = disruptor.get(seq);
182         final ListenableFuture<Void> future = event.initialize(notification, subscribers);
183         disruptor.getRingBuffer().publish(seq);
184         return future;
185     }
186
187     @Override
188     public ListenableFuture<? extends Object> putNotification(final DOMNotification notification) throws InterruptedException {
189         final Collection<ListenerRegistration<? extends DOMNotificationListener>> subscribers = listeners.get(notification.getType());
190         if (subscribers.isEmpty()) {
191             return NO_LISTENERS;
192         }
193
194         final long seq = disruptor.getRingBuffer().next();
195         return publish(seq, notification, subscribers);
196     }
197
198     private ListenableFuture<? extends Object> tryPublish(final DOMNotification notification, final Collection<ListenerRegistration<? extends DOMNotificationListener>> subscribers) {
199         final long seq;
200         try {
201              seq = disruptor.getRingBuffer().tryNext();
202         } catch (final InsufficientCapacityException e) {
203             return DOMNotificationPublishService.REJECTED;
204         }
205
206         return publish(seq, notification, subscribers);
207     }
208
209     @Override
210     public ListenableFuture<? extends Object> offerNotification(final DOMNotification notification) {
211         final Collection<ListenerRegistration<? extends DOMNotificationListener>> subscribers = listeners.get(notification.getType());
212         if (subscribers.isEmpty()) {
213             return NO_LISTENERS;
214         }
215
216         return tryPublish(notification, subscribers);
217     }
218
219     @Override
220     public ListenableFuture<? extends Object> offerNotification(final DOMNotification notification, final long timeout,
221             final TimeUnit unit) throws InterruptedException {
222         final Collection<ListenerRegistration<? extends DOMNotificationListener>> subscribers = listeners.get(notification.getType());
223         if (subscribers.isEmpty()) {
224             return NO_LISTENERS;
225         }
226
227         // Attempt to perform a non-blocking publish first
228         final ListenableFuture<? extends Object> noBlock = tryPublish(notification, subscribers);
229         if (!DOMNotificationPublishService.REJECTED.equals(noBlock)) {
230             return noBlock;
231         }
232
233         /*
234          * FIXME: we need a background thread, which will watch out for blocking too long. Here
235          *        we will arm a tasklet for it and synchronize delivery of interrupt properly.
236          */
237         throw new UnsupportedOperationException("Not implemented yet");
238     }
239
240     @Override
241     public void close() {
242         disruptor.shutdown();
243         executor.shutdown();
244     }
245 }