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