pax_global_header00006660000000000000000000000064134472063600014517gustar00rootroot0000000000000052 comment=b0b32f3efdde4252466f4e57b98773d9e86951ec terminado-0.8.2/000077500000000000000000000000001344720636000135105ustar00rootroot00000000000000terminado-0.8.2/.gitignore000077500000000000000000000002201344720636000154750ustar00rootroot00000000000000.DS_Store *~ *.pyc *.prev *.sav *.old *.pem .cache/ README.html build/* dist/* MANIFEST terminado.egg-info/* BAK IGNORE ORIG SUBMIT doc/_build/ terminado-0.8.2/.travis.yml000066400000000000000000000003531344720636000156220ustar00rootroot00000000000000language: python python: - "3.6" - "3.5" - "3.4" - "2.7" # Install dependencies install: - pip install tornado ptyprocess # command to run tests script: py.test # Enable new Travis stack, should speed up builds sudo: false terminado-0.8.2/LICENSE000066400000000000000000000027631344720636000145250ustar00rootroot00000000000000# terminado: A python websocket server backend for xterm.js # # BSD License # # Copyright (c) 2014-, Jupyter development team # Copyright (c) 2014, Ramalingam Saravanan # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. terminado-0.8.2/README.rst000066400000000000000000000053641344720636000152070ustar00rootroot00000000000000This is a `Tornado `_ websocket backend for the `Xterm.js `_ Javascript terminal emulator library. It evolved out of `pyxterm `_, which was part of `GraphTerm `_ (as lineterm.py), v0.57.0 (2014-07-18), and ultimately derived from the public-domain `Ajaxterm `_ code, v0.11 (2008-11-13) (also on Github as part of `QWeb `_). Modules: * ``terminado.management``: controls launching virtual terminals, connecting them to Tornado's event loop, and closing them down. * ``terminado.websocket``: Provides a websocket handler for communicating with a terminal. * ``terminado.uimodule``: Provides a ``Terminal`` Tornado `UI Module `_. JS: * ``terminado/_static/terminado.js``: A lightweight wrapper to set up a term.js terminal with a websocket. Usage example: .. code:: python import os.path import tornado.web import tornado.ioloop # This demo requires tornado_xstatic and XStatic-term.js import tornado_xstatic import terminado STATIC_DIR = os.path.join(os.path.dirname(terminado.__file__), "_static") class TerminalPageHandler(tornado.web.RequestHandler): def get(self): return self.render("termpage.html", static=self.static_url, xstatic=self.application.settings['xstatic_url'], ws_url_path="/websocket") if __name__ == '__main__': term_manager = terminado.SingleTermManager(shell_command=['bash']) handlers = [ (r"/websocket", terminado.TermSocket, {'term_manager': term_manager}), (r"/", TerminalPageHandler), (r"/xstatic/(.*)", tornado_xstatic.XStaticFileHandler, {'allowed_modules': ['termjs']}) ] app = tornado.web.Application(handlers, static_path=STATIC_DIR, xstatic_url = tornado_xstatic.url_maker('/xstatic/')) # Serve at http://localhost:8765/ N.B. Leaving out 'localhost' here will # work, but it will listen on the public network interface as well. # Given what terminado does, that would be rather a security hole. app.listen(8765, 'localhost') try: tornado.ioloop.IOLoop.instance().start() finally: term_manager.shutdown() See the `demos directory `_ for more examples. This is a simplified version of the ``single.py`` demo. Run the unit tests with: $ nosetests terminado-0.8.2/appveyor.yml000066400000000000000000000023611344720636000161020ustar00rootroot00000000000000# Do not build feature branch with open Pull Requests skip_branch_with_pr: true # environment variables environment: matrix: - PYTHON: "C:\\Python27-x64" - PYTHON: "C:\\Python35-x64" - PYTHON: "C:\\Python36-x64" build: off # scripts that run after cloning repository install: # If there is a newer build queued for the same PR, cancel this one. # The AppVeyor 'rollout builds' option is supposed to serve the same # purpose but it is problematic because it tends to cancel builds pushed # directly to master instead of just PR builds (or the converse). # credits: JuliaLang developers. - ps: if ($env:APPVEYOR_PULL_REQUEST_NUMBER -and $env:APPVEYOR_BUILD_NUMBER -ne ((Invoke-RestMethod ` https://ci.appveyor.com/api/projects/$env:APPVEYOR_ACCOUNT_NAME/$env:APPVEYOR_PROJECT_SLUG/history?recordsNumber=50).builds | ` Where-Object pullRequestId -eq $env:APPVEYOR_PULL_REQUEST_NUMBER)[0].buildNumber) { ` throw "There are newer queued builds for this pull request, failing early." } # Install dependencies # update path to use installed pip and py.test - set PATH=%PYTHON%\\scripts;%PATH% - 'pip install tornado pywinpty pytest' test_script: - 'py.test terminado/tests/basic_test.py::CommonTests::test_basic' terminado-0.8.2/demos/000077500000000000000000000000001344720636000146175ustar00rootroot00000000000000terminado-0.8.2/demos/README.md000066400000000000000000000006171344720636000161020ustar00rootroot00000000000000Demos ===== requirements ------------ Install requirements to run these demos: ```sh $ pip install -r requirements.txt ``` named.py: --------- One shared terminal per URL endpoint Plus a /new URL which will create a new terminal and redirect to it. single.py: ---------- A single common terminal for all websockets. unique.py: ---------- A separate terminal for every websocket opened. terminado-0.8.2/demos/common_demo_stuff.py000066400000000000000000000010041344720636000206670ustar00rootroot00000000000000import os.path import webbrowser import tornado.ioloop import terminado STATIC_DIR = os.path.join(os.path.dirname(terminado.__file__), "_static") TEMPLATE_DIR = os.path.join(os.path.dirname(__file__), "templates") def run_and_show_browser(url, term_manager): loop = tornado.ioloop.IOLoop.instance() loop.add_callback(webbrowser.open, url) try: loop.start() except KeyboardInterrupt: print(" Shutting down on SIGINT") finally: term_manager.shutdown() loop.close()terminado-0.8.2/demos/named.py000077500000000000000000000036021344720636000162610ustar00rootroot00000000000000"""One shared terminal per URL endpoint Plus a /new URL which will create a new terminal and redirect to it. """ from __future__ import print_function, absolute_import import logging import os.path import sys import tornado.web # This demo requires tornado_xstatic and XStatic-term.js import tornado_xstatic from terminado import TermSocket, NamedTermManager from common_demo_stuff import run_and_show_browser, STATIC_DIR, TEMPLATE_DIR AUTH_TYPES = ("none", "login") class TerminalPageHandler(tornado.web.RequestHandler): """Render the /ttyX pages""" def get(self, term_name): return self.render("termpage.html", static=self.static_url, xstatic=self.application.settings['xstatic_url'], ws_url_path="/_websocket/"+term_name) class NewTerminalHandler(tornado.web.RequestHandler): """Redirect to an unused terminal name""" def get(self): name, terminal = self.application.settings['term_manager'].new_named_terminal() self.redirect("/" + name, permanent=False) def main(): term_manager = NamedTermManager(shell_command=['bash'], max_terminals=100) handlers = [ (r"/_websocket/(\w+)", TermSocket, {'term_manager': term_manager}), (r"/new/?", NewTerminalHandler), (r"/(\w+)/?", TerminalPageHandler), (r"/xstatic/(.*)", tornado_xstatic.XStaticFileHandler) ] application = tornado.web.Application(handlers, static_path=STATIC_DIR, template_path=TEMPLATE_DIR, xstatic_url=tornado_xstatic.url_maker('/xstatic/'), term_manager=term_manager) application.listen(8700, 'localhost') run_and_show_browser("http://localhost:8700/new", term_manager) if __name__ == "__main__": main()terminado-0.8.2/demos/requirements.txt000066400000000000000000000000721344720636000201020ustar00rootroot00000000000000terminado tornado tornado-xstatic XStatic XStatic-term.js terminado-0.8.2/demos/single.py000077500000000000000000000023631344720636000164610ustar00rootroot00000000000000"""A single common terminal for all websockets. """ import tornado.web # This demo requires tornado_xstatic and XStatic-term.js import tornado_xstatic from terminado import TermSocket, SingleTermManager from common_demo_stuff import run_and_show_browser, STATIC_DIR, TEMPLATE_DIR class TerminalPageHandler(tornado.web.RequestHandler): def get(self): return self.render("termpage.html", static=self.static_url, xstatic=self.application.settings['xstatic_url'], ws_url_path="/websocket") def main(argv): term_manager = SingleTermManager(shell_command=['bash']) handlers = [ (r"/websocket", TermSocket, {'term_manager': term_manager}), (r"/", TerminalPageHandler), (r"/xstatic/(.*)", tornado_xstatic.XStaticFileHandler, {'allowed_modules': ['termjs']}) ] app = tornado.web.Application(handlers, static_path=STATIC_DIR, template_path=TEMPLATE_DIR, xstatic_url = tornado_xstatic.url_maker('/xstatic/')) app.listen(8765, 'localhost') run_and_show_browser("http://localhost:8765/", term_manager) if __name__ == '__main__': main([])terminado-0.8.2/demos/templates/000077500000000000000000000000001344720636000166155ustar00rootroot00000000000000terminado-0.8.2/demos/templates/termpage.html000077500000000000000000000043001344720636000213070ustar00rootroot00000000000000 pyxterm terminado-0.8.2/demos/templates/uimod.html000077500000000000000000000012171344720636000206240ustar00rootroot00000000000000 Terminado UIModule demo

Terminado UIModule terminal

{% module Terminal("/websocket") %}
terminado-0.8.2/demos/uimod.py000066400000000000000000000025231344720636000163100ustar00rootroot00000000000000"""A single common terminal for all websockets. """ import tornado.web # This demo requires tornado_xstatic and XStatic-term.js import tornado_xstatic from terminado import TermSocket, SingleTermManager from terminado import uimodule from common_demo_stuff import run_and_show_browser, STATIC_DIR, TEMPLATE_DIR class TerminalPageHandler(tornado.web.RequestHandler): def get(self): return self.render("uimod.html", static=self.static_url, xstatic=self.application.settings['xstatic_url'], ws_url_path="/websocket") def main(argv): term_manager = SingleTermManager(shell_command=['bash']) handlers = [ (r"/websocket", TermSocket, {'term_manager': term_manager}), (r"/", TerminalPageHandler), (r"/xstatic/(.*)", tornado_xstatic.XStaticFileHandler, {'allowed_modules': ['termjs']}) ] app = tornado.web.Application(handlers, static_path=STATIC_DIR, template_path=TEMPLATE_DIR, ui_modules = {'Terminal': uimodule.Terminal}, xstatic_url = tornado_xstatic.url_maker('/xstatic/')) app.listen(8765, 'localhost') run_and_show_browser("http://localhost:8765/", term_manager) if __name__ == '__main__': main([])terminado-0.8.2/demos/unique.py000077500000000000000000000023661344720636000165110ustar00rootroot00000000000000"""A separate terminal for every websocket opened. """ import tornado.web # This demo requires tornado_xstatic and XStatic-term.js import tornado_xstatic from terminado import TermSocket, UniqueTermManager from common_demo_stuff import run_and_show_browser, STATIC_DIR, TEMPLATE_DIR class TerminalPageHandler(tornado.web.RequestHandler): def get(self): return self.render("termpage.html", static=self.static_url, xstatic=self.application.settings['xstatic_url'], ws_url_path="/websocket") def main(argv): term_manager = UniqueTermManager(shell_command=['bash']) handlers = [ (r"/websocket", TermSocket, {'term_manager': term_manager}), (r"/", TerminalPageHandler), (r"/xstatic/(.*)", tornado_xstatic.XStaticFileHandler, {'allowed_modules': ['termjs']}) ] app = tornado.web.Application(handlers, static_path=STATIC_DIR, template_path=TEMPLATE_DIR, xstatic_url = tornado_xstatic.url_maker('/xstatic/')) app.listen(8765, 'localhost') run_and_show_browser("http://localhost:8765/", term_manager) if __name__ == '__main__': main([])terminado-0.8.2/doc/000077500000000000000000000000001344720636000142555ustar00rootroot00000000000000terminado-0.8.2/doc/Makefile000066400000000000000000000151661344720636000157260ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Terminado.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Terminado.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/Terminado" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Terminado" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." terminado-0.8.2/doc/conf.py000066400000000000000000000203051344720636000155540ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # Terminado documentation build configuration file, created by # sphinx-quickstart on Mon Oct 6 12:11:56 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Terminado' copyright = u'2014, Thomas Kluyver' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.7' # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Terminadodoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'Terminado.tex', u'Terminado Documentation', u'Thomas Kluyver', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'terminado', u'Terminado Documentation', [u'Thomas Kluyver'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'Terminado', u'Terminado Documentation', u'Thomas Kluyver', 'Terminado', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'tornado': ('http://www.tornadoweb.org/en/stable/', None)} terminado-0.8.2/doc/index.rst000066400000000000000000000005401344720636000161150ustar00rootroot00000000000000Terminado ========= Contents: .. toctree:: :maxdepth: 2 websocket uimodule releasenotes .. seealso:: `Connecting Xterm.js to Terminado `_ From the Xterm.js docs .. include:: ../README.rst Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` terminado-0.8.2/doc/releasenotes.rst000066400000000000000000000011121344720636000174730ustar00rootroot00000000000000Release notes ============= 0.7 --- - :meth:`terminado.TermSocket.open` now calls the ``open()`` method on the parent class using ``super()``. This allows a mixin class; for instance, to periodically send ping messages to keep a connection open. - When a websocket client disconnects from a terminal managed by :class:`~.UniqueTermManager`, the ``SIGHUP`` signal is sent to the process group, not just the main process. - Fixed :meth:`terminado.NamedTermManager.kill` to use the signal number passed to it. - Switched to Flit packaging. - README and requirements for demos. terminado-0.8.2/doc/requirements.txt000066400000000000000000000000231344720636000175340ustar00rootroot00000000000000ptyprocess tornado terminado-0.8.2/doc/uimodule.rst000066400000000000000000000020111344720636000166240ustar00rootroot00000000000000Using the Tornado UI Module =========================== Terminado provides a Tornado :ref:`UI Module `. Once you have the websocket handler set up (see :doc:`websocket`), add the module to your application:: from terminado import uimodule # ... app = tornado.web.Application(... ui_modules = {'Terminal': uimodule.Terminal}, ) Now, when you want a terminal in your application, you can put this in the template:: {% module Terminal("/websocket", rows=30, cols=90) %} This will create a div, and include the necessary Javascript code to set up a terminal in that div and connect it to a websocket on ``ws:///websocket``. If not specified, rows and cols default to 25 and 80, respectively. For now, this assumes that term.js is available at ``/xstatic/termjs/term.js``, and terminado.js at ``/static/terminado.js``. To serve them from different locations, subclass :class:`terminado.uimodule.Terminal`, overriding :meth:`~terminado.uimodule.Terminal.javascript_files`. terminado-0.8.2/doc/websocket.rst000066400000000000000000000044441344720636000170030ustar00rootroot00000000000000Using the TermSocket handler ============================ :class:`terminado.TermSocket` is the main API in Terminado. It is a subclass of :class:`tornado.web.WebSocketHandler`, used to communicate between a pseudoterminal and term.js. You add it to your web application as a handler like any other:: app = tornado.web.Application([ # ... other handlers ... (r"/websocket", terminado.TermSocket, {'term_manager': terminado.SingleTermManager(shell_command=['bash'])}), ], **kwargs) Now, a page in your application can connect to ``ws:///websocket``. Using :file:`terminado/_static/terminado.js`, you can do this using: .. code-block:: javascript make_terminal(target_html_element, {rows:25, cols:80}, "ws:///websocket"); .. warning:: :class:`~terminado.TermSocket` does not authenticate the connection at all, and using it with a program like ``bash`` means that anyone who can connect to it can run commands on your server. It is up to you to integrate the handler with whatever authentication system your application uses. For instance, in IPython, we subclass it like this:: class TermSocket(terminado.TermSocket, IPythonHandler): def get(self, *args, **kwargs): if not self.get_current_user(): raise web.HTTPError(403) return super(TermSocket, self).get(*args, **kwargs) Terminal managers ----------------- The terminal manager control the behaviour when you connect and disconnect websockets. Terminado offers three options: .. module:: terminado .. autoclass:: SingleTermManager .. autoclass:: UniqueTermManager .. autoclass:: NamedTermManager You can also define your own behaviours, by subclassing any of these, or the base class. The important methods are described here: .. autoclass:: TermManagerBase .. automethod:: get_terminal .. automethod:: new_terminal .. automethod:: start_reading .. automethod:: client_disconnected This may still be subject to change as we work out the best API. In the example above, the terminal manager was only attached to the websocket handler. If you want to access it from other handlers, for instance to list running terminals, attach the instance to your application, for instance in the settings dictionary. terminado-0.8.2/pyproject.toml000066400000000000000000000012531344720636000164250ustar00rootroot00000000000000[build-system] requires = ["flit"] build-backend = "flit.buildapi" [tool.flit.metadata] module = "terminado" author = "Jupyter Development Team" author-email = "jupyter@googlegroups.com" home-page = "https://github.com/jupyter/terminado" description-file = "README.rst" requires = [ "ptyprocess;os_name!='nt'", "pywinpty (>=0.5);os_name=='nt'", "tornado (>=4)", ] requires-python=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" classifiers=[ "Environment :: Web Environment", "License :: OSI Approved :: BSD License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Terminals :: Terminal Emulators/X Terminals", ] terminado-0.8.2/terminado/000077500000000000000000000000001344720636000154725ustar00rootroot00000000000000terminado-0.8.2/terminado/__init__.py000066400000000000000000000010401344720636000175760ustar00rootroot00000000000000"""Terminals served to xterm.js using Tornado websockets""" # Copyright (c) Jupyter Development Team # Copyright (c) 2014, Ramalingam Saravanan # Distributed under the terms of the Simplified BSD License. from .websocket import TermSocket from .management import (TermManagerBase, SingleTermManager, UniqueTermManager, NamedTermManager) import logging # Prevent a warning about no attached handlers in Python 2 logging.getLogger(__name__).addHandler(logging.NullHandler()) __version__ = '0.8.2' terminado-0.8.2/terminado/_static/000077500000000000000000000000001344720636000171205ustar00rootroot00000000000000terminado-0.8.2/terminado/_static/terminado.js000066400000000000000000000023021344720636000214350ustar00rootroot00000000000000// Copyright (c) Jupyter Development Team // Copyright (c) 2014, Ramalingam Saravanan // 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}; } terminado-0.8.2/terminado/management.py000066400000000000000000000272621344720636000201710ustar00rootroot00000000000000"""Terminal management for exposing terminals to a web interface using Tornado. """ # Copyright (c) Jupyter Development Team # Copyright (c) 2014, Ramalingam Saravanan # Distributed under the terms of the Simplified BSD License. from __future__ import absolute_import, print_function import sys if sys.version_info[0] < 3: byte_code = ord else: byte_code = lambda x: x unicode = str from collections import deque import itertools import logging import os import signal try: from ptyprocess import PtyProcessUnicode except ImportError: from winpty import PtyProcess as PtyProcessUnicode from tornado import gen from tornado.ioloop import IOLoop ENV_PREFIX = "PYXTERM_" # Environment variable prefix DEFAULT_TERM_TYPE = "xterm" class PtyWithClients(object): def __init__(self, ptyproc): self.ptyproc = ptyproc self.clients = [] # Store the last few things read, so when a new client connects, # it can show e.g. the most recent prompt, rather than absolutely # nothing. self.read_buffer = deque([], maxlen=10) 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) @gen.coroutine 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] loop = IOLoop.current() sleep = lambda : gen.sleep(self.ptyproc.delayafterterminate) if not self.ptyproc.isalive(): raise gen.Return(True) try: for sig in signals: self.kill(sig) yield sleep() if not self.ptyproc.isalive(): raise gen.Return(True) if force: self.kill(signal.SIGKILL) yield sleep() if not self.ptyproc.isalive(): raise gen.Return(True) else: raise gen.Return(False) raise gen.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. yield sleep() if not self.ptyproc.isalive(): raise gen.Return(True) else: raise gen.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 class TermManagerBase(object): """Base class for a terminal manager.""" def __init__(self, shell_command, server_url="", term_settings={}, extra_env=None, ioloop=None): self.shell_command = shell_command self.server_url = server_url self.term_settings = term_settings self.extra_env = extra_env self.log = logging.getLogger(__name__) self.ptys_by_fd = {} if ioloop is not None: self.ioloop = ioloop else: import tornado.ioloop self.ioloop = tornado.ioloop.IOLoop.instance() 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() 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) 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) pty = PtyProcessUnicode.spawn(argv, env=env, cwd=options.get('cwd', None)) return PtyWithClients(pty) 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 self.ioloop.add_handler(fd, self.pty_read, self.ioloop.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] self.ioloop.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.""" ptywclients = self.ptys_by_fd[fd] try: 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 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 @gen.coroutine def shutdown(self): yield self.kill_all() @gen.coroutine def kill_all(self): futures = [] for term in self.ptys_by_fd.values(): futures.append(term.terminate(force=True)) # wait for futures to finish for f in futures: yield f class SingleTermManager(TermManagerBase): """All connections to the websocket share a common terminal.""" def __init__(self, **kwargs): super(SingleTermManager, self).__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 @gen.coroutine def kill_all(self): yield super(SingleTermManager, self).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(UniqueTermManager, self).__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(NamedTermManager, self).__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): name = self._next_available_name() term = self.new_terminal() 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 @gen.coroutine def terminate(self, name, force=False): term = self.terminals[name] yield term.terminate(force=force) def on_eof(self, ptywclients): super(NamedTermManager, self).on_eof(ptywclients) name = ptywclients.term_name self.log.info("Terminal %s closed", name) self.terminals.pop(name, None) @gen.coroutine def kill_all(self): yield super(NamedTermManager, self).kill_all() self.terminals = {} terminado-0.8.2/terminado/tests/000077500000000000000000000000001344720636000166345ustar00rootroot00000000000000terminado-0.8.2/terminado/tests/__init__.py000066400000000000000000000000001344720636000207330ustar00rootroot00000000000000terminado-0.8.2/terminado/tests/basic_test.py000066400000000000000000000215261344720636000213340ustar00rootroot00000000000000# basic_tests.py -- Basic unit tests for Terminado # Copyright (c) Jupyter Development Team # Copyright (c) 2014, Ramalingam Saravanan # Distributed under the terms of the Simplified BSD License. from __future__ import absolute_import, print_function import unittest from terminado import * import tornado import tornado.httpserver from tornado.httpclient import HTTPError from tornado.ioloop import IOLoop import tornado.testing import datetime import logging import json import os import re # # 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(object): """Test connection to a terminal manager""" def __init__(self, websocket): self.ws = websocket self.pending_read = None @tornado.gen.coroutine 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 = yield self.pending_read self.pending_read = None if response: response = json.loads(response) raise tornado.gen.Return(response) @tornado.gen.coroutine def read_all_msg(self, timeout=DONE_TIMEOUT): """Read messages until read times out""" msglist = [] delta = datetime.timedelta(seconds=timeout) while True: try: mf = self.read_msg() msg = yield tornado.gen.with_timeout(delta, mf) except tornado.gen.TimeoutError: raise tornado.gen.Return(msglist) msglist.append(msg) def write_msg(self, msg): self.ws.write_message(json.dumps(msg)) @tornado.gen.coroutine def read_stdout(self, timeout=DONE_TIMEOUT): """Read standard output until timeout read reached, return stdout and any non-stdout msgs received.""" msglist = yield 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'] raise tornado.gen.Return((stdout, othermsg)) def write_stdin(self, data): """Write to terminal stdin""" self.write_msg(['stdin', data]) @tornado.gen.coroutine def get_pid(self): """Get process ID of terminal shell process""" yield self.read_stdout() # Clear out any pending self.write_stdin("echo $$\r") (stdout, extra) = yield self.read_stdout() if os.name == 'nt': match = re.search(r'echo \$\$\x1b\[0K\r\n(\d+)', stdout) pid = int(match.groups()[0]) else: pid = int(stdout.split('\n')[1]) raise tornado.gen.Return(pid) def close(self): self.ws.close() class TermTestCase(tornado.testing.AsyncHTTPTestCase): # Factory for TestTermClient, because it has to be a Tornado co-routine. # See: https://github.com/tornadoweb/tornado/issues/1161 @tornado.gen.coroutine 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 = yield tornado.websocket.websocket_connect(request) raise tornado.gen.Return(TestTermClient(ws)) @tornado.gen.coroutine def get_term_clients(self, paths): tms = yield [self.get_term_client(path) for path in paths] raise tornado.gen.Return(tms) @tornado.gen.coroutine def get_pids(self, tm_list): pids = [] for tm in tm_list: # Must be sequential, in case terms are shared pid = yield tm.get_pid() pids.append(pid) raise tornado.gen.Return(pids) def get_app(self): self.named_tm = NamedTermManager(shell_command=['bash'], max_terminals=MAX_TERMS, ioloop=self.io_loop) self.single_tm = SingleTermManager(shell_command=['bash'], ioloop=self.io_loop) self.unique_tm = UniqueTermManager(shell_command=['bash'], max_terminals=MAX_TERMS, ioloop=self.io_loop) 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') class CommonTests(TermTestCase): @tornado.testing.gen_test def test_basic(self): for url in self.test_urls: tm = yield self.get_term_client(url) response = yield tm.read_msg() self.assertEqual(response, ['setup', {}]) # Check for initial shell prompt response = yield tm.read_msg() self.assertEqual(response[0], 'stdout') self.assertGreater(len(response[1]), 0) tm.close() @tornado.testing.gen_test def test_basic_command(self): for url in self.test_urls: tm = yield self.get_term_client(url) yield tm.read_all_msg() tm.write_stdin("whoami\n") (stdout, other) = yield 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 def test_namespace(self): names = ["/named/1"]*2 + ["/named/2"]*2 tms = yield self.get_term_clients(names) pids = yield self.get_pids(tms) self.assertEqual(pids[0], pids[1]) self.assertEqual(pids[2], pids[3]) self.assertNotEqual(pids[0], pids[3]) @tornado.testing.gen_test def test_max_terminals(self): urls = ["/named/%d" % i for i in range(MAX_TERMS+1)] tms = yield self.get_term_clients(urls[:MAX_TERMS]) pids = yield self.get_pids(tms) # MAX_TERMS+1 should fail tm = yield self.get_term_client(urls[MAX_TERMS]) msg = yield tm.read_msg() self.assertEqual(msg, None) # Connection closed class SingleTermTests(TermTestCase): @tornado.testing.gen_test def test_single_process(self): tms = yield self.get_term_clients(["/single", "/single"]) pids = yield self.get_pids(tms) self.assertEqual(pids[0], pids[1]) class UniqueTermTests(TermTestCase): @tornado.testing.gen_test def test_unique_processes(self): tms = yield self.get_term_clients(["/unique", "/unique"]) pids = yield self.get_pids(tms) self.assertNotEqual(pids[0], pids[1]) @tornado.testing.gen_test def test_max_terminals(self): tms = yield self.get_term_clients(['/unique'] * MAX_TERMS) pids = yield self.get_pids(tms) self.assertEqual(len(set(pids)), MAX_TERMS) # All PIDs unique # MAX_TERMS+1 should fail tm = yield self.get_term_client("/unique") msg = yield tm.read_msg() self.assertEqual(msg, None) # Connection closed # Close one tms[0].close() msg = yield tms[0].read_msg() # Closed self.assertEquals(msg, None) # Should be able to open back up to MAX_TERMS tm = yield self.get_term_client("/unique") msg = yield tm.read_msg() self.assertEquals(msg[0], 'setup') if __name__ == '__main__': unittest.main() terminado-0.8.2/terminado/uimod_embed.js000066400000000000000000000014051344720636000203010ustar00rootroot00000000000000// Copyright (c) Jupyter Development Team // Copyright (c) 2014, Ramalingam Saravanan // 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); terminado-0.8.2/terminado/uimodule.py000066400000000000000000000017641344720636000176770ustar00rootroot00000000000000"""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 # 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 ('
').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() terminado-0.8.2/terminado/websocket.py000066400000000000000000000066551344720636000200460ustar00rootroot00000000000000"""Tornado websocket handler to serve a terminal interface. """ # Copyright (c) Jupyter Development Team # Copyright (c) 2014, Ramalingam Saravanan # Distributed under the terms of the Simplified BSD License. from __future__ import absolute_import, print_function # Python3-friendly imports try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse import json import logging import tornado.web 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__) 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(TermSocket, self).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) for s in self.terminal.read_buffer: self.on_pty_read(s) self.terminal.clients.append(self) self.send_json_message(["setup", {}]) self._logger.info("TermSocket.open: Opened %s", self.term_name) 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) 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] if msg_type == "stdin": self.terminal.ptyproc.write(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