Fix web-socket timeout closure exceptions
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / streams / listeners / AbstractCommonSubscriber.java
1 /*
2  * Copyright (c) 2016 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.restconf.nb.rfc8040.streams.listeners;
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.base.MoreObjects;
15 import java.time.Instant;
16 import java.time.format.DateTimeFormatter;
17 import java.time.format.DateTimeFormatterBuilder;
18 import java.time.format.DateTimeParseException;
19 import java.time.temporal.ChronoField;
20 import java.time.temporal.TemporalAccessor;
21 import java.util.HashSet;
22 import java.util.Iterator;
23 import java.util.Set;
24 import java.util.concurrent.ExecutionException;
25 import javax.xml.xpath.XPathExpressionException;
26 import org.checkerframework.checker.lock.qual.GuardedBy;
27 import org.checkerframework.checker.lock.qual.Holding;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
30 import org.opendaylight.restconf.nb.rfc8040.NotificationQueryParams;
31 import org.opendaylight.restconf.nb.rfc8040.streams.StreamSessionHandler;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
33 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
34 import org.opendaylight.yangtools.concepts.Registration;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 /**
40  * Features of subscribing part of both notifications.
41  */
42 abstract class AbstractCommonSubscriber<P, T> extends AbstractNotificationsData implements BaseListenerInterface {
43     private static final Logger LOG = LoggerFactory.getLogger(AbstractCommonSubscriber.class);
44     private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
45         .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
46         .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
47         .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
48         .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
49         .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
50         .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
51         .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
52         .appendOffset("+HH:MM", "Z").toFormatter();
53
54     private final EventFormatterFactory<T> formatterFactory;
55     private final NotificationOutputType outputType;
56     private final String streamName;
57     private final P path;
58
59     @GuardedBy("this")
60     private final Set<StreamSessionHandler> subscribers = new HashSet<>();
61     @GuardedBy("this")
62     private Registration registration;
63
64     // FIXME: these should be final
65     private Instant start = null;
66     private Instant stop = null;
67     private boolean leafNodesOnly = false;
68     private boolean skipNotificationData = false;
69     private EventFormatter<T> formatter;
70
71     AbstractCommonSubscriber(final QName lastQName, final String streamName, final P path,
72             final NotificationOutputType outputType, final EventFormatterFactory<T> formatterFactory) {
73         super(lastQName);
74         this.streamName = requireNonNull(streamName);
75         checkArgument(!streamName.isEmpty());
76         this.path = requireNonNull(path);
77
78         this.outputType = requireNonNull(outputType);
79         this.formatterFactory = requireNonNull(formatterFactory);
80         formatter = formatterFactory.getFormatter();
81     }
82
83     @Override
84     public final String getStreamName() {
85         return streamName;
86     }
87
88     @Override
89     public final String getOutputType() {
90         return outputType.getName();
91     }
92
93     @Override
94     public final synchronized boolean hasSubscribers() {
95         return !subscribers.isEmpty();
96     }
97
98     @Override
99     public final synchronized Set<StreamSessionHandler> getSubscribers() {
100         return new HashSet<>(subscribers);
101     }
102
103     @Override
104     public final synchronized void close() throws InterruptedException, ExecutionException {
105         if (registration != null) {
106             registration.close();
107             registration = null;
108         }
109         deleteDataInDS().get();
110         subscribers.clear();
111     }
112
113     @Override
114     public synchronized void addSubscriber(final StreamSessionHandler subscriber) {
115         final boolean isConnected = subscriber.isConnected();
116         checkState(isConnected);
117         LOG.debug("Subscriber {} is added.", subscriber);
118         subscribers.add(subscriber);
119     }
120
121     @Override
122     public synchronized void removeSubscriber(final StreamSessionHandler subscriber) {
123         subscribers.remove(subscriber);
124         LOG.debug("Subscriber {} is removed", subscriber);
125         if (!hasSubscribers()) {
126             ListenersBroker.getInstance().removeAndCloseListener(this);
127         }
128     }
129
130     public final Instant getStart() {
131         return start;
132     }
133
134     /**
135      * Set query parameters for listener.
136      *
137      * @param params NotificationQueryParams to use.
138      */
139     public final void setQueryParams(final NotificationQueryParams params) {
140         final var startTime = params.startTime();
141         start = startTime == null ? Instant.now() : parseDateAndTime(startTime.value());
142
143         final var stopTime = params.stopTime();
144         stop = stopTime == null ? null : parseDateAndTime(stopTime.value());
145
146         final var leafNodes = params.leafNodesOnly();
147         leafNodesOnly = leafNodes == null ? false : leafNodes.value();
148
149         final var skipData = params.skipNotificationData();
150         skipNotificationData = skipData == null ? false : skipData.value();
151
152         final var filter = params.filter();
153         final String filterValue = filter == null ? null : filter.paramValue();
154         if (filterValue != null && !filterValue.isEmpty()) {
155             try {
156                 formatter = formatterFactory.getFormatter(filterValue);
157             } catch (XPathExpressionException e) {
158                 throw new IllegalArgumentException("Failed to get filter", e);
159             }
160         } else {
161             formatter = formatterFactory.getFormatter();
162         }
163     }
164
165     final P path() {
166         return path;
167     }
168
169     /**
170      * Check whether this query should only notify about leaf node changes.
171      *
172      * @return true if this query should only notify about leaf node changes
173      */
174     final boolean getLeafNodesOnly() {
175         return leafNodesOnly;
176     }
177
178     /**
179      * Check whether this query should notify changes without data.
180      *
181      * @return true if this query should notify about changes with  data
182      */
183     final boolean isSkipNotificationData() {
184         return skipNotificationData;
185     }
186
187     final EventFormatter<T> formatter() {
188         return formatter;
189     }
190
191     /**
192      * Sets {@link Registration} registration.
193      *
194      * @param registration a listener registration registration.
195      */
196     @Holding("this")
197     final void setRegistration(final Registration registration) {
198         this.registration = requireNonNull(registration);
199     }
200
201     /**
202      * Checks if {@link Registration} registration exists.
203      *
204      * @return {@code true} if exists, {@code false} otherwise.
205      */
206     @Holding("this")
207     final boolean isListening() {
208         return registration != null;
209     }
210
211     /**
212      * Post data to subscribed SSE session handlers.
213      *
214      * @param data Data of incoming notifications.
215      */
216     synchronized void post(final String data) {
217         final Iterator<StreamSessionHandler> iterator = subscribers.iterator();
218         while (iterator.hasNext()) {
219             final StreamSessionHandler subscriber = iterator.next();
220             final boolean isConnected = subscriber.isConnected();
221             if (isConnected) {
222                 subscriber.sendDataMessage(data);
223                 LOG.debug("Data was sent to subscriber {} on connection {}:", this, subscriber);
224             } else {
225                 // removal is probably not necessary, because it will be removed explicitly soon after invocation of
226                 // onWebSocketClosed(..) in handler; but just to be sure ...
227                 iterator.remove();
228                 LOG.debug("Subscriber for {} was removed - web-socket session is not open.", this);
229             }
230         }
231     }
232
233     @SuppressWarnings("checkstyle:IllegalCatch")
234     final boolean checkStartStop(final Instant now) {
235         if (stop != null) {
236             if (start.compareTo(now) < 0 && stop.compareTo(now) > 0) {
237                 return true;
238             }
239             if (stop.compareTo(now) < 0) {
240                 try {
241                     close();
242                 } catch (final Exception e) {
243                     throw new RestconfDocumentedException("Problem with unregister listener." + e);
244                 }
245             }
246         } else if (start != null) {
247             if (start.compareTo(now) < 0) {
248                 start = null;
249                 return true;
250             }
251         } else {
252             return true;
253         }
254         return false;
255     }
256
257     @Override
258     public final String toString() {
259         return MoreObjects.toStringHelper(this)
260             .add("path", path)
261             .add("stream-name", streamName)
262             .add("output-type", getOutputType())
263             .toString();
264     }
265
266     /**
267      * Parse input of query parameters - start-time or stop-time - from {@link DateAndTime} format
268      * to {@link Instant} format.
269      *
270      * @param uriValue Start-time or stop-time as string in {@link DateAndTime} format.
271      * @return Parsed {@link Instant} by entry.
272      */
273     private static @NonNull Instant parseDateAndTime(final DateAndTime dateAndTime) {
274         final TemporalAccessor accessor;
275         try {
276             accessor = FORMATTER.parse(dateAndTime.getValue());
277         } catch (final DateTimeParseException e) {
278             throw new RestconfDocumentedException("Cannot parse of value in date: " + dateAndTime, e);
279         }
280         return Instant.from(accessor);
281     }
282 }