first commit

This commit is contained in:
Ayxan
2022-05-23 00:16:32 +04:00
commit d660f2a4ca
24786 changed files with 4428337 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
"""Terminals served to xterm.js using Tornado websockets"""
# Copyright (c) Jupyter Development Team
# Copyright (c) 2014, Ramalingam Saravanan <sarava@sarava.net>
# Distributed under the terms of the Simplified BSD License.
from .management import NamedTermManager # noqa
from .management import SingleTermManager # noqa
from .management import TermManagerBase # noqa
from .management import UniqueTermManager # noqa
from .websocket import TermSocket # noqa
__version__ = "0.15.0"

View File

@@ -0,0 +1,46 @@
// Copyright (c) Jupyter Development Team
// Copyright (c) 2014, Ramalingam Saravanan <sarava@sarava.net>
// Distributed under the terms of the Simplified BSD License.
function make_terminal(element, size, ws_url) {
var ws = new WebSocket(ws_url);
var term = new Terminal({
cols: size.cols,
rows: size.rows,
screenKeys: true,
useStyle: true,
});
ws.onopen = function (event) {
ws.send(
JSON.stringify([
"set_size",
size.rows,
size.cols,
window.innerHeight,
window.innerWidth,
])
);
term.on("data", function (data) {
ws.send(JSON.stringify(["stdin", data]));
});
term.on("title", function (title) {
document.title = title;
});
term.open(element);
ws.onmessage = function (event) {
json_msg = JSON.parse(event.data);
switch (json_msg[0]) {
case "stdout":
term.write(json_msg[1]);
break;
case "disconnect":
term.write("\r\n\r\n[Finished... Terminado]\r\n");
break;
}
};
};
return { socket: ws, term: term };
}

View File

