Remove BaseListenerInterface
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / streams / WebSocketSessionHandler.java
1 /*
2  * Copyright © 2019 FRINX s.r.o. 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;
9
10 import com.google.common.base.Strings;
11 import java.io.IOException;
12 import java.nio.ByteBuffer;
13 import java.nio.charset.Charset;
14 import java.util.ArrayList;
15 import java.util.List;
16 import java.util.Objects;
17 import java.util.concurrent.ScheduledExecutorService;
18 import java.util.concurrent.ScheduledFuture;
19 import java.util.concurrent.TimeUnit;
20 import java.util.concurrent.TimeoutException;
21 import org.eclipse.jetty.websocket.api.CloseException;
22 import org.eclipse.jetty.websocket.api.RemoteEndpoint;
23 import org.eclipse.jetty.websocket.api.Session;
24 import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
25 import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
26 import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;
27 import org.eclipse.jetty.websocket.api.annotations.WebSocket;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 /**
32  * Web-socket session handler that is responsible for controlling of session, managing subscription
33  * to data-change-event or notification listener, and sending of data over established web-socket session.
34  */
35 @WebSocket
36 public final class WebSocketSessionHandler implements StreamSessionHandler {
37     private static final Logger LOG = LoggerFactory.getLogger(WebSocketSessionHandler.class);
38     private static final byte[] PING_PAYLOAD = "ping".getBytes(Charset.defaultCharset());
39
40     private final ScheduledExecutorService executorService;
41     // FIXME: this really should include formatter etc.
42     private final AbstractStream<?> listener;
43     private final int maximumFragmentLength;
44     private final int heartbeatInterval;
45
46     private Session session;
47     private ScheduledFuture<?> pingProcess;
48
49     /**
50      * Creation of the new web-socket session handler.
51      *
52      * @param executorService       Executor that is used for periodical sending of web-socket ping messages to keep
53      *                              session up even if the notifications doesn't flow from server to clients or clients
54      *                              don't implement ping-pong service.
55      * @param listener              YANG notification or data-change event listener to which client on this web-socket
56      *                              session subscribes to.
57      * @param maximumFragmentLength Maximum fragment length in number of Unicode code units (characters).
58      *                              If this parameter is set to 0, the maximum fragment length is disabled and messages
59      *                              up to 64 KB can be sent in TCP segment (exceeded notification length ends in error).
60      *                              If the parameter is set to non-zero positive value, messages longer than this
61      *                              parameter are fragmented into multiple web-socket messages sent in one transaction.
62      * @param heartbeatInterval     Interval in milliseconds of sending of ping control frames to remote endpoint
63      *                              to keep session up. Ping control frames are disabled if this parameter is set to 0.
64      */
65     WebSocketSessionHandler(final ScheduledExecutorService executorService, final AbstractStream<?> listener,
66             final int maximumFragmentLength, final int heartbeatInterval) {
67         this.executorService = executorService;
68         this.listener = listener;
69         this.maximumFragmentLength = maximumFragmentLength;
70         this.heartbeatInterval = heartbeatInterval;
71     }
72
73     /**
74      * Handling of the web-socket connected event (web-socket session between local server and remote endpoint has been
75      * established). Web-socket session handler is registered at data-change-event / YANG notification listener and
76      * the heartbeat ping process is started if it is enabled.
77      *
78      * @param webSocketSession Created web-socket session.
79      * @see OnWebSocketConnect More information about invocation of this method and parameters.
80      */
81     @OnWebSocketConnect
82     public synchronized void onWebSocketConnected(final Session webSocketSession) {
83         if (session == null || !session.isOpen()) {
84             session = webSocketSession;
85             listener.addSubscriber(this);
86             LOG.debug("A new web-socket session {} has been successfully registered.", webSocketSession);
87             if (heartbeatInterval != 0) {
88                 // sending of PING frame can be long if there is an error on web-socket - from this reason
89                 // the fixed-rate should not be used
90                 pingProcess = executorService.scheduleWithFixedDelay(this::sendPingMessage, heartbeatInterval,
91                         heartbeatInterval, TimeUnit.MILLISECONDS);
92             }
93         }
94     }
95
96     /**
97      * Handling of web-socket session closed event (timeout, error, or both parties closed session). Removal
98      * of subscription at listener and stopping of the ping process.
99      *
100      * @param statusCode Web-socket status code.
101      * @param reason     Reason, why the web-socket is closed (for example, reached timeout).
102      * @see OnWebSocketClose More information about invocation of this method and parameters.
103      */
104     @OnWebSocketClose
105     public synchronized void onWebSocketClosed(final int statusCode, final String reason) {
106         // note: there is not guarantee that Session.isOpen() returns true - it is better to not check it here
107         // using 'session != null && session.isOpen()'
108         if (session != null) {
109             LOG.debug("Web-socket session has been closed with status code {} and reason message: {}.",
110                     statusCode, reason);
111             listener.removeSubscriber(this);
112             stopPingProcess();
113         }
114     }
115
116     /**
117      * Handling of error in web-socket implementation. Subscription at listener is removed, open session is closed
118      * and ping process is stopped.
119      *
120      * @param error Error details.
121      * @see OnWebSocketError More information about invocation of this method and parameters.
122      */
123     @OnWebSocketError
124     public synchronized void onWebSocketError(final Throwable error) {
125         if (error instanceof CloseException && error.getCause() instanceof TimeoutException timeout) {
126             // A timeout is expected, do not log the complete stack trace
127             LOG.info("Web-socket closed by timeout: {}", timeout.getMessage());
128         } else {
129             LOG.warn("An error occurred on web-socket: ", error);
130         }
131         if (session != null) {
132             LOG.info("Trying to close web-socket session {} gracefully after error.", session);
133             listener.removeSubscriber(this);
134             if (session.isOpen()) {
135                 session.close();
136             }
137             stopPingProcess();
138         }
139     }
140
141     private void stopPingProcess() {
142         if (pingProcess != null && !pingProcess.isDone() && !pingProcess.isCancelled()) {
143             pingProcess.cancel(true);
144         }
145     }
146
147     /**
148      * Sensing of string message to remote endpoint of {@link org.eclipse.jetty.websocket.api.Session}. If the maximum
149      * fragment length is set to non-zero positive value and input message exceeds this value, message is fragmented
150      * to multiple message fragments which are send individually but still in one web-socket transaction.
151      *
152      * @param message Message data to be send over web-socket session.
153      */
154     @Override
155     public synchronized void sendDataMessage(final String message) {
156         if (Strings.isNullOrEmpty(message)) {
157             // FIXME: should this be tolerated?
158             return;
159         }
160
161         if (session != null && session.isOpen()) {
162             final RemoteEndpoint remoteEndpoint = session.getRemote();
163             if (maximumFragmentLength == 0 || message.length() <= maximumFragmentLength) {
164                 sendDataMessage(message, remoteEndpoint);
165             } else {
166                 sendFragmentedMessage(splitMessageToFragments(message, maximumFragmentLength), remoteEndpoint);
167             }
168         } else {
169             LOG.trace("Message with body '{}' is not sent because underlay web-socket session is not open.", message);
170         }
171     }
172
173     private void sendDataMessage(final String message, final RemoteEndpoint remoteEndpoint) {
174         try {
175             remoteEndpoint.sendString(message);
176             LOG.trace("Message with body '{}' has been successfully sent to remote endpoint {}.", message,
177                 remoteEndpoint);
178         } catch (IOException e) {
179             LOG.warn("Cannot send message over web-socket session {}.", session, e);
180         }
181     }
182
183     private void sendFragmentedMessage(final List<String> orderedFragments, final RemoteEndpoint remoteEndpoint) {
184         for (int i = 0; i < orderedFragments.size(); i++) {
185             final String fragment = orderedFragments.get(i);
186             final boolean last = i == orderedFragments.size() - 1;
187
188             try {
189                 remoteEndpoint.sendPartialString(fragment, last);
190             } catch (IOException e) {
191                 LOG.warn("Cannot send message fragment number {} over web-socket session {}. All other fragments of "
192                     + " the message are dropped too.", i, session, e);
193                 return;
194             }
195             LOG.trace("Message fragment number {} with body '{}' has been successfully sent to remote endpoint {}.", i,
196                 fragment, remoteEndpoint);
197         }
198     }
199
200     private synchronized void sendPingMessage() {
201         try {
202             Objects.requireNonNull(session).getRemote().sendPing(ByteBuffer.wrap(PING_PAYLOAD));
203         } catch (IOException e) {
204             LOG.warn("Cannot send ping message over web-socket session {}.", session, e);
205         }
206     }
207
208     private static List<String> splitMessageToFragments(final String inputMessage, final int maximumFragmentLength) {
209         final List<String> parts = new ArrayList<>();
210         int length = inputMessage.length();
211         for (int i = 0; i < length; i += maximumFragmentLength) {
212             parts.add(inputMessage.substring(i, Math.min(length, i + maximumFragmentLength)));
213         }
214         return parts;
215     }
216
217     @Override
218     public synchronized boolean isConnected() {
219         return session != null && session.isOpen();
220     }
221 }