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