@@ -0,0 +1,387 @@
"""Terminal management for exposing terminals to a web interface using Tornado.
"""
# Copyright (c) Jupyter Development Team
# Copyright (c) 2014, Ramalingam Saravanan <sarava@sarava.net>
# Distributed under the terms of the Simplified BSD License.
import asyncio
import codecs
import itertools
import logging
import os
import select
import signal
import warnings
from collections import deque
try:
from ptyprocess import PtyProcessUnicode
def preexec_fn():
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
except ImportError:
try:
from winpty import PtyProcess as PtyProcessUnicode
except ImportError:
PtyProcessUnicode = object
preexec_fn = None # type:ignore[assignment]
from tornado.ioloop import IOLoop
ENV_PREFIX = "PYXTERM_" # Environment variable prefix
# TERM is set according to xterm.js capabilities
DEFAULT_TERM_TYPE = "xterm-256color"
class PtyWithClients:
def __init__(self, argv, env=None, cwd=None):
self.clients = []
# Use read_buffer to store historical messages for reconnection
self.read_buffer: deque[list] = deque([], maxlen=1000)
kwargs = dict(argv=argv, env=env or [], cwd=cwd)
if preexec_fn is not None:
kwargs["preexec_fn"] = preexec_fn
self.ptyproc = PtyProcessUnicode.spawn(**kwargs)
# The output might not be strictly UTF-8 encoded, so
# we replace the inner decoder of PtyProcessUnicode
# to allow non-strict decode.
self.ptyproc.decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
def resize_to_smallest(self):
"""Set the terminal size to that of the smallest client dimensions.
A terminal not using the full space available is much nicer than a
terminal trying to use more than the available space, so we keep it
sized to the smallest client.
"""
minrows = mincols = 10001
for client in self.clients:
rows, cols = client.size
if rows is not None and rows < minrows:
minrows = rows
if cols is not None and cols < mincols:
mincols = cols
if minrows == 10001 or mincols == 10001:
return
rows, cols = self.ptyproc.getwinsize()
if (rows, cols) != (minrows, mincols):
self.ptyproc.setwinsize(minrows, mincols)
def kill(self, sig=signal.SIGTERM):
"""Send a signal to the process in the pty"""
self.ptyproc.kill(sig)
def killpg(self, sig=signal.SIGTERM):
"""Send a signal to the process group of the process in the pty"""
if os.name == "nt":
return self.ptyproc.kill(sig)
pgid = os.getpgid(self.ptyproc.pid)
os.killpg(pgid, sig)
async def terminate(self, force=False):
"""This forces a child process to terminate. It starts nicely with
SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
returns True if the child was terminated. This returns False if the
child could not be terminated."""
if os.name == "nt":
signals = [signal.SIGINT, signal.SIGTERM]
else:
signals = [signal.SIGHUP, signal.SIGCONT, signal.SIGINT, signal.SIGTERM]
_ = IOLoop.current()
def sleep():
return asyncio.sleep(self.ptyproc.delayafterterminate)
if not self.ptyproc.isalive():
return True
try:
for sig in signals:
self.kill(sig)
await sleep()
if not self.ptyproc.isalive():
return True
if force:
self.kill(signal.SIGKILL)
await sleep()
if not self.ptyproc.isalive():
return True
else:
return False
return False
except OSError:
# I think there are kernel timing issues that sometimes cause
# this to happen. I think isalive() reports True, but the
# process is dead to the kernel.
# Make one last attempt to see if the kernel is up to date.
await sleep()
if not self.ptyproc.isalive():
return True
else:
return False
def _update_removing(target, changes):
"""Like dict.update(), but remove keys where the value is None."""
for k, v in changes.items():
if v is None:
target.pop(k, None)
else:
target[k] = v
def _poll(fd: int, timeout: float = 0.1) -> list:
"""Poll using poll() on posix systems and select() elsewhere (e.g., Windows)"""
if os.name == "posix":
poller = select.poll() # noqa: ignore missing method on Windows
poller.register(
fd, select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR
) # read-only
return poller.poll(timeout * 1000) # milliseconds
else:
# poll() not supported on Windows
r, _, _ = select.select([fd], [], [], timeout)
return r
class TermManagerBase:
"""Base class for a terminal manager."""
def __init__(
self, shell_command, server_url="", term_settings=None, extra_env=None, ioloop=None
):
self.shell_command = shell_command
self.server_url = server_url
self.term_settings = term_settings or {}
self.extra_env = extra_env
self.log = logging.getLogger(__name__)
self.ptys_by_fd = {}
if ioloop is not None:
warnings.warn(
f"Setting {self.__class__.__name__}.ioloop is deprecated and ignored",
DeprecationWarning,
stacklevel=2,
)
def make_term_env(self, height=25, width=80, winheight=0, winwidth=0, **kwargs):
"""Build the environment variables for the process in the terminal."""
env = os.environ.copy()
# ignore any previously set TERM
# TERM is set according to xterm.js capabilities
env["TERM"] = self.term_settings.get("type", DEFAULT_TERM_TYPE)
dimensions = "%dx%d" % (width, height)
if winwidth and winheight:
dimensions += ";%dx%d" % (winwidth, winheight)
env[ENV_PREFIX + "DIMENSIONS"] = dimensions
env["COLUMNS"] = str(width)
env["LINES"] = str(height)
if self.server_url:
env[ENV_PREFIX + "URL"] = self.server_url
if self.extra_env:
_update_removing(env, self.extra_env)
term_env = kwargs.get("extra_env", {})
if term_env and isinstance(term_env, dict):
_update_removing(env, term_env)
return env
def new_terminal(self, **kwargs):
"""Make a new terminal, return a :class:`PtyWithClients` instance."""
options = self.term_settings.copy()
options["shell_command"] = self.shell_command
options.update(kwargs)
argv = options["shell_command"]
env = self.make_term_env(**options)
cwd = options.get("cwd", None)
return PtyWithClients(argv, env, cwd)
def start_reading(self, ptywclients):
"""Connect a terminal to the tornado event loop to read data from it."""
fd = ptywclients.ptyproc.fd
self.ptys_by_fd[fd] = ptywclients
loop = IOLoop.current()
loop.add_handler(fd, self.pty_read, loop.READ)
def on_eof(self, ptywclients):
"""Called when the pty has closed."""
# Stop trying to read from that terminal
fd = ptywclients.ptyproc.fd
self.log.info("EOF on FD %d; stopping reading", fd)
del self.ptys_by_fd[fd]
IOLoop.current().remove_handler(fd)
# This closes the fd, and should result in the process being reaped.
ptywclients.ptyproc.close()
def pty_read(self, fd, events=None):
"""Called by the event loop when there is pty data ready to read."""
# prevent blocking on fd
if not _poll(fd, timeout=0.1): # 100ms
self.log.debug(f"Spurious pty_read() on fd {fd}")
return
ptywclients = self.ptys_by_fd[fd]
try:
self.pre_pty_read_hook(ptywclients)
s = ptywclients.ptyproc.read(65536)
ptywclients.read_buffer.append(s)
for client in ptywclients.clients:
client.on_pty_read(s)
except EOFError:
self.on_eof(ptywclients)
for client in ptywclients.clients:
client.on_pty_died()
def pre_pty_read_hook(self, ptywclients):
"""Hook before pty read, subclass can patch something into ptywclients when pty_read"""
def get_terminal(self, url_component=None):
"""Override in a subclass to give a terminal to a new websocket connection
The :class:`TermSocket` handler works with zero or one URL components
(capturing groups in the URL spec regex). If it receives one, it is
passed as the ``url_component`` parameter; otherwise, this is None.
"""
raise NotImplementedError
def client_disconnected(self, websocket):
"""Override this to e.g. kill terminals on client disconnection."""
pass
async def shutdown(self):
await self.kill_all()
async def kill_all(self):
futures = []
for term in self.ptys_by_fd.values():
futures.append(term.terminate(force=True))
# wait for futures to finish
if futures:
await asyncio.gather(*futures)
class SingleTermManager(TermManagerBase):
"""All connections to the websocket share a common terminal."""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.terminal = None
def get_terminal(self, url_component=None):
if self.terminal is None:
self.terminal = self.new_terminal()
self.start_reading(self.terminal)
return self.terminal
async def kill_all(self):
await super().kill_all()
self.terminal = None
class MaxTerminalsReached(Exception):
def __init__(self, max_terminals):
self.max_terminals = max_terminals
def __str__(self):
return "Cannot create more than %d terminals" % self.max_terminals
class UniqueTermManager(TermManagerBase):
"""Give each websocket a unique terminal to use."""
def __init__(self, max_terminals=None, **kwargs):
super().__init__(**kwargs)
self.max_terminals = max_terminals
def get_terminal(self, url_component=None):
if self.max_terminals and len(self.ptys_by_fd) >= self.max_terminals:
raise MaxTerminalsReached(self.max_terminals)
term = self.new_terminal()
self.start_reading(term)
return term
def client_disconnected(self, websocket):
"""Send terminal SIGHUP when client disconnects."""
self.log.info("Websocket closed, sending SIGHUP to terminal.")
if websocket.terminal:
if os.name == "nt":
websocket.terminal.kill()
# Immediately call the pty reader to process
# the eof and free up space
self.pty_read(websocket.terminal.ptyproc.fd)
return
websocket.terminal.killpg(signal.SIGHUP)
class NamedTermManager(TermManagerBase):
"""Share terminals between websockets connected to the same endpoint."""
def __init__(self, max_terminals=None, **kwargs):
super().__init__(**kwargs)
self.max_terminals = max_terminals
self.terminals = {}
def get_terminal(self, term_name):
assert term_name is not None
if term_name in self.terminals:
return self.terminals[term_name]
if self.max_terminals and len(self.terminals) >= self.max_terminals:
raise MaxTerminalsReached(self.max_terminals)
# Create new terminal
self.log.info("New terminal with specified name: %s", term_name)
term = self.new_terminal()
term.term_name = term_name
self.terminals[term_name] = term
self.start_reading(term)
return term
name_template = "%d"
def _next_available_name(self):
for n in itertools.count(start=1):
name = self.name_template % n
if name not in self.terminals:
return name
def new_named_terminal(self, **kwargs):
if "name" in kwargs:
name = kwargs["name"]
else:
name = self._next_available_name()
term = self.new_terminal(**kwargs)
self.log.info("New terminal with automatic name: %s", name)
term.term_name = name
self.terminals[name] = term
self.start_reading(term)
return name, term
def kill(self, name, sig=signal.SIGTERM):
term = self.terminals[name]
term.kill(sig) # This should lead to an EOF
async def terminate(self, name, force=False):
term = self.terminals[name]
await term.terminate(force=force)
def on_eof(self, ptywclients):
super().on_eof(ptywclients)
name = ptywclients.term_name
self.log.info("Terminal %s closed", name)
self.terminals.pop(name, None)
async def kill_all(self):
await super().kill_all()
self.terminals = {}

