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