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