View File

@@ -0,0 +1,287 @@
# basic_tests.py -- Basic unit tests for Terminado
# Copyright (c) Jupyter Development Team
# Copyright (c) 2014, Ramalingam Saravanan <sarava@sarava.net>
# Distributed under the terms of the Simplified BSD License.
import asyncio
import datetime
import json
import os
import re
# We must set the policy for python >=3.8, see https://www.tornadoweb.org/en/stable/#installation
# Snippet from https://github.com/tornadoweb/tornado/issues/2608#issuecomment-619524992
import sys
import unittest
from sys import platform
import pytest
import tornado
import tornado.httpserver
import tornado.testing
from tornado.ioloop import IOLoop
from terminado import NamedTermManager, SingleTermManager, TermSocket, UniqueTermManager
if sys.version_info[0] == 3 and sys.version_info[1] >= 8 and sys.platform.startswith("win"):
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
#
# The timeout we use to assume no more messages are coming
# from the sever.
#
DONE_TIMEOUT = 1.0
os.environ["ASYNC_TEST_TIMEOUT"] = "20" # Global test case timeout
MAX_TERMS = 3 # Testing thresholds
class TestTermClient:
"""Test connection to a terminal manager"""
__test__ = False
def __init__(self, websocket):
self.ws = websocket
self.pending_read = None
async def read_msg(self):
# Because the Tornado Websocket client has no way to cancel
# a pending read, we have to keep track of them...
if self.pending_read is None:
self.pending_read = self.ws.read_message()
response = await self.pending_read
self.pending_read = None
if response:
response = json.loads(response)
return response
async def read_all_msg(self, timeout=DONE_TIMEOUT):
"""Read messages until read times out"""
msglist: list = []
delta = datetime.timedelta(seconds=timeout)
while True:
try:
mf = self.read_msg()
msg = await tornado.gen.with_timeout(delta, mf)
except tornado.gen.TimeoutError:
return msglist
msglist.append(msg)
async def write_msg(self, msg):
await self.ws.write_message(json.dumps(msg))
async def read_stdout(self, timeout=DONE_TIMEOUT):
"""Read standard output until timeout read reached,
return stdout and any non-stdout msgs received."""
msglist = await self.read_all_msg(timeout)
stdout = "".join([msg[1] for msg in msglist if msg[0] == "stdout"])
othermsg = [msg for msg in msglist if msg[0] != "stdout"]
return (stdout, othermsg)
async def write_stdin(self, data):
"""Write to terminal stdin"""
await self.write_msg(["stdin", data])
async def get_pid(self):
"""Get process ID of terminal shell process"""
await self.read_stdout() # Clear out any pending
await self.write_stdin("echo $$\r")
(stdout, extra) = await self.read_stdout()
if os.name == "nt":
match = re.search(r"echo \$\$\\.*?\\r\\n(\d+)", repr(stdout))
assert match is not None
pid = int(match.groups()[0])
else:
pid = int(stdout.split("\n")[1])
return pid
def close(self):
self.ws.close()
class TermTestCase(tornado.testing.AsyncHTTPTestCase):
# Factory for TestTermClient, because it has to be async
# See: https://github.com/tornadoweb/tornado/issues/1161
async def get_term_client(self, path):
port = self.get_http_port()
url = "ws://127.0.0.1:%d%s" % (port, path)
request = tornado.httpclient.HTTPRequest(
url, headers={"Origin": "http://127.0.0.1:%d" % port}
)
ws = await tornado.websocket.websocket_connect(request)
return TestTermClient(ws)
async def get_term_clients(self, paths):
return await asyncio.gather(*(self.get_term_client(path) for path in paths))
async def get_pids(self, tm_list):
pids = []
for tm in tm_list: # Must be sequential, in case terms are shared
pid = await tm.get_pid()
pids.append(pid)
return pids
def tearDown(self):
run = IOLoop.current().run_sync
run(self.named_tm.kill_all)
run(self.single_tm.kill_all)
run(self.unique_tm.kill_all)
super().tearDown()
def get_app(self):
self.named_tm = NamedTermManager(
shell_command=["bash"],
max_terminals=MAX_TERMS,
)
self.single_tm = SingleTermManager(shell_command=["bash"])
self.unique_tm = UniqueTermManager(
shell_command=["bash"],
max_terminals=MAX_TERMS,
)
named_tm = self.named_tm
class NewTerminalHandler(tornado.web.RequestHandler):
"""Create a new named terminal, return redirect"""
def get(self):
name, terminal = named_tm.new_named_terminal()
self.redirect("/named/" + name, permanent=False)
return tornado.web.Application(
[
(r"/new", NewTerminalHandler),
(r"/named/(\w+)", TermSocket, {"term_manager": self.named_tm}),
(r"/single", TermSocket, {"term_manager": self.single_tm}),
(r"/unique", TermSocket, {"term_manager": self.unique_tm}),
],
debug=True,
)
test_urls = ("/named/term1", "/unique") + (("/single",) if os.name != "nt" else ())
class CommonTests(TermTestCase):
@tornado.testing.gen_test
async def test_basic(self):
for url in self.test_urls:
tm = await self.get_term_client(url)
response = await tm.read_msg()
self.assertEqual(response, ["setup", {}])
# Check for initial shell prompt
response = await tm.read_msg()
self.assertEqual(response[0], "stdout")
self.assertGreater(len(response[1]), 0)
tm.close()
@tornado.testing.gen_test
async def test_basic_command(self):
for url in self.test_urls:
tm = await self.get_term_client(url)
await tm.read_all_msg()
await tm.write_stdin("whoami\n")
(stdout, other) = await tm.read_stdout()
if os.name == "nt":
assert "whoami" in stdout
else:
assert stdout.startswith("who")
assert other == []
tm.close()
class NamedTermTests(TermTestCase):
def test_new(self):
response = self.fetch("/new", follow_redirects=False)
self.assertEqual(response.code, 302)
url = response.headers["Location"]
# Check that the new terminal was created
name = url.split("/")[2]
self.assertIn(name, self.named_tm.terminals)
@tornado.testing.gen_test
async def test_namespace(self):
names = ["/named/1"] * 2 + ["/named/2"] * 2
tms = await self.get_term_clients(names)
pids = await self.get_pids(tms)
self.assertEqual(pids[0], pids[1])
self.assertEqual(pids[2], pids[3])
self.assertNotEqual(pids[0], pids[3])
terminal = self.named_tm.terminals["1"]
killed = await terminal.terminate(True)
assert killed
assert not terminal.ptyproc.isalive()
assert terminal.ptyproc.closed
@tornado.testing.gen_test
@pytest.mark.skipif("linux" not in platform, reason="It only works on Linux")
async def test_max_terminals(self):
urls = ["/named/%d" % i for i in range(MAX_TERMS + 1)]
tms = await self.get_term_clients(urls[:MAX_TERMS])
_ = await self.get_pids(tms)
# MAX_TERMS+1 should fail
tm = await self.get_term_client(urls[MAX_TERMS])
msg = await tm.read_msg()
self.assertEqual(msg, None) # Connection closed
class SingleTermTests(TermTestCase):
@tornado.testing.gen_test
async def test_single_process(self):
tms = await self.get_term_clients(["/single", "/single"])
pids = await self.get_pids(tms)
self.assertEqual(pids[0], pids[1])
assert self.single_tm.terminal is not None
killed = await self.single_tm.terminal.terminate(True)
assert killed
assert self.single_tm.terminal.ptyproc.closed
class UniqueTermTests(TermTestCase):
@tornado.testing.gen_test
async def test_unique_processes(self):
tms = await self.get_term_clients(["/unique", "/unique"])
pids = await self.get_pids(tms)
self.assertNotEqual(pids[0], pids[1])
@tornado.testing.gen_test
@pytest.mark.skipif("linux" not in platform, reason="It only works on Linux")
async def test_max_terminals(self):
tms = await self.get_term_clients(["/unique"] * MAX_TERMS)
pids = await self.get_pids(tms)
self.assertEqual(len(set(pids)), MAX_TERMS) # All PIDs unique
# MAX_TERMS+1 should fail
tm = await self.get_term_client("/unique")
msg = await tm.read_msg()
self.assertEqual(msg, None) # Connection closed
# Close one
tms[0].close()
msg = await tms[0].read_msg() # Closed
self.assertEqual(msg, None)
# Should be able to open back up to MAX_TERMS
tm = await self.get_term_client("/unique")
msg = await tm.read_msg()
self.assertEqual(msg[0], "setup")
if __name__ == "__main__":
unittest.main()

