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