2 * Copyright (c) 2014 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
8 package org.opendaylight.controller.md.sal.dom.broker.impl;
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;
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;
46 * Joint implementation of {@link DOMNotificationPublishService} and {@link DOMNotificationService}. Provides
47 * routing of notifications from publishers to subscribers.
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.
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.
59 public final class DOMNotificationRouter implements AutoCloseable, DOMNotificationPublishService,
60 DOMNotificationService, DOMNotificationSubscriptionListenerRegistry {
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>() {
67 public void onEvent(final DOMNotificationRouterEvent event, final long sequence, final boolean endOfBatch) throws Exception {
68 event.deliverNotification();
72 private static final EventHandler<DOMNotificationRouterEvent> NOTIFY_FUTURE = new EventHandler<DOMNotificationRouterEvent>() {
74 public void onEvent(final DOMNotificationRouterEvent event, final long sequence, final boolean endOfBatch) {
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();
84 @SuppressWarnings("unchecked")
85 private DOMNotificationRouter(final ExecutorService executor, final int queueDepth, final WaitStrategy strategy) {
86 this.executor = Preconditions.checkNotNull(executor);
88 disruptor = new Disruptor<>(DOMNotificationRouterEvent.FACTORY, queueDepth, executor, ProducerType.MULTI, strategy);
89 disruptor.handleEventsWith(DISPATCH_NOTIFICATIONS);
90 disruptor.after(DISPATCH_NOTIFICATIONS).handleEventsWith(NOTIFY_FUTURE);
94 public static DOMNotificationRouter create(final int queueDepth) {
95 final ExecutorService executor = Executors.newCachedThreadPool();
97 return new DOMNotificationRouter(executor, queueDepth, DEFAULT_STRATEGY);
100 public static DOMNotificationRouter create(final int queueDepth, final long spinTime, final long parkTime, final TimeUnit unit) {
101 Preconditions.checkArgument(Long.lowestOneBit(queueDepth) == Long.highestOneBit(queueDepth),
102 "Queue depth %s is not power-of-two", queueDepth);
103 final ExecutorService executor = Executors.newCachedThreadPool();
104 final WaitStrategy strategy = PhasedBackoffWaitStrategy.withLock(spinTime, parkTime, unit);
106 return new DOMNotificationRouter(executor, queueDepth, strategy);
110 public synchronized <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(final T listener, final Collection<SchemaPath> types) {
111 final ListenerRegistration<T> reg = new AbstractListenerRegistration<T>(listener) {
113 protected void removeRegistration() {
114 final ListenerRegistration<T> me = this;
116 synchronized (DOMNotificationRouter.this) {
117 replaceListeners(ImmutableMultimap.copyOf(Multimaps.filterValues(listeners, new Predicate<ListenerRegistration<? extends DOMNotificationListener>>() {
119 public boolean apply(final ListenerRegistration<? extends DOMNotificationListener> input) {
127 if (!types.isEmpty()) {
128 final Builder<SchemaPath, ListenerRegistration<? extends DOMNotificationListener>> b = ImmutableMultimap.builder();
131 for (final SchemaPath t : types) {
135 replaceListeners(b.build());
142 public <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(final T listener, final SchemaPath... types) {
143 return registerNotificationListener(listener, Arrays.asList(types));
147 * Swaps registered listeners and triggers notification update
149 * @param newListeners
151 private void replaceListeners(
152 final Multimap<SchemaPath, ListenerRegistration<? extends DOMNotificationListener>> newListeners) {
153 listeners = newListeners;
154 notifyListenerTypesChanged(newListeners.keySet());
157 private void notifyListenerTypesChanged(final Set<SchemaPath> typesAfter) {
158 final List<ListenerRegistration<DOMNotificationSubscriptionListener>> listenersAfter =ImmutableList.copyOf(subscriptionListeners.getListeners());
159 executor.submit(new Runnable() {
163 for (final ListenerRegistration<DOMNotificationSubscriptionListener> subListener : listenersAfter) {
165 subListener.getInstance().onSubscriptionChanged(typesAfter);
166 } catch (final Exception e) {
167 LOG.warn("Uncaught exception during invoking listener {}", subListener.getInstance(), e);
175 public <L extends DOMNotificationSubscriptionListener> ListenerRegistration<L> registerSubscriptionListener(
177 final Set<SchemaPath> initialTypes = listeners.keySet();
178 executor.submit(new Runnable() {
182 listener.onSubscriptionChanged(initialTypes);
185 return subscriptionListeners.registerWithType(listener);
188 private ListenableFuture<Void> publish(final long seq, final DOMNotification notification, final Collection<ListenerRegistration<? extends DOMNotificationListener>> subscribers) {
189 final DOMNotificationRouterEvent event = disruptor.get(seq);
190 final ListenableFuture<Void> future = event.initialize(notification, subscribers);
191 disruptor.getRingBuffer().publish(seq);
196 public ListenableFuture<?> putNotification(final DOMNotification notification) throws InterruptedException {
197 final Collection<ListenerRegistration<? extends DOMNotificationListener>> subscribers = listeners.get(notification.getType());
198 if (subscribers.isEmpty()) {
202 final long seq = disruptor.getRingBuffer().next();
203 return publish(seq, notification, subscribers);
206 private ListenableFuture<?> tryPublish(final DOMNotification notification, final Collection<ListenerRegistration<? extends DOMNotificationListener>> subscribers) {
209 seq = disruptor.getRingBuffer().tryNext();
210 } catch (final InsufficientCapacityException e) {
211 return DOMNotificationPublishService.REJECTED;
214 return publish(seq, notification, subscribers);
218 public ListenableFuture<?> offerNotification(final DOMNotification notification) {
219 final Collection<ListenerRegistration<? extends DOMNotificationListener>> subscribers = listeners.get(notification.getType());
220 if (subscribers.isEmpty()) {
224 return tryPublish(notification, subscribers);
228 public ListenableFuture<?> offerNotification(final DOMNotification notification, final long timeout,
229 final TimeUnit unit) throws InterruptedException {
230 final Collection<ListenerRegistration<? extends DOMNotificationListener>> subscribers = listeners.get(notification.getType());
231 if (subscribers.isEmpty()) {
235 // Attempt to perform a non-blocking publish first
236 final ListenableFuture<?> noBlock = tryPublish(notification, subscribers);
237 if (!DOMNotificationPublishService.REJECTED.equals(noBlock)) {
242 * FIXME: we need a background thread, which will watch out for blocking too long. Here
243 * we will arm a tasklet for it and synchronize delivery of interrupt properly.
245 throw new UnsupportedOperationException("Not implemented yet");
249 public void close() {
250 disruptor.shutdown();