0a1bac8a2ada4ff47e883c313137845121189e6e
[netconf.git] / netconf / mdsal-netconf-notification / src / main / java / org / opendaylight / netconf / mdsal / notification / impl / NetconfNotificationManager.java
1 /*
2  * Copyright (c) 2015 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.netconf.mdsal.notification.impl;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.collect.HashMultimap;
15 import com.google.common.collect.HashMultiset;
16 import com.google.common.collect.Maps;
17 import com.google.common.collect.Multimap;
18 import com.google.common.collect.Multiset;
19 import java.util.ArrayList;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.Map;
23 import java.util.Set;
24 import javax.annotation.PreDestroy;
25 import javax.inject.Inject;
26 import javax.inject.Singleton;
27 import org.checkerframework.checker.lock.qual.GuardedBy;
28 import org.opendaylight.mdsal.binding.dom.codec.spi.BindingDOMCodecFactory;
29 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeGenerator;
30 import org.opendaylight.netconf.mdsal.notification.impl.ops.NotificationsTransformUtil;
31 import org.opendaylight.netconf.notifications.BaseNotificationPublisherRegistration;
32 import org.opendaylight.netconf.notifications.NetconfNotification;
33 import org.opendaylight.netconf.notifications.NetconfNotificationCollector;
34 import org.opendaylight.netconf.notifications.NetconfNotificationListener;
35 import org.opendaylight.netconf.notifications.NetconfNotificationRegistry;
36 import org.opendaylight.netconf.notifications.NotificationListenerRegistration;
37 import org.opendaylight.netconf.notifications.NotificationPublisherRegistration;
38 import org.opendaylight.netconf.notifications.NotificationRegistration;
39 import org.opendaylight.netconf.notifications.YangLibraryPublisherRegistration;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.StreamNameType;
41 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.Streams;
42 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.StreamsBuilder;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.streams.Stream;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.streams.StreamBuilder;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.streams.StreamKey;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfSessionEnd;
48 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfSessionStart;
49 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.YangLibraryChange;
50 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.YangLibraryUpdate;
51 import org.opendaylight.yangtools.yang.binding.Notification;
52 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
53 import org.opendaylight.yangtools.yang.parser.api.YangParserException;
54 import org.opendaylight.yangtools.yang.parser.api.YangParserFactory;
55 import org.osgi.service.component.annotations.Activate;
56 import org.osgi.service.component.annotations.Component;
57 import org.osgi.service.component.annotations.Deactivate;
58 import org.osgi.service.component.annotations.Reference;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 /**
63  *  A thread-safe implementation NetconfNotificationRegistry.
64  */
65 @Singleton
66 @Component(service = { NetconfNotificationCollector.class, NetconfNotificationRegistry.class }, immediate = true,
67            property = "type=netconf-notification-manager")
68 public final class NetconfNotificationManager implements NetconfNotificationCollector, NetconfNotificationRegistry,
69         NetconfNotificationListener, AutoCloseable {
70     public static final StreamNameType BASE_STREAM_NAME = new StreamNameType("NETCONF");
71     public static final Stream BASE_NETCONF_STREAM = new StreamBuilder()
72                 .setName(BASE_STREAM_NAME)
73                 .withKey(new StreamKey(BASE_STREAM_NAME))
74                 .setReplaySupport(false)
75                 .setDescription("Default Event Stream")
76                 .build();
77
78     private static final Logger LOG = LoggerFactory.getLogger(NetconfNotificationManager.class);
79
80     // TODO excessive synchronization provides thread safety but is most likely not optimal
81     // (combination of concurrent collections might improve performance)
82     // And also calling callbacks from a synchronized block is dangerous
83     // since the listeners/publishers can block the whole notification processing
84
85     @GuardedBy("this")
86     private final Multimap<StreamNameType, GenericNotificationListenerReg> notificationListeners =
87             HashMultimap.create();
88
89     @GuardedBy("this")
90     private final Set<NetconfNotificationStreamListener> streamListeners = new HashSet<>();
91
92     @GuardedBy("this")
93     private final Map<StreamNameType, Stream> streamMetadata = new HashMap<>();
94
95     @GuardedBy("this")
96     private final Multiset<StreamNameType> availableStreams = HashMultiset.create();
97
98     @GuardedBy("this")
99     private final Set<GenericNotificationPublisherReg> notificationPublishers = new HashSet<>();
100     private final NotificationsTransformUtil transformUtil;
101
102     @Inject
103     @Activate
104     public NetconfNotificationManager(@Reference final YangParserFactory parserFactory,
105             @Reference final BindingRuntimeGenerator generator, @Reference final BindingDOMCodecFactory codecFactory)
106                 throws YangParserException {
107         transformUtil = new NotificationsTransformUtil(parserFactory, generator, codecFactory);
108     }
109
110     @PreDestroy
111     @Deactivate
112     @Override
113     public synchronized void close() {
114         // Unregister all listeners
115         // Use new list to avoid ConcurrentModificationException
116         for (final GenericNotificationListenerReg listenerReg : new ArrayList<>(notificationListeners.values())) {
117             listenerReg.close();
118         }
119         notificationListeners.clear();
120
121         // Unregister all publishers
122         // Use new list to avoid ConcurrentModificationException
123         for (final GenericNotificationPublisherReg notificationPublisher : new ArrayList<>(notificationPublishers)) {
124             notificationPublisher.close();
125         }
126         notificationPublishers.clear();
127
128         // Clear stream Listeners
129         streamListeners.clear();
130     }
131
132     @Override
133     public synchronized void onNotification(final StreamNameType stream, final NetconfNotification notification) {
134         LOG.debug("Notification of type {} detected", stream);
135         if (LOG.isTraceEnabled()) {
136             LOG.debug("Notification of type {} detected: {}", stream, notification);
137         }
138
139         for (final GenericNotificationListenerReg listenerReg : notificationListeners.get(stream)) {
140             listenerReg.getListener().onNotification(stream, notification);
141         }
142     }
143
144     @Override
145     public synchronized NotificationListenerRegistration registerNotificationListener(
146             final StreamNameType stream,
147             final NetconfNotificationListener listener) {
148         requireNonNull(stream);
149         requireNonNull(listener);
150
151         LOG.trace("Notification listener registered for stream: {}", stream);
152
153         final GenericNotificationListenerReg reg = new GenericNotificationListenerReg(listener, stream) {
154             @Override
155             public void close() {
156                 synchronized (NetconfNotificationManager.this) {
157                     LOG.trace("Notification listener unregistered for stream: {}", stream);
158                     super.close();
159                 }
160             }
161         };
162
163         notificationListeners.put(stream, reg);
164         return reg;
165     }
166
167     @Override
168     public synchronized Streams getNotificationPublishers() {
169         return new StreamsBuilder().setStream(Maps.uniqueIndex(streamMetadata.values(), Stream::key)).build();
170     }
171
172     @Override
173     public synchronized boolean isStreamAvailable(final StreamNameType streamNameType) {
174         return availableStreams.contains(streamNameType);
175     }
176
177     @Override
178     public synchronized NotificationRegistration registerStreamListener(
179             final NetconfNotificationStreamListener listener) {
180         streamListeners.add(listener);
181
182         // Notify about all already available
183         for (final Stream availableStream : streamMetadata.values()) {
184             listener.onStreamRegistered(availableStream);
185         }
186
187         return () -> {
188             synchronized (NetconfNotificationManager.this) {
189                 streamListeners.remove(listener);
190             }
191         };
192     }
193
194     @Override
195     public synchronized NotificationPublisherRegistration registerNotificationPublisher(final Stream stream) {
196         final StreamNameType streamName = requireNonNull(stream).getName();
197
198         LOG.debug("Notification publisher registered for stream: {}", streamName);
199         if (LOG.isTraceEnabled()) {
200             LOG.trace("Notification publisher registered for stream: {}", stream);
201         }
202
203         if (streamMetadata.containsKey(streamName)) {
204             LOG.warn("Notification stream {} already registered as: {}. Will be reused", streamName,
205                     streamMetadata.get(streamName));
206         } else {
207             streamMetadata.put(streamName, stream);
208         }
209
210         availableStreams.add(streamName);
211
212         final GenericNotificationPublisherReg reg = new GenericNotificationPublisherReg(this, streamName) {
213             @Override
214             public void close() {
215                 synchronized (NetconfNotificationManager.this) {
216                     super.close();
217                 }
218             }
219         };
220
221         notificationPublishers.add(reg);
222
223         notifyStreamAdded(stream);
224         return reg;
225     }
226
227     private void unregisterNotificationPublisher(
228             final StreamNameType streamName,
229             final GenericNotificationPublisherReg genericNotificationPublisherReg) {
230         availableStreams.remove(streamName);
231         notificationPublishers.remove(genericNotificationPublisherReg);
232
233         LOG.debug("Notification publisher unregistered for stream: {}", streamName);
234
235         // Notify stream listeners if all publishers are gone and also clear metadata for stream
236         if (!isStreamAvailable(streamName)) {
237             LOG.debug("Notification stream: {} became unavailable", streamName);
238             streamMetadata.remove(streamName);
239             notifyStreamRemoved(streamName);
240         }
241     }
242
243     private synchronized void notifyStreamAdded(final Stream stream) {
244         for (final NetconfNotificationStreamListener streamListener : streamListeners) {
245             streamListener.onStreamRegistered(stream);
246         }
247     }
248
249     private synchronized void notifyStreamRemoved(final StreamNameType stream) {
250         for (final NetconfNotificationStreamListener streamListener : streamListeners) {
251             streamListener.onStreamUnregistered(stream);
252         }
253     }
254
255     @Override
256     public BaseNotificationPublisherRegistration registerBaseNotificationPublisher() {
257         final NotificationPublisherRegistration notificationPublisherRegistration =
258                 registerNotificationPublisher(BASE_NETCONF_STREAM);
259         return new BaseNotificationPublisherReg(transformUtil, notificationPublisherRegistration);
260     }
261
262     @Override
263     public YangLibraryPublisherRegistration registerYangLibraryPublisher() {
264         final NotificationPublisherRegistration notificationPublisherRegistration =
265                 registerNotificationPublisher(BASE_NETCONF_STREAM);
266         return new YangLibraryPublisherReg(transformUtil, notificationPublisherRegistration);
267     }
268
269     private static class GenericNotificationPublisherReg implements NotificationPublisherRegistration {
270         private NetconfNotificationManager baseListener;
271         private final StreamNameType registeredStream;
272
273         GenericNotificationPublisherReg(final NetconfNotificationManager baseListener,
274                                         final StreamNameType registeredStream) {
275             this.baseListener = baseListener;
276             this.registeredStream = registeredStream;
277         }
278
279         @Override
280         public void close() {
281             baseListener.unregisterNotificationPublisher(registeredStream, this);
282             baseListener = null;
283         }
284
285         @Override
286         public void onNotification(final StreamNameType stream, final NetconfNotification notification) {
287             checkState(baseListener != null, "Already closed");
288             checkArgument(stream.equals(registeredStream));
289             baseListener.onNotification(stream, notification);
290         }
291     }
292
293     private static class BaseNotificationPublisherReg implements BaseNotificationPublisherRegistration {
294         static final Absolute CAPABILITY_CHANGE_SCHEMA_PATH = Absolute.of(NetconfCapabilityChange.QNAME);
295         static final Absolute SESSION_START_PATH = Absolute.of(NetconfSessionStart.QNAME);
296         static final Absolute SESSION_END_PATH = Absolute.of(NetconfSessionEnd.QNAME);
297
298         private final NotificationPublisherRegistration baseRegistration;
299         private final NotificationsTransformUtil transformUtil;
300
301         BaseNotificationPublisherReg(final NotificationsTransformUtil transformUtil,
302                 final NotificationPublisherRegistration baseRegistration) {
303             this.transformUtil = requireNonNull(transformUtil);
304             this.baseRegistration = baseRegistration;
305         }
306
307         @Override
308         public void close() {
309             baseRegistration.close();
310         }
311
312         private NetconfNotification serializeNotification(final Notification<?> notification, final Absolute path) {
313             return transformUtil.transform(notification, path);
314         }
315
316         @Override
317         public void onCapabilityChanged(final NetconfCapabilityChange capabilityChange) {
318             baseRegistration.onNotification(BASE_STREAM_NAME,
319                     serializeNotification(capabilityChange, CAPABILITY_CHANGE_SCHEMA_PATH));
320         }
321
322         @Override
323         public void onSessionStarted(final NetconfSessionStart start) {
324             baseRegistration.onNotification(BASE_STREAM_NAME, serializeNotification(start, SESSION_START_PATH));
325         }
326
327         @Override
328         public void onSessionEnded(final NetconfSessionEnd end) {
329             baseRegistration.onNotification(BASE_STREAM_NAME, serializeNotification(end, SESSION_END_PATH));
330         }
331     }
332
333     private static class YangLibraryPublisherReg implements YangLibraryPublisherRegistration {
334         static final Absolute YANG_LIBRARY_CHANGE_PATH = Absolute.of(YangLibraryChange.QNAME);
335         static final Absolute YANG_LIBRARY_UPDATE_PATH = Absolute.of(YangLibraryUpdate.QNAME);
336
337         private final NotificationPublisherRegistration baseRegistration;
338         private final NotificationsTransformUtil transformUtil;
339
340         YangLibraryPublisherReg(final NotificationsTransformUtil transformUtil,
341                 final NotificationPublisherRegistration baseRegistration) {
342             this.transformUtil = requireNonNull(transformUtil);
343             this.baseRegistration = baseRegistration;
344         }
345
346         @Override
347         @Deprecated
348         public void onYangLibraryChange(final YangLibraryChange yangLibraryChange) {
349             baseRegistration.onNotification(BASE_STREAM_NAME,
350                 transformUtil.transform(yangLibraryChange, YANG_LIBRARY_CHANGE_PATH));
351         }
352
353         @Override
354         public void onYangLibraryUpdate(final YangLibraryUpdate yangLibraryUpdate) {
355             baseRegistration.onNotification(BASE_STREAM_NAME,
356                     transformUtil.transform(yangLibraryUpdate, YANG_LIBRARY_UPDATE_PATH));
357         }
358
359         @Override
360         public void close() {
361             baseRegistration.close();
362         }
363     }
364
365     private class GenericNotificationListenerReg implements NotificationListenerRegistration {
366         private final NetconfNotificationListener listener;
367         private final StreamNameType listenedStream;
368
369         GenericNotificationListenerReg(final NetconfNotificationListener listener,
370                                        final StreamNameType listenedStream) {
371             this.listener = listener;
372             this.listenedStream = listenedStream;
373         }
374
375         public NetconfNotificationListener getListener() {
376             return listener;
377         }
378
379         @Override
380         public void close() {
381             notificationListeners.remove(listenedStream, this);
382         }
383     }
384 }