2 * Copyright © 2019 FRINX s.r.o. All rights reserved.
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
8 package org.opendaylight.restconf.nb.rfc8040.streams;
10 import com.google.common.base.Strings;
11 import java.io.IOException;
12 import java.net.InetSocketAddress;
13 import java.nio.ByteBuffer;
14 import java.nio.charset.Charset;
15 import java.util.ArrayList;
16 import java.util.List;
17 import java.util.Objects;
18 import java.util.Optional;
19 import java.util.concurrent.ScheduledExecutorService;
20 import java.util.concurrent.ScheduledFuture;
21 import java.util.concurrent.TimeUnit;
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.opendaylight.restconf.nb.rfc8040.streams.listeners.BaseListenerInterface;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
33 * Web-socket session handler that is responsible for controlling of session, managing subscription
34 * to data-change-event or notification listener, and sending of data over established web-socket session.
37 public final class WebSocketSessionHandler implements StreamSessionHandler {
38 private static final Logger LOG = LoggerFactory.getLogger(WebSocketSessionHandler.class);
39 private static final byte[] PING_PAYLOAD = "ping".getBytes(Charset.defaultCharset());
41 private final ScheduledExecutorService executorService;
42 private final BaseListenerInterface listener;
43 private final int maximumFragmentLength;
44 private final int heartbeatInterval;
46 private Session session;
47 private ScheduledFuture<?> pingProcess;
50 * Creation of the new web-socket session handler.
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.
65 WebSocketSessionHandler(final ScheduledExecutorService executorService, final BaseListenerInterface listener,
66 final int maximumFragmentLength, final int heartbeatInterval) {
67 this.executorService = executorService;
68 this.listener = listener;
69 this.maximumFragmentLength = maximumFragmentLength;
70 this.heartbeatInterval = heartbeatInterval;
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.
78 * @param webSocketSession Created web-socket session.
79 * @see OnWebSocketConnect More information about invocation of this method and parameters.
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);
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.
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.
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: {}.",
111 listener.removeSubscriber(this);
117 * Handling of error in web-socket implementation. Subscription at listener is removed, open session is closed
118 * and ping process is stopped.
120 * @param error Error details.
121 * @see OnWebSocketError More information about invocation of this method and parameters.
124 public synchronized void onWebSocketError(final Throwable error) {
125 LOG.warn("An error occurred on web-socket: ", error);
126 if (session != null) {
127 LOG.warn("Trying to close web-socket session {} gracefully after error.", session);
128 listener.removeSubscriber(this);
129 if (session.isOpen()) {
136 private void stopPingProcess() {
137 if (pingProcess != null && !pingProcess.isDone() && !pingProcess.isCancelled()) {
138 pingProcess.cancel(true);
143 * Sensing of string message to remote endpoint of {@link org.eclipse.jetty.websocket.api.Session}. If the maximum
144 * fragment length is set to non-zero positive value and input message exceeds this value, message is fragmented
145 * to multiple message fragments which are send individually but still in one web-socket transaction.
147 * @param message Message data to be send over web-socket session.
150 public synchronized void sendDataMessage(final String message) {
151 if (Strings.isNullOrEmpty(message)) {
152 // FIXME: should this be tolerated?
156 if (session != null && session.isOpen()) {
157 final RemoteEndpoint remoteEndpoint = session.getRemote();
158 if (maximumFragmentLength == 0 || message.length() <= maximumFragmentLength) {
159 sendDataMessage(message, remoteEndpoint);
161 sendFragmentedMessage(splitMessageToFragments(message, maximumFragmentLength), remoteEndpoint);
164 LOG.trace("Message with body '{}' is not sent because underlay web-socket session is not open.", message);
168 private void sendDataMessage(final String message, final RemoteEndpoint remoteEndpoint) {
170 remoteEndpoint.sendString(message);
171 LOG.trace("Message with body '{}' has been successfully sent to remote endpoint {}.", message,
173 } catch (IOException e) {
174 LOG.warn("Cannot send message over web-socket session {}.", session, e);
178 private void sendFragmentedMessage(final List<String> orderedFragments, final RemoteEndpoint remoteEndpoint) {
179 for (int i = 0; i < orderedFragments.size(); i++) {
180 final String fragment = orderedFragments.get(i);
181 final boolean last = i == orderedFragments.size() - 1;
184 remoteEndpoint.sendPartialString(fragment, last);
185 } catch (IOException e) {
186 LOG.warn("Cannot send message fragment number {} over web-socket session {}. All other fragments of "
187 + " the message are dropped too.", i, session, e);
190 LOG.trace("Message fragment number {} with body '{}' has been successfully sent to remote endpoint {}.", i,
191 fragment, remoteEndpoint);
195 private synchronized void sendPingMessage() {
197 Objects.requireNonNull(session).getRemote().sendPing(ByteBuffer.wrap(PING_PAYLOAD));
198 } catch (IOException e) {
199 LOG.warn("Cannot send ping message over web-socket session {}.", session, e);
203 private static List<String> splitMessageToFragments(final String inputMessage, final int maximumFragmentLength) {
204 final List<String> parts = new ArrayList<>();
205 int length = inputMessage.length();
206 for (int i = 0; i < length; i += maximumFragmentLength) {
207 parts.add(inputMessage.substring(i, Math.min(length, i + maximumFragmentLength)));
213 * Get remote endpoint address of the current web-socket session.
215 * @return If the session exists and is open the {@link InetSocketAddress} wrapped in {@link Optional} is returned.
216 * Otherwise, {@link Optional#empty()} is returned.
218 // FIXME: remove this method?
219 public synchronized Optional<InetSocketAddress> getRemoteEndpointAddress() {
220 if (session != null && session.isOpen()) {
221 return Optional.of(session.getRemote().getInetSocketAddress());
223 return Optional.empty();
228 public synchronized boolean isConnected() {
229 if (session != null && session.isOpen()) {