View File

@@ -0,0 +1,21 @@
// Copyright (c) Jupyter Development Team
// Copyright (c) 2014, Ramalingam Saravanan <sarava@sarava.net>
// Distributed under the terms of the Simplified BSD License.
window.addEventListener(
"load",
function () {
var containers = document.getElementsByClassName("terminado-container");
var container, rows, cols, protocol, ws_url;
for (var i = 0; i < containers.length; i++) {
container = containers[i];
rows = parseInt(container.dataset.rows);
cols = parseInt(container.dataset.cols);
protocol = window.location.protocol.indexOf("https") === 0 ? "wss" : "ws";
ws_url =
protocol + "://" + window.location.host + container.dataset.wsUrl;
make_terminal(container, { rows: rows, cols: cols }, ws_url);
}
},
false
);

View File

@@ -0,0 +1,30 @@
"""A Tornado UI module for a terminal backed by terminado.
See the Tornado docs for information on UI modules:
http://www.tornadoweb.org/en/stable/guide/templates.html#ui-modules
"""
# Copyright (c) Jupyter Development Team
# Copyright (c) 2014, Ramalingam Saravanan <sarava@sarava.net>
# Distributed under the terms of the Simplified BSD License.
import os.path
import tornado.web
class Terminal(tornado.web.UIModule):
def render(self, ws_url, cols=80, rows=25):
return (
'<div class="terminado-container" '
'data-ws-url="{ws_url}" '
'data-rows="{rows}" data-cols="{cols}"/>'
).format(ws_url=ws_url, rows=rows, cols=cols)
def javascript_files(self):
# TODO: Can we calculate these dynamically?
return ["/xstatic/termjs/term.js", "/static/terminado.js"]
def embedded_javascript(self):
file = os.path.join(os.path.dirname(__file__), "uimod_embed.js")
with open(file) as f:
return f.read()

