|
| 1 | +"""Gateway connection classes.""" |
| 2 | +# Copyright (c) Jupyter Development Team. |
| 3 | +# Distributed under the terms of the Modified BSD License. |
| 4 | + |
| 5 | +import asyncio |
| 6 | +import logging |
| 7 | +import random |
| 8 | +from typing import Any, cast |
| 9 | + |
| 10 | +import tornado.websocket as tornado_websocket |
| 11 | +from tornado.concurrent import Future |
| 12 | +from tornado.escape import json_decode, url_escape, utf8 |
| 13 | +from tornado.httpclient import HTTPRequest |
| 14 | +from tornado.ioloop import IOLoop |
| 15 | +from traitlets import Bool, Instance, Int |
| 16 | + |
| 17 | +from ..services.kernels.connection.base import BaseKernelWebsocketConnection |
| 18 | +from ..utils import url_path_join |
| 19 | +from .managers import GatewayClient |
| 20 | + |
| 21 | + |
| 22 | +class GatewayWebSocketConnection(BaseKernelWebsocketConnection): |
| 23 | + """Web socket connection that proxies to a kernel/enterprise gateway.""" |
| 24 | + |
| 25 | + ws = Instance(klass=tornado_websocket.WebSocketClientConnection, allow_none=True) |
| 26 | + |
| 27 | + ws_future = Instance(default_value=Future(), klass=Future) |
| 28 | + |
| 29 | + disconnected = Bool(False) |
| 30 | + |
| 31 | + retry = Int(0) |
| 32 | + |
| 33 | + async def connect(self): |
| 34 | + """Connect to the socket.""" |
| 35 | + # websocket is initialized before connection |
| 36 | + self.ws = None |
| 37 | + ws_url = url_path_join( |
| 38 | + GatewayClient.instance().ws_url, |
| 39 | + GatewayClient.instance().kernels_endpoint, |
| 40 | + url_escape(self.kernel_id), |
| 41 | + "channels", |
| 42 | + ) |
| 43 | + self.log.info(f"Connecting to {ws_url}") |
| 44 | + kwargs: dict = {} |
| 45 | + kwargs = GatewayClient.instance().load_connection_args(**kwargs) |
| 46 | + |
| 47 | + request = HTTPRequest(ws_url, **kwargs) |
| 48 | + self.ws_future = cast(Future, tornado_websocket.websocket_connect(request)) |
| 49 | + self.ws_future.add_done_callback(self._connection_done) |
| 50 | + |
| 51 | + loop = IOLoop.current() |
| 52 | + loop.add_future(self.ws_future, lambda future: self._read_messages()) |
| 53 | + |
| 54 | + def _connection_done(self, fut): |
| 55 | + """Handle a finished connection.""" |
| 56 | + if ( |
| 57 | + not self.disconnected and fut.exception() is None |
| 58 | + ): # prevent concurrent.futures._base.CancelledError |
| 59 | + self.ws = fut.result() |
| 60 | + self.retry = 0 |
| 61 | + self.log.debug(f"Connection is ready: ws: {self.ws}") |
| 62 | + else: |
| 63 | + self.log.warning( |
| 64 | + "Websocket connection has been closed via client disconnect or due to error. " |
| 65 | + "Kernel with ID '{}' may not be terminated on GatewayClient: {}".format( |
| 66 | + self.kernel_id, GatewayClient.instance().url |
| 67 | + ) |
| 68 | + ) |
| 69 | + |
| 70 | + def disconnect(self): |
| 71 | + """Handle a disconnect.""" |
| 72 | + self.disconnected = True |
| 73 | + if self.ws is not None: |
| 74 | + # Close connection |
| 75 | + self.ws.close() |
| 76 | + elif not self.ws_future.done(): |
| 77 | + # Cancel pending connection. Since future.cancel() is a noop on tornado, we'll track cancellation locally |
| 78 | + self.ws_future.cancel() |
| 79 | + self.log.debug(f"_disconnect: future cancelled, disconnected: {self.disconnected}") |
| 80 | + |
| 81 | + async def _read_messages(self): |
| 82 | + """Read messages from gateway server.""" |
| 83 | + while self.ws is not None: |
| 84 | + message = None |
| 85 | + if not self.disconnected: |
| 86 | + try: |
| 87 | + message = await self.ws.read_message() |
| 88 | + except Exception as e: |
| 89 | + self.log.error( |
| 90 | + f"Exception reading message from websocket: {e}" |
| 91 | + ) # , exc_info=True) |
| 92 | + if message is None: |
| 93 | + if not self.disconnected: |
| 94 | + self.log.warning(f"Lost connection to Gateway: {self.kernel_id}") |
| 95 | + break |
| 96 | + self.handle_outgoing_message( |
| 97 | + message |
| 98 | + ) # pass back to notebook client (see self.on_open and WebSocketChannelsHandler.open) |
| 99 | + else: # ws cancelled - stop reading |
| 100 | + break |
| 101 | + |
| 102 | + # NOTE(esevan): if websocket is not disconnected by client, try to reconnect. |
| 103 | + if not self.disconnected and self.retry < GatewayClient.instance().gateway_retry_max: |
| 104 | + jitter = random.randint(10, 100) * 0.01 # noqa |
| 105 | + retry_interval = ( |
| 106 | + min( |
| 107 | + GatewayClient.instance().gateway_retry_interval * (2**self.retry), |
| 108 | + GatewayClient.instance().gateway_retry_interval_max, |
| 109 | + ) |
| 110 | + + jitter |
| 111 | + ) |
| 112 | + self.retry += 1 |
| 113 | + self.log.info( |
| 114 | + "Attempting to re-establish the connection to Gateway in %s secs (%s/%s): %s", |
| 115 | + retry_interval, |
| 116 | + self.retry, |
| 117 | + GatewayClient.instance().gateway_retry_max, |
| 118 | + self.kernel_id, |
| 119 | + ) |
| 120 | + await asyncio.sleep(retry_interval) |
| 121 | + loop = IOLoop.current() |
| 122 | + loop.spawn_callback(self.connect) |
| 123 | + |
| 124 | + def handle_outgoing_message(self, incoming_msg: str, *args: Any) -> None: |
| 125 | + """Send message to the notebook client.""" |
| 126 | + try: |
| 127 | + self.websocket_handler.write_message(incoming_msg) |
| 128 | + except tornado_websocket.WebSocketClosedError: |
| 129 | + if self.log.isEnabledFor(logging.DEBUG): |
| 130 | + msg_summary = GatewayWebSocketConnection._get_message_summary( |
| 131 | + json_decode(utf8(incoming_msg)) |
| 132 | + ) |
| 133 | + self.log.debug( |
| 134 | + "Notebook client closed websocket connection - message dropped: {}".format( |
| 135 | + msg_summary |
| 136 | + ) |
| 137 | + ) |
| 138 | + |
| 139 | + def handle_incoming_message(self, message: str) -> None: |
| 140 | + """Send message to gateway server.""" |
| 141 | + if self.ws is None: |
| 142 | + loop = IOLoop.current() |
| 143 | + loop.add_future(self.ws_future, lambda future: self.handle_incoming_message(message)) |
| 144 | + else: |
| 145 | + self._write_message(message) |
| 146 | + |
| 147 | + def _write_message(self, message): |
| 148 | + """Send message to gateway server.""" |
| 149 | + try: |
| 150 | + if not self.disconnected and self.ws is not None: |
| 151 | + self.ws.write_message(message) |
| 152 | + except Exception as e: |
| 153 | + self.log.error(f"Exception writing message to websocket: {e}") # , exc_info=True) |
| 154 | + |
| 155 | + @staticmethod |
| 156 | + def _get_message_summary(message): |
| 157 | + """Get a summary of a message.""" |
| 158 | + summary = [] |
| 159 | + message_type = message["msg_type"] |
| 160 | + summary.append(f"type: {message_type}") |
| 161 | + |
| 162 | + if message_type == "status": |
| 163 | + summary.append(", state: {}".format(message["content"]["execution_state"])) |
| 164 | + elif message_type == "error": |
| 165 | + summary.append( |
| 166 | + ", {}:{}:{}".format( |
| 167 | + message["content"]["ename"], |
| 168 | + message["content"]["evalue"], |
| 169 | + message["content"]["traceback"], |
| 170 | + ) |
| 171 | + ) |
| 172 | + else: |
| 173 | + summary.append(", ...") # don't display potentially sensitive data |
| 174 | + |
| 175 | + return "".join(summary) |
0 commit comments