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