View File

@@ -0,0 +1,127 @@
"""Tornado websocket handler to serve a terminal interface.
"""
# Copyright (c) Jupyter Development Team
# Copyright (c) 2014, Ramalingam Saravanan <sarava@sarava.net>
# Distributed under the terms of the Simplified BSD License.
import json
import logging
import os
import tornado.websocket
def _cast_unicode(s):
if isinstance(s, bytes):
return s.decode("utf-8")
return s
class TermSocket(tornado.websocket.WebSocketHandler):
"""Handler for a terminal websocket"""
def initialize(self, term_manager):
self.term_manager = term_manager
self.term_name = ""
self.size = (None, None)
self.terminal = None
self._logger = logging.getLogger(__name__)
self._user_command = ""
# Enable if the environment variable LOG_TERMINAL_OUTPUT is "true"
self._enable_output_logging = str.lower(os.getenv("LOG_TERMINAL_OUTPUT", "false")) == "true"
def origin_check(self, origin=None):
"""Deprecated: backward-compat for terminado <= 0.5."""
return self.check_origin(origin or self.request.headers.get("Origin"))
def open(self, url_component=None):
"""Websocket connection opened.
Call our terminal manager to get a terminal, and connect to it as a
client.
"""
# Jupyter has a mixin to ping websockets and keep connections through
# proxies alive. Call super() to allow that to set up:
super().open(url_component)
self._logger.info("TermSocket.open: %s", url_component)
url_component = _cast_unicode(url_component)
self.term_name = url_component or "tty"
self.terminal = self.term_manager.get_terminal(url_component)
self.terminal.clients.append(self)
self.send_json_message(["setup", {}])
self._logger.info("TermSocket.open: Opened %s", self.term_name)
# Now drain the preopen buffer, if reconnect.
buffered = ""
preopen_buffer = self.terminal.read_buffer.copy()
while True:
if not preopen_buffer:
break
s = preopen_buffer.popleft()
buffered += s
if buffered:
self.on_pty_read(buffered)
def on_pty_read(self, text):
"""Data read from pty; send to frontend"""
self.send_json_message(["stdout", text])
def send_json_message(self, content):
json_msg = json.dumps(content)
self.write_message(json_msg)
if self._enable_output_logging:
if content[0] == "stdout" and isinstance(content[1], str):
self.log_terminal_output(f"STDOUT: {content[1]}")
def on_message(self, message):
"""Handle incoming websocket message
We send JSON arrays, where the first element is a string indicating
what kind of message this is. Data associated with the message follows.
"""
# logging.info("TermSocket.on_message: %s - (%s) %s", self.term_name, type(message), len(message) if isinstance(message, bytes) else message[:250])
command = json.loads(message)
msg_type = command[0]
assert self.terminal is not None
if msg_type == "stdin":
self.terminal.ptyproc.write(command[1])
if self._enable_output_logging:
if command[1] == "\r":
self.log_terminal_output(f"STDIN: {self._user_command}")
self._user_command = ""
else:
self._user_command += command[1]
elif msg_type == "set_size":
self.size = command[1:3]
self.terminal.resize_to_smallest()
def on_close(self):
"""Handle websocket closing.
Disconnect from our terminal, and tell the terminal manager we're
disconnecting.
"""
self._logger.info("Websocket closed")
if self.terminal:
self.terminal.clients.remove(self)
self.terminal.resize_to_smallest()
self.term_manager.client_disconnected(self)
def on_pty_died(self):
"""Terminal closed: tell the frontend, and close the socket."""
self.send_json_message(["disconnect", 1])
self.close()
self.terminal = None
def log_terminal_output(self, log: str = "") -> None:
"""
Logs the terminal input/output
:param log: log line to write
:return:
"""
self._logger.debug(log)