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