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