1b6391083ab6fda7090020102d77ee39fae2f852
[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.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(stream)) {
105             listenerReg.getListener().onNotification(stream, 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 reg = new GenericNotificationListenerReg(listener, stream) {
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(stream, reg);
129         return reg;
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         // Use new list to avoid ConcurrentModificationException
163         for (final GenericNotificationListenerReg listenerReg : new ArrayList<>(notificationListeners.values())) {
164             listenerReg.close();
165         }
166         notificationListeners.clear();
167
168         // Unregister all publishers
169         // Use new list to avoid ConcurrentModificationException
170         for (final GenericNotificationPublisherReg notificationPublisher : new ArrayList<>(notificationPublishers)) {
171             notificationPublisher.close();
172         }
173         notificationPublishers.clear();
174
175         // Clear stream Listeners
176         streamListeners.clear();
177     }
178
179     @Override
180     public synchronized NotificationPublisherRegistration registerNotificationPublisher(final Stream stream) {
181         final StreamNameType streamName = requireNonNull(stream).getName();
182
183         LOG.debug("Notification publisher registered for stream: {}", streamName);
184         if (LOG.isTraceEnabled()) {
185             LOG.trace("Notification publisher registered for stream: {}", stream);
186         }
187
188         if (streamMetadata.containsKey(streamName)) {
189             LOG.warn("Notification stream {} already registered as: {}. Will be reused", streamName,
190                     streamMetadata.get(streamName));
191         } else {
192             streamMetadata.put(streamName, stream);
193         }
194
195         availableStreams.add(streamName);
196
197         final GenericNotificationPublisherReg reg = new GenericNotificationPublisherReg(this, streamName) {
198             @Override
199             public void close() {
200                 synchronized (NetconfNotificationManager.this) {
201                     super.close();
202                 }
203             }
204         };
205
206         notificationPublishers.add(reg);
207
208         notifyStreamAdded(stream);
209         return reg;
210     }
211
212     private void unregisterNotificationPublisher(
213             final StreamNameType streamName,
214             final GenericNotificationPublisherReg genericNotificationPublisherReg) {
215         availableStreams.remove(streamName);
216         notificationPublishers.remove(genericNotificationPublisherReg);
217
218         LOG.debug("Notification publisher unregistered for stream: {}", streamName);
219
220         // Notify stream listeners if all publishers are gone and also clear metadata for stream
221         if (!isStreamAvailable(streamName)) {
222             LOG.debug("Notification stream: {} became unavailable", streamName);
223             streamMetadata.remove(streamName);
224             notifyStreamRemoved(streamName);
225         }
226     }
227
228     private synchronized void notifyStreamAdded(final Stream stream) {
229         for (final NetconfNotificationStreamListener streamListener : streamListeners) {
230             streamListener.onStreamRegistered(stream);
231         }
232     }
233
234     private synchronized void notifyStreamRemoved(final StreamNameType stream) {
235         for (final NetconfNotificationStreamListener streamListener : streamListeners) {
236             streamListener.onStreamUnregistered(stream);
237         }
238     }
239
240     @Override
241     public BaseNotificationPublisherRegistration registerBaseNotificationPublisher() {
242         final NotificationPublisherRegistration notificationPublisherRegistration =
243                 registerNotificationPublisher(BASE_NETCONF_STREAM);
244         return new BaseNotificationPublisherReg(transformUtil, notificationPublisherRegistration);
245     }
246
247     @Override
248     public YangLibraryPublisherRegistration registerYangLibraryPublisher() {
249         final NotificationPublisherRegistration notificationPublisherRegistration =
250                 registerNotificationPublisher(BASE_NETCONF_STREAM);
251         return new YangLibraryPublisherReg(transformUtil, notificationPublisherRegistration);
252     }
253
254     private static class GenericNotificationPublisherReg implements NotificationPublisherRegistration {
255         private NetconfNotificationManager baseListener;
256         private final StreamNameType registeredStream;
257
258         GenericNotificationPublisherReg(final NetconfNotificationManager baseListener,
259                                         final StreamNameType registeredStream) {
260             this.baseListener = baseListener;
261             this.registeredStream = registeredStream;
262         }
263
264         @Override
265         public void close() {
266             baseListener.unregisterNotificationPublisher(registeredStream, this);
267             baseListener = null;
268         }
269
270         @Override
271         public void onNotification(final StreamNameType stream, final NetconfNotification notification) {
272             checkState(baseListener != null, "Already closed");
273             checkArgument(stream.equals(registeredStream));
274             baseListener.onNotification(stream, notification);
275         }
276     }
277
278     private static class BaseNotificationPublisherReg implements BaseNotificationPublisherRegistration {
279
280         static final SchemaPath CAPABILITY_CHANGE_SCHEMA_PATH = SchemaPath.create(true, NetconfCapabilityChange.QNAME);
281         static final SchemaPath SESSION_START_PATH = SchemaPath.create(true, NetconfSessionStart.QNAME);
282         static final SchemaPath SESSION_END_PATH = SchemaPath.create(true, NetconfSessionEnd.QNAME);
283
284         private final NotificationPublisherRegistration baseRegistration;
285         private final NotificationsTransformUtil transformUtil;
286
287         BaseNotificationPublisherReg(final NotificationsTransformUtil transformUtil,
288                 final NotificationPublisherRegistration baseRegistration) {
289             this.transformUtil = requireNonNull(transformUtil);
290             this.baseRegistration = baseRegistration;
291         }
292
293         @Override
294         public void close() {
295             baseRegistration.close();
296         }
297
298         private NetconfNotification serializeNotification(final Notification notification, final SchemaPath path) {
299             return transformUtil.transform(notification, path);
300         }
301
302         @Override
303         public void onCapabilityChanged(final NetconfCapabilityChange capabilityChange) {
304             baseRegistration.onNotification(BASE_STREAM_NAME,
305                     serializeNotification(capabilityChange, CAPABILITY_CHANGE_SCHEMA_PATH));
306         }
307
308         @Override
309         public void onSessionStarted(final NetconfSessionStart start) {
310             baseRegistration.onNotification(BASE_STREAM_NAME, serializeNotification(start, SESSION_START_PATH));
311         }
312
313         @Override
314         public void onSessionEnded(final NetconfSessionEnd end) {
315             baseRegistration.onNotification(BASE_STREAM_NAME, serializeNotification(end, SESSION_END_PATH));
316         }
317     }
318
319     private static class YangLibraryPublisherReg implements YangLibraryPublisherRegistration {
320         static final SchemaPath YANG_LIBRARY_CHANGE_PATH = SchemaPath.create(true, YangLibraryChange.QNAME);
321         static final SchemaPath YANG_LIBRARY_UPDATE_PATH = SchemaPath.create(true, YangLibraryUpdate.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         @Deprecated
334         public void onYangLibraryChange(final YangLibraryChange yangLibraryChange) {
335             baseRegistration.onNotification(BASE_STREAM_NAME,
336                 transformUtil.transform(yangLibraryChange, YANG_LIBRARY_CHANGE_PATH));
337         }
338
339         @Override
340         public void onYangLibraryUpdate(final YangLibraryUpdate yangLibraryUpdate) {
341             baseRegistration.onNotification(BASE_STREAM_NAME,
342                     transformUtil.transform(yangLibraryUpdate, YANG_LIBRARY_UPDATE_PATH));
343         }
344
345         @Override
346         public void close() {
347             baseRegistration.close();
348         }
349     }
350
351     private class GenericNotificationListenerReg implements NotificationListenerRegistration {
352         private final NetconfNotificationListener listener;
353         private final StreamNameType listenedStream;
354
355         GenericNotificationListenerReg(final NetconfNotificationListener listener,
356                                        final StreamNameType listenedStream) {
357             this.listener = listener;
358             this.listenedStream = listenedStream;
359         }
360
361         public NetconfNotificationListener getListener() {
362             return listener;
363         }
364
365         @Override
366         public void close() {
367             notificationListeners.remove(listenedStream, this);
368         }
369     }